qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
98,224 | <p>After downloading files from a remote UNIX FTP server, you want to verify that you have downloaded all the files correctly. Minimal you will get information similar to "dir /s" command in Windows command prompt. The FTP client runs on Windows.</p>
| [
{
"answer_id": 98234,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 6,
"selected": true,
"text": "<p>Sadly this was written for Unix/Linux users :/</p>\n\n<p>Personally, I would install CYGWIN just to get Linux binaries of LFTP/RSYNC to work on windows, as there appears not to be anything that competes with it. </p>\n\n<p>As @zadok.myopenid.com \nmentioned rsync, this appears to be a windows build for it using CYGWIN ( if you manage to be able to get ssh access to the box eventually ) </p>\n\n<p><a href=\"http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp\" rel=\"noreferrer\">http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp</a> </p>\n\n<p>Rsync is handy in that it will compare everything with check sums, and optimally transfer partial change blocks.</p>\n\n<hr>\n\n<p>If you get CYGWIN/Linux:</p>\n\n<p><a href=\"http://lftp.yar.ru/\" rel=\"noreferrer\">http://lftp.yar.ru/</a> is my favorite exploration tool for this. </p>\n\n<p>It can do almost everything bash can do, albeit remotely. </p>\n\n<p>Example: </p>\n\n<pre>\n$ lftp mirror.3fl.net.au\nlftp mirror.3fl.net.au:~> ls \ndrwxr-xr-x 14 root root 4096 Nov 27 2007 games\ndrwx------ 2 root root 16384 Apr 13 2006 lost+found\ndrwxr-xr-x 15 mirror mirror 4096 Jul 15 05:20 pub\nlftp mirror.3fl.net.au:/> cd games/misc\nlftp mirror.3fl.net.au:/games/misc>find\n./\n./dreamchess/\n./dreamchess/full_game/ \n./dreamchess/full_game/dreamchess-0.2.0-win32.exe \n./frets_on_fire/\n./frets_on_fire/full_game/ \n./frets_on_fire/full_game/FretsOnFire-1.2.451-macosx.zip \n./frets_on_fire/full_game/FretsOnFire-1.2.512-win32.zip\n./frets_on_fire/full_game/FretsOnFire_ghc_mod.zip\n./gametap_setup.exe\n......\nlftp mirror.3fl.net.au:/games/misc> du gametap_setup.exe \n32442 gametap_setup.exe\nlftp mirror.3fl.net.au:/games/misc> du -sh gametap_setup.exe \n32M gametap_setup.exe\nlftp mirror.3fl.net.au:/games/misc> \n</pre>\n"
},
{
"answer_id": 98246,
"author": "Jonah Braun",
"author_id": 15948,
"author_profile": "https://Stackoverflow.com/users/15948",
"pm_score": 2,
"selected": false,
"text": "<p>If you have ssh access, use rsync instead. It is a far better data transfer app.</p>\n\n<p>Grab fuse for your OS and load ftpfs. This will let you mount the remote ftp directory locally and you can use dir /s or any other application you want on it.</p>\n"
},
{
"answer_id": 4414456,
"author": "jamesmar",
"author_id": 538522,
"author_profile": "https://Stackoverflow.com/users/538522",
"pm_score": 3,
"selected": false,
"text": "<p>Do this :</p>\n\n<pre><code>ls -lR\n</code></pre>\n\n<p>..................</p>\n"
},
{
"answer_id": 15923366,
"author": "Raja",
"author_id": 1833666,
"author_profile": "https://Stackoverflow.com/users/1833666",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <strong>ftp.listFiles(\"directory\")</strong> from apache-commons-net and can write your own BFS or DFS to fetch all the files recursively.</p>\n"
},
{
"answer_id": 30852654,
"author": "SmitaK",
"author_id": 5012619,
"author_profile": "https://Stackoverflow.com/users/5012619",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming you are using simple ftp via command line, \nUse dir command with -Rl option to search recursively and copy it to a file and then search the file using grep, find or whatever way is supported on your OS.</p>\n\n<p>ftp> dir -Rl education.txt\noutput to local-file: education.txt? y\n227 Entering Passive Mode (9,62,119,15,138,239)\n150 Opening ASCII mode data connection for file list\n226 Transfer complete</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13584/"
]
| After downloading files from a remote UNIX FTP server, you want to verify that you have downloaded all the files correctly. Minimal you will get information similar to "dir /s" command in Windows command prompt. The FTP client runs on Windows. | Sadly this was written for Unix/Linux users :/
Personally, I would install CYGWIN just to get Linux binaries of LFTP/RSYNC to work on windows, as there appears not to be anything that competes with it.
As @zadok.myopenid.com
mentioned rsync, this appears to be a windows build for it using CYGWIN ( if you manage to be able to get ssh access to the box eventually )
<http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp>
Rsync is handy in that it will compare everything with check sums, and optimally transfer partial change blocks.
---
If you get CYGWIN/Linux:
<http://lftp.yar.ru/> is my favorite exploration tool for this.
It can do almost everything bash can do, albeit remotely.
Example:
```
$ lftp mirror.3fl.net.au
lftp mirror.3fl.net.au:~> ls
drwxr-xr-x 14 root root 4096 Nov 27 2007 games
drwx------ 2 root root 16384 Apr 13 2006 lost+found
drwxr-xr-x 15 mirror mirror 4096 Jul 15 05:20 pub
lftp mirror.3fl.net.au:/> cd games/misc
lftp mirror.3fl.net.au:/games/misc>find
./
./dreamchess/
./dreamchess/full_game/
./dreamchess/full_game/dreamchess-0.2.0-win32.exe
./frets_on_fire/
./frets_on_fire/full_game/
./frets_on_fire/full_game/FretsOnFire-1.2.451-macosx.zip
./frets_on_fire/full_game/FretsOnFire-1.2.512-win32.zip
./frets_on_fire/full_game/FretsOnFire_ghc_mod.zip
./gametap_setup.exe
......
lftp mirror.3fl.net.au:/games/misc> du gametap_setup.exe
32442 gametap_setup.exe
lftp mirror.3fl.net.au:/games/misc> du -sh gametap_setup.exe
32M gametap_setup.exe
lftp mirror.3fl.net.au:/games/misc>
``` |
98,242 | <blockquote>
<p><strong>Possible Duplicate:</strong><br />
<a href="https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-c-c-java-c-sharp">Pre & post increment operator behavior in C, C++, Java, & C#</a></p>
</blockquote>
<p>Here is a test case:</p>
<pre><code>
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
</code></pre>
<p>I would expect to get a "0 1" output, but I get "0 0"
What gives??</p>
| [
{
"answer_id": 98256,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 7,
"selected": true,
"text": "<p>This is an example of unspecified behavior. The standard does <strong>not</strong> say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order. </p>\n\n<p>In this case, it looks like actually processes the arguments right to left instead of the expected left to right.</p>\n\n<p>In general, doing side-effects in arguments is bad programming practice. </p>\n\n<p>Instead of <strong>foo(test++, test);</strong> you should write <strong>foo(test, test+1); test++;</strong></p>\n\n<p>It would be semantically equivalent to what you are trying to accomplish.</p>\n\n<p>Edit:\nAs Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed <strong>undefined</strong>. So the compiler is free to generate whatever code it wants.</p>\n"
},
{
"answer_id": 98259,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>The compiler might not be evaluating the arguments in the order you'd expect.</p>\n"
},
{
"answer_id": 98263,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 4,
"selected": false,
"text": "<p>Everything I said originally is WRONG! The point in time at which the side-affect is calculated <strong>is</strong> unspecified. Visual C++ will perform the increment after the call to foo() if test is a local variable, but if test is declared as static or global it will be incremented before the call to foo() and produce different results, although the final value of test will be correct.</p>\n\n<p>The increment should really be done in a separate statement after the call to foo(). Even if the behaviour was specified in the C/C++ standard it would be confusing. You would think that C++ compilers would flag this as a potential error.</p>\n\n<p><a href=\"https://www.securecoding.cert.org/confluence/display/cplusplus/EXP34-C.+Do+not+depend+on+order+of+evaluation+between+sequence+points\" rel=\"nofollow noreferrer\">Here</a> is a good description of sequence points and unspecified behaviour.</p>\n\n<p><----START OF WRONG WRONG WRONG----></p>\n\n<p>The \"++\" bit of \"test++\" gets executed after the call to foo. So you pass in (0,0) to foo, not (1,0)</p>\n\n<p>Here is the assembler output from Visual Studio 2002:</p>\n\n<pre><code>mov ecx, DWORD PTR _i$[ebp]\npush ecx\nmov edx, DWORD PTR tv66[ebp]\npush edx\ncall _foo\nadd esp, 8\nmov eax, DWORD PTR _i$[ebp]\nadd eax, 1\nmov DWORD PTR _i$[ebp], eax\n</code></pre>\n\n<p>The increment is done AFTER the call to foo(). While this behavior is by design, it is certainly confusing to the casual reader and should probably be avoided. The increment should really be done in a separate statement after the call to foo()</p>\n\n<p><----END OF WRONG WRONG WRONG ----></p>\n"
},
{
"answer_id": 98267,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 1,
"selected": false,
"text": "<p>The order of evaluation for arguments to a function is undefined. In this case it appears that it did them right-to-left.</p>\n\n<p>(Modifying variables between sequence points basically allows a compiler to do anything it wants.)</p>\n"
},
{
"answer_id": 98277,
"author": "Fabio Ceconello",
"author_id": 8999,
"author_profile": "https://Stackoverflow.com/users/8999",
"pm_score": 2,
"selected": false,
"text": "<p>C doesn't guarantee the order of evaluation of parameters in a function call, so with this you might get the results \"0 1\" or \"0 0\". The order can change from compiler to compiler, and the same compiler could choose different orders based on optimization parameters.</p>\n\n<p>It's safer to write foo(test, test + 1) and then do ++test in the next line. Anyway, the compiler should optimize it if possible.</p>\n"
},
{
"answer_id": 99363,
"author": "Benjamin Autin",
"author_id": 1440933,
"author_profile": "https://Stackoverflow.com/users/1440933",
"pm_score": 3,
"selected": false,
"text": "<p>It's \"unspecified behavior\", but in practice with the way the C call stack is specified it almost always guarantees that you will see it as 0, 0 and never 1, 0.</p>\n\n<p>As someone noted, the assembler output by VC pushes the right most parameter on the stack first. This is how C function calls are implemented in assembler. This is to accommodate C's \"endless parameter list\" feature. By pushing parameters in a right-to-left order, the first parameter is guaranteed to be the top item on the stack.</p>\n\n<p>Take printf's signature:</p>\n\n<pre><code>int printf(const char *format, ...);\n</code></pre>\n\n<p>Those ellipses denote an unknown number of parameters. If parameters were pushed left-to-right, the format would be at the bottom of a stack of which we don't know the size.</p>\n\n<p>Knowing that in C (and C++) that parameters are processed left-to-right, we can determine the simplest way of parsing and interpreting a function call. Get to the end of the parameter list, and start pushing, evaluating any complex statements as you go.</p>\n\n<p>However, even this can't save you as most C compilers have an option to parse functions \"Pascal style\". And all this means is that the function parameters are pushed on the stack in a left-to-right fashion. If, for instance, printf was compiled with the Pascal option, then the output would most likely be 1, 0 (however, since printf uses the ellipse, I don't think it can be compiled Pascal style).</p>\n"
},
{
"answer_id": 100634,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 5,
"selected": false,
"text": "<p>This is not just <em>unspecified</em> behaviour, it is actually <strong>undefined behaviour</strong> .</p>\n\n<p>Yes, the order of argument evaluation is <em>unspecified</em>, but it is <em>undefined</em> to both read and modify a single variable without an intervening sequence point unless the read is solely for the purpose of computing the new value. There is no sequence point between the evaluations of function arguments, so <code>f(test,test++)</code> is <strong>undefined behaviour</strong>: <code>test</code> is being read for one argument and modified for the other. If you move the modification into a function then you're fine:</p>\n\n<pre><code>int preincrement(int* p)\n{\n return ++(*p);\n}\n\nint test;\nprintf(\"%d %d\\n\",preincrement(&test),test);\n</code></pre>\n\n<p>This is because there is a sequence point on entry and exit to <code>preincrement</code>, so the call must be evaluated either before or after the simple read. Now the order is just <em>unspecified</em>.</p>\n\n<p>Note also that the comma <em>operator</em> provides a sequence point, so</p>\n\n<pre><code>int dummy;\ndummy=test++,test;\n</code></pre>\n\n<p>is fine --- the increment happens before the read, so <code>dummy</code> is set to the new value.</p>\n"
},
{
"answer_id": 102223,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 1,
"selected": false,
"text": "<p>Um, now that the OP has been edited for consistency, it is out of sync with the answers. The fundamental answer about order of evaluation is correct. However the specific possible values are different for the foo(++test, test); case.</p>\n\n<p>++test <em>will</em> be incremented before being passed, so the first argument will always be 1. The second argument will be 0, or 1 depending on evaluation order.</p>\n"
},
{
"answer_id": 106678,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>According to the C standard, it is undefined behaviour to have more than one references to a variable in a single sequence point (here you can think of that as being a statement, or parameters to a function) where one of more of those references includes a pre/post modification.\nSo:\nfoo(f++,f) <--undefined as to when f increments.\nAnd likewise (I see this all the time in user code):\n*p = p++ + p;</p>\n\n<p>Typically a compiler will not change its behaviour for this type of thing (except for major revisions).</p>\n\n<p>Avoid it by turning on warnings and paying attention to them.</p>\n"
},
{
"answer_id": 167227,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 1,
"selected": false,
"text": "<p>To repeat what others have said, this is not unspecified behavior, but rather undefined. This program can legally output anything or nothing, leave n at any value, or send insulting email to your boss.</p>\n\n<p>As a matter of practice, compiler writers will usually just do what's easiest for them to write, which generally means that the program will fetch n once or twice, call the function, and increment sometime. This, like any other conceivable behavior, is just fine according to the standard. There is no reason to expect the same behavior between compilers, or versions, or with different compiler options. There is no reason why two different but similar-looking examples in the same program have to be compiled consistently, although that's the way I'd bet.</p>\n\n<p>In short, don't do this. Test it under different circumstances if you're curious, but don't pretend that there is a single correct or even predictable result.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
| >
> **Possible Duplicate:**
>
> [Pre & post increment operator behavior in C, C++, Java, & C#](https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-c-c-java-c-sharp)
>
>
>
Here is a test case:
```
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
```
I would expect to get a "0 1" output, but I get "0 0"
What gives?? | This is an example of unspecified behavior. The standard does **not** say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order.
In this case, it looks like actually processes the arguments right to left instead of the expected left to right.
In general, doing side-effects in arguments is bad programming practice.
Instead of **foo(test++, test);** you should write **foo(test, test+1); test++;**
It would be semantically equivalent to what you are trying to accomplish.
Edit:
As Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed **undefined**. So the compiler is free to generate whatever code it wants. |
98,274 | <p>Is it possible to integrate SSRS reports to the webforms..an example will be enough to keep me moving. </p>
| [
{
"answer_id": 98312,
"author": "user10635",
"author_id": 10635,
"author_profile": "https://Stackoverflow.com/users/10635",
"pm_score": 0,
"selected": false,
"text": "<p>this is a knowledge base article which describes how to render report output to an aspx page in a particular file format.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/875447/en-us\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/875447/en-us</a></p>\n"
},
{
"answer_id": 98344,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 3,
"selected": false,
"text": "<p>Absolutely it is.</p>\n\n<p>What you are looking for is the ReportViewer control, located in the Microsoft.Reporting.WebForms assembly. It will allow you to place a control right on your web form that will give people an interface for setting report parameters and getting the report.</p>\n\n<p>Alternatively you can set all the parameters yourself and output the report in whatever format you need. We use it in our application to output PDF.</p>\n\n<p>For instance - this is how we setup a reportviewer object for one of our reports and get the PDF, and then send it back to the user. The particular code block is a web handler.</p>\n\n<pre><code>public void ProcessRequest(HttpContext context)\n{\n string report = null;\n int managerId = -1;\n int planId = -1;\n GetParametersFromSession(context.Session, out report, out managerId, out planId);\n if (report == null || managerId == -1 || planId == -1)\n {\n return;\n }\n\n CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;\n\n List<ReportParameter> parameters = new List<ReportParameter>();\n parameters.Add(new ReportParameter(\"Prefix\", report));\n parameters.Add(new ReportParameter(\"ManagerId\", managerId.ToString()));\n parameters.Add(new ReportParameter(\"ActionPlanId\", planId.ToString()));\n string language = Thread.CurrentThread.CurrentCulture.Name;\n language = String.Format(\"{0}_{1}\", language.Substring(0, 2), language.Substring(3, 2).ToLower());\n parameters.Add(new ReportParameter(\"Lang\", language));\n\n ReportViewer rv = new ReportViewer();\n rv.ProcessingMode = ProcessingMode.Remote;\n rv.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings[\"ReportServer\"]);\n if (ConfigurationManager.AppSettings[\"DbYear\"] == \"2007\")\n {\n rv.ServerReport.ReportPath = \"/ActionPlanning/Plan\";\n }\n else\n {\n rv.ServerReport.ReportPath = String.Format(\"/ActionPlanning{0}/Plan\", ConfigurationManager.AppSettings[\"DbYear\"]);\n }\n rv.ServerReport.SetParameters(parameters);\n\n string mimeType = null;\n string encoding = null;\n string extension = null;\n string[] streamIds = null;\n Warning[] warnings = null;\n byte[] output = rv.ServerReport.Render(\"pdf\", null, out mimeType, out encoding, out extension, out streamIds, out warnings);\n\n context.Response.ContentType = mimeType;\n context.Response.BinaryWrite(output);\n}\n</code></pre>\n"
},
{
"answer_id": 98407,
"author": "Bob Albright",
"author_id": 15050,
"author_profile": "https://Stackoverflow.com/users/15050",
"pm_score": 0,
"selected": false,
"text": "<p>Be warned that you will lose some functionality such as the parameter selection stuff when you do not use the URL Access method.</p>\n\n<blockquote>\n <p>Report server URL access supports HTML Viewer and the extended functionality of the report toolbar. The SOAP API does not support this type of rendered report. You need to design and develop your own report toolbar, if you render reports using SOAP.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms155089.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms155089.aspx</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
]
| Is it possible to integrate SSRS reports to the webforms..an example will be enough to keep me moving. | Absolutely it is.
What you are looking for is the ReportViewer control, located in the Microsoft.Reporting.WebForms assembly. It will allow you to place a control right on your web form that will give people an interface for setting report parameters and getting the report.
Alternatively you can set all the parameters yourself and output the report in whatever format you need. We use it in our application to output PDF.
For instance - this is how we setup a reportviewer object for one of our reports and get the PDF, and then send it back to the user. The particular code block is a web handler.
```
public void ProcessRequest(HttpContext context)
{
string report = null;
int managerId = -1;
int planId = -1;
GetParametersFromSession(context.Session, out report, out managerId, out planId);
if (report == null || managerId == -1 || planId == -1)
{
return;
}
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
List<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("Prefix", report));
parameters.Add(new ReportParameter("ManagerId", managerId.ToString()));
parameters.Add(new ReportParameter("ActionPlanId", planId.ToString()));
string language = Thread.CurrentThread.CurrentCulture.Name;
language = String.Format("{0}_{1}", language.Substring(0, 2), language.Substring(3, 2).ToLower());
parameters.Add(new ReportParameter("Lang", language));
ReportViewer rv = new ReportViewer();
rv.ProcessingMode = ProcessingMode.Remote;
rv.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServer"]);
if (ConfigurationManager.AppSettings["DbYear"] == "2007")
{
rv.ServerReport.ReportPath = "/ActionPlanning/Plan";
}
else
{
rv.ServerReport.ReportPath = String.Format("/ActionPlanning{0}/Plan", ConfigurationManager.AppSettings["DbYear"]);
}
rv.ServerReport.SetParameters(parameters);
string mimeType = null;
string encoding = null;
string extension = null;
string[] streamIds = null;
Warning[] warnings = null;
byte[] output = rv.ServerReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
context.Response.ContentType = mimeType;
context.Response.BinaryWrite(output);
}
``` |
98,320 | <p>My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.</p>
<p>My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 98456,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 0,
"selected": false,
"text": "<p>By default Spring beans are singletons and are instantiated when the application context is created (at startup). So assuming you haven't overridden the default behaviour, then a single instance of every bean will be created.</p>\n"
},
{
"answer_id": 98494,
"author": "willCode4Beer",
"author_id": 17909,
"author_profile": "https://Stackoverflow.com/users/17909",
"pm_score": -1,
"selected": false,
"text": "<p>Depends upon the objects.</p>\n\n<p>But, unused code is 'cruft' and will increase the cost of maintenance.</p>\n\n<p>Better to delete the refs and classes. You can always restore from version control if they are needed later.</p>\n"
},
{
"answer_id": 98544,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 4,
"selected": true,
"text": "<p>Taken from the <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lazy-init\" rel=\"noreferrer\">Spring Reference Manual</a>:</p>\n<blockquote>\n<p>The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).</p>\n<p>However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.</p>\n<p>When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example:</p>\n</blockquote>\n<pre><code><bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>\n</code></pre>\n<p>But, unless your beans are using up resources like file locks or database connections, I wouldn't worry too much about simple memory overhead if it is easier for you to have this one configuration for multiple (but different) profiles.</p>\n"
},
{
"answer_id": 150210,
"author": "Tom De Leu",
"author_id": 22263,
"author_profile": "https://Stackoverflow.com/users/22263",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the other comments: it's also possible to specify a whole configuration file to be lazily initialized, by using the 'default-lazy-init' attribute on the <code><beans/></code> element; for example:</p>\n\n<pre><code><beans default-lazy-init=\"true\">\n <!-- no beans will be pre-instantiated... -->\n</beans>\n</code></pre>\n\n<p>This is much easier than adding the <code>lazy-init</code> attribute to every bean, if you have a lot of them.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
| My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.
My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.
Any ideas? | Taken from the [Spring Reference Manual](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lazy-init):
>
> The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).
>
>
> However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.
>
>
> When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example:
>
>
>
```
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
```
But, unless your beans are using up resources like file locks or database connections, I wouldn't worry too much about simple memory overhead if it is easier for you to have this one configuration for multiple (but different) profiles. |
98,340 | <p>An example of unspecified behavior in the C language is the order of evaluation of arguments to a function. It might be left to right or right to left, you just don't know. This would affect how <code>foo(c++, c)</code> or <code>foo(++c, c)</code> gets evaluated.</p>
<p>What other unspecified behavior is there that can surprise the unaware programmer?</p>
| [
{
"answer_id": 98351,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 1,
"selected": false,
"text": "<p>Be sure to always initialize your variables before you use them! When I had just started with C, that caused me a number of headaches.</p>\n"
},
{
"answer_id": 98356,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 7,
"selected": true,
"text": "<p>A language lawyer question. Hmkay.</p>\n<p>My personal top3:</p>\n<ol>\n<li><p>violating the strict aliasing rule</p>\n</li>\n<li><p>violating the strict aliasing rule</p>\n</li>\n<li><p>violating the strict aliasing rule</p>\n<p>:-)</p>\n</li>\n</ol>\n<p><strong>Edit</strong> Here is a little example that does it wrong twice:</p>\n<p>(assume 32 bit ints and little endian)</p>\n<pre><code>float funky_float_abs (float a)\n{\n unsigned int temp = *(unsigned int *)&a;\n temp &= 0x7fffffff;\n return *(float *)&temp;\n}\n</code></pre>\n<p>That code tries to get the absolute value of a float by bit-twiddling with the sign bit directly in the representation of a float.</p>\n<p>However, the result of creating a pointer to an object by casting from one type to another is not valid C. The compiler may assume that pointers to different types don't point to the same chunk of memory. This is true for all kind of pointers except void* and char* (sign-ness does not matter).</p>\n<p>In the case above I do that twice. Once to get an int-alias for the float a, and once to convert the value back to float.</p>\n<p>There are three valid ways to do the same.</p>\n<p>Use a char or void pointer during the cast. These always alias to anything, so they are safe.</p>\n<pre><code>float funky_float_abs (float a)\n{\n float temp_float = a;\n // valid, because it's a char pointer. These are special.\n unsigned char * temp = (unsigned char *)&temp_float;\n temp[3] &= 0x7f;\n return temp_float;\n}\n</code></pre>\n<p>Use memcopy. Memcpy takes void pointers, so it will force aliasing as well.</p>\n<pre><code>float funky_float_abs (float a)\n{\n int i;\n float result;\n memcpy (&i, &a, sizeof (int));\n i &= 0x7fffffff;\n memcpy (&result, &i, sizeof (int));\n return result;\n}\n</code></pre>\n<p>The third valid way: use unions. This is explicitly <strong>not undefined since C99:</strong></p>\n<pre><code>float funky_float_abs (float a)\n{\n union \n {\n unsigned int i;\n float f;\n } cast_helper;\n\n cast_helper.f = a;\n cast_helper.i &= 0x7fffffff;\n return cast_helper.f;\n}\n</code></pre>\n"
},
{
"answer_id": 98358,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": false,
"text": "<p>My favorite is this:</p>\n\n<pre><code>// what does this do?\nx = x++;\n</code></pre>\n\n<p>To answer some comments, it is undefined behaviour according to the standard. Seeing this, the compiler is allowed to do anything up to and including format your hard drive.\nSee for example <a href=\"http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=47343\" rel=\"noreferrer\">this comment here</a>. The point is not that you can see there is a possible reasonable expectation of some behaviour. Because of the C++ standard and the way the sequence points are defined, this line of code is actually undefined behaviour.</p>\n\n<p>For example, if we had <code>x = 1</code> before the line above, then what would the valid result be afterwards? Someone commented that it should be </p>\n\n<blockquote>\n <p>x is incremented by 1</p>\n</blockquote>\n\n<p>so we should see x == 2 afterwards. However this is not actually true, you will find some compilers that have x == 1 afterwards, or maybe even x == 3. You would have to look closely at the generated assembly to see why this might be, but the differences are due to the underlying problem. Essentially, I think this is because the compiler is allowed to evaluate the two assignments statements in any order it likes, so it could do the <code>x++</code> first, or the <code>x =</code> first.</p>\n"
},
{
"answer_id": 98414,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 4,
"selected": false,
"text": "<p>Dividing something by a pointer to something. Just won't compile for some reason... :-)</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>result = x/*y;\n</code></pre>\n"
},
{
"answer_id": 98589,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 5,
"selected": false,
"text": "<p>My personal favourite undefined behaviour is that if a non-empty source file doesn't end in a newline, behaviour is undefined.</p>\n\n<p>I suspect it's true though that no compiler I will ever see has treated a source file differently according to whether or not it is newline terminated, other than to emit a warning. So it's not really something that will surprise unaware programmers, other than that they might be surprised by the warning.</p>\n\n<p>So for genuine portability issues (which mostly are implementation-dependent rather than unspecified or undefined, but I think that falls into the spirit of the question):</p>\n\n<ul>\n<li>char is not necessarily (un)signed.</li>\n<li>int can be any size from 16 bits.</li>\n<li>floats are not necessarily IEEE-formatted or conformant.</li>\n<li>integer types are not necessarily two's complement, and integer arithmetic overflow causes undefined behaviour (modern hardware won't crash, but some compiler optimizations will result in behavior different from wraparound even though that's what the hardware does. For example <code>if (x+1 < x)</code> may be optimized as always false when <code>x</code> has signed type: see <code>-fstrict-overflow</code> option in GCC). </li>\n<li>\"/\", \".\" and \"..\" in a #include have no defined meaning and can be treated differently by different compilers (this does actually vary, and if it goes wrong it will ruin your day).</li>\n</ul>\n\n<p>Really serious ones that can be surprising even on the platform you developed on, because behaviour is only partially undefined / unspecified:</p>\n\n<ul>\n<li><p>POSIX threading and the ANSI memory model. Concurrent access to memory is not as well defined as novices think. volatile doesn't do what novices think. Order of memory accesses is not as well defined as novices think. Accesses <em>can</em> be moved across memory barriers in certain directions. Memory cache coherency is not required.</p></li>\n<li><p>Profiling code is not as easy as you think. If your test loop has no effect, the compiler can remove part or all of it. inline has no defined effect.</p></li>\n</ul>\n\n<p>And, as I think Nils mentioned in passing:</p>\n\n<ul>\n<li>VIOLATING THE STRICT ALIASING RULE.</li>\n</ul>\n"
},
{
"answer_id": 99028,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 3,
"selected": false,
"text": "<p>A compiler doesn't have to tell you that you're calling a function with the wrong number of parameters/wrong parameter types if the function prototype isn't available.</p>\n"
},
{
"answer_id": 99044,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 2,
"selected": false,
"text": "<p>The EE's here just discovered that a>>-2 is a bit fraught.</p>\n\n<p>I nodded and told them it was not natural.</p>\n"
},
{
"answer_id": 100361,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": 4,
"selected": false,
"text": "<p>Another issue I encountered (which is defined, but definitely unexpected).</p>\n\n<p>char is evil.</p>\n\n<ul>\n<li>signed or unsigned depending on what the compiler feels </li>\n<li><strong>not</strong> mandated as 8 bits</li>\n</ul>\n"
},
{
"answer_id": 9104210,
"author": "Per Johansson",
"author_id": 622060,
"author_profile": "https://Stackoverflow.com/users/622060",
"pm_score": 3,
"selected": false,
"text": "<p>The clang developers posted some <a href=\"http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html\" rel=\"noreferrer\">great examples</a> a while back, in a post every C programmer should read. Some interesting ones not mentioned before:</p>\n\n<ul>\n<li>Signed integer overflow - no it's not ok to wrap a signed variable past its max.</li>\n<li>Dereferencing a NULL Pointer - yes this is undefined, and might be ignored, see part 2 of the link.</li>\n</ul>\n"
},
{
"answer_id": 18260275,
"author": "Jens",
"author_id": 648658,
"author_profile": "https://Stackoverflow.com/users/648658",
"pm_score": 4,
"selected": false,
"text": "<p>I can't count the number of times I've corrected printf format specifiers to match their argument. <strong>Any mismatch is undefined behavior</strong>.</p>\n\n<ul>\n<li>No, you must not pass an <code>int</code> (or <code>long</code>) to <code>%x</code> - an <code>unsigned int</code> is required</li>\n<li>No, you must not pass an <code>unsigned int</code> to <code>%d</code> - an <code>int</code> is required</li>\n<li>No, you must not pass a <code>size_t</code> to <code>%u</code> or <code>%d</code> - use <code>%zu</code></li>\n<li>No, you must not print a pointer with <code>%d</code> or <code>%x</code> - use <code>%p</code> and cast to a <code>void *</code></li>\n</ul>\n"
},
{
"answer_id": 18261067,
"author": "Keith Thompson",
"author_id": 827263,
"author_profile": "https://Stackoverflow.com/users/827263",
"pm_score": 3,
"selected": false,
"text": "<p>I've seen a lot of relatively inexperienced programmers bitten by multi-character constants.</p>\n\n<p>This:</p>\n\n<pre><code>\"x\"\n</code></pre>\n\n<p>is a string literal (which is of type <code>char[2]</code> and decays to <code>char*</code> in most contexts).</p>\n\n<p>This:</p>\n\n<pre><code>'x'\n</code></pre>\n\n<p>is an ordinary character constant (which, for historical reasons, is of type <code>int</code>).</p>\n\n<p>This:</p>\n\n<pre><code>'xy'\n</code></pre>\n\n<p>is also a perfectly legal character constant, but its value (which is still of type <code>int</code>) is implementation-defined. It's a nearly useless language feature that serves mostly to cause confusion.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
| An example of unspecified behavior in the C language is the order of evaluation of arguments to a function. It might be left to right or right to left, you just don't know. This would affect how `foo(c++, c)` or `foo(++c, c)` gets evaluated.
What other unspecified behavior is there that can surprise the unaware programmer? | A language lawyer question. Hmkay.
My personal top3:
1. violating the strict aliasing rule
2. violating the strict aliasing rule
3. violating the strict aliasing rule
:-)
**Edit** Here is a little example that does it wrong twice:
(assume 32 bit ints and little endian)
```
float funky_float_abs (float a)
{
unsigned int temp = *(unsigned int *)&a;
temp &= 0x7fffffff;
return *(float *)&temp;
}
```
That code tries to get the absolute value of a float by bit-twiddling with the sign bit directly in the representation of a float.
However, the result of creating a pointer to an object by casting from one type to another is not valid C. The compiler may assume that pointers to different types don't point to the same chunk of memory. This is true for all kind of pointers except void\* and char\* (sign-ness does not matter).
In the case above I do that twice. Once to get an int-alias for the float a, and once to convert the value back to float.
There are three valid ways to do the same.
Use a char or void pointer during the cast. These always alias to anything, so they are safe.
```
float funky_float_abs (float a)
{
float temp_float = a;
// valid, because it's a char pointer. These are special.
unsigned char * temp = (unsigned char *)&temp_float;
temp[3] &= 0x7f;
return temp_float;
}
```
Use memcopy. Memcpy takes void pointers, so it will force aliasing as well.
```
float funky_float_abs (float a)
{
int i;
float result;
memcpy (&i, &a, sizeof (int));
i &= 0x7fffffff;
memcpy (&result, &i, sizeof (int));
return result;
}
```
The third valid way: use unions. This is explicitly **not undefined since C99:**
```
float funky_float_abs (float a)
{
union
{
unsigned int i;
float f;
} cast_helper;
cast_helper.f = a;
cast_helper.i &= 0x7fffffff;
return cast_helper.f;
}
``` |
98,376 | <p>I need to store some simple properties in a file and access them from Ruby.</p>
<p>I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read.</p>
<p>So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort?</p>
<p>I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax").</p>
<p>I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line....</p>
<hr>
<p>UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone!</p>
| [
{
"answer_id": 98415,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 6,
"selected": true,
"text": "<p>Is this for a Rails application or a Ruby one?</p>\n\n<p>Really with either you may be able to stick your properties in a yaml file and then <code>YAML::Load(File.open(\"file\"))</code> it.</p>\n\n<hr>\n\n<p><strong>NOTE from Mike Stone:</strong> It would actually be better to do:</p>\n\n<pre><code>File.open(\"file\") { |yf| YAML::load(yf) }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>YAML.load_file(\"file\")\n</code></pre>\n\n<p>as the ruby docs suggest, otherwise the file won't be closed till garbage collection, but good suggestion regardless :-)</p>\n"
},
{
"answer_id": 98445,
"author": "Christopher Currie",
"author_id": 9700,
"author_profile": "https://Stackoverflow.com/users/9700",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of the .properties style of config file, you might consider using YAML. YAML used in Ruby on Rails for database configuration, and has gained in popularity in other languages (Python, Java, Perl, and others).</p>\n\n<p>An overview of the Ruby YAML module is here: <a href=\"http://www.ruby-doc.org/core/classes/YAML.html\" rel=\"nofollow noreferrer\">http://www.ruby-doc.org/core/classes/YAML.html</a></p>\n\n<p>And the home page of YAML is here: <a href=\"http://yaml.org/\" rel=\"nofollow noreferrer\">http://yaml.org</a></p>\n"
},
{
"answer_id": 98473,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 2,
"selected": false,
"text": "<p>Devender Gollapally wrote a <a href=\"http://devender.wordpress.com/2006/05/01/reading-and-writing-java-property-files-with-ruby\" rel=\"nofollow noreferrer\">class</a> to do precisely that:</p>\n\n<p>...though i'd recommend better to use a YAML file.</p>\n"
},
{
"answer_id": 99032,
"author": "Dan Harper",
"author_id": 14530,
"author_profile": "https://Stackoverflow.com/users/14530",
"pm_score": 3,
"selected": false,
"text": "<p>YAML will do it perfectly as described above. For an example, in one of my Ruby scripts I have a YAML file like:</p>\n\n<pre><code>migration:\n customer: Example Customer\n test: false\nsources:\n- name: Use the Source\n engine: Foo\n- name: Sourcey\n engine: Bar\n</code></pre>\n\n<p>which I then use within Ruby as:</p>\n\n<pre><code>config = YAML.load_file(File.join(File.dirname(__FILE__), ARGV[0]))\nputs config['migration']['customer']\n\nconfig['sources'].each do |source|\n puts source['name']\nend\n</code></pre>\n"
},
{
"answer_id": 99695,
"author": "Aaron Hinni",
"author_id": 12086,
"author_profile": "https://Stackoverflow.com/users/12086",
"pm_score": 3,
"selected": false,
"text": "<p>Another option is to simply use another Ruby file as your configuration file.</p>\n\n<p>Example, create a file called 'options'</p>\n\n<pre><code>{\n :blah => 'blee',\n :foo => 'bar',\n :items => ['item1', 'item2'],\n :stuff => true\n}\n</code></pre>\n\n<p>And then in your Ruby code do something like:</p>\n\n<pre><code>ops = eval(File.open('options') {|f| f.read })\nputs ops[:foo]\n</code></pre>\n"
},
{
"answer_id": 15607254,
"author": "Ross Attrill",
"author_id": 556644,
"author_profile": "https://Stackoverflow.com/users/556644",
"pm_score": 3,
"selected": false,
"text": "<p><em>inifile</em> - <a href=\"http://rubydoc.info/gems/inifile/2.0.2/frames\" rel=\"nofollow\">http://rubydoc.info/gems/inifile/2.0.2/frames</a> will support basic .properties files and also .ini files with [SECTIONS] eg.</p>\n\n<pre><code>[SECTION]\nkey=value\n</code></pre>\n\n<p>YAML is good when your data has complex structure but can be fiddly with spaces, tabs, end of lines etc - which might cause problems if the files are not maintained by programmers. By contrast <code>.properties</code> and <code>.ini</code> files are more forgiving and may be suitable if you don't need the deep structure available through YAML.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
| I need to store some simple properties in a file and access them from Ruby.
I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read.
So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort?
I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax").
I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line....
---
UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone! | Is this for a Rails application or a Ruby one?
Really with either you may be able to stick your properties in a yaml file and then `YAML::Load(File.open("file"))` it.
---
**NOTE from Mike Stone:** It would actually be better to do:
```
File.open("file") { |yf| YAML::load(yf) }
```
or
```
YAML.load_file("file")
```
as the ruby docs suggest, otherwise the file won't be closed till garbage collection, but good suggestion regardless :-) |
98,394 | <p>I looked for the name of a procedure, which applies a tree structure of procedures to a tree structure of data, yielding a tree structure of results - all three trees having the same structure. </p>
<p>Such a procedure might have the signature: </p>
<pre>(map-tree data functree)</pre>
<p>Its return value would be the result of elementwise application of functree's elements on the corresponding data elements. </p>
<p>Examples (assuming that the procedure is called map-tree): </p>
<p>Example 1: </p>
<pre>(define *2 (lambda (x) (* 2 x)))
; and similar definitions for *3 and *5
(map-tree '(100 (10 1)) '(*2 (*3 *5)))</pre>
<p>would yield the result <pre>(200 (30 5))</pre></p>
<p>Example 2: </p>
<pre>(map-tree '(((aa . ab) (bb . bc)) (cc . (cd . ce)))
'((car cdr) cadr))</pre>
<p>yields the result <pre>((aa bc) cd)</pre></p>
<p>However I did not find such a function in the SLIB documentation, which I consulted. </p>
<p>Does such a procedure already exist?<br>
If not, what would be a suitable name for the procedure, and how would you order its arguments?</p>
| [
{
"answer_id": 98520,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p>I don't have a very good name for the function. I'm pasting my implementation below (I've called it <code>map-traversing</code>; others should suggest a better name). I've made the argument order mirror that of <code>map</code> itself.</p>\n\n<pre><code>(define (map-traversing func data)\n (if (list? func)\n (map map-traversing func data)\n (func data)))\n</code></pre>\n\n<p>Using your sample data, we have:</p>\n\n<pre><code>(map-traversing `((,car ,cdr) ,cadr) '(((aa . ab) (bb . bc)) (cc cd . ce)))\n</code></pre>\n\n<p>The second sample requires SRFI 26. (Allows writing <code>(cut * 2 <>)</code> instead of <code>(lambda (x) (* 2 x))</code>.)</p>\n\n<pre><code>(map-traversing `(,(cut * 2 <>) (,(cut * 3 <>) ,(cut * 5 <>))) '(100 (10 1)))\n</code></pre>\n\n<p>The most important thing is that your functions must all be unquoted, unlike your example.</p>\n"
},
{
"answer_id": 99190,
"author": "Omer Zak",
"author_id": 11886,
"author_profile": "https://Stackoverflow.com/users/11886",
"pm_score": 1,
"selected": false,
"text": "<p>I found that with the follwing definition of map-traversing, you don't need to unquote the functions:</p>\n\n<pre>(define (map-traversing func data)\n (if (list? func)\n (map map-traversing func data)\n (apply (eval func (interaction-environment)) (list data))))</pre>\n\n<p>Note: in my installed version of Guile, due to some reason, only (interaction-environment) does not raise the Unbound variable error. The other environments i.e. (scheme-report-environment 5) and (null-environment 5) raise this error. </p>\n\n<p>Note 2: Subsequently, I found in [1] that for (scheme-report-environment 5) and (null-environment 5) to work, you need first to (use-modules (ice-9 r5rs))</p>\n\n<p>[1]: <a href=\"http://www.mail-archive.com/[email protected]/msg04368.html\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/msg04368.html</a> 'Re: guile -c \"(scheme-report-environment 5)\" ==> ERROR: Unbound variable: scheme-report-environment'</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11886/"
]
| I looked for the name of a procedure, which applies a tree structure of procedures to a tree structure of data, yielding a tree structure of results - all three trees having the same structure.
Such a procedure might have the signature:
```
(map-tree data functree)
```
Its return value would be the result of elementwise application of functree's elements on the corresponding data elements.
Examples (assuming that the procedure is called map-tree):
Example 1:
```
(define *2 (lambda (x) (* 2 x)))
; and similar definitions for *3 and *5
(map-tree '(100 (10 1)) '(*2 (*3 *5)))
```
would yield the result
```
(200 (30 5))
```
Example 2:
```
(map-tree '(((aa . ab) (bb . bc)) (cc . (cd . ce)))
'((car cdr) cadr))
```
yields the result
```
((aa bc) cd)
```
However I did not find such a function in the SLIB documentation, which I consulted.
Does such a procedure already exist?
If not, what would be a suitable name for the procedure, and how would you order its arguments? | I don't have a very good name for the function. I'm pasting my implementation below (I've called it `map-traversing`; others should suggest a better name). I've made the argument order mirror that of `map` itself.
```
(define (map-traversing func data)
(if (list? func)
(map map-traversing func data)
(func data)))
```
Using your sample data, we have:
```
(map-traversing `((,car ,cdr) ,cadr) '(((aa . ab) (bb . bc)) (cc cd . ce)))
```
The second sample requires SRFI 26. (Allows writing `(cut * 2 <>)` instead of `(lambda (x) (* 2 x))`.)
```
(map-traversing `(,(cut * 2 <>) (,(cut * 3 <>) ,(cut * 5 <>))) '(100 (10 1)))
```
The most important thing is that your functions must all be unquoted, unlike your example. |
98,479 | <p>What is the maximum value of an int in ChucK? Is there a symbolic constant for it?</p>
| [
{
"answer_id": 98500,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://chuck.cs.princeton.edu/doc/program/stdlib.html\" rel=\"nofollow noreferrer\">The ChucK API reference</a> uses the C <code>int</code> type, so the maximum value would depend on your local machine (2^31-1, around two billion on standard 32-bit x86). I don't see any references to retrieving limits, but if ChucK is extensible using C you could add a function that returns <code>MAXINT</code>.</p>\n"
},
{
"answer_id": 98865,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": 4,
"selected": true,
"text": "<p>New in the latest version!</p>\n\n<pre><code><<<Math.INT_MAX>>>;\n</code></pre>\n\n<p>For reference though, it uses the \"<code>long</code>\" keyword in C++ to represent integers.\nSo on 32-bit computers the max should be <code>0x7FFFFFFF</code>, or <code>2147483647</code>.\nOn 64-bit computers it will be <code>0x7FFFFFFFFFFFFFFFFF</code>, or <code>9223372036854775807</code>.</p>\n\n<p>Answer from Kassen and Stephen Sinclair on the <a href=\"https://lists.cs.princeton.edu/mailman/listinfo/chuck-users\" rel=\"noreferrer\">chuck-users mailing list</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
]
| What is the maximum value of an int in ChucK? Is there a symbolic constant for it? | New in the latest version!
```
<<<Math.INT_MAX>>>;
```
For reference though, it uses the "`long`" keyword in C++ to represent integers.
So on 32-bit computers the max should be `0x7FFFFFFF`, or `2147483647`.
On 64-bit computers it will be `0x7FFFFFFFFFFFFFFFFF`, or `9223372036854775807`.
Answer from Kassen and Stephen Sinclair on the [chuck-users mailing list](https://lists.cs.princeton.edu/mailman/listinfo/chuck-users). |
98,497 | <p>Hi i need to generate 9 digit unique account numbers. Here is my pseudocode:</p>
<pre><code>function generateAccNo()
generate an account number between 100,000,000 and 999,999,999
if the account number already exists in the DB
call generateAccNo() /* recursive call */
else
return new accout number
end if
end function
</code></pre>
<p>The function seems to be working well, however I am a bit worried about the recursive call. </p>
<p>Will this cause any memory leaks (PHP 5 under apache)?</p>
<p>Is this an acceptable way to tackle this problem?</p>
<p>Thanks for your input.</p>
| [
{
"answer_id": 98502,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 4,
"selected": true,
"text": "<p>You realize this could very well cause a stack overflow, right? As the number of customesr increases, the probability of not finding a an acceptable account number increases. </p>\n\n<p>Also, why can't you just do sequential account numbers and just increase by one every time? With this approach, you'd just have to read the max id currently in the database and just increment it.</p>\n\n<p>Sorry to be so blunt, but your solution is a terrible way to tackle the problem. It'll use tons of memory (as the stack possibly grows infinitely) and it will makes tons of expensive calls to the database. </p>\n\n<p><strong>You should really consider some other approach:</strong><br>\nI strongly recommend just incrementing the customer number every time you create a customer. In fact, if you set up your db properly (with auto increment on the id column), you won't even have to set the id. The id will be set for you whenever you insert a new customer.</p>\n"
},
{
"answer_id": 98509,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 0,
"selected": false,
"text": "<p>You do not need to use recursion here. A simple loop would be just as fast and consume less stack space.</p>\n"
},
{
"answer_id": 98513,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>You could put it in a while loop:</p>\n\n<pre><code>function generateAccNo()\n\n while (true) { \n\n generate an account number between 100,000,000 and 999,999,999\n\n if the account number already exists in the DB \n /* do nothing */\n else\n return new accout number\n end if\n }\n\nend function\n</code></pre>\n"
},
{
"answer_id": 98517,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 1,
"selected": false,
"text": "<p>It seems fine, but I think you need some sort of die condition, how many times are you going to let this run before you give up?</p>\n\n<p>I know this seems unlikely with the huge number range, but something could go wrong that just drops you back to the previous call, which will call itself again, ad-nauseum.</p>\n"
},
{
"answer_id": 98522,
"author": "Josh Millard",
"author_id": 13600,
"author_profile": "https://Stackoverflow.com/users/13600",
"pm_score": 2,
"selected": false,
"text": "<p>There's no need to use a recursive call here. Run a simple while loop in the function testing against non-existence as the conditional, e.g.</p>\n\n<pre><code>function generateAccNo()\n\n generate an account number between 100,000,000 and 999,999,999\n\n while ( the account number already exists in the DB ) {\n generate new account number;\n }\n return new account number\n\nend function\n</code></pre>\n\n<p>Randomly generating-and-testing is a sub-optimal approach to generating unique account numbers, though, if this code is for anything other than a toy.</p>\n"
},
{
"answer_id": 98529,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 0,
"selected": false,
"text": "<p>Why not:</p>\n\n<pre><code>lock_db\ndo\n account_num <= generate number\nwhile account_num in db\n\nput row with account_num in db\n\nunlock_db\n</code></pre>\n"
},
{
"answer_id": 98533,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>Why not have the database handle this? IN SQL Server, you can just have an identity column that starts at 100000000. Or you could use sql in whatever db that you have. Just get the max id plus 1.</p>\n"
},
{
"answer_id": 98595,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 1,
"selected": false,
"text": "<p>Generating account numbers sequentially is a security risk - you should find some other algorithm to do it.</p>\n"
},
{
"answer_id": 98637,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": false,
"text": "<p>Alternately, you can maintain a separate table containing a buffer of generated, known to be unique account numbers. This table should have an auto-incrementing integer id. When you want an account number, simply pull the record with the lowest index in the buffer and remove it from that table. Have some process that runs regularly which replenishes the buffer and makes sure it has capacity >> normal usage. The advantage is that the amount of time experienced by the end user spent creating an account number will be essentially constant.</p>\n\n<p>Also, I should note that the processing overhead or risks of recursion or iteration, the real issue is determinism and the overhead of repeating database queries. I like TheZenker's solution of random + sequential. Guaranteed to generate a unique id without adding unnecessary overhead.</p>\n"
},
{
"answer_id": 98763,
"author": "TheZenker",
"author_id": 10552,
"author_profile": "https://Stackoverflow.com/users/10552",
"pm_score": 2,
"selected": false,
"text": "<p>I really don't think it comes down to recursion vs. looping, both are prone to problems as the dataset grows and if the random number generation is not correctly implemented. Two ideas come to mind:</p>\n\n<p>. GUID</p>\n\n<p>If a truly unique id is required with as little effort as possible, consider a GUID, your DB will most likely be able to assign on for you on insert, if not create one in code. It is guaranteed to be unique although it is not very user friendly. However, in combination with a sequential AccountRecordId generated by the DB on insert you would have a solid combination</p>\n\n<p>. Composite Key: Random + Sequential</p>\n\n<p>One way to address all the needs, although at the surface it feels a bit kludgy, is to create a composite account number from a sequential db key of 5 digits (or more) and then another 5 digits of randomness. If the random number was duplicated it would not matter as the sequential id would guarantee the uniqueness of the entire account number</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Hi i need to generate 9 digit unique account numbers. Here is my pseudocode:
```
function generateAccNo()
generate an account number between 100,000,000 and 999,999,999
if the account number already exists in the DB
call generateAccNo() /* recursive call */
else
return new accout number
end if
end function
```
The function seems to be working well, however I am a bit worried about the recursive call.
Will this cause any memory leaks (PHP 5 under apache)?
Is this an acceptable way to tackle this problem?
Thanks for your input. | You realize this could very well cause a stack overflow, right? As the number of customesr increases, the probability of not finding a an acceptable account number increases.
Also, why can't you just do sequential account numbers and just increase by one every time? With this approach, you'd just have to read the max id currently in the database and just increment it.
Sorry to be so blunt, but your solution is a terrible way to tackle the problem. It'll use tons of memory (as the stack possibly grows infinitely) and it will makes tons of expensive calls to the database.
**You should really consider some other approach:**
I strongly recommend just incrementing the customer number every time you create a customer. In fact, if you set up your db properly (with auto increment on the id column), you won't even have to set the id. The id will be set for you whenever you insert a new customer. |
98,559 | <pre><code>uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
</code></pre>
<p>doesn't work. What am i doing wrong?</p>
| [
{
"answer_id": 98572,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 8,
"selected": true,
"text": "<p>Try </p>\n\n<pre><code>Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment\n</code></pre>\n"
},
{
"answer_id": 98588,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 4,
"selected": false,
"text": "<p>Or like </p>\n\n<pre><code>string hexNum = \"0xFFFF\";\nstring hexNumWithoutPrefix = hexNum.Substring(2);\n\nuint i;\nbool success = uint.TryParse(hexNumWithoutPrefix, System.Globalization.NumberStyles.HexNumber, null, out i);\n</code></pre>\n"
},
{
"answer_id": 98592,
"author": "Jeremy Wiebe",
"author_id": 11807,
"author_profile": "https://Stackoverflow.com/users/11807",
"pm_score": 6,
"selected": false,
"text": "<p>You can use an overloaded <code>TryParse()</code> which adds a NumberStyle parameter to the <code>TryParse</code> call which provides parsing of Hexadecimal values. Use <code>NumberStyles.HexNumber</code> which allows you to pass the string as a hex number.</p>\n<p><strong>Note</strong>: The problem with <code>NumberStyles.HexNumber</code> is that it <em>doesn't</em> support parsing values with a prefix (ie. <code>0x</code>, <code>&H</code>, or <code>#</code>), so you have to strip it off before trying to parse the value.</p>\n<p>Basically you'd do this:</p>\n<pre><code>uint color;\nvar hex = TextBox1.Text;\n\nif (hex.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) ||\n hex.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase)) \n{\n hex = hex.Substring(2);\n}\n\nbool parsedSuccessfully = uint.TryParse(hex, \n NumberStyles.HexNumber, \n CultureInfo.CurrentCulture, \n out color);\n</code></pre>\n<p>See the documentation for <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Globalization_NumberStyles_System_IFormatProvider_System_Int32__\" rel=\"nofollow noreferrer\">TryParse(String, NumberStyles, IFormatProvider, Int32)</a> for an example of how to use the NumberStyles enumeration.</p>\n"
},
{
"answer_id": 19301980,
"author": "Curtis Yallop",
"author_id": 854342,
"author_profile": "https://Stackoverflow.com/users/854342",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a try-parse style function:</p>\n\n<pre><code> private static bool TryParseHex(string hex, out UInt32 result)\n {\n result = 0;\n\n if (hex == null)\n {\n return false;\n }\n\n try\n {\n result = Convert.ToUInt32(hex, 16);\n\n return true;\n }\n catch (Exception exception)\n {\n return false;\n }\n }\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
]
| ```
uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
```
doesn't work. What am i doing wrong? | Try
```
Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment
``` |
98,597 | <p>I use AutoHotKey for Windows macros. Most commonly I use it to define hotkeys that start/focus particular apps, and one to send an instant email message into my ToDo list. I also have an emergency one that kills all of my big memory-hogging apps (Outlook, Firefox, etc).</p>
<p>So, does anyone have any good AHK macros to share?</p>
| [
{
"answer_id": 98926,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p>There are tons of good ones in the AutoHotKey Forum:</p>\n\n<p><a href=\"http://www.autohotkey.com/forum/forum-2.html&sid=8149586e9d533532ea76e71e8c9e5b7b\" rel=\"nofollow noreferrer\">http://www.autohotkey.com/forum/forum-2.html&sid=8149586e9d533532ea76e71e8c9e5b7b</a></p>\n\n<p>How good? really depends on what you want/need.</p>\n"
},
{
"answer_id": 100648,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 4,
"selected": false,
"text": "<p>Very simple and useful snippet:</p>\n\n<pre><code>SetTitleMatchMode RegEx ;\n; Stuff to do when Windows Explorer is open\n;\n#IfWinActive ahk_class ExploreWClass|CabinetWClass\n ; create new folder\n ;\n ^!n::Send !fwf\n\n ; create new text file\n ;\n ^!t::Send !fwt\n\n ; open 'cmd' in the current directory\n ;\n ^!c::\n OpenCmdInCurrent()\n return\n#IfWinActive\n\n; Opens the command shell 'cmd' in the directory browsed in Explorer.\n; Note: expecting to be run when the active window is Explorer.\n;\nOpenCmdInCurrent()\n{\n WinGetText, full_path, A ; This is required to get the full path of the file from the address bar\n\n ; Split on newline (`n)\n StringSplit, word_array, full_path, `n\n full_path = %word_array1% ; Take the first element from the array\n\n ; Just in case - remove all carriage returns (`r)\n StringReplace, full_path, full_path, `r, , all \n full_path := RegExReplace(full_path, \"^Address: \", \"\") ;\n\n IfInString full_path, \\\n {\n Run, cmd /K cd /D \"%full_path%\"\n }\n else\n {\n Run, cmd /K cd /D \"C:\\ \"\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100711,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 2,
"selected": false,
"text": "<p>I use this one all the time, usually for quick access to the MySQL command line.</p>\n\n<p><a href=\"http://lifehacker.com/software/featured-windows-download/make-a-quake+style-command-prompt-with-autohotkey-297607.php\" rel=\"nofollow noreferrer\">http://lifehacker.com/software/featured-windows-download/make-a-quake+style-command-prompt-with-autohotkey-297607.php</a></p>\n"
},
{
"answer_id": 780626,
"author": "Bård",
"author_id": 89349,
"author_profile": "https://Stackoverflow.com/users/89349",
"pm_score": 3,
"selected": false,
"text": "<p>; I have this in my start menu so that I won't ruin my ears when I put on my headphones after rebooting my computer</p>\n\n<pre><code>sleep, 5000\nSoundSet, 1.5 ; really low volume\n</code></pre>\n"
},
{
"answer_id": 2331289,
"author": "Peter Gfader",
"author_id": 35693,
"author_profile": "https://Stackoverflow.com/users/35693",
"pm_score": 2,
"selected": false,
"text": "<p>I create new <strong>Outlook</strong> objects with AutoHotKey</p>\n\n<p>; Win+Shift+M = new email</p>\n\n<pre><code>#+m:: Run \"mailto:\"\n</code></pre>\n\n<p>; Outlook</p>\n\n<pre><code>#^M:: Run \"%ProgramFiles%\\Microsoft Office\\Office12\\OUTLOOK.EXE\" /recycle\n</code></pre>\n\n<p>; Win+Shift+A = create new calendar appointment</p>\n\n<pre><code>#+A:: Run \"%ProgramFiles%\\Microsoft Office\\Office12\\OUTLOOK.EXE\"/c ipm.appointment\n</code></pre>\n\n<p>; Win+Shift+T = create new Task\n; Win+Shift+K = New task</p>\n\n<pre><code>#+T:: Run \"%ProgramFiles%\\Microsoft Office\\Office12\\OUTLOOK.EXE\"/c ipm.task\n#+K:: Run \"%ProgramFiles%\\Microsoft Office\\Office12\\OUTLOOK.EXE\"/c ipm.task\n</code></pre>\n"
},
{
"answer_id": 2331297,
"author": "Peter Gfader",
"author_id": 35693,
"author_profile": "https://Stackoverflow.com/users/35693",
"pm_score": 3,
"selected": false,
"text": "<p>Add surrounding quotes on selected text/word<br>\nUseful when writing emails or during coding... </p>\n\n<p>Doubleclick word, hit Win+X, have quotes around</p>\n\n<pre><code>; Win + X\n#x:: ; Attention: Strips formatting from the clipboard too!\nSend ^c\nclipboard = \"%clipboard%\"\n; Remove space introduced by WORD\nStringReplace, clipboard, clipboard,%A_SPACE%\",\", All\nSend ^v\nreturn\n</code></pre>\n"
},
{
"answer_id": 5336476,
"author": "rkagerer",
"author_id": 589059,
"author_profile": "https://Stackoverflow.com/users/589059",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a dead-simple snippet to quickly close the current window using a mouse button.</p>\n\n<p>It's one of the actions you perform most often in Windows, and you'll be surprised at how much time you save by no longer having to shoot for that little X. With a 5-button mouse, I find this a very useful reassignment of the \"Forward\" button.</p>\n\n<pre><code>#IfWinActive ;Close active window when mouse button 5 is pressed\n XButton2::\n SendInput {Alt Down}{F4}{Alt Up}\n Return\n#IfWinActive \n</code></pre>\n\n<p>To take into account programs that use tabbed documents (like web browsers), here's a more comprehensive version:</p>\n\n<pre><code>;-----------------------------------------------------------------------------\n; Bind Mouse Button 5 to Close Tab / Close Window command\n;-----------------------------------------------------------------------------\n\n; Create a group to hold windows which will use Ctrl+F4 instead of Alt+F4\nGroupAdd, CtrlCloseGroup, ahk_class IEFrame ; Internet Explorer\nGroupAdd, CtrlCloseGroup, ahk_class Chrome_WidgetWin_0 ; Google Chrome\n; (Add more programs that use tabbed documents here)\nReturn\n\n; For windows in above group, bind mouse button to Ctrl+F4\n#IfWinActive, ahk_group CtrlCloseGroup\n XButton2::\n SendInput {Ctrl Down}{F4}{Ctrl Up}\n Return\n#IfWinActive \n\n; For everything else, bind mouse button to Alt+F4\n#IfWinActive\n XButton2::\n SendInput {Alt Down}{F4}{Alt Up}\n Return\n#IfWinActive \n\n; In FireFox, bind to Ctrl+W instead, so that the close command also works\n; on the Downloads window.\n#IfWinActive, ahk_class MozillaUIWindowClass\n XButton2::\n SendInput {Ctrl Down}w{Ctrl Up}\n Return\n#IfWinActive\n</code></pre>\n\n<p>Visual Studio 2010 can't easily be added to the <code>CtrlCloseGroup</code> above, as it's window class / title aren't easily predictable (I think). Here's the snippet I use to handle it, including a couple additional helpful bindings:</p>\n\n<pre><code>SetTitleMatchMode, 2 ; Move this line to the top of your script\n\n;-----------------------------------------------------------------------------\n; Visual Studio 2010\n;-----------------------------------------------------------------------------\n\n#IfWinActive, Microsoft Visual Studio\n\n ; Make the middle mouse button jump to the definition of any token\n MButton::\n Click Left ; put the cursor where you clicked\n Send {Shift Down}{F2}{Shift Up}\n Return\n\n ; Make the Back button on the mouse jump you back to the previous area\n ; of code you were working on.\n XButton1::\n Send {Ctrl Down}{Shift Down}{F2}{Shift Up}{Ctrl Up}\n Return\n\n ; Bind the Forward button to close the current tab\n XButton2::\n SendInput {Ctrl Down}{F4}{Ctrl Up}\n Return\n\n#IfWinActive\n</code></pre>\n\n<p>I also find it useful in Outlook to map ALT+1, ALT+2, etc. to macros I wrote which move the currently selected message(s) to specific folders (eg. \"Personal Filed\", \"Work Filed\", etc) but that's a bit more complicated.</p>\n"
},
{
"answer_id": 9555021,
"author": "EvanBlack",
"author_id": 394622,
"author_profile": "https://Stackoverflow.com/users/394622",
"pm_score": 4,
"selected": false,
"text": "<p>Here is so simple but useful script:</p>\n\n<pre><code>^SPACE:: Winset, Alwaysontop, , A\n</code></pre>\n\n<p>Use CTRL + Space to set any window always on top.</p>\n"
},
{
"answer_id": 14455149,
"author": "Johann",
"author_id": 638040,
"author_profile": "https://Stackoverflow.com/users/638040",
"pm_score": 2,
"selected": false,
"text": "<p>Fix an issue when copying file to FTP server when the \"Copying\" dialog appears on top of the \"Confirm File Replace\" dialog (very annoying):</p>\n\n<pre><code>SetTimer, FocusOnWindow, 500\nreturn\n\nFocusOnWindow:\nIfWinExist, Confirm File Replace\n WinActivate\nreturn\n</code></pre>\n\n<p>One to deactivate the useless Caps-lock key:</p>\n\n<pre><code>Capslock::\nreturn\n</code></pre>\n\n<p>CTRL + shift + c will copy colour below cursor to the clipboard (in hexadecimal)</p>\n\n<pre><code>^+c::\nMouseGetPos,x,y\nPixelGetColor,rgb,x,y,RGB\nStringTrimLeft,rgb,rgb,2\nClipboard=%rgb%\nReturn\n</code></pre>\n\n<p>Write your email address in the active field (Win key + m)</p>\n\n<pre><code>#m::\nSend, [email protected]{LWINUP}\nSleep, 100\nSend, {TAB}\nreturn\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10934/"
]
| I use AutoHotKey for Windows macros. Most commonly I use it to define hotkeys that start/focus particular apps, and one to send an instant email message into my ToDo list. I also have an emergency one that kills all of my big memory-hogging apps (Outlook, Firefox, etc).
So, does anyone have any good AHK macros to share? | Very simple and useful snippet:
```
SetTitleMatchMode RegEx ;
; Stuff to do when Windows Explorer is open
;
#IfWinActive ahk_class ExploreWClass|CabinetWClass
; create new folder
;
^!n::Send !fwf
; create new text file
;
^!t::Send !fwt
; open 'cmd' in the current directory
;
^!c::
OpenCmdInCurrent()
return
#IfWinActive
; Opens the command shell 'cmd' in the directory browsed in Explorer.
; Note: expecting to be run when the active window is Explorer.
;
OpenCmdInCurrent()
{
WinGetText, full_path, A ; This is required to get the full path of the file from the address bar
; Split on newline (`n)
StringSplit, word_array, full_path, `n
full_path = %word_array1% ; Take the first element from the array
; Just in case - remove all carriage returns (`r)
StringReplace, full_path, full_path, `r, , all
full_path := RegExReplace(full_path, "^Address: ", "") ;
IfInString full_path, \
{
Run, cmd /K cd /D "%full_path%"
}
else
{
Run, cmd /K cd /D "C:\ "
}
}
``` |
98,610 | <p>By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences.</p>
| [
{
"answer_id": 98625,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": false,
"text": "<p>In your package explorer, pull down the menu and select \"Filters ...\". You can adjust what types of files are shown/hidden there.</p>\n\n<p>Looking at my Red Hat Developer Studio (approximately Eclipse 3.2), I see that the top item in the list is \".* resources\" and it is excluded by default.</p>\n"
},
{
"answer_id": 98634,
"author": "scubabbl",
"author_id": 9450,
"author_profile": "https://Stackoverflow.com/users/9450",
"pm_score": 11,
"selected": true,
"text": "<p>In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters</p>\n\n<p><img src=\"https://i.stack.imgur.com/NWo2x.jpg\" alt=\"filters menu\"></p>\n\n<p>From there, uncheck .* resources.</p>\n\n<p>So <code>Package Explorer -> View Menu -> Filters -> uncheck .* resources</code>.</p>\n\n<p>With Eclipse Kepler and OS X this is a bit different:</p>\n\n<pre><code>Package Explorer -> Customize View -> Filters -> uncheck .* resources\n</code></pre>\n"
},
{
"answer_id": 619607,
"author": "Cory Collier",
"author_id": 53954,
"author_profile": "https://Stackoverflow.com/users/53954",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using Eclipse PDT, this is done by opening up the PHP explorer view, then clicking the upside-down triangle in the top-right of that window. A context window appears, and the filters option is available there. Clicking the Filters menu option opens a new window, where .* files can be unchecked, thus allowing the editing of .htaccess files.</p>\n\n<p>I searched forever for this, so I'm sorta answering my own question here. I'm sure someone else will have the same problem too, so I hope this helps someone else as well.</p>\n"
},
{
"answer_id": 1223325,
"author": "vsecades",
"author_id": 149862,
"author_profile": "https://Stackoverflow.com/users/149862",
"pm_score": 3,
"selected": false,
"text": "<p>If using Zend Studio, same arrow, go to RSE view, click on the downward facing arrow, hit preferences, and then check show hidden files.</p>\n\n<p>That did the trick for me.</p>\n"
},
{
"answer_id": 1430729,
"author": "Aaron Newton",
"author_id": 174075,
"author_profile": "https://Stackoverflow.com/users/174075",
"pm_score": 5,
"selected": false,
"text": "<p>Cory is correct</p>\n\n<p>@ If you're using Eclipse PDT, this is done by opening up the PHP explorer view</p>\n\n<p>I just spent about half an hour looking for the little arrow, until I actually looked up what the 'PHP Explorer' view is. Here is a screenshot:</p>\n\n<p><img src=\"https://i.stack.imgur.com/NWo2x.jpg\" alt=\"PHP perspective edit image\"></p>\n"
},
{
"answer_id": 1814429,
"author": "lo_fye",
"author_id": 3407,
"author_profile": "https://Stackoverflow.com/users/3407",
"pm_score": 3,
"selected": false,
"text": "<p>In my case, I wanted to see .htaccess files, but not all the other .* resources.<br>\nIn Zend Studio for Eclipse, in PHP Explorer (not Remote System Explorer), click the downward facing arrow (next to the left/right arrows).<br>\nChoose Filters.<br>\nUncheck .* resources<br>\nIn the \"Name filter patterns\" area, type the filenames you want to ignore.<br>\nI used: \n.svn, .cvs, .DS_Store, .buildpath, .project</p>\n"
},
{
"answer_id": 6475156,
"author": "tmsimont",
"author_id": 512685,
"author_profile": "https://Stackoverflow.com/users/512685",
"pm_score": 4,
"selected": false,
"text": "<p>I'm using 64 bit Eclipse for PHP Devleopers\nVersion: Helios Service Release 2</p>\n\n<p>It cam with RSE..</p>\n\n<p>None of the above solutions worked for me... What I did was similar to scubabble's answer, but after clicking the down arrow (view menu) in the top of the RSE package explorer I had to mouseover \"Preferences\" and click on \"Remote Systems\"</p>\n\n<p>I then opened the \"Remote Systems\" nav tree in the left of the preferences window that came u and went to \"Files\"</p>\n\n<p>Underneath a list of File types is a checkbox that was unchecked: \"Show hidden files\"</p>\n\n<p>CHECK IT!</p>\n"
},
{
"answer_id": 10298789,
"author": "bezz",
"author_id": 587052,
"author_profile": "https://Stackoverflow.com/users/587052",
"pm_score": 3,
"selected": false,
"text": "<p>On Mac:\nEclipse -> Preferences -> Remote Systems -> Files -> click Show Hidden Files.</p>\n"
},
{
"answer_id": 14483467,
"author": "sergionni",
"author_id": 170830,
"author_profile": "https://Stackoverflow.com/users/170830",
"pm_score": 5,
"selected": false,
"text": "<p>For <strong>Project Explorer View</strong>:<br>\n<strong>1.</strong> Click on arrow(<strong><em>View Menu</em></strong>) in right corner<br>\n<strong>2.</strong> Select <strong><em>Customize View...</em></strong> item from menu<br>\n<strong>3.</strong> Uncheck *.<em>resources</em> checkbox under <strong><em>Filters</em></strong> tab<br>\n<strong>4.</strong> Click <strong><em>OK</em></strong></p>\n\n<p>--<br>\nEclipse Juno</p>\n"
},
{
"answer_id": 24488793,
"author": "Bao Le",
"author_id": 301132,
"author_profile": "https://Stackoverflow.com/users/301132",
"pm_score": 2,
"selected": false,
"text": "<p>Eclipse shows hidden files in the \"Navigator\" view. You can add that via Window->Show View->Navigator.</p>\n"
},
{
"answer_id": 26042251,
"author": "kakhkAtion",
"author_id": 3434053,
"author_profile": "https://Stackoverflow.com/users/3434053",
"pm_score": 2,
"selected": false,
"text": "<p><code>Preferences -> Remote Systems -> Files -> Show hidden files</code></p>\n\n<p>(make sure this is checked)</p>\n"
},
{
"answer_id": 51046273,
"author": "Saikat",
"author_id": 1594823,
"author_profile": "https://Stackoverflow.com/users/1594823",
"pm_score": 4,
"selected": false,
"text": "<p><strong>1. From <code>Package Explorer</code> open the <code>Filters...</code> dialog:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/Nxl2M.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Nxl2M.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>2. Then uncheck <code>.* resources</code> option:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/D4tSB.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/D4tSB.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 66291347,
"author": "shanwu",
"author_id": 1145976,
"author_profile": "https://Stackoverflow.com/users/1145976",
"pm_score": 3,
"selected": false,
"text": "<p>Spring Tool Suite 4</p>\n<p>Version: 4.9.0.RELEASE\nBuild Id: 202012132054</p>\n<p>For Mac:</p>\n<p><a href=\"https://i.stack.imgur.com/AVDQ5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/AVDQ5.png\" alt=\"enter image description here\" /></a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
]
| By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences. | In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters

From there, uncheck .\* resources.
So `Package Explorer -> View Menu -> Filters -> uncheck .* resources`.
With Eclipse Kepler and OS X this is a bit different:
```
Package Explorer -> Customize View -> Filters -> uncheck .* resources
``` |
98,622 | <p>In VisualStudio (Pro 2008), I have just noticed some inconsistent behaviour and wondered if there was any logical reasoning behind it</p>
<p>In a WinForms project, if I use the line</p>
<pre><code>if(myComboBox.Items[i] == myObject)
</code></pre>
<p>I get a compiler warning that I might get 'Possible unintended references' as I am comparing type object to type MyObject. Fair enough.</p>
<p>However, if I instead use an interface to compare against:</p>
<pre><code>if(myComboBox.Items[i] == iMyInterface)
</code></pre>
<p>the compile warning goes away.</p>
<p>Can anyone think if there is any logical reason why this should happen, or just an artifact of the compiler not to check interfaces for comparison warnings. Any thoughts?</p>
<p><strong>EDIT</strong> In my example, the combobox was bound to a List, but that list was generated using <code>list<IMyInterface>.Cast<MyObject>().ToList<MyObject>()</code></p>
<p>Its as if the compiler is only taking still assuming I am binding to the List of IMyInterface.</p>
<p>(Object and Interface methods have been changed to protect the innocent)</p>
| [
{
"answer_id": 98708,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 0,
"selected": false,
"text": "<p>Lagerdalek,</p>\n\n<p>The warning is generated because you need to cast the item from the Items collection back into the orginal type that was bound to the combo box, before comparing; otherwise you may get unexpected results as the compiler warns.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>myComboBox.DataSource = Collection<Car>;\n</code></pre>\n\n<p>So if the combo box is bound to a collection of <strong>car</strong> objects you would cast them back before comparison:</p>\n\n<pre><code>if((car)myComboBox.Items[i] == thisCar)\n</code></pre>\n\n<p>Then you shouldn't get any warnings.</p>\n\n<p>Another method you could do is:</p>\n\n<pre><code>using(myComboBox.Items[i] as car){\n if(myComboBox.Items[i] == thisCar)\n}\n</code></pre>\n\n<p>Let me know. Good Luck! I'm going from memory, I hope I didn't mistype anything. :o)</p>\n"
},
{
"answer_id": 171045,
"author": "Danny Tuppeny",
"author_id": 25124,
"author_profile": "https://Stackoverflow.com/users/25124",
"pm_score": 2,
"selected": true,
"text": "<p>The compile warning for the first sample is because any custom == operator for your class would be ignored and the references compared (maybe not what you intended, hence the warning).</p>\n\n<p>It's not possible to specify that an operator should be overridden on an interface, so this will <em>always</em> be a reference comparison. The warning is not needed because you should always expect this.</p>\n\n<p>Here's an example of overriding the == operator:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n object t1 = new MyTest() { Key = 1 };\n MyTest t2 = new MyTest() { Key = 1 };\n\n Console.WriteLine((MyTest)t1 == t2); // Uses overriden == operator, returns true\n Console.WriteLine(t1 == t2); // Reference comparison, returns false\n }\n}\n\npublic class MyTest\n{\n public int Key { get; set; }\n\n public override bool Equals(object obj)\n {\n return this.Key == (obj as MyTest).Key;\n }\n\n public override int GetHashCode()\n {\n return this.Key.GetHashCode();\n }\n\n public static bool operator ==(MyTest t1, MyTest t2)\n {\n return t1.Equals(t2);\n }\n\n public static bool operator !=(MyTest t1, MyTest t2)\n {\n return !t1.Equals(t2);\n }\n\n}\n</code></pre>\n\n<p>The MyTest class is considered equal if the Key property is equal. If you were to create an interface, you cannot specify that it should include a custom == operator and therefore the comparison would always be a reference comparison (and therefore false in the case of our sample code).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
| In VisualStudio (Pro 2008), I have just noticed some inconsistent behaviour and wondered if there was any logical reasoning behind it
In a WinForms project, if I use the line
```
if(myComboBox.Items[i] == myObject)
```
I get a compiler warning that I might get 'Possible unintended references' as I am comparing type object to type MyObject. Fair enough.
However, if I instead use an interface to compare against:
```
if(myComboBox.Items[i] == iMyInterface)
```
the compile warning goes away.
Can anyone think if there is any logical reason why this should happen, or just an artifact of the compiler not to check interfaces for comparison warnings. Any thoughts?
**EDIT** In my example, the combobox was bound to a List, but that list was generated using `list<IMyInterface>.Cast<MyObject>().ToList<MyObject>()`
Its as if the compiler is only taking still assuming I am binding to the List of IMyInterface.
(Object and Interface methods have been changed to protect the innocent) | The compile warning for the first sample is because any custom == operator for your class would be ignored and the references compared (maybe not what you intended, hence the warning).
It's not possible to specify that an operator should be overridden on an interface, so this will *always* be a reference comparison. The warning is not needed because you should always expect this.
Here's an example of overriding the == operator:
```
class Program
{
static void Main(string[] args)
{
object t1 = new MyTest() { Key = 1 };
MyTest t2 = new MyTest() { Key = 1 };
Console.WriteLine((MyTest)t1 == t2); // Uses overriden == operator, returns true
Console.WriteLine(t1 == t2); // Reference comparison, returns false
}
}
public class MyTest
{
public int Key { get; set; }
public override bool Equals(object obj)
{
return this.Key == (obj as MyTest).Key;
}
public override int GetHashCode()
{
return this.Key.GetHashCode();
}
public static bool operator ==(MyTest t1, MyTest t2)
{
return t1.Equals(t2);
}
public static bool operator !=(MyTest t1, MyTest t2)
{
return !t1.Equals(t2);
}
}
```
The MyTest class is considered equal if the Key property is equal. If you were to create an interface, you cannot specify that it should include a custom == operator and therefore the comparison would always be a reference comparison (and therefore false in the case of our sample code). |
98,650 | <p>When asking about <a href="https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into">common undefined behavior in C</a>, people sometimes refer to the strict aliasing rule.<br>
What are they talking about?</p>
| [
{
"answer_id": 98666,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 4,
"selected": false,
"text": "<p>Strict aliasing is not allowing different pointer types to the same data.</p>\n\n<p><a href=\"http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html\" rel=\"noreferrer\">This article</a> should help you understand the issue in full detail.</p>\n"
},
{
"answer_id": 98700,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Type_punning\" rel=\"noreferrer\">Type punning</a> via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.</p>\n"
},
{
"answer_id": 98702,
"author": "Niall",
"author_id": 6049,
"author_profile": "https://Stackoverflow.com/users/6049",
"pm_score": 8,
"selected": false,
"text": "<p>The best explanation I have found is by Mike Acton, <a href=\"http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html\" rel=\"noreferrer\">Understanding Strict Aliasing</a>. It's focused a little on PS3 development, but that's basically just GCC.</p>\n\n<p>From the article:</p>\n\n<blockquote>\n <p>\"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)\"</p>\n</blockquote>\n\n<p>So basically if you have an <code>int*</code> pointing to some memory containing an <code>int</code> and then you point a <code>float*</code> to that memory and use it as a <code>float</code> you break the rule. If your code does not respect this, then the compiler's optimizer will most likely break your code.</p>\n\n<p>The exception to the rule is a <code>char*</code>, which is allowed to point to any type.</p>\n"
},
{
"answer_id": 99010,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 10,
"selected": true,
"text": "<p>A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to <code>uint32_t</code>s or <code>uint16_t</code>s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.</p>\n<p>So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:</p>\n<pre><code>typedef struct Msg\n{\n unsigned int a;\n unsigned int b;\n} Msg;\n\nvoid SendWord(uint32_t);\n\nint main(void)\n{\n // Get a 32-bit buffer from the system\n uint32_t* buff = malloc(sizeof(Msg));\n \n // Alias that buffer through message\n Msg* msg = (Msg*)(buff);\n \n // Send a bunch of messages \n for (int i = 0; i < 10; ++i)\n {\n msg->a = i;\n msg->b = i+1;\n SendWord(buff[0]);\n SendWord(buff[1]); \n }\n}\n</code></pre>\n<p>The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a <a href=\"http://en.cppreference.com/w/c/language/type\" rel=\"noreferrer\">compatible type</a> or one of the other types allowed by C 2011 6.5 paragraph 7<sup>1</sup> is undefined behavior. Unfortunately, you can still code this way, <em>maybe</em> get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.</p>\n<p>(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)</p>\n<p>To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of <code>buff</code> every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load <code>buff[0]</code> and <code>buff[1]</code> into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of <code>buff</code> could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.</p>\n<p>Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.</p>\n<pre><code>void SendMessage(uint32_t* buff, size_t size32)\n{\n for (int i = 0; i < size32; ++i) \n {\n SendWord(buff[i]);\n }\n}\n</code></pre>\n<p>And rewrote our earlier loop to take advantage of this convenient function</p>\n<pre><code>for (int i = 0; i < 10; ++i)\n{\n msg->a = i;\n msg->b = i+1;\n SendMessage(buff, 2);\n}\n</code></pre>\n<p>The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If <code>SendMessage</code> is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.</p>\n<p><strong>So how do I get around this?</strong></p>\n<ul>\n<li><p>Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.</p>\n<pre><code> union {\n Msg msg;\n unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];\n };\n</code></pre>\n</li>\n<li><p>You can disable strict aliasing in your compiler (<a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825\" rel=\"noreferrer\">f[no-]strict-aliasing</a> in gcc))</p>\n</li>\n<li><p>You can use <code>char*</code> for aliasing instead of your system's word. The rules allow an exception for <code>char*</code> (including <code>signed char</code> and <code>unsigned char</code>). It's always assumed that <code>char*</code> aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.</p>\n</li>\n</ul>\n<p><strong>Beginner beware</strong></p>\n<p>This is only one potential minefield when overlaying two types onto each other. You should also learn about <a href=\"http://en.wikipedia.org/wiki/Endianness\" rel=\"noreferrer\">endianness</a>, <a href=\"http://web.archive.org/web/20170708093042/http://www.cs.umd.edu:80/class/sum2003/cmsc311/Notes/Data/aligned.html\" rel=\"noreferrer\">word alignment</a>, and how to deal with alignment issues through <a href=\"http://grok2.com/structure_packing.html\" rel=\"noreferrer\">packing structs</a> correctly.</p>\n<h2>Footnote</h2>\n<p><sup>1</sup> The types that C 2011 6.5 7 allows an lvalue to access are:</p>\n<ul>\n<li>a type compatible with the effective type of the object,</li>\n<li>a qualified version of a type compatible with the effective type of the object,</li>\n<li>a type that is the signed or unsigned type corresponding to the effective type of the object,</li>\n<li>a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,</li>\n<li>an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or</li>\n<li>a character type.</li>\n</ul>\n"
},
{
"answer_id": 6405776,
"author": "phorgan1",
"author_id": 805830,
"author_profile": "https://Stackoverflow.com/users/805830",
"pm_score": 6,
"selected": false,
"text": "<p>Strict aliasing doesn't refer only to pointers, it affects references as well, I wrote a paper about it for the boost developer wiki and it was so well received that I turned it into a page on my consulting web site. It explains completely what it is, why it confuses people so much and what to do about it. <a href=\"http://dbp-consulting.com/tutorials/StrictAliasing.html\">Strict Aliasing White Paper</a>. In particular it explains why unions are risky behavior for C++, and why using memcpy is the only fix portable across both C and C++. Hope this is helpful.</p>\n"
},
{
"answer_id": 7005988,
"author": "Ben Voigt",
"author_id": 103167,
"author_profile": "https://Stackoverflow.com/users/103167",
"pm_score": 7,
"selected": false,
"text": "<p>This is the strict aliasing rule, found in section 3.10 of the <strong>C++03</strong> standard (other answers provide good explanation, but none provided the rule itself):</p>\n<blockquote>\n<p>If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:</p>\n<ul>\n<li>the dynamic type of the object,</li>\n<li>a cv-qualified version of the dynamic type of the object,</li>\n<li>a type that is the signed or unsigned type corresponding to the dynamic type of the object,</li>\n<li>a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,</li>\n<li>an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union),</li>\n<li>a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,</li>\n<li>a <code>char</code> or <code>unsigned char</code> type.</li>\n</ul>\n</blockquote>\n<p><strong>C++11</strong> and <strong>C++14</strong> wording (changes emphasized):</p>\n<blockquote>\n<p>If a program attempts to access the stored value of an object through a <em>glvalue</em> of other than one of the following types the behavior is undefined:</p>\n<ul>\n<li>the dynamic type of the object,</li>\n<li>a cv-qualified version of the dynamic type of the object,</li>\n<li><em>a type similar (as defined in 4.4) to the dynamic type of the object,</em></li>\n<li>a type that is the signed or unsigned type corresponding to the dynamic type of the object,</li>\n<li>a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,</li>\n<li>an aggregate or union type that includes one of the aforementioned types among its <em>elements or non-static data members</em> (including, recursively, an <em>element or non-static data member</em> of a subaggregate or contained union),</li>\n<li>a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,</li>\n<li>a <code>char</code> or <code>unsigned char</code> type.</li>\n</ul>\n</blockquote>\n<p>Two changes were small: <em>glvalue</em> instead of <em>lvalue</em>, and clarification of the aggregate/union case.</p>\n<p>The third change makes a stronger guarantee (relaxes the strong aliasing rule): The new concept of <em>similar types</em> that are now safe to alias.</p>\n<hr />\n<p>Also the <strong>C</strong> wording (C99; ISO/IEC 9899:1999 6.5/7; the exact same wording is used in ISO/IEC 9899:2011 §6.5 ¶7):</p>\n<blockquote>\n<p>An object shall have its stored value accessed only by an lvalue\nexpression that has one of the following types <sup> 73) or 88)</sup>:</p>\n<ul>\n<li>a type compatible with the effective type of the object,</li>\n<li>a qualified version of a type compatible with the effective type of\nthe object,</li>\n<li>a type that is the signed or unsigned type corresponding to the\neffective type of the object,</li>\n<li>a type that is the signed or unsigned type corresponding to a\nqualified version of the effective type of the object,</li>\n<li>an aggregate or union type that includes one of the aforementioned\ntypes among its members (including, recursively, a member of a\nsubaggregate or contained union), or</li>\n<li>a character type.</li>\n</ul>\n<p><sup> 73) or 88)</sup> The intent of this list is to specify those circumstances in which an object may or may not be aliased.</p>\n</blockquote>\n"
},
{
"answer_id": 16534243,
"author": "Ingo Blackman",
"author_id": 1917520,
"author_profile": "https://Stackoverflow.com/users/1917520",
"pm_score": 5,
"selected": false,
"text": "<p>As addendum to what Doug T. already wrote, here\nis a simple test case which probably triggers it with gcc :</p>\n\n<p>check.c</p>\n\n<pre><code>#include <stdio.h>\n\nvoid check(short *h,long *k)\n{\n *h=5;\n *k=6;\n if (*h == 5)\n printf(\"strict aliasing problem\\n\");\n}\n\nint main(void)\n{\n long k[1];\n check((short *)k,k);\n return 0;\n}\n</code></pre>\n\n<p>Compile with <code>gcc -O2 -o check check.c</code> .\nUsually (with most gcc versions I tried) this outputs \"strict aliasing problem\", because the compiler assumes that \"h\" cannot be the same address as \"k\" in the \"check\" function. Because of that the compiler optimizes the <code>if (*h == 5)</code> away and always calls the printf.</p>\n\n<p>For those who are interested here is the x64 assembler code, produced by gcc 4.6.3, running on ubuntu 12.04.2 for x64:</p>\n\n<pre><code>movw $5, (%rdi)\nmovq $6, (%rsi)\nmovl $.LC0, %edi\njmp puts\n</code></pre>\n\n<p>So the if condition is completely gone from the assembler code.</p>\n"
},
{
"answer_id": 43645721,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 5,
"selected": false,
"text": "<p>According to the C89 rationale, the authors of the Standard did not want to require that compilers given code like:</p>\n\n<pre><code>int x;\nint test(double *p)\n{\n x=5;\n *p = 1.0;\n return x;\n}\n</code></pre>\n\n<p>should be required to reload the value of <code>x</code> between the assignment and return statement so as to allow for the possibility that <code>p</code> might point to <code>x</code>, and the assignment to <code>*p</code> might consequently alter the value of <code>x</code>. The notion that a compiler should be entitled to presume that there won't be aliasing <em>in situations like the above</em> was non-controversial.</p>\n\n<p>Unfortunately, the authors of the C89 wrote their rule in a way that, if read literally, would make even the following function invoke Undefined Behavior:</p>\n\n<pre><code>void test(void)\n{\n struct S {int x;} s;\n s.x = 1;\n}\n</code></pre>\n\n<p>because it uses an lvalue of type <code>int</code> to access an object of type <code>struct S</code>, and <code>int</code> is not among the types that may be used accessing a <code>struct S</code>. Because it would be absurd to treat all use of non-character-type members of structs and unions as Undefined Behavior, almost everyone recognizes that there are at least some circumstances where an lvalue of one type may be used to access an object of another type. Unfortunately, the C Standards Committee has failed to define what those circumstances are.</p>\n\n<p>Much of the problem is a result of Defect Report #028, which asked about the behavior of a program like:</p>\n\n<pre><code>int test(int *ip, double *dp)\n{\n *ip = 1;\n *dp = 1.23;\n return *ip;\n}\nint test2(void)\n{\n union U { int i; double d; } u;\n return test(&u.i, &u.d);\n}\n</code></pre>\n\n<p>Defect Report #28 states that the program invokes Undefined Behavior because the action of writing a union member of type \"double\" and reading one of type \"int\" invokes Implementation-Defined behavior. Such reasoning is nonsensical, but forms the basis for the Effective Type rules which needlessly complicate the language while doing nothing to address the original problem.</p>\n\n<p>The best way to resolve the original problem would probably be to treat the\nfootnote about the purpose of the rule as though it were normative, and made\nthe rule unenforceable except in cases which actually involve conflicting accesses using aliases. Given something like:</p>\n\n<pre><code> void inc_int(int *p) { *p = 3; }\n int test(void)\n {\n int *p;\n struct S { int x; } s;\n s.x = 1;\n p = &s.x;\n inc_int(p);\n return s.x;\n }\n</code></pre>\n\n<p>There's no conflict within <code>inc_int</code> because all accesses to the storage accessed through <code>*p</code> are done with an lvalue of type <code>int</code>, and there's no conflict in <code>test</code> because <code>p</code> is visibly derived from a <code>struct S</code>, and by the next time <code>s</code> is used, all accesses to that storage that will ever be made through <code>p</code> will have already happened.</p>\n\n<p>If the code were changed slightly...</p>\n\n<pre><code> void inc_int(int *p) { *p = 3; }\n int test(void)\n {\n int *p;\n struct S { int x; } s;\n p = &s.x;\n s.x = 1; // !!*!!\n *p += 1;\n return s.x;\n }\n</code></pre>\n\n<p>Here, there is an aliasing conflict between <code>p</code> and the access to <code>s.x</code> on the marked line because at that point in execution another reference exists <em>that will be used to access the same storage</em>.</p>\n\n<p>Had Defect Report 028 said the original example invoked UB because of the overlap between the creation and use of the two pointers, that would have made things a lot more clear without having to add \"Effective Types\" or other such complexity.</p>\n"
},
{
"answer_id": 47960435,
"author": "Myst",
"author_id": 4025095,
"author_profile": "https://Stackoverflow.com/users/4025095",
"pm_score": 4,
"selected": false,
"text": "<p>After reading many of the answers, I feel the need to add something:</p>\n\n<p>Strict aliasing (which I'll describe in a bit) <strong>is important because</strong>:</p>\n\n<ol>\n<li><p>Memory access can be expensive (performance wise), which is why <strong>data is manipulated in CPU registers</strong> before being written back to the physical memory.</p></li>\n<li><p>If data in two different CPU registers will be written to the same memory space, <strong>we can't predict which data will \"survive\"</strong> when we code in C.</p>\n\n<p>In assembly, where we code the loading and unloading of CPU registers manually, we will know which data remains intact. But C (thankfully) abstracts this detail away.</p></li>\n</ol>\n\n<p>Since two pointers can point to the same location in the memory, this could result in <strong>complex code that handles possible collisions</strong>.</p>\n\n<p>This extra code is slow and <strong>hurts performance</strong> since it performs extra memory read / write operations which are both slower and (possibly) unnecessary.</p>\n\n<p>The <strong>Strict aliasing rule allows us to avoid redundant machine code</strong> in cases in which it <em>should be</em> safe to assume that two pointers don't point to the same memory block (see also the <code>restrict</code> keyword).</p>\n\n<p>The Strict aliasing states it's safe to assume that pointers to different types point to different locations in the memory.</p>\n\n<p>If a compiler notices that two pointers point to different types (for example, an <code>int *</code> and a <code>float *</code>), it will assume the memory address is different and it <strong>will not</strong> protect against memory address collisions, resulting in faster machine code.</p>\n\n<p><strong>For example</strong>:</p>\n\n<p>Lets assume the following function:</p>\n\n<pre><code>void merge_two_ints(int *a, int *b) {\n *b += *a;\n *a += *b;\n}\n</code></pre>\n\n<p>In order to handle the case in which <code>a == b</code> (both pointers point to the same memory), we need to order and test the way we load data from the memory to the CPU registers, so the code might end up like this:</p>\n\n<ol>\n<li><p>load <code>a</code> and <code>b</code> from memory.</p></li>\n<li><p>add <code>a</code> to <code>b</code>.</p></li>\n<li><p><strong>save</strong> <code>b</code> and <strong>reload</strong> <code>a</code>.</p>\n\n<p>(save from CPU register to the memory and load from the memory to the CPU register). </p></li>\n<li><p>add <code>b</code> to <code>a</code>.</p></li>\n<li><p>save <code>a</code> (from the CPU register) to the memory.</p></li>\n</ol>\n\n<p>Step 3 is very slow because it needs to access the physical memory. However, it's required to protect against instances where <code>a</code> and <code>b</code> point to the same memory address.</p>\n\n<p>Strict aliasing would allow us to prevent this by telling the compiler that these memory addresses are distinctly different (which, in this case, will allow even further optimization which can't be performed if the pointers share a memory address).</p>\n\n<ol>\n<li><p>This can be told to the compiler in two ways, by using different types to point to. i.e.:</p>\n\n<pre><code>void merge_two_numbers(int *a, long *b) {...}\n</code></pre></li>\n<li><p>Using the <code>restrict</code> keyword. i.e.:</p>\n\n<pre><code>void merge_two_ints(int * restrict a, int * restrict b) {...}\n</code></pre></li>\n</ol>\n\n<p>Now, by satisfying the Strict Aliasing rule, step 3 can be avoided and the code will run significantly faster.</p>\n\n<p>In fact, by adding the <code>restrict</code> keyword, the whole function could be optimized to:</p>\n\n<ol>\n<li><p>load <code>a</code> and <code>b</code> from memory.</p></li>\n<li><p>add <code>a</code> to <code>b</code>.</p></li>\n<li><p>save result both to <code>a</code> and to <code>b</code>.</p></li>\n</ol>\n\n<p>This optimization couldn't have been done before, because of the possible collision (where <code>a</code> and <code>b</code> would be tripled instead of doubled).</p>\n"
},
{
"answer_id": 51228315,
"author": "Shafik Yaghmour",
"author_id": 1708801,
"author_profile": "https://Stackoverflow.com/users/1708801",
"pm_score": 7,
"selected": false,
"text": "<h2>Note</h2>\n<p>This is excerpted from my <a href=\"https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8\" rel=\"noreferrer\">"What is the Strict Aliasing Rule and Why do we care?"</a> write-up.</p>\n<h2>What is strict aliasing?</h2>\n<p>In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term <em>strict aliasing rule</em>. If we attempt to access a value using a type not allowed it is classified as <a href=\"http://en.cppreference.com/w/cpp/language/ub\" rel=\"noreferrer\">undefined behavior</a> (<strong>UB</strong>). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.</p>\n<p>Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we thought was valid. This is undesirable and it is a worthwhile goal to understand the strict aliasing rules and how to avoid violating them.</p>\n<p>To understand more about why we care, we will discuss issues that come up when violating strict aliasing rules, type punning since common techniques used in type punning often violate strict aliasing rules and how to type pun correctly.</p>\n<h3>Preliminary examples</h3>\n<p>Let's look at some examples, then we can talk about exactly what the standard(s) say, examine some further examples and then see how to avoid strict aliasing and catch violations we missed. Here is an example that should not be surprising (<a href=\"https://wandbox.org/permlink/7sCJTAyrifZ0zfFA\" rel=\"noreferrer\">live example</a>):</p>\n<pre><code>int x = 10;\nint *ip = &x;\n\nstd::cout << *ip << "\\n";\n*ip = 12;\nstd::cout << x << "\\n";\n</code></pre>\n<p>We have a <em>int*</em> pointing to memory occupied by an <em>int</em> and this is a valid aliasing. The optimizer must assume that assignments through <strong>ip</strong> could update the value occupied by <strong>x</strong>.</p>\n<p>The next example shows aliasing that leads to undefined behavior (<a href=\"https://wandbox.org/permlink/8qA8JyJRVHtS9LPf\" rel=\"noreferrer\">live example</a>):</p>\n<pre><code>int foo( float *f, int *i ) { \n *i = 1;\n *f = 0.f;\n \n return *i;\n}\n\nint main() {\n int x = 0;\n \n std::cout << x << "\\n"; // Expect 0\n x = foo(reinterpret_cast<float*>(&x), &x);\n std::cout << x << "\\n"; // Expect 0?\n}\n</code></pre>\n<p>In the function <strong>foo</strong> we take an <em>int*</em> and a <em>float*</em>, in this example we call <strong>foo</strong> and set both parameters to point to the same memory location which in this example contains an <em>int</em>. Note, the <a href=\"http://en.cppreference.com/w/cpp/language/reinterpret_cast\" rel=\"noreferrer\">reinterpret_cast</a> is telling the compiler to treat the expression as if it had the type specified by its template parameter. In this case we are telling it to treat the expression <strong>&x</strong> as if it had type <em>float*</em>. We may naively expect the result of the second <strong>cout</strong> to be <strong>0</strong> but with optimization enabled using <strong>-O2</strong> both gcc and clang produce the following result:</p>\n<pre><code>0\n1\n</code></pre>\n<p>Which may not be expected but is perfectly valid since we have invoked undefined behavior. A <em>float</em> can not validly alias an <em>int</em> object. Therefore the optimizer can assume the <em>constant 1</em> stored when dereferencing <strong>i</strong> will be the return value since a store through <strong>f</strong> could not validly affect an <em>int</em> object. Plugging the code in Compiler Explorer shows this is exactly what is happening(<a href=\"https://godbolt.org/g/yNV5aj\" rel=\"noreferrer\">live example</a>):</p>\n<pre><code>foo(float*, int*): # @foo(float*, int*)\nmov dword ptr [rsi], 1\nmov dword ptr [rdi], 0\nmov eax, 1\nret\n</code></pre>\n<p>The optimizer using <a href=\"http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/DDJ/2000/0010/0010d/0010d.htm\" rel=\"noreferrer\">Type-Based Alias Analysis (TBAA)</a> assumes <strong>1</strong> will be returned and directly moves the constant value into register <strong>eax</strong> which carries the return value. TBAA uses the languages rules about what types are allowed to alias to optimize loads and stores. In this case TBAA knows that a <em>float</em> can not alias an <em>int</em> and optimizes away the load of <strong>i</strong>.</p>\n<h2>Now, to the Rule-Book</h2>\n<p>What exactly does the standard say we are allowed and not allowed to do? The standard language is not straightforward, so for each item I will try to provide code examples that demonstrates the meaning.</p>\n<h3>What does the C11 standard say?</h3>\n<p>The <strong>C11</strong> standard says the following in section <em>6.5 Expressions paragraph 7</em>:</p>\n<blockquote>\n<p>An object shall have its stored value accessed only by an lvalue expression that has one of the following types:<sup>88)</sup>\n— a type compatible with the effective type of the object,</p>\n</blockquote>\n<pre><code>int x = 1;\nint *p = &x;\nprintf("%d\\n", *p); // *p gives us an lvalue expression of type int which is compatible with int\n</code></pre>\n<blockquote>\n<p>— a qualified version of a type compatible with the effective type of the object,</p>\n</blockquote>\n<pre><code>int x = 1;\nconst int *p = &x;\nprintf("%d\\n", *p); // *p gives us an lvalue expression of type const int which is compatible with int\n</code></pre>\n<blockquote>\n<p>— a type that is the signed or unsigned type corresponding to the effective type of the object,</p>\n</blockquote>\n<pre><code>int x = 1;\nunsigned int *p = (unsigned int*)&x;\nprintf("%u\\n", *p ); // *p gives us an lvalue expression of type unsigned int which corresponds to \n // the effective type of the object\n</code></pre>\n<p><a href=\"https://twitter.com/shafikyaghmour/status/957702383810658304\" rel=\"noreferrer\">gcc/clang has an extension</a> and <a href=\"https://gcc.gnu.org/ml/gcc/2003-10/msg00184.html\" rel=\"noreferrer\">also</a> that allows assigning <em>unsigned int*</em> to <em>int*</em> even though they are not compatible types.</p>\n<blockquote>\n<p>— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,</p>\n</blockquote>\n<pre><code>int x = 1;\nconst unsigned int *p = (const unsigned int*)&x;\nprintf("%u\\n", *p ); // *p gives us an lvalue expression of type const unsigned int which is a unsigned type \n // that corresponds with to a qualified version of the effective type of the object\n</code></pre>\n<blockquote>\n<p>— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or</p>\n</blockquote>\n<pre><code>struct foo {\n int x;\n};\n \nvoid foobar( struct foo *fp, int *ip ); // struct foo is an aggregate that includes int among its members so it\n // can alias with *ip\n\nfoo f;\nfoobar( &f, &f.x );\n</code></pre>\n<blockquote>\n<p>— a character type.</p>\n</blockquote>\n<pre><code>int x = 65;\nchar *p = (char *)&x;\nprintf("%c\\n", *p ); // *p gives us an lvalue expression of type char which is a character type.\n // The results are not portable due to endianness issues.\n</code></pre>\n<h3>What the C++17 Draft Standard says</h3>\n<p>The C++17 draft standard in section <em>[basic.lval] paragraph 11</em> says:</p>\n<blockquote>\n<p>If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:<sup>63</sup></p>\n</blockquote>\n<blockquote>\n<p>(11.1) — the dynamic type of the object,</p>\n</blockquote>\n<pre><code>void *p = malloc( sizeof(int) ); // We have allocated storage but not started the lifetime of an object\nint *ip = new (p) int{0}; // Placement new changes the dynamic type of the object to int\nstd::cout << *ip << "\\n"; // *ip gives us a glvalue expression of type int which matches the dynamic type \n // of the allocated object\n</code></pre>\n<blockquote>\n<p>(11.2) — a cv-qualified version of the dynamic type of the object,</p>\n</blockquote>\n<pre><code>int x = 1;\nconst int *cip = &x;\nstd::cout << *cip << "\\n"; // *cip gives us a glvalue expression of type const int which is a cv-qualified \n // version of the dynamic type of x\n</code></pre>\n<blockquote>\n<p>(11.3) — a type similar (as defined in 7.5) to the dynamic type of the object,</p>\n</blockquote>\n<blockquote>\n<p>(11.4) — a type that is the signed or unsigned type corresponding to the dynamic type of the object,</p>\n</blockquote>\n<pre><code>// Both si and ui are signed or unsigned types corresponding to each others dynamic types\n// We can see from this godbolt(https://godbolt.org/g/KowGXB) the optimizer assumes aliasing.\nsigned int foo( signed int &si, unsigned int &ui ) {\n si = 1;\n ui = 2;\n\n return si;\n}\n</code></pre>\n<blockquote>\n<p>(11.5) — a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,</p>\n</blockquote>\n<pre><code>signed int foo( const signed int &si1, int &si2); // Hard to show this one assumes aliasing\n</code></pre>\n<blockquote>\n<p>(11.6) — an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),</p>\n</blockquote>\n<pre><code>struct foo {\n int x;\n};\n\n// Compiler Explorer example(https://godbolt.org/g/z2wJTC) shows aliasing assumption\nint foobar( foo &fp, int &ip ) {\n fp.x = 1;\n ip = 2;\n\n return fp.x;\n}\n\nfoo f;\nfoobar( f, f.x );\n</code></pre>\n<blockquote>\n<p>(11.7) — a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,</p>\n</blockquote>\n<pre><code>struct foo { int x; };\n\nstruct bar : public foo {};\n\nint foobar( foo &f, bar &b ) {\n f.x = 1;\n b.x = 2;\n\n return f.x;\n}\n</code></pre>\n<blockquote>\n<p>(11.8) — a char, unsigned char, or std::byte type.</p>\n</blockquote>\n<pre><code>int foo( std::byte &b, uint32_t &ui ) {\n b = static_cast<std::byte>('a');\n ui = 0xFFFFFFFF;\n \n return std::to_integer<int>( b ); // b gives us a glvalue expression of type std::byte which can alias\n // an object of type uint32_t\n}\n</code></pre>\n<p>Worth noting <em>signed char</em> is not included in the list above, this is a notable difference from <em>C</em> which says <em>a character type</em>.</p>\n<h2>What is Type Punning</h2>\n<p>We have gotten to this point and we may be wondering, why would we want to alias for? The answer typically is to <em>type pun</em>, often the methods used violate strict aliasing rules.</p>\n<p>Sometimes we want to circumvent the type system and interpret an object as a different type. This is called <em>type punning</em>, to reinterpret a segment of memory as another type. <em>Type punning</em> is useful for tasks that want access to the underlying representation of an object to view, transport or manipulate. Typical areas we find type punning being used are compilers, serialization, networking code, etc…</p>\n<p>Traditionally this has been accomplished by taking the address of the object, casting it to a pointer of the type we want to reinterpret it as and then accessing the value, or in other words by aliasing. For example:</p>\n<pre><code>int x = 1;\n\n// In C\nfloat *fp = (float*)&x; // Not a valid aliasing\n\n// In C++\nfloat *fp = reinterpret_cast<float*>(&x); // Not a valid aliasing\n\nprintf( "%f\\n", *fp );\n</code></pre>\n<p>As we have seen earlier this is not a valid aliasing, so we are invoking undefined behavior. But traditionally compilers did not take advantage of strict aliasing rules and this type of code usually just worked, developers have unfortunately gotten used to doing things this way. A common alternate method for type punning is through unions, which is valid in C but <em>undefined behavior</em> in C++ (<a href=\"https://wandbox.org/permlink/oOf9bPlcWDYrYqPF\" rel=\"noreferrer\">see live example</a>):</p>\n<pre><code>union u1\n{\n int n;\n float f;\n};\n\nunion u1 u;\nu.f = 1.0f;\n\nprintf( "%d\\n", u.n ); // UB in C++ n is not the active member\n</code></pre>\n<p>This is not valid in C++ and some consider the purpose of unions to be solely for implementing variant types and feel using unions for type punning is an abuse.</p>\n<h3>How do we Type Pun correctly?</h3>\n<p>The standard method for <em>type punning</em> in both C and C++ is <strong>memcpy</strong>. This may seem a little heavy handed but the optimizer should recognize the use of <strong>memcpy</strong> for <em>type punning</em> and optimize it away and generate a register to register move. For example if we know <em>int64_t</em> is the same size as <em>double</em>:</p>\n<pre><code>static_assert( sizeof( double ) == sizeof( int64_t ) ); // C++17 does not require a message\n</code></pre>\n<p>we can use <strong>memcpy</strong>:</p>\n<pre><code>void func1( double d ) {\n std::int64_t n;\n std::memcpy(&n, &d, sizeof d);\n //...\n</code></pre>\n<p>At a sufficient optimization level any decent modern compiler generates identical code to the previously mentioned <strong>reinterpret_cast</strong> method or <em>union</em> method for <em>type punning</em>. Examining the generated code we see it uses just register mov (<a href=\"https://godbolt.org/g/BfZGwX\" rel=\"noreferrer\">live Compiler Explorer Example</a>).</p>\n<h2>C++20 and bit_cast</h2>\n<p>In C++20 we may gain <strong>bit_cast</strong> (<a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0476r2.html\" rel=\"noreferrer\">implementation available in link from proposal</a>) which gives a simple and safe way to type-pun as well as being usable in a constexpr context.</p>\n<p>The following is an example of how to use <strong>bit_cast</strong> to type pun a <em>unsigned int</em> to <em>float</em>, (<a href=\"https://wandbox.org/permlink/i5l0g4IYuCFgLzzl\" rel=\"noreferrer\">see it live</a>):</p>\n<pre><code>std::cout << bit_cast<float>(0x447a0000) << "\\n"; //assuming sizeof(float) == sizeof(unsigned int)\n</code></pre>\n<p>In the case where <em>To</em> and <em>From</em> types don't have the same size, it requires us to use an intermediate struct15. We will use a struct containing a <strong>sizeof( unsigned int )</strong> character array (<em>assumes 4 byte unsigned int</em>) to be the <em>From</em> type and <em>unsigned int</em> as the <em>To</em> type.:</p>\n<pre><code>struct uint_chars {\n unsigned char arr[sizeof( unsigned int )] = {}; // Assume sizeof( unsigned int ) == 4\n};\n\n// Assume len is a multiple of 4 \nint bar( unsigned char *p, size_t len ) {\n int result = 0;\n\n for( size_t index = 0; index < len; index += sizeof(unsigned int) ) {\n uint_chars f;\n std::memcpy( f.arr, &p[index], sizeof(unsigned int));\n unsigned int result = bit_cast<unsigned int>(f);\n\n result += foo( result );\n }\n\n return result;\n}\n</code></pre>\n<p>It is unfortunate that we need this intermediate type but that is the current constraint of <strong>bit_cast</strong>.</p>\n<h2>Catching Strict Aliasing Violations</h2>\n<p>We don't have a lot of good tools for catching strict aliasing in C++, the tools we have will catch some cases of strict aliasing violations and some cases of misaligned loads and stores.</p>\n<p>gcc using the flag <strong>-fstrict-aliasing</strong> and <strong>-Wstrict-aliasing</strong> can catch some cases although not without false positives/negatives. For example the following cases will generate a warning in gcc (<a href=\"https://wandbox.org/permlink/cfckjTgwNTYHDIry\" rel=\"noreferrer\">see it live</a>):</p>\n<pre><code>int a = 1;\nshort j;\nfloat f = 1.f; // Originally not initialized but tis-kernel caught \n // it was being accessed w/ an indeterminate value below\n\nprintf("%i\\n", j = *(reinterpret_cast<short*>(&a)));\nprintf("%i\\n", j = *(reinterpret_cast<int*>(&f)));\n</code></pre>\n<p>although it will not catch this additional case (<a href=\"https://wandbox.org/permlink/dwd9jhy53AF7a2D0\" rel=\"noreferrer\">see it live</a>):</p>\n<pre><code>int *p;\n\np = &a;\nprintf("%i\\n", j = *(reinterpret_cast<short*>(p)));\n</code></pre>\n<p>Although clang allows these flags it apparently does not actually implement the warnings.</p>\n<p>Another tool we have available to us is ASan which can catch misaligned loads and stores. Although these are not directly strict aliasing violations they are a common result of strict aliasing violations. For example the following cases will generate runtime errors when built with clang using <strong>-fsanitize=address</strong></p>\n<pre><code>int *x = new int[2]; // 8 bytes: [0,7].\nint *u = (int*)((char*)x + 6); // regardless of alignment of x this will not be an aligned address\n*u = 1; // Access to range [6-9]\nprintf( "%d\\n", *u ); // Access to range [6-9]\n</code></pre>\n<p>The last tool I will recommend is C++ specific and not strictly a tool but a coding practice, don't allow C-style casts. Both gcc and clang will produce a diagnostic for C-style casts using <strong>-Wold-style-cast</strong>. This will force any undefined type puns to use reinterpret_cast, in general reinterpret_cast should be a flag for closer code review. It is also easier to search your code base for reinterpret_cast to perform an audit.</p>\n<p>For C we have all the tools already covered and we also have tis-interpreter, a static analyzer that exhaustively analyzes a program for a large subset of the C language. Given a C version of the earlier example where using <strong>-fstrict-aliasing</strong> misses one case (<a href=\"https://wandbox.org/permlink/ebLBJ17Pg7TsnIgY\" rel=\"noreferrer\">see it live</a>)</p>\n<pre><code>int a = 1;\nshort j;\nfloat f = 1.0;\n\nprintf("%i\\n", j = *((short*)&a));\nprintf("%i\\n", j = *((int*)&f));\n \nint *p;\n\np = &a;\nprintf("%i\\n", j = *((short*)p));\n</code></pre>\n<p>tis-interpeter is able to catch all three, the following example invokes tis-kernel as tis-interpreter (output is edited for brevity):</p>\n<pre><code>./bin/tis-kernel -sa example1.c \n...\nexample1.c:9:[sa] warning: The pointer (short *)(& a) has type short *. It violates strict aliasing\n rules by accessing a cell with effective type int.\n...\n\nexample1.c:10:[sa] warning: The pointer (int *)(& f) has type int *. It violates strict aliasing rules by\n accessing a cell with effective type float.\n Callstack: main\n...\n\nexample1.c:15:[sa] warning: The pointer (short *)p has type short *. It violates strict aliasing rules by\n accessing a cell with effective type int.\n</code></pre>\n<p>Finally there is <a href=\"https://www.youtube.com/watch?v=vAXJeN7k32Y\" rel=\"noreferrer\">TySan</a> which is currently in development. This sanitizer adds type checking information in a shadow memory segment and checks accesses to see if they violate aliasing rules. The tool potentially should be able to catch all aliasing violations but may have a large run-time overhead.</p>\n"
},
{
"answer_id": 51237865,
"author": "curiousguy",
"author_id": 963864,
"author_profile": "https://Stackoverflow.com/users/963864",
"pm_score": -1,
"selected": false,
"text": "<p>Technically in C++, the strict aliasing rule is probably never applicable.</p>\n\n<p>Note the definition of indirection (<a href=\"http://eel.is/c++draft/expr.unary.op#def:indirection\" rel=\"nofollow noreferrer\">* operator</a>):</p>\n\n<blockquote>\n <p>The unary * operator performs indirection: the expression to which it\n is applied shall be a pointer to an object type, or a pointer to a\n function type and <strong>the result is an lvalue referring to the object</strong> or\n function <strong>to which the expression points</strong>.</p>\n</blockquote>\n\n<p>Also from <a href=\"http://eel.is/c++draft/basic.lval#1.1\" rel=\"nofollow noreferrer\">the definition of glvalue</a></p>\n\n<blockquote>\n <p>A glvalue is an expression whose evaluation determines the identity of\n an object, (...snip)</p>\n</blockquote>\n\n<p>So in any well defined program trace, a glvalue refers to an object. <strong>So the so called strict aliasing rule doesn't apply, ever.</strong> This may not be what the designers wanted.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
| When asking about [common undefined behavior in C](https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into), people sometimes refer to the strict aliasing rule.
What are they talking about? | A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to `uint32_t`s or `uint16_t`s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.
So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:
```
typedef struct Msg
{
unsigned int a;
unsigned int b;
} Msg;
void SendWord(uint32_t);
int main(void)
{
// Get a 32-bit buffer from the system
uint32_t* buff = malloc(sizeof(Msg));
// Alias that buffer through message
Msg* msg = (Msg*)(buff);
// Send a bunch of messages
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendWord(buff[0]);
SendWord(buff[1]);
}
}
```
The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a [compatible type](http://en.cppreference.com/w/c/language/type) or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, *maybe* get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.
(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)
To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of `buff` every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load `buff[0]` and `buff[1]` into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of `buff` could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.
Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.
```
void SendMessage(uint32_t* buff, size_t size32)
{
for (int i = 0; i < size32; ++i)
{
SendWord(buff[i]);
}
}
```
And rewrote our earlier loop to take advantage of this convenient function
```
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendMessage(buff, 2);
}
```
The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If `SendMessage` is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.
**So how do I get around this?**
* Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.
```
union {
Msg msg;
unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
};
```
* You can disable strict aliasing in your compiler ([f[no-]strict-aliasing](http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825) in gcc))
* You can use `char*` for aliasing instead of your system's word. The rules allow an exception for `char*` (including `signed char` and `unsigned char`). It's always assumed that `char*` aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.
**Beginner beware**
This is only one potential minefield when overlaying two types onto each other. You should also learn about [endianness](http://en.wikipedia.org/wiki/Endianness), [word alignment](http://web.archive.org/web/20170708093042/http://www.cs.umd.edu:80/class/sum2003/cmsc311/Notes/Data/aligned.html), and how to deal with alignment issues through [packing structs](http://grok2.com/structure_packing.html) correctly.
Footnote
--------
1 The types that C 2011 6.5 7 allows an lvalue to access are:
* a type compatible with the effective type of the object,
* a qualified version of a type compatible with the effective type of the object,
* a type that is the signed or unsigned type corresponding to the effective type of the object,
* a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
* an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
* a character type. |
98,705 | <p>I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g.</p>
<pre><code>class object
{
int get_value(int n) const
{
...
}
...
object x;
int a = x.get_value(1);
...
int b = x.get_value(1);
</code></pre>
<p>then the compiler could optimize the second call away and either use the value in a register or simply do <code>b = a;</code></p>
<p>Is this true?</p>
| [
{
"answer_id": 98733,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>I doubt it, the function could still call a global function that altered the state of the world and not violate const.</p>\n"
},
{
"answer_id": 98754,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 2,
"selected": false,
"text": "<p>The const keyword on a member function marks the <em>this</em> parameter as constant. The function can still mute global data (so can't be cached), but not object data (allowing for calls on const objects).</p>\n"
},
{
"answer_id": 98762,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>In this context, a <code>const</code> member function means that <code>this</code> is treated as a <code>const</code> pointer also. In practical terms, it means you aren't allowed to modify the state of <code>this</code> inside a <code>const</code> member function.</p>\n\n<p>For no-side-effect functions (i.e., what you're trying to achieve), GCC has a \"function attribute\" called <code>pure</code> (you use it by saying <code>__attribute__((pure))</code>): <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html\" rel=\"nofollow noreferrer\">http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html</a></p>\n"
},
{
"answer_id": 98787,
"author": "blackwing",
"author_id": 9107,
"author_profile": "https://Stackoverflow.com/users/9107",
"pm_score": 2,
"selected": false,
"text": "<p>No. </p>\n\n<p>A const method is a method that doesn't change the state of the object (i.e. its fields), but you can't assume that given the same input, return value of a const method is determined. In other words, <code>const</code> keyword does NOT imply that the function is one-to-one. For instance a method that returns the current time is a const method but its return value changes between calls.</p>\n"
},
{
"answer_id": 98796,
"author": "KTC",
"author_id": 12868,
"author_profile": "https://Stackoverflow.com/users/12868",
"pm_score": 0,
"selected": false,
"text": "<p>On top of the fact that the member function can modify global data, it is possible for the member function to modify explicitly declared mutable members of the object in question.</p>\n"
},
{
"answer_id": 98804,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 2,
"selected": false,
"text": "<p>The keyword <a href=\"http://msdn.microsoft.com/en-us/library/4h2h0ktk(VS.80).aspx\" rel=\"nofollow noreferrer\">mutable</a> on member variables allows for const functions to alter the state of the object at hand. </p>\n\n<p>And no, it doesn't cache data (at least not all calls) since the following code is a valid const function that changes over time:</p>\n\n<pre><code>int something() const { return m_pSomeObject->NextValue(); }\n</code></pre>\n\n<p>Note that the pointer can be const, though the object pointed to is not const, therefore the call to NextValue on SomeObject may or may not alter it's own internal state. This causes the function something to return different values each time it's called.</p>\n\n<p>However, I can't answer how the compiler works with const methods. I have heard that it can optimize certain things, though I'd have to look it up to be certain.</p>\n"
},
{
"answer_id": 98806,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 0,
"selected": false,
"text": "<p>Corey is correct, but bear in mind that any member variables that are marked as <strong>mutable</strong> <em>can</em> be modified in const member functions.</p>\n\n<p>It also means that these functions can be called from other const functions, or via other const references.</p>\n\n<hr>\n\n<p>Edit: Damn, was beaten by 9 seconds.... 9!!! :)</p>\n"
},
{
"answer_id": 100593,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 6,
"selected": true,
"text": "<p><code>const</code> is about program semantics and not about implementation details. You should mark a member function <code>const</code> when it does not change the visible state of the object, and should be callable on an object that is itself <code>const</code>. Within a <code>const</code> member function on a class <code>X</code>, the type of <code>this</code> is <code>X const *</code>: pointer to constant <code>X</code> object. Thus all member variables are effectively <code>const</code> within that member function (except <code>mutable</code> ones). If you have a <code>const</code> object, you can only call <code>const</code> member functions on it.</p>\n\n<p>You can use <code>mutable</code> to indicate that a member variable may change even within a <code>const</code> member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the <code>const</code> member functions) or use counters.</p>\n\n<pre><code>class X\n{\n int data;\n mutable boost::mutex m;\npublic:\n void set_data(int i)\n {\n boost::lock_guard<boost::mutex> lk(m);\n data=i;\n }\n int get_data() const // we want to be able to get the data on a const object\n {\n boost::lock_guard<boost::mutex> lk(m); // this requires m to be non-const\n return data;\n }\n};\n</code></pre>\n\n<p>If you hold the data by pointer rather than directly (including smart pointers such as <code>std::auto_ptr</code> or <code>boost::shared_ptr</code>) then the pointer becomes <code>const</code> in a <code>const</code> member function, but not the pointed-to data, so you can modify the pointed-to data.</p>\n\n<p>As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function <em>effectively</em> only being called once.</p>\n\n<p>The next version of the <a href=\"http://www.open-std.org/jtc1/sc22/wg21/\" rel=\"noreferrer\">C++ Standard (C++0x)</a> will have a new keyword <code>constexpr</code>. Functions tagged <code>constexpr</code> return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact).</p>\n"
},
{
"answer_id": 106578,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": 0,
"selected": false,
"text": "<p>const methods are also allowed to modify static locals. For example, the following is perfectly legal (and repeated calls to bar() will return increasing values - not a cached 0):</p>\n\n<pre><code>class Foo\n{\npublic:\n int bar() const\n {\n static int x = 0;\n return x++;\n }\n};\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
]
| I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g.
```
class object
{
int get_value(int n) const
{
...
}
...
object x;
int a = x.get_value(1);
...
int b = x.get_value(1);
```
then the compiler could optimize the second call away and either use the value in a register or simply do `b = a;`
Is this true? | `const` is about program semantics and not about implementation details. You should mark a member function `const` when it does not change the visible state of the object, and should be callable on an object that is itself `const`. Within a `const` member function on a class `X`, the type of `this` is `X const *`: pointer to constant `X` object. Thus all member variables are effectively `const` within that member function (except `mutable` ones). If you have a `const` object, you can only call `const` member functions on it.
You can use `mutable` to indicate that a member variable may change even within a `const` member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the `const` member functions) or use counters.
```
class X
{
int data;
mutable boost::mutex m;
public:
void set_data(int i)
{
boost::lock_guard<boost::mutex> lk(m);
data=i;
}
int get_data() const // we want to be able to get the data on a const object
{
boost::lock_guard<boost::mutex> lk(m); // this requires m to be non-const
return data;
}
};
```
If you hold the data by pointer rather than directly (including smart pointers such as `std::auto_ptr` or `boost::shared_ptr`) then the pointer becomes `const` in a `const` member function, but not the pointed-to data, so you can modify the pointed-to data.
As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function *effectively* only being called once.
The next version of the [C++ Standard (C++0x)](http://www.open-std.org/jtc1/sc22/wg21/) will have a new keyword `constexpr`. Functions tagged `constexpr` return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact). |
98,774 | <p>I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this.</p>
<pre><code>// Quick, and very dirty
System.IO.File.WriteAllBytes(filename, new byte[f.Length]);
</code></pre>
<p>It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops.</p>
<p>So, with a little more enlightenment, I set out with the following algorithm.</p>
<pre><code>using (FileStream outFile = System.IO.File.Create(filename))
{
// 4194304 = 4MB; loops from 1 block in so that we leave the loop one
// block short
byte[] buff = new byte[4194304];
for (int i = buff.Length; i < f.Length; i += buff.Length)
{
outFile.Write(buff, 0, buff.Length);
}
outFile.Write(buff, 0, f.Length % buff.Length);
}
</code></pre>
<p>This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk.</p>
<p>The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct).</p>
| [
{
"answer_id": 98822,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 3,
"selected": false,
"text": "<p>If you have to create the file, I think that you can probably do something like this:</p>\n\n<pre><code>using (FileStream outFile = System.IO.File.Create(filename))\n{\n outFile.Seek(<length_to_write>-1, SeekOrigin.Begin);\n OutFile.WriteByte(0);\n}\n</code></pre>\n\n<p>Where length_to_write would be the size in bytes of the file to write. I'm not sure that I have the C# syntax correct (not on a computer to test), but I've done similar things in C++ in the past and it's worked.</p>\n"
},
{
"answer_id": 98838,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength\" rel=\"noreferrer\">FileStream.SetLength</a> is the one you want. The syntax:</p>\n\n<pre><code>public override void SetLength(\n long value\n)\n</code></pre>\n"
},
{
"answer_id": 98855,
"author": "user10392",
"author_id": 10392,
"author_profile": "https://Stackoverflow.com/users/10392",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, you can't really do this just by seeking to the end. That will set the file length to something huge, but may not actually allocate disk blocks for storage. So when you go to write the file, it will still fail.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
]
| I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this.
```
// Quick, and very dirty
System.IO.File.WriteAllBytes(filename, new byte[f.Length]);
```
It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops.
So, with a little more enlightenment, I set out with the following algorithm.
```
using (FileStream outFile = System.IO.File.Create(filename))
{
// 4194304 = 4MB; loops from 1 block in so that we leave the loop one
// block short
byte[] buff = new byte[4194304];
for (int i = buff.Length; i < f.Length; i += buff.Length)
{
outFile.Write(buff, 0, buff.Length);
}
outFile.Write(buff, 0, f.Length % buff.Length);
}
```
This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk.
The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct). | [FileStream.SetLength](http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength) is the one you want. The syntax:
```
public override void SetLength(
long value
)
``` |
98,778 | <p>I need to execute a batch file as part of the un-install process in a Windows installer project (standard OOTB VS 2008 installer project-vdproj). One cannot execute a bat file directly from the Custom Actions in the installer project, so I wrote a quick vbs script to call the required bat file.<br>
vbs code: </p>
<pre><code>Set WshShell = WScript.CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
</code></pre>
<p>When this script is run independent of the uninstall, it works perfectly. However, when run as part of the uninstall, it does not execute the bat file (but the message box is shown, so I know the vbs file is called). No errors reported (at least that I can tell). Why doesn't this script work as part of the "Uninstall Custom Action"</p>
| [
{
"answer_id": 98839,
"author": "Mike L",
"author_id": 12085,
"author_profile": "https://Stackoverflow.com/users/12085",
"pm_score": 0,
"selected": false,
"text": "<p>In your installer class, are you overriding the Uninstall method: </p>\n\n<pre><code> Public Overrides Sub Uninstall(ByVal savedState As System.Collections.IDictionary)\n MyBase.Uninstall(savedState)\n 'Shell to batch file here\n End Sub\n</code></pre>\n\n<p>And secondly, have you qualified the full path to the batch file?</p>\n"
},
{
"answer_id": 98840,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 0,
"selected": false,
"text": "<p>Have you checked that the batch file is in the current directory as seen by the script? I would add another message showing the directory it is using to ensure it is actually trying to execute the batch file where you think it is located.</p>\n"
},
{
"answer_id": 123745,
"author": "Mark Verrey",
"author_id": 16728,
"author_profile": "https://Stackoverflow.com/users/16728",
"pm_score": 0,
"selected": false,
"text": "<p>Windows Installer scripts generally run as System, unless you tell it otherwise. Is it possible that your batch file needs to be run by the interactive user?</p>\n"
},
{
"answer_id": 123766,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 3,
"selected": false,
"text": "<p>I've run into this same problem and the issue is that you can't call WScript within the vbs file - you will need to JUST call CreateObject</p>\n\n<p>ie.</p>\n\n<pre><code>Set WshShell = CreateObject( \"WScript.Shell\" )\ncommand = \"uninstall-windows-serivce.bat\"\nmsgbox command\nWshShell.Run (\"cmd /C \" & \"\"\"\" & command & \"\"\"\")\nSet WshShell = Nothing\n</code></pre>\n"
},
{
"answer_id": 159319,
"author": "LanceSc",
"author_id": 10012,
"author_profile": "https://Stackoverflow.com/users/10012",
"pm_score": 1,
"selected": false,
"text": "<p>The wider you need to distribute your application, the more strongly I would recommend against scripted custom actions. I had written a bunch in the past, but I found that too many computers have problems running <a href=\"http://en.wikipedia.org/wiki/VBScript\" rel=\"nofollow noreferrer\">VBScript</a> or JavaScript. I ended up rewriting them all in C++ to handle this situation. Here are a couple of posts that give an in-depth explanation on why you should avoid scripted custom actions:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/robmen/archive/2004/05/20/136530.aspx\" rel=\"nofollow noreferrer\">VBScript (and Jscript) MSI CustomActions suck</a></li>\n<li><a href=\"http://bonemanblog.blogspot.com/2004/06/vbscript-and-jscript-msi-custom.html\" rel=\"nofollow noreferrer\">VBScript (and Jscript) MSI Custom Actions (don't have to) suck</a></li>\n</ul>\n"
},
{
"answer_id": 3750935,
"author": "CuberIce",
"author_id": 452651,
"author_profile": "https://Stackoverflow.com/users/452651",
"pm_score": 0,
"selected": false,
"text": "<p>What worked for me was to specify the full path of the .bat file.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18449/"
]
| I need to execute a batch file as part of the un-install process in a Windows installer project (standard OOTB VS 2008 installer project-vdproj). One cannot execute a bat file directly from the Custom Actions in the installer project, so I wrote a quick vbs script to call the required bat file.
vbs code:
```
Set WshShell = WScript.CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
```
When this script is run independent of the uninstall, it works perfectly. However, when run as part of the uninstall, it does not execute the bat file (but the message box is shown, so I know the vbs file is called). No errors reported (at least that I can tell). Why doesn't this script work as part of the "Uninstall Custom Action" | I've run into this same problem and the issue is that you can't call WScript within the vbs file - you will need to JUST call CreateObject
ie.
```
Set WshShell = CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
``` |
98,827 | <p>I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET
something like </p>
<pre><code>String^ speed;
String^ size;
</code></pre>
<p>"command SPEED=[speed] SIZE=[size]"</p>
<p>Right now I'm using IndexOf() and Substring() but it is quite ugly</p>
| [
{
"answer_id": 98946,
"author": "user10392",
"author_id": 10392,
"author_profile": "https://Stackoverflow.com/users/10392",
"pm_score": 0,
"selected": false,
"text": "<p>If you put all the variables in a class, you can use reflection to iterate over its fields, getting their names and values and plugging them into a string.</p>\n\n<p>Given an instance of some class named InputArgs:</p>\n\n<pre><code>foreach (FieldInfo f in typeof(InputArgs).GetFields()) {\n string = Regex.replace(\"\\\\[\" + f.Name + \"\\\\]\",\n f.GetValue(InputArgs).ToString());\n}\n</code></pre>\n"
},
{
"answer_id": 99048,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 3,
"selected": true,
"text": "<pre><code>String^ speed; String^ size;\nMatch m;\nRegex theregex = new Regex (\n \"SPEED=(?<speed>(.*?)) SIZE=(?<size>(.*?)) \",\n RegexOptions::ExplicitCapture);\nm = theregex.Match (yourinputstring);\nif (m.Success)\n{\n if (m.Groups[\"speed\"].Success)\n speed = m.Groups[\"speed\"].Value;\n if (m.Groups[\"size\"].Success)\n size = m.Groups[\"size\"].Value;\n}\nelse\n throw new FormatException (\"Input options not recognized\");\n</code></pre>\n\n<p>Apologies for syntax errors, I don't have a compiler to test with right now.</p>\n"
},
{
"answer_id": 99114,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand your question correctly, you are looking for capturing groups. I'm not familiar with the .net api, but in java this would look something like:</p>\n\n<pre><code>Pattern pattern = Pattern.compile(\"command SPEED=(\\d+) SIZE=(\\d+)\");\nMatcher matcher = pattern.matcher(inputStr);\nif (matcher.find()) {\n speed = matcher.group(1);\n size = matcher.group(2);\n}\n</code></pre>\n\n<p>There are two capturing groups in the regex pattern above, designated by the two sets of parentheses. In java these must be referenced by number but in some other languages you are able to reference them by name.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6367/"
]
| I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET
something like
```
String^ speed;
String^ size;
```
"command SPEED=[speed] SIZE=[size]"
Right now I'm using IndexOf() and Substring() but it is quite ugly | ```
String^ speed; String^ size;
Match m;
Regex theregex = new Regex (
"SPEED=(?<speed>(.*?)) SIZE=(?<size>(.*?)) ",
RegexOptions::ExplicitCapture);
m = theregex.Match (yourinputstring);
if (m.Success)
{
if (m.Groups["speed"].Success)
speed = m.Groups["speed"].Value;
if (m.Groups["size"].Success)
size = m.Groups["size"].Value;
}
else
throw new FormatException ("Input options not recognized");
```
Apologies for syntax errors, I don't have a compiler to test with right now. |
98,895 | <p>I'm having problems refreshing .Net 2.0 with IIS 6.</p>
<p>I have been able to successfully execute "aspnet_regiis.exe -i", but when I try to register the aspnet_isapi.dll:</p>
<pre><code>regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
</code></pre>
<p>I get the error</p>
<blockquote>
<p>C:\Windows..\aspnet_isapi.dll was loaded, but the DllRegisterServer entry point was not found.</p>
<p>The file cannot be registered.</p>
</blockquote>
<p>Does anyone know how to resolve this? Google hasn't been very helpful.</p>
<p><strong>Edit:</strong> My problem is actually that IIS isn't serving my webpages properly - that is, it's returning 404s when I try to request .aspx files that I know exist.</p>
<p>I can access .gif and .js files OK, but I can't access .aspx or other .Net files. I know this is related to .Net being properly configured with IIS, and the above commands are supposed to be the solution, but the second command doesn't work.</p>
<p><strong>@aaronjensen</strong>: Your command to register scripts worked successfully, and investigating the logs I find that I'm getting an entry for my failed request with status 404, substatus 2.</p>
<p>Microsoft tells me this because "<a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true" rel="nofollow noreferrer">Lockdown Policy Prevents This Request</a>".</p>
<blockquote>
<p>If a request is denied because the
associated ISAPI or CGI has not been
unlocked, a 404.2 error is returned.</p>
</blockquote>
<p>Which I assume is due to the isapi DLL in my original query being denied?</p>
| [
{
"answer_id": 98907,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 0,
"selected": false,
"text": "<p>When you get the error, it means either:</p>\n\n<p>1 The DLL does not need to be registered</p>\n\n<p>or</p>\n\n<p>2 The DLL is corrupt</p>\n"
},
{
"answer_id": 98955,
"author": "Aaron Jensen",
"author_id": 11229,
"author_profile": "https://Stackoverflow.com/users/11229",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to register that. Try this as well:\nC:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis -s /w3svc/1/root</p>\n\n<p>If IIS is still giving you issues, check your event log and google the error there. You'll get hits.</p>\n"
},
{
"answer_id": 601267,
"author": "dance2die",
"author_id": 4035,
"author_profile": "https://Stackoverflow.com/users/4035",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>Check the credential that IIS server is running under.</li>\n<li>Check for the AppPool user permission.</li>\n</ol>\n"
},
{
"answer_id": 1052042,
"author": "Dexter",
"author_id": 10717,
"author_profile": "https://Stackoverflow.com/users/10717",
"pm_score": 3,
"selected": true,
"text": "<p>In the end, I think the problem was caused by a step that is missed by the script when you refresh ASP.Net 2.0 with IIS 6.</p>\n\n<p>I managed to resolve this using the following steps:</p>\n\n<ul>\n<li><p>Refresh the install using <code>C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis -s /w3svc/1/root</code></p></li>\n<li><p>Enable ASP.Net Web Service Extension in the IIS 6 Management Console - it looks like the extension was not enabled by default in IIS, hence the 404.2 <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true\" rel=\"nofollow noreferrer\">Lockdown Policy Prevents This Request</a> errors that I was seeing. Instructions to <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/596ff388-bc4c-472f-b029-aea2b0418bea.mspx?mfr=true\" rel=\"nofollow noreferrer\">enable the ASP.Net webservice extension</a> are on MSDN.</p></li>\n</ul>\n"
},
{
"answer_id": 5296417,
"author": "Nikos Tsokos",
"author_id": 15228,
"author_profile": "https://Stackoverflow.com/users/15228",
"pm_score": 0,
"selected": false,
"text": "<p>At first try all the following</p>\n\n<ol>\n<li>aspnet_regiis.exe -i</li>\n<li>C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis -s /w3svc/1/root</li>\n<li>regsvr32 “C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_isapi.dll\"</li>\n</ol>\n\n<p>If it doesnt fix the problem, check event log in computer management because it could also be another issue. \nMy case was an impersonation issue, but it only started to show up in event viewer after i did the aspnet_regiis. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10717/"
]
| I'm having problems refreshing .Net 2.0 with IIS 6.
I have been able to successfully execute "aspnet\_regiis.exe -i", but when I try to register the aspnet\_isapi.dll:
```
regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
```
I get the error
>
> C:\Windows..\aspnet\_isapi.dll was loaded, but the DllRegisterServer entry point was not found.
>
>
> The file cannot be registered.
>
>
>
Does anyone know how to resolve this? Google hasn't been very helpful.
**Edit:** My problem is actually that IIS isn't serving my webpages properly - that is, it's returning 404s when I try to request .aspx files that I know exist.
I can access .gif and .js files OK, but I can't access .aspx or other .Net files. I know this is related to .Net being properly configured with IIS, and the above commands are supposed to be the solution, but the second command doesn't work.
**@aaronjensen**: Your command to register scripts worked successfully, and investigating the logs I find that I'm getting an entry for my failed request with status 404, substatus 2.
Microsoft tells me this because "[Lockdown Policy Prevents This Request](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true)".
>
> If a request is denied because the
> associated ISAPI or CGI has not been
> unlocked, a 404.2 error is returned.
>
>
>
Which I assume is due to the isapi DLL in my original query being denied? | In the end, I think the problem was caused by a step that is missed by the script when you refresh ASP.Net 2.0 with IIS 6.
I managed to resolve this using the following steps:
* Refresh the install using `C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root`
* Enable ASP.Net Web Service Extension in the IIS 6 Management Console - it looks like the extension was not enabled by default in IIS, hence the 404.2 [Lockdown Policy Prevents This Request](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true) errors that I was seeing. Instructions to [enable the ASP.Net webservice extension](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/596ff388-bc4c-472f-b029-aea2b0418bea.mspx?mfr=true) are on MSDN. |
98,941 | <p>How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see </p>
<pre><code>wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_RIGHT_DCLICK
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_MOUSEWHEEL
</code></pre>
<p>But there is no <code>wxEVT_LEFT_CLICK</code> or similar. </p>
| [
{
"answer_id": 99659,
"author": "Zach Burlingame",
"author_id": 2233,
"author_profile": "https://Stackoverflow.com/users/2233",
"pm_score": 3,
"selected": true,
"text": "<p>Typically, there is no \"click\" event (and in the case of <a href=\"http://www.wxwidgets.org/\" rel=\"nofollow noreferrer\">wxWidgets</a> - <a href=\"http://docs.wxwidgets.org/stable/wx_wxmouseevent.html#wxmouseevent\" rel=\"nofollow noreferrer\">there isn't</a>\n). The action of clicking is broken into its two parts: Mouse Down and Mouse Up. Typically what you think of as a \"left click\" event is actually handled in a \"left up\" event.</p>\n\n<p>Try it out: </p>\n\n<ul>\n<li>Hover over a button (such as the \"Add Comment\" button this page) </li>\n<li>Click the left-mouse button down and hold</li>\n<li>Move the mouse off of the button while holding down</li>\n<li>Release the left-mouse button</li>\n<li>Nothing happens!</li>\n</ul>\n\n<p>This time:</p>\n\n<ul>\n<li>Hover over the same button </li>\n<li>Click the\nleft-mouse button down and hold</li>\n<li>Release the left-mouse button</li>\n<li>The \"click\" action you expect is triggered by the up event!</li>\n</ul>\n"
},
{
"answer_id": 99689,
"author": "Bill Forster",
"author_id": 3955,
"author_profile": "https://Stackoverflow.com/users/3955",
"pm_score": 2,
"selected": false,
"text": "<p>In the first instance I recommend inheriting from wxControl not wxWindow, wxControl is designed for that exact purpose and you are less likely to find yourself fighting the system. When I look at a control I am building in my own wxWidgets app, I see that my click handler is attached to wxEVT_LEFT_DOWN. Looking in my copy of Cross Platform GUI Programming with wxWidgets I can see a list of all wxMouseEvents, and there is no wxEVT_LEFT_CLICK. I would suggest wxEVT_LEFT_DOWN is the event to use.</p>\n\n<p>Now after posting I've read Burly's answer and I agree with him, wxWidgets offers the lowest level events and that gives you the maximum amount of control of the user interface you construct for your users.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11238/"
]
| How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see
```
wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_RIGHT_DCLICK
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_MOUSEWHEEL
```
But there is no `wxEVT_LEFT_CLICK` or similar. | Typically, there is no "click" event (and in the case of [wxWidgets](http://www.wxwidgets.org/) - [there isn't](http://docs.wxwidgets.org/stable/wx_wxmouseevent.html#wxmouseevent)
). The action of clicking is broken into its two parts: Mouse Down and Mouse Up. Typically what you think of as a "left click" event is actually handled in a "left up" event.
Try it out:
* Hover over a button (such as the "Add Comment" button this page)
* Click the left-mouse button down and hold
* Move the mouse off of the button while holding down
* Release the left-mouse button
* Nothing happens!
This time:
* Hover over the same button
* Click the
left-mouse button down and hold
* Release the left-mouse button
* The "click" action you expect is triggered by the up event! |
98,944 | <p>How do I write a cpp macro which expands to include newlines?</p>
| [
{
"answer_id": 98956,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>\\</code>, like so:</p>\n\n<pre><code>#define my_multiline_macro(a, b, c) \\\nif (a) { \\\n b += c; \\\n}\n</code></pre>\n"
},
{
"answer_id": 98962,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 3,
"selected": false,
"text": "<p>C & C++ compilers ignore unquoted whitespace (except for the > > template issue), so getting a macro to emit newlines doesn't really make sense. You can make a macro span several lines by ending each line of the macro with a backslash, but this doesn't output newlines.</p>\n"
},
{
"answer_id": 98972,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": -1,
"selected": false,
"text": "<p>Not quite sure what you're asking here. Do you want a macro on multiple lines?</p>\n\n<pre><code>#define NEWLINE_MACRO(x) line1 \\\nline2 \\\nline3\n</code></pre>\n\n<p>Additionally, if you would like to include a literal in your macro:</p>\n\n<pre><code>#define NEWLINE_MACRO(x) ##x\n</code></pre>\n\n<p>what you you put in x will be put in place of ##x, so:</p>\n\n<pre><code>NEWLINE_MACRO( line1 ) // is replaced with line1\n</code></pre>\n\n<p>This can be helpful for making custom global functions then just need part of the function name changed.</p>\n\n<p>Also:</p>\n\n<pre><code>#define NEWLINE_MACRO(x) #x // stringify x\n</code></pre>\n\n<p>Will put quotes around x</p>\n"
},
{
"answer_id": 98973,
"author": "David L Morris",
"author_id": 3137,
"author_profile": "https://Stackoverflow.com/users/3137",
"pm_score": 3,
"selected": false,
"text": "<p>The C compiler is aware of white space, but it doesn't distinguish between spaces, tabs or new lines.</p>\n\n<p>If you mean how do I have a new line inside a string in a macro, then:</p>\n\n<pre><code>#define SOME_STRING \"Some string\\n with a new line.\"\n</code></pre>\n\n<p>will work.</p>\n"
},
{
"answer_id": 99017,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": -1,
"selected": false,
"text": "<p>Use the \\ at the end of the line. I've seen a lot of C macos where they use a do...while(0)</p>\n\n<pre><code>#define foo() do \\\n{\n //code goes here \\\n \\\n \\\n}while(0);\n</code></pre>\n\n<p>Also, remember to use parenthases in many instances.</p>\n\n<p>Example: </p>\n\n<pre><code>#define foo(x) a+b\n//should be\n#define foo(x) (a+b)\n</code></pre>\n"
},
{
"answer_id": 100329,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": 3,
"selected": false,
"text": "<p>It is not possible. It would only be relevant if you were looking at listing files or pre-processor output.</p>\n\n<p>A common technique in writing macros so that they are easier to read is to use the \\ character to continue the macro onto a following line.</p>\n\n<p>I (believe I) have seen compilers that include new lines in the expanded macros in listing output - for your benefit. This is only of use to us poor humans reading the expanded macros to try to understand what we really asked the compiler to do. it makes no difference to the compiler.</p>\n\n<p>The C & C++ languages treat all whitespace outside of strings in the same way. Just as a separator.</p>\n"
},
{
"answer_id": 36384452,
"author": "Florian Fleissner",
"author_id": 6151578,
"author_profile": "https://Stackoverflow.com/users/6151578",
"pm_score": 4,
"selected": false,
"text": "<p>I am working on a large project that involves a lot of preprocessor macro functions to synthesize any code that cannot be replaced by templates. Believe me, I am familiar with all sorts of template tricks, but as long as there is no standardized, type safe metaprogramming language that can directly create code, we will have to stick with good old preprocessor and its cumbersome macros to solve some problems that would require to write ten times more code without.\nSome of the macros span many lines and they are very hard to read in preprocessed code. Therefore, I thought of a solution to that problem and what I came up with is the following:</p>\n\n<p>Let's say we have a C/C++ macro that spans multiple lines, e.g. in a file named <em>MyMacro.hpp</em></p>\n\n<pre><code>// Content of MyMacro.hpp\n\n#include \"MultilineMacroDebugging.hpp\"\n\n#define PRINT_VARIABLE(S) \\\n__NL__ std::cout << #S << \": \" << S << std::endl; \\\n__NL__ /* more lines if necessary */ \\\n__NL__ /* even more lines */\n</code></pre>\n\n<p>In every file where I defined such a macro, I include another file <em>MultilineMacroDebugging.hpp</em> that contains the following:</p>\n\n<pre><code>// Content of MultilineMacroDebugging.hpp\n\n#ifndef HAVE_MULTILINE_DEBUGGING\n#define __NL__\n#endif\n</code></pre>\n\n<p>This defines an empty macro <code>__NL__</code>, which makes the <code>__NL__</code> definitions disappear during preprocessing. The macro can then be used somewhere, e.g.\nin a file named <em>MyImplementation.cpp</em>.</p>\n\n<pre><code>// Content of MyImplementation.cpp\n\n// Uncomment the following line to enable macro debugging\n//#define HAVE_MULTILINE_DEBUGGING\n\n#include \"MyMacro.hpp\"\n\nint a = 10;\nPRINT_VARIABLE(a)\n</code></pre>\n\n<p>If I need to debug the <code>PRINT_VARIABLE</code> macro, I just uncomment the line that defines the macro <code>HAVE_MULTILINE_DEBUGGING</code> in <em>MyImplementation.cpp</em>. The resulting code does of course not compile, as the <code>__NL__</code> macro results undefined, which causes it to remain in the compiled code, but it can, however, be preprocessed.</p>\n\n<p>The crucial step is now to replace the <code>__NL__</code> string in the preprocessor output by newlines using your favorite text editor and, voila, you end up with a readable representation of the result of the replaced macro after preprocessing which resembles exactly what the compiler would see, except for the artificially introduced newlines.</p>\n"
},
{
"answer_id": 74238404,
"author": "Björn Grieger",
"author_id": 20360122,
"author_profile": "https://Stackoverflow.com/users/20360122",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same problem. I abuse the preprocessor on non C files, therefore the fact that the C compiler ignores line breaks is irrelevant for me. I am using \\\\ at the end of lines in the macro definition (which is pretty neat syntax, resembling LaTeX) and pass the result through</p>\n<pre><code>sed s/'\\\\ '/'\\n'/g\n</code></pre>\n<p>This does the trick. The preprocessor strips one \\ away from the \\\\ and joins the lines, and the sed splits them again by replacing the remaining \\ by a real newline.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/98944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18458/"
]
| How do I write a cpp macro which expands to include newlines? | I am working on a large project that involves a lot of preprocessor macro functions to synthesize any code that cannot be replaced by templates. Believe me, I am familiar with all sorts of template tricks, but as long as there is no standardized, type safe metaprogramming language that can directly create code, we will have to stick with good old preprocessor and its cumbersome macros to solve some problems that would require to write ten times more code without.
Some of the macros span many lines and they are very hard to read in preprocessed code. Therefore, I thought of a solution to that problem and what I came up with is the following:
Let's say we have a C/C++ macro that spans multiple lines, e.g. in a file named *MyMacro.hpp*
```
// Content of MyMacro.hpp
#include "MultilineMacroDebugging.hpp"
#define PRINT_VARIABLE(S) \
__NL__ std::cout << #S << ": " << S << std::endl; \
__NL__ /* more lines if necessary */ \
__NL__ /* even more lines */
```
In every file where I defined such a macro, I include another file *MultilineMacroDebugging.hpp* that contains the following:
```
// Content of MultilineMacroDebugging.hpp
#ifndef HAVE_MULTILINE_DEBUGGING
#define __NL__
#endif
```
This defines an empty macro `__NL__`, which makes the `__NL__` definitions disappear during preprocessing. The macro can then be used somewhere, e.g.
in a file named *MyImplementation.cpp*.
```
// Content of MyImplementation.cpp
// Uncomment the following line to enable macro debugging
//#define HAVE_MULTILINE_DEBUGGING
#include "MyMacro.hpp"
int a = 10;
PRINT_VARIABLE(a)
```
If I need to debug the `PRINT_VARIABLE` macro, I just uncomment the line that defines the macro `HAVE_MULTILINE_DEBUGGING` in *MyImplementation.cpp*. The resulting code does of course not compile, as the `__NL__` macro results undefined, which causes it to remain in the compiled code, but it can, however, be preprocessed.
The crucial step is now to replace the `__NL__` string in the preprocessor output by newlines using your favorite text editor and, voila, you end up with a readable representation of the result of the replaced macro after preprocessing which resembles exactly what the compiler would see, except for the artificially introduced newlines. |
99,045 | <p>We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.</p>
<p>Currently we use the commands in the test:</p>
<pre><code>// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");
</code></pre>
<p>...which works <em>most of the time</em>. Occasionally the test will fail on the <code>waitForPopUp()</code> line with </p>
<pre><code>com.thoughtworks.selenium.SeleniumException: Permission denied
</code></pre>
<p>Can anyone suggest a better, more <em>reliable</em> method?</p>
<p>Also, we primarily run these tests on IE6 and 7.</p>
| [
{
"answer_id": 99127,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 1,
"selected": false,
"text": "<p>If you are running in *iehta mode then you are going to run into some glitches here and there. We run Selenium at my job and there seem to be lots of issues with IE and AJAX.</p>\n\n<p>However, it sounds like the issue you are running into is one where Selenium is trying to access a component in another window before it completely loads up. I am not sure what your default timeout range is set to, but you may want to try increasing it to 60 (60000ms) seconds or so to get past the issue.</p>\n\n<p>Other than that I would suggest running your tests in Firefox (using *chrome) as it produces much more reliable results, but sometimes it is simply not possible due to business requirements.</p>\n"
},
{
"answer_id": 99372,
"author": "brasskazoo",
"author_id": 6340,
"author_profile": "https://Stackoverflow.com/users/6340",
"pm_score": 0,
"selected": false,
"text": "<p>I just trialled adding another selenium function, <code>windowFocus()</code>:</p>\n\n<pre><code>// force new window to open at this point - so we can select it later\nselenium().getEval(\"this.browserbot.getCurrentWindow().open('', 'enquiryPopup')\");\nselenium().click(\"//input[@value='Submit']\");\nselenium().windowFocus(\"enquiryPopup\");\nselenium().waitForPopUp(\"enquiryPopup\", getWaitTime());\nselenium().selectWindow(\"enquiryPopup\");\n</code></pre>\n\n<p>The test succeeded when I ran it locally, but only with all those method calls - create/focus/wait/select. </p>\n\n<p>I'm about to let the build server run all the tests, and if that succeeds too, I'll be making a library function out of it...!</p>\n"
},
{
"answer_id": 102184,
"author": "Peter Bernier",
"author_id": 6112,
"author_profile": "https://Stackoverflow.com/users/6112",
"pm_score": -1,
"selected": false,
"text": "<p>Try adding some wait statements around the calls that are causing you issues.</p>\n\n<p>I've had the same errors before and the only way I was able to <i>reliably</i> resolve them was by making calls to System.Threading.Thread.Sleep(5000)..</p>\n"
},
{
"answer_id": 429196,
"author": "branchgabriel",
"author_id": 30807,
"author_profile": "https://Stackoverflow.com/users/30807",
"pm_score": 3,
"selected": true,
"text": "<p>It works!! Just to make it easier for the folks who prefer selenese.</p>\n\n<p>This worked for me using IE7(normal mode). </p>\n\n<p>What a freaking hassle. Thank the spaghetti monster in the sky for SO or there is no way I would have got this working in IE.</p>\n\n<pre><code><tr>\n <td>getEval</td>\n <td>selenium.browserbot.getCurrentWindow().open('', 'windowName');</td>\n <td></td>\n</tr>\n<tr>\n <td>click</td>\n <td>buttonName</td>\n <td></td>\n</tr>\n<tr>\n <td>windowFocus</td>\n <td>windowName</td>\n <td></td>\n</tr>\n<tr>\n <td>waitForPopUp</td>\n <td>windowName</td>\n <td>3000</td>\n</tr>\n<tr>\n <td>selectWindow</td>\n <td>windowName</td>\n <td></td>\n</tr>\n</code></pre>\n"
},
{
"answer_id": 1941915,
"author": "nicholasklick",
"author_id": 236260,
"author_profile": "https://Stackoverflow.com/users/236260",
"pm_score": 0,
"selected": false,
"text": "<p>I needed to select an iframe within a popup window and fill out a form. \nI had trouble using the selectWindow cmd where selenium couldn't find my iframe, so I removed the command.</p>\n\n<p>This selenese worked well for me (where the iframe title and id = account_frame) :</p>\n\n<pre><code><tr>\n <td>click</td>\n <td>//a[@class='item_add']</td>\n <td></td>\n</tr>\n<tr>\n <td>windowFocus</td>\n <td>account_frame</td>\n <td></td>\n</tr>\n<tr>\n <td>waitForPopUp</td>\n <td>account_frame</td>\n <td>10000</td>\n</tr>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
]
| We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.
Currently we use the commands in the test:
```
// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");
```
...which works *most of the time*. Occasionally the test will fail on the `waitForPopUp()` line with
```
com.thoughtworks.selenium.SeleniumException: Permission denied
```
Can anyone suggest a better, more *reliable* method?
Also, we primarily run these tests on IE6 and 7. | It works!! Just to make it easier for the folks who prefer selenese.
This worked for me using IE7(normal mode).
What a freaking hassle. Thank the spaghetti monster in the sky for SO or there is no way I would have got this working in IE.
```
<tr>
<td>getEval</td>
<td>selenium.browserbot.getCurrentWindow().open('', 'windowName');</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>buttonName</td>
<td></td>
</tr>
<tr>
<td>windowFocus</td>
<td>windowName</td>
<td></td>
</tr>
<tr>
<td>waitForPopUp</td>
<td>windowName</td>
<td>3000</td>
</tr>
<tr>
<td>selectWindow</td>
<td>windowName</td>
<td></td>
</tr>
``` |
99,074 | <p>Would it be useful to be able to provide method return value for null objects?</p>
<p>For a List the null return values might be:</p>
<pre><code>get(int) : null
size() : 0
iterator() : empty iterator
</code></pre>
<p>That would allow the following code that has less null checks.</p>
<pre><code>List items = null;
if(something) {
items = ...
}
for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}
</code></pre>
<p>This would only be used if the class or interface defined it and a null check would still work. Sometimes you don't want to do null checks so it seems like it could be beneficial to have this as an option.</p>
<p>From: <a href="http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html</a></p>
| [
{
"answer_id": 99112,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This is a good idea.</strong></p>\n\n<p>Smalltalk does this.</p>\n\n<p>There is a NULL object. It <em>doesn't</em> descend from Object. (Smalltalk is a singly-rooted class hierarchy like Java)</p>\n\n<p>For the advanced student, you can sub-class it for making proxies!</p>\n"
},
{
"answer_id": 99160,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>It's a pattern called Null Object</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Null_Object_pattern</a></p>\n"
},
{
"answer_id": 99191,
"author": "flukus",
"author_id": 407256,
"author_profile": "https://Stackoverflow.com/users/407256",
"pm_score": 0,
"selected": false,
"text": "<p>Ruby does this (as well as others). It has nil instead of null and it's an object.</p>\n\n<p>I dp hate when functions that are meant to return lists can return null. It's better to return an empty list and let the user decide if they want to check for null (empty) or not.</p>\n"
},
{
"answer_id": 99203,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 2,
"selected": false,
"text": "<p>It is nice to not have to check for NULL, and some languages make it easier -- e.g. C#'s non-NULLable types, or Haskell which doesn't have NULLs but can express a missing value with the Maybe type constructor.</p>\n\n<p>A NULL is distinct from an empty list. You can take the point-of-view that someone passing in a NULL where you need a list is making a programming error, and that the right thing to do is throw a NullPointerException.</p>\n\n<p>The typical excuse for accepting NULLs is that often there's a case where you don't need the list, and you shouldn't have to create a new List that's empty, especially when there's some concern about efficiency. You can have many of the benefits without changing the language, but by instead having a static EmptyList that people can pass in, that never needs to be reinitialized.</p>\n"
},
{
"answer_id": 99332,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>In C# (among other languages), this is normally not allowed. Without an instance of Foo, .net doesn't know to call Foo's method or Foo's child's method.</p>\n\n<p>However, an C# 3.0 extension method applied to the Foo type would allow this:</p>\n\n<pre><code>Foo x = null;\nif (x.Bar() == 0)\n{\n Console.WriteLine(\"I win\");\n}\n</code></pre>\n\n<p>Bar could be constructed like so:</p>\n\n<pre><code>public static int Bar (this Foo theFoo)\n{\n return theFoo == null ? 0 : 1;\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| Would it be useful to be able to provide method return value for null objects?
For a List the null return values might be:
```
get(int) : null
size() : 0
iterator() : empty iterator
```
That would allow the following code that has less null checks.
```
List items = null;
if(something) {
items = ...
}
for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}
```
This would only be used if the class or interface defined it and a null check would still work. Sometimes you don't want to do null checks so it seems like it could be beneficial to have this as an option.
From: <http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html> | It's a pattern called Null Object
<http://en.wikipedia.org/wiki/Null_Object_pattern> |
99,098 | <p>What is the best way to generate a current datestamp in Java? </p>
<p>YYYY-MM-DD:hh-mm-ss</p>
| [
{
"answer_id": 99105,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Date d = new Date();\nString formatted = new SimpleDateFormat (\"yyyy-MM-dd:HH-mm-ss\").format (d);\nSystem.out.println (formatted);\n</code></pre>\n"
},
{
"answer_id": 99108,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 0,
"selected": false,
"text": "<p>SimpleDateFormatter is what you want. </p>\n"
},
{
"answer_id": 99133,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "<p>There's also</p>\n\n<pre><code>long timestamp = System.currentTimeMillis() \n</code></pre>\n\n<p>which is what <code>new Date()</code> (@<a href=\"https://stackoverflow.com/questions/99098/generate-a-current-datestamp-in-java#99105\">John Millikin</a>) uses internally. Once you have that, you can format it however you like.</p>\n"
},
{
"answer_id": 99152,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": 0,
"selected": false,
"text": "<pre><code>final DateFormat formatter = new SimpleDateFormat(\"yyyy-MM-dd:hh-mm-ss\");\n\nformatter.format(new Date());\n</code></pre>\n\n<p>The <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\">JavaDoc for SimpleDateFormat</a> provides information on date and time pattern strings.</p>\n"
},
{
"answer_id": 99175,
"author": "jt.",
"author_id": 4362,
"author_profile": "https://Stackoverflow.com/users/4362",
"pm_score": 6,
"selected": true,
"text": "<p>Using the standard JDK, you will want to use java.text.SimpleDateFormat</p>\n\n<pre><code>Date myDate = new Date();\nSimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd:HH-mm-ss\");\nString myDateString = sdf.format(myDate);\n</code></pre>\n\n<p>However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat</p>\n\n<pre><code>Date myDate = new Date();\nFastDateFormat fdf = FastDateFormat.getInstance(\"yyyy-MM-dd:HH-mm-ss\");\nString myDateString = fdf.format(myDate);\n</code></pre>\n\n<p>FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:</p>\n\n<pre><code>SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd:HH-mm-ss\");\nDate yourDate = sdf.parse(\"2008-09-18:22-03-15\");\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3020/"
]
| What is the best way to generate a current datestamp in Java?
YYYY-MM-DD:hh-mm-ss | Using the standard JDK, you will want to use java.text.SimpleDateFormat
```
Date myDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
String myDateString = sdf.format(myDate);
```
However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat
```
Date myDate = new Date();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss");
String myDateString = fdf.format(myDate);
```
FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
Date yourDate = sdf.parse("2008-09-18:22-03-15");
``` |
99,118 | <p>Is there any downside or problem potential to change the Java compiler to automatically cast? In the example below the result of list.get(0) would automatically be casted to the type of the variable hi.</p>
<pre><code>List list = new ArrayList();
list.add("hi");
String hi = list.get(0);
</code></pre>
<p>I know that generics allow you to reduce casting but they do so at the expense of making declaration more difficult. To me, the benefit of generics is that they allow you to have the complier enforce more rules -- not they they reduce casting (but I haven't used them much so I am somewhat uninformed). This proposal would only reduce the amount of code to type, not move it to another place.
Also there are instances where generics can't be used because a collection can have different objectis.
If that "looks too surprising" based on current usage maybe there could be a syntax tweak to use it.</p>
<p>From: <a href="http://jamesjava.blogspot.com/2007/01/automatic-casting.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2007/01/automatic-casting.html</a></p>
| [
{
"answer_id": 99135,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": false,
"text": "<p>Casting is an explicit instruction to the Java compiler to ignore type safety so allowing automatic casts would remove one of the features purposely designed into the language.</p>\n\n<p>I personally like compiler warnings and errors, since it's much harder to find this type of problem at run time (assuming the compiler somehow managed to force one object type to another).</p>\n"
},
{
"answer_id": 99142,
"author": "perimosocordiae",
"author_id": 10601,
"author_profile": "https://Stackoverflow.com/users/10601",
"pm_score": 1,
"selected": false,
"text": "<p>I would avoid it, because I have a feeling it will come back and bite you later on. Generics are worth the hassle, in my opinion, because they save lots of headache down the road. Also, it's not too hard to use a \"container\" object for collections that hold different object types.</p>\n"
},
{
"answer_id": 99145,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 1,
"selected": false,
"text": "<p>Seems to me like having type checks is a good thing. An automatic cast would remove a potentially useful compile-time error.</p>\n\n<p>If you worry about the number of keystrokes, you could use an IDE like Eclipse, were the type cast can be inserted with a double-click.</p>\n"
},
{
"answer_id": 99168,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, it would move errors which are currently found at compile time to being found at runtime. While this is not considered to be a huge drawback by some, those people are using Python, Ruby or Perl and not Java ;-).</p>\n"
},
{
"answer_id": 99216,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 2,
"selected": false,
"text": "<p>The biggest benefit of using generics in your example is that it changes what would be a run time error into a compile time error. </p>\n\n<pre><code>List list = new ArrayList();\nlist.add(new Integer(42));\nString hi = (String) list.get(0); // run time error\n\nList<String> list = new ArrayList<String>();\nlist.add(new Integer(42)); // compile time error\nString hi = list.get(0);\n</code></pre>\n\n<p>Because run time errors are seen by users and compile time errors are seen by programmers, compile time errors are much, much better. </p>\n\n<p>To answer your question, there would not be any drastic failures if casts were automatically made (and a ClassCastException was still thrown at runtime in your example). The benefit of requiring an explicit cast is that it requires the coder to think about what he's doing, and to realize that a cast is taking place. </p>\n\n<blockquote>\n <p>Also there are instances where\n generics can't be used because a\n collection can have different object</p>\n</blockquote>\n\n<p>You can still add different objects to a generic collection using wildcards. </p>\n"
},
{
"answer_id": 99759,
"author": "ColinD",
"author_id": 13792,
"author_profile": "https://Stackoverflow.com/users/13792",
"pm_score": 0,
"selected": false,
"text": "<p>As others have said, automatic type-casting would eliminate type safety. Generics have multiple benefits and really aren't any harder to declare. With Eclipse, you can can just declare the generic variable and then use auto-complete on the instantiation and it will automatically fill in the type you used. Plus you (or perhaps more importantly, someone else) have the advantage of actually knowing at a glance exactly what the list or whatever contains.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| Is there any downside or problem potential to change the Java compiler to automatically cast? In the example below the result of list.get(0) would automatically be casted to the type of the variable hi.
```
List list = new ArrayList();
list.add("hi");
String hi = list.get(0);
```
I know that generics allow you to reduce casting but they do so at the expense of making declaration more difficult. To me, the benefit of generics is that they allow you to have the complier enforce more rules -- not they they reduce casting (but I haven't used them much so I am somewhat uninformed). This proposal would only reduce the amount of code to type, not move it to another place.
Also there are instances where generics can't be used because a collection can have different objectis.
If that "looks too surprising" based on current usage maybe there could be a syntax tweak to use it.
From: <http://jamesjava.blogspot.com/2007/01/automatic-casting.html> | Casting is an explicit instruction to the Java compiler to ignore type safety so allowing automatic casts would remove one of the features purposely designed into the language.
I personally like compiler warnings and errors, since it's much harder to find this type of problem at run time (assuming the compiler somehow managed to force one object type to another). |
99,132 | <p>I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it.</p>
<p>I mainly use mingw/msys but would like something that works across other shells/systems too.</p>
<p>I tried this but it didn't work, any ideas?</p>
<pre><code>ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif
</code></pre>
| [
{
"answer_id": 99156,
"author": "andrewdotnich",
"author_id": 10569,
"author_profile": "https://Stackoverflow.com/users/10569",
"pm_score": 4,
"selected": false,
"text": "<p>If having the directory already exist is not a problem for you, you could just redirect stderr for that command, getting rid of the error message:</p>\n\n<pre><code>-mkdir $(OBJDIR) 2>/dev/null\n</code></pre>\n"
},
{
"answer_id": 99174,
"author": "tchen",
"author_id": 18417,
"author_profile": "https://Stackoverflow.com/users/18417",
"pm_score": 8,
"selected": true,
"text": "<p>On UNIX Just use this:</p>\n\n<pre><code>mkdir -p $(OBJDIR)\n</code></pre>\n\n<p>The -p option to mkdir prevents the error message if the directory exists.</p>\n"
},
{
"answer_id": 99176,
"author": "Lee H",
"author_id": 18201,
"author_profile": "https://Stackoverflow.com/users/18201",
"pm_score": 4,
"selected": false,
"text": "<p>Inside your makefile:</p>\n\n<pre><code>target:\n if test -d dir; then echo \"hello world!\"; else mkdir dir; fi\n</code></pre>\n"
},
{
"answer_id": 99188,
"author": "skymt",
"author_id": 18370,
"author_profile": "https://Stackoverflow.com/users/18370",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the test command:</p>\n\n<pre><code>test -d $(OBJDIR) || mkdir $(OBJDIR)\n</code></pre>\n"
},
{
"answer_id": 175750,
"author": "Michael McCarty",
"author_id": 25007,
"author_profile": "https://Stackoverflow.com/users/25007",
"pm_score": 3,
"selected": false,
"text": "<pre><code>ifeq \"$(wildcard $(MY_DIRNAME) )\" \"\"\n -mkdir $(MY_DIRNAME)\nendif\n</code></pre>\n"
},
{
"answer_id": 511665,
"author": "Martin Fido",
"author_id": 62457,
"author_profile": "https://Stackoverflow.com/users/62457",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$(OBJDIR):\n mkdir $@\n</code></pre>\n\n<p>Which also works for multiple directories, e.g..</p>\n\n<pre><code>OBJDIRS := $(sort $(dir $(OBJECTS)))\n\n$(OBJDIRS):\n mkdir $@\n</code></pre>\n\n<p>Adding <code>$(OBJDIR)</code> as the first target works well.</p>\n"
},
{
"answer_id": 3300436,
"author": "wmad",
"author_id": 398088,
"author_profile": "https://Stackoverflow.com/users/398088",
"pm_score": 3,
"selected": false,
"text": "<p>On Windows </p>\n\n<pre><code>if not exist \"$(OBJDIR)\" mkdir $(OBJDIR)\n</code></pre>\n\n<p>On Unix | Linux </p>\n\n<pre><code>if [ ! -d \"$(OBJDIR)\" ]; then mkdir $(OBJDIR); fi\n</code></pre>\n"
},
{
"answer_id": 3739843,
"author": "Northern Stream",
"author_id": 1167733,
"author_profile": "https://Stackoverflow.com/users/1167733",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:</p>\n\n<pre><code> %/.d:\n mkdir -p $(@D)\n touch $@\n</code></pre>\n\n<p>Then make all files that go into the directory dependent on the .d file in that directory:</p>\n\n<pre><code> obj/%.o: %.c obj/.d\n $(CC) $(CFLAGS) -c -o $@ $<\n</code></pre>\n\n<p>Note use of $< instead of $^. </p>\n\n<p>Finally prevent the .d files from being removed automatically:</p>\n\n<pre><code> .PRECIOUS: %/.d\n</code></pre>\n\n<p>Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.</p>\n"
},
{
"answer_id": 6170280,
"author": "ofavre",
"author_id": 508831,
"author_profile": "https://Stackoverflow.com/users/508831",
"pm_score": 7,
"selected": false,
"text": "<p>Looking at <a href=\"http://www.gnu.org/software/make/manual/make.html#Prerequisite-Types\">the official make documentation</a>, here is a good way to do it:</p>\n\n<pre><code>OBJDIR := objdir\nOBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)\n\n$(OBJDIR)/%.o : %.c\n $(COMPILE.c) $(OUTPUT_OPTION) $<\n\nall: $(OBJS)\n\n$(OBJS): | $(OBJDIR)\n\n$(OBJDIR):\n mkdir -p $(OBJDIR)\n</code></pre>\n\n<p>You should see here the usage of the | pipe operator, defining an order only prerequisite.\nMeaning that the <code>$(OBJDIR)</code> target should be existent (instead of <em>more recent</em>) in order to build the current target.</p>\n\n<p>Note that I used <code>mkdir -p</code>. The <code>-p</code> flag was added compared to the example of the docs.\nSee other answers for another alternative.</p>\n"
},
{
"answer_id": 10100865,
"author": "lygstate",
"author_id": 321938,
"author_profile": "https://Stackoverflow.com/users/321938",
"pm_score": 2,
"selected": false,
"text": "<p>It works under mingw32/msys/cygwin/linux</p>\n\n<pre><code>ifeq \"$(wildcard .dep)\" \"\"\n-include $(shell mkdir .dep) $(wildcard .dep/*)\nendif\n</code></pre>\n"
},
{
"answer_id": 17385817,
"author": "Mischa",
"author_id": 205874,
"author_profile": "https://Stackoverflow.com/users/205874",
"pm_score": 0,
"selected": false,
"text": "<p>A little simpler than Lars' answer:</p>\n\n<pre><code>something_needs_directory_xxx : xxx/..\n</code></pre>\n\n<p>and generic rule:</p>\n\n<pre><code>%/.. : ;@mkdir -p $(@D)\n</code></pre>\n\n<p>No touch-files to clean up or make .PRECIOUS :-)</p>\n\n<p>If you want to see another little generic gmake trick, or if you're interested in non-recursive make with minimal scaffolding, you might care to check out <a href=\"https://mischasan.wordpress.com/2012/07/05/two-more-cheap-gmake-tricks-creating-directories-and-printing-variables/\" rel=\"nofollow noreferrer\">Two more cheap gmake tricks</a> and the other make-related posts in that blog.</p>\n"
},
{
"answer_id": 32495400,
"author": "Andrew",
"author_id": 383188,
"author_profile": "https://Stackoverflow.com/users/383188",
"pm_score": 0,
"selected": false,
"text": "<p>If you explicitly ignore the return code and dump the error stream then your make will ignore the error if it occurs:</p>\n\n<pre><code>mkdir 2>/dev/null || true\n</code></pre>\n\n<p>This should not cause a race hazard in a parallel make - but I haven't tested it to be sure.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
]
| I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it.
I mainly use mingw/msys but would like something that works across other shells/systems too.
I tried this but it didn't work, any ideas?
```
ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif
``` | On UNIX Just use this:
```
mkdir -p $(OBJDIR)
```
The -p option to mkdir prevents the error message if the directory exists. |
99,161 | <p>I search for "nurple" in a file. I found it, great. But now, every occurrence of "nurple" is rendered in sick black on yellow. Forever.</p>
<p>Forever, that is, until I search for something I know won't be found, such as "asdhfalsdflajdflakjdf" simply so it clears the previous search highlighting.</p>
<p>Can't I just hit a magic key to kill the highlights when I'm done searching?</p>
| [
{
"answer_id": 99182,
"author": "Lee H",
"author_id": 18201,
"author_profile": "https://Stackoverflow.com/users/18201",
"pm_score": 9,
"selected": false,
"text": "<p><code>:noh</code> (short for <code>nohighlight</code>) will temporarily clear the search highlight. The next search will still be highlighted.</p>\n"
},
{
"answer_id": 99186,
"author": "Lucas S.",
"author_id": 7363,
"author_profile": "https://Stackoverflow.com/users/7363",
"pm_score": 9,
"selected": true,
"text": "<p>Just put this in your .vimrc</p>\n\n<pre><code>\" <Ctrl-l> redraws the screen and removes any search highlighting.\nnnoremap <silent> <C-l> :nohl<CR><C-l>\n</code></pre>\n"
},
{
"answer_id": 99196,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<pre>\n *:noh* *:nohlsearch*\n:noh[lsearch] Stop the highlighting for the 'hlsearch' option. It\n is automatically turned back on when using a search\n command, or setting the 'hlsearch' option.\n This command doesn't work in an autocommand, because\n the highlighting state is saved and restored when\n executing autocommands |autocmd-searchpat|.\n Same thing for when invoking a user function.\n</pre>\n\n<p>I found it just under <code>:help #</code>, which I keep hitting all the time, and which highlights all the words on the current page like the current one.</p>\n"
},
{
"answer_id": 99207,
"author": "Daniel Bruce",
"author_id": 6456,
"author_profile": "https://Stackoverflow.com/users/6456",
"pm_score": 4,
"selected": false,
"text": "<p>Append the following line to the end of your <code>.vimrc</code> to prevent highlighting altogether:</p>\n\n<pre><code>set nohlsearch\n</code></pre>\n"
},
{
"answer_id": 99208,
"author": "Jeffrey Vanneste",
"author_id": 5497,
"author_profile": "https://Stackoverflow.com/users/5497",
"pm_score": 2,
"selected": false,
"text": "<p>There is <code>hlsearch</code> and <code>nohlsearch</code>. <code>:help hlsearch</code> will provide more information.</p>\n\n<p>If you want to bind <kbd>F12</kbd> to toggle it on/off you can use this:</p>\n\n<pre><code>map <F12> :nohlsearch<CR>\nimap <F12> <ESC>:nohlsearch<CR>i\nvmap <F12> <ESC>:nohlsearch<CR>gv\n</code></pre>\n"
},
{
"answer_id": 99226,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 7,
"selected": false,
"text": "<p><code>/lkjasdf</code> has always been faster than <code>:noh</code> for me.</p>\n"
},
{
"answer_id": 99982,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 4,
"selected": false,
"text": "<p>Then I prefer this:</p>\n\n<pre><code>map <F12> :set hls!<CR>\nimap <F12> <ESC>:set hls!<CR>a\nvmap <F12> <ESC>:set hls!<CR>gv\n</code></pre>\n\n<p>And why? Because it <strong>toggles</strong> the switch: if highlight is on, then pressing <kbd>F12</kbd> turns it off. And vica versa. HTH.</p>\n"
},
{
"answer_id": 100141,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I search so often that I've found it useful to map the underscore key to remove the search highlight:</p>\n\n<pre><code>nnoremap <silent> _ :nohl<CR>\n</code></pre>\n"
},
{
"answer_id": 101756,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 2,
"selected": false,
"text": "<p>I have this in my .vimrc:</p>\n\n<pre><code>nnoremap ; :set invhlsearch<CR>\n</code></pre>\n\n<p>This way, <kbd>;</kbd> will toggle search highlighting. Normally, the <kbd>;</kbd> key repeats the latest t/T/f/F command, but I never really used that functionality. I find this setting much more useful, because I can change search highlighting on and off very quickly and can easily get a sense of where my search results are, at a glance.</p>\n"
},
{
"answer_id": 19865983,
"author": "Daniel Miessler",
"author_id": 500958,
"author_profile": "https://Stackoverflow.com/users/500958",
"pm_score": 2,
"selected": false,
"text": "<p>I think the best answer is to have a leader shortcut:</p>\n\n<pre><code><leader>c :nohl<CR>\n</code></pre>\n\n<p>Now whenever you have your document all junked up with highlighted terms, you just hit <kbd>,</kbd> + <kbd>C</kbd> (I have my leader mapped to a comma). It works perfectly.</p>\n"
},
{
"answer_id": 19877212,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 5,
"selected": false,
"text": "<pre><code>\" Make double-<Esc> clear search highlights\nnnoremap <silent> <Esc><Esc> <Esc>:nohlsearch<CR><Esc>\n</code></pre>\n"
},
{
"answer_id": 22807541,
"author": "nocache",
"author_id": 778675,
"author_profile": "https://Stackoverflow.com/users/778675",
"pm_score": 2,
"selected": false,
"text": "<p>I think this answer in \"<a href=\"https://stackoverflow.com/questions/657447/vim-clear-last-search-highlighting/657484#657484\">Vim clear last search highlighting</a>\" is better:</p>\n\n<pre><code>:let @/ = \"\"\n</code></pre>\n"
},
{
"answer_id": 23416923,
"author": "Aman Jain",
"author_id": 29405,
"author_profile": "https://Stackoverflow.com/users/29405",
"pm_score": -1,
"selected": false,
"text": "<p>I add the following mapping to my ~/.vimrc</p>\n\n<pre><code>map e/ /sdfdskfxxxxy\n</code></pre>\n\n<p>And in ESC mode, I press <code>e/</code></p>\n"
},
{
"answer_id": 24951879,
"author": "Guillaume",
"author_id": 857728,
"author_profile": "https://Stackoverflow.com/users/857728",
"pm_score": 0,
"selected": false,
"text": "<p>Also, if you want to have a toogle and be sure that the highlight will be reactivate for the next time you search something, you can use this</p>\n\n<pre><code>nmap <F12> :set hls!<CR>\nnnoremap / :set hls<CR>/\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
]
| I search for "nurple" in a file. I found it, great. But now, every occurrence of "nurple" is rendered in sick black on yellow. Forever.
Forever, that is, until I search for something I know won't be found, such as "asdhfalsdflajdflakjdf" simply so it clears the previous search highlighting.
Can't I just hit a magic key to kill the highlights when I'm done searching? | Just put this in your .vimrc
```
" <Ctrl-l> redraws the screen and removes any search highlighting.
nnoremap <silent> <C-l> :nohl<CR><C-l>
``` |
99,164 | <p>I often see code like:</p>
<pre><code>Iterator i = list.iterator();
while(i.hasNext()) {
...
}
</code></pre>
<p>but I write that (when Java 1.5 isn't available or for each can't be used) as:</p>
<pre><code>for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
</code></pre>
<p>because</p>
<ul>
<li>It is shorter</li>
<li>It keeps <code>i</code> in a smaller scope</li>
<li>It reduces the chance of confusion. (Is <code>i</code> used outside the
while? Where is <code>i</code> declared?)</li>
</ul>
<p>I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?</p>
<p>From: <a href="http://jamesjava.blogspot.com/2006/04/iterating.html" rel="noreferrer">http://jamesjava.blogspot.com/2006/04/iterating.html</a></p>
| [
{
"answer_id": 99177,
"author": "scubabbl",
"author_id": 9450,
"author_profile": "https://Stackoverflow.com/users/9450",
"pm_score": 0,
"selected": false,
"text": "<p>Either is fine. I use for () myself, and I don't know if there are compile issues. I suspect they both get optimized down to pretty much the same thing.</p>\n"
},
{
"answer_id": 99178,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 7,
"selected": true,
"text": "<p>I prefer the for loop because it also sets the scope of the iterator to just the for loop.</p>\n"
},
{
"answer_id": 99180,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>if you're only going to use the iterator once and throw it away, the second form is preferred; otherwise you must use the first form</p>\n"
},
{
"answer_id": 99189,
"author": "Giorgio Galante",
"author_id": 18269,
"author_profile": "https://Stackoverflow.com/users/18269",
"pm_score": 3,
"selected": false,
"text": "<p>Why not use the for-each construct? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too):</p>\n\n<pre><code>List<String> names = new ArrayList<String>();\nnames.add(\"a\");\nnames.add(\"b\");\nnames.add(\"c\");\n\nfor (String name : names)\n System.out.println(name.charAt(0));\n</code></pre>\n"
},
{
"answer_id": 99194,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 1,
"selected": false,
"text": "<p>I would agree that the \"for\" loop is clearer and more appropriate when iterating.</p>\n\n<p>The \"while\" loop is appropriate for polling, or where the number of loops to meet exit condition will change based on activity inside the loop.</p>\n"
},
{
"answer_id": 99215,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 2,
"selected": false,
"text": "<p>I think scope is the biggest issue here, as you have pointed out.</p>\n\n<p>In the \"while\" example, the iterator is declared outside the loop, so it will continue to exist after the loop is done. This may cause issues if this same iterator is used again at some later point. E. g. you may forget to initialize it before using it in another loop.</p>\n\n<p>In the \"for\" example, the iterator is declared inside the loop, so its scope is limited to the loop. If you try to use it after the loop, you will get a compiler error.</p>\n"
},
{
"answer_id": 99220,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 0,
"selected": false,
"text": "<p>Although both are really fine, I tend to use the first example because it is easier to read. </p>\n\n<p>There are fewer operations happening on each line with the while() loop, making the code easier for someone new to the code to understand what's going on.</p>\n\n<p>That type of construct also allows me to group initializations in a common location (at the top of the method) which also simplifies commenting for me, and conceptualization for someone reading it for the first time.</p>\n"
},
{
"answer_id": 99228,
"author": "Svet",
"author_id": 8934,
"author_profile": "https://Stackoverflow.com/users/8934",
"pm_score": 0,
"selected": false,
"text": "<p>I agree that the for loop should be used whenever possible but sometimes there's more complex logic that controls the iterator in the body of the loop. In that case you have to go with while.</p>\n"
},
{
"answer_id": 99246,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 4,
"selected": false,
"text": "<p>There are appropriate uses for the while, the for, and the foreach constructs:</p>\n\n<ul>\n<li><p><code>while</code> - Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition</p></li>\n<li><p><code>for</code> - Use this if you are looping and your primary concern is the index of the array/collection/list. It is more useful to use a for if you are most likely to go through <em>all</em> the elements anyway, and in a particular order (e.g., going backwards through a sorted list, for example).</p></li>\n<li><p><code>foreach</code> - Use this if you merely need to go through your collection regardless of order.</p></li>\n</ul>\n\n<p>Obviously there are exceptions to the above, but that's the general rule I use when deciding to use which. That being said I tend to use <code>foreach</code> more often.</p>\n"
},
{
"answer_id": 99273,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I was the for loop for clarity. While I use the <em>while loop</em> when faced with some undeterministic condition.</p>\n"
},
{
"answer_id": 99303,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 1,
"selected": false,
"text": "<p>Not that it probably matters in this case, but Compilers, VMs and CPU's normally have special optimization techniques they user under the hood that will make for loops performance better (and in the near future parallel), in general they don't do that with while loops (because its harder to determine how it's actually going to run). But in most cases code clarity should trump optimization.</p>\n"
},
{
"answer_id": 101271,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 0,
"selected": false,
"text": "<p>Both are fine, but remember that sometimes access to the Iterator directly is useful (such as if you are removing elements that match a certain condition - you will get a ConcurrentModificationException if you do collection.remove(o) inside a for(T o : collection) loop).</p>\n\n<p>I prefer to write the for(blah : blah) [foreach] syntax almost all of the time because it seems more naturally readable to me. The concept of iterators in general don't really have parallels outside of programming</p>\n"
},
{
"answer_id": 101321,
"author": "James Muscat",
"author_id": 11643,
"author_profile": "https://Stackoverflow.com/users/11643",
"pm_score": 0,
"selected": false,
"text": "<p>Academia tends to prefer the while-loop as it makes for less complicated reasoning about programs. I tend to prefer the for- or foreach-loop structures as they make for easier-to-read code.</p>\n"
},
{
"answer_id": 8435741,
"author": "Igor Vaschuk",
"author_id": 154664,
"author_profile": "https://Stackoverflow.com/users/154664",
"pm_score": 2,
"selected": false,
"text": "<p>IMHO, the <strong>for</strong> loop is less readable in this scenario, if you look at this code from the perspective of English language. I am working on a code where author does abuse <strong>for</strong> loop, and it ain't pretty. Compare following:</p>\n\n<pre><code>for (; (currUserObjectIndex < _domainObjectReferences.Length) && (_domainObjectReferences[currUserObjectIndex].VisualIndex == index); ++currUserObjectIndex)\n ++currNumUserObjects;\n</code></pre>\n\n<p>vs </p>\n\n<pre><code>while (currUserObjectIndex < _domainObjectReferences.Length && _domainObjectReferences[currUserObjectIndex].VisualIndex == index)\n{\n ++currNumUserObjects;\n ++currUserObjectIndex;\n}\n</code></pre>\n"
},
{
"answer_id": 20952127,
"author": "Abhishek Kaushik",
"author_id": 2447909,
"author_profile": "https://Stackoverflow.com/users/2447909",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Using for loop you can work with a single variable, as it sets the scope of variable for a current working for loop only. However this is not possible in while loop</strong>.\nFor Example:<br>\nint i; for(i=0; in1;i++) do something.. </p>\n\n<p>for(i=0;i n2;i+=2) do something. </p>\n\n<p>So after 1st loop i=n1-1 at the end. But while using second loop you can set i again to 0. \n <strong>However</strong> </p>\n\n<p>int i=0; </p>\n\n<p>while(i less than limit) { do something ..; i++; }</p>\n\n<p>Hence i is set to limit-1 at the end. So you cant use same i in another while loop.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| I often see code like:
```
Iterator i = list.iterator();
while(i.hasNext()) {
...
}
```
but I write that (when Java 1.5 isn't available or for each can't be used) as:
```
for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
```
because
* It is shorter
* It keeps `i` in a smaller scope
* It reduces the chance of confusion. (Is `i` used outside the
while? Where is `i` declared?)
I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?
From: <http://jamesjava.blogspot.com/2006/04/iterating.html> | I prefer the for loop because it also sets the scope of the iterator to just the for loop. |
99,211 | <p>I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an <code>aplication.html.haml</code> or <code>index.html.haml</code> for a view, I just receive errors.</p>
<p>I am using NetBeans as my IDE.</p>
| [
{
"answer_id": 105542,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 5,
"selected": false,
"text": "<p>First, <strong>install haml</strong> as a gem in bundler by adding this to your <code>Gemfile</code>:</p>\n\n<pre><code>gem \"haml\"\n</code></pre>\n\n<p>Run <code>bundle install</code>, then make sure your views are named with a <strong>*.html.haml</strong> extension. For example:</p>\n\n<pre><code>`-- app\n `-- views\n |-- layouts\n | `-- application.html.haml\n `-- users\n |-- edit.html.haml\n |-- index.html.haml\n |-- new.html.haml\n `-- show.html.haml\n</code></pre>\n"
},
{
"answer_id": 106547,
"author": "Pete",
"author_id": 13472,
"author_profile": "https://Stackoverflow.com/users/13472",
"pm_score": 3,
"selected": false,
"text": "<p>First, make sure you have the HAML gem. </p>\n\n<pre><code>gem list --local | grep haml\n</code></pre>\n\n<p>If haml doesn't show up in the list, then do this: </p>\n\n<pre><code>sudo gem install haml\n</code></pre>\n\n<p>Then do this from your project directory: </p>\n\n<pre><code># cd ../\n# haml --rails <yourproject>\n</code></pre>\n\n<p>That should install everything you need, and the HAML views should stop complaining and parse correctly. </p>\n"
},
{
"answer_id": 774022,
"author": "gdelfino",
"author_id": 93947,
"author_profile": "https://Stackoverflow.com/users/93947",
"pm_score": 4,
"selected": false,
"text": "<p>Before trying to use haml in your rails application, you can verify that the command line executable is installed correctly:</p>\n\n<pre><code>$ haml\n%p \n %span Hello World!\n</code></pre>\n\n<p>Then press CTRL-D and you should see:</p>\n\n<pre><code><p>\n <span>Hello World!</span>\n</p>\n</code></pre>\n"
},
{
"answer_id": 1610001,
"author": "railsuser1984",
"author_id": 194909,
"author_profile": "https://Stackoverflow.com/users/194909",
"pm_score": 1,
"selected": false,
"text": "<p>if for some reason you installed haml, but you haml doesn't start. try </p>\n\n<pre><code>sudo ln haml /usr/bin/\n</code></pre>\n\n<p>in the bin directory of your haml gem</p>\n\n<p>for some reason this didn't happen automatically on my ubuntu 9.04 Jaunty.</p>\n"
},
{
"answer_id": 2888046,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 6,
"selected": false,
"text": "<h2>Haml with Rails 3</h2>\n\n<p>For Rails 3 all you need to do is add <code>gem \"haml\", '3.0.25'</code> to your <code>Gemfile</code>. No need to install plugin or run <code>haml --rails .</code>.</p>\n\n<p>Just:</p>\n\n<pre>\n$ cd awesome-rails-3-app.git\n$ echo 'gem \"haml\"' >> Gemfile\n</pre>\n\n<p>And you're done.</p>\n"
},
{
"answer_id": 5034759,
"author": "bowsersenior",
"author_id": 457819,
"author_profile": "https://Stackoverflow.com/users/457819",
"pm_score": 6,
"selected": false,
"text": "<p>The answers above are spot-on. You just need to put <code>gem 'haml'</code> in your <code>Gemfile</code>. </p>\n\n<p>One other tip that was not mentioned: to have rails generators use <code>haml</code> instead of <code>erb</code>, add the following to <code>config/application.rb</code>:</p>\n\n<pre><code>config.generators do |g|\n g.template_engine :haml\n\n # you can also specify a different test framework or ORM here\n # g.test_framework :rspec\n # g.orm :mongoid\nend \n</code></pre>\n"
},
{
"answer_id": 10460681,
"author": "thd",
"author_id": 586981,
"author_profile": "https://Stackoverflow.com/users/586981",
"pm_score": 2,
"selected": false,
"text": "<p>This may be an old question but I think the answer is using haml-rails at <a href=\"https://github.com/indirect/haml-rails\" rel=\"nofollow\">https://github.com/indirect/haml-rails</a></p>\n"
},
{
"answer_id": 10503861,
"author": "Matthias",
"author_id": 600104,
"author_profile": "https://Stackoverflow.com/users/600104",
"pm_score": 5,
"selected": false,
"text": "<p>Add haml to your Gemfile:</p>\n\n<pre><code>gem \"haml\"\n</code></pre>\n\n<p>If you want to use the scaffold-functions too, add haml-rails within your development-group:</p>\n\n<pre><code>gem 'haml-rails', :group => :development\n</code></pre>\n\n<p>Don't forget to run:</p>\n\n<pre><code>$ bundle install\n</code></pre>\n"
},
{
"answer_id": 10509600,
"author": "chris raethke",
"author_id": 43672,
"author_profile": "https://Stackoverflow.com/users/43672",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using <a href=\"http://pow.cx/\" rel=\"nofollow\">Pow</a> you will need to restart it also. Ideally you are using <a href=\"http://rubygems.org/gems/powder\" rel=\"nofollow\">powder</a> (gem install powder), because then you can just run this at the terminal</p>\n\n<pre><code>$ powder restart\n</code></pre>\n"
},
{
"answer_id": 62284685,
"author": "hsul4n",
"author_id": 8009543,
"author_profile": "https://Stackoverflow.com/users/8009543",
"pm_score": 0,
"selected": false,
"text": "<p>make sure to add <code>haml</code> gem into your <code>Gemfile</code></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an `aplication.html.haml` or `index.html.haml` for a view, I just receive errors.
I am using NetBeans as my IDE. | Haml with Rails 3
-----------------
For Rails 3 all you need to do is add `gem "haml", '3.0.25'` to your `Gemfile`. No need to install plugin or run `haml --rails .`.
Just:
```
$ cd awesome-rails-3-app.git
$ echo 'gem "haml"' >> Gemfile
```
And you're done. |
99,279 | <p>I want to parse a web page in Groovy and extract all of the href links and the associated text with it.</p>
<p>If the page contained these links:</p>
<pre><code><a href="http://www.google.com">Google</a><br />
<a href="http://www.apple.com">Apple</a>
</code></pre>
<p>the output would be:</p>
<pre><code>Google, http://www.google.com<br />
Apple, http://www.apple.com
</code></pre>
<p>I'm looking for a Groovy answer. AKA. The easy way!</p>
| [
{
"answer_id": 99293,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 2,
"selected": false,
"text": "<p>A quick google search turned up a nice looking possibility, <a href=\"http://blog.foosion.org/2008/06/09/parse-html-the-groovy-way/\" rel=\"nofollow noreferrer\">TagSoup</a>.</p>\n"
},
{
"answer_id": 99362,
"author": "J D OConal",
"author_id": 17023,
"author_profile": "https://Stackoverflow.com/users/17023",
"pm_score": 0,
"selected": false,
"text": "<p>Try a regular expression. Something like this should work:</p>\n\n<pre><code>(html =~ /<a.*href='(.*?)'.*>(.*?)<\\/a>/).each { url, text -> \n // do something with url and text\n}\n</code></pre>\n\n<p>Take a look at <a href=\"http://groovy.codehaus.org/Tutorial+4+-+Regular+expressions+basics\" rel=\"nofollow noreferrer\">Groovy - Tutorial 4 - Regular expressions basics</a> and <a href=\"http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx\" rel=\"nofollow noreferrer\">Anchor Tag Regular Expression Breaking</a>.</p>\n"
},
{
"answer_id": 99436,
"author": "Peter Kelley",
"author_id": 14893,
"author_profile": "https://Stackoverflow.com/users/14893",
"pm_score": 1,
"selected": false,
"text": "<p>Use XMLSlurper to parse the HTML as an XML document and then use the find method with an appropriate closure to select the a tags and then use the list method on GPathResult to get a list of the tags. You should then be able to extract the text as children of the GPathResult.</p>\n"
},
{
"answer_id": 100197,
"author": "yann.kmm",
"author_id": 15780,
"author_profile": "https://Stackoverflow.com/users/15780",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know java but I think that xpath is far better than classic regular expressions in order to get one (or more) html elements.</p>\n\n<p>It is also easier to write and to read.</p>\n\n<pre><code><html>\n <body>\n <a href=\"1.html\">1</a>\n <a href=\"2.html\">2</a>\n <a href=\"3.html\">3</a>\n </body>\n</html>\n</code></pre>\n\n<p>With the html above, this expression \"/html/body/a\" will list all href elements.</p>\n\n<p>Here's a good step by step tutorial <a href=\"http://www.zvon.org/xxl/XPathTutorial/General/examples.html\" rel=\"nofollow noreferrer\">http://www.zvon.org/xxl/XPathTutorial/General/examples.html</a></p>\n"
},
{
"answer_id": 163795,
"author": "John Flinchbaugh",
"author_id": 12591,
"author_profile": "https://Stackoverflow.com/users/12591",
"pm_score": 5,
"selected": true,
"text": "<p>Assuming well-formed XHTML, slurp the xml, collect up all the tags, find the 'a' tags, and print out the href and text.</p>\n\n<pre><code>input = \"\"\"<html><body>\n<a href = \"http://www.hjsoft.com/\">John</a>\n<a href = \"http://www.google.com/\">Google</a>\n<a href = \"http://www.stackoverflow.com/\">StackOverflow</a>\n</body></html>\"\"\"\n\ndoc = new XmlSlurper().parseText(input)\ndoc.depthFirst().collect { it }.findAll { it.name() == \"a\" }.each {\n println \"${it.text()}, ${[email protected]()}\"\n}\n</code></pre>\n"
},
{
"answer_id": 163874,
"author": "Prog",
"author_id": 23890,
"author_profile": "https://Stackoverflow.com/users/23890",
"pm_score": -1,
"selected": false,
"text": "<p>Html parser + Regular expressions\nAny language would do it, though I'd say Perl is the fastest solution.</p>\n"
},
{
"answer_id": 10024482,
"author": "Sree",
"author_id": 1294908,
"author_profile": "https://Stackoverflow.com/users/1294908",
"pm_score": 0,
"selected": false,
"text": "<p>Parsing using XMlSlurper only works if HTMl is well-formed.</p>\n\n<p>If your HTMl page has non-well-formed tags, then use regex for parsing the page.</p>\n\n<p>Ex: <code><a href=\"www.google.com\"></code></p>\n\n<p>here, 'a' is not closed and thus not well formed.</p>\n\n<pre><code> new URL(url).eachLine{\n (it =~ /.*<A HREF=\"(.*?)\">/).each{\n // process hrefs\n }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to parse a web page in Groovy and extract all of the href links and the associated text with it.
If the page contained these links:
```
<a href="http://www.google.com">Google</a><br />
<a href="http://www.apple.com">Apple</a>
```
the output would be:
```
Google, http://www.google.com<br />
Apple, http://www.apple.com
```
I'm looking for a Groovy answer. AKA. The easy way! | Assuming well-formed XHTML, slurp the xml, collect up all the tags, find the 'a' tags, and print out the href and text.
```
input = """<html><body>
<a href = "http://www.hjsoft.com/">John</a>
<a href = "http://www.google.com/">Google</a>
<a href = "http://www.stackoverflow.com/">StackOverflow</a>
</body></html>"""
doc = new XmlSlurper().parseText(input)
doc.depthFirst().collect { it }.findAll { it.name() == "a" }.each {
println "${it.text()}, ${[email protected]()}"
}
``` |
99,285 | <p>Would it be useful to be able to mark objects where the value ofString.valueOf() would included in any stack trace. In my example below I used "trace". Variables that aren't declared at the point of the stack trace would just be ingored.
It would make debugging much easier and make it much easier to write programs that are easy to debug.</p>
<p>Example stack trace for the code below:</p>
<pre><code>java.lang.NullPointerException:
at Test.main(Test.java:7) index=0, sum=3, obj=null
public class Test {
Object obj;
public void main(String[] args) trace obj {
trace int sum = 0;
for(trace int index = 0; index < args.length; index++) {
sum += Integer.parseInt(args[index]);
sum += obj.hashCode();//Will cause NullPointerException
}
}
}
</code></pre>
<p>From: <a href="http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html</a></p>
| [
{
"answer_id": 99385,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>this might be useful, but i think it clutters the code - presumably when the code is working you would want to remove the 'trace' keywords; perhaps some form of metadata would be more appropriate</p>\n\n<p>then there's always print statements...</p>\n"
},
{
"answer_id": 99400,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it can be quite useful. I often do this kind of thing myself, but I only have it compile into non-production code, usually.</p>\n"
},
{
"answer_id": 99435,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "<p>What I'd love is a property of the exception which would be a string array of all the method signatures leading up to the throw... without having to parse it out of the Exception text.</p>\n"
},
{
"answer_id": 99513,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>The Visual Studio C# debugger's call stack window includes a stack trace with all the argument values displayed.</p>\n"
},
{
"answer_id": 101969,
"author": "18Rabbit",
"author_id": 12662,
"author_profile": "https://Stackoverflow.com/users/12662",
"pm_score": 0,
"selected": false,
"text": "<p>Eh. Personally I don't think it would be that useful. If I'm running my code and hitting exceptions I can more easily set a breakpoint and step into the code and see what all of the variables are at that point and figure out where it's really breaking. </p>\n\n<p>Using this trace method not only would I have to keep adding and removing keywords from in front of variables as I worked on different bugs but I don't think that it would be any real improvement over just adding good logging/debugging messaging (which is much easier to remove or disable when pushed to production).</p>\n"
},
{
"answer_id": 104593,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 1,
"selected": false,
"text": "<p>Tempting, but I don't think this feature warrants a new keyword in Java (and that much more complexity in the language). </p>\n\n<p>I've found the use of Throwable.printStackTrace has usually been plenty to quickly point to the problems that need my attention.</p>\n"
},
{
"answer_id": 1026056,
"author": "GaZ",
"author_id": 62667,
"author_profile": "https://Stackoverflow.com/users/62667",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps I'm missing the point, but why not use a proper logging framework (e.g. Log4j)? Then you can use nested / mapped diagnostic contexts (<a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html\" rel=\"nofollow noreferrer\">NDC</a> / <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html\" rel=\"nofollow noreferrer\">MDC</a>) for outputting variable values.</p>\n"
},
{
"answer_id": 1026108,
"author": "akarnokd",
"author_id": 61158,
"author_profile": "https://Stackoverflow.com/users/61158",
"pm_score": 1,
"selected": false,
"text": "<p>I would rather prefer a standard (annotation based) way of describing the programmers intent for nullness (FindBugs, JSR 305). I once considered having not just the line number, but the column number included in the exception message so in long chained invocations you could easier see which dot operator caused the NPE. As stated by others in NPE related questions here on StackOverflow, in most cases you get NPE from trying to access a field/method on a null object.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| Would it be useful to be able to mark objects where the value ofString.valueOf() would included in any stack trace. In my example below I used "trace". Variables that aren't declared at the point of the stack trace would just be ingored.
It would make debugging much easier and make it much easier to write programs that are easy to debug.
Example stack trace for the code below:
```
java.lang.NullPointerException:
at Test.main(Test.java:7) index=0, sum=3, obj=null
public class Test {
Object obj;
public void main(String[] args) trace obj {
trace int sum = 0;
for(trace int index = 0; index < args.length; index++) {
sum += Integer.parseInt(args[index]);
sum += obj.hashCode();//Will cause NullPointerException
}
}
}
```
From: <http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html> | this might be useful, but i think it clutters the code - presumably when the code is working you would want to remove the 'trace' keywords; perhaps some form of metadata would be more appropriate
then there's always print statements... |
99,315 | <p>What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:</p>
<pre><code>String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
</code></pre>
<ol>
<li>Would that be possible?</li>
<li>Would that be beneficial?</li>
<li>Do any languages currently support both and how well does it work out?</li>
</ol>
<p>Here is a better example (generics can't be used but the program does know the type):</p>
<pre><code>var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
</code></pre>
| [
{
"answer_id": 99333,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 1,
"selected": false,
"text": "<p>Can you explain the difference between your example and</p>\n\n<pre><code>String str = \"Hello\";\nObject temp = str;\ntemp = 10;\n</code></pre>\n"
},
{
"answer_id": 99373,
"author": "Thelema",
"author_id": 12874,
"author_profile": "https://Stackoverflow.com/users/12874",
"pm_score": 0,
"selected": false,
"text": "<p>Dynamic typed variables just have type <strong>Universal</strong>, such that every other type is a subtype of <strong>Universal</strong>. Any language where all types inherit from such a universal type (such as Java modulo unboxed values) already have this capability. As for usefulness - depends on what you're doing. I prefer a fully static type system where it's easy to create safe tagged unions so I can put whatever values I need into a variable, but in a more controlled way than <strong>Universal</strong>.</p>\n"
},
{
"answer_id": 99376,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it would be beneficial, but not for the example you are showing. I think something like this would be better</p>\n\n<pre><code>public void f(var o)\n{\n o.method();\n}\n</code></pre>\n\n<p>and I could call f with any object with a method called method() without needing to introduce an interface. It's nice for places where there is a convention, but not necessarily an interface. It would also be useful for interop with languages with a dynamic dispatch.</p>\n"
},
{
"answer_id": 99392,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 2,
"selected": false,
"text": "<p>C# has a \"var\" keyword used in the manner you describe, but it ends up being a strongly typed variable based on the types of values that type checking suggests will go into it.</p>\n"
},
{
"answer_id": 100265,
"author": "Das",
"author_id": 17585,
"author_profile": "https://Stackoverflow.com/users/17585",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>Would that be possible?<br>\nHardly. Java is a C-like language, which was initially designed to support only static typing. It will take a lot of time to introduce this feature to Java and I don't think developers will spend time on that.</li>\n<li>Would that be beneficial?<br>\nNo. Java is a traditional language, and static typing is one of the base principles or it's architecture. In fact, static-typing is still more popular in programming (you can check the interesting statistics <a href=\"http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html\" rel=\"nofollow noreferrer\">here</a>).</li>\n<li>Do any languages currently support that and how well does it work out?<br>\nWell, there are a lot of languages which support dynamic typing, but I guess you know this. If the language supports dynamic typing, it doesn't make sense to introduce static typing to this language...</li>\n</ol>\n\n<p>Also, feature which you show in your example can be implemented with static typing. jon gave you an example with \"Object\" class in Java. You can do similar with void* in C/C++. Still, this doesn't make language dynamic-typed.</p>\n"
},
{
"answer_id": 100366,
"author": "jb.",
"author_id": 7918,
"author_profile": "https://Stackoverflow.com/users/7918",
"pm_score": 0,
"selected": false,
"text": "<p>@Lou: It would be just syntactic sugar for:</p>\n\n<pre><code>void doSth(Object foo) throws Exception{\n Method m = foo.getClass().getMethod(\"foo\", String.class);\n m.invoke(foo, \"baz\"); \n}\n</code></pre>\n\n<p>I do use reflection, but I prefer it to be ugly so it's not abused. </p>\n"
},
{
"answer_id": 5057555,
"author": "mikera",
"author_id": 214010,
"author_profile": "https://Stackoverflow.com/users/214010",
"pm_score": 0,
"selected": false,
"text": "<p>Dynamic typing certainly has its uses.</p>\n\n<p>However, I don't think it would make sense adding this to Java - Java is designed as a statically typed language and it would be too large a philosophical and architectural shift to try and graft on dynamic types at this point.</p>\n\n<p>If you want proper dynamic typing but\n still want to be part of the Java\n ecosystem, take a look at one of the\n other great JVM languages that\n supports dynamic typing: e.g. Clojure\n and Groovy.</p>\n"
},
{
"answer_id": 5057902,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 0,
"selected": false,
"text": "<p>Dynamically typed languages make coding somewhat simpler and faster, but they do so at the cost of pushing bugs from compile-time (very easy to find) to run-time (hard to find and unpredictable). If Java introduced it and it became prevalent, I would look for another language that cared more about code quality, and my time.</p>\n\n<p>I'm doing a lot of Flex development at work as a front end to my Java work, and it frustrates me to no end that when I am working on a Flex method with parameters, most of the time the developer used Object for the parameter type, and I have absolutely no idea what properties/methods it will have without running the program with breakpoints and hoping I've tested all possible calls to the method. And even when they used a specific class for the parameter, there's no saying that properties/methods haven't been added or deleted from it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:
```
String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
```
1. Would that be possible?
2. Would that be beneficial?
3. Do any languages currently support both and how well does it work out?
Here is a better example (generics can't be used but the program does know the type):
```
var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
``` | C# has a "var" keyword used in the manner you describe, but it ends up being a strongly typed variable based on the types of values that type checking suggests will go into it. |
99,318 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby">What does map(&:name) mean in Ruby?</a> </p>
</blockquote>
<p>I was watching a railscast and saw this code.</p>
<pre><code>[Category, Product].(&:delete_all)
</code></pre>
<p>In regards to clearing a database.</p>
<p>I asked about the line in IRC and was told </p>
<pre><code>(&:delete_all)
</code></pre>
<p>was a shortcut for </p>
<pre><code>{|model| model.delete_all}
</code></pre>
<p>I tested this with the following</p>
<pre><code>class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
</code></pre>
<p>I received an error saying</p>
<pre><code>Wrong Argument type Symbol (expected Proc)
</code></pre>
<p>I also tried</p>
<pre><code>one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
</code></pre>
<p>But that still failed.</p>
<p>If I modified it to read</p>
<pre><code>[one, two].each{|model| model.class_method}
</code></pre>
<p>Everything worked as expected.</p>
<p>So, what does <code>&:delete_all</code> actually do? The docs say <code>delete_all</code> is a method, so I am confused as to what is going on here.</p>
| [
{
"answer_id": 99336,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 5,
"selected": true,
"text": "<p>This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:</p>\n\n<pre><code>class Symbol\n def to_proc\n proc { |obj, *args| obj.send(self, *args) }\n end\nend\n</code></pre>\n\n<p>I believe Rails defines this in <code>ActiveSupport</code>.</p>\n"
},
{
"answer_id": 99345,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 2,
"selected": false,
"text": "<p>It's some Rails specific patching of Ruby, <a href=\"http://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand\" rel=\"nofollow noreferrer\">symbol to proc</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
]
| >
> **Possible Duplicate:**
>
> [What does map(&:name) mean in Ruby?](https://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby)
>
>
>
I was watching a railscast and saw this code.
```
[Category, Product].(&:delete_all)
```
In regards to clearing a database.
I asked about the line in IRC and was told
```
(&:delete_all)
```
was a shortcut for
```
{|model| model.delete_all}
```
I tested this with the following
```
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
```
I received an error saying
```
Wrong Argument type Symbol (expected Proc)
```
I also tried
```
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
```
But that still failed.
If I modified it to read
```
[one, two].each{|model| model.class_method}
```
Everything worked as expected.
So, what does `&:delete_all` actually do? The docs say `delete_all` is a method, so I am confused as to what is going on here. | This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
```
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
```
I believe Rails defines this in `ActiveSupport`. |
99,350 | <p>Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:</p>
<pre><code>$items = array("1", "2",
array(
"item3.1" => "3.1",
"item3.2" => "3.2"
"isawesome" => true
)
);
</code></pre>
<p>How would I turn it into something similar to the following XML in as few lines as possible, then back again?</p>
<pre><code><items>
<item>1</item>
<item>2</item>
<item>
<item3_1>3.1</item3_1>
<item3_2>3.2</item3_2>
<isawesome>true</isawesome>
</item>
</items>
</code></pre>
<p>I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's <a href="http://php.net/manual/en/book.xmlreader.php" rel="noreferrer">XMLReader</a> and <a href="http://php.net/manual/en/book.xmlwriter.php" rel="noreferrer">XMLWriter</a>, but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:</p>
<pre><code>$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);
</code></pre>
<p>Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?</p>
<p>I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it.</p>
| [
{
"answer_id": 99367,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 2,
"selected": false,
"text": "<p>Have you seen the PEAR package XML_Serializer?</p>\n\n<p><a href=\"http://pear.php.net/package/XML_Serializer\" rel=\"nofollow noreferrer\">pear_php_XML_Serializer</a></p>\n"
},
{
"answer_id": 99378,
"author": "Oddmund",
"author_id": 4417,
"author_profile": "https://Stackoverflow.com/users/4417",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://php.net/simplexml\" rel=\"noreferrer\">SimpleXML</a> works great for your use.</p>\n"
},
{
"answer_id": 99674,
"author": "Eduardo Marinho",
"author_id": 13211,
"author_profile": "https://Stackoverflow.com/users/13211",
"pm_score": 2,
"selected": false,
"text": "<p>Try Zend_Config and Zend Framework in general. </p>\n\n<p>I imagine it would be a 2 step process: array to Zend_Config, Zend_Config to XML.</p>\n"
},
{
"answer_id": 100287,
"author": "DreamWerx",
"author_id": 15487,
"author_profile": "https://Stackoverflow.com/users/15487",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like a job for SimpleXML. </p>\n\n<p>I would suggest a slightly different XML structure.. </p>\n\n<p>And wonder why you need to convert from an array -> XML and back.. If you can modify the array structure as you said why not just generate XML instead? If some piece of code already exists that takes that array configuration, just modify it to accept the XML instead. Then you have 1 data format/ input type, and don't need to convert at all..</p>\n\n<pre><code><items>\n <item id=\"1\"/>\n <item id=\"2\"/>\n <item id=\"3\">\n <subitems> \n <item id=\"3.1\"/>\n <item id=\"3.2\" isawesome=\"true\"/>\n </subitems>\n </item>\n</items>\n</code></pre>\n"
},
{
"answer_id": 100377,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 1,
"selected": false,
"text": "<p>I agree this is one area that PHP's documentation has dropped the ball, but for me I've always used the SimpleXML mixed with something like the xml2Array functions. The Xml you get from simpleXML isn't that hard to navigate with the help of a dumping function like print_r.</p>\n"
},
{
"answer_id": 125761,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've had some of these same issues, and so I created two classes:</p>\n\n<p><strong>bXml</strong></p>\n\n<p>A class that extends SimpleXml and corrects some of the problems it has. Like not being able to add CData nodes or Comment nodes. I also added some additional features, like using the php streams functionality to add child nodes <code>$oXml->AddChild(\"file:///user/data.xml\")</code> or add XML string child nodes like <code>$oXml->AddChild(\"<more><xml>yes</xml></more>\");</code> but basically I just wanted to fix the simpleXML problems.</p>\n\n<p><strong>bArray</strong></p>\n\n<p>I extended the ArrayObject class so that all array functionality could be object oriented and consistent, so you don't need to remember that array_walk operates on the array by reference, while array_filter operates on the array by value. So you can do things like <code>$oArray->flip()->Reverse()->Walk(/*callback*/);</code> then still access the value the same way you normally would like <code>$oArray[key]</code>.</p>\n\n<p>Both of the methods output themselves as Arrays and Xml so you can jump seamlessly between them. So you can <code>$oXml->AsArray();</code> or <code>$oArray->AsXml();</code> I found that it was easier to do this than to constantly pass things back and forth between array2xml or xml2array methods.</p>\n\n<p><a href=\"http://code.google.com/p/blibrary/source/browse/#svn/trunk/classes\" rel=\"nofollow noreferrer\">http://code.google.com/p/blibrary/source</a></p>\n\n<p>Both classes are can be overridden to make a custom class of your choosing and can be used independently of one another.</p>\n"
},
{
"answer_id": 633483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Following class uses simplexml to achieve the same, you just need to loop through the array and call addchild of ximplexml.</p>\n\n<p><a href=\"http://snipplr.com/view.php?codeview&id=3491\" rel=\"nofollow noreferrer\">http://snipplr.com/view.php?codeview&id=3491</a></p>\n"
},
{
"answer_id": 1243839,
"author": "Conrad",
"author_id": 131678,
"author_profile": "https://Stackoverflow.com/users/131678",
"pm_score": 4,
"selected": true,
"text": "<p>For those of you not using the PEAR packages, but you've got PHP5 installed. This worked for me: </p>\n\n<pre><code>/**\n * Build A XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default fx_request\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\npublic function buildXMLData($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8') {\n if(!is_array($data)) {\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($xml_version, $xml_encoding);\n $xml->startElement($startElement);\n\n /**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n function write(XMLWriter $xml, $data) {\n foreach($data as $key => $value) {\n if(is_array($value)) {\n $xml->startElement($key);\n write($xml, $value);\n $xml->endElement();\n continue;\n }\n $xml->writeElement($key, $value);\n }\n }\n write($xml, $data);\n\n $xml->endElement();//write end element\n //Return the XML results\n return $xml->outputMemory(true); \n}\n</code></pre>\n"
},
{
"answer_id": 6237999,
"author": "gskluzacek",
"author_id": 784078,
"author_profile": "https://Stackoverflow.com/users/784078",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a function that I wrote to take XML and converts it to a PHP Associative Array. One Caveat is that id does not currently handle attributes or c-data. Though it will handle repeated XML Tag at the same level by placing them into an array named after the tag.</p>\n\n<pre><code>\n<?php\n\n$xml_req1 = <<<XML\n<?xml version=\"1.0\"?>\n<Vastera:CustomerValidation_RequestInfo\n xmlns:Vastera=\"http://ndc-ah-prd.am.mot.com:10653/MotVastera_CustomerValidation/MC000078/Docs/\">\n <PartnerID>5550000100-003</PartnerID>\n <PartnerType>PTNR_INTER_CONSIGNEE</PartnerType>\n <OperatingUnit>100</OperatingUnit>\n <Status>ACTIVE</Status>\n <CustomerSeqNumber>111</CustomerSeqNumber>\n <CustomerName>Greg Co</CustomerName>\n <Address1>123 Any Ln</Address1>\n <Address2>?</Address2>\n <Address3>?</Address3>\n <Address4>?</Address4>\n <Address5>?</Address5>\n <City>Someplace</City>\n <PostalCode>603021</PostalCode>\n <State>CA</State>\n <CountryCode>US</CountryCode>\n <TaxReference>222</TaxReference>\n <PartyRelated>Y</PartyRelated>\n <BusinessUnit>GSBU</BusinessUnit>\n <Region>GSRGN</Region>\n <LocationName>DBA Mac Head Computing</LocationName>\n <LoadOnly>N</LoadOnly>\n <VSTM>333</VSTM>\n <MilitaryCustomerFlag>Y</MilitaryCustomerFlag>\n <USFederalGovernmentCustomer>Y</USFederalGovernmentCustomer>\n <Non-USGovernmentCustomer>Y</Non-USGovernmentCustomer>\n <Vastera:EPCIActivity>\n <EPCIActivityNuclearCode>NUCLEAR</EPCIActivityNuclearCode>\n <EPCIActivityNuclearValue>N</EPCIActivityNuclearValue>\n <EPCIActivityNuclearApproveDate>2011-05-16:07:19:37</EPCIActivityNuclearApproveDate>\n <EPCIActivityNuclearExpireDate>2056-12-31:12:00:00</EPCIActivityNuclearExpireDate>\n <EPCIActivityNuclearCountry>US</EPCIActivityNuclearCountry>\n <EPCIActivityChemBioCode>CHEM_BIO</EPCIActivityChemBioCode>\n <EPCIActivityChemBioValue>N</EPCIActivityChemBioValue>\n <EPCIActivityChemBioApproveDate>2011-05-16:07:19:37</EPCIActivityChemBioApproveDate>\n <EPCIActivityChemBioExpireDate>2056-12-31:12:00:00</EPCIActivityChemBioExpireDate>\n <EPCIActivityChemBioCountry>US</EPCIActivityChemBioCountry>\n <EPCIActivityMissileCode>MISSILE</EPCIActivityMissileCode>\n <EPCIActivityMissileValue>N</EPCIActivityMissileValue>\n <EPCIActivityMissileApproveDate>2011-05-16:07:19:37</EPCIActivityMissileApproveDate>\n <EPCIActivityMissileExpireDate>2056-12-31:12:00:00</EPCIActivityMissileExpireDate>\n <EPCIActivityMissileCountry>US</EPCIActivityMissileCountry>\n </Vastera:EPCIActivity>\n <SourceSystem>GSB2BSS</SourceSystem>\n <CreatedDate>2011-05-16:07:18:55</CreatedDate>\n <CreatedBy>c18530</CreatedBy>\n <LastModifiedDate>2011-05-16:07:18:55</LastModifiedDate>\n <LastModifiedBy>c18530</LastModifiedBy>\n <ContactName>Greg, "Da Man" Skluacek</ContactName>\n <ContactTitle>Head Honcho</ContactTitle>\n <ContactPhone>555-555-5555</ContactPhone>\n <ContactFax>666-666-6666</ContactFax>\n <ContactEmail>[email protected]</ContactEmail>\n <ContactWeb>www.gregco.com</ContactWeb>\n</Vastera:CustomerValidation_RequestInfo>\nXML;\n\n$xml_req2 = <<<XML\n<?xml version=\"1.0\"?>\n<order>\n <orderNumber>123</orderNumber>\n <customerAddress>\n <type>Ship To</type>\n <name>Bob McFly</name>\n <addr1>123 Lincoln St</addr1>\n <city>Chicago</city>\n <state>IL</state>\n <zip>60001</zip>\n </customerAddress>\n <customerAddress>\n <type>Bill To</type>\n <name>McFly Products Inc.</name>\n <addr1>P.O. Box 6695</addr1>\n <city>New York</city>\n <state>NY</state>\n <zip>99081-6695</zip>\n </customerAddress>\n <item>\n <line>1</line>\n <part>123001A</part>\n <qty>5</qty>\n <price>10.25</price>\n </item>\n <item>\n <line>2</line>\n <part>456002B</part>\n <qty>3</qty>\n <price>20.50</price>\n </item>\n <item>\n <line>3</line>\n <part>789003C</part>\n <qty>1</qty>\n <price>41.00</price>\n </item>\n <orderSubTotal>133.25</orderSubTotal>\n <tax>6.66</tax>\n <shipping>10.00</shipping>\n <orderTotal>149.91</orderTotal>\n</order>\nXML;\n\n$doc = new DOMDocument();\n$doc->preserveWhiteSpace = false;\n$doc->loadXML($xml_req1);\n\n$arr = xml_to_arr($doc->documentElement);\n\nprint \"\\n\\n----\\n\\n\";\n\nprint_r($arr);\n\nprint \"\\n\\n----\\n\\n\";\n\n$doc2 = new DOMDocument();\n$doc2->preserveWhiteSpace = false;\n$doc2->loadXML($xml_req2);\n\n$arr2 = xml_to_arr($doc2->documentElement);\n\nprint \"\\n\\n----\\n\\n\";\n\nprint_r($arr2);\n\nprint \"\\n\\n----\\n\\n\";\n\nexit;\n\nfunction xml_to_arr($curr_node) {\n $val_array = array();\n $typ_array = array();\n\n foreach($curr_node->childNodes as $node) {\n if ($node->nodeType == XML_ELEMENT_NODE) {\n\n $val = xml_to_arr($node);\n\n if (array_key_exists($node->tagName, $val_array)) {\n\n if (!is_array($val_array[$node->tagName]) || $type_array[$node->tagName] == 'hash') {\n $existing_val = $val_array[$node->tagName];\n unset($val_array[$node->tagName]);\n $val_array[$node->tagName][0] = $existing_val;\n $type_array[$node->tagName] = 'array';\n }\n $val_array[$node->tagName][] = $val;\n\n } else {\n\n $val_array[$node->tagName] = $val;\n if (is_array($val)) {\n $type_array[$node->tagName] = 'hash';\n }\n\n } // end if array key exists\n\n } // end if elment node\n }// end for each\n\n if (count($val_array) == 0) {\n return $curr_node->nodeValue;\n } else {\n return $val_array;\n }\n\n} // end function xml to arr\n\n?>\n</code></pre>\n\n<p>example output</p>\n\n<pre><code>\n----\n\nArray\n(\n [PartnerID] => 5550000100-003\n [PartnerType] => PTNR_INTER_CONSIGNEE\n [OperatingUnit] => 100\n [Status] => ACTIVE\n [CustomerSeqNumber] => 111\n [CustomerName] => Greg Co\n [Address1] => 123 Any Ln\n [Address2] => ?\n [Address3] => ?\n [Address4] => ?\n [Address5] => ?\n [City] => Somplace\n [PostalCode] => 60123\n [State] => CA\n [CountryCode] => US\n [TaxReference] => 222\n [PartyRelated] => Y\n [BusinessUnit] => GSBU\n [Region] => GSRGN\n [LocationName] => DBA Mac Head Computing\n [LoadOnly] => N\n [VSTM] => 333\n [MilitaryCustomerFlag] => Y\n [USFederalGovernmentCustomer] => Y\n [Non-USGovernmentCustomer] => Y\n [Vastera:EPCIActivity] => Array\n (\n [EPCIActivityNuclearCode] => NUCLEAR\n [EPCIActivityNuclearValue] => N\n [EPCIActivityNuclearApproveDate] => 2011-05-16:07:19:37\n [EPCIActivityNuclearExpireDate] => 2056-12-31:12:00:00\n [EPCIActivityNuclearCountry] => US\n [EPCIActivityChemBioCode] => CHEM_BIO\n [EPCIActivityChemBioValue] => N\n [EPCIActivityChemBioApproveDate] => 2011-05-16:07:19:37\n [EPCIActivityChemBioExpireDate] => 2056-12-31:12:00:00\n [EPCIActivityChemBioCountry] => US\n [EPCIActivityMissileCode] => MISSILE\n [EPCIActivityMissileValue] => N\n [EPCIActivityMissileApproveDate] => 2011-05-16:07:19:37\n [EPCIActivityMissileExpireDate] => 2056-12-31:12:00:00\n [EPCIActivityMissileCountry] => US\n )\n\n [SourceSystem] => GSB2BSS\n [CreatedDate] => 2011-05-16:07:18:55\n [CreatedBy] => c18530\n [LastModifiedDate] => 2011-05-16:07:18:55\n [LastModifiedBy] => c18530\n [ContactName] => Greg, \"Da Man\" Skluacek\n [ContactTitle] => Head Honcho\n [ContactPhone] => 555-555-5555\n [ContactFax] => 666-666-6666\n [ContactEmail] => [email protected]\n [ContactWeb] => www.gregco.com\n)\n\n----\n\nArray\n(\n [orderNumber] => 123\n [customerAddress] => Array\n (\n [0] => Array\n (\n [type] => Ship To\n [name] => Bob McFly\n [addr1] => 123 Lincoln St\n [city] => Chicago\n [state] => IL\n [zip] => 60001\n )\n\n [1] => Array\n (\n [type] => Bill To\n [name] => McFly Products Inc.\n [addr1] => P.O. Box 6695\n [city] => New York\n [state] => NY\n [zip] => 99081-6695\n )\n\n )\n\n [item] => Array\n (\n [0] => Array\n (\n [line] => 1\n [part] => 123001A\n [qty] => 5\n [price] => 10.25\n )\n\n [1] => Array\n (\n [line] => 2\n [part] => 456002B\n [qty] => 3\n [price] => 20.50\n )\n\n [2] => Array\n (\n [line] => 3\n [part] => 789003C\n [qty] => 1\n [price] => 41.00\n )\n\n )\n\n [orderSubTotal] => 133.25\n [tax] => 6.66\n [shipping] => 10.00\n [orderTotal] => 149.91\n)\n\n--------\n</code></pre>\n"
},
{
"answer_id": 6880640,
"author": "Ángel López",
"author_id": 379027,
"author_profile": "https://Stackoverflow.com/users/379027",
"pm_score": 2,
"selected": false,
"text": "<p>Hey @Conrad I just modify your code to work well with numeric arrays:</p>\n\n<pre><code>/**\n * Build A XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default fx_request\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\npublic static function arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){\n if(!is_array($data)){\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($xml_version, $xml_encoding);\n $xml->startElement($startElement);\n\n /**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n function write(XMLWriter $xml, $data){\n foreach($data as $key => $value){\n if (is_array($value) && isset($value[0])){\n foreach($value as $itemValue){\n //$xml->writeElement($key, $itemValue);\n\n if(is_array($itemValue)){\n $xml->startElement($key);\n write($xml, $itemValue);\n $xml->endElement();\n continue;\n } \n\n if (!is_array($itemValue)){\n $xml->writeElement($key, $itemValue.\"\");\n }\n }\n }else if(is_array($value)){\n $xml->startElement($key);\n write($xml, $value);\n $xml->endElement();\n continue;\n } \n\n if (!is_array($value)){\n $xml->writeElement($key, $value.\"\");\n }\n }\n }\n write($xml, $data);\n\n $xml->endElement();//write end element\n //returns the XML results\n return $xml->outputMemory(true);\n}\n</code></pre>\n\n<p>so yo can convert this:</p>\n\n<pre><code>$mArray[\"invitations\"][\"user\"][0][\"name\"] = \"paco\";\n$mArray[\"invitations\"][\"user\"][0][\"amigos\"][0] = 82;\n$mArray[\"invitations\"][\"user\"][0][\"amigos\"][1] = 29;\n$mArray[\"invitations\"][\"user\"][0][\"amigos\"][2] = 6;\n\n$mArray[\"invitations\"][\"user\"][1][\"name\"] = \"jose\";\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][0] = 43;\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][1][\"tuyos\"] = 32;\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][1][\"mios\"] = 79;\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][2] = 11;\n\n$mArray[\"invitations\"][\"user\"][2][\"name\"] = \"luis\";\n$mArray[\"invitations\"][\"user\"][2][\"amigos\"][0] = 65;\n</code></pre>\n\n<p>into this xml:</p>\n\n<pre><code><invitations>\n<user>\n <name>paco</name>\n <amigos>82</amigos>\n <amigos>29</amigos>\n <amigos>6</amigos>\n</user>\n<user>\n <name>jose</name>\n <amigos>43</amigos>\n <amigos>\n <tuyos>32</tuyos>\n <mios>79</mios>\n </amigos>\n <amigos>11</amigos>\n</user>\n<user>\n <name>luis</name>\n <amigos>65</amigos>\n</user>\n</code></pre>\n\n<p></p>\n\n<p>I hope I can help someone with this</p>\n"
},
{
"answer_id": 7331866,
"author": "xrado",
"author_id": 345085,
"author_profile": "https://Stackoverflow.com/users/345085",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class Xml {\n\n public static function from_array($arr, $xml = NULL)\n {\n $first = $xml;\n if($xml === NULL) $xml = new SimpleXMLElement('<root/>');\n foreach ($arr as $k => $v) \n {\n is_array($v)\n ? self::from_array($v, $xml->addChild($k))\n : $xml->addChild($k, $v);\n }\n return ($first === NULL) ? $xml->asXML() : $xml;\n }\n\n public static function to_array($xml)\n {\n $xml = simplexml_load_string($xml);\n $json = json_encode($xml);\n return json_decode($json,TRUE);\n }\n\n}\n\n$xml = xml::from_array($array);\n$array = xml::to_array($xml);\n</code></pre>\n"
},
{
"answer_id": 7404818,
"author": "tomas",
"author_id": 942915,
"author_profile": "https://Stackoverflow.com/users/942915",
"pm_score": 0,
"selected": false,
"text": "<p>The most simple way to get assoc array from xml string:</p>\n\n<pre><code><?\n$data_array = (array) simplexml_load_string($xml_string);\n?>\n</code></pre>\n"
},
{
"answer_id": 17050255,
"author": "Dan James",
"author_id": 2475599,
"author_profile": "https://Stackoverflow.com/users/2475599",
"pm_score": 1,
"selected": false,
"text": "<p>This builds on Ángel López's answer. Added support for attributes. If an element has attributes, prefix them with @, and refer to the actual element content with an empty string as the key.</p>\n\n<pre><code>/**\n * Build an XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default fx_request\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\nfunction arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){\n if(!is_array($data)){\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n //if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($xml_version, $xml_encoding);\n $xml->startElement($startElement);\n\n /**\n * Write keys in $data prefixed with @ as XML attributes, if $data is an array. When an @ prefixed key is found, a '' key is expected to indicate the element itself.\n * @param object $xml XMLWriter Object\n * @param array $data with attributes filtered out\n */\n function writeAttr(XMLWriter $xml, $data) {\n if(is_array($data)) {\n $nonAttributes = array();\n foreach($data as $key => $val) {\n //handle an attribute with elements\n if($key[0] == '@') {\n $xml->writeAttribute(substr($key, 1), $val);\n } else if($key == '') {\n if(is_array($val)) $nonAttributes = $val;\n else $xml->text(\"$val\");\n }\n\n //ignore normal elements\n else $nonAttributes[$key] = $val;\n }\n return $nonAttributes;\n }\n else return $data;\n }\n\n /**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n function writeEl(XMLWriter $xml, $data) {\n foreach($data as $key => $value) {\n if(is_array($value) && isset($value[0])) { //numeric array\n foreach($value as $itemValue){\n if(is_array($itemValue)) {\n $xml->startElement($key);\n $itemValue = writeAttr($xml, $itemValue);\n writeEl($xml, $itemValue);\n $xml->endElement();\n } else {\n $itemValue = writeAttr($xml, $itemValue);\n $xml->writeElement($key, \"$itemValue\");\n }\n }\n } else if(is_array($value)) { //associative array\n $xml->startElement($key);\n $value = writeAttr($xml, $value);\n writeEl($xml, $value);\n $xml->endElement();\n } else { //scalar\n $value = writeAttr($xml, $value);\n $xml->writeElement($key, \"$value\");\n }\n }\n }\n writeEl($xml, $data);\n\n $xml->endElement();//write end element\n //returns the XML results\n return $xml->outputMemory(true);\n}\n</code></pre>\n\n<p>so yo can convert this:</p>\n\n<pre><code>$mArray[\"invitations\"][\"user\"][0][\"@name\"] = \"paco\";\n$mArray[\"invitations\"][\"user\"][0][\"\"][\"amigos\"][0] = 82;\n$mArray[\"invitations\"][\"user\"][0][\"\"][\"amigos\"][1] = 29;\n$mArray[\"invitations\"][\"user\"][0][\"\"][\"amigos\"][2] = 6;\n\n$mArray[\"invitations\"][\"user\"][1][\"@name\"] = \"jose\";\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][0] = 43;\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][1][\"tuyos\"] = 32;\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][1][\"mios\"] = 79;\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][2] = 11;\n\n$mArray[\"invitations\"][\"user\"][2][\"@name\"] = \"luis\";\n$mArray[\"invitations\"][\"user\"][2][\"\"][\"amigos\"][0] = 65;\n</code></pre>\n\n<p>into this xml:</p>\n\n<pre><code><invitations>\n <user name=\"paco\">\n <amigos>82</amigos>\n <amigos>29</amigos>\n <amigos>6</amigos>\n </user>\n <user name=\"jose\">\n <amigos>43</amigos>\n <amigos>\n <tuyos>32</tuyos>\n <mios>79</mios>\n </amigos>\n <amigos>11</amigos>\n </user>\n <user name=\"luis\">\n <amigos>65</amigos>\n </user>\n</invitations>\n</code></pre>\n\n<p>Thanks Ángel.</p>\n"
},
{
"answer_id": 17906457,
"author": "Andrey Vorobyev",
"author_id": 1091104,
"author_profile": "https://Stackoverflow.com/users/1091104",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\nfunction writeXmlRecursive(XMLWriter $xml, $data){\n foreach($data as $key => $value){\n if (is_array($value) && isset($value[0])){\n $xml->startElement($key);\n foreach($value as $itemValue){\n\n if(is_array($itemValue)){\n writeXmlRecursive($xml, $itemValue);\n }\n else\n {\n $xml->writeElement($key, $itemValue.\"\");\n }\n }\n $xml->endElement();\n\n }else if(is_array($value)){\n $xml->startElement($key);\n writeXmlRecursive($xml, $value);\n $xml->endElement();\n continue;\n }\n\n if (!is_array($value)){\n $xml->writeElement($key, $value.\"\");\n }\n }\n}\n</code></pre>\n\n<p>This is final version, that give ahat i want from array with 4 nested level</p>\n\n<pre><code><items>\n<item>\n <id_site>59332</id_site>\n <id>33</id>\n <code>196429985</code>\n <tombid>23</tombid>\n <tombcode>196429985</tombcode>\n <religion></religion>\n <lastname>lastname</lastname>\n <firstname>name</firstname>\n <patronymicname>patronymicname</patronymicname>\n <sex>1</sex>\n <birthday>2</birthday>\n <birthmonth>4</birthmonth>\n <birthyear>1946</birthyear>\n <deathday>13</deathday>\n <deathmonth>5</deathmonth>\n <deathyear>2006</deathyear>\n <s_comments></s_comments>\n <graveyard>17446</graveyard>\n <latitude></latitude>\n <longitude></longitude>\n <images>\n <image>\n <siteId>52225</siteId>\n <fileId>62</fileId>\n <prefix>0</prefix>\n <path>path</path>\n </image>\n <image>\n <siteId>52226</siteId>\n <fileId>63</fileId>\n <prefix>0</prefix>\n <path>path</path>\n </image>\n </images>\n </item>\n<items>\n</code></pre>\n"
},
{
"answer_id": 24468165,
"author": "jmarceli",
"author_id": 2041318,
"author_profile": "https://Stackoverflow.com/users/2041318",
"pm_score": 1,
"selected": false,
"text": "<p>Based on answers here I made github repo <a href=\"https://github.com/jmarceli/array2xml\" rel=\"nofollow noreferrer\">https://github.com/jmarceli/array2xml</a></p>\n\n<p>Maybe not the prettiest repo on the internet but the code seems to be working fine.</p>\n\n<p>Here is the code which may be used:</p>\n\n<pre><code>// Based on: http://stackoverflow.com/questions/99350/passing-php-associative-arrays-to-and-from-xml\nclass ArrayToXML {\n private $version;\n private $encoding;\n /*\n * Construct ArrayToXML object with selected version and encoding \n *\n * for available values check XmlWriter docs http://www.php.net/manual/en/function.xmlwriter-start-document.php\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n */\n public function __construct($xmlVersion = '1.0', $xmlEncoding = 'UTF-8') {\n $this->version = $xmlVersion;\n $this->encoding = $xmlEncoding;\n }\n /**\n * Build an XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default data\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\n public function buildXML($data, $startElement = 'data'){\n if(!is_array($data)){\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n //if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($this->version, $this->encoding);\n $xml->startElement($startElement);\n $this->writeEl($xml, $data);\n $xml->endElement();//write end element\n //returns the XML results\n return $xml->outputMemory(true);\n }\n /**\n * Write keys in $data prefixed with @ as XML attributes, if $data is an array. \n * When an @ prefixed key is found, a '%' key is expected to indicate the element itself, \n * and '#' prefixed key indicates CDATA content\n *\n * @param object $xml XMLWriter Object\n * @param array $data with attributes filtered out\n */\n protected function writeAttr(XMLWriter $xml, $data) {\n if(is_array($data)) {\n $nonAttributes = array();\n foreach($data as $key => $val) {\n //handle an attribute with elements\n if($key[0] == '@') {\n $xml->writeAttribute(substr($key, 1), $val);\n } else if($key[0] == '%') {\n if(is_array($val)) $nonAttributes = $val;\n else $xml->text($val);\n } elseif($key[0] == '#') {\n if(is_array($val)) $nonAttributes = $val;\n else {\n $xml->startElement(substr($key, 1));\n $xml->writeCData($val);\n $xml->endElement();\n }\n }\n //ignore normal elements\n else $nonAttributes[$key] = $val;\n }\n return $nonAttributes;\n }\n else return $data;\n }\n /**\n * Write XML as per Associative Array\n *\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n protected function writeEl(XMLWriter $xml, $data) {\n foreach($data as $key => $value) {\n if(is_array($value) && !$this->isAssoc($value)) { //numeric array\n foreach($value as $itemValue){\n if(is_array($itemValue)) {\n $xml->startElement($key);\n $itemValue = $this->writeAttr($xml, $itemValue);\n $this->writeEl($xml, $itemValue);\n $xml->endElement();\n } else {\n $itemValue = $this->writeAttr($xml, $itemValue);\n $xml->writeElement($key, \"$itemValue\");\n }\n }\n } else if(is_array($value)) { //associative array\n $xml->startElement($key);\n $value = $this->writeAttr($xml, $value);\n $this->writeEl($xml, $value);\n $xml->endElement();\n } else { //scalar\n $value = $this->writeAttr($xml, $value);\n $xml->writeElement($key, \"$value\");\n }\n }\n }\n /*\n * Check if array is associative with string based keys\n * FROM: http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential/4254008#4254008\n *\n * @param array $array Array to check\n */\n protected function isAssoc($array) {\n return (bool)count(array_filter(array_keys($array), 'is_string'));\n }\n}\n</code></pre>\n\n<p>After that just use the <code>ArrayToXML</code> class. Example:</p>\n\n<pre><code>$xml = new ArrayToXML();\nprint $xml->buildXML($input);\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15004/"
]
| Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:
```
$items = array("1", "2",
array(
"item3.1" => "3.1",
"item3.2" => "3.2"
"isawesome" => true
)
);
```
How would I turn it into something similar to the following XML in as few lines as possible, then back again?
```
<items>
<item>1</item>
<item>2</item>
<item>
<item3_1>3.1</item3_1>
<item3_2>3.2</item3_2>
<isawesome>true</isawesome>
</item>
</items>
```
I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's [XMLReader](http://php.net/manual/en/book.xmlreader.php) and [XMLWriter](http://php.net/manual/en/book.xmlwriter.php), but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:
```
$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);
```
Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?
I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it. | For those of you not using the PEAR packages, but you've got PHP5 installed. This worked for me:
```
/**
* Build A XML Data Set
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default fx_request
* @param string $xml_version XML Version, default 1.0
* @param string $xml_encoding XML Encoding, default UTF-8
* @return string XML String containig values
* @return mixed Boolean false on failure, string XML result on success
*/
public function buildXMLData($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8') {
if(!is_array($data)) {
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
if($this->_debug) echo $err;
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($xml_version, $xml_encoding);
$xml->startElement($startElement);
/**
* Write XML as per Associative Array
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
function write(XMLWriter $xml, $data) {
foreach($data as $key => $value) {
if(is_array($value)) {
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $data);
$xml->endElement();//write end element
//Return the XML results
return $xml->outputMemory(true);
}
``` |
99,391 | <p>When I commit I get this error from Subversion:</p>
<pre><code>bash-2.05b$ svn commit -m "testing subversion, still"
Adding baz
svn: Commit failed (details follow):
svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com)
</code></pre>
| [
{
"answer_id": 99413,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 8,
"selected": true,
"text": "<p>This happens when you have added a directory that someone else has also added and already committed. The error message on a commit is really confusing, but if you do an <code>svn up</code> instead you'll see this message:</p>\n\n<pre><code>bash-2.05b$ svn up\nsvn: Failed to add directory 'baz': object of the same name already exists\n</code></pre>\n\n<p>To resolve the issue, remove your directory (or move it aside) and do an <code>svn update</code> to get the version on the server and re-do your changes.</p>\n\n<p>As a general rule, be sure to do <code>svn update</code> since the error messages tend to be more helpful.</p>\n"
},
{
"answer_id": 37965567,
"author": "Harshal Doshi Jain",
"author_id": 1461781,
"author_profile": "https://Stackoverflow.com/users/1461781",
"pm_score": 4,
"selected": false,
"text": "<p>This happens when you have added a directory that someone else has also added and already committed. </p>\n\n<p>This is something to indicate conflict but at Directories level (just to understand).</p>\n\n<p>To resolve this, just do <code>svn update</code> before committing your changes</p>\n"
},
{
"answer_id": 67856429,
"author": "Mahavirsinh Padhiyar",
"author_id": 3992496,
"author_profile": "https://Stackoverflow.com/users/3992496",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes this happens.\nSolution:\nWhen you create any new repository must add read.me file to create a default branch(trunk) so that it will find a proper path to push your stuff.\nIf you create a repository and do not add read. me and if it is blank then upload a file like test.txt and take that uploaded file as latest update in your local folder and then try to push your code from that updated folder. This works for me.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594/"
]
| When I commit I get this error from Subversion:
```
bash-2.05b$ svn commit -m "testing subversion, still"
Adding baz
svn: Commit failed (details follow):
svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com)
``` | This happens when you have added a directory that someone else has also added and already committed. The error message on a commit is really confusing, but if you do an `svn up` instead you'll see this message:
```
bash-2.05b$ svn up
svn: Failed to add directory 'baz': object of the same name already exists
```
To resolve the issue, remove your directory (or move it aside) and do an `svn update` to get the version on the server and re-do your changes.
As a general rule, be sure to do `svn update` since the error messages tend to be more helpful. |
99,468 | <p>I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL_SCROLLABLE. How do I do this with a UNION query (with two selects)?</p>
<p>The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.</p>
<p>This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL_FETCH_FIRST or SQL_FETCH_LAST as well as):</p>
<pre>
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SCROLLABLE,
(SQLPOINTER)SQL_SCROLLABLE,
SQL_IS_INTEGER);
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SENSITIVITY,
(SQLPOINTER)SQL_INSENSITIVE,
SQL_IS_INTEGER);
...
retcode = SQLGetStmtAttr(hstmt1Fetch,
SQL_ATTR_ROW_NUMBER,
&CurrentRowNumber,
SQL_IS_UINTEGER,
NULL);
...
retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position);
</pre>
<p>(The above is is a fragment from working code for a single SELECT).</p>
<p>Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)</p>
<p>Assuming yes to the above, how do I achieve the same result with a UNION query?</p>
<p>LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something.</p>
| [
{
"answer_id": 99628,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>can you not define a view on the db server that does the union query for you, so from the client code it just looks like a single select?</p>\n\n<p>if you can't, can you just issue the union operation as part of your select, e.g.</p>\n\n<pre><code>select some_fields from table1\nunion\nselect same_fields from table2\n</code></pre>\n\n<p>and treat the result as a single result set?</p>\n"
},
{
"answer_id": 146031,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>If the issue is just needing to get the last row to get the number of rows and caching the last few rows (I assume if there are a million items in the select that you're not populating a drop-list with all of them) then you may be able to take advantage of the <code>ROW_NUMBER()</code> function of SQL Server 2005</p>\n\n<p>You could:</p>\n\n<pre><code>select count(*) \nfrom (select blah UNION select blah) \n</code></pre>\n\n<p>to get the number of rows.</p>\n\n<p>Then:</p>\n\n<pre><code>select ROW_NUMBER() as rownum,blah \nfrom (select blah UNION select blah) \nwhere rownum between minrow and maxrow \n</code></pre>\n\n<p>to just fetch the rows that you need to display/cache</p>\n\n<p>But seriously folks, if you're selecting items from a million-row table, you might want to consider a different mechanism</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 146243,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using <code>union</code> to make a derived table ?</p>\n\n<pre><code>select * from \n(select field1, field from table1\nunion all\nslect field1, filed2 from table2) a\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137/"
]
| I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL\_SCROLLABLE. How do I do this with a UNION query (with two selects)?
The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.
This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL\_FETCH\_FIRST or SQL\_FETCH\_LAST as well as):
```
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SCROLLABLE,
(SQLPOINTER)SQL_SCROLLABLE,
SQL_IS_INTEGER);
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SENSITIVITY,
(SQLPOINTER)SQL_INSENSITIVE,
SQL_IS_INTEGER);
...
retcode = SQLGetStmtAttr(hstmt1Fetch,
SQL_ATTR_ROW_NUMBER,
&CurrentRowNumber,
SQL_IS_UINTEGER,
NULL);
...
retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position);
```
(The above is is a fragment from working code for a single SELECT).
Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)
Assuming yes to the above, how do I achieve the same result with a UNION query?
LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL\_FETCH\_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something. | can you not define a view on the db server that does the union query for you, so from the client code it just looks like a single select?
if you can't, can you just issue the union operation as part of your select, e.g.
```
select some_fields from table1
union
select same_fields from table2
```
and treat the result as a single result set? |
99,488 | <p>If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).</p>
<p>I want to know how to do this to a complex widget as well, for example, an <code>HBox</code> that contains a <code>VBox</code> that contains some <code>Labels</code>.</p>
<p>Ideally this would also include a solution solution that allows me to <em>tint</em> the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red.</p>
| [
{
"answer_id": 100266,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 4,
"selected": true,
"text": "<p>Example program:</p>\n\n<pre><code>#include <gtk/gtk.h>\n\nstatic void on_destroy(GtkWidget* widget, gpointer data)\n{\n gtk_main_quit ();\n}\n\nint main (int argc, char* argv[])\n{\n GtkWidget* window;\n GtkWidget* button;\n\n gtk_init(&argc, &argv);\n window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n g_signal_connect(G_OBJECT (window), \"destroy\",\n G_CALLBACK (on_destroy), NULL);\n button = gtk_button_new_with_label(\"Hello world!\");\n GdkColor red = {0, 0xffff, 0x0000, 0x0000};\n GdkColor green = {0, 0x0000, 0xffff, 0x0000};\n GdkColor blue = {0, 0x0000, 0x0000, 0xffff};\n gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);\n gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);\n gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);\n gtk_container_add(GTK_CONTAINER(window), button);\n gtk_widget_show_all(window);\n gtk_main();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 126365,
"author": "Johan Dahlin",
"author_id": 14337,
"author_profile": "https://Stackoverflow.com/users/14337",
"pm_score": 2,
"selected": false,
"text": "<p>The best documentation that I know of is the one available here: <a href=\"http://ometer.com/gtk-colors.html\" rel=\"nofollow noreferrer\">http://ometer.com/gtk-colors.html</a></p>\n"
},
{
"answer_id": 18240336,
"author": "shovon3091",
"author_id": 2683628,
"author_profile": "https://Stackoverflow.com/users/2683628",
"pm_score": 1,
"selected": false,
"text": "<p>You can always use <a href=\"https://developer.gnome.org/gtk3/3.4/GtkWidget.html#gtk-widget-override-color\" rel=\"nofollow\">gtk_widget_override_color ()</a> and <a href=\"https://developer.gnome.org/gtk3/3.4/GtkWidget.html#gtk-widget-override-background-color\" rel=\"nofollow\">gtk_widget_override_background_color ()</a>. These two functions allow you to change the color of a widget. But it is better to use CSS classes and regions in your widget/container implementation through <code>gtk_style_context_add_class()</code> and <code>gtk_style_context_add_region()</code>.</p>\n"
},
{
"answer_id": 22662978,
"author": "nishantbhardwaj2002",
"author_id": 3340994,
"author_profile": "https://Stackoverflow.com/users/3340994",
"pm_score": 1,
"selected": false,
"text": "<p>To modify the color of a widget you can initialize a color and use it to modify the color of the widget:</p>\n\n<pre><code>GdkColor color;\ngdk_color_parse(\"#00FF7F\", &color);\ngtk_widget_modify_bg(widget, GTK_STATE_NORMAL, &color);\n</code></pre>\n\n<p>To use an image instead of color:</p>\n\n<pre><code>GdkPixbuf *image = NULL;\nGdkPixmap *background = NULL;\nGtkStyle *style = NULL;\n\nimage = gdk_pixbuf_new_from_file (\"background.jpg\", NULL);\ngdk_pixbuf_render_pixmap_and_mask (image, &background, NULL, 0);\nstyle = gtk_style_new ();\nstyle->bg_pixmap [0] = background;\n\ngtk_widget_set_style (GTK_WIDGET(widget), GTK_STYLE (style));\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13564/"
]
| If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).
I want to know how to do this to a complex widget as well, for example, an `HBox` that contains a `VBox` that contains some `Labels`.
Ideally this would also include a solution solution that allows me to *tint* the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red. | Example program:
```
#include <gtk/gtk.h>
static void on_destroy(GtkWidget* widget, gpointer data)
{
gtk_main_quit ();
}
int main (int argc, char* argv[])
{
GtkWidget* window;
GtkWidget* button;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT (window), "destroy",
G_CALLBACK (on_destroy), NULL);
button = gtk_button_new_with_label("Hello world!");
GdkColor red = {0, 0xffff, 0x0000, 0x0000};
GdkColor green = {0, 0x0000, 0xffff, 0x0000};
GdkColor blue = {0, 0x0000, 0x0000, 0xffff};
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);
gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
``` |
99,542 | <p>How do I correct for floating point error in the following physical simulation:</p>
<ul>
<li>Original point (x, y, z),</li>
<li>Desired point (x', y', z') after forces are applied.</li>
<li>Two triangles (A, B, C) and (B, C, D), who share edge BC</li>
</ul>
<p>I am using this method for collision detection:</p>
<pre><code>For each Triangle
If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
If the intersection point is inside the triangle edges (!)
Respond to the collision.
End If
End If
Next Triangle
</code></pre>
<p>The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with <strong>(!)</strong> because I believe that's where I should be making a change.</p>
<p>One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.</p>
<p>I am specifically using the dot product and triangle normals for all of my front-back testing.</p>
| [
{
"answer_id": 99562,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you ain't including testing if it's ON the edge (you're writing \"Inside triangle edges\"). Try changing code to \"less than or equal\" (inside, or overlapping).</p>\n"
},
{
"answer_id": 99584,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>I find it somewhat unlikely that your ray would fall exactly between the triangles in a way that the floating point precision would take effect. Are you absolutely positive that this is indeed the problem?</p>\n\n<p>At any rate, a possible solution is instead of shooting just one ray to shoot three that are very close to each other. If one falls exactly in between that atleast one of the other two is guaranteed to fall on a triangle.</p>\n\n<p>This will atleast allow you to test if the problem is really the floating point error or something more likely.</p>\n"
},
{
"answer_id": 99631,
"author": "Martin",
"author_id": 2581,
"author_profile": "https://Stackoverflow.com/users/2581",
"pm_score": 0,
"selected": false,
"text": "<p>@Statement: I am indeed already using a \"greater than or equal to\" comparison in my code, thank you for the suggestion. +1</p>\n\n<p>My current solution is to add a small nudge amount to the edge test. Basically when each triangle is tested, its edges are pushed out by a very small amount to counteract the error in floating point. Sort of like testing if the result of a floating point calculation is less than 0.01 rather than testing for equality with zero.</p>\n\n<p>Is this a reasonable solution?</p>\n"
},
{
"answer_id": 168377,
"author": "user4891",
"author_id": 4891,
"author_profile": "https://Stackoverflow.com/users/4891",
"pm_score": 0,
"selected": false,
"text": "<p>If you are doing distance measurements, watch out for square roots. They have a nasty habit of throwing away <em>half</em> of your precision. If you stack a few of these calculations up, you can get in big trouble fast. Here is a distance function I have used.</p>\n\n<pre><code>double Distance(double x0, double y0, double x1, double y1)\n{\n double a, b, dx, dy;\n\n dx = abs(x1 - x0);\n dy = abs(y1 - y0);\n\n a = max(dx, dy));\n if (a == 0)\n return 0;\n b = min(dx, dy);\n\n return a * sqrt( 1 + (b*b) / (a*a) );\n}\n</code></pre>\n\n<p>Since the last operation isn't a square root, you don't lose the precision any more.</p>\n\n<p>I discovered this in a project I was working on. After studying it and figuring out what it did I tracked down the programmer who I thought was responsible to congratulate him, but he had no idea what I was talking about.</p>\n"
},
{
"answer_id": 563136,
"author": "Gareth Rees",
"author_id": 68063,
"author_profile": "https://Stackoverflow.com/users/68063",
"pm_score": 4,
"selected": true,
"text": "<p>This is an inevitable problem when shooting a single ray against some geometry with edges and vertices. It's amazing how physical simulations seem to seek out the smallest of numerical inaccuracies!</p>\n\n<p>Some of the explanations and solutions proposed by other respondents will not work. In particular:</p>\n\n<ul>\n<li><p>Numerical inaccuracy really can cause a ray to \"fall through the gap\". The problem is that we intersect the ray with the plane ABC (getting the point P, say) before testing against line BC. Then we intersect the ray with plane BCD (getting the point Q, say) before testing against line BC. P and Q are both represented by the closest floating-point approximation; there's no reason to expect that these exactly lie on the planes that they are supposed to lie on, and so every possibility that you can have both P to the left of BC and Q to the right of BC.</p></li>\n<li><p>Using less-than-or-equal test won't help; it's inaccuracy in the intersection of the ray and the plane that's the trouble. </p></li>\n<li><p>Square roots are not the issue; you can do all of the necessary computations using dot products and floating-point division.</p></li>\n</ul>\n\n<p>Here are some genuine solutions:</p>\n\n<ul>\n<li><p>For convex meshes, you can just test against all the planes and ignore the edges and vertices, as you say (thus avoiding the issue entirely).</p></li>\n<li><p>Don't intersect the ray with each triangle in turn. Instead, use the <a href=\"http://realtimecollisiondetection.net/blog/?p=69\" rel=\"noreferrer\">scalar triple product</a>. (This method makes the exact same sequence of computations for the ray and the edge BC when considering each triangle, ensuring that any numerical inaccuracy is at least consistent between the two triangles.)</p></li>\n<li><p>For non-convex meshes, give the edges and vertices some width. That is, place a small sphere at each vertex in the mesh, and place a thin cylinder along each edge of the mesh. Intersect the ray with these spheres and cylinders as well as with the triangles. These additional geometric figures stop the ray passing through edges and vertices of the mesh.</p></li>\n</ul>\n\n<p>Let me strongly recommend the book <a href=\"http://realtimecollisiondetection.net/\" rel=\"noreferrer\">Real-Time Collision Detection</a> by Christer Ericson. There's a discussion of this exact problem on pages 446–448, and an explanation of the scalar triple product approach to intersecting a ray with a triangle on pages 184–188.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
]
| How do I correct for floating point error in the following physical simulation:
* Original point (x, y, z),
* Desired point (x', y', z') after forces are applied.
* Two triangles (A, B, C) and (B, C, D), who share edge BC
I am using this method for collision detection:
```
For each Triangle
If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
If the intersection point is inside the triangle edges (!)
Respond to the collision.
End If
End If
Next Triangle
```
The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with **(!)** because I believe that's where I should be making a change.
One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.
I am specifically using the dot product and triangle normals for all of my front-back testing. | This is an inevitable problem when shooting a single ray against some geometry with edges and vertices. It's amazing how physical simulations seem to seek out the smallest of numerical inaccuracies!
Some of the explanations and solutions proposed by other respondents will not work. In particular:
* Numerical inaccuracy really can cause a ray to "fall through the gap". The problem is that we intersect the ray with the plane ABC (getting the point P, say) before testing against line BC. Then we intersect the ray with plane BCD (getting the point Q, say) before testing against line BC. P and Q are both represented by the closest floating-point approximation; there's no reason to expect that these exactly lie on the planes that they are supposed to lie on, and so every possibility that you can have both P to the left of BC and Q to the right of BC.
* Using less-than-or-equal test won't help; it's inaccuracy in the intersection of the ray and the plane that's the trouble.
* Square roots are not the issue; you can do all of the necessary computations using dot products and floating-point division.
Here are some genuine solutions:
* For convex meshes, you can just test against all the planes and ignore the edges and vertices, as you say (thus avoiding the issue entirely).
* Don't intersect the ray with each triangle in turn. Instead, use the [scalar triple product](http://realtimecollisiondetection.net/blog/?p=69). (This method makes the exact same sequence of computations for the ray and the edge BC when considering each triangle, ensuring that any numerical inaccuracy is at least consistent between the two triangles.)
* For non-convex meshes, give the edges and vertices some width. That is, place a small sphere at each vertex in the mesh, and place a thin cylinder along each edge of the mesh. Intersect the ray with these spheres and cylinders as well as with the triangles. These additional geometric figures stop the ray passing through edges and vertices of the mesh.
Let me strongly recommend the book [Real-Time Collision Detection](http://realtimecollisiondetection.net/) by Christer Ericson. There's a discussion of this exact problem on pages 446–448, and an explanation of the scalar triple product approach to intersecting a ray with a triangle on pages 184–188. |
99,546 | <p>I read this <a href="http://smartprogrammer.blogspot.com/2006/04/15-exercises-for-learning-new.html" rel="nofollow noreferrer">article</a> and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.</p>
<blockquote>
<p>(1) Display series of numbers
(1,2,3,4, 5....etc) in an infinite
loop. The program should quit if
someone hits a specific key (Say
ESCAPE key).</p>
</blockquote>
<p>Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.</p>
<p>I know I can use some 3rd party library like <a href="http://www.gnu.org/software/ncurses/" rel="nofollow noreferrer">ncurses</a>, but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.</p>
<p>How could I do it?</p>
| [
{
"answer_id": 99593,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>D generally has all the C stdlib available (Tango or Phobos) so answers to this question for GNU C should work in D as well.</p>\n\n<p>If tango doesn't have the needed function, generating the bindings is easy. (Take a look at CPP to cut through any macro junk.)</p>\n"
},
{
"answer_id": 100064,
"author": "larsivi",
"author_id": 14047,
"author_profile": "https://Stackoverflow.com/users/14047",
"pm_score": 2,
"selected": false,
"text": "<p>kbhit is indeed not part of any standard C interfaces, but can be found in conio.h. </p>\n\n<p>However, you should be able to use getc/getchar from tango.stdc.stdio - I changed the FAQ you mention to reflect this.</p>\n"
},
{
"answer_id": 100380,
"author": "Brian Hsu",
"author_id": 242644,
"author_profile": "https://Stackoverflow.com/users/242644",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for both of your replies.</p>\n\n<p>Unfortunately, my main development environment is Linux + GDC + Tango, so I don't have conio.h, since I don't use DMC as my C compiler.</p>\n\n<p>And I also found both getc() and getchar() is also line buffered in my development environment, so it could not achieve what I wish I could do.</p>\n\n<p>In the end, I've done this exercise by using GNU ncurses library. Since D could interface C library directly, so it does not take much effort. I just declare the function prototype that I used in my program, call these function and linking my program against ncurses library directly.</p>\n\n<p>It works perfectly on my Linux machine, but I still not figure out how could I do this without any 3rd party library and could run on both Linux and Windows yet.</p>\n\n<pre><code>import tango.io.Stdout;\nimport tango.core.Thread;\n\n// Prototype for used ncurses library function.\nextern(C)\n{\n void * initscr();\n int cbreak ();\n int getch();\n int endwin();\n int noecho();\n}\n\n// A keyboard handler to quit the program when user hit ESC key.\nvoid keyboardHandler ()\n{\n initscr();\n cbreak();\n noecho();\n while (getch() != 27) {\n }\n endwin();\n}\n\n// Main Program\nvoid main ()\n{\n Thread handler = new Thread (&keyboardHandler);\n handler.start();\n\n for (int i = 0; ; i++) {\n Stdout.format (\"{}\\r\\n\", i).flush;\n\n // If keyboardHandler is not ruuning, it means user hits\n // ESC key, so we break the infinite loop.\n if (handler.isRunning == false) {\n break;\n }\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 261583,
"author": "Walter Bright",
"author_id": 33949,
"author_profile": "https://Stackoverflow.com/users/33949",
"pm_score": 3,
"selected": false,
"text": "<p>Here's how you do it in the D programming language:</p>\n\n<pre><code> import std.c.stdio;\n import std.c.linux.termios;\n\n termios ostate; /* saved tty state */\n termios nstate; /* values for editor mode */\n\n // Open stdin in raw mode\n /* Adjust output channel */\n tcgetattr(1, &ostate); /* save old state */\n tcgetattr(1, &nstate); /* get base of new state */\n cfmakeraw(&nstate);\n tcsetattr(1, TCSADRAIN, &nstate); /* set mode */\n\n // Read characters in raw mode\n c = fgetc(stdin);\n\n // Close\n tcsetattr(1, TCSADRAIN, &ostate); // return to original mode\n</code></pre>\n"
},
{
"answer_id": 705544,
"author": "DK.",
"author_id": 42353,
"author_profile": "https://Stackoverflow.com/users/42353",
"pm_score": 0,
"selected": false,
"text": "<p>As Lars pointed out, you can use _kbhit and _getch defined in conio.h and implemented in (I believe) msvcrt for Windows. Here's an <a href=\"http://nibuthomas.com/2009/02/06/how-to-check-for-keyhit-in-a-windows-console-application/\" rel=\"nofollow noreferrer\">article with C++ code for using _kbhit and _getch</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242644/"
]
| I read this [article](http://smartprogrammer.blogspot.com/2006/04/15-exercises-for-learning-new.html) and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.
>
> (1) Display series of numbers
> (1,2,3,4, 5....etc) in an infinite
> loop. The program should quit if
> someone hits a specific key (Say
> ESCAPE key).
>
>
>
Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.
I know I can use some 3rd party library like [ncurses](http://www.gnu.org/software/ncurses/), but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.
How could I do it? | Here's how you do it in the D programming language:
```
import std.c.stdio;
import std.c.linux.termios;
termios ostate; /* saved tty state */
termios nstate; /* values for editor mode */
// Open stdin in raw mode
/* Adjust output channel */
tcgetattr(1, &ostate); /* save old state */
tcgetattr(1, &nstate); /* get base of new state */
cfmakeraw(&nstate);
tcsetattr(1, TCSADRAIN, &nstate); /* set mode */
// Read characters in raw mode
c = fgetc(stdin);
// Close
tcsetattr(1, TCSADRAIN, &ostate); // return to original mode
``` |
99,552 | <p>I sometimes notice programs that crash on my computer with the error: "pure virtual function call".</p>
<p>How do these programs even compile when an object cannot be created of an abstract class?</p>
| [
{
"answer_id": 99567,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>I'd guess there is a vtbl created for the abstract class for some internal reason (it might be needed for some sort of run time type info) and something goes wrong and a real object gets it. It's a bug. That alone should say that something that can't happen is.</p>\n\n<p>Pure speculation</p>\n\n<p><strong>edit:</strong> looks like I'm wrong in the case in question. OTOH IIRC some languages do allow vtbl calls out of the constructor destructor. </p>\n"
},
{
"answer_id": 99575,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 8,
"selected": true,
"text": "<p>They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.</p>\n<pre><code>class Base\n{\npublic:\n Base() { reallyDoIt(); }\n void reallyDoIt() { doIt(); } // DON'T DO THIS\n virtual void doIt() = 0;\n};\n\nclass Derived : public Base\n{\n void doIt() {}\n};\n\nint main(void)\n{\n Derived d; // This will cause "pure virtual function call" error\n}\n</code></pre>\n<p>See also Raymond Chen's <a href=\"https://devblogs.microsoft.com/oldnewthing/20040428-00/?p=39613\" rel=\"noreferrer\">2</a> <a href=\"https://devblogs.microsoft.com/oldnewthing/20131011-00/?p=2953\" rel=\"noreferrer\">articles on the subject</a></p>\n"
},
{
"answer_id": 99591,
"author": "Braden",
"author_id": 18144,
"author_profile": "https://Stackoverflow.com/users/18144",
"pm_score": 3,
"selected": false,
"text": "<p>Usually when you call a virtual function through a dangling pointer--most likely the instance has already been destroyed.</p>\n\n<p>There can be more \"creative\" reasons, too: maybe you've managed to slice off the part of your object where the virtual function was implemented. But usually it's just that the instance has already been destroyed.</p>\n"
},
{
"answer_id": 99622,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a sneaky way for it to happen. I had this essentially happen to me today.</p>\n\n<pre><code>class A\n{\n A *pThis;\n public:\n A()\n : pThis(this)\n {\n }\n\n void callFoo()\n {\n pThis->foo(); // call through the pThis ptr which was initialized in the constructor\n }\n\n virtual void foo() = 0;\n};\n\nclass B : public A\n{\npublic:\n virtual void foo()\n {\n }\n};\n\nB b();\nb.callFoo();\n</code></pre>\n"
},
{
"answer_id": 100555,
"author": "Len Holgate",
"author_id": 7925,
"author_profile": "https://Stackoverflow.com/users/7925",
"pm_score": 6,
"selected": false,
"text": "<p>As well as the standard case of calling a virtual function from the constructor or destructor of an object with pure virtual functions you can also get a pure virtual function call (on MSVC at least) if you call a virtual function after the object has been destroyed. Obviously this is a pretty bad thing to try and do but if you're working with abstract classes as interfaces and you mess up then it's something that you might see. It's possibly more likely if you're using referenced counted interfaces and you have a ref count bug or if you have an object use/object destruction race condition in a multi-threaded program... The thing about these kinds of purecall is that it's often less easy to fathom out what's going on as a check for the 'usual suspects' of virtual calls in ctor and dtor will come up clean.</p>\n\n<p>To help with debugging these kinds of problems you can, in various versions of MSVC, replace the runtime library's purecall handler. You do this by providing your own function with this signature:</p>\n\n<pre><code>int __cdecl _purecall(void)\n</code></pre>\n\n<p>and linking it before you link the runtime library. This gives YOU control of what happens when a purecall is detected. Once you have control you can do something more useful than the standard handler. I have a handler that can provide a stack trace of where the purecall happened; see here: <a href=\"http://www.lenholgate.com/blog/2006/01/purecall.html\" rel=\"noreferrer\">http://www.lenholgate.com/blog/2006/01/purecall.html</a> for more details.</p>\n\n<p>(Note you can also call _set_purecall_handler() to install your handler in some versions of MSVC).</p>\n"
},
{
"answer_id": 13410826,
"author": "David Lee",
"author_id": 853315,
"author_profile": "https://Stackoverflow.com/users/853315",
"pm_score": 0,
"selected": false,
"text": "<p>I use VS2010 and whenever I try calling destructor directly from public method, I get a \"pure virtual function call\" error during runtime.</p>\n\n<pre><code>template <typename T>\nclass Foo {\npublic:\n Foo<T>() {};\n ~Foo<T>() {};\n\npublic:\n void SomeMethod1() { this->~Foo(); }; /* ERROR */\n};\n</code></pre>\n\n<p>So I moved what's inside ~Foo() to separate private method, then it worked like a charm.</p>\n\n<pre><code>template <typename T>\nclass Foo {\npublic:\n Foo<T>() {};\n ~Foo<T>() {};\n\npublic:\n void _MethodThatDestructs() {};\n void SomeMethod1() { this->_MethodThatDestructs(); }; /* OK */\n};\n</code></pre>\n"
},
{
"answer_id": 49431746,
"author": "Niki",
"author_id": 1894559,
"author_profile": "https://Stackoverflow.com/users/1894559",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Borland/CodeGear/Embarcadero/Idera C++ Builder, your can just implement </p>\n\n<pre><code>extern \"C\" void _RTLENTRY _pure_error_()\n{\n //_ErrorExit(\"Pure virtual function called\");\n throw Exception(\"Pure virtual function called\");\n}\n</code></pre>\n\n<p>While debugging place a breakpoint in the code and see the callstack in the IDE, otherwise log the call stack in your exception handler (or that function) if you have the appropriate tools for that. I personally use MadExcept for that.</p>\n\n<p>PS. The original function call is in [C++ Builder]\\source\\cpprtl\\Source\\misc\\pureerr.cpp</p>\n"
},
{
"answer_id": 56061610,
"author": "Baiyan Huang",
"author_id": 70198,
"author_profile": "https://Stackoverflow.com/users/70198",
"pm_score": 3,
"selected": false,
"text": "<p>I ran into the scenario that the pure virtual functions gets called because of destroyed objects, <code>Len Holgate</code> already have a very nice <a href=\"https://stackoverflow.com/a/100555/71312\">answer</a>, I would like\nto add some color with an example:</p>\n<ol>\n<li>A Derived object is created, and the pointer (as Base class) is\nsaved somewhere</li>\n<li>The Derived object is deleted, but somehow the pointer is\nstill referenced</li>\n<li>The pointer which points to deleted Derived\nobject gets called</li>\n</ol>\n<p>The Derived class destructor reset the vptr points to the Base class vtable, which has the pure virtual function, so when we call the virtual function, it actually calls into the pure virutal ones.</p>\n<p>This could happen because of an obvious code bug, or a complicated scenario of race condition in multi-threading environments.</p>\n<p>Here is an simple example (g++ compile with optimization turned off - a simple program could be easily optimized away):</p>\n<pre><code> #include <iostream>\n using namespace std;\n\n char pool[256];\n\n struct Base\n {\n virtual void foo() = 0;\n virtual ~Base(){};\n };\n\n struct Derived: public Base\n {\n virtual void foo() override { cout <<"Derived::foo()" << endl;}\n };\n\n int main()\n {\n auto* pd = new (pool) Derived();\n Base* pb = pd;\n pd->~Derived();\n pb->foo();\n }\n</code></pre>\n<p>And the stack trace looks like:</p>\n<pre><code>#0 0x00007ffff7499428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54\n#1 0x00007ffff749b02a in __GI_abort () at abort.c:89\n#2 0x00007ffff7ad78f7 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#3 0x00007ffff7adda46 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#4 0x00007ffff7adda81 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#5 0x00007ffff7ade84f in __cxa_pure_virtual () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#6 0x0000000000400f82 in main () at purev.C:22\n</code></pre>\n<p><strong>Highlight:</strong></p>\n<p>if the object is fully deleted, meaning destructor gets called, and memory gets reclaimed, we may simply get a <code>Segmentation fault</code> as the memory has returned to the operating system, and the program just can't access it. So this "pure virtual function call" scenario usually happens when the object is allocated on the memory pool, while an object is deleted, the underlying memory is actually not reclaimed by OS, it is still there accessible by the process.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
| I sometimes notice programs that crash on my computer with the error: "pure virtual function call".
How do these programs even compile when an object cannot be created of an abstract class? | They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.
```
class Base
{
public:
Base() { reallyDoIt(); }
void reallyDoIt() { doIt(); } // DON'T DO THIS
virtual void doIt() = 0;
};
class Derived : public Base
{
void doIt() {}
};
int main(void)
{
Derived d; // This will cause "pure virtual function call" error
}
```
See also Raymond Chen's [2](https://devblogs.microsoft.com/oldnewthing/20040428-00/?p=39613) [articles on the subject](https://devblogs.microsoft.com/oldnewthing/20131011-00/?p=2953) |
99,560 | <p>I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?</p>
<p>When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?</p>
| [
{
"answer_id": 99829,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 0,
"selected": false,
"text": "<p>If your application has users in multiple time zones, you should always store your times in UTC (any timezone would work, but you should stick with the most common convention).</p>\n\n<p>Let the user input in local time, but convert to UTC to store (and compare, and manipulate). Then, convert back from UTC to display in each users' local time zone.</p>\n"
},
{
"answer_id": 99942,
"author": "nikz",
"author_id": 3977,
"author_profile": "https://Stackoverflow.com/users/3977",
"pm_score": 4,
"selected": true,
"text": "<p>If you've set:</p>\n\n<pre><code>config.time_zone = 'UTC'\n</code></pre>\n\n<p>In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.</p>\n\n<p>Then if you set Time.zone (in a before_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.</p>\n\n<p>Just be careful with Time.now.</p>\n\n<p>Also see:</p>\n\n<p><a href=\"http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/\" rel=\"nofollow noreferrer\">http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/</a></p>\n\n<p><a href=\"http://errtheblog.com/posts/49-a-zoned-defense\" rel=\"nofollow noreferrer\">http://errtheblog.com/posts/49-a-zoned-defense</a> - you can use the JS here to detect zones</p>\n\n<p>Hope that helps.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7717/"
]
| I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?
When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate? | If you've set:
```
config.time_zone = 'UTC'
```
In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.
Then if you set Time.zone (in a before\_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.
Just be careful with Time.now.
Also see:
<http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/>
<http://errtheblog.com/posts/49-a-zoned-defense> - you can use the JS here to detect zones
Hope that helps. |
99,623 | <p>I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window. </p>
<p>Is this possible, using C++ / MFC?</p>
| [
{
"answer_id": 99629,
"author": "Andrei Belogortseff",
"author_id": 17037,
"author_profile": "https://Stackoverflow.com/users/17037",
"pm_score": 2,
"selected": false,
"text": "<p>In order to draw in the non-client area, you need to get the \"window\" DC (rather than \"client\" DC), and draw in the \"window\" DC.</p>\n"
},
{
"answer_id": 99639,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want something in the menu bar, maybe it is easier/cleaner to add it as a right-aligned menu item. This way it'll also work with different Windows themes, etc.</p>\n"
},
{
"answer_id": 99679,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 2,
"selected": false,
"text": "<p>You should try handling WM_NCPAINT. This is similar to a normal WM_PAINT message, but deals with the entire window, rather than just the client area. The MSDN documents on WM_NCPAINT provide the following sample code:</p>\n\n<pre><code>case WM_NCPAINT:\n{\n HDC hdc;\n hdc = GetDCEx(hwnd, (HRGN)wParam, DCX_WINDOW|DCX_INTERSECTRGN);\n // Paint into this DC\n ReleaseDC(hwnd, hdc);\n}\n</code></pre>\n\n<p>This code is intended to be used in the message loop of your applicaton, which is canonically organized using a large 'switch' statement.</p>\n\n<p>As noted in the MFC example from Shog, make sure to call the default version, which in this example would mean a call to DefWindowProc.</p>\n"
},
{
"answer_id": 99787,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>Charlie hit on the answer with <code>WM_NCPAINT</code>. If you're using MFC, the code would look something like this:</p>\n\n<pre><code>// in the message map\nON_WM_NCPAINT()\n\n// ...\n\nvoid CMainFrame::OnNcPaint()\n{\n // still want the menu to be drawn, so trigger default handler first\n Default();\n\n // get menu bar bounds\n MENUBARINFO menuInfo = {sizeof(MENUBARINFO)};\n if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) )\n {\n CRect windowBounds;\n GetWindowRect(&windowBounds);\n CRect menuBounds(menuInfo.rcBar);\n menuBounds.OffsetRect(-windowBounds.TopLeft());\n\n // horrible, horrible icon-drawing code. Don't use this. Seriously.\n CWindowDC dc(this);\n HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);\n ::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL);\n ::DestroyIcon(appIcon);\n }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window.
Is this possible, using C++ / MFC? | Charlie hit on the answer with `WM_NCPAINT`. If you're using MFC, the code would look something like this:
```
// in the message map
ON_WM_NCPAINT()
// ...
void CMainFrame::OnNcPaint()
{
// still want the menu to be drawn, so trigger default handler first
Default();
// get menu bar bounds
MENUBARINFO menuInfo = {sizeof(MENUBARINFO)};
if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) )
{
CRect windowBounds;
GetWindowRect(&windowBounds);
CRect menuBounds(menuInfo.rcBar);
menuBounds.OffsetRect(-windowBounds.TopLeft());
// horrible, horrible icon-drawing code. Don't use this. Seriously.
CWindowDC dc(this);
HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL);
::DestroyIcon(appIcon);
}
}
``` |
99,683 | <p>My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.</p>
<p>I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.</p>
<p>update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code.</p>
| [
{
"answer_id": 99694,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": false,
"text": "<p>I use both actually.</p>\n\n<p>I use return codes if it's a known, possible error. If it's a scenario that I know can, and will happen, then there's a code that gets sent back.</p>\n\n<p>Exceptions are used solely for things that I'm NOT expecting.</p>\n"
},
{
"answer_id": 99699,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "<p>With any decent compiler or runtime environment exceptions do not incur a significant penalty. It's more or less like a GOTO statement that jumps to the exception handler. Also, having exceptions caught by a runtime environment (like the JVM) helps isolating and fixing a bug a lot easier. I'll take a NullPointerException in Java over a segfault in C any day.</p>\n"
},
{
"answer_id": 99723,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 4,
"selected": false,
"text": "<p>My preference (in C++ and Python) is to use exceptions. The language-provided facilities make it a well-defined process to both raise, catch and (if necessary) re-throw exceptions, making the model easy to see and use. Conceptually, it's cleaner than return codes, in that specific exceptions can be defined by their names, and have additional information accompanying them. With a return code, you're limited to just the error value (unless you want to define an ReturnStatus object or something).</p>\n\n<p>Unless the code you're writing is time-critical, the overhead associated with unwinding the stack is not significant enough to worry about.</p>\n"
},
{
"answer_id": 99725,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 3,
"selected": false,
"text": "<p>Exceptions should only be returned where something happens that you were not expecting.</p>\n\n<p>The other point of exceptions, historically, is that return codes are inherently proprietary, sometimes a 0 could be returned from a C function to indicate success, sometimes -1, or either of them for a fail with 1 for a success. Even when they are enumerated, enumerations can be ambiguous.</p>\n\n<p>Exceptions can also provide a lot more information, and specifically spell out well 'Something Went Wrong, here's what, a stack trace and some supporting information for the context'</p>\n\n<p>That being said, a well enumerated return code can be useful for a known set of outcomes, a simple 'heres n outcomes of the function, and it just ran this way'</p>\n"
},
{
"answer_id": 99728,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "<p>I only use exceptions, no return codes. I'm talking about Java here.</p>\n\n<p>The general rule I follow is if I have a method called <code>doFoo()</code> then it follows that if it doesn't \"do foo\", as it were, then something exceptional has happened and an Exception should be thrown.</p>\n"
},
{
"answer_id": 99735,
"author": "Smashery",
"author_id": 14902,
"author_profile": "https://Stackoverflow.com/users/14902",
"pm_score": 2,
"selected": false,
"text": "<p>A great piece of advice I got from <em>The Pragmatic Programmer</em> was something along the lines of \"your program should be able to perform all its main functionality without using exceptions at all\".</p>\n"
},
{
"answer_id": 99740,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 1,
"selected": false,
"text": "<p>One thing I fear about exceptions is that throwing an exception will screw up code flow. For example if you do </p>\n\n<pre><code>void foo()\n{\n MyPointer* p = NULL;\n try{\n p = new PointedStuff();\n //I'm a module user and I'm doing stuff that might throw or not\n\n }\n catch(...)\n {\n //should I delete the pointer?\n }\n}\n</code></pre>\n\n<p>Or even worse what if I deleted something I shouldn't have, but got thrown to catch before I did the rest of the cleanup. Throwing put a lot of weight on the poor user IMHO.</p>\n"
},
{
"answer_id": 99742,
"author": "Trent",
"author_id": 9083,
"author_profile": "https://Stackoverflow.com/users/9083",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to use exceptions for error handling and return values (or parameters) as the normal result of a function. This gives an easy and consistent error-handling scheme and if done correctly it makes for much cleaner looking code.</p>\n"
},
{
"answer_id": 99749,
"author": "Daniel Bruce",
"author_id": 6456,
"author_profile": "https://Stackoverflow.com/users/6456",
"pm_score": 2,
"selected": false,
"text": "<p>One of the big differences is that exceptions force you to handle an error, whereas error return codes can go unchecked. </p>\n\n<p>Error return codes, if used heavily, can also cause very ugly code with lots of if tests similar to this form:</p>\n\n<pre><code>if(function(call) != ERROR_CODE) {\n do_right_thing();\n}\nelse {\n handle_error();\n}\n</code></pre>\n\n<p>Personally I prefer to use exceptions for errors that SHOULD or MUST be acted upon by the calling code, and only use error codes for \"expected failings\" where returning something is actually valid and possible.</p>\n"
},
{
"answer_id": 99754,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>In Java, I use (in the following order):</p>\n\n<ol>\n<li><p>Design-by-contract (ensuring preconditions are met before trying <em>anything</em> that might fail). This catches most things and I return an error code for this.</p></li>\n<li><p>Returning error codes whilst processing work (and performing rollback if needed).</p></li>\n<li><p>Exceptions, but these are used <em>only</em> for unexpected things.</p></li>\n</ol>\n"
},
{
"answer_id": 99756,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>My general rule in the exception vs. return code argument:</p>\n\n<ul>\n<li>Use errorcodes when you need localization/internationalization -- in .NET, you could use these errorcodes to reference a resource file which will then display the error in the appropriate language. Otherwise, use exceptions</li>\n<li>Use exceptions only for errors that are <em>really</em> exceptional. If it's something that happens fairly often, either use a boolean or an enum errorcode.</li>\n</ul>\n"
},
{
"answer_id": 99764,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a <a href=\"http://typethinker.blogspot.com/2007/04/checks-exceptions-and-assertions.html\" rel=\"noreferrer\">blog post</a> about this a while ago.</p>\n\n<p>The performance overhead of throwing an exception should not play any role in your decision. If you're doing it right, after all, an exception is <em>exceptional</em>.</p>\n"
},
{
"answer_id": 99771,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 2,
"selected": false,
"text": "<p>There is many reason to prefer Exceptions over return code:</p>\n\n<ul>\n<li>Usually, for readibility, people try to minimize the number of return statement in a method. Doing so, exceptions prevent to do some extra work while in a incoorect state, and thus prevent to potentially damage more data.</li>\n<li>Exception are generally more verbose arn more easilly extensible than return value. Assume that a method return natural number and that you use negative numbers as return code when an error occurs, if the scope of you method change and now return integers, you'll have to modify all the method calls instead of just tweaking a little bit the exception.</li>\n<li>Exceptions allows more easilly to separate error handling of normal behaviour. They allows to ensure that some operations performs somehow as an atomic operation.</li>\n</ul>\n"
},
{
"answer_id": 99775,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 2,
"selected": false,
"text": "<p>I have a simple set of rules:</p>\n\n<p>1) Use return codes for things you expect your immediate caller to react to.</p>\n\n<p>2) Use exceptions for errors that are broader in scope, and may reasonable be expected to be handled by something many levels above the caller so that awareness of the error does not have to percolate up through many layers, making code more complex.</p>\n\n<p>In Java I only ever used unchecked exceptions, checked exceptions end up just being another form of return code and in my experience the duality of what might be \"returned\" by a method call was generally more of a hinderance than a help.</p>\n"
},
{
"answer_id": 99784,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": false,
"text": "<p>I dislike return codes because they cause the following pattern to mushroom throughout your code</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>CRetType obReturn = CODE_SUCCESS;\nobReturn = CallMyFunctionWhichReturnsCodes();\nif (obReturn == CODE_BLOW_UP)\n{\n // bail out\n goto FunctionExit;\n}\n</code></pre>\n\n<p>Soon a method call consisting of 4 function calls bloats up with 12 lines of error handling.. Some of which will never happen. If and switch cases abound.</p>\n\n<p>Exceptions are cleaner if you use them well... to signal exceptional events .. after which the execution path cannot continue. They are often more descriptive and informational than error codes.</p>\n\n<p>If you have multiple states after a method call that should be handled differently (and are not exceptional cases), use error codes or out params. Although Personaly I've found this to be rare.. </p>\n\n<p>I've hunted a bit about the 'performance penalty' counterargument.. more in the C++ / COM world but in the newer languages, I think the difference isn't that much. In any case, when something blows up, performance concerns are relegated to the backburner :)</p>\n"
},
{
"answer_id": 99800,
"author": "Jonathan Adelson",
"author_id": 8092,
"author_profile": "https://Stackoverflow.com/users/8092",
"pm_score": 1,
"selected": false,
"text": "<p>I don't find return codes to be less ugly than exceptions. With the exception, you have the <code>try{} catch() {} finally {}</code> where as with return codes you have <code>if(){}</code>. I used to fear exceptions for the reasons given in the post; you don't know if the pointer needs to be cleared, what have you. But I think you have the same problems when it comes to the return codes. You don't know the state of the parameters unless you know some details about the function/method in question.</p>\n\n<p>Regardless, you have to handle the error if possible. You can just as easily let an exception propagate to the top level as ignore a return code and let the program segfault.</p>\n\n<p>I do like the idea of returning a value (enumeration?) for results and an exception for an exceptional case.</p>\n"
},
{
"answer_id": 99822,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "<p>I use Exceptions in python in both Exceptional, and non-Exceptional circumstances.</p>\n\n<p>It is often nice to be able to use an Exception to indicate the \"request could not be performed\", as opposed to returning an Error value. It means that you /always/ know that the return value is the right type, instead of arbitarily None or NotFoundSingleton or something. Here is a good example of where I prefer to use an exception handler instead of a conditional on the return value.</p>\n\n<pre><code>try:\n dataobj = datastore.fetch(obj_id)\nexcept LookupError:\n # could not find object, create it.\n dataobj = datastore.create(....)\n</code></pre>\n\n<p>The side effect is that when a datastore.fetch(obj_id) is run, you never have to check if its return value is None, you get that error immediately for free. This is counter to the argument, \"your program should be able to perform all its main functionality without using exceptions at all\".</p>\n\n<p>Here is another example of where exceptions are 'exceptionally' useful, in order to write code for dealing with the filesystem that isn't subject to race conditions.</p>\n\n<pre><code># wrong way:\nif os.path.exists(directory_to_remove):\n # race condition is here.\n os.path.rmdir(directory_to_remove)\n\n# right way:\ntry: \n os.path.rmdir(directory_to_remove)\nexcept OSError:\n # directory didn't exist, good.\n pass\n</code></pre>\n\n<p>One system call instead of two, no race condition. This is a poor example because obviously this will fail with an OSError in more circumstances than the directory doesn't exist, but it's a 'good enough' solution for many tightly controlled situations.</p>\n"
},
{
"answer_id": 99878,
"author": "rpattabi",
"author_id": 15139,
"author_profile": "https://Stackoverflow.com/users/15139",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the return codes adds to code noise. For example, I always hated the look of COM/ATL code due to return codes. There had to be an HRESULT check for every line of code. I consider the error return code is one of the bad decisions made by architects of COM. It makes it difficult to do logical grouping of the code, thus code review becomes difficult. </p>\n\n<p>I am not sure about the performance comparison when there is an explicit check for the return code every line.</p>\n"
},
{
"answer_id": 100300,
"author": "noocyte",
"author_id": 11220,
"author_profile": "https://Stackoverflow.com/users/11220",
"pm_score": 2,
"selected": false,
"text": "<p>Exceptions are not for error handling, IMO. Exceptions are just that; exceptional events that you did not expect. Use with caution I say. </p>\n\n<p>Error codes can be OK, but returning 404 or 200 from a method is bad, IMO. Use enums (.Net) instead, that makes the code more readable and easier to use for other developers. Also you don't have to maintain a table over numbers and descriptions.</p>\n\n<p>Also; the try-catch-finally pattern is an anti-pattern in my book. Try-finally can be good, try-catch can also be good but try-catch-finally is never good. try-finally can often times be replaced by a \"using\" statement (IDispose pattern), which is better IMO. And Try-catch where you actually catch an exception you're able to handle is good, or if you do this:</p>\n\n<pre><code>try{\n db.UpdateAll(somevalue);\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\n</code></pre>\n\n<p>So as long as you let the exception continue to bubble it's OK. Another example is this:</p>\n\n<pre><code>try{\n dbHasBeenUpdated = db.UpdateAll(somevalue); // true/false\n}\ncatch (ConnectionException ex) {\n logger.Exception(ex, \"Connection failed\");\n dbHasBeenUpdated = false;\n}\n</code></pre>\n\n<p>Here I actually handle the exception; what I do outside of the try-catch when the update method fails is another story, but I think my point has been made. :)</p>\n\n<p>Why is then try-catch-finally an anti-pattern? Here's why:</p>\n\n<pre><code>try{\n db.UpdateAll(somevalue);\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\nfinally {\n db.Close();\n}\n</code></pre>\n\n<p>What happens if the db object has already been closed? A new exception is thrown and it has to be handled! This is better:</p>\n\n<pre><code>try{\n using(IDatabase db = DatabaseFactory.CreateDatabase()) {\n db.UpdateAll(somevalue);\n }\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\n</code></pre>\n\n<p>Or, if the db object does not implement IDisposable do this:</p>\n\n<pre><code>try{\n try {\n IDatabase db = DatabaseFactory.CreateDatabase();\n db.UpdateAll(somevalue);\n }\n finally{\n db.Close();\n }\n}\ncatch (DatabaseAlreadyClosedException dbClosedEx) {\n logger.Exception(dbClosedEx, \"Database connection was closed already.\");\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\n</code></pre>\n\n<p>That's my 2 cents anyway! :)</p>\n"
},
{
"answer_id": 100395,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 5,
"selected": false,
"text": "<p>According to Chapter 7 titled \"Exceptions\" in <strong>Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries</strong>, numerous rationales are given for why using exceptions over return values is necessary for OO frameworks such as C#.</p>\n\n<p>Perhaps this is the most compelling reason (page 179):</p>\n\n<p>\"Exceptions integrate well with object-oriented languages. Object-oriented languages tend to impose constraints on member signatures that are not imposed by functions in non-OO languages. <strong>For example, in the case of constructors, operator overloads, and properties, the developer has no choice in the return value.</strong> For this reason, it is not possible to standardize on return-value-based error reporting for object-oriented frameworks. <strong>An error reporting method, such as exceptions, which is out of band of the method signature is the only option.</strong>\"</p>\n"
},
{
"answer_id": 111213,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": true,
"text": "<h1>For some languages (i.e. C++) Resources leak should not be a reason</h1>\n<p>C++ is based on RAII.</p>\n<p>If you have code that could fail, return or throw (that is, most normal code), then you should have your pointer wrapped inside a smart pointer (assuming you have a <em>very good</em> reason to not have your object created on stack).</p>\n<h1>Return codes are more verbose</h1>\n<p>They are verbose, and tend to develop into something like:</p>\n<pre><code>if(doSomething())\n{\n if(doSomethingElse())\n {\n if(doSomethingElseAgain())\n {\n // etc.\n }\n else\n {\n // react to failure of doSomethingElseAgain\n }\n }\n else\n {\n // react to failure of doSomethingElse\n }\n}\nelse\n{\n // react to failure of doSomething\n}\n</code></pre>\n<p>In the end, you code is a collection of idented instructions (I saw this kind of code in production code).</p>\n<p>This code could well be translated into:</p>\n<pre><code>try\n{\n doSomething() ;\n doSomethingElse() ;\n doSomethingElseAgain() ;\n}\ncatch(const SomethingException & e)\n{\n // react to failure of doSomething\n}\ncatch(const SomethingElseException & e)\n{\n // react to failure of doSomethingElse\n}\ncatch(const SomethingElseAgainException & e)\n{\n // react to failure of doSomethingElseAgain\n}\n</code></pre>\n<p>Which cleanly separate code and error processing, which <strong>can</strong> be a <strong>good</strong> thing.</p>\n<h1>Return codes are more brittle</h1>\n<p>If not some obscure warning from one compiler (see "phjr" 's comment), they can easily be ignored.</p>\n<p>With the above examples, assume than someone forgets to handle its possible error (this happens...). The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception.</p>\n<p>The error won't be ignored. Sometimes, you want it to not explode, though... So you must chose carefully.</p>\n<h1>Return Codes must sometimes be translated</h1>\n<p>Let's say we have the following functions:</p>\n<ul>\n<li>doSomething, which can return an int called NOT_FOUND_ERROR</li>\n<li>doSomethingElse, which can return a bool "false" (for failed)</li>\n<li>doSomethingElseAgain, which can return an Error object (with both the __LINE__, __FILE__ and half the stack variables.</li>\n<li>doTryToDoSomethingWithAllThisMess which, well... Use the above functions, and return an error code of type...</li>\n</ul>\n<p>What is the type of the return of doTryToDoSomethingWithAllThisMess if one of its called functions fail ?</p>\n<h1>Return Codes are not a universal solution</h1>\n<p>Operators cannot return an error code. C++ constructors can't, too.</p>\n<h1>Return Codes means you can't chain expressions</h1>\n<p>The corollary of the above point. What if I want to write:</p>\n<pre><code>CMyType o = add(a, multiply(b, c)) ;\n</code></pre>\n<p>I can't, because the return value is already used (and sometimes, it can't be changed). So the return value becomes the first parameter, sent as a reference... Or not.</p>\n<h1>Exception are typed</h1>\n<p>You can send different classes for each kind of exception. Ressources exceptions (i.e. out of memory) should be light, but anything else could be as heavy as necessary (I like the Java Exception giving me the whole stack).</p>\n<p>Each catch can then be specialized.</p>\n<h1>Don't ever use catch(...) without re-throwing</h1>\n<p>Usually, you should not hide an error. If you do not re-throw, at the very least, log the error in a file, open a messagebox, whatever...</p>\n<h1>Exception are... NUKE</h1>\n<p>The problem with exception is that overusing them will produce code full of try/catches. But the problem is elsewhere: Who try/catch his/her code using STL container? Still, those containers can send an exception.</p>\n<p>Of course, in C++, don't ever let an exception exit a destructor.</p>\n<h1>Exception are... synchronous</h1>\n<p>Be sure to catch them before they bring out your thread on its knees, or propagate inside your Windows message loop.</p>\n<h1>The solution could be mixing them?</h1>\n<p>So I guess the solution is to throw when something should <strong>not</strong> happen. And when something can happen, then use a return code or a parameter to enable to user to react to it.</p>\n<p>So, the only question is "what is something that should not happen?"</p>\n<p>It depends on the contract of your function. If the function accepts a pointer, but specifies the pointer must be non-NULL, then it is ok to throw an exception when the user sends a NULL pointer (the question being, in C++, when didn't the function author use references instead of pointers, but...)</p>\n<h1>Another solution would be to show the error</h1>\n<p>Sometimes, your problem is that you don't want errors. Using exceptions or error return codes are cool, but... You want to know about it.</p>\n<p>In my job, we use a kind of "Assert". It will, depending on the values of a configuration file, no matter the debug/release compile options:</p>\n<ul>\n<li>log the error</li>\n<li>open a messagebox with a "Hey, you have a problem"</li>\n<li>open a messagebox with a "Hey, you have a problem, do you want to debug"</li>\n</ul>\n<p>In both development and testing, this enable the user to pinpoint the problem exactly when it is detected, and not after (when some code cares about the return value, or inside a catch).</p>\n<p>It is easy to add to legacy code. For example:</p>\n<pre><code>void doSomething(CMyObject * p, int iRandomData)\n{\n // etc.\n}\n</code></pre>\n<p>leads a kind of code similar to:</p>\n<pre><code>void doSomething(CMyObject * p, int iRandomData)\n{\n if(iRandomData < 32)\n {\n MY_RAISE_ERROR("Hey, iRandomData " << iRandomData << " is lesser than 32. Aborting processing") ;\n return ;\n }\n\n if(p == NULL)\n {\n MY_RAISE_ERROR("Hey, p is NULL !\\niRandomData is equal to " << iRandomData << ". Will throw.") ;\n throw std::some_exception() ;\n }\n\n if(! p.is Ok())\n {\n MY_RAISE_ERROR("Hey, p is NOT Ok!\\np is equal to " << p->toString() << ". Will try to continue anyway") ;\n }\n\n // etc.\n}\n</code></pre>\n<p>(I have similar macros that are active only on debug).</p>\n<p>Note that on production, the configuration file does not exist, so the client never sees the result of this macro... But it is easy to activate it when needed.</p>\n<h1>Conclusion</h1>\n<p>When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough.</p>\n<p>When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen".</p>\n<p>But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible". The macro I spoke above follow this philosophy.</p>\n"
},
{
"answer_id": 46982339,
"author": "b_levitt",
"author_id": 852208,
"author_profile": "https://Stackoverflow.com/users/852208",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Always use exceptions by default, but consider providing an additional tester-doer option (TryX)!</strong> For me the answer is really clear. When the context dictates a Try or Tester-Doer pattern (ie cpu intensive or public api), I will ADDITIONALLY provide those methods to the exception throwing version. I think blanket rules of avoiding exceptions are misguided, unsupported, and likely cause far more expense in terms of bugs, than any performance issues they claim to prevent.</p>\n<p><strong>No, <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance\" rel=\"nofollow noreferrer\">Microsoft</a> DOES NOT say to not use exceptions (common misinterpretation).</strong></p>\n<p>It says if you're <strong>designing an API</strong> provide ways to help a user of that API to avoid THROWING exceptions if they need too (Try and Tester-Doer patterns)</p>\n<blockquote>\n<p>❌ DO NOT use exceptions for the normal flow of control, if possible.</p>\n<p>Except for system failures and operations with potential race\nconditions, framework designers should design APIs so users can write\ncode that does not throw exceptions. For example, you can provide a\nway to check preconditions before calling a member so users can write\ncode that does not throw exceptions.</p>\n</blockquote>\n<p><em>What is inferred here is that the non-tester-doer/non-try implementation SHOULD throw an exception upon failure and then the user CAN change that to one of your tester-doer or try methods for performance. Pit of success is maintained for safety and the user OPTS INTO the more dangerous but more performant method.</em></p>\n<p><strong>Microsoft DOES say to NOT use return codes TWICE, <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing\" rel=\"nofollow noreferrer\">here</a>:</strong></p>\n<blockquote>\n<p>❌ DO NOT return error codes.</p>\n<p>Exceptions are the primary means of reporting errors in frameworks.</p>\n<p>✔️ DO report execution failures by throwing exceptions.</p>\n</blockquote>\n<p>and <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance\" rel=\"nofollow noreferrer\">here</a>:</p>\n<blockquote>\n<p>❌ DO NOT use error codes because of concerns that exceptions might\naffect performance negatively.</p>\n<p>To improve performance, it is possible to use either the Tester-Doer\nPattern or the Try-Parse Pattern, described in the next two sections.</p>\n</blockquote>\n<p><em>If you're not using exceptions you're probably breaking this other rule of returning return codes or booleans from a non-tester/non-try implementation.\nAgain, TryParse does not replace Parse. It is provided in addition to Parse</em></p>\n<p><strong>MAIN REASON: Return codes fail the "<a href=\"https://blogs.msdn.microsoft.com/ricom/2015/12/16/pit-of-success-for-organizations/\" rel=\"nofollow noreferrer\">Pit of Success</a>" test for me almost every time.</strong></p>\n<ul>\n<li>It is far too easy to forget to check a return code and then have a red-herring error later on.\n<ul>\n<li>var success = Save()? How much performance is worth someone forgetting an if check here?</li>\n<li>var success = TrySave()? Better, but are we going to abuse everything with the TryX pattern? Did you still provide a Save method?</li>\n</ul>\n</li>\n<li>Return codes don't have any of the great debugging information on them like call stack, inner exceptions.</li>\n<li>Return codes do not propagate which, along with the point above, tends to drive excessive and interwoven diagnostic logging instead of logging in one centralized place (application and thread level exception handlers).</li>\n<li>Return codes tend to drive messy code in the form of nested 'if' blocks</li>\n<li>Developer time spent debugging an unknown issue that would otherwise have been an obvious exception (pit of success) IS expensive.</li>\n<li>If the team behind C# didn't intend for exceptions to govern control flow, execeptions wouldn't be typed, there would be no "when" filter on catch statements, and there would be no need for the parameter-less 'throw' statement.</li>\n</ul>\n<p><strong>Regarding Performance:</strong></p>\n<ul>\n<li><p>Exceptions may be computationally expensive RELATIVE to not throwing at all, but they're called EXCEPTIONS for a reason. Speed comparisons always manage to assume a 100% exception rate which should never be the case. Even if an exception is 100x slower, how much does that really matter if it only happens 1% of the time?</p>\n</li>\n<li><p>Context is everything. For example, A Tester-Doer or Try option to avoid a unique key violation is likely to waste more time and resources on average (checking for existance when a collision is rare) than just assuming a successful entry and catching that rare violation.</p>\n</li>\n<li><p>Unless we're talking floating point arithmetic for graphics applications or something similar, CPU cycles are cheap compared to developer time.</p>\n</li>\n<li><p>Cost from a time perspective carries the same argument. Relative to database queries or web service calls or file loads, normal application time will dwarf exception time. Exceptions were nearly <a href=\"http://stackoverflow.com/questions/891217/how-expensive-are-exceptions-in-c\">sub-MICROsecond in 2006</a></p>\n</li>\n<li><p>I dare anybody that works in .net, to set your debugger to break on all exceptions and disable just my code and see how many exceptions are already happening that you don't even know about.</p>\n</li>\n<li><p>Jon Skeet says <a href=\"http://not%20slow%20enough%20to%20make%20it%20worth%20avoiding%20them%20in%20normal%20use\" rel=\"nofollow noreferrer\">"[Exceptions are] not slow enough to make it worth avoiding them in normal use"</a>. The linked response also contains two articles from Jon on the subject. His generalized theme is that exceptions are fine and if you're experiencing them as a performance problem, there's likely a larger design issue.</p>\n</li>\n</ul>\n"
},
{
"answer_id": 48895320,
"author": "2ank3th",
"author_id": 2094168,
"author_profile": "https://Stackoverflow.com/users/2094168",
"pm_score": 0,
"selected": false,
"text": "<p>For a language like Java, I would go with Exception because the compiler gives compile time error if exceptions are not handled.This forces the calling function to handle/throw the exceptions. </p>\n\n<p>For Python, I am more conflicted. There is no compiler so it's possible that caller does not handle the exception thrown by the function leading to runtime exceptions. If you use return codes you might have unexpected behavior if not handled properly and if you use exceptions you might get runtime exceptions. </p>\n"
},
{
"answer_id": 63397412,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 2,
"selected": false,
"text": "<p>I generally prefer return codes because <strong>they let the caller decide whether the failure is exceptional</strong>.</p>\n<p>This approach is typical in the Elixir language.</p>\n<pre><code># I care whether this succeeds. If it doesn't return :ok, raise an exception.\n:ok = File.write(path, content)\n\n# I don't care whether this succeeds. Don't check the return value.\nFile.write(path, content)\n\n# This had better not succeed - the path should be read-only to me.\n# If I get anything other than this error, raise an exception.\n{:error, :erofs} = File.write(path, content)\n\n# I want this to succeed but I can handle its failure\ncase File.write(path, content) do\n :ok => handle_success()\n error => handle_error(error)\nend\n</code></pre>\n<p>People mentioned that return codes can cause you to have a lot of nested <code>if</code> statements, but that can be handled with better syntax. In Elixir, the <code>with</code> statement lets us easily separate a series of happy-path return value from any failures.</p>\n<pre><code>with {:ok, content} <- get_content(),\n :ok <- File.write(path, content) do\n IO.puts "everything worked, happy path code goes here"\nelse\n # Here we can use a single catch-all failure clause\n # or match every kind of failure individually\n # or match subsets of them however we like\n _some_error => IO.puts "one of those steps failed"\n _other_error => IO.puts "one of those steps failed"\nend\n</code></pre>\n<p>Elixir still has functions that raise exceptions. Going back to my first example, I could do either of these to raise an exception if the file can't be written.</p>\n<pre><code># Raises a generic MatchError because the return value isn't :ok\n:ok = File.write(path, content)\n\n# Raises a File.Error with a descriptive error message - eg, saying\n# that the file is read-only\nFile.write!(path, content)\n</code></pre>\n<p>If I, as the caller, know that I want to raise an error if the write fails, I can choose to call <code>File.write!</code> instead of <code>File.write</code>.\nOr I can choose to call <code>File.write</code> and handle each of the possible reasons for failure differently.</p>\n<p>Of course it's always possible to <code>rescue</code> an exception if we want to. But compared to handling an informative return value, it seems awkward to me. If I know that a function call can fail or even should fail, its failure isn't an exceptional case.</p>\n"
},
{
"answer_id": 72937513,
"author": "Carsten Führmann",
"author_id": 1290368,
"author_profile": "https://Stackoverflow.com/users/1290368",
"pm_score": 0,
"selected": false,
"text": "<p>There are some important aspects that remain unmentioned in this - very interesting - discussion so far.</p>\n<p>First, it is important to note that exceptions don't apply to distributed computing, but error codes still do. Imagine communicating services distributed over multiple servers. Some communication might even be asynchronous. And the services might even use different technology stacks. Cleary, an error-handling concept is crucial here. And clearly, exceptions can't be used in this most general case, since errors have to be serialized things sent "through the cable", perhaps even in a language-neutral way. From that angle, error codes (really, error <em>messages</em>) are more universal than exceptions. One needs good error-message Kung Fu once one assumes a system-architect view and things need to scale.</p>\n<p>The second point is a very different, it is about if or how a language represents discriminated unions. The question was strictly speaking about "error codes". And so were some the answers, mentioning that error codes cannot transport information as nicely as exceptions. This is true if an error code is a number. But for a fairer contrasting with exceptions, one should probably consider error <em>values</em> of discriminated union type. So, the return value of the callee would be of discriminated union type, and it would either be the desired happy-path value or <em>the payload the exception would otherwise have</em>. How often this approach is elegant enough to be preferable depends on the programming language. For example, F# has super elegant discriminated unions and the according pattern matching. In such a language it would be more seductive to avoid exceptions than in, say, C++.</p>\n<p>The third and final point is about functional programming and pure functions. Exceptions are (in a practical way and in a theoretical-computer-science way) "side effects". In other words, functions or methods that deal with exceptions are not <em>pure</em>. (One practical consequence is that with exceptions one must pay attention to evaluation order.) By contrast, error values are pure, because the are just ordinary return values, with no side effects involved. Therefore, functional programmers may more likely frown upon exceptions than object-oriented programmers. (In particular if the language also has an elegant representation of the aforementioned discriminated unions.)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
]
| My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.
I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.
update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code. | For some languages (i.e. C++) Resources leak should not be a reason
===================================================================
C++ is based on RAII.
If you have code that could fail, return or throw (that is, most normal code), then you should have your pointer wrapped inside a smart pointer (assuming you have a *very good* reason to not have your object created on stack).
Return codes are more verbose
=============================
They are verbose, and tend to develop into something like:
```
if(doSomething())
{
if(doSomethingElse())
{
if(doSomethingElseAgain())
{
// etc.
}
else
{
// react to failure of doSomethingElseAgain
}
}
else
{
// react to failure of doSomethingElse
}
}
else
{
// react to failure of doSomething
}
```
In the end, you code is a collection of idented instructions (I saw this kind of code in production code).
This code could well be translated into:
```
try
{
doSomething() ;
doSomethingElse() ;
doSomethingElseAgain() ;
}
catch(const SomethingException & e)
{
// react to failure of doSomething
}
catch(const SomethingElseException & e)
{
// react to failure of doSomethingElse
}
catch(const SomethingElseAgainException & e)
{
// react to failure of doSomethingElseAgain
}
```
Which cleanly separate code and error processing, which **can** be a **good** thing.
Return codes are more brittle
=============================
If not some obscure warning from one compiler (see "phjr" 's comment), they can easily be ignored.
With the above examples, assume than someone forgets to handle its possible error (this happens...). The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception.
The error won't be ignored. Sometimes, you want it to not explode, though... So you must chose carefully.
Return Codes must sometimes be translated
=========================================
Let's say we have the following functions:
* doSomething, which can return an int called NOT\_FOUND\_ERROR
* doSomethingElse, which can return a bool "false" (for failed)
* doSomethingElseAgain, which can return an Error object (with both the \_\_LINE\_\_, \_\_FILE\_\_ and half the stack variables.
* doTryToDoSomethingWithAllThisMess which, well... Use the above functions, and return an error code of type...
What is the type of the return of doTryToDoSomethingWithAllThisMess if one of its called functions fail ?
Return Codes are not a universal solution
=========================================
Operators cannot return an error code. C++ constructors can't, too.
Return Codes means you can't chain expressions
==============================================
The corollary of the above point. What if I want to write:
```
CMyType o = add(a, multiply(b, c)) ;
```
I can't, because the return value is already used (and sometimes, it can't be changed). So the return value becomes the first parameter, sent as a reference... Or not.
Exception are typed
===================
You can send different classes for each kind of exception. Ressources exceptions (i.e. out of memory) should be light, but anything else could be as heavy as necessary (I like the Java Exception giving me the whole stack).
Each catch can then be specialized.
Don't ever use catch(...) without re-throwing
=============================================
Usually, you should not hide an error. If you do not re-throw, at the very least, log the error in a file, open a messagebox, whatever...
Exception are... NUKE
=====================
The problem with exception is that overusing them will produce code full of try/catches. But the problem is elsewhere: Who try/catch his/her code using STL container? Still, those containers can send an exception.
Of course, in C++, don't ever let an exception exit a destructor.
Exception are... synchronous
============================
Be sure to catch them before they bring out your thread on its knees, or propagate inside your Windows message loop.
The solution could be mixing them?
==================================
So I guess the solution is to throw when something should **not** happen. And when something can happen, then use a return code or a parameter to enable to user to react to it.
So, the only question is "what is something that should not happen?"
It depends on the contract of your function. If the function accepts a pointer, but specifies the pointer must be non-NULL, then it is ok to throw an exception when the user sends a NULL pointer (the question being, in C++, when didn't the function author use references instead of pointers, but...)
Another solution would be to show the error
===========================================
Sometimes, your problem is that you don't want errors. Using exceptions or error return codes are cool, but... You want to know about it.
In my job, we use a kind of "Assert". It will, depending on the values of a configuration file, no matter the debug/release compile options:
* log the error
* open a messagebox with a "Hey, you have a problem"
* open a messagebox with a "Hey, you have a problem, do you want to debug"
In both development and testing, this enable the user to pinpoint the problem exactly when it is detected, and not after (when some code cares about the return value, or inside a catch).
It is easy to add to legacy code. For example:
```
void doSomething(CMyObject * p, int iRandomData)
{
// etc.
}
```
leads a kind of code similar to:
```
void doSomething(CMyObject * p, int iRandomData)
{
if(iRandomData < 32)
{
MY_RAISE_ERROR("Hey, iRandomData " << iRandomData << " is lesser than 32. Aborting processing") ;
return ;
}
if(p == NULL)
{
MY_RAISE_ERROR("Hey, p is NULL !\niRandomData is equal to " << iRandomData << ". Will throw.") ;
throw std::some_exception() ;
}
if(! p.is Ok())
{
MY_RAISE_ERROR("Hey, p is NOT Ok!\np is equal to " << p->toString() << ". Will try to continue anyway") ;
}
// etc.
}
```
(I have similar macros that are active only on debug).
Note that on production, the configuration file does not exist, so the client never sees the result of this macro... But it is easy to activate it when needed.
Conclusion
==========
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough.
When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen".
But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible". The macro I spoke above follow this philosophy. |
99,684 | <p>The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?</p>
<p>If object <code> foo </code> calls into object <code> bar</code>, is it correct to say (in pseudo-code):</p>
<pre><code>bar = new barClass()
foo = new fooClass(bar)
</code></pre>
<p>What happens if you need to pass messages back and forth? Do you need a method for registering the target object?</p>
<pre><code>foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
</code></pre>
<p>Is there a pattern that addresses this?</p>
| [
{
"answer_id": 99700,
"author": "scubabbl",
"author_id": 9450,
"author_profile": "https://Stackoverflow.com/users/9450",
"pm_score": 0,
"selected": false,
"text": "<p>Well, depending on the level of messaging, you could implement a messaging service. Objects listen for messages, or register as a MessageListener on some MessageProvider.</p>\n\n<p>You end up with cyclical dependencies if two objects have references to each other, which I would consider bad in most cases.</p>\n"
},
{
"answer_id": 99789,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 2,
"selected": false,
"text": "<p>Dependency injection frameworks like <a href=\"http://www.springframework.org/documentation\" rel=\"nofollow noreferrer\">Spring</a> and <a href=\"http://code.google.com/p/google-guice/\" rel=\"nofollow noreferrer\">Guice</a> provide a solution to cyclical dependencies in Java by using proxies which can resolve the receiver of a message the first time it is required. This isn't a generally applicable OO pattern, however. </p>\n"
},
{
"answer_id": 99821,
"author": "Rob Gray",
"author_id": 5691,
"author_profile": "https://Stackoverflow.com/users/5691",
"pm_score": 3,
"selected": true,
"text": "<p>Generally dependency injection is the way to go. If you're just talking about two objects communicating then pass an instance of one in as a paramter to the other, as in your first example. Passing in the constructor ensure the reference is always valid. Otherwise you'd have to test to ensure register had been called. Also you'd need to make sure calling register more than once wouldn't have adverse effects.</p>\n\n<p>What if you want a controlling object, to which other objects register for events. It would then be suitable to use a Register method ( which may add to a delegate).</p>\n\n<p>See <a href=\"http://www.dofactory.com/Patterns/PatternObserver.aspx\" rel=\"nofollow noreferrer\">Observer Pattern</a></p>\n"
},
{
"answer_id": 99921,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 0,
"selected": false,
"text": "<p>One of your object types could be a factory for the other. When Foo poops out a new Bar, the connection has already been made:</p>\n\n<pre><code>foo = new Foo();\nbar = Foo.Poop();\n\nfunction Foo::Poop()\n{\n bar = new Bar(this);\n myChildren.Add(bar);\n return bar;\n}\n\nbar.SayHiToParent();\nfoo.SayHiToChildren();\n</code></pre>\n"
},
{
"answer_id": 100384,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 0,
"selected": false,
"text": "<p>I think that it highly depends on what the exact relation is between the two objects. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8092/"
]
| The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?
If object `foo` calls into object `bar`, is it correct to say (in pseudo-code):
```
bar = new barClass()
foo = new fooClass(bar)
```
What happens if you need to pass messages back and forth? Do you need a method for registering the target object?
```
foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
```
Is there a pattern that addresses this? | Generally dependency injection is the way to go. If you're just talking about two objects communicating then pass an instance of one in as a paramter to the other, as in your first example. Passing in the constructor ensure the reference is always valid. Otherwise you'd have to test to ensure register had been called. Also you'd need to make sure calling register more than once wouldn't have adverse effects.
What if you want a controlling object, to which other objects register for events. It would then be suitable to use a Register method ( which may add to a delegate).
See [Observer Pattern](http://www.dofactory.com/Patterns/PatternObserver.aspx) |
99,732 | <p>Using reflection in .Net, what is the differnce between:</p>
<pre><code> if (foo.IsAssignableFrom(typeof(IBar)))
</code></pre>
<p>And</p>
<pre><code> if (foo.GetInterface(typeof(IBar).FullName) != null)
</code></pre>
<p>Which is more appropriate, why?<br></p>
<p>When could one or the other fail?</p>
| [
{
"answer_id": 99744,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p>If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faster since IsAssignableFrom() does more internal checks than GetInterface(). It'll probably even faster to check the results of Type.GetInterfaces() which returns the same internal list that both of the other methods use anyway.</p>\n"
},
{
"answer_id": 45838091,
"author": "Holf",
"author_id": 169334,
"author_profile": "https://Stackoverflow.com/users/169334",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Edit: This answer is wrong! Please see comments.</strong></p>\n\n<p>There is a difference in how internal classes are handled. Take the following class:</p>\n\n<pre><code>public interface IFoo\n{\n} \n\ninternal class Foo: IFoo\n{\n}\n</code></pre>\n\n<p>This will give you a list of one item:</p>\n\n<pre><code>var types = typeof(IFoo).Assembly.GetTypes()\n .Where(x => x.GetInterface(typeof(IFoo).FullName) != null)\n .ToList();\n</code></pre>\n\n<p>Whereas this will give you an empty list:</p>\n\n<pre><code>var types = typeof(IFoo).Assembly.GetTypes()\n .Where(x => x.IsAssignableFrom(typeof(IFoo))\n .ToList();\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
]
| Using reflection in .Net, what is the differnce between:
```
if (foo.IsAssignableFrom(typeof(IBar)))
```
And
```
if (foo.GetInterface(typeof(IBar).FullName) != null)
```
Which is more appropriate, why?
When could one or the other fail? | If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faster since IsAssignableFrom() does more internal checks than GetInterface(). It'll probably even faster to check the results of Type.GetInterfaces() which returns the same internal list that both of the other methods use anyway. |
99,781 | <p>I have a client that is asking me to give them a listing of every file and folder in the source code (and then a brief explanation of the source tree). Is there an easy way to create some sort of decently formatted list like this from a subversion repository?</p>
| [
{
"answer_id": 99788,
"author": "Subimage",
"author_id": 10596,
"author_profile": "https://Stackoverflow.com/users/10596",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming it's available via HTTP - why not just give them a read-only login, and point them at the web address?</p>\n"
},
{
"answer_id": 99794,
"author": "RKitson",
"author_id": 16947,
"author_profile": "https://Stackoverflow.com/users/16947",
"pm_score": 1,
"selected": false,
"text": "<p>try: svn list -R</p>\n\n<p>with the root of the branch you're trying to list.</p>\n"
},
{
"answer_id": 99797,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "<p>Do a checkout, then drop into a command prompt, <code>cd</code> to the right directory, and type something like</p>\n\n<pre>dir /a:d /s /b > listing.txt</pre>\n\n<p>(Assuming that you're on Windows, of course.)</p>\n"
},
{
"answer_id": 99798,
"author": "PostMan",
"author_id": 18405,
"author_profile": "https://Stackoverflow.com/users/18405",
"pm_score": 1,
"selected": false,
"text": "<p>svn list -R svn://svnlocation</p>\n\n<p>This should list all the files and folders, could outout this to a text file</p>\n"
},
{
"answer_id": 99810,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 4,
"selected": true,
"text": "<p>You'll want the list command. Assuming you're using the command line client</p>\n\n<pre><code>svn list -R http://example.com/path/to/repos\n</code></pre>\n\n<p>This will give you a full recursive list of everything that's in the repository. Redirect it to a text file</p>\n\n<pre><code>svn list -R http://example.com/path/to/repos > file.txt\n</code></pre>\n\n<p>and then format to your heart's content.</p>\n"
},
{
"answer_id": 100013,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 2,
"selected": false,
"text": "<p>More generally, you can use the tree utility (in *Nix systems) to print out such a list for any directory structure. It is installed by default in many distros. If it isn't in yours, you might check the standard repositories for it. For example, in Ubuntu, with the default repositories, \"sudo apt-get install tree\" should do the trick. Alternatively, there's a shell script using sed that implements it <a href=\"http://www.centerkey.com/tree/\" rel=\"nofollow noreferrer\" title=\"Tree Shell Script\">here</a>. Once you have tree, just cd to the directory you'd like to print the listing for and type \"tree\" (redirect it to a file if you like).</p>\n\n<p>This does require that you have a checkout of the repository, but you'll probably already have one in most cases. Note that this will also include the .svn directories, which is kind of a pain, but you can always pipe the output through a \"grep -v .svn\" that will strip out these lines, possibly with some additional magic to take out anything \"underneath\" such a .svn-containing line in the hierarchy (using sed or a procedural shell-script loop or similar).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
]
| I have a client that is asking me to give them a listing of every file and folder in the source code (and then a brief explanation of the source tree). Is there an easy way to create some sort of decently formatted list like this from a subversion repository? | You'll want the list command. Assuming you're using the command line client
```
svn list -R http://example.com/path/to/repos
```
This will give you a full recursive list of everything that's in the repository. Redirect it to a text file
```
svn list -R http://example.com/path/to/repos > file.txt
```
and then format to your heart's content. |
99,796 | <p>I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this:</p>
<pre><code> | BSP | Quadtree | Octree
------------+----------------+-------
Situation A | X | |
Situation B | | X |
Situation C | | | X
</code></pre>
<p>What are A, B, and C?</p>
| [
{
"answer_id": 99817,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have much experience with BSPs, but I can say that you should go with octrees over quadtrees when you the scene you're rendering is tall. That is, the height is more than half the width and depth -- little rule of thumb. Generally, octrees won't bring a huge cost over quadtrees and they have the potential to speed things up a decent bit. YMMV.</p>\n"
},
{
"answer_id": 99879,
"author": "Jonathan Adelson",
"author_id": 8092,
"author_profile": "https://Stackoverflow.com/users/8092",
"pm_score": 0,
"selected": false,
"text": "<p>Usually these things don't have a clear-cut answer. I would suggest that A,B, and C are the result of a function of the size of your space and the amount of stuff you are differentiating.</p>\n"
},
{
"answer_id": 99926,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 0,
"selected": false,
"text": "<p>A BSP is better for a smaller, simpler space that you only want to do occlusion with. If you want all intersections for a given ray, you'll need to upgrade to a quad/octree.</p>\n\n<p>As for quadtree vs. octree - how many dimensions do you care a lot about? Two dimensions means a quadtree, four an octree. As stated, as quadtree can work in three-space, but if you want each dimension given a proper treatment, an octree is the way to go.</p>\n"
},
{
"answer_id": 100740,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 3,
"selected": false,
"text": "<p>A BSP is best for urban environments.</p>\n\n<p>A Quadtree is best for when you use a height map for terrain, etc.</p>\n\n<p>An Octree is best for when you have clumps of geometry in 3d space, such as a solar system.</p>\n"
},
{
"answer_id": 100814,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>BSPs are a good option for accelerating collision-detection, depending on which flavour you use. They're particularly fast at point and line or ray tests, somewhat less fast and a little more complicated for things with volume.</p>\n\n<p>As for their use in graphics, BSPs are pretty much obsolete. Octrees work well for things like gross visibility culling, as do AABB trees.</p>\n"
},
{
"answer_id": 100873,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 7,
"selected": true,
"text": "<p>There is no clear answer to your question. It depends entirely how your data is organized.</p>\n\n<p>Something to keep in mind:</p>\n\n<p>Quadtrees work best for data that is mostly two dimensional like map-rendering in navigation systems. In this case it's faster than octrees because it adapts better to the geometry and keeps the node-structures small.</p>\n\n<p>Octrees and BVHs (Bounding Volume Hierarchies) benefit if the data is three dimensional. It also works very well if your geometric entities are clustered in 3D space. (see <a href=\"https://web.archive.org/web/20180111010801/http://www.thomasdiewald.com/blog/?p=1488\" rel=\"noreferrer\">Octree vs BVH</a>) (archived from <del><a href=\"http://thomasdiewald.com/blog/?p=1488\" rel=\"noreferrer\">original</a></del>)</p>\n\n<p>The benefit of Oc- and Quadtrees is that you can stop generating trees anytime you wish. If you want to render graphics using a graphic accelerator it allows you to just generate trees on an object level and send each object in a single draw-call to the graphics API. This performs <strong>much</strong> better than sending individual triangles (something you have to do if you use BSP-Trees to the full extent).</p>\n\n<p>BSP-Trees are a special case really. They work very very well in 2D and 3D, but generating good BSP-Trees is an art form on its own. BSP-Trees have the drawback that you may have to split your geometry into smaller pieces. This can increase the overall polygon-count of your data-set. They are nice for rendering, but they are much better for collision detection and ray-tracing.</p>\n\n<p>A nice property of the BSP-trees is that they decompose a polygon-soup into a structure that can be perfectly rendered back to front (and vice versa) from any camera position without doing an actual sort. The order from each viewpoint is part of the data-structure and done during BSP-Tree compilation.</p>\n\n<p>That, by the way, is the reason why they were so popular 10 years ago. Quake used them because it allowed the graphic engine / software rasterizer to not use a costly z-buffer.</p>\n\n<p>All the trees mentioned are just families of trees. There are loose octrees, kd-trees hybrid-trees and lots of other related structures as well.</p>\n"
},
{
"answer_id": 26517609,
"author": "David Jeske",
"author_id": 519568,
"author_profile": "https://Stackoverflow.com/users/519568",
"pm_score": 4,
"selected": false,
"text": "<p>The biggest practical difference between BSP-Trees and other kinds of 3d-trees are that BSP-Trees can be more optimal but only work on <em>static</em> geometry. This is because BSP-Trees are generally very slow to build, often taking hours or days for a typical static urban game level. </p>\n\n<p>The two main reasons BSP-Trees take longer to build are (a) they use non-axis-aligned splitting planes, which take longer to optimally find, and (b) they subdivide geometry on axis boundaries, assuring no objects cross split planes.</p>\n\n<p>Other types of 3d-trees (Octrees, Quadtrees, kd-tree, Bounding-Volume-Hierarchy) use axis-aligned bounding volumes, and volumes are (optionally) allowed to overlap, so contained objects don't need to be cut on volume boundaries. These both make the trees less optimal than BSP-trees, but quicker to build, and easier to change for dynamic objects.</p>\n\n<p>Extrapolating these factors into situations...</p>\n\n<p>Outdoor areas typically use height-field based ground representations, either simple heightmaps or more complex geo-mip-mapping techniques like ROAM. The ground itself doesn't participate in the 3d space partitioning, only objects placed on the ground. </p>\n\n<p>Worlds with lots of instances of simpler and similar geometry (houses, trees, asteroids, etc) will often use a non-BSP-tree (such as a BVH), because putting the geometry into a BSP-tree would mean duplicating and splitting the detail geometry for every instance. </p>\n\n<p>Conversely, a large custom static mesh with no instancing, such as an urban scene, or a complex indoor environment, will typically use a BSP-Tree for improved runtime performance. The fact that the BSP-Tree splits geometry on node-boundaries is helpful for rendering performance, because the BSP nodes can be used as pre-organized triangle rendering batches. The BSP-Tree can also be optimized for occlusion, avoiding the need to draw portions of the BSP-Tree which are known to be behind other geometry.</p>\n\n<p>See also: <a href=\"https://web.archive.org/web/20180111010801/http://www.thomasdiewald.com/blog/?p=1488\" rel=\"nofollow noreferrer\">Octree vs BVH</a> (archived from <del><a href=\"http://thomasdiewald.com/blog/?p=1488\" rel=\"nofollow noreferrer\">original</a></del>), <a href=\"http://www.3dmuve.com/3dmuve.html?file=blog/blog_post_3.html\" rel=\"nofollow noreferrer\">Bounding Volume Hierarchy Tutorial</a>, <a href=\"http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm\" rel=\"nofollow noreferrer\">BSP Tutorial</a>.</p>\n"
},
{
"answer_id": 58417808,
"author": "CoffeDeveloper",
"author_id": 1829943,
"author_profile": "https://Stackoverflow.com/users/1829943",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you know what you are doing always go for the octrees so you can stop focusing on overoptimizing and start working on more serious features. Seriously the bottlenecks will always be somewhere else, or you are designing you code around a optimized system which in the end prevents certain types of changes later.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
]
| I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this:
```
| BSP | Quadtree | Octree
------------+----------------+-------
Situation A | X | |
Situation B | | X |
Situation C | | | X
```
What are A, B, and C? | There is no clear answer to your question. It depends entirely how your data is organized.
Something to keep in mind:
Quadtrees work best for data that is mostly two dimensional like map-rendering in navigation systems. In this case it's faster than octrees because it adapts better to the geometry and keeps the node-structures small.
Octrees and BVHs (Bounding Volume Hierarchies) benefit if the data is three dimensional. It also works very well if your geometric entities are clustered in 3D space. (see [Octree vs BVH](https://web.archive.org/web/20180111010801/http://www.thomasdiewald.com/blog/?p=1488)) (archived from ~~[original](http://thomasdiewald.com/blog/?p=1488)~~)
The benefit of Oc- and Quadtrees is that you can stop generating trees anytime you wish. If you want to render graphics using a graphic accelerator it allows you to just generate trees on an object level and send each object in a single draw-call to the graphics API. This performs **much** better than sending individual triangles (something you have to do if you use BSP-Trees to the full extent).
BSP-Trees are a special case really. They work very very well in 2D and 3D, but generating good BSP-Trees is an art form on its own. BSP-Trees have the drawback that you may have to split your geometry into smaller pieces. This can increase the overall polygon-count of your data-set. They are nice for rendering, but they are much better for collision detection and ray-tracing.
A nice property of the BSP-trees is that they decompose a polygon-soup into a structure that can be perfectly rendered back to front (and vice versa) from any camera position without doing an actual sort. The order from each viewpoint is part of the data-structure and done during BSP-Tree compilation.
That, by the way, is the reason why they were so popular 10 years ago. Quake used them because it allowed the graphic engine / software rasterizer to not use a costly z-buffer.
All the trees mentioned are just families of trees. There are loose octrees, kd-trees hybrid-trees and lots of other related structures as well. |
99,827 | <p>I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...</p>
<pre><code>exec sp_executesql N'SELECT [t0].[CustomerID]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[ContactName] LIKE @p0
ORDER BY [t0].[CompanyName]',
'N'@p0 nvarchar(2)',@p0=N'c%'
</code></pre>
<p>...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.</p>
<p>Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.</p>
<pre><code>var customers = from c in context.Customers
where c.CompanyName.StartsWith("c")
orderby c.CompanyName
select c.CustomerID;
foreach (var CustomerID in customers.TagWith("CustomerList4"))
{
Console.WriteLine(CustomerID);
}
</code></pre>
<p>If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.</p>
| [
{
"answer_id": 99839,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 1,
"selected": false,
"text": "<p>in the <a href=\"http://cftextmate.com/\" rel=\"nofollow noreferrer\">cftextmate</a> bundle you can type any cfml tag without the opening \"<\" or closing \">\" and press tab and it completes the entire tag and you can then tab to each of the tag attributes. i'm not sure if this type of shortcut works for other languages.</p>\n"
},
{
"answer_id": 99901,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 1,
"selected": false,
"text": "<p>I just found a list of shortcut key symbols w/ definitions under <strong>Bundles</strong> > <strong>HTML</strong> > <strong>Entities</strong> - helpful for me in figuring out the whole short-cut bonanza going on with TextMate.</p>\n"
},
{
"answer_id": 99967,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": 6,
"selected": true,
"text": "<p>These are my favorite shortcuts:</p>\n\n<ul>\n<li><kbd>cmd</kbd>+<kbd>t</kbd> Start typing name of a file to open it</li>\n<li><kbd>ctrl</kbd>+<kbd>w</kbd> Select word</li>\n<li><kbd>cmd</kbd>+<kbd>r</kbd> Run the ruby or php-script that is open</li>\n<li><kbd>cmd</kbd>+<kbd>opt</kbd>+<kbd>m</kbd> Define a new macro</li>\n<li><kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>m</kbd> Run the macro</li>\n<li><kbd>opt</kbd> Switch to vertical selection mode</li>\n<li><kbd>cmd</kbd>+<kbd>opt</kbd>+<kbd>a</kbd> Edit ends of selected lines</li>\n</ul>\n"
},
{
"answer_id": 100528,
"author": "Matt",
"author_id": 15368,
"author_profile": "https://Stackoverflow.com/users/15368",
"pm_score": 3,
"selected": false,
"text": "<p>Personally two of my favourite shortcuts are:</p>\n\n<ul>\n<li>⌃⇧L (that's <kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>L</kbd>): Which wraps the currently selected text with a link to whatever's in the clipboard, and works for every text language I've tried it in.</li>\n<li>⌃⇧⌘L (that's <kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>cmd</kbd>+<kbd>L</kbd>): Which googles for the selected text and links to the top result.</li>\n</ul>\n\n<p>The are both super useful for writing text and blogging, (and stackoverflow).</p>\n\n<p>Codewise, I think that I prefer snippets to key shortcuts. Being able to type <code>if⇥</code> etc., in almost any language is ridiculously useful, and the consistent interface is what keeps me using TextMate.</p>\n\n<p>I also found <a href=\"http://www.macility.com/images/products/kc/KCTextmate.jpg\" rel=\"nofollow noreferrer\">this</a> quite amusing. But I prefer to learn my shortcuts in small steps, and often find that just looking in the gear menu (⌃⎋) works.</p>\n"
},
{
"answer_id": 108216,
"author": "melfar",
"author_id": 9804,
"author_profile": "https://Stackoverflow.com/users/9804",
"pm_score": 4,
"selected": false,
"text": "<ul>\n<li><kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>K</kbd> deletes current line</li>\n<li><kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>J</kbd> merges current line with the next line</li>\n</ul>\n"
},
{
"answer_id": 262857,
"author": "Nate Smith",
"author_id": 1238,
"author_profile": "https://Stackoverflow.com/users/1238",
"pm_score": 1,
"selected": false,
"text": "<p>You can get a really great desktop background <a href=\"http://www.wishingline.com/notebook/2007/01/textmateshortcutsdesktop/\" rel=\"nofollow noreferrer\">here</a>. It has a ton of really useful keyboard shortcuts. I used it for a couple of days before memorizing the most useful ones.</p>\n"
},
{
"answer_id": 525480,
"author": "alamodey",
"author_id": 58521,
"author_profile": "https://Stackoverflow.com/users/58521",
"pm_score": 3,
"selected": false,
"text": "<p>My favourites are:</p>\n\n<ul>\n<li><kbd>option</kbd>+<kbd>command</kbd>+<kbd>[</kbd> to clean up your indentation</li>\n<li>\"lorem\", <kbd>TAB</kbd> to insert placeholder text</li>\n</ul>\n"
},
{
"answer_id": 1138037,
"author": "svnlto",
"author_id": 139450,
"author_profile": "https://Stackoverflow.com/users/139450",
"pm_score": 3,
"selected": false,
"text": "<p>shift+ctrl+alt+v sends selected text to pastie.org</p>\n\n<p>also, using the PHP Bundle, try to start writing a function name and do the following:</p>\n\n<p>str + alt + F3 = list of available functions</p>\n\n<p>str + alt + F1 = short description of the function you've just completed.</p>\n"
},
{
"answer_id": 2646864,
"author": "Agos",
"author_id": 107613,
"author_profile": "https://Stackoverflow.com/users/107613",
"pm_score": 0,
"selected": false,
"text": "<p>(these are mostly html-related) </p>\n\n<ul>\n<li><kbd>cmd</kbd> + <kbd>option</kbd> <kbd>+</kbd> closes current open html tag </li>\n<li><kbd>shift</kbd> + <kbd>cmd</kbd> + <kbd>w</kbd> wrap selection in tags</li>\n<li><kbd>ctrl</kbd> + <kbd>return</kbd> insert escaped line end, i.e. <code>\\n</code> or <code><br></code> depending on the occasion. </li>\n</ul>\n"
},
{
"answer_id": 4586495,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 1,
"selected": false,
"text": "<p>Wrap selected text in markup tags: <kbd>SHIFT</kbd> + <kbd>CONTROL</kbd> + <kbd>W</kbd></p>\n\n<p>For example, if you have:</p>\n\n<pre><code>Lorem ipsum dolor sit amet, consectetur\n</code></pre>\n\n<p>Highlight the text and press <kbd>SHIFT</kbd> + <kbd>CONTROL</kbd> + <kbd>W</kbd> to create:</p>\n\n<pre><code><p>Lorem ipsum dolor sit amet, consectetur</p>\n</code></pre>\n"
},
{
"answer_id": 4586528,
"author": "sethvargo",
"author_id": 365738,
"author_profile": "https://Stackoverflow.com/users/365738",
"pm_score": 2,
"selected": false,
"text": "<p>Selecting text using <kbd>alt</kbd> (via click and drag)</p>\n\n<p>then use <kbd>⌘</kbd> + <kbd>]</kbd> to indent (or <kbd>[</kbd> to dedent)</p>\n"
},
{
"answer_id": 4586541,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 3,
"selected": false,
"text": "<p>Look word up in dictionary, in any Cocoa app (not just Textmate): ctrl + cmd + D</p>\n\n<p><img src=\"https://i.stack.imgur.com/lEAjv.png\" alt=\"alt text\"></p>\n"
},
{
"answer_id": 4586587,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Close the nearest open html/xml tag: <kbd>OPTION</kbd> + <kbd>COMMAND</kbd> + <kbd>PERIOD</kbd></p>\n\n<p>For example, if you have: </p>\n\n<pre><code><div>Lorem ipsum dolor sit amet, consectetur\n</code></pre>\n\n<p><kbd>CONTROL</kbd> + <kbd>COMMAND</kbd> + <kbd>D</kbd> will automatically add the closing <code></div></code> tag to create:</p>\n\n<pre><code><div>Lorem ipsum dolor sit amet, consectetur</div>\n</code></pre>\n"
},
{
"answer_id": 4586597,
"author": "Kevin Sylvestre",
"author_id": 259900,
"author_profile": "https://Stackoverflow.com/users/259900",
"pm_score": 1,
"selected": false,
"text": "<p>Go to File: <kbd>⌘</kbd> + <kbd>T</kbd></p>\n\n<p>Find in Project: <kbd>⌘</kbd> + <kbd>SHIFT</kbd> + <kbd>F</kbd></p>\n"
},
{
"answer_id": 4586611,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Delete the current line: <kbd>CONTROL</kbd> + <kbd>SHIFT</kbd> + <kbd>K</kbd></p>\n"
},
{
"answer_id": 4586645,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Wrap each selected line in markup tags: <kbd>SHIFT</kbd> + <kbd>CONTROL</kbd> + <kbd>COMMAND</kbd> + <kbd>W</kbd></p>\n\n<p>For example, if you have: </p>\n\n<pre><code> This is a \n few sample\n list items \n</code></pre>\n\n<p>Highlight all three lines and presss <kbd>SHIFT</kbd> + <kbd>CONTROL</kbd> + <kbd>COMMAND</kbd> + <kbd>W</kbd> to create:</p>\n\n<pre><code> <li>This is a </li>\n <li>few sample</li>\n <li>list items</li>\n</code></pre>\n"
},
{
"answer_id": 4586682,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Switch between tabs: </p>\n\n<ul>\n<li>Left: <kbd>SHIFT</kbd> + <kbd>COMMAND</kbd> + <kbd>[</kbd></li>\n<li>Right: <kbd>SHIFT</kbd> + <kbd>COMMAND</kbd> + <kbd>]</kbd></li>\n</ul>\n"
},
{
"answer_id": 4586703,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 1,
"selected": false,
"text": "<p>Eliminate all whitespace / carriage returns between the location of your caret and the start of the next piece of content: <kbd>SHIFT</kbd> + <kbd>CONTROL</kbd> + <kbd>J</kbd></p>\n\n<p>For example, if you have:</p>\n\n<blockquote>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\n eiusmod tempor incididunt ut labore et\n dolore magna aliqua. </p>\n \n <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris\n nisi ut aliquip.</p>\n</blockquote>\n\n<p>Place your caret at the end of the first paragraph and press <kbd>SHIFT</kbd> + <kbd>CONTROL</kbd> + <kbd>J</kbd> to remove the space in between the paragraphs: </p>\n\n<blockquote>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.</p>\n</blockquote>\n"
},
{
"answer_id": 4586776,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Format CSS: <kbd>CONTROL</kbd> + <kbd>Q</kbd></p>\n\n<p>Select some CSS and press <kbd>CONTROL</kbd> + <kbd>Q</kbd> to turn this: </p>\n\n<pre><code>body { background: red; font-size: 10px; color: black; }\n</code></pre>\n\n<p>Into this:</p>\n\n<pre><code>body {\n background: red;\n font-size: 10px;\n color: black;\n}\n</code></pre>\n"
},
{
"answer_id": 4586904,
"author": "Eric Van Joshnon",
"author_id": 560190,
"author_profile": "https://Stackoverflow.com/users/560190",
"pm_score": 4,
"selected": false,
"text": "<p><kbd>Esc</kbd> auto completes common words in the document you are working in. </p>\n\n<p>For example if you are using a function alot called <code>LongFuntionNameThatChecksStuff</code>, you can type <code>Lon</code> and press<kbd>Esc</kbd> and it should auto complete.</p>\n"
},
{
"answer_id": 4586920,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Look up property specifications in W3C: <kbd>CONTROL</kbd> + <kbd>H</kbd></p>\n\n<p>This works for both HTML and CSS. Place your carrot over whatever property you'd like to look up and press <kbd>CONTROL</kbd> + <kbd>h</kbd>. This will open a new window listing the W3C info. </p>\n\n<p>For example, place your carrot over background:</p>\n\n<pre><code>body {\n background: red;\n}\n</code></pre>\n\n<p>Hit <kbd>command</kbd> + <kbd>h</kbd> and you'll see something like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/XzHTW.png\" alt=\"alt text\"></p>\n"
},
{
"answer_id": 4586939,
"author": "Eric Van Joshnon",
"author_id": 560190,
"author_profile": "https://Stackoverflow.com/users/560190",
"pm_score": 0,
"selected": false,
"text": "<p>Copy and Paste Clipboard: <kbd>⌘</kbd> + <kbd>SHIFT</kbd> + <kbd>V</kbd></p>\n"
},
{
"answer_id": 4589132,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Generate Lorem ipsum: <code>lorem</code> + <kbd>TAB</kbd></p>\n\n<p>Will generate: </p>\n\n<blockquote>\n <p>Lorem ipsum dolor sit amet,\n consectetur adipisicing elit, sed do\n eiusmod tempor incididunt ut labore et\n dolore magna aliqua. Ut enim ad minim\n veniam, quis nostrud exercitation\n ullamco laboris nisi ut aliquip ex ea\n commodo consequat. Duis aute irure\n dolor in reprehenderit in voluptate\n velit esse cillum dolore eu fugiat\n nulla pariatur. Excepteur sint\n occaecat cupidatat non proident, sunt\n in culpa qui officia deserunt mollit\n anim id est laborum.</p>\n</blockquote>\n"
},
{
"answer_id": 4589153,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 0,
"selected": false,
"text": "<p>Titleize selected text: <kbd>CONTROL</kbd> + <kbd>OPTION</kbd> + <kbd>U</kbd></p>\n\n<p>Will turn:</p>\n\n<blockquote>\n <p>Lorem ipsum dolor sit amet,\n consectetur adipisicing elit.</p>\n</blockquote>\n\n<p>Into:</p>\n\n<blockquote>\n <p>Lorem Ipsum Dolor Sit Amet,\n Consectetur Adipisicing Elit.</p>\n</blockquote>\n"
},
{
"answer_id": 4589166,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 0,
"selected": false,
"text": "<p>Downcase selected text: <kbd>CONTROL</kbd> + <kbd>SHIFT</kbd> + <kbd>U</kbd></p>\n\n<p>Will turn:</p>\n\n<blockquote>\n <p>Lorem ipsum dolor sit amet,\n consectetur adipisicing elit.</p>\n</blockquote>\n\n<p>Into:</p>\n\n<blockquote>\n <p>lorem ipsum dolor sit amet,\n consectetur adipisicing elit.</p>\n</blockquote>\n"
},
{
"answer_id": 4589175,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 0,
"selected": false,
"text": "<p>Upcase selected text: <kbd>CONTROL</kbd> + <kbd>SHIFT</kbd> + <kbd>U</kbd></p>\n\n<p>Will turn:</p>\n\n<blockquote>\n <p>Lorem ipsum dolor sit amet,\n consectetur adipisicing elit.</p>\n</blockquote>\n\n<p>Into:</p>\n\n<blockquote>\n <p>LOREM IPSUM DOLOR SIT AMET,\n CONSECTETUR ADIPISICING ELIT.</p>\n</blockquote>\n"
},
{
"answer_id": 4589192,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Edit the end of multiple selected lines simultaneously : <kbd>COMMAND</kbd> + <kbd>OPTION</kbd> + <kbd>A</kbd></p>\n"
},
{
"answer_id": 5123781,
"author": "Cory Schires",
"author_id": 388061,
"author_profile": "https://Stackoverflow.com/users/388061",
"pm_score": 2,
"selected": false,
"text": "<p>Toggle between <code>{}</code> and <code>do</code> <code>end</code> blocks. Place your cursor on the block arugument (i.e. the word after the keyword <code>do</code> between the two pipes) and press <kbd>Shift</kbd> + <kbd>Control</kbd> + <kbd>{</kbd></p>\n\n<p>For example, converts: </p>\n\n<pre><code>@post.each do |post|\n puts post.name\nend\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>@post.each { |post| puts post.name }\n</code></pre>\n"
},
{
"answer_id": 7314742,
"author": "Justin Thiele",
"author_id": 689168,
"author_profile": "https://Stackoverflow.com/users/689168",
"pm_score": 2,
"selected": false,
"text": "<p><kbd>CMD</kbd> + <kbd>/</kbd> comments out a line and it's smart enough to format based on language. I use it all the time.</p>\n"
},
{
"answer_id": 10964780,
"author": "drukepple",
"author_id": 391198,
"author_profile": "https://Stackoverflow.com/users/391198",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Control-T</strong>(<kbd>Control</kbd><kbd>T</kbd>): <em>Transpose</em> (works in most Cocoa-native text fields and areas, but TextMate enhances the behavior).</p>\n\n<ul>\n<li><p>Place your caret between two characters, hit <kbd>Control</kbd><kbd>T</kbd>, and the characters switch places (this is standard Mac behavior). Awesome for typos.</p></li>\n<li><p>Select a word or series of characters on a single line, hit <kbd>Control</kbd><kbd>T</kbd>, and the characters in the selection will now be reversed (not too useful, but this is a TextMate enhancement)</p></li>\n<li><p>Select a series of characters that spans more than one line, hit <kbd>Control</kbd><kbd>T</kbd>, and the lines will reverse. Characters within the line will still be in order. Most useful when selecting whole lines, but still works with partial lines selected, just so long as there is at least one newline character selected (TextMate enhancement).</p></li>\n</ul>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360388/"
]
| I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...
```
exec sp_executesql N'SELECT [t0].[CustomerID]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[ContactName] LIKE @p0
ORDER BY [t0].[CompanyName]',
'N'@p0 nvarchar(2)',@p0=N'c%'
```
...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.
Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.
```
var customers = from c in context.Customers
where c.CompanyName.StartsWith("c")
orderby c.CompanyName
select c.CustomerID;
foreach (var CustomerID in customers.TagWith("CustomerList4"))
{
Console.WriteLine(CustomerID);
}
```
If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks. | These are my favorite shortcuts:
* `cmd`+`t` Start typing name of a file to open it
* `ctrl`+`w` Select word
* `cmd`+`r` Run the ruby or php-script that is open
* `cmd`+`opt`+`m` Define a new macro
* `cmd`+`shift`+`m` Run the macro
* `opt` Switch to vertical selection mode
* `cmd`+`opt`+`a` Edit ends of selected lines |
99,866 | <p>I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?</p>
<p>A couple things that we've seen/heard already include:</p>
<ul>
<li>Google not being able to index content</li>
<li>CSS and styling in general seems to be a bit flaky</li>
</ul>
<p>Looking for any additional feedback on these items as well. Thanks!</p>
| [
{
"answer_id": 99920,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 3,
"selected": false,
"text": "<p>No major pitfalls that I haven't been able to overcome easily. Use hosted mode heavily. \nAs you are using GWT-ext you will almost never need to touch CSS yourself unless you want to tweak the out of the box look. </p>\n\n<p>My recommendation is to use a GWT \"native\" widget over a library one where they are close in features. </p>\n\n<p>Re search engine indexing: yes the site will not have navigable URLs normally (unless you are only adding widgets to elements of a regular web site). You can do history back/forward functionality though. </p>\n"
},
{
"answer_id": 99977,
"author": "rustyshelf",
"author_id": 6044,
"author_profile": "https://Stackoverflow.com/users/6044",
"pm_score": 9,
"selected": true,
"text": "<p>I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome:</p>\n\n<p><strong>Problem:</strong> Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute.</p>\n\n<p><strong>Solution:</strong> Split your code into separate modules, and tell ant to only build it when it's changed. Also while developing, you can massively speed up compile times by only building for one browser. You can do this by putting this into your .gwt.xml file:</p>\n\n<pre><code><set-property name=\"user.agent\" value=\"gecko1_8\" />\n</code></pre>\n\n<p>Where gecko1_8 is Firefox 2+, ie6 is IE, etc.</p>\n\n<hr>\n\n<p><strong>Problem:</strong> Hosted mode is very slow (on OS X at least) and does not come close to matching the 'live' changes you get when you edit things like JSPs or Rails pages and hit refresh in your browser.</p>\n\n<p><strong>Solution:</strong> You can give the hosted mode more memory (I generally got for 512M) but it's still slow, I've found once you get good enough with GWT you stop using this. You make a large chunk of changes, then compile for just one browser (generally 20s worth of compile) and then just hit refresh in your browser.</p>\n\n<p>Update: With GWT 2.0+ this is no longer an issue, because you use the new 'Development Mode'. It basically means you can run code directly in your browser of choice, so no loss of speed, plus you can firebug/inspect it, etc.</p>\n\n<p><a href=\"http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM\" rel=\"nofollow noreferrer\">http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM</a></p>\n\n<hr>\n\n<p><strong>Problem:</strong> GWT code is java, and has a different mentality to laying out a HTML page, which makes taking a HTML design and turning it into GWT harder</p>\n\n<p><strong>Solution:</strong> Again you get used to this, but unfortunately converting a HTML design to a GWT design is always going to be slower than doing something like converting a HTML design to a JSP page.</p>\n\n<hr>\n\n<p><strong>Problem:</strong> GWT takes a bit of getting your head around, and is not yet mainstream. Meaning that most developers that join your team or maintain your code will have to learn it from scratch</p>\n\n<p><strong>Solution:</strong> It remains to be seen if GWT will take off, but if you're a company in control of who you hire, then you can always choose people that either know GWT or want to learn it.</p>\n\n<hr>\n\n<p><strong>Problem:</strong> GWT is a sledgehammer compared to something like jquery or just plain javascript. It takes a lot more setup to get it happening than just including a JS file.</p>\n\n<p><strong>Solution:</strong> Use libraries like jquery for smaller, simple tasks that are suited to those. Use GWT when you want to build something truly complex in AJAX, or where you need to pass your data back and forth via the RPC mechanism.</p>\n\n<hr>\n\n<p><strong>Problem:</strong> Sometimes in order to populate your GWT page, you need to make a server call when the page first loads. It can be annoying for the user to sit there and watch a loading symbol while you fetch the data you need.</p>\n\n<p><strong>Solution:</strong> In the case of a JSP page, your page was already rendered by the server before becoming HTML, so you can actually make all your GWT calls then, and pre-load them onto the page, for an instant load. See here for details:</p>\n\n<p><a href=\"http://wiki.shiftyjelly.com/index.php/GWT#Speed_up_Page_Loading.2C_by_pre-serializing_your_GWT_calls\" rel=\"nofollow noreferrer\">Speed up Page Loading by pre-serializing your GWT calls</a></p>\n\n<hr>\n\n<p>I've never had any problems CSS styling my widgets, out of the box, custom or otherwise, so I don't know what you mean by that being a pitfall?</p>\n\n<p>As for performance, I've always found that once compiled GWT code is fast, and AJAX calls are nearly always smaller than doing a whole page refresh, but that's not really unique to GWT, though the native RPC packets that you get if you use a JAVA back end are pretty compact.</p>\n"
},
{
"answer_id": 101060,
"author": "Confusion",
"author_id": 16784,
"author_profile": "https://Stackoverflow.com/users/16784",
"pm_score": 1,
"selected": false,
"text": "<p>One major pitfall is that sometimes you need to explicitly assign an id to what ultimately becomes an HTML element to be able to use certain CSS styles. For instance: a GWT TabPanel will only do :hover over tabBarItems when the tabBar of the tabPanel has been assigned an id and you specify a :hover on that elementId.</p>\n\n<p>I wrote about some other <a href=\"http://confusion.tweakblogs.net/blog/1052/the-disadvantages-of-the-google-web-toolkit.html\" rel=\"nofollow noreferrer\">disadvantages of GWT</a> elsewhere, but they are already covered by rustyshelfs answer :).</p>\n"
},
{
"answer_id": 102608,
"author": "Ace",
"author_id": 18673,
"author_profile": "https://Stackoverflow.com/users/18673",
"pm_score": 2,
"selected": false,
"text": "<p>I used GWT and GWT-ext together on a project a while ago. I found the experience quite smooth as web development goes, but my advice would be this:</p>\n\n<p>Don't mix GWT native widgets with EXT widgets. It's confusing as hell, since usually the names are the same (GWT.Button or GWText.Button?) </p>\n\n<p>One thing that happened to me that really made the code more complex than I'd like, was that I wanted a Panel that was\na) dynamically updatable\nb) cascadable</p>\n\n<p>GWT native panels are dynamic, Ext panels are cascadable. Solution? A GWT.VerticalPanel wrapping a GWTExt Panel... Chaos. :) </p>\n\n<p>But hey, it works. ;)</p>\n"
},
{
"answer_id": 102717,
"author": "JP Richardson",
"author_id": 10333,
"author_profile": "https://Stackoverflow.com/users/10333",
"pm_score": 3,
"selected": false,
"text": "<p>I'm working on a project right now that uses EXT GWT (GXT) not to be confused with GWT EXT. There is a difference, EXT GWT is the one that is actually produced by the company that wrote ExtJS the javascript library. GWT EXT is a GWT wrapper around the ExtJS library. GXT is native GWT.</p>\n\n<p>Anyways, GXT is still somewhat immature and lacks a solid community that I feel GWT EXT has. However, the future is with GXT, as it's native GWT and actually developed by the company that made ExtJS. GWT EXT is somewhat crippled as the license changed on the ExtJS library, thus slowing the development of GWT EXT.</p>\n\n<p>Overall, I think GWT/GXT is a good solution for developing a web application. I actually quite like hosted mode for development, it makes things quick and easy. You also get the benefit of being able to debug your code as well. Unit testings with JUnit is pretty solid as well. I haven't yet seen a great JavaScript unit testing framework that I felt was mature enough for testing an enterprise application. </p>\n\n<p>For more information on GWT EXT:\n<a href=\"http://gwt-ext.com/\" rel=\"noreferrer\">http://gwt-ext.com/</a></p>\n\n<p>For more information on EXT GWT (GXT):\n<a href=\"http://extjs.com/products/gxt/\" rel=\"noreferrer\">http://extjs.com/products/gxt/</a></p>\n"
},
{
"answer_id": 104641,
"author": "jgindin",
"author_id": 17941,
"author_profile": "https://Stackoverflow.com/users/17941",
"pm_score": 4,
"selected": false,
"text": "<p>Pitfalls that we've run into:</p>\n\n<ul>\n<li><p>While you can get a lot of mileage from using something like GWT EXT, any time you use this sort of thin veneer on top of a JavaScript library, you lose the ability to debug. More than once I've bashed my head on the desk because I cannot inspect (inside my IntelliJ debugger) what's happening in the GWT EXT table class... All you can see is that it's a JavaScriptObject. This makes it quite difficult to figure out what's gone wrong...</p></li>\n<li><p>Not having someone on your team who knows CSS. From my experience, it didn't matter that the person wasn't expert...it's enough that he has some good working knowledge, and knows the right terms to google when necessary.</p></li>\n<li><p>Debugging across browsers. Keep an eye on Out of Process Hosted Mode[<a href=\"http://code.google.com/p/google-web-toolkit/wiki/DesignOOPHM\" rel=\"nofollow noreferrer\">1</a>][<a href=\"http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/4a62dd27602d822d/c37fece9c24f3715?lnk=gst&q=noserver\" rel=\"nofollow noreferrer\">2</a>][<a href=\"http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/1203bb0f1eb36ad5\" rel=\"nofollow noreferrer\">3</a>], hopefully coming in GWT 1.6... For now, you just have to get things good with hosted mode, then use the \"Compile/Browse\" button, where you can play with other browsers. For me, working on Windows, this means I can view my work in FireFox, and use FireBug to help tweak and make things better.</p></li>\n<li><p>IE6. It's amazing how different IE 6 will render things. I've taken the approach of applying a style to the outermost \"viewport\" according to the browser so that I can have CSS rules like:</p>\n\n<pre><code>.my-style { /* stuff that works most everywhere */ }\n\n.msie6 .my-style { /* \"override\" so that styles work on IE 6 */ }\n</code></pre></li>\n</ul>\n\n<p>Finally, make sure you use an editor that helps you. I use IntelliJ -- it's got lots of GWT smarts. E.g., If I try to use a class that isn't handled by the JRE emulation, it lets me know; if I specify a style for a widget, and I haven't defined that style yet, the code gets the little red squiggly... Or, when looking at the CSS, it will tell me when I've specified conflicting attributes in a single rule. (I haven't tried it yet, but I understand that version 8 has even better GWT support, like keeping the \"local\" and \"async\" RPC interfaces and implementations in sync.)</p>\n"
},
{
"answer_id": 105153,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 2,
"selected": false,
"text": "<p>We've had a very hard time marrying our GWT codebase with HTML web templates that we got from a web designer (static HTML pages with specific div ids that we wanted GWT to manage). At least back when we used it, we couldn't get GWT to integrate with parts of our website that were not coded in GWT. We had it working eventually, but it was a big hack.</p>\n"
},
{
"answer_id": 106656,
"author": "Steve Buikhuizen",
"author_id": 4974,
"author_profile": "https://Stackoverflow.com/users/4974",
"pm_score": 2,
"selected": false,
"text": "<p>I second the comment from ykagano, the biggest disadvantage is losing the V in MVC. Although you can separate the true ui class from the rest of your client side code, you cannot easily use an HTML page generated by a graphic/web designer. This means you need a developer to translate HTML into java.</p>\n\n<p>Get a wysiwyg ui editor, it will save you lots of time. I use GWTDesigner.</p>\n\n<p>The biggest upside of GWT is being able to forget about cross browser issues. Its not 100% but takes almost all that pain away. Combined with the benefit of hosted mode debugging (as opposed to Firebug which is excellent but not the same as a java debugger) it gives the developer a huge advantage in generating complex ajax apps.</p>\n\n<p>Oh and its fast at runtime, especially if you use a gzip filter.</p>\n"
},
{
"answer_id": 108434,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Slightly off-topic, but the #gwt channel on irc is very helpful, in-case you have a persistent problem.</p>\n"
},
{
"answer_id": 216297,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 3,
"selected": false,
"text": "<p>I'll add some points to the ones already mentioned:</p>\n\n<ul>\n<li>Databinding/validation. GWT doesn't have a databinding/validation support out of the box, although there are some projects on this area starting to emerge. You'll find yourself writing alot of this:</li>\n</ul>\n\n<pre>\nTextField fname, faddress;\n...\nfname.setText(person.getName());\nfaddress.setText(person.getAddress());\n...\n</pre>\n\n<ul>\n<li>Lazy loading. Since gwt is on the client side, lazy loading is really not an option. You'll have to design your RPCs and Domain Objects carefully in order to \n\n<ul>\n<li>send all your object data that is needed</li>\n<li>avoid eager fetching all of your data</li>\n<li>You'll have also to make sure that you will not send proxies/non serializable objects. <a href=\"http://hibernate4gwt.sf.net\" rel=\"noreferrer\">hibernate4gwt</a> can help you with these points.</li>\n</ul></li>\n<li>UI design. It is harder to visualize an UI in java (Panels, Buttons, etc) than in html. </li>\n<li>History support. GWT does not ship with a History subsystem, nor does it ship with any subsystem for nice urls or statefull bookmarking. You'll have to roll your own (although it has support for History tokens, which is a start). This happens with all AJAX toolkits AFAIK.</li>\n</ul>\n\n<p>IMHO, GWT is missing a framework that has out of the box support for all of the issues mentioned on this 'thread'.</p>\n"
},
{
"answer_id": 272255,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>The Async interface you have to write for each service interface looks like something that could have been automatically generated by the GWT compiler.</li>\n<li>Compile times become long for large projects</li>\n</ul>\n\n<p>But for a large Javascript project it's the best choice </p>\n"
},
{
"answer_id": 431537,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>We have been working with gwt for almost 2 years. We have learned a lot of lessons. Here is what we think:</p>\n\n<ol>\n<li><p>Dont use third party widget libraries especially gwt-ext. It will kill your debugging, development and runtime performance. If you have questions about how this happens, contact me directly.</p></li>\n<li><p>Use gwt to only fill in the dynamic parts of your apps. So if you have some complex user interactions with lots of fields. However, don't use the panels that come with it. Take your existing stock designer supplied pages. Carve out the areas that will contain the controls for your app. Attach these controls to the page within onModuleLoad(). This way you can use the standard pages from your designer and also do all the styling outside the gwt.</p></li>\n<li><p>Don't build the entire app as one standard page that then dynamically builds all the pieces. If you do what I suggest in item 2, this won't happen anyway. If you build everything dynamically you will kill performance and consume huge amounts of memory for medium to large apps. Also, if you do what I am suggesting, the back button will work great, so will search engine indexing etc.</p></li>\n</ol>\n\n<p>The other commenters also had some good suggestions. The rule of thumb i use is to create pages like you were doing a standard web page. Then carve out the pieces that need to be dynamic. Replace them with elements that have id's and then use <code>RootPanel.get( id ).add( widget )</code> to fill those areas in. </p>\n"
},
{
"answer_id": 1403439,
"author": "Salvin Francis",
"author_id": 146182,
"author_profile": "https://Stackoverflow.com/users/146182",
"pm_score": 1,
"selected": false,
"text": "<p>I have done a lot of work on GWT recently, and this is wht i have to say:</p>\n\n<ol>\n<li>CSS styling is tricky only sometimes, use IE developer tool in IE and firebug in Firefox to figure out what exactly is happening and you will get a clear idea of what css needs to be changed</li>\n<li>You can use tricks to get google to index it. A very famous site is <a href=\"http://examples.roughian.com/\" rel=\"nofollow noreferrer\">http://examples.roughian.com/</a> check its ratings at google. A far less famous site is <a href=\"http://www.salvin.in\" rel=\"nofollow noreferrer\">www.salvin.in</a> (couldnt resist to mention that), i optimised it to words: salvin home page (search google for these three words)</li>\n</ol>\n\n<p>I do not know much about GWT-EXT, But i too am of the belief that there is no need to include Third party libraries.</p>\n\n<p>Best of luck on your decision :)</p>\n"
},
{
"answer_id": 1407135,
"author": "Adam Albrecht",
"author_id": 138265,
"author_profile": "https://Stackoverflow.com/users/138265",
"pm_score": 4,
"selected": false,
"text": "<p>GWT 2.0, which is supposed to come out sometime in the next few months, solves a lot of the issues discussed.</p>\n\n<ul>\n<li>Create layouts using an html/xml like syntax</li>\n<li>Dynamic Script Loading - only the essential JS will be downloaded initially. The rest will be downloaded as needed</li>\n<li>In-Browser Hosted Mode - This might take care of the hosted mode speed issues discussed, among other benefits</li>\n<li>\"Compiler Optimizations\" - Faster compilation, hopefully</li>\n</ul>\n\n<p><a href=\"http://code.google.com/events/io/sessions/GwtPreviewGoogleWebToolkit2.html\" rel=\"noreferrer\">GWT 2.0 Preview Video at Google I/O</a></p>\n"
},
{
"answer_id": 1628454,
"author": "antony.trupe",
"author_id": 5849,
"author_profile": "https://Stackoverflow.com/users/5849",
"pm_score": 0,
"selected": false,
"text": "<p>Re-using RPC service objects.<br>\nIt causes race conditions with symptoms that look like the app hanging.</p>\n"
},
{
"answer_id": 2182527,
"author": "Blessed Geek",
"author_id": 140803,
"author_profile": "https://Stackoverflow.com/users/140803",
"pm_score": 2,
"selected": false,
"text": "<p>GWT is pretty straight-forward and intuitive.</p>\n\n<p>Especially with the release of UIBinder to allow GWT widgets to be laid out in XML and then coded-behind in Java.</p>\n\n<p>So if you have used other Ajax or Flash design tools, or Silverlight, etc, GWT is very easy to learn.</p>\n\n<p>The major hurdle, if not pitfall, is GWT RPC. The very reason you wish to use GWT is because of GWT async RPC. Otherwise, why not just rely on css to format your page?</p>\n\n<p>GWT RPC is that element that allows your server to refresh data on your server without having to refresh the page. This is an absolute requirement for pages such as stock performance monitoring (or the current national and public debt of the US or the number of unborn babies aborted worldwide by the second).</p>\n\n<p>GWT RPC takes some effort to understand but given a few hours, it should come all clear.</p>\n\n<p>Above that, after putting in some effort to learn GWT RPC, you finally discover that you cannot use JSPs as the service component for RPC, unless ... I have an 8 part (I think) series on my blog on how to use JSP as the GWT RPC servicer. However, since you had not asked for answers but just issues, I shall desist from advertising my blog.</p>\n\n<p>So. I very much believe that the worst roadblocks/pitfalls to using GWT is finding out how to properly deploy GWT async RPC and how to enable it to use JSP servicers.</p>\n"
},
{
"answer_id": 3280983,
"author": "Jla",
"author_id": 255844,
"author_profile": "https://Stackoverflow.com/users/255844",
"pm_score": 4,
"selected": false,
"text": "<p>Not \"unable to be overcome\" but a bit of a pain for something basic.</p>\n\n<p><strong>Date handling:</strong></p>\n\n<p>GWT uses the deprecated <code>java.util.Date</code> which can lead to unexpected behaviour when dealing with dates on the client side. <code>java.util.Calendar</code> is not supported by GWT. <a href=\"http://code.google.com/p/google-web-toolkit/issues/detail?id=603\" rel=\"nofollow noreferrer\">More info here</a>.</p>\n\n<p>Related problem examples:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2102085/gwt-java-util-date-serialization-bug\">GWT java.util.Date serialization bug</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3201762/get-date-details-day-month-year-in-gwt\">Get Date details (day, month, year) in GWT</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1686448/client-side-time-zone-support-in-gwt\">Client side time zone support in GWT</a></li>\n</ul>\n"
},
{
"answer_id": 6004520,
"author": "Eduardo",
"author_id": 229414,
"author_profile": "https://Stackoverflow.com/users/229414",
"pm_score": 1,
"selected": false,
"text": "<p>GWT does Browser Sniffing instead of Feature Detection and your application will not work on some browsers (specially new ones)</p>\n\n<p>Here are some references of the problem:</p>\n\n<ul>\n<li><a href=\"http://code.google.com/p/google-web-toolkit/issues/detail?id=2938\" rel=\"nofollow\">google-web-toolkit Issue 2938: RFE: improve the user.agent property-provider to cope for userAgent string \"masking\"</a></li>\n<li><a href=\"http://www.google.com/support/forum/p/Google+Docs/thread?tid=72fe7b0e15737560&hl=en\" rel=\"nofollow\">Iceweasel no longer supported? - Google Docs Help</a></li>\n<li><a href=\"http://code.google.com/p/google-web-toolkit/source/browse/#svn/trunk/user/src/com/google/gwt/user/client/impl\" rel=\"nofollow\">GWT implementations for every browser</a></li>\n</ul>\n\n<p>Here are some references to Feature Detection:</p>\n\n<ul>\n<li><a href=\"http://www.jibbering.com/faq/faq_notes/not_browser_detect.html\" rel=\"nofollow\">Browser Detecting (and what to do Instead)</a></li>\n<li><a href=\"http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting\" rel=\"nofollow\">Feature Detection: State of the Art Browser Scripting</a></li>\n<li><a href=\"https://developer.mozilla.org/En/Browser_Feature_Detection\" rel=\"nofollow\">Browser Feature Detection</a></li>\n</ul>\n\n<p>Extracted from <a href=\"http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks\" rel=\"nofollow\">Comparison of JavaScript frameworks - Wikipedia</a></p>\n"
},
{
"answer_id": 9773927,
"author": "Joseph Lust",
"author_id": 564157,
"author_profile": "https://Stackoverflow.com/users/564157",
"pm_score": 2,
"selected": false,
"text": "<p>GWT 2.4 has fixed many of the aforementioned issues and a great widget library is just coming out of Beta (Ext GWT 3.0.4 a.k.a. GXT), which is written completely in GWT, not a wrapper of a JS lib.</p>\n\n<p>Remaining pain:</p>\n\n<ul>\n<li>Lack of CSS3 selector support, you can use \"literal()\" in some cases to get around it.</li>\n<li>Lack of support for CSS3 and modern browser events like <em>transitionEnd</em>.</li>\n<li>Lack of Java Calendar class support (many years later).</li>\n<li>Lack of JUnit4 support (5 years and counting).</li>\n<li><strong>Lack of clear road map and release schedule from Google GWT team.</strong></li>\n</ul>\n"
},
{
"answer_id": 9905934,
"author": "Gal Bracha",
"author_id": 395804,
"author_profile": "https://Stackoverflow.com/users/395804",
"pm_score": 2,
"selected": false,
"text": "<p>Regarding GWT 2.4, <strong>Use Firefox</strong> when debugging GWT, it alot more faster then using chrome.\nAnd if you'll using only firefox, consider putting this line in your <strong>project.gwt.xml</strong> file</p>\n\n<pre><code><set-property name=\"user.agent\" value=\"gecko1_8\" />\n</code></pre>\n\n<p>Also, If you're using eclipse, then add the following under arguments -> VM arguments: </p>\n\n<p><strong>-Xmx512m -XX:MaxPermSize=1024m -XX:PermSize=1024m</strong></p>\n\n<p>You can divide your server and client, and use the following under arguments -> Program arguments:\n<strong>-codeServerPort 9997 -startupUrl <a href=\"http://yourserver/project\" rel=\"nofollow\">http://yourserver/project</a> -noserver</strong></p>\n\n<p>Also, to prevent refreshing your server on each change, use JRebel\n<a href=\"http://zeroturnaround.com/blog/how-to-rock-out-with-jrebel-and-google-web-toolkit-gwt/\" rel=\"nofollow\">http://zeroturnaround.com/blog/how-to-rock-out-with-jrebel-and-google-web-toolkit-gwt/</a>\nAnd here's a live demo\n<a href=\"http://www.youtube.com/watch?feature=player_embedded&v=4JGGFCzspaY\" rel=\"nofollow\">http://www.youtube.com/watch?feature=player_embedded&v=4JGGFCzspaY</a></p>\n"
},
{
"answer_id": 27434070,
"author": "Marcel Pater",
"author_id": 1098577,
"author_profile": "https://Stackoverflow.com/users/1098577",
"pm_score": 0,
"selected": false,
"text": "<p>Pitfalls I ran into\n1. Different behaviour in superdev mode. E.g. Someclass.class.getName() works absolutely fine in Superdev mode and returns the fully qualified name of the class. In productive mode this does not work.</p>\n\n<ol start=\"2\">\n<li>addWidget(widget) will call widget's removefromparent()</li>\n</ol>\n"
},
{
"answer_id": 28227774,
"author": "confile",
"author_id": 1055664,
"author_profile": "https://Stackoverflow.com/users/1055664",
"pm_score": 1,
"selected": false,
"text": "<p>The GWT team make a lot of great improvements in to last year releasing GWT 2.7. One major weakness of GWT was that compilation takes to much time in GWT 2.6 and below. This is now gone GWT has not incremental compile which is super fast and compiles only the changes. </p>\n\n<p>GWT 2.7 now has (<a href=\"https://drive.google.com/file/d/0B3ktS-w9vr8IbERCZ2VXbjZYeVE/view\" rel=\"nofollow\">Source</a>): </p>\n\n<ul>\n<li>Incremental builds now just seconds</li>\n<li>More compact, more accurate SourceMaps</li>\n<li>GSS support</li>\n<li>JSInterop </li>\n<li>Great JavaScript Performance</li>\n<li>Smaller Code Size</li>\n</ul>\n"
},
{
"answer_id": 29044371,
"author": "jgleoj23",
"author_id": 3781537,
"author_profile": "https://Stackoverflow.com/users/3781537",
"pm_score": 1,
"selected": false,
"text": "<p>The best way to get reliable facts are from the <a href=\"https://vaadin.com/documents/10187/4238532/GWT_report_2015.pdf/066936d9-8fcf-40bb-a58f-616a3d3f8203\" rel=\"nofollow\">gwt survey</a>. One of the biggest issues with GWT has always been a long compile time. Fortunately, it's improving very quickly so it won't be a significant issue in the near future. Another pitfall is that GWT is dramatically more complicated because Java is a more complicated language that resists bad coders every step of the way. In addition, compiling adds a layer. For example, js interop requires a little boilerplate. The fundamental issue is that GWT wasn't designed to be simple. It was designed from the ground up for extremely complicated web apps and the entire community consistently prioritizes, performance, code quality, architecture etcetera over easy coding.<br>\n Remember that you can use js in GWT at any point so if you are struggling with GWT consider using js. At the end of the day GWT is js so you can do anything in GWT that you can in js. In fact, most GWT projects use js. The problem is that GWT is drastically more complicated. Nevertheless, it's sometimes worth the extra complexity. </p>\n\n<p>It's worth noting that GWT 3.0 will bring massive improvements.</p>\n"
},
{
"answer_id": 30689134,
"author": "Alex Rogachevsky",
"author_id": 4982193,
"author_profile": "https://Stackoverflow.com/users/4982193",
"pm_score": 0,
"selected": false,
"text": "<p>GWT is a technology masterpiece. It unites client and server programming making it one coherent application - the way software was written before \"layering\", and the way it should be written. It eliminates different skills sets, miscommunication between team members, and generally the whole Web Design phase: both the artistic and programming. And it is the closest you'd get to mobile e.g. Android development. In fact GWT was designed to generate different native UIs, not just HTML. Though it requires enormous discipline to ensure such decoupling - to keep your inner layers presentation-agnostic.</p>\n\n<p>The first mistake you should avoid, which took me four years to realize, is using third-party extensions like EXT-GWT aka GXT and SmartGWT. It is very tempting to start using their pretty desktopish widgets instead of investing in your own styling, but I cannot tell how many problems I had with SmartGWT until I finally got fed up. In short it freezes the core GWT feature set at the certain (pretty outdated) level and then builds on top of it. Also keep in mind, that chiseled desktop look and feel looks silly nowadays, not to mention the sluggish performance, tons of bugs, and compatibility features - especially on mobile devices. You want to stay as close to the native browser controls, as possible i.e. dropdowns rendered as native <select> elements, not some custom-painted controls.</p>\n\n<p>Thanks to mobile trends the whole UX is becoming simpler and flatter, so you don't need to do much to style a sharp-looking application. Though if you want \"3D\" look, there are also gradients. CSS3 made everything easy, and GWT wraps it an elegant object-oriented manner unlike the raw CSS. So don't be discouraged by looking at rather ugly barebones controls in the GWT Showcase. The GWT team intentionally didn't offer any styling, because it it the developer's job.</p>\n\n<p>The rest is pretty much conventional browser programming in strongly typed Java with beautiful concise APIs. But of course never forgetting your code runs inside the browser, so all of the calls are asynchronous e.g. you cannot call GWT-RPC methods in a loop (to populate some list), but need to recursively chain them if you ever come to to this situation.</p>\n\n<p>There are some self-proclaimed \"anti-patterns\" like don't use GWT-RPC. It's been good to me so far: for 10 years. Simplicity is key. I wouldn't think even a second to sacrifice some marginal performance for code elegance and maintainability. besides this is not where your bottlenecks would be - in the database. Of course mind how much data you are sending to the client. </p>\n\n<p>And if you cannot find or style the existing gadget - read rich HTML5 element set, you can always wrap a third-party one. I did it with a popular jQuery FullCalendar. Not rocket science at all. Everything else like Google Maps and Google Charts has semi-official GWT wrappers. </p>\n\n<p>GWT is perfect. The only reason it doesn't get enough love is because early Internet adopters who still influence the industry didn't come from Computer Science and object-oriented languages to appreciate them. They have either artistic (Photoshop/WordPress) or network (Perl/Python) background. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18402/"
]
| I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?
A couple things that we've seen/heard already include:
* Google not being able to index content
* CSS and styling in general seems to be a bit flaky
Looking for any additional feedback on these items as well. Thanks! | I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome:
**Problem:** Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute.
**Solution:** Split your code into separate modules, and tell ant to only build it when it's changed. Also while developing, you can massively speed up compile times by only building for one browser. You can do this by putting this into your .gwt.xml file:
```
<set-property name="user.agent" value="gecko1_8" />
```
Where gecko1\_8 is Firefox 2+, ie6 is IE, etc.
---
**Problem:** Hosted mode is very slow (on OS X at least) and does not come close to matching the 'live' changes you get when you edit things like JSPs or Rails pages and hit refresh in your browser.
**Solution:** You can give the hosted mode more memory (I generally got for 512M) but it's still slow, I've found once you get good enough with GWT you stop using this. You make a large chunk of changes, then compile for just one browser (generally 20s worth of compile) and then just hit refresh in your browser.
Update: With GWT 2.0+ this is no longer an issue, because you use the new 'Development Mode'. It basically means you can run code directly in your browser of choice, so no loss of speed, plus you can firebug/inspect it, etc.
<http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM>
---
**Problem:** GWT code is java, and has a different mentality to laying out a HTML page, which makes taking a HTML design and turning it into GWT harder
**Solution:** Again you get used to this, but unfortunately converting a HTML design to a GWT design is always going to be slower than doing something like converting a HTML design to a JSP page.
---
**Problem:** GWT takes a bit of getting your head around, and is not yet mainstream. Meaning that most developers that join your team or maintain your code will have to learn it from scratch
**Solution:** It remains to be seen if GWT will take off, but if you're a company in control of who you hire, then you can always choose people that either know GWT or want to learn it.
---
**Problem:** GWT is a sledgehammer compared to something like jquery or just plain javascript. It takes a lot more setup to get it happening than just including a JS file.
**Solution:** Use libraries like jquery for smaller, simple tasks that are suited to those. Use GWT when you want to build something truly complex in AJAX, or where you need to pass your data back and forth via the RPC mechanism.
---
**Problem:** Sometimes in order to populate your GWT page, you need to make a server call when the page first loads. It can be annoying for the user to sit there and watch a loading symbol while you fetch the data you need.
**Solution:** In the case of a JSP page, your page was already rendered by the server before becoming HTML, so you can actually make all your GWT calls then, and pre-load them onto the page, for an instant load. See here for details:
[Speed up Page Loading by pre-serializing your GWT calls](http://wiki.shiftyjelly.com/index.php/GWT#Speed_up_Page_Loading.2C_by_pre-serializing_your_GWT_calls)
---
I've never had any problems CSS styling my widgets, out of the box, custom or otherwise, so I don't know what you mean by that being a pitfall?
As for performance, I've always found that once compiled GWT code is fast, and AJAX calls are nearly always smaller than doing a whole page refresh, but that's not really unique to GWT, though the native RPC packets that you get if you use a JAVA back end are pretty compact. |
99,876 | <p>I just wanted some opinions from people that have run Selenium (<a href="http://selenium.openqa.org" rel="nofollow noreferrer">http://selenium.openqa.org</a>) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it. </p>
<p>If you have run selenium have you had a lot of success? </p>
<p>I will be using .NET 3.5, does Selenium work well with it? </p>
<p>Is the code produced clean or simply a list of all the interaction? (<a href="http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx" rel="nofollow noreferrer">http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx</a>) </p>
<p>How well does the distributed testing suite fair?</p>
<p>Any other gripes or compliments on the system would be greatly appreciated!</p>
| [
{
"answer_id": 99965,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 6,
"selected": true,
"text": "<p>If you are using <a href=\"http://selenium-ide.openqa.org/\" rel=\"nofollow noreferrer\">Selenium IDE</a> to generate code, then you just get a list of every action that selenium will execute. To me, Selenium IDE is a good way to start or do a fast \"try and see\" test. But, when you think about maintainability and more readable code, you must write your own code.</p>\n\n<p>A good way to achieve good selenium code is to use the <a href=\"http://code.google.com/p/webdriver/wiki/PageObjects\" rel=\"nofollow noreferrer\">Page Object Pattern</a> in a way that the code represents your navigation flow. Here is a good example that I see in <a href=\"http://dojofloripa.wordpress.com/2008/04/20/como-usar-tdd-e-page-objects-para-construir-interfaces-web/\" rel=\"nofollow noreferrer\">Coding Dojo Floripa</a> (from Brazil):</p>\n\n<pre><code>public class GoogleTest {\n\n private Selenium selenium;\n\n @Before\n public void setUp() throws Exception {\n selenium = new DefaultSelenium(\"localhost\", 4444, \"*firefox\",\n \"http://www.google.com/webhp?hl=en\");\n selenium.start();\n }\n\n @Test\n public void codingDojoShouldBeInFirstPageOfResults() {\n GoogleHomePage home = new GoogleHomePage(selenium);\n GoogleSearchResults searchResults = home.searchFor(\"coding dojo\");\n String firstEntry = searchResults.getResult(0);\n assertEquals(\"Coding Dojo Wiki: FrontPage\", firstEntry);\n }\n\n @After\n public void tearDown() throws Exception {\n selenium.stop();\n }\n\n}\n\n\npublic class GoogleHomePage {\n\n private final Selenium selenium;\n\n public GoogleHomePage(Selenium selenium) {\n this.selenium = selenium;\n this.selenium.open(\"http://www.google.com/webhp?hl=en\");\n if (!\"Google\".equals(selenium.getTitle())) {\n throw new IllegalStateException(\"Not the Google Home Page\");\n }\n }\n\n public GoogleSearchResults searchFor(String string) {\n selenium.type(\"q\", string);\n selenium.click(\"btnG\");\n selenium.waitForPageToLoad(\"5000\");\n return new GoogleSearchResults(string, selenium);\n }\n}\n\npublic class GoogleSearchResults {\n\n private final Selenium selenium;\n\n public GoogleSearchResults(String string, Selenium selenium) {\n this.selenium = selenium;\n if (!(string + \" - Google Search\").equals(selenium.getTitle())) {\n throw new IllegalStateException(\n \"This is not the Google Results Page\");\n }\n }\n\n public String getResult(int i) {\n String nameXPath = \"xpath=id('res')/div[1]/div[\" + (i + 1) + \"]/h2/a\";\n return selenium.getText(nameXPath);\n }\n}\n</code></pre>\n\n<p>Hope that Helps</p>\n"
},
{
"answer_id": 103941,
"author": "Peter Bernier",
"author_id": 6112,
"author_profile": "https://Stackoverflow.com/users/6112",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using Selenium Remote Control in order to test ASP.Net apps (which is what I'm assuming you'll be targetting as well), and it works great.</p>\n\n<p>If you've never used Selenium, watch some of the <a href=\"http://wiki.openqa.org/download/attachments/400/Selenium+IDE.swf?version=1\" rel=\"nofollow noreferrer\">screencasts</a> for using Selenium IDE. This will give you a good idea of how 'Selenium' works. The IDE is a firefox plugin that basically lets you develop quick record-and-play tests as you go. For larger test suites or for writing really maintainable tests though, I'd recommend Selenium Remote Control. (The IDE is terrific if you're just getting a start though.)</p>\n\n<p><a href=\"http://selenium-rc.openqa.org/\" rel=\"nofollow noreferrer\">Selenium Remote Control</a> lets you use your favourite language and unit testing framework to drive a web browser in order to execute your tests. If you're most comfortable with C#/NUnit, you can write your tests that way and use all the NUnit goodies that you like. (For example, the Test-Driven.net plugin). Also, since your tests are written in a high level language, you're able to do things like inherit from a particular test class which you can use to make your actual test method code much cleaner. (Or at least thats the way I write my tests. It lets me test complex scenarios which keeping my test method line-count at a reasonable number.)</p>\n\n<p>You mention distributed testing. Unfortunately I haven't found a way to use the <a href=\"http://selenium-grid.openqa.org/\" rel=\"nofollow noreferrer\">Selenium Grid</a> project with NUnit. Selenium Grid allows you to execute your test suite over a number different machines and browser instances. So rather than running through say 200 test methods one after another (ie, serially), you could spread the load out over say four Grid instances (ie, running in four different browsers instances at a time) on a single machine or multiple machines depending on how distributed you want to get. </p>\n\n<p>If you write your tests in Java or PHP though, you might have better luck. I'm expecting this to be available via NUnit with the release of NUnit2.5 which will include pNUnit for parallel testing.</p>\n\n<p>If you have any further questions about selenium, just clarify your original question and I'll be happy to try and help you out. (Selenium is just one of those tools that I use everyday so I enjoy helping to get new people started with it..)</p>\n"
},
{
"answer_id": 141515,
"author": "Howard",
"author_id": 21479,
"author_profile": "https://Stackoverflow.com/users/21479",
"pm_score": 2,
"selected": false,
"text": "<p>I started out with Selenium IDE and Selenium Core. Those are definitely good tools to get you started. But they're not very powerful, since you can only use Selenese, Selenium's HTML-based command-by-command language.</p>\n\n<p>Now I use Selenium Remote Control with the Ruby driver, which allows me to utilize what Ruby offers. I test many environments: Windows 2000, XP, Vista, Mac 10.4/10.5, and for each of those that apply, Safari 2/3, Firefox 2/3, Internet Explorer 6/7.</p>\n\n<p>Selenium claims to be compatible with all those OS's and browsers, though I'm having problems currently with Internet Explorer (my first question on StackOverflow is about that, actually). But I don't know of any other tools that are this powerful and works with so many platforms.</p>\n\n<p>The biggest problem I've had with Selenium is the DOM parsing. JavaScript's childNodes is unreliable because Safari/Firefox ignore whitespace & comment nodes, while Internet Explorer doesn't. XPath in Internet Explorer is 10-20 times slower than in SF/FF. innerHTML isn't always reliable in IE.</p>\n"
},
{
"answer_id": 211452,
"author": "Petteri H",
"author_id": 28841,
"author_profile": "https://Stackoverflow.com/users/28841",
"pm_score": 1,
"selected": false,
"text": "<p>Selenium is pretty decent tool but there are couple things to watch out:</p>\n\n<ul>\n<li><p>Selenium IDE and Selenium core do not share 100% same functionality. For example right clicking is supported by IDE but current core release does not have it. However, using a newer version from their repository solves that.</p></li>\n<li><p>In case of ext js, gwt etc make sure you have proper IDs for your display elements instead of automatically generated (random) ones.</p></li>\n<li><p>Maintaining test cases. I have seen cases where a lot of effort was put on Selenium tests and good coverage. Later on tests started to fail as the person creating them was busy with other tasks and no-one else wanted to touch them. But this was issue with management, not Selenium.</p></li>\n</ul>\n"
},
{
"answer_id": 1168635,
"author": "Mark Erdmann",
"author_id": 143151,
"author_profile": "https://Stackoverflow.com/users/143151",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a big fan of Selenium. One major gotcha that's good to know about ahead of time, though, is that Selenium IDE has a lot of trouble with pop-up windows. These problems don't persist in Selenium RC, but it can make development a bit of a headache.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
]
| I just wanted some opinions from people that have run Selenium (<http://selenium.openqa.org>) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it.
If you have run selenium have you had a lot of success?
I will be using .NET 3.5, does Selenium work well with it?
Is the code produced clean or simply a list of all the interaction? (<http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx>)
How well does the distributed testing suite fair?
Any other gripes or compliments on the system would be greatly appreciated! | If you are using [Selenium IDE](http://selenium-ide.openqa.org/) to generate code, then you just get a list of every action that selenium will execute. To me, Selenium IDE is a good way to start or do a fast "try and see" test. But, when you think about maintainability and more readable code, you must write your own code.
A good way to achieve good selenium code is to use the [Page Object Pattern](http://code.google.com/p/webdriver/wiki/PageObjects) in a way that the code represents your navigation flow. Here is a good example that I see in [Coding Dojo Floripa](http://dojofloripa.wordpress.com/2008/04/20/como-usar-tdd-e-page-objects-para-construir-interfaces-web/) (from Brazil):
```
public class GoogleTest {
private Selenium selenium;
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*firefox",
"http://www.google.com/webhp?hl=en");
selenium.start();
}
@Test
public void codingDojoShouldBeInFirstPageOfResults() {
GoogleHomePage home = new GoogleHomePage(selenium);
GoogleSearchResults searchResults = home.searchFor("coding dojo");
String firstEntry = searchResults.getResult(0);
assertEquals("Coding Dojo Wiki: FrontPage", firstEntry);
}
@After
public void tearDown() throws Exception {
selenium.stop();
}
}
public class GoogleHomePage {
private final Selenium selenium;
public GoogleHomePage(Selenium selenium) {
this.selenium = selenium;
this.selenium.open("http://www.google.com/webhp?hl=en");
if (!"Google".equals(selenium.getTitle())) {
throw new IllegalStateException("Not the Google Home Page");
}
}
public GoogleSearchResults searchFor(String string) {
selenium.type("q", string);
selenium.click("btnG");
selenium.waitForPageToLoad("5000");
return new GoogleSearchResults(string, selenium);
}
}
public class GoogleSearchResults {
private final Selenium selenium;
public GoogleSearchResults(String string, Selenium selenium) {
this.selenium = selenium;
if (!(string + " - Google Search").equals(selenium.getTitle())) {
throw new IllegalStateException(
"This is not the Google Results Page");
}
}
public String getResult(int i) {
String nameXPath = "xpath=id('res')/div[1]/div[" + (i + 1) + "]/h2/a";
return selenium.getText(nameXPath);
}
}
```
Hope that Helps |
99,880 | <p>I need to write a function that generates an id that is unique for a given machine running a Windows OS.</p>
<p>Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use?
Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric.</p>
<p>However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen.</p>
<p>For reference, these are the metrics I'm currently using:</p>
<pre><code>Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeed
Win32_BIOS:Manufacturer
Win32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,Version
Win32_DiskDrive:Model, Manufacturer, Signature, TotalHeads
Win32_BaseBoard:Model, Manufacturer, Name, SerialNumber
Win32_VideoController:DriverVersion, Name
</code></pre>
| [
{
"answer_id": 99889,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>You should look into using the MAC address on the network card (if it exists). Those are usually unique but can be fabricated. I've used software that generates its license file based on your network adapter MAC address, so it's considered a fairly reliable way to distinguish between computers.</p>\n"
},
{
"answer_id": 99892,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 2,
"selected": false,
"text": "<p>What about just using the UniqueID of the processor?</p>\n"
},
{
"answer_id": 99902,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": -1,
"selected": false,
"text": "<p>Look up CPUID for one option. There might be some issues with multi-CPU systems.</p>\n"
},
{
"answer_id": 99908,
"author": "bfabry",
"author_id": 924607,
"author_profile": "https://Stackoverflow.com/users/924607",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe cheating a little, but the MAC Address of a machines Ethernet adapter rarely changes without the motherboard changing these days.</p>\n"
},
{
"answer_id": 99914,
"author": "Jonathan Adelson",
"author_id": 8092,
"author_profile": "https://Stackoverflow.com/users/8092",
"pm_score": 1,
"selected": false,
"text": "<p>I hate to be the guy who says, \"you're just doing it wrong\" (I always hate that guy ;) but...</p>\n\n<p>Does it have to be repeatably generated for the unique machine? Could you just assign the identifier or do a public/private key? Maybe if you could generate and store the value, you could access it from both OS installs on the same disk?</p>\n\n<p>You've probably explored these options and they doesn't work for you, but if not, it's something to consider.</p>\n\n<p>If it's not a matter of user trust, you could just use MAC addresses.</p>\n"
},
{
"answer_id": 99916,
"author": "Christopher Cashell",
"author_id": 13091,
"author_profile": "https://Stackoverflow.com/users/13091",
"pm_score": 0,
"selected": false,
"text": "<p>Can you pull some kind of manufacturer serial number or service tag?</p>\n\n<p>Our shop is a Dell shop, so we use the service tag which is unique to each machine to identify them. I know it can be queried from the BIOS, at least in Linux, but I don't know offhand how to do it in Windows.</p>\n"
},
{
"answer_id": 114949,
"author": "Jonas Engström",
"author_id": 7634,
"author_profile": "https://Stackoverflow.com/users/7634",
"pm_score": 6,
"selected": true,
"text": "<p>Parse the <a href=\"http://www.dmtf.org/standards/smbios/\" rel=\"noreferrer\">SMBIOS</a> yourself and hash it to an arbitrary length. See the <a href=\"http://www.dmtf.org/standards/published_documents/DSP0134_2.6.0.pdf\" rel=\"noreferrer\">PDF specification</a> for all SMBIOS structures available.</p>\n\n<p>To query the SMBIOS info from Windows you could use <a href=\"http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/enumsystemfirmwaretables.asp\" rel=\"noreferrer\"><code>EnumSystemFirmwareEntries</code></a>, <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms724259(v=vs.85).aspx\" rel=\"noreferrer\"><code>EnumSystemFirmwareTables</code></a> and <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms724379%28v=vs.85%29.aspx\" rel=\"noreferrer\"><code>GetSystemFirmwareTable</code></a>.</p>\n\n<p>IIRC, the \"unique id\" from the CPUID instruction is deprecated from P3 and newer.</p>\n"
},
{
"answer_id": 289806,
"author": "AngelBlaZe",
"author_id": 24252,
"author_profile": "https://Stackoverflow.com/users/24252",
"pm_score": 1,
"selected": false,
"text": "<p>In my program I first check for Terminal Server and use the WTSClientHardwareId. Else the MAC address of the local PC should be adequate.</p>\n\n<p>If you really want to use the list of properties you provided leave out things like <code>Name</code> and <code>DriverVersion</code>, <code>Clockspeed</code>, etc. since it's possibly OS dependent. Try outputting the same info on both operating systems and leave out that which differs between.</p>\n"
},
{
"answer_id": 820549,
"author": "Fabio Ceconello",
"author_id": 8999,
"author_profile": "https://Stackoverflow.com/users/8999",
"pm_score": 6,
"selected": false,
"text": "<p>I had the same problem and after a little research I decided the best would be to read <code>MachineGuid</code> in registry key <code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography</code>, as @Agnus suggested. It is generated during OS installation and won't change unless you make another fresh OS install. Depending on the OS version it may contain the network adapter MAC address embedded (plus some other numbers, including random), or a pseudorandom number, the later for newer OS versions (after XP SP2, I believe, but not sure). If it's a pseudorandom theoretically it can be forged - if two machines have the same initial state, including real time clock. In practice, this will be rare, but be aware if you expect it to be a base for security that can be attacked by hardcore hackers.</p>\n\n<p>Of course a registry entry can also be easily changed by anyone to forge a machine GUID, but what I found is that this would disrupt normal operation of so many components of Windows that in most cases no regular user would do it (again, watch out for hardcore hackers).</p>\n"
},
{
"answer_id": 5502834,
"author": "cmcginty",
"author_id": 110715,
"author_profile": "https://Stackoverflow.com/users/110715",
"pm_score": 1,
"selected": false,
"text": "<p>For one of my applications, I either use the computer name if it is non-domain computer, or the domain machine account SID for domain computers. Mark Russinovich talks about it in this blog post, <a href=\"http://blogs.technet.com/b/markrussinovich/archive/2009/11/03/3291024.aspx\" rel=\"nofollow\">Machine SID</a>:</p>\n\n<blockquote>\n <p>The final case where SID duplication would be an issue is if a distributed application used machine SIDs to uniquely identify computers. No Microsoft software does so and using the machine SID in that way doesn’t work just for the fact that all DC’s have the same machine SID. Software that relies on unique computer identities either uses computer names or computer Domain SIDs (the SID of the computer accounts in the Domain). </p>\n</blockquote>\n\n<p>You can access the domain machine account SID via LDAP or <code>System.DirectoryServices</code>.</p>\n"
},
{
"answer_id": 9609588,
"author": "Paul Alexander",
"author_id": 76456,
"author_profile": "https://Stackoverflow.com/users/76456",
"pm_score": 5,
"selected": false,
"text": "<p>With our <a href=\"http://xheo.com/products/copy-protection\">licensing tool</a> we consider the following components</p>\n\n<ul>\n<li>MAC Address</li>\n<li>CPU (Not the serial number, but the actual CPU profile like stepping and model)</li>\n<li>System Drive Serial Number (Not Volume Label)</li>\n<li>Memory</li>\n<li>CD-ROM model & vendor</li>\n<li>Video Card model & vendor</li>\n<li>IDE Controller</li>\n<li>SCSI Controller</li>\n</ul>\n\n<p>However, rather than just hashing the components and creating a pass/fail system, we create a <a href=\"http://xheo.com/docs/dlxl/5/html/developers%20guide/licensing%20basics/hardware%20locking%20and%20the%20activation%20process.html\">comparable fingerprint</a> that can be used to determine how different two machine profiles are. If the difference rating is above a specified tolerance then ask the user to activate again. </p>\n\n<p>We've found over the last 8 years in use with hundreds of thousands of end-user installs that this combination works well to provide a reliably unique machine id - even for virtual machines and cloned OS installs.</p>\n"
},
{
"answer_id": 17341423,
"author": "wahm sarab",
"author_id": 2515998,
"author_profile": "https://Stackoverflow.com/users/2515998",
"pm_score": -1,
"selected": false,
"text": "<p>Try this one, it gives a unique hard disk ID: <a href=\"https://code.google.com/p/dvsrc/downloads/detail?name=20120116DiskId32Port_fixed.7z&can=2&q=\" rel=\"nofollow\">Port of DiskId32 for Delphi 7-2010</a>.</p>\n"
},
{
"answer_id": 22372918,
"author": "ariwez",
"author_id": 2249054,
"author_profile": "https://Stackoverflow.com/users/2249054",
"pm_score": 1,
"selected": false,
"text": "<p>There is a library available for getting hardware specific informations: <a href=\"http://www.soft.tahionic.com/download-hdd_id/hardware%20id%20programming%20source%20code/index.html\" rel=\"nofollow\">Hardware serial number extractor (CPU, RAM, HDD, BIOS)</a></p>\n"
},
{
"answer_id": 51161965,
"author": "user2515235",
"author_id": 2515235,
"author_profile": "https://Stackoverflow.com/users/2515235",
"pm_score": 0,
"selected": false,
"text": "<p>I had an additional constraint, I was using .net express so I couldn't use the standard hardware query mechanism. So I decided to use power shell to do the query. The full code looks like this:</p>\n\n<pre><code>Private Function GetUUID() As String\n Dim GetDiskUUID As String = \"get-wmiobject Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID\"\n Dim X As String = \"\"\n Dim oProcess As New Process()\n Dim oStartInfo As New ProcessStartInfo(\"powershell.exe\", GetDiskUUID)\n oStartInfo.UseShellExecute = False\n oStartInfo.RedirectStandardInput = True\n oStartInfo.RedirectStandardOutput = True\n oStartInfo.CreateNoWindow = True\n oProcess.StartInfo = oStartInfo\n oProcess.Start()\n oProcess.WaitForExit()\n X = oProcess.StandardOutput.ReadToEnd\n Return X.Trim()\nEnd Function\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618/"
]
| I need to write a function that generates an id that is unique for a given machine running a Windows OS.
Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use?
Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric.
However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen.
For reference, these are the metrics I'm currently using:
```
Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeed
Win32_BIOS:Manufacturer
Win32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,Version
Win32_DiskDrive:Model, Manufacturer, Signature, TotalHeads
Win32_BaseBoard:Model, Manufacturer, Name, SerialNumber
Win32_VideoController:DriverVersion, Name
``` | Parse the [SMBIOS](http://www.dmtf.org/standards/smbios/) yourself and hash it to an arbitrary length. See the [PDF specification](http://www.dmtf.org/standards/published_documents/DSP0134_2.6.0.pdf) for all SMBIOS structures available.
To query the SMBIOS info from Windows you could use [`EnumSystemFirmwareEntries`](http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/enumsystemfirmwaretables.asp), [`EnumSystemFirmwareTables`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724259(v=vs.85).aspx) and [`GetSystemFirmwareTable`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724379%28v=vs.85%29.aspx).
IIRC, the "unique id" from the CPUID instruction is deprecated from P3 and newer. |
99,912 | <p>I am trying to use directory services to add a directory entry to an openldap server. The examples I have seen look pretty simple, but I keep getting the error "There is an naming violation". What does this message mean? How do I resolve it?</p>
<p>I have included the code, ldif file used to create the person container.</p>
<pre><code>Public Function Ldap_Store_Manual_Registration(ByVal userName As String, ByVal firstMiddleName As String, ByVal lastName As String, ByVal password As String)
Dim entry As DirectoryEntry = OpenLDAPconnection() 'OpenLDAPconnection() is DirectoryEntry(domainName, userId, password, AuthenticationTypes.SecureSocketsLayer) )
Dim newUser As DirectoryEntry
newUser = entry.Children.Add("ou=alumni", "organizationalUnit") 'also try with newUser = entry.Children.Add("ou=alumni,o=xxxx", "organizationalUnit") , also not working
SetADProperty(newUser, "objectClass", "organizationalPerson")
SetADProperty(newUser, "objectClass", "person")
SetADProperty(newUser, "cn", userName)
SetADProperty(newUser, "sn", userName)
newUser.CommitChanges()
End Function
Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, _
ByVal pName As String, ByVal pValue As String)
'First make sure the property value isnt "nothing"
If Not pValue Is Nothing Then
'Check to see if the DirectoryEntry contains this property already
If de.Properties.Contains(pName) Then 'The DE contains this property
'Update the properties value
de.Properties(pName)(0) = pValue
Else 'Property doesnt exist
'Add the property and set it's value
de.Properties(pName).Add(pValue)
End If
End If
End Sub
</code></pre>
<p>The ldif file:</p>
<pre><code>version: 1
dn: cn=test3,ou=alumni,o=unimelb
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: test3
sn: test3
</code></pre>
| [
{
"answer_id": 104942,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you need to include this?</p>\n\n<pre><code>SetADProperty(newUser, \"objectClass\", \"top\")\n</code></pre>\n\n<p>Also, check what the required fields for <code>organizationalPerson</code> and <code>person</code> are...you might be missing one.</p>\n"
},
{
"answer_id": 1195895,
"author": "mellamokb",
"author_id": 116614,
"author_profile": "https://Stackoverflow.com/users/116614",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>Dim entry As New DirectoryEntry(\"LDAP://ou=alumni\", etc.)\nnewUser = entry.Children.Add(\"cn=\" + userName, \"user\")\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to use directory services to add a directory entry to an openldap server. The examples I have seen look pretty simple, but I keep getting the error "There is an naming violation". What does this message mean? How do I resolve it?
I have included the code, ldif file used to create the person container.
```
Public Function Ldap_Store_Manual_Registration(ByVal userName As String, ByVal firstMiddleName As String, ByVal lastName As String, ByVal password As String)
Dim entry As DirectoryEntry = OpenLDAPconnection() 'OpenLDAPconnection() is DirectoryEntry(domainName, userId, password, AuthenticationTypes.SecureSocketsLayer) )
Dim newUser As DirectoryEntry
newUser = entry.Children.Add("ou=alumni", "organizationalUnit") 'also try with newUser = entry.Children.Add("ou=alumni,o=xxxx", "organizationalUnit") , also not working
SetADProperty(newUser, "objectClass", "organizationalPerson")
SetADProperty(newUser, "objectClass", "person")
SetADProperty(newUser, "cn", userName)
SetADProperty(newUser, "sn", userName)
newUser.CommitChanges()
End Function
Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, _
ByVal pName As String, ByVal pValue As String)
'First make sure the property value isnt "nothing"
If Not pValue Is Nothing Then
'Check to see if the DirectoryEntry contains this property already
If de.Properties.Contains(pName) Then 'The DE contains this property
'Update the properties value
de.Properties(pName)(0) = pValue
Else 'Property doesnt exist
'Add the property and set it's value
de.Properties(pName).Add(pValue)
End If
End If
End Sub
```
The ldif file:
```
version: 1
dn: cn=test3,ou=alumni,o=unimelb
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: test3
sn: test3
``` | Maybe you need to include this?
```
SetADProperty(newUser, "objectClass", "top")
```
Also, check what the required fields for `organizationalPerson` and `person` are...you might be missing one. |
99,917 | <p>So I was reading these Asp.Net <a href="http://www.hanselman.com/blog/ASPNETInterviewQuestions.aspx" rel="nofollow noreferrer">interview questions</a> at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about.</p>
| [
{
"answer_id": 100102,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>I think what he's asking here is how you wire up javascript functions to work hand in hand with your ASP.NET postback functionality.</p>\n<p>i.e. How can I trigger a control's event using my own JavaScript?</p>\n<p>The ASP.NET class library contains a <code>ClientScript</code> class - Found in the <code>System.Web.UI.Page</code> class - which enables you to programmatically add JavaScript to your ASP.NET page.</p>\n<p>This contains a method called <code>GetPostBackEventReference</code> which will generate the <code>__doPostBack</code> script ASP.NET utilises to trigger events wired up to your web controls.</p>\n<p>Hope that makes sense</p>\n"
},
{
"answer_id": 100431,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 1,
"selected": false,
"text": "<p>Do you mean something like this:</p>\n\n<p>in your code behind:</p>\n\n<pre><code>protected string GetPostBack()\n{\n return ClientScript.GetPostBackEventReference(this, null);\n}\n</code></pre>\n\n<p>and in your aspx:</p>\n\n<pre><code><a href=\"javascript:<%=GetPostBack() %>\">Click here to postback</a>\n</code></pre>\n"
},
{
"answer_id": 100577,
"author": "Martin",
"author_id": 18660,
"author_profile": "https://Stackoverflow.com/users/18660",
"pm_score": 2,
"selected": false,
"text": "<pre><code><asp:LinkButton ID="lbEdit" CssClass="button" \n OnClientClick="javascript:alert('do something')" \n onclick="OnEdit" runat="server">Edit</asp:LinkButton>\n</code></pre>\n<p>The <code>OnClientClick</code> attribute means you can add some JavaScript without losing PostBack functionality would be my answer in the interview.</p>\n"
},
{
"answer_id": 331821,
"author": "Matt Briggs",
"author_id": 10771,
"author_profile": "https://Stackoverflow.com/users/10771",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Explain how PostBacks work</p>\n</blockquote>\n\n<p>Postbacks are an abstraction on top of web protocols which emulate stateful behavior over a stateless protocol.</p>\n\n<blockquote>\n <p>, on both the client-side</p>\n</blockquote>\n\n<p>On the client side, postbacks are achieved by javascript calls and hidden fields which store the state of all controls on the page.</p>\n\n<blockquote>\n <p>and server-side.</p>\n</blockquote>\n\n<p>The server side goes through a life cycle of events, part of that life cycle is the hydration of the viewstate to maintain the state of all the controls on the page, and the raising of events based on the paramaters that were passed into the __doPostBack call on the client side</p>\n\n<blockquote>\n <p>How do I chain my own JavaScript into\n the client side without losing\n PostBack functionality?</p>\n</blockquote>\n\n<p>Depends on what is required. The easiest way that works 99% of the time is to use asp:hiddenfield to communicate between client and server side. For edge cases, you want to get into Exenders and manipulating viewstate/controlstate/clientstate in javascript through the MS ajax APIs. This is pretty painful with a huge learning curve and a lot of gotchas, generally using hidden fields and manually calling __doPostBack is enough</p>\n\n<hr>\n\n<p>That is how I would answer that bullet point. For more information on __doPostBack, a quick google will give you plenty of results (for the lazy, this is the first hit <a href=\"http://aspalliance.com/895\" rel=\"nofollow noreferrer\">http://aspalliance.com/895</a>)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
]
| So I was reading these Asp.Net [interview questions](http://www.hanselman.com/blog/ASPNETInterviewQuestions.aspx) at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about. | ```
<asp:LinkButton ID="lbEdit" CssClass="button"
OnClientClick="javascript:alert('do something')"
onclick="OnEdit" runat="server">Edit</asp:LinkButton>
```
The `OnClientClick` attribute means you can add some JavaScript without losing PostBack functionality would be my answer in the interview. |
99,927 | <p>Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures? </p>
| [
{
"answer_id": 99949,
"author": "moltenform",
"author_id": 18506,
"author_profile": "https://Stackoverflow.com/users/18506",
"pm_score": 2,
"selected": false,
"text": "<p>Variables not declared with var are global in scope. \nFunctions introduce a scope, but note that if blocks and other blocks do not introduce a scope.</p>\n\n<p>I could also see much information about this by Googling Javascript scope. That's really what I would recommend.\n<a href=\"http://www.digital-web.com/articles/scope_in_javascript/\" rel=\"nofollow noreferrer\">http://www.digital-web.com/articles/scope_in_javascript/</a></p>\n"
},
{
"answer_id": 101089,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 6,
"selected": true,
"text": "<h3>Global variables</h3>\n\n<p>Every variable in Javascript is a named attribute of an object. For example:-</p>\n\n<pre><code>var x = 1;\n</code></pre>\n\n<p>x is added to the global object. The global object is provided by the script context and may already have a set of attributes. For example in a browser the global object is window. An equivalent to the above line in a browser would be:-</p>\n\n<pre><code>window.x = 1;\n</code></pre>\n\n<h3>Local variables</h3>\n\n<p>Now what if we change this to:-</p>\n\n<pre><code>function fn()\n{\n var x = 1;\n}\n</code></pre>\n\n<p>When <code>fn</code> is called a new object is created called the <em>execution context</em> also referred to as the <em>scope</em> (I use these terms interchangeably). <code>x</code> is added as an attribute to this scope object. Hence each call to <code>fn</code> will get its own instance of a scope object and therefore its own instance of the x attribute attached to that scope object.</p>\n\n<h3>Closure</h3>\n\n<p>Now lets take this further:-</p>\n\n<pre><code>function fnSequence()\n{\n var x = 1;\n return function() { return x++; }\n}\n\nvar fn1 = fnSequence();\nvar fn2 = fnSequence();\n\nWScript.Echo(fn1())\nWScript.Echo(fn2())\nWScript.Echo(fn1())\nWScript.Echo(fn2())\nWScript.Echo(fn1())\nWScript.Echo(fn1())\nWScript.Echo(fn2())\nWScript.Echo(fn2())\n</code></pre>\n\n<p><strong>Note:</strong> Replace <code>WScript.Echo</code> with whatever writes to stdout in your context.</p>\n\n<p>The sequence you should get is :-</p>\n\n<p>1 1 2 2 3 4 3 4</p>\n\n<p>So what has happened here? We have <code>fnSequence</code> which initialises a variable <code>x</code> to 1 and returns an anonymous function which will return the value of <code>x</code> and then increment it.</p>\n\n<p>When this function is first executed a scope object is created and an attribute <code>x</code> is added to that scope object with the value of 1. Also created in the same execution object is an anonymous function. Each function object will have a scope attribute which points to the execution context in which it is created. This creates what is know as a <em>scope chain</em> which we will come to later. A reference to this function is returned by <code>fnSequence</code> and stored in <code>fn1</code>.</p>\n\n<p>Note that <code>fn1</code> is now pointing at the anonymous function and that the anonymous function has a scope attribute pointing at a scope object that still has an <code>x</code> attribute attached. This is known as <code>closure</code> where the contents of an execution context is still reachable after the function it was created for has completed execution.</p>\n\n<p>Now this same sequence happens when assigning to <code>fn2</code>. <code>fn2</code> will be pointing at a different anonymous function that was created in a different execution context that was create when <code>fnSequence</code> was called this second time.</p>\n\n<h3>Scope Chain</h3>\n\n<p>What happens when the function held by <code>fn1</code> is executed the first time? A new execution context is created for the execution of the anonymous function. A return value is to be found from the identifier <code>x</code>. The function's scope object is inspected for an <code>x</code> attribute but none is found. This is where the <em>scope chain</em> comes in. Having failed to find <code>x</code> in the current execution context JavaScript takes the object held by the function's scope attribute and looks for <code>x</code> there. It finds it since the functions scope was created inside an execution of <code>fnSequence</code>, retrieves its value and increments it. Hence 1 is output and the <code>x</code> in this scope is incremented to 2.</p>\n\n<p>Now when <code>fn2</code> is executed it is ultimately attached to a different execution context whose <code>x</code> attribute is still 1. Hence executing <code>fn2</code> also results in 1.</p>\n\n<p>As you can see <code>fn1</code> and <code>fn2</code> each generate their own independent sequence of numbers.</p>\n"
},
{
"answer_id": 101135,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 1,
"selected": false,
"text": "<p>Functions introduce a scope. You can declare functions inside other functions, thereby creating a nested scope. The inner scope can access the outer scope, but the outer can not access the inner scope.</p>\n\n<p>Variables are bound to a scope, using the <strong>var</strong> keyword. All variables are implicitly bound to the top-level scope. So if you omit the var keyword, you are implicitly referring to a variable bound to the top level. In a browser, the top level is the <strong>window</strong> object. Note that <strong>window</strong> is it self a variable, so <strong>window</strong> == <strong>window.window</strong></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/99927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56663/"
]
| Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures? | ### Global variables
Every variable in Javascript is a named attribute of an object. For example:-
```
var x = 1;
```
x is added to the global object. The global object is provided by the script context and may already have a set of attributes. For example in a browser the global object is window. An equivalent to the above line in a browser would be:-
```
window.x = 1;
```
### Local variables
Now what if we change this to:-
```
function fn()
{
var x = 1;
}
```
When `fn` is called a new object is created called the *execution context* also referred to as the *scope* (I use these terms interchangeably). `x` is added as an attribute to this scope object. Hence each call to `fn` will get its own instance of a scope object and therefore its own instance of the x attribute attached to that scope object.
### Closure
Now lets take this further:-
```
function fnSequence()
{
var x = 1;
return function() { return x++; }
}
var fn1 = fnSequence();
var fn2 = fnSequence();
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn1())
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn2())
```
**Note:** Replace `WScript.Echo` with whatever writes to stdout in your context.
The sequence you should get is :-
1 1 2 2 3 4 3 4
So what has happened here? We have `fnSequence` which initialises a variable `x` to 1 and returns an anonymous function which will return the value of `x` and then increment it.
When this function is first executed a scope object is created and an attribute `x` is added to that scope object with the value of 1. Also created in the same execution object is an anonymous function. Each function object will have a scope attribute which points to the execution context in which it is created. This creates what is know as a *scope chain* which we will come to later. A reference to this function is returned by `fnSequence` and stored in `fn1`.
Note that `fn1` is now pointing at the anonymous function and that the anonymous function has a scope attribute pointing at a scope object that still has an `x` attribute attached. This is known as `closure` where the contents of an execution context is still reachable after the function it was created for has completed execution.
Now this same sequence happens when assigning to `fn2`. `fn2` will be pointing at a different anonymous function that was created in a different execution context that was create when `fnSequence` was called this second time.
### Scope Chain
What happens when the function held by `fn1` is executed the first time? A new execution context is created for the execution of the anonymous function. A return value is to be found from the identifier `x`. The function's scope object is inspected for an `x` attribute but none is found. This is where the *scope chain* comes in. Having failed to find `x` in the current execution context JavaScript takes the object held by the function's scope attribute and looks for `x` there. It finds it since the functions scope was created inside an execution of `fnSequence`, retrieves its value and increments it. Hence 1 is output and the `x` in this scope is incremented to 2.
Now when `fn2` is executed it is ultimately attached to a different execution context whose `x` attribute is still 1. Hence executing `fn2` also results in 1.
As you can see `fn1` and `fn2` each generate their own independent sequence of numbers. |
100,003 | <p>What are metaclasses? What are they used for?</p>
| [
{
"answer_id": 100037,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 9,
"selected": false,
"text": "<p><em>Note, this answer is for Python 2.x as it was written in 2008, metaclasses are slightly different in 3.x.</em></p>\n\n<p>Metaclasses are the secret sauce that make 'class' work. The default metaclass for a new style object is called 'type'.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>class type(object)\n | type(object) -> the object's type\n | type(name, bases, dict) -> a new type\n</code></pre>\n\n<p>Metaclasses take 3 args. '<strong>name</strong>', '<strong>bases</strong>' and '<strong>dict</strong>'</p>\n\n<p>Here is where the secret starts. Look for where name, bases and the dict come from in this example class definition.</p>\n\n<pre><code>class ThisIsTheName(Bases, Are, Here):\n All_the_code_here\n def doesIs(create, a):\n dict\n</code></pre>\n\n<p>Lets define a metaclass that will demonstrate how '<strong>class:</strong>' calls it.</p>\n\n<pre><code>def test_metaclass(name, bases, dict):\n print 'The Class Name is', name\n print 'The Class Bases are', bases\n print 'The dict has', len(dict), 'elems, the keys are', dict.keys()\n\n return \"yellow\"\n\nclass TestName(object, None, int, 1):\n __metaclass__ = test_metaclass\n foo = 1\n def baz(self, arr):\n pass\n\nprint 'TestName = ', repr(TestName)\n\n# output => \nThe Class Name is TestName\nThe Class Bases are (<type 'object'>, None, <type 'int'>, 1)\nThe dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']\nTestName = 'yellow'\n</code></pre>\n\n<p>And now, an example that actually means something, this will automatically make the variables in the list \"attributes\" set on the class, and set to None.</p>\n\n<pre><code>def init_attributes(name, bases, dict):\n if 'attributes' in dict:\n for attr in dict['attributes']:\n dict[attr] = None\n\n return type(name, bases, dict)\n\nclass Initialised(object):\n __metaclass__ = init_attributes\n attributes = ['foo', 'bar', 'baz']\n\nprint 'foo =>', Initialised.foo\n# output=>\nfoo => None\n</code></pre>\n\n<p><strong>Note that the magic behaviour that <code>Initialised</code> gains by having the metaclass <code>init_attributes</code> is not passed onto a subclass of <code>Initialised</code>.</strong></p>\n\n<p>Here is an even more concrete example, showing how you can subclass 'type' to make a metaclass that performs an action when the class is created. This is quite tricky:</p>\n\n<pre><code>class MetaSingleton(type):\n instance = None\n def __call__(cls, *args, **kw):\n if cls.instance is None:\n cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)\n return cls.instance\n\nclass Foo(object):\n __metaclass__ = MetaSingleton\n\na = Foo()\nb = Foo()\nassert a is b\n</code></pre>\n"
},
{
"answer_id": 100059,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 7,
"selected": false,
"text": "<p>I think the ONLamp introduction to metaclass programming is well written and gives a really good introduction to the topic despite being several years old already.</p>\n\n<p><a href=\"http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html\" rel=\"noreferrer\">http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html</a> (archived at <a href=\"https://web.archive.org/web/20080206005253/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html\" rel=\"noreferrer\">https://web.archive.org/web/20080206005253/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html</a>)</p>\n\n<p>In short: A class is a blueprint for the creation of an instance, a metaclass is a blueprint for the creation of a class. It can be easily seen that in Python classes need to be first-class objects too to enable this behavior.</p>\n\n<p>I've never written one myself, but I think one of the nicest uses of metaclasses can be seen in the <a href=\"http://www.djangoproject.com/\" rel=\"noreferrer\">Django framework</a>. The model classes use a metaclass approach to enable a declarative style of writing new models or form classes. While the metaclass is creating the class, all members get the possibility to customize the class itself.</p>\n\n<ul>\n<li><a href=\"http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3\" rel=\"noreferrer\">Creating a new model</a></li>\n<li><a href=\"http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py#L25\" rel=\"noreferrer\">The metaclass enabling this</a></li>\n</ul>\n\n<p>The thing that's left to say is: If you don't know what metaclasses are, the probability that you <strong>will not need them</strong> is 99%.</p>\n"
},
{
"answer_id": 100091,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 8,
"selected": false,
"text": "<p>One use for metaclasses is adding new properties and methods to an instance automatically.</p>\n\n<p>For example, if you look at <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/\" rel=\"noreferrer\">Django models</a>, their definition looks a bit confusing. It looks as if you are only defining class properties:</p>\n\n<pre><code>class Person(models.Model):\n first_name = models.CharField(max_length=30)\n last_name = models.CharField(max_length=30)\n</code></pre>\n\n<p>However, at runtime the Person objects are filled with all sorts of useful methods. See the <a href=\"http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py\" rel=\"noreferrer\">source</a> for some amazing metaclassery.</p>\n"
},
{
"answer_id": 100146,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 13,
"selected": true,
"text": "<p>A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.</p>\n\n<p>While in Python you can use arbitrary callables for metaclasses (like <a href=\"https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037\">Jerub</a> shows), the better approach is to make it an actual class itself. <code>type</code> is the usual metaclass in Python. <code>type</code> is itself a class, and it is its own type. You won't be able to recreate something like <code>type</code> purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass <code>type</code>.</p>\n\n<p>A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal <code>__init__</code> and <code>__new__</code> methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.</p>\n\n<p>When the <code>class</code> statement is executed, Python first executes the body of the <code>class</code> statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the <code>__metaclass__</code> attribute of the class-to-be (if any) or the <code>__metaclass__</code> global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.</p>\n\n<p>However, metaclasses actually define the <em>type</em> of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. <code>type.__subclasses__()</code> is an example of a method on the <code>type</code> metaclass. You can also define the normal 'magic' methods, like <code>__add__</code>, <code>__iter__</code> and <code>__getattr__</code>, to implement or change how the class behaves.</p>\n\n<p>Here's an aggregated example of the bits and pieces:</p>\n\n<pre><code>def make_hook(f):\n \"\"\"Decorator to turn 'foo' method into '__foo__'\"\"\"\n f.is_hook = 1\n return f\n\nclass MyType(type):\n def __new__(mcls, name, bases, attrs):\n\n if name.startswith('None'):\n return None\n\n # Go over attributes and see if they should be renamed.\n newattrs = {}\n for attrname, attrvalue in attrs.iteritems():\n if getattr(attrvalue, 'is_hook', 0):\n newattrs['__%s__' % attrname] = attrvalue\n else:\n newattrs[attrname] = attrvalue\n\n return super(MyType, mcls).__new__(mcls, name, bases, newattrs)\n\n def __init__(self, name, bases, attrs):\n super(MyType, self).__init__(name, bases, attrs)\n\n # classregistry.register(self, self.interfaces)\n print \"Would register class %s now.\" % self\n\n def __add__(self, other):\n class AutoClass(self, other):\n pass\n return AutoClass\n # Alternatively, to autogenerate the classname as well as the class:\n # return type(self.__name__ + other.__name__, (self, other), {})\n\n def unregister(self):\n # classregistry.unregister(self)\n print \"Would unregister class %s now.\" % self\n\nclass MyObject:\n __metaclass__ = MyType\n\n\nclass NoneSample(MyObject):\n pass\n\n# Will print \"NoneType None\"\nprint type(NoneSample), repr(NoneSample)\n\nclass Example(MyObject):\n def __init__(self, value):\n self.value = value\n @make_hook\n def add(self, other):\n return self.__class__(self.value + other.value)\n\n# Will unregister the class\nExample.unregister()\n\ninst = Example(10)\n# Will fail with an AttributeError\n#inst.unregister()\n\nprint inst + inst\nclass Sibling(MyObject):\n pass\n\nExampleSibling = Example + Sibling\n# ExampleSibling is now a subclass of both Example and Sibling (with no\n# content of its own) although it will believe it's called 'AutoClass'\nprint ExampleSibling\nprint ExampleSibling.__mro__\n</code></pre>\n"
},
{
"answer_id": 6428779,
"author": "kindall",
"author_id": 416467,
"author_profile": "https://Stackoverflow.com/users/416467",
"pm_score": 8,
"selected": false,
"text": "<p>Others have explained how metaclasses work and how they fit into the Python type system. Here's an example of what they can be used for. In a testing framework I wrote, I wanted to keep track of the order in which classes were defined, so that I could later instantiate them in this order. I found it easiest to do this using a metaclass.</p>\n\n<pre><code>class MyMeta(type):\n\n counter = 0\n\n def __init__(cls, name, bases, dic):\n type.__init__(cls, name, bases, dic)\n cls._order = MyMeta.counter\n MyMeta.counter += 1\n\nclass MyType(object): # Python 2\n __metaclass__ = MyMeta\n\nclass MyType(metaclass=MyMeta): # Python 3\n pass\n</code></pre>\n\n<p>Anything that's a subclass of <code>MyType</code> then gets a class attribute <code>_order</code> that records the order in which the classes were defined.</p>\n"
},
{
"answer_id": 6581949,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 13,
"selected": false,
"text": "<h1>Classes as objects</h1>\n<p>Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language.</p>\n<p>In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too:</p>\n<pre><code>>>> class ObjectCreator(object):\n... pass\n...\n\n>>> my_object = ObjectCreator()\n>>> print(my_object)\n<__main__.ObjectCreator object at 0x8974f2c>\n</code></pre>\n<p>But classes are more than that in Python. Classes are objects too.</p>\n<p>Yes, objects.</p>\n<p>As soon as you use the keyword <code>class</code>, Python executes it and creates\nan <strong>object</strong>. The instruction</p>\n<pre><code>>>> class ObjectCreator(object):\n... pass\n...\n</code></pre>\n<p>creates in memory an object with the name <code>ObjectCreator</code>.</p>\n<p><strong>This object (the class) is itself capable of creating objects (the instances),\nand this is why it's a class</strong>.</p>\n<p>But still, it's an object, and therefore:</p>\n<ul>\n<li>you can assign it to a variable</li>\n<li>you can copy it</li>\n<li>you can add attributes to it</li>\n<li>you can pass it as a function parameter</li>\n</ul>\n<p>e.g.:</p>\n<pre><code>>>> print(ObjectCreator) # you can print a class because it's an object\n<class '__main__.ObjectCreator'>\n>>> def echo(o):\n... print(o)\n...\n>>> echo(ObjectCreator) # you can pass a class as a parameter\n<class '__main__.ObjectCreator'>\n>>> print(hasattr(ObjectCreator, 'new_attribute'))\nFalse\n>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class\n>>> print(hasattr(ObjectCreator, 'new_attribute'))\nTrue\n>>> print(ObjectCreator.new_attribute)\nfoo\n>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable\n>>> print(ObjectCreatorMirror.new_attribute)\nfoo\n>>> print(ObjectCreatorMirror())\n<__main__.ObjectCreator object at 0x8997b4c>\n</code></pre>\n<h1>Creating classes dynamically</h1>\n<p>Since classes are objects, you can create them on the fly, like any object.</p>\n<p>First, you can create a class in a function using <code>class</code>:</p>\n<pre><code>>>> def choose_class(name):\n... if name == 'foo':\n... class Foo(object):\n... pass\n... return Foo # return the class, not an instance\n... else:\n... class Bar(object):\n... pass\n... return Bar\n...\n>>> MyClass = choose_class('foo')\n>>> print(MyClass) # the function returns a class, not an instance\n<class '__main__.Foo'>\n>>> print(MyClass()) # you can create an object from this class\n<__main__.Foo object at 0x89c6d4c>\n</code></pre>\n<p>But it's not so dynamic, since you still have to write the whole class yourself.</p>\n<p>Since classes are objects, they must be generated by something.</p>\n<p>When you use the <code>class</code> keyword, Python creates this object automatically. But as\nwith most things in Python, it gives you a way to do it manually.</p>\n<p>Remember the function <code>type</code>? The good old function that lets you know what\ntype an object is:</p>\n<pre><code>>>> print(type(1))\n<type 'int'>\n>>> print(type("1"))\n<type 'str'>\n>>> print(type(ObjectCreator))\n<type 'type'>\n>>> print(type(ObjectCreator()))\n<class '__main__.ObjectCreator'>\n</code></pre>\n<p>Well, <a href=\"http://docs.python.org/2/library/functions.html#type\" rel=\"noreferrer\"><code>type</code></a> has also a completely different ability: it can create classes on the fly. <code>type</code> can take the description of a class as parameters,\nand return a class.</p>\n<p>(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward\ncompatibility in Python)</p>\n<p><code>type</code> works this way:</p>\n<pre><code>type(name, bases, attrs)\n</code></pre>\n<p>Where:</p>\n<ul>\n<li><strong><code>name</code></strong>: name of the class</li>\n<li><strong><code>bases</code></strong>: tuple of the parent class (for inheritance, can be empty)</li>\n<li><strong><code>attrs</code></strong>: dictionary containing attributes names and values</li>\n</ul>\n<p>e.g.:</p>\n<pre><code>>>> class MyShinyClass(object):\n... pass\n</code></pre>\n<p>can be created manually this way:</p>\n<pre><code>>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object\n>>> print(MyShinyClass)\n<class '__main__.MyShinyClass'>\n>>> print(MyShinyClass()) # create an instance with the class\n<__main__.MyShinyClass object at 0x8997cec>\n</code></pre>\n<p>You'll notice that we use <code>MyShinyClass</code> as the name of the class\nand as the variable to hold the class reference. They can be different,\nbut there is no reason to complicate things.</p>\n<p><code>type</code> accepts a dictionary to define the attributes of the class. So:</p>\n<pre><code>>>> class Foo(object):\n... bar = True\n</code></pre>\n<p>Can be translated to:</p>\n<pre><code>>>> Foo = type('Foo', (), {'bar':True})\n</code></pre>\n<p>And used as a normal class:</p>\n<pre><code>>>> print(Foo)\n<class '__main__.Foo'>\n>>> print(Foo.bar)\nTrue\n>>> f = Foo()\n>>> print(f)\n<__main__.Foo object at 0x8a9b84c>\n>>> print(f.bar)\nTrue\n</code></pre>\n<p>And of course, you can inherit from it, so:</p>\n<pre><code>>>> class FooChild(Foo):\n... pass\n</code></pre>\n<p>would be:</p>\n<pre><code>>>> FooChild = type('FooChild', (Foo,), {})\n>>> print(FooChild)\n<class '__main__.FooChild'>\n>>> print(FooChild.bar) # bar is inherited from Foo\nTrue\n</code></pre>\n<p>Eventually, you'll want to add methods to your class. Just define a function\nwith the proper signature and assign it as an attribute.</p>\n<pre><code>>>> def echo_bar(self):\n... print(self.bar)\n...\n>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})\n>>> hasattr(Foo, 'echo_bar')\nFalse\n>>> hasattr(FooChild, 'echo_bar')\nTrue\n>>> my_foo = FooChild()\n>>> my_foo.echo_bar()\nTrue\n</code></pre>\n<p>And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.</p>\n<pre><code>>>> def echo_bar_more(self):\n... print('yet another method')\n...\n>>> FooChild.echo_bar_more = echo_bar_more\n>>> hasattr(FooChild, 'echo_bar_more')\nTrue\n</code></pre>\n<p>You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.</p>\n<p>This is what Python does when you use the keyword <code>class</code>, and it does so by using a metaclass.</p>\n<h1>What are metaclasses (finally)</h1>\n<p>Metaclasses are the 'stuff' that creates classes.</p>\n<p>You define classes in order to create objects, right?</p>\n<p>But we learned that Python classes are objects.</p>\n<p>Well, metaclasses are what create these objects. They are the classes' classes,\nyou can picture them this way:</p>\n<pre><code>MyClass = MetaClass()\nmy_object = MyClass()\n</code></pre>\n<p>You've seen that <code>type</code> lets you do something like this:</p>\n<pre><code>MyClass = type('MyClass', (), {})\n</code></pre>\n<p>It's because the function <code>type</code> is in fact a metaclass. <code>type</code> is the\nmetaclass Python uses to create all classes behind the scenes.</p>\n<p>Now you wonder "why the heck is it written in lowercase, and not <code>Type</code>?"</p>\n<p>Well, I guess it's a matter of consistency with <code>str</code>, the class that creates\nstrings objects, and <code>int</code> the class that creates integer objects. <code>type</code> is\njust the class that creates class objects.</p>\n<p>You see that by checking the <code>__class__</code> attribute.</p>\n<p>Everything, and I mean everything, is an object in Python. That includes integers,\nstrings, functions and classes. All of them are objects. And all of them have\nbeen created from a class:</p>\n<pre><code>>>> age = 35\n>>> age.__class__\n<type 'int'>\n>>> name = 'bob'\n>>> name.__class__\n<type 'str'>\n>>> def foo(): pass\n>>> foo.__class__\n<type 'function'>\n>>> class Bar(object): pass\n>>> b = Bar()\n>>> b.__class__\n<class '__main__.Bar'>\n</code></pre>\n<p>Now, what is the <code>__class__</code> of any <code>__class__</code> ?</p>\n<pre><code>>>> age.__class__.__class__\n<type 'type'>\n>>> name.__class__.__class__\n<type 'type'>\n>>> foo.__class__.__class__\n<type 'type'>\n>>> b.__class__.__class__\n<type 'type'>\n</code></pre>\n<p>So, a metaclass is just the stuff that creates class objects.</p>\n<p>You can call it a 'class factory' if you wish.</p>\n<p><code>type</code> is the built-in metaclass Python uses, but of course, you can create your\nown metaclass.</p>\n<h1>The <a href=\"http://docs.python.org/2/reference/datamodel.html?highlight=__metaclass__#__metaclass__\" rel=\"noreferrer\"><code>__metaclass__</code></a> attribute</h1>\n<p>In Python 2, you can add a <code>__metaclass__</code> attribute when you write a class (see next section for the Python 3 syntax):</p>\n<pre><code>class Foo(object):\n __metaclass__ = something...\n [...]\n</code></pre>\n<p>If you do so, Python will use the metaclass to create the class <code>Foo</code>.</p>\n<p>Careful, it's tricky.</p>\n<p>You write <code>class Foo(object)</code> first, but the class object <code>Foo</code> is not created\nin memory yet.</p>\n<p>Python will look for <code>__metaclass__</code> in the class definition. If it finds it,\nit will use it to create the object class <code>Foo</code>. If it doesn't, it will use\n<code>type</code> to create the class.</p>\n<p>Read that several times.</p>\n<p>When you do:</p>\n<pre><code>class Foo(Bar):\n pass\n</code></pre>\n<p>Python does the following:</p>\n<p>Is there a <code>__metaclass__</code> attribute in <code>Foo</code>?</p>\n<p>If yes, create in-memory a class object (I said a class object, stay with me here), with the name <code>Foo</code> by using what is in <code>__metaclass__</code>.</p>\n<p>If Python can't find <code>__metaclass__</code>, it will look for a <code>__metaclass__</code> at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).</p>\n<p>Then if it can't find any <code>__metaclass__</code> at all, it will use the <code>Bar</code>'s (the first parent) own metaclass (which might be the default <code>type</code>) to create the class object.</p>\n<p>Be careful here that the <code>__metaclass__</code> attribute will not be inherited, the metaclass of the parent (<code>Bar.__class__</code>) will be. If <code>Bar</code> used a <code>__metaclass__</code> attribute that created <code>Bar</code> with <code>type()</code> (and not <code>type.__new__()</code>), the subclasses will not inherit that behavior.</p>\n<p>Now the big question is, what can you put in <code>__metaclass__</code>?</p>\n<p>The answer is something that can create a class.</p>\n<p>And what can create a class? <code>type</code>, or anything that subclasses or uses it.</p>\n<h1>Metaclasses in Python 3</h1>\n<p>The syntax to set the metaclass has been changed in Python 3:</p>\n<pre><code>class Foo(object, metaclass=something):\n ...\n</code></pre>\n<p>i.e. the <code>__metaclass__</code> attribute is no longer used, in favor of a keyword argument in the list of base classes.</p>\n<p>The behavior of metaclasses however stays <a href=\"https://www.python.org/dev/peps/pep-3115/\" rel=\"noreferrer\">largely the same</a>.</p>\n<p>One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:</p>\n<pre><code>class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):\n ...\n</code></pre>\n<p>Read the section below for how Python handles this.</p>\n<h1>Custom metaclasses</h1>\n<p>The main purpose of a metaclass is to change the class automatically,\nwhen it's created.</p>\n<p>You usually do this for APIs, where you want to create classes matching the\ncurrent context.</p>\n<p>Imagine a stupid example, where you decide that all classes in your module\nshould have their attributes written in uppercase. There are several ways to\ndo this, but one way is to set <code>__metaclass__</code> at the module level.</p>\n<p>This way, all classes of this module will be created using this metaclass,\nand we just have to tell the metaclass to turn all attributes to uppercase.</p>\n<p>Luckily, <code>__metaclass__</code> can actually be any callable, it doesn't need to be a\nformal class (I know, something with 'class' in its name doesn't need to be\na class, go figure... but it's helpful).</p>\n<p>So we will start with a simple example, by using a function.</p>\n<pre><code># the metaclass will automatically get passed the same argument\n# that you usually pass to `type`\ndef upper_attr(future_class_name, future_class_parents, future_class_attrs):\n """\n Return a class object, with the list of its attribute turned\n into uppercase.\n """\n # pick up any attribute that doesn't start with '__' and uppercase it\n uppercase_attrs = {\n attr if attr.startswith("__") else attr.upper(): v\n for attr, v in future_class_attrs.items()\n }\n\n # let `type` do the class creation\n return type(future_class_name, future_class_parents, uppercase_attrs)\n\n__metaclass__ = upper_attr # this will affect all classes in the module\n\nclass Foo(): # global __metaclass__ won't work with "object" though\n # but we can define __metaclass__ here instead to affect only this class\n # and this will work with "object" children\n bar = 'bip'\n</code></pre>\n<p>Let's check:</p>\n<pre><code>>>> hasattr(Foo, 'bar')\nFalse\n>>> hasattr(Foo, 'BAR')\nTrue\n>>> Foo.BAR\n'bip'\n</code></pre>\n<p>Now, let's do exactly the same, but using a real class for a metaclass:</p>\n<pre><code># remember that `type` is actually a class like `str` and `int`\n# so you can inherit from it\nclass UpperAttrMetaclass(type):\n # __new__ is the method called before __init__\n # it's the method that creates the object and returns it\n # while __init__ just initializes the object passed as parameter\n # you rarely use __new__, except when you want to control how the object\n # is created.\n # here the created object is the class, and we want to customize it\n # so we override __new__\n # you can do some stuff in __init__ too if you wish\n # some advanced use involves overriding __call__ as well, but we won't\n # see this\n def __new__(upperattr_metaclass, future_class_name,\n future_class_parents, future_class_attrs):\n uppercase_attrs = {\n attr if attr.startswith("__") else attr.upper(): v\n for attr, v in future_class_attrs.items()\n }\n return type(future_class_name, future_class_parents, uppercase_attrs)\n</code></pre>\n<p>Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean:</p>\n<pre><code>class UpperAttrMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n uppercase_attrs = {\n attr if attr.startswith("__") else attr.upper(): v\n for attr, v in attrs.items()\n }\n return type(clsname, bases, uppercase_attrs)\n</code></pre>\n<p>You may have noticed the extra argument <code>cls</code>. There is\nnothing special about it: <code>__new__</code> always receives the class it's defined in, as the first parameter. Just like you have <code>self</code> for ordinary methods which receive the instance as the first parameter, or the defining class for class methods.</p>\n<p>But this is not proper OOP. We are calling <code>type</code> directly and we aren't overriding or calling the parent's <code>__new__</code>. Let's do that instead:</p>\n<pre><code>class UpperAttrMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n uppercase_attrs = {\n attr if attr.startswith("__") else attr.upper(): v\n for attr, v in attrs.items()\n }\n return type.__new__(cls, clsname, bases, uppercase_attrs)\n</code></pre>\n<p>We can make it even cleaner by using <code>super</code>, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):</p>\n<pre><code>class UpperAttrMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n uppercase_attrs = {\n attr if attr.startswith("__") else attr.upper(): v\n for attr, v in attrs.items()\n }\n\n # Python 2 requires passing arguments to super:\n return super(UpperAttrMetaclass, cls).__new__(\n cls, clsname, bases, uppercase_attrs)\n\n # Python 3 can use no-arg super() which infers them:\n return super().__new__(cls, clsname, bases, uppercase_attrs)\n</code></pre>\n<p>Oh, and in Python 3 if you do this call with keyword arguments, like this:</p>\n<pre><code>class Foo(object, metaclass=MyMetaclass, kwarg1=value1):\n ...\n</code></pre>\n<p>It translates to this in the metaclass to use it:</p>\n<pre><code>class MyMetaclass(type):\n def __new__(cls, clsname, bases, dct, kwargs1=default):\n ...\n</code></pre>\n<p>That's it. There is really nothing more about metaclasses.</p>\n<p>The reason behind the complexity of the code using metaclasses is not because\nof metaclasses, it's because you usually use metaclasses to do twisted stuff\nrelying on introspection, manipulating inheritance, vars such as <code>__dict__</code>, etc.</p>\n<p>Indeed, metaclasses are especially useful to do black magic, and therefore\ncomplicated stuff. But by themselves, they are simple:</p>\n<ul>\n<li>intercept a class creation</li>\n<li>modify the class</li>\n<li>return the modified class</li>\n</ul>\n<h1>Why would you use metaclasses classes instead of functions?</h1>\n<p>Since <code>__metaclass__</code> can accept any callable, why would you use a class\nsince it's obviously more complicated?</p>\n<p>There are several reasons to do so:</p>\n<ul>\n<li>The intention is clear. When you read <code>UpperAttrMetaclass(type)</code>, you know\nwhat's going to follow</li>\n<li>You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.</li>\n<li>Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function.</li>\n<li>You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.</li>\n<li>You can hook on <code>__new__</code>, <code>__init__</code> and <code>__call__</code>. Which will allow you to do different stuff, Even if usually you can do it all in <code>__new__</code>,\nsome people are just more comfortable using <code>__init__</code>.</li>\n<li>These are called metaclasses, damn it! It must mean something!</li>\n</ul>\n<h1>Why would you use metaclasses?</h1>\n<p>Now the big question. Why would you use some obscure error-prone feature?</p>\n<p>Well, usually you don't:</p>\n<blockquote>\n<p>Metaclasses are deeper magic that\n99% of users should never worry about it.\nIf you wonder whether you need them,\nyou don't (the people who actually\nneed them know with certainty that\nthey need them, and don't need an\nexplanation about why).</p>\n</blockquote>\n<p><em>Python Guru Tim Peters</em></p>\n<p>The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this:</p>\n<pre><code>class Person(models.Model):\n name = models.CharField(max_length=30)\n age = models.IntegerField()\n</code></pre>\n<p>But if you do this:</p>\n<pre><code>person = Person(name='bob', age='35')\nprint(person.age)\n</code></pre>\n<p>It won't return an <code>IntegerField</code> object. It will return an <code>int</code>, and can even take it directly from the database.</p>\n<p>This is possible because <code>models.Model</code> defines <code>__metaclass__</code> and\nit uses some magic that will turn the <code>Person</code> you just defined with simple statements\ninto a complex hook to a database field.</p>\n<p>Django makes something complex look simple by exposing a simple API\nand using metaclasses, recreating code from this API to do the real job\nbehind the scenes.</p>\n<h1>The last word</h1>\n<p>First, you know that classes are objects that can create instances.</p>\n<p>Well, in fact, classes are themselves instances. Of metaclasses.</p>\n<pre><code>>>> class Foo(object): pass\n>>> id(Foo)\n142630324\n</code></pre>\n<p>Everything is an object in Python, and they are all either instance of classes\nor instances of metaclasses.</p>\n<p>Except for <code>type</code>.</p>\n<p><code>type</code> is actually its own metaclass. This is not something you could\nreproduce in pure Python, and is done by cheating a little bit at the implementation\nlevel.</p>\n<p>Secondly, metaclasses are complicated. You may not want to use them for\nvery simple class alterations. You can change classes by using two different techniques:</p>\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Monkey_patch\" rel=\"noreferrer\">monkey patching</a></li>\n<li>class decorators</li>\n</ul>\n<p>99% of the time you need class alteration, you are better off using these.</p>\n<p>But 98% of the time, you don't need class alteration at all.</p>\n"
},
{
"answer_id": 21999253,
"author": "Craig",
"author_id": 1489354,
"author_profile": "https://Stackoverflow.com/users/1489354",
"pm_score": 6,
"selected": false,
"text": "<p>A <code>metaclass</code> is a class that tells how (some) other class should be created.</p>\n<p>This is a case where I saw <code>metaclass</code> as a solution to my problem:\nI had a really complicated problem, that probably could have been solved differently, but I chose to solve it using a <code>metaclass</code>. Because of the complexity, it is one of the few modules I have written where the comments in the module surpass the amount of code that has been written. Here it is...</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\n# Copyright (C) 2013-2014 Craig Phillips. All rights reserved.\n\n# This requires some explaining. The point of this metaclass excercise is to\n# create a static abstract class that is in one way or another, dormant until\n# queried. I experimented with creating a singlton on import, but that did\n# not quite behave how I wanted it to. See now here, we are creating a class\n# called GsyncOptions, that on import, will do nothing except state that its\n# class creator is GsyncOptionsType. This means, docopt doesn't parse any\n# of the help document, nor does it start processing command line options.\n# So importing this module becomes really efficient. The complicated bit\n# comes from requiring the GsyncOptions class to be static. By that, I mean\n# any property on it, may or may not exist, since they are not statically\n# defined; so I can't simply just define the class with a whole bunch of\n# properties that are @property @staticmethods.\n#\n# So here's how it works:\n#\n# Executing 'from libgsync.options import GsyncOptions' does nothing more\n# than load up this module, define the Type and the Class and import them\n# into the callers namespace. Simple.\n#\n# Invoking 'GsyncOptions.debug' for the first time, or any other property\n# causes the __metaclass__ __getattr__ method to be called, since the class\n# is not instantiated as a class instance yet. The __getattr__ method on\n# the type then initialises the class (GsyncOptions) via the __initialiseClass\n# method. This is the first and only time the class will actually have its\n# dictionary statically populated. The docopt module is invoked to parse the\n# usage document and generate command line options from it. These are then\n# paired with their defaults and what's in sys.argv. After all that, we\n# setup some dynamic properties that could not be defined by their name in\n# the usage, before everything is then transplanted onto the actual class\n# object (or static class GsyncOptions).\n#\n# Another piece of magic, is to allow command line options to be set in\n# in their native form and be translated into argparse style properties.\n#\n# Finally, the GsyncListOptions class is actually where the options are\n# stored. This only acts as a mechanism for storing options as lists, to\n# allow aggregation of duplicate options or options that can be specified\n# multiple times. The __getattr__ call hides this by default, returning the\n# last item in a property's list. However, if the entire list is required,\n# calling the 'list()' method on the GsyncOptions class, returns a reference\n# to the GsyncListOptions class, which contains all of the same properties\n# but as lists and without the duplication of having them as both lists and\n# static singlton values.\n#\n# So this actually means that GsyncOptions is actually a static proxy class...\n#\n# ...And all this is neatly hidden within a closure for safe keeping.\ndef GetGsyncOptionsType():\n class GsyncListOptions(object):\n __initialised = False\n\n class GsyncOptionsType(type):\n def __initialiseClass(cls):\n if GsyncListOptions._GsyncListOptions__initialised: return\n\n from docopt import docopt\n from libgsync.options import doc\n from libgsync import __version__\n\n options = docopt(\n doc.__doc__ % __version__,\n version = __version__,\n options_first = True\n )\n\n paths = options.pop('<path>', None)\n setattr(cls, "destination_path", paths.pop() if paths else None)\n setattr(cls, "source_paths", paths)\n setattr(cls, "options", options)\n\n for k, v in options.iteritems():\n setattr(cls, k, v)\n\n GsyncListOptions._GsyncListOptions__initialised = True\n\n def list(cls):\n return GsyncListOptions\n\n def __getattr__(cls, name):\n cls.__initialiseClass()\n return getattr(GsyncListOptions, name)[-1]\n\n def __setattr__(cls, name, value):\n # Substitut option names: --an-option-name for an_option_name\n import re\n name = re.sub(r'^__', "", re.sub(r'-', "_", name))\n listvalue = []\n\n # Ensure value is converted to a list type for GsyncListOptions\n if isinstance(value, list):\n if value:\n listvalue = [] + value\n else:\n listvalue = [ None ]\n else:\n listvalue = [ value ]\n\n type.__setattr__(GsyncListOptions, name, listvalue)\n\n # Cleanup this module to prevent tinkering.\n import sys\n module = sys.modules[__name__]\n del module.__dict__['GetGsyncOptionsType']\n\n return GsyncOptionsType\n\n# Our singlton abstract proxy class.\nclass GsyncOptions(object):\n __metaclass__ = GetGsyncOptionsType()\n</code></pre>\n"
},
{
"answer_id": 31930795,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 7,
"selected": false,
"text": "<blockquote>\n <h2>What are metaclasses? What do you use them for?</h2>\n</blockquote>\n\n<p>TLDR: A metaclass instantiates and defines behavior for a class just like a class instantiates and defines behavior for an instance. </p>\n\n<p>Pseudocode:</p>\n\n<pre><code>>>> Class(...)\ninstance\n</code></pre>\n\n<p>The above should look familiar. Well, where does <code>Class</code> come from? It's an instance of a metaclass (also pseudocode):</p>\n\n<pre><code>>>> Metaclass(...)\nClass\n</code></pre>\n\n<p>In real code, we can pass the default metaclass, <code>type</code>, everything we need to instantiate a class and we get a class:</p>\n\n<pre><code>>>> type('Foo', (object,), {}) # requires a name, bases, and a namespace\n<class '__main__.Foo'>\n</code></pre>\n\n<h2>Putting it differently</h2>\n\n<ul>\n<li><p>A class is to an instance as a metaclass is to a class. </p>\n\n<p>When we instantiate an object, we get an instance:</p>\n\n<pre><code>>>> object() # instantiation of class\n<object object at 0x7f9069b4e0b0> # instance\n</code></pre>\n\n<p>Likewise, when we define a class explicitly with the default metaclass, <code>type</code>, we instantiate it:</p>\n\n<pre><code>>>> type('Object', (object,), {}) # instantiation of metaclass\n<class '__main__.Object'> # instance\n</code></pre></li>\n<li><p>Put another way, a class is an instance of a metaclass:</p>\n\n<pre><code>>>> isinstance(object, type)\nTrue\n</code></pre></li>\n<li><p>Put a third way, a metaclass is a class's class.</p>\n\n<pre><code>>>> type(object) == type\nTrue\n>>> object.__class__\n<class 'type'>\n</code></pre></li>\n</ul>\n\n<p>When you write a class definition and Python executes it, it uses a metaclass to instantiate the class object (which will, in turn, be used to instantiate instances of that class).</p>\n\n<p>Just as we can use class definitions to change how custom object instances behave, we can use a metaclass class definition to change the way a class object behaves.</p>\n\n<p>What can they be used for? From the <a href=\"https://docs.python.org/3/reference/datamodel.html#metaclass-example\" rel=\"noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p>The potential uses for metaclasses are boundless. Some ideas that have been explored include logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.</p>\n</blockquote>\n\n<p>Nevertheless, it is usually encouraged for users to avoid using metaclasses unless absolutely necessary.</p>\n\n<h1>You use a metaclass every time you create a class:</h1>\n\n<p>When you write a class definition, for example, like this,</p>\n\n<pre><code>class Foo(object): \n 'demo'\n</code></pre>\n\n<p>You instantiate a class object.</p>\n\n<pre><code>>>> Foo\n<class '__main__.Foo'>\n>>> isinstance(Foo, type), isinstance(Foo, object)\n(True, True)\n</code></pre>\n\n<p>It is the same as functionally calling <code>type</code> with the appropriate arguments and assigning the result to a variable of that name:</p>\n\n<pre><code>name = 'Foo'\nbases = (object,)\nnamespace = {'__doc__': 'demo'}\nFoo = type(name, bases, namespace)\n</code></pre>\n\n<p>Note, some things automatically get added to the <code>__dict__</code>, i.e., the namespace:</p>\n\n<pre><code>>>> Foo.__dict__\ndict_proxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, \n'__module__': '__main__', '__weakref__': <attribute '__weakref__' \nof 'Foo' objects>, '__doc__': 'demo'})\n</code></pre>\n\n<p>The <em>metaclass</em> of the object we created, in both cases, is <code>type</code>. </p>\n\n<p>(A side-note on the contents of the class <code>__dict__</code>: <code>__module__</code> is there because classes must know where they are defined, and <code>__dict__</code> and <code>__weakref__</code> are there because we don't define <code>__slots__</code> - if we <a href=\"https://stackoverflow.com/q/472000/541136\">define <code>__slots__</code></a> we'll save a bit of space in the instances, as we can disallow <code>__dict__</code> and <code>__weakref__</code> by excluding them. For example:</p>\n\n<pre><code>>>> Baz = type('Bar', (object,), {'__doc__': 'demo', '__slots__': ()})\n>>> Baz.__dict__\nmappingproxy({'__doc__': 'demo', '__slots__': (), '__module__': '__main__'})\n</code></pre>\n\n<p>... but I digress.)</p>\n\n<h1>We can extend <code>type</code> just like any other class definition:</h1>\n\n<p>Here's the default <code>__repr__</code> of classes:</p>\n\n<pre><code>>>> Foo\n<class '__main__.Foo'>\n</code></pre>\n\n<p>One of the most valuable things we can do by default in writing a Python object is to provide it with a good <code>__repr__</code>. When we call <code>help(repr)</code> we learn that there's a good test for a <code>__repr__</code> that also requires a test for equality - <code>obj == eval(repr(obj))</code>. The following simple implementation of <code>__repr__</code> and <code>__eq__</code> for class instances of our type class provides us with a demonstration that may improve on the default <code>__repr__</code> of classes:</p>\n\n<pre><code>class Type(type):\n def __repr__(cls):\n \"\"\"\n >>> Baz\n Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n >>> eval(repr(Baz))\n Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n \"\"\"\n metaname = type(cls).__name__\n name = cls.__name__\n parents = ', '.join(b.__name__ for b in cls.__bases__)\n if parents:\n parents += ','\n namespace = ', '.join(': '.join(\n (repr(k), repr(v) if not isinstance(v, type) else v.__name__))\n for k, v in cls.__dict__.items())\n return '{0}(\\'{1}\\', ({2}), {{{3}}})'.format(metaname, name, parents, namespace)\n def __eq__(cls, other):\n \"\"\"\n >>> Baz == eval(repr(Baz))\n True \n \"\"\"\n return (cls.__name__, cls.__bases__, cls.__dict__) == (\n other.__name__, other.__bases__, other.__dict__)\n</code></pre>\n\n<p>So now when we create an object with this metaclass, the <code>__repr__</code> echoed on the command line provides a much less ugly sight than the default:</p>\n\n<pre><code>>>> class Bar(object): pass\n>>> Baz = Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n>>> Baz\nType('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n</code></pre>\n\n<p>With a nice <code>__repr__</code> defined for the class instance, we have a stronger ability to debug our code. However, much further checking with <code>eval(repr(Class))</code> is unlikely (as functions would be rather impossible to eval from their default <code>__repr__</code>'s).</p>\n\n<h1>An expected usage: <code>__prepare__</code> a namespace</h1>\n\n<p>If, for example, we want to know in what order a class's methods are created in, we could provide an ordered dict as the namespace of the class. We would do this with <code>__prepare__</code> which <a href=\"https://docs.python.org/3/reference/datamodel.html#preparing-the-class-namespace\" rel=\"noreferrer\">returns the namespace dict for the class if it is implemented in Python 3</a>: </p>\n\n<pre><code>from collections import OrderedDict\n\nclass OrderedType(Type):\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n return OrderedDict()\n def __new__(cls, name, bases, namespace, **kwargs):\n result = Type.__new__(cls, name, bases, dict(namespace))\n result.members = tuple(namespace)\n return result\n</code></pre>\n\n<p>And usage:</p>\n\n<pre><code>class OrderedMethodsObject(object, metaclass=OrderedType):\n def method1(self): pass\n def method2(self): pass\n def method3(self): pass\n def method4(self): pass\n</code></pre>\n\n<p>And now we have a record of the order in which these methods (and other class attributes) were created:</p>\n\n<pre><code>>>> OrderedMethodsObject.members\n('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4')\n</code></pre>\n\n<p>Note, this example was adapted from the <a href=\"https://docs.python.org/3/reference/datamodel.html#metaclass-example\" rel=\"noreferrer\">documentation</a> - the new <a href=\"https://github.com/python/cpython/blob/master/Lib/enum.py\" rel=\"noreferrer\">enum in the standard library</a> does this.</p>\n\n<p>So what we did was instantiate a metaclass by creating a class. We can also treat the metaclass as we would any other class. It has a method resolution order:</p>\n\n<pre><code>>>> inspect.getmro(OrderedType)\n(<class '__main__.OrderedType'>, <class '__main__.Type'>, <class 'type'>, <class 'object'>)\n</code></pre>\n\n<p>And it has approximately the correct <code>repr</code> (which we can no longer eval unless we can find a way to represent our functions.):</p>\n\n<pre><code>>>> OrderedMethodsObject\nOrderedType('OrderedMethodsObject', (object,), {'method1': <function OrderedMethodsObject.method1 at 0x0000000002DB01E0>, 'members': ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4'), 'method3': <function OrderedMet\nhodsObject.method3 at 0x0000000002DB02F0>, 'method2': <function OrderedMethodsObject.method2 at 0x0000000002DB0268>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'OrderedMethodsObject' objects>, '__doc__': None, '__d\nict__': <attribute '__dict__' of 'OrderedMethodsObject' objects>, 'method4': <function OrderedMethodsObject.method4 at 0x0000000002DB0378>})\n</code></pre>\n"
},
{
"answer_id": 35732111,
"author": "Ethan Furman",
"author_id": 208880,
"author_profile": "https://Stackoverflow.com/users/208880",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Python 3 update</strong></p>\n\n<p>There are (at this point) two key methods in a metaclass:</p>\n\n<ul>\n<li><code>__prepare__</code>, and</li>\n<li><code>__new__</code></li>\n</ul>\n\n<p><code>__prepare__</code> lets you supply a custom mapping (such as an <code>OrderedDict</code>) to be used as the namespace while the class is being created. You must return an instance of whatever namespace you choose. If you don't implement <code>__prepare__</code> a normal <code>dict</code> is used.</p>\n\n<p><code>__new__</code> is responsible for the actual creation/modification of the final class.</p>\n\n<p>A bare-bones, do-nothing-extra metaclass would like:</p>\n\n<pre><code>class Meta(type):\n\n def __prepare__(metaclass, cls, bases):\n return dict()\n\n def __new__(metacls, cls, bases, clsdict):\n return super().__new__(metacls, cls, bases, clsdict)\n</code></pre>\n\n<p>A simple example:</p>\n\n<p>Say you want some simple validation code to run on your attributes -- like it must always be an <code>int</code> or a <code>str</code>. Without a metaclass, your class would look something like:</p>\n\n<pre><code>class Person:\n weight = ValidateType('weight', int)\n age = ValidateType('age', int)\n name = ValidateType('name', str)\n</code></pre>\n\n<p>As you can see, you have to repeat the name of the attribute twice. This makes typos possible along with irritating bugs.</p>\n\n<p>A simple metaclass can address that problem:</p>\n\n<pre><code>class Person(metaclass=Validator):\n weight = ValidateType(int)\n age = ValidateType(int)\n name = ValidateType(str)\n</code></pre>\n\n<p>This is what the metaclass would look like (not using <code>__prepare__</code> since it is not needed):</p>\n\n<pre><code>class Validator(type):\n def __new__(metacls, cls, bases, clsdict):\n # search clsdict looking for ValidateType descriptors\n for name, attr in clsdict.items():\n if isinstance(attr, ValidateType):\n attr.name = name\n attr.attr = '_' + name\n # create final class and return it\n return super().__new__(metacls, cls, bases, clsdict)\n</code></pre>\n\n<p>A sample run of:</p>\n\n<pre><code>p = Person()\np.weight = 9\nprint(p.weight)\np.weight = '9'\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>9\nTraceback (most recent call last):\n File \"simple_meta.py\", line 36, in <module>\n p.weight = '9'\n File \"simple_meta.py\", line 24, in __set__\n (self.name, self.type, value))\nTypeError: weight must be of type(s) <class 'int'> (got '9')\n</code></pre>\n\n<hr>\n\n<p><strong>Note</strong>: This example is simple enough it could have also been accomplished with a class decorator, but presumably an actual metaclass would be doing much more.</p>\n\n<p>The 'ValidateType' class for reference:</p>\n\n<pre><code>class ValidateType:\n def __init__(self, type):\n self.name = None # will be set by metaclass\n self.attr = None # will be set by metaclass\n self.type = type\n def __get__(self, inst, cls):\n if inst is None:\n return self\n else:\n return inst.__dict__[self.attr]\n def __set__(self, inst, value):\n if not isinstance(value, self.type):\n raise TypeError('%s must be of type(s) %s (got %r)' %\n (self.name, self.type, value))\n else:\n inst.__dict__[self.attr] = value\n</code></pre>\n"
},
{
"answer_id": 38858285,
"author": "Mushahid Khan",
"author_id": 4636600,
"author_profile": "https://Stackoverflow.com/users/4636600",
"pm_score": 6,
"selected": false,
"text": "<p><code>type</code> is actually a <code>metaclass</code> -- a class that creates another classes.\nMost <code>metaclass</code> are the subclasses of <code>type</code>. The <code>metaclass</code> receives the <code>new</code> class as its first argument and provide access to class object with details as mentioned below:</p>\n\n<pre><code>>>> class MetaClass(type):\n... def __init__(cls, name, bases, attrs):\n... print ('class name: %s' %name )\n... print ('Defining class %s' %cls)\n... print('Bases %s: ' %bases)\n... print('Attributes')\n... for (name, value) in attrs.items():\n... print ('%s :%r' %(name, value))\n... \n\n>>> class NewClass(object, metaclass=MetaClass):\n... get_choch='dairy'\n... \nclass name: NewClass\nBases <class 'object'>: \nDefining class <class 'NewClass'>\nget_choch :'dairy'\n__module__ :'builtins'\n__qualname__ :'NewClass'\n</code></pre>\n\n<p><code>Note:</code></p>\n\n<p>Notice that the class was not instantiated at any time; the simple act of creating the class triggered execution of the <code>metaclass</code>.</p>\n"
},
{
"answer_id": 40017019,
"author": "Michael Ekoka",
"author_id": 56974,
"author_profile": "https://Stackoverflow.com/users/56974",
"pm_score": 7,
"selected": false,
"text": "<h1>Role of a metaclass' <code>__call__()</code> method when creating a class instance</h1>\n\n<p>If you've done Python programming for more than a few months you'll eventually stumble upon code that looks like this:</p>\n\n<pre><code># define a class\nclass SomeClass(object):\n # ...\n # some definition here ...\n # ...\n\n# create an instance of it\ninstance = SomeClass()\n\n# then call the object as if it's a function\nresult = instance('foo', 'bar')\n</code></pre>\n\n<p>The latter is possible when you implement the <code>__call__()</code> magic method on the class.</p>\n\n<pre><code>class SomeClass(object):\n # ...\n # some definition here ...\n # ...\n\n def __call__(self, foo, bar):\n return bar + foo\n</code></pre>\n\n<p>The <code>__call__()</code> method is invoked when an instance of a class is used as a callable. But as we've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we're actually calling its metaclass' <code>__call__()</code> method. At this point most Python programmers are a bit confused because they've been told that when creating an instance like this <code>instance = SomeClass()</code> you're calling its <code>__init__()</code> method. Some who've dug a bit deeper know that before <code>__init__()</code> there's <code>__new__()</code>. Well, today another layer of truth is being revealed, before <code>__new__()</code> there's the metaclass' <code>__call__()</code>.</p>\n\n<p>Let's study the method call chain from specifically the perspective of creating an instance of a class.</p>\n\n<p>This is a metaclass that logs exactly the moment before an instance is created and the moment it's about to return it.</p>\n\n<pre><code>class Meta_1(type):\n def __call__(cls):\n print \"Meta_1.__call__() before creating an instance of \", cls\n instance = super(Meta_1, cls).__call__()\n print \"Meta_1.__call__() about to return instance.\"\n return instance\n</code></pre>\n\n<p>This is a class that uses that metaclass</p>\n\n<pre><code>class Class_1(object):\n\n __metaclass__ = Meta_1\n\n def __new__(cls):\n print \"Class_1.__new__() before creating an instance.\"\n instance = super(Class_1, cls).__new__(cls)\n print \"Class_1.__new__() about to return instance.\"\n return instance\n\n def __init__(self):\n print \"entering Class_1.__init__() for instance initialization.\"\n super(Class_1,self).__init__()\n print \"exiting Class_1.__init__().\"\n</code></pre>\n\n<p>And now let's create an instance of <code>Class_1</code></p>\n\n<pre><code>instance = Class_1()\n# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.\n# Class_1.__new__() before creating an instance.\n# Class_1.__new__() about to return instance.\n# entering Class_1.__init__() for instance initialization.\n# exiting Class_1.__init__().\n# Meta_1.__call__() about to return instance.\n</code></pre>\n\n<p>Observe that the code above doesn't actually do anything more than logging the tasks. Each method delegates the actual work to its parent's implementation, thus keeping the default behavior. Since <code>type</code> is <code>Meta_1</code>'s parent class (<code>type</code> being the default parent metaclass) and considering the ordering sequence of the output above, we now have a clue as to what would be the pseudo implementation of <code>type.__call__()</code>:</p>\n\n<pre><code>class type:\n def __call__(cls, *args, **kwarg):\n\n # ... maybe a few things done to cls here\n\n # then we call __new__() on the class to create an instance\n instance = cls.__new__(cls, *args, **kwargs)\n\n # ... maybe a few things done to the instance here\n\n # then we initialize the instance with its __init__() method\n instance.__init__(*args, **kwargs)\n\n # ... maybe a few more things done to instance here\n\n # then we return it\n return instance\n</code></pre>\n\n<p>We can see that the metaclass' <code>__call__()</code> method is the one that's called first. It then delegates creation of the instance to the class's <code>__new__()</code> method and initialization to the instance's <code>__init__()</code>. It's also the one that ultimately returns the instance.</p>\n\n<p>From the above it stems that the metaclass' <code>__call__()</code> is also given the opportunity to decide whether or not a call to <code>Class_1.__new__()</code> or <code>Class_1.__init__()</code> will eventually be made. Over the course of its execution it could actually return an object that hasn't been touched by either of these methods. Take for example this approach to the singleton pattern:</p>\n\n<pre><code>class Meta_2(type):\n singletons = {}\n\n def __call__(cls, *args, **kwargs):\n if cls in Meta_2.singletons:\n # we return the only instance and skip a call to __new__()\n # and __init__()\n print (\"{} singleton returning from Meta_2.__call__(), \"\n \"skipping creation of new instance.\".format(cls))\n return Meta_2.singletons[cls]\n\n # else if the singleton isn't present we proceed as usual\n print \"Meta_2.__call__() before creating an instance.\"\n instance = super(Meta_2, cls).__call__(*args, **kwargs)\n Meta_2.singletons[cls] = instance\n print \"Meta_2.__call__() returning new instance.\"\n return instance\n\nclass Class_2(object):\n\n __metaclass__ = Meta_2\n\n def __new__(cls, *args, **kwargs):\n print \"Class_2.__new__() before creating instance.\"\n instance = super(Class_2, cls).__new__(cls)\n print \"Class_2.__new__() returning instance.\"\n return instance\n\n def __init__(self, *args, **kwargs):\n print \"entering Class_2.__init__() for initialization.\"\n super(Class_2, self).__init__()\n print \"exiting Class_2.__init__().\"\n</code></pre>\n\n<p>Let's observe what happens when repeatedly trying to create an object of type <code>Class_2</code></p>\n\n<pre><code>a = Class_2()\n# Meta_2.__call__() before creating an instance.\n# Class_2.__new__() before creating instance.\n# Class_2.__new__() returning instance.\n# entering Class_2.__init__() for initialization.\n# exiting Class_2.__init__().\n# Meta_2.__call__() returning new instance.\n\nb = Class_2()\n# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.\n\nc = Class_2()\n# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.\n\na is b is c # True\n</code></pre>\n"
},
{
"answer_id": 41338238,
"author": "noɥʇʎԀʎzɐɹƆ",
"author_id": 1459669,
"author_profile": "https://Stackoverflow.com/users/1459669",
"pm_score": 6,
"selected": false,
"text": "<h2>The tl;dr version</h2>\n\n<p>The <code>type(obj)</code> function gets you the type of an object. </p>\n\n<p><strong>The <code>type()</code> of a class is its <em>metaclass</em>.</strong></p>\n\n<p>To use a metaclass:</p>\n\n<pre><code>class Foo(object):\n __metaclass__ = MyMetaClass\n</code></pre>\n\n<p><code>type</code> is its own metaclass. The class of a class is a metaclass-- the body of a class is the arguments passed to the metaclass that is used to construct the class.</p>\n\n<p><a href=\"https://docs.python.org/3/reference/datamodel.html#metaclasses\" rel=\"noreferrer\">Here</a> you can read about how to use metaclasses to customize class construction.</p>\n"
},
{
"answer_id": 45074712,
"author": "Xingzhou Liu",
"author_id": 8056974,
"author_profile": "https://Stackoverflow.com/users/8056974",
"pm_score": 5,
"selected": false,
"text": "<p>Python classes are themselves objects - as in instance - of their meta-class. </p>\n\n<p>The default metaclass, which is applied when when you determine classes as:</p>\n\n<pre><code>class foo:\n ...\n</code></pre>\n\n<p>meta class are used to apply some rule to an entire set of classes. For example, suppose you're building an ORM to access a database, and you want records from each table to be of a class mapped to that table (based on fields, business rules, etc..,), a possible use of metaclass is for instance, connection pool logic, which is share by all classes of record from all tables. Another use is logic to to support foreign keys, which involves multiple classes of records. </p>\n\n<p>when you define metaclass, you subclass type, and can overrided the following magic methods to insert your logic. </p>\n\n<pre><code>class somemeta(type):\n __new__(mcs, name, bases, clsdict):\n \"\"\"\n mcs: is the base metaclass, in this case type.\n name: name of the new class, as provided by the user.\n bases: tuple of base classes \n clsdict: a dictionary containing all methods and attributes defined on class\n\n you must return a class object by invoking the __new__ constructor on the base metaclass. \n ie: \n return type.__call__(mcs, name, bases, clsdict).\n\n in the following case:\n\n class foo(baseclass):\n __metaclass__ = somemeta\n\n an_attr = 12\n\n def bar(self):\n ...\n\n @classmethod\n def foo(cls):\n ...\n\n arguments would be : ( somemeta, \"foo\", (baseclass, baseofbase,..., object), {\"an_attr\":12, \"bar\": <function>, \"foo\": <bound class method>}\n\n you can modify any of these values before passing on to type\n \"\"\"\n return type.__call__(mcs, name, bases, clsdict)\n\n\n def __init__(self, name, bases, clsdict):\n \"\"\" \n called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.\n \"\"\"\n pass\n\n\n def __prepare__():\n \"\"\"\n returns a dict or something that can be used as a namespace.\n the type will then attach methods and attributes from class definition to it.\n\n call order :\n\n somemeta.__new__ -> type.__new__ -> type.__init__ -> somemeta.__init__ \n \"\"\"\n return dict()\n\n def mymethod(cls):\n \"\"\" works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.\n \"\"\"\n pass\n</code></pre>\n\n<p>anyhow, those two are the most commonly used hooks. metaclassing is powerful, and above is nowhere near and exhaustive list of uses for metaclassing. </p>\n"
},
{
"answer_id": 48222963,
"author": "binbjz",
"author_id": 5064780,
"author_profile": "https://Stackoverflow.com/users/5064780",
"pm_score": 5,
"selected": false,
"text": "<p>The type() function can return the type of an object or create a new type, </p>\n\n<p>for example, we can create a Hi class with the type() function and do not need to use this way with class Hi(object):</p>\n\n<pre><code>def func(self, name='mike'):\n print('Hi, %s.' % name)\n\nHi = type('Hi', (object,), dict(hi=func))\nh = Hi()\nh.hi()\nHi, mike.\n\ntype(Hi)\ntype\n\ntype(h)\n__main__.Hi\n</code></pre>\n\n<p>In addition to using type() to create classes dynamically, you can control creation behavior of class and use metaclass.</p>\n\n<p>According to the Python object model, the class is the object, so the class must be an instance of another certain class.\nBy default, a Python class is instance of the type class. That is, type is metaclass of most of the built-in classes and metaclass of user-defined classes.</p>\n\n<pre><code>class ListMetaclass(type):\n def __new__(cls, name, bases, attrs):\n attrs['add'] = lambda self, value: self.append(value)\n return type.__new__(cls, name, bases, attrs)\n\nclass CustomList(list, metaclass=ListMetaclass):\n pass\n\nlst = CustomList()\nlst.add('custom_list_1')\nlst.add('custom_list_2')\n\nlst\n['custom_list_1', 'custom_list_2']\n</code></pre>\n\n<p>Magic will take effect when we passed keyword arguments in metaclass, it indicates the Python interpreter to create the CustomList through ListMetaclass. <strong>new</strong> (), at this point, we can modify the class definition, for example, and add a new method and then return the revised definition.</p>\n"
},
{
"answer_id": 52344780,
"author": "Andy Jazz",
"author_id": 6599590,
"author_profile": "https://Stackoverflow.com/users/6599590",
"pm_score": 5,
"selected": false,
"text": "<p>In addition to the published answers I can say that a <code>metaclass</code> defines the behaviour for a class. So, you can explicitly set your metaclass. Whenever Python gets a keyword <code>class</code> then it starts searching for the <code>metaclass</code>. If it's not found – the default metaclass type is used to create the class's object. Using the <code>__metaclass__</code> attribute, you can set <code>metaclass</code> of your class:</p>\n\n<pre><code>class MyClass:\n __metaclass__ = type\n # write here other method\n # write here one more method\n\nprint(MyClass.__metaclass__)\n</code></pre>\n\n<p>It'll produce the output like this:</p>\n\n<pre><code>class 'type'\n</code></pre>\n\n<p>And, of course, you can create your own <code>metaclass</code> to define the behaviour of any class that are created using your class.</p>\n\n<p>For doing that, your default <code>metaclass</code> type class must be inherited as this is the main <code>metaclass</code>:</p>\n\n<pre><code>class MyMetaClass(type):\n __metaclass__ = type\n # you can write here any behaviour you want\n\nclass MyTestClass:\n __metaclass__ = MyMetaClass\n\nObj = MyTestClass()\nprint(Obj.__metaclass__)\nprint(MyMetaClass.__metaclass__)\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code>class '__main__.MyMetaClass'\nclass 'type'\n</code></pre>\n"
},
{
"answer_id": 56945952,
"author": "Venu Gopal Tewari",
"author_id": 1609259,
"author_profile": "https://Stackoverflow.com/users/1609259",
"pm_score": 4,
"selected": false,
"text": "<p>In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain class and their instances\nThe term metaclass simply means something used to create classes. In other words, it is the class of a class. The metaclass is used to create the class so like the object being an instance of a class, a class is an instance of a metaclass. In python classes are also considered objects.</p>\n"
},
{
"answer_id": 59424178,
"author": "Carson",
"author_id": 9935654,
"author_profile": "https://Stackoverflow.com/users/9935654",
"pm_score": 4,
"selected": false,
"text": "<p>Here's another example of what it can be used for:</p>\n\n<ul>\n<li>You can use the <code>metaclass</code> to change the function of its instance (the class).</li>\n</ul>\n\n<pre><code>class MetaMemberControl(type):\n __slots__ = ()\n\n @classmethod\n def __prepare__(mcs, f_cls_name, f_cls_parents, # f_cls means: future class\n meta_args=None, meta_options=None): # meta_args and meta_options is not necessarily needed, just so you know.\n f_cls_attr = dict()\n if not \"do something or if you want to define your cool stuff of dict...\":\n return dict(make_your_special_dict=None)\n else:\n return f_cls_attr\n\n def __new__(mcs, f_cls_name, f_cls_parents, f_cls_attr,\n meta_args=None, meta_options=None):\n\n original_getattr = f_cls_attr.get('__getattribute__')\n original_setattr = f_cls_attr.get('__setattr__')\n\n def init_getattr(self, item):\n if not item.startswith('_'): # you can set break points at here\n alias_name = '_' + item\n if alias_name in f_cls_attr['__slots__']:\n item = alias_name\n if original_getattr is not None:\n return original_getattr(self, item)\n else:\n return super(eval(f_cls_name), self).__getattribute__(item)\n\n def init_setattr(self, key, value):\n if not key.startswith('_') and ('_' + key) in f_cls_attr['__slots__']:\n raise AttributeError(f\"you can't modify private members:_{key}\")\n if original_setattr is not None:\n original_setattr(self, key, value)\n else:\n super(eval(f_cls_name), self).__setattr__(key, value)\n\n f_cls_attr['__getattribute__'] = init_getattr\n f_cls_attr['__setattr__'] = init_setattr\n\n cls = super().__new__(mcs, f_cls_name, f_cls_parents, f_cls_attr)\n return cls\n\n\nclass Human(metaclass=MetaMemberControl):\n __slots__ = ('_age', '_name')\n\n def __init__(self, name, age):\n self._name = name\n self._age = age\n\n def __getattribute__(self, item):\n \"\"\"\n is just for IDE recognize.\n \"\"\"\n return super().__getattribute__(item)\n\n \"\"\" with MetaMemberControl then you don't have to write as following\n @property\n def name(self):\n return self._name\n\n @property\n def age(self):\n return self._age\n \"\"\"\n\n\ndef test_demo():\n human = Human('Carson', 27)\n # human.age = 18 # you can't modify private members:_age <-- this is defined by yourself.\n # human.k = 18 # 'Human' object has no attribute 'k' <-- system error.\n age1 = human._age # It's OK, although the IDE will show some warnings. (Access to a protected member _age of a class)\n\n age2 = human.age # It's OK! see below:\n \"\"\"\n if you do not define `__getattribute__` at the class of Human,\n the IDE will show you: Unresolved attribute reference 'age' for class 'Human'\n but it's ok on running since the MetaMemberControl will help you.\n \"\"\"\n\n\nif __name__ == '__main__':\n test_demo()\n\n</code></pre>\n\n<p>The <code>metaclass</code> is powerful, there are many things (such as monkey magic) you can do with it, but be careful this may only be known to you.</p>\n"
},
{
"answer_id": 59818321,
"author": "Swati Srivastava",
"author_id": 9851541,
"author_profile": "https://Stackoverflow.com/users/9851541",
"pm_score": 4,
"selected": false,
"text": "<p>A class, in Python, is an object, and just like any other object, it is an instance of \"something\". This \"something\" is what is termed as a Metaclass. This metaclass is a special type of class that creates other class's objects. Hence, metaclass is responsible for making new classes. This allows the programmer to customize the way classes are generated.</p>\n\n<p>To create a metaclass, overriding of <strong>new</strong>() and <strong>init</strong>() methods is usually done. <strong>new</strong>() can be overridden to change the way objects are created, while <strong>init</strong>() can be overridden to change the way of initializing the object. Metaclass can be created by a number of ways. One of the ways is to use type() function. type() function, when called with 3 parameters, creates a metaclass. The parameters are :-</p>\n\n<ol>\n<li>Class Name</li>\n<li>Tuple having base classes inherited by class</li>\n<li>A dictionary having all class methods and class variables</li>\n</ol>\n\n<p>Another way of creating a metaclass comprises of 'metaclass' keyword. Define the metaclass as a simple class. In the parameters of inherited class, pass metaclass=metaclass_name</p>\n\n<p>Metaclass can be specifically used in the following situations :-</p>\n\n<ol>\n<li>when a particular effect has to be applied to all the subclasses</li>\n<li>Automatic change of class (on creation) is required</li>\n<li>By API developers</li>\n</ol>\n"
},
{
"answer_id": 60504738,
"author": "Lars",
"author_id": 1023470,
"author_profile": "https://Stackoverflow.com/users/1023470",
"pm_score": 4,
"selected": false,
"text": "<p>Note that in python 3.6 a new dunder method <code>__init_subclass__(cls, **kwargs)</code> was introduced to replace a lot of common use cases for metaclasses. Is is called when a subclass of the defining class is created. See <a href=\"https://docs.python.org/3.6/reference/datamodel.html\" rel=\"noreferrer\">python docs</a>.</p>\n"
},
{
"answer_id": 67201732,
"author": "DrosnickX",
"author_id": 15691322,
"author_profile": "https://Stackoverflow.com/users/15691322",
"pm_score": 3,
"selected": false,
"text": "<p>In Python, a metaclass is a subclass of a subclass that determines how a subclass behaves. A class is an instance of another metaclass. In Python, a class specifies how the class's instance will behave.</p>\n<p>Since metaclasses are in charge of class generation, you can write your own custom metaclasses to change how classes are created by performing additional actions or injecting code. Custom metaclasses aren't always important, but they can be.</p>\n"
},
{
"answer_id": 68354618,
"author": "Emma Brown",
"author_id": 13649935,
"author_profile": "https://Stackoverflow.com/users/13649935",
"pm_score": 4,
"selected": false,
"text": "<p>I saw an interesting use case for metaclasses in a package called <code>classutilities</code>. It checks if all class variables are in upper case format (it is convenient to have unified logic for configuration classes), and checks if there are no instance level methods in class.\nAnother interesting example for metaclases was deactivation of unittests based on complex conditions (checking values of multiple environmental variables).</p>\n"
},
{
"answer_id": 68417609,
"author": "Manukumar",
"author_id": 14964700,
"author_profile": "https://Stackoverflow.com/users/14964700",
"pm_score": 4,
"selected": false,
"text": "<p><strong>The top answer is correct</strong>.</p>\n<p>But readers may be coming here searching answers about similarly named inner classes. They are present in popular libraries, such as <code>Django</code> and <code>WTForms</code>.</p>\n<p>As DavidW points out in the comments beneath this answer, <strong>these are <em>library-specific</em> features and are not to be confused with the advanced, unrelated <em>Python language</em> feature with a similar name</strong>.</p>\n<p>Rather, these are namespaces within classes' dicts. They are constructed using inner classes for sake of readability.</p>\n<p>In this example special field, <code>abstract</code> is visibly separate from fields of Author model.</p>\n<pre><code>from django.db import models\n\nclass Author(models.Model):\n name = models.CharField(max_length=50)\n email = models.EmailField()\n\n class Meta:\n abstract = True\n</code></pre>\n<p>Another example is from the documentation for <code>WTForms</code>:</p>\n<pre><code>from wtforms.form import Form\nfrom wtforms.csrf.session import SessionCSRF\nfrom wtforms.fields import StringField\n\nclass MyBaseForm(Form):\n class Meta:\n csrf = True\n csrf_class = SessionCSRF\n\n name = StringField("name")\n</code></pre>\n<p>This syntax does not get special treatment in the python programming language. <code>Meta</code> is not a keyword here, and does not trigger metaclass behavior. Rather, third-party library code in packages like <code>Django</code> and <code>WTForms</code> reads this property in the constructors of certain classes, and elsewhere.</p>\n<p>The presence of these declarations modifies the behavior of the classes that have these declarations. For example, <code>WTForms</code> reads <code>self.Meta.csrf</code> to determine if the form needs a <code>csrf</code> field.</p>\n"
},
{
"answer_id": 69426577,
"author": "Delta",
"author_id": 16608876,
"author_profile": "https://Stackoverflow.com/users/16608876",
"pm_score": 2,
"selected": false,
"text": "<p>look this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>Python 3.10.0rc2 (tags/v3.10.0rc2:839d789, Sep 7 2021, 18:51:45) [MSC v.1929 64 bit (AMD64)] on win32\nType "help", "copyright", "credits" or "license" for more information.\n>>> class Object:\n... pass\n... \n>>> class Meta(type):\n... test = 'Worked!!!'\n... def __repr__(self):\n... return 'This is "Meta" metaclass'\n... \n>>> class ObjectWithMetaClass(metaclass=Meta):\n... pass\n... \n>>> Object or type(Object())\n<class '__main__.Object'>\n>>> ObjectWithMetaClass or type(ObjectWithMetaClass())\nThis is "Meta" metaclass\n>>> Object.test\nAttributeError: ...\n>>> ObjectWithMetaClass.test\n'Worked!!!'\n>>> type(Object)\n<class 'type'>\n>>> type(ObjectWithMetaClass)\n<class '__main__.Meta'>\n>>> type(type(ObjectWithMetaClass))\n<class 'type'>\n>>> Object.__bases__\n(<class 'object'>,)\n>>> ObjectWithMetaClass.__bases__\n(<class 'object'>,)\n>>> type(ObjectWithMetaClass).__bases__\n(<class 'type'>,)\n>>> Object.__mro__\n(<class '__main__.Object'>, <class 'object'>)\n>>> ObjectWithMetaClass.__mro__\n(This is "Meta" metaclass, <class 'object'>)\n>>> \n</code></pre>\n<p>In other words, when an object was not created (type of object), we looking MetaClass.</p>\n"
},
{
"answer_id": 73205479,
"author": "Siva Sankar",
"author_id": 11282077,
"author_profile": "https://Stackoverflow.com/users/11282077",
"pm_score": -1,
"selected": false,
"text": "<p>Meta is a Greek word which means 'after' or 'beyond'.\nGenerally meta referring to self.\nMeta represents the additional information.\nMeta class is a helper class to explicitly tell about any additional information that has to be mentioned or any additional thing that has to be added about to the super or parent class.\nIn python, when you define a class, it automatically takes it as a type=metaclass and this class functionality (behavior-methods, properties-self information) is applicable to other child class when created.</p>\n<p>Here is a <a href=\"https://www.pythontutorial.net/python-oop/python-metaclass/\" rel=\"nofollow noreferrer\">detailed explanation</a> of what is a meta class and how it works, with coding examples.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
]
| What are metaclasses? What are they used for? | A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like [Jerub](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037) shows), the better approach is to make it an actual class itself. `type` is the usual metaclass in Python. `type` is itself a class, and it is its own type. You won't be able to recreate something like `type` purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass `type`.
A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal `__init__` and `__new__` methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.
When the `class` statement is executed, Python first executes the body of the `class` statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the `__metaclass__` attribute of the class-to-be (if any) or the `__metaclass__` global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.
However, metaclasses actually define the *type* of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. `type.__subclasses__()` is an example of a method on the `type` metaclass. You can also define the normal 'magic' methods, like `__add__`, `__iter__` and `__getattr__`, to implement or change how the class behaves.
Here's an aggregated example of the bits and pieces:
```
def make_hook(f):
"""Decorator to turn 'foo' method into '__foo__'"""
f.is_hook = 1
return f
class MyType(type):
def __new__(mcls, name, bases, attrs):
if name.startswith('None'):
return None
# Go over attributes and see if they should be renamed.
newattrs = {}
for attrname, attrvalue in attrs.iteritems():
if getattr(attrvalue, 'is_hook', 0):
newattrs['__%s__' % attrname] = attrvalue
else:
newattrs[attrname] = attrvalue
return super(MyType, mcls).__new__(mcls, name, bases, newattrs)
def __init__(self, name, bases, attrs):
super(MyType, self).__init__(name, bases, attrs)
# classregistry.register(self, self.interfaces)
print "Would register class %s now." % self
def __add__(self, other):
class AutoClass(self, other):
pass
return AutoClass
# Alternatively, to autogenerate the classname as well as the class:
# return type(self.__name__ + other.__name__, (self, other), {})
def unregister(self):
# classregistry.unregister(self)
print "Would unregister class %s now." % self
class MyObject:
__metaclass__ = MyType
class NoneSample(MyObject):
pass
# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)
class Example(MyObject):
def __init__(self, value):
self.value = value
@make_hook
def add(self, other):
return self.__class__(self.value + other.value)
# Will unregister the class
Example.unregister()
inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()
print inst + inst
class Sibling(MyObject):
pass
ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__
``` |
100,007 | <p>When logging with Log4Net it's very easy to put class that called the log into the log file. I've found in the past that this makes it very easy to trace through the code and see the flow through the classes. In Log4Net I use the %logger property in the conversion pattern like so: </p>
<pre><code><conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</code></pre>
<p>And this gives me the output I want: </p>
<p><code>2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method</code></p>
<p>You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.</p>
<p>In the Logging Applicaton Block I cannot figure out how to do this with a simple log call. Does anyone know how it can be done? If so, an example or steps to do so would be very helpful.</p>
| [
{
"answer_id": 100075,
"author": "Tom Carr",
"author_id": 14954,
"author_profile": "https://Stackoverflow.com/users/14954",
"pm_score": 1,
"selected": false,
"text": "<p>We havn't found an easy way without hitting the StackTrace. If it's an exception, we just grab from that:</p>\n\n<pre><code> StackTrace trace = new StackTrace(ex, true);\n StackFrame frame = trace.GetFrame(0);\n</code></pre>\n\n<p>For chatty items, we just write the string. We have a snippet that's able to grab the class name on insertion. We also declare the const string with the class name.</p>\n\n<p>Not pretty, but it's the best we've found. I hope someone else has a bettwe answer in this thread :)</p>\n"
},
{
"answer_id": 100961,
"author": "lotsoffreetime",
"author_id": 18248,
"author_profile": "https://Stackoverflow.com/users/18248",
"pm_score": 4,
"selected": true,
"text": "<p>Add the calling method to the LogEntry's ExtendedProperties dictionary; assuming you haven't removed the ExtendedProperties tokens from the formatter template, of course.</p>\n\n<p>Put something like this in a logging wrapper: </p>\n\n<pre><code>public void LogSomething(string msg)\n{\n LogEntry le = new LogEntry { Message = msg };\n le.ExtendedProperties.Add(\"Called from\", new StackFrame(1).GetMethod().ReflectedType);\n Logger.Write(le);\n}\n</code></pre>\n\n<p>Calling this produces something like this at the end of the log:</p>\n\n<pre><code>Extended Properties: Called from - LAB_Demo.Tester\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11908/"
]
| When logging with Log4Net it's very easy to put class that called the log into the log file. I've found in the past that this makes it very easy to trace through the code and see the flow through the classes. In Log4Net I use the %logger property in the conversion pattern like so:
```
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
```
And this gives me the output I want:
`2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method`
You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.
In the Logging Applicaton Block I cannot figure out how to do this with a simple log call. Does anyone know how it can be done? If so, an example or steps to do so would be very helpful. | Add the calling method to the LogEntry's ExtendedProperties dictionary; assuming you haven't removed the ExtendedProperties tokens from the formatter template, of course.
Put something like this in a logging wrapper:
```
public void LogSomething(string msg)
{
LogEntry le = new LogEntry { Message = msg };
le.ExtendedProperties.Add("Called from", new StackFrame(1).GetMethod().ReflectedType);
Logger.Write(le);
}
```
Calling this produces something like this at the end of the log:
```
Extended Properties: Called from - LAB_Demo.Tester
``` |
100,045 | <p>What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have <code>\/:*?"<>|</code> characters).</p>
<p>I'd like to use it like the following:</p>
<pre><code>// Return true if string is invalid.
if (Regex.IsMatch(szFileName, "<your regex string>"))
{
// Tell user to reformat their filename.
}
</code></pre>
| [
{
"answer_id": 100057,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "<p>Why not using the System.IO.FileInfo class, together with the DirectoryInfo class you have a set of usefull methods. </p>\n"
},
{
"answer_id": 100066,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 7,
"selected": true,
"text": "<p>As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions:</p>\n\n<pre><code>if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)\n{\n MessageBox.Show(\"The filename is invalid\");\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 100198,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 3,
"selected": false,
"text": "<p>This isn't as simple as just checking whether the file name contains any of <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx\" rel=\"noreferrer\">System.IO.Path.GetInvalidFileNameChars</a> (as mentioned in a couple of other answers already).</p>\n\n<p>For example what if somebody enters a name that contains no invalid chars but is 300 characters long (i.e. greater than MAX_PATH) - this won't work with any of the .NET file APIs, and only has limited support in the rest of windows using the \\?\\ path syntax. You need context as to how long the rest of the path is to determine how long the file name can be. You can find <a href=\"http://blogs.msdn.com/brian_dewey/archive/2004/01/19/60263.aspx\" rel=\"noreferrer\">more information about this type of thing here</a>.</p>\n\n<p>Ultimately all your checks can <em>reliably</em> do is prove that a file name is not valid, or give you a reasonable estimate as to whether it is valid. It's virtually impossible to prove that the file name is valid without actually trying to use it. (And even then you have issues like what if it already exists? It may be a valid file name, but is it valid in your scenario to have a duplicate name?)</p>\n"
},
{
"answer_id": 356289,
"author": "Viacheslav Ivanov",
"author_id": 45003,
"author_profile": "https://Stackoverflow.com/users/45003",
"pm_score": 0,
"selected": false,
"text": "<p>Path.GetInvalidFileNameChars - Is not a good way. Try this:</p>\n\n<pre><code>if(@\"C:\\A.txt\".IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)\n{\n MessageBox.Show(\"The filename is invalid\");\n return;\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13115/"
]
| What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have `\/:*?"<>|` characters).
I'd like to use it like the following:
```
// Return true if string is invalid.
if (Regex.IsMatch(szFileName, "<your regex string>"))
{
// Tell user to reformat their filename.
}
``` | As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions:
```
if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
MessageBox.Show("The filename is invalid");
return;
}
``` |
100,048 | <p>I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.</p>
<p>The elements can occur multiple times in both lists and they are originally unsorted.</p>
<p>My function looks like this:</p>
<pre><code>(defun merge-lists (list-a list-b sort-fn)
"Merges two lists of (x, y) coordinates sorting them and removing dupes"
(let ((prev nil))
(remove-if
(lambda (point)
(let ((ret-val (equal point prev)))
(setf prev point)
ret-val))
(sort
(merge 'list list-a list-b sort-fn) ;'
sort-fn))))
</code></pre>
<p>Is there a better way to achieve the same?</p>
<p>Sample call:</p>
<pre><code>[CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>)
==> (9 8 7 6 4 3 2 1)
</code></pre>
| [
{
"answer_id": 100077,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "<p>I think I would first sort the two lists separately and then merge them with a function that also skips over duplicates. This should be a bit faster as it requires one less traversal of both lists.</p>\n\n<p>P.S.: I doubt it can be done much faster as you basically always need at least one sort and one merge. Perhaps you can combine both in one function, but I wouldn't be surprised if that doesn't make a (big) difference.</p>\n"
},
{
"answer_id": 100086,
"author": "RKitson",
"author_id": 16947,
"author_profile": "https://Stackoverflow.com/users/16947",
"pm_score": -1,
"selected": false,
"text": "<p>Sounds like you need to be using Sets.</p>\n"
},
{
"answer_id": 100109,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 5,
"selected": true,
"text": "<p>Our neighbourhood friendly Lisp guru pointed out the <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_dup.htm\" rel=\"nofollow noreferrer\">remove-duplicates function</a>.</p>\n\n<p>He also provided the following snippet:</p>\n\n<pre><code>(defun merge-lists (list-a list-b sort-fn test-fn)\n (sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))\n</code></pre>\n"
},
{
"answer_id": 100125,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 1,
"selected": false,
"text": "<p>If the lists are sorted before you merge them, they can be merged, duplicate-removed and sorted at the same time. If they are sorted AND duplicate-free, then the merge/sort/duplicate-remove function becomes really trivial.</p>\n\n<p>In fact, it might be better to change your insert function so that it performs a sorted insertion that checks for duplicates. Then you always have sorted lists that are free of duplicates, and merging them is a trivial matter.</p>\n\n<p>Then again, you might prefer to have a fast insert function at the cost of sorting/removing duplicates later on.</p>\n"
},
{
"answer_id": 101034,
"author": "jdkoftinoff",
"author_id": 32198,
"author_profile": "https://Stackoverflow.com/users/32198",
"pm_score": 0,
"selected": false,
"text": "<p>Wouldn't the remove-duplicates function operate better if the sort was applied before the remove-duplicates?</p>\n"
},
{
"answer_id": 268436,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 0,
"selected": false,
"text": "<p>As Antti pointed out, you probably want to leverage REMOVE-DUPLICATES and SORT, though I'd probably use a keyword (or optional argument) for the test function:\n(defun merge-lists (list-1 list-2 sort-fn &key (test #'eql))\n ...)\nor\n(defun merge-lists (list-1 list-2 sort-fn &optional (test #'eql)\n ...)</p>\n\n<p>This way, you won't have to specify the test function (used by REMOVE-DUPLICATES to test for \"is these considered duplicates\"), unless EQL is not good enough.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7780/"
]
| I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.
The elements can occur multiple times in both lists and they are originally unsorted.
My function looks like this:
```
(defun merge-lists (list-a list-b sort-fn)
"Merges two lists of (x, y) coordinates sorting them and removing dupes"
(let ((prev nil))
(remove-if
(lambda (point)
(let ((ret-val (equal point prev)))
(setf prev point)
ret-val))
(sort
(merge 'list list-a list-b sort-fn) ;'
sort-fn))))
```
Is there a better way to achieve the same?
Sample call:
```
[CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>)
==> (9 8 7 6 4 3 2 1)
``` | Our neighbourhood friendly Lisp guru pointed out the [remove-duplicates function](http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_dup.htm).
He also provided the following snippet:
```
(defun merge-lists (list-a list-b sort-fn test-fn)
(sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))
``` |
100,053 | <p>I posted a <a href="https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages">question</a> about using Messages versus Fault Exceptions to communicate business rules between services.</p>
<p>I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.</p>
<p>But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.</p>
<p>Now within my service, if i use</p>
<pre><code>throw new FaultException
</code></pre>
<p>to communicate a simple business rule like "Your account has not been activated",
What overhead does this now carry?
Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.</p>
<p>So in my user example, which is the optimal/preferred way to write my service method</p>
<p>option a</p>
<pre><code>public void AuthenticateUser()
{
throw new FaultException("Your account has not been activated");
}
</code></pre>
<p>option b</p>
<pre><code>public AutheticateDto AutheticateUser()
{
return new AutheticateDto() {
Success = false,
Message = "Your account has not been activated"};
}
</code></pre>
| [
{
"answer_id": 100088,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 0,
"selected": false,
"text": "<p>It's just like a normal exception, and uses the same wrapping code as a normal exception would to marshal into a fault, including unwinding the stack.</p>\n\n<p>Like exceptions SOAP faults shouldn't, to my mind, be used for program flow, but to indicate errors.</p>\n"
},
{
"answer_id": 100111,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 2,
"selected": false,
"text": "<p>Well... In general you shouldn't be throwing exceptions for expected conditions, or anything you <em>expect</em> to happen regularly. They are massively slower than doing normal methods. E.g., if you expect a file open to fail, don't throw a that exception up to your caller, pass the back a failure code, or provide a \"CanOpenFile\" method to do the test.</p>\n\n<p>True, the message text itself isn't much, but a real exception is thrown and handled (possibly more expensively because of IIS), and then real exception is again thrown on the client when the fault is deserialized. So, double hit.</p>\n\n<p>Honestly, if it is a low volume of calls, then you probably won't take any noticeable hit, but is not a good idea anyway. Who wants to put business logic in a catch block :)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms229009.aspx\" rel=\"nofollow noreferrer\">Microsoft : Exceptions And Performance, & Alternatives</a></p>\n\n<p><a href=\"http://www.developerfusion.co.uk/show/5250/\" rel=\"nofollow noreferrer\">Developer Fusion: Performance, with example</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15360/"
]
| I posted a [question](https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages) about using Messages versus Fault Exceptions to communicate business rules between services.
I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.
But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.
Now within my service, if i use
```
throw new FaultException
```
to communicate a simple business rule like "Your account has not been activated",
What overhead does this now carry?
Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.
So in my user example, which is the optimal/preferred way to write my service method
option a
```
public void AuthenticateUser()
{
throw new FaultException("Your account has not been activated");
}
```
option b
```
public AutheticateDto AutheticateUser()
{
return new AutheticateDto() {
Success = false,
Message = "Your account has not been activated"};
}
``` | Well... In general you shouldn't be throwing exceptions for expected conditions, or anything you *expect* to happen regularly. They are massively slower than doing normal methods. E.g., if you expect a file open to fail, don't throw a that exception up to your caller, pass the back a failure code, or provide a "CanOpenFile" method to do the test.
True, the message text itself isn't much, but a real exception is thrown and handled (possibly more expensively because of IIS), and then real exception is again thrown on the client when the fault is deserialized. So, double hit.
Honestly, if it is a low volume of calls, then you probably won't take any noticeable hit, but is not a good idea anyway. Who wants to put business logic in a catch block :)
[Microsoft : Exceptions And Performance, & Alternatives](http://msdn.microsoft.com/en-us/library/ms229009.aspx)
[Developer Fusion: Performance, with example](http://www.developerfusion.co.uk/show/5250/) |
100,068 | <p>I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills. </p>
<p>Here's what I've got, but it seems like there should be an easier way.</p>
<pre><code>public static TEntity InsertIfNotExists<TEntity>
(
DataContext db,
Table<TEntity> table,
Func<TEntity,bool> where,
TEntity record
)
where TEntity : class
{
TEntity existing = table.SingleOrDefault<TEntity>(where);
if (existing != null)
{
return existing;
}
else
{
table.InsertOnSubmit(record);
// Can't use table.Context.SubmitChanges()
// 'cause it's read-only
db.SubmitChanges();
}
return record;
}
</code></pre>
| [
{
"answer_id": 100496,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<pre><code>public static void InsertIfNotExists<TEntity>\n (this Table<TEntity> table,\n TEntity entity,\n Expression<Func<TEntity,bool>> predicate)\n where TEntity : class\n{ \n if (!table.Any(predicate)) \n {\n table.InsertOnSubmit(record);\n table.Context.SubmitChanges();\n }\n }\n\n\ntable.InsertIfNotExists(entity, e=>e.BooleanProperty);\n</code></pre>\n"
},
{
"answer_id": 100635,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": false,
"text": "<p>Agree with <a href=\"https://stackoverflow.com/questions/100068/linq-to-sql-insert-if-non-existent#100496\">marxidad's answer</a>, but see note 1.</p>\n\n<p>Note 1: IMHO, it is not wise to call <code>db.SubmitChanges()</code> in a helper method, because you may break the context transaction. This means that if you call the <code>InsertIfNotExists<TEntity></code> in the middle of a complex update of several entities you are saving the changes not at once but in steps. </p>\n\n<p>Note 2: The <code>InsertIfNotExists<TEntity></code> method is a very generic method that works for any scenario. If you want to just discriminate the entities that have loaded from the database from the entities that have been created from the code, you can utilize the partial method <code>OnLoaded</code> of the Entity class like this:</p>\n\n<pre><code>public partial class MyEntity\n{\n public bool IsLoaded { get; private set; }\n partial void OnLoaded()\n {\n IsLoaded = true;\n }\n}\n</code></pre>\n\n<p>Given that (and note 1), then InsertIfNotExists functionality is reduced to the following:</p>\n\n<pre><code>if (!record.IsLoaded)\n db.InsertOnSubmit(record);\n</code></pre>\n"
},
{
"answer_id": 2108466,
"author": "Jamal",
"author_id": 143582,
"author_profile": "https://Stackoverflow.com/users/143582",
"pm_score": 2,
"selected": false,
"text": "<p>Small modification for Mark's answer:</p>\n\n<p>If you only care about checking if the entity exists by its primary key, Marke's answer can be used like this:</p>\n\n<pre><code>public static void InsertIfNotExists<TEntity>\n (this Table<TEntity> table\n , TEntity entity\n ) where TEntity : class\n {\n if (!table.Contains(entity))\n {\n table.InsertOnSubmit(entity);\n\n }\n }\n</code></pre>\n"
},
{
"answer_id": 4799362,
"author": "Michael Kropat",
"author_id": 27581,
"author_profile": "https://Stackoverflow.com/users/27581",
"pm_score": 4,
"selected": false,
"text": "<p>As others have pointed out, the <code>if (!Any()) { InsertOnSubmit(); }</code> solutions all have a race condition. If you go that route, when you call <code>SubmitChanges</code>, you have to take into account that either a) a <code>SqlException</code> could be raised for a duplicate insert, or b) you could have duplicate records in the table.</p>\n\n<p>Fortunately, we can use the database to avoid the race condition by enforcing uniqueness. The following code assumes that there is a primary key or unique constraint on the table to prevent the insertion of duplicate records.</p>\n\n<pre><code>using (var db = new DataContext()) {\n\n // Add the new (possibly duplicate) record to the data context here.\n\n try {\n db.SubmitChanges();\n } catch (SqlException ex) {\n const int violationOfPrimaryKeyContraint = 2627;\n const int violationOfUniqueConstraint = 2601;\n var duplicateRecordExceptionNumbers = new [] {\n violationOfPrimaryKeyContraint, violationOfUniqueConstraint\n };\n if (!duplicateRecordExceptionNumbers.Contains(ex.Number)) {\n throw;\n }\n }\n}\n</code></pre>\n\n<p>Now... things get a fair bit more complicated if you have to perform the insert in a batch transaction with other database updates.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
]
| I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills.
Here's what I've got, but it seems like there should be an easier way.
```
public static TEntity InsertIfNotExists<TEntity>
(
DataContext db,
Table<TEntity> table,
Func<TEntity,bool> where,
TEntity record
)
where TEntity : class
{
TEntity existing = table.SingleOrDefault<TEntity>(where);
if (existing != null)
{
return existing;
}
else
{
table.InsertOnSubmit(record);
// Can't use table.Context.SubmitChanges()
// 'cause it's read-only
db.SubmitChanges();
}
return record;
}
``` | ```
public static void InsertIfNotExists<TEntity>
(this Table<TEntity> table,
TEntity entity,
Expression<Func<TEntity,bool>> predicate)
where TEntity : class
{
if (!table.Any(predicate))
{
table.InsertOnSubmit(record);
table.Context.SubmitChanges();
}
}
table.InsertIfNotExists(entity, e=>e.BooleanProperty);
``` |
100,081 | <p>I have the following C# singleton pattern, is there any way of improving it? </p>
<pre><code> public class Singleton<T> where T : class, new()
{
private static object _syncobj = new object();
private static volatile T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncobj)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public Singleton()
{ }
}
</code></pre>
<p>Preferred usage example: </p>
<pre><code>class Foo : Singleton<Foo>
{
}
</code></pre>
<p><strong>Related</strong>: </p>
<p><a href="https://stackoverflow.com/questions/953259/an-obvious-singleton-implementation-for-net">An obvious singleton implementation for .NET?</a></p>
| [
{
"answer_id": 100093,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 3,
"selected": false,
"text": "<p>Courtesy of Judith Bishop, <a href=\"http://patterns.cs.up.ac.za/\" rel=\"noreferrer\">http://patterns.cs.up.ac.za/</a></p>\n\n<p>This singleton pattern implementation ensures lazy initialisation.</p>\n\n<pre><code>// Singleton PatternJudith Bishop Nov 2007\n// Generic version\n\npublic class Singleton<T> where T : class, new()\n{\n Singleton() { }\n\n class SingletonCreator\n {\n static SingletonCreator() { }\n // Private object instantiated with private constructor\n internal static readonly T instance = new T();\n }\n\n public static T UniqueInstance\n {\n get { return SingletonCreator.instance; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100098,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public sealed class Singleton\n{\n private static readonly Singleton instance = new Singleton();\n\n private Singleton(){}\n\n public static Singleton Instance\n {\n get \n {\n return instance; \n }\n }\n}\n</code></pre>\n\n<p>There's <a href=\"http://msdn.microsoft.com/en-us/library/ms998558.aspx\" rel=\"nofollow noreferrer\">no ambiguity in .NET around initialization order</a>; but this raises threading issues.</p>\n"
},
{
"answer_id": 100116,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 4,
"selected": false,
"text": "<p>According to Jon Skeet in <a href=\"https://csharpindepth.com/articles/Singleton\" rel=\"nofollow noreferrer\">Implementing the Singleton Pattern in C#</a> the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.</p>\n\n<p>Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton.</p>\n"
},
{
"answer_id": 100127,
"author": "Wyzfen",
"author_id": 15261,
"author_profile": "https://Stackoverflow.com/users/15261",
"pm_score": 0,
"selected": false,
"text": "<p>I quite liked your original answer - the only thing missing (according to the link posted by blowdart) is to make the _instance variable volatile, to make sure it has actually been set in the lock.\nI actually use blowdarts solution when I have to use a singleton, but I dont have any need to late-instantiate etc.</p>\n"
},
{
"answer_id": 100149,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": -1,
"selected": false,
"text": "<p>You don't need all that, C# already has a good singleton pattern built-in.</p>\n\n<pre><code>static class Foo\n</code></pre>\n\n<p>If you need anything more interesting than that, chances are your new singleton is going to be just different enough that your generic pattern is going to be useless.</p>\n\n<p>EDIT: By \"anything more interesting\" I'm including inheritance. If you can inherit from a singleton, it isn't a singleton any more.</p>\n"
},
{
"answer_id": 100159,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 3,
"selected": false,
"text": "<p>This code won't compile, you need \"class\" constraint on T. </p>\n\n<p>Also, this code requires public constructor on target class, which is not good for singleton, because you can't control at compile time that you obtain (single) instance only via Instance property (or field). If you don't have any other static members except Instance, you are ok to go with just this:</p>\n\n<pre><code>class Foo\n{\n public static readonly Instance = new Foo();\n private Foo() {}\n static Foo() {}\n}\n</code></pre>\n\n<p>It is thread safe (guaranteed by CLR) and lazy (instance is created with first access to type). For more discussion about BeforeFieldInit and why we need static constructor here, see <a href=\"https://csharpindepth.com/articles/BeforeFieldInit\" rel=\"nofollow noreferrer\">https://csharpindepth.com/articles/BeforeFieldInit</a>.</p>\n\n<p>If you want to have other public static members on type, but create object only on access to Instance, you may create nested type, like in <a href=\"https://csharpindepth.com/articles/Singleton\" rel=\"nofollow noreferrer\">https://csharpindepth.com/articles/Singleton</a></p>\n"
},
{
"answer_id": 292211,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think that you really want to \"burn your base class\" so that you can save 2 lines of code. You don't really need a base class to implement singleton.</p>\n\n<p>Whenever you need a singleton, just do this:</p>\n\n<pre><code>class MyConcreteClass\n{\n #region Singleton Implementation\n\n public static readonly Instance = new MyConcreteClass();\n\n private MyConcreteClass(){}\n\n #endregion\n\n /// ...\n}\n</code></pre>\n"
},
{
"answer_id": 359638,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 2,
"selected": false,
"text": "<p>More details on this answer on a different thread : <a href=\"https://stackoverflow.com/questions/246710/how-to-implement-a-singleton-in-c\">How to implement a singleton in C#?</a></p>\n\n<p>However the thread doesn't use <strong><em>generic</em></strong>.</p>\n"
},
{
"answer_id": 869526,
"author": "dr. evil",
"author_id": 40322,
"author_profile": "https://Stackoverflow.com/users/40322",
"pm_score": 1,
"selected": false,
"text": "<p>I was looking for a better Singleton pattern and liked this one. So ported it to VB.NET, can be useful for others:</p>\n\n<pre><code>Public MustInherit Class Singleton(Of T As {Class, New})\n Public Sub New()\n End Sub\n\n Private Class SingletonCreator\n Shared Sub New()\n End Sub\n Friend Shared ReadOnly Instance As New T\n End Class\n\n Public Shared ReadOnly Property Instance() As T\n Get\n Return SingletonCreator.Instance\n End Get\n End Property\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 929408,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>My contribution for ensuring on demand creation of instance data:</p>\n\n<pre><code>\n/// <summary>Abstract base class for thread-safe singleton objects</summary>\n/// <typeparam name=\"T\">Instance type</typeparam>\npublic abstract class SingletonOnDemand<T> {\n private static object __SYNC = new object();\n private static volatile bool _IsInstanceCreated = false;\n private static T _Instance = default(T);\n<br/>\n /// <summary>Instance data</summary>\n public static T Instance {\n get {\n if (!_IsInstanceCreated)\n lock (__SYNC)\n if (!_IsInstanceCreated)\n _Instance = Activator.CreateInstance<T>();\n return _Instance;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 929441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>pff... again... :)<br/>\nMy contribution for ensuring on demand creation of instance data:</p>\n\n<pre><code>\n/// <summary>Abstract base class for thread-safe singleton objects</summary>\n/// <typeparam name=\"T\">Instance type</typeparam>\npublic abstract class SingletonOnDemand<T> {\n private static object __SYNC = new object();\n private static volatile bool _IsInstanceCreated = false;\n private static T _Instance = default(T);\n\n /// <summary>Instance data</summary>\n public static T Instance {\n get {\n if (!_IsInstanceCreated)\n lock (__SYNC)\n if (!_IsInstanceCreated) {\n _Instance = Activator.CreateInstance<T>();\n _IsInstanceCreated = true;\n }\n return _Instance;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1010662,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>As requested, cross posting from my original answer to another question.</p>\n\n<p>My version uses Reflection, works with non-public constructors in the derived class, is threadsafe (obviously) with lazy instantiation (according to the article I found linked below):</p>\n\n<pre><code>public class SingletonBase<T> where T : class\n{\n static SingletonBase()\n {\n }\n\n public static readonly T Instance = \n typeof(T).InvokeMember(typeof(T).Name, \n BindingFlags.CreateInstance | \n BindingFlags.Instance |\n BindingFlags.Public |\n BindingFlags.NonPublic, \n null, null, null) as T;\n}\n</code></pre>\n\n<p>I picked this up a few years ago, not sure how much is mine, but googling on the code might find the original source of the technique if it wasn't me.</p>\n\n<p>This is the <a href=\"http://www.360doc.com/content/070103/00/16729_316696.html\" rel=\"nofollow noreferrer\">oldest source of the code that I can find</a> that was not me posting it.</p>\n"
},
{
"answer_id": 1323320,
"author": "haze4real",
"author_id": 132225,
"author_profile": "https://Stackoverflow.com/users/132225",
"pm_score": 2,
"selected": false,
"text": "<p>:/ The generic \"singleton\" pattern by Judith Bishop seems kinda flawed, its always possible to create several instances of type T as the constructor must be public to use it in this \"pattern\". In my opinion it has absolutely nothing to do with singleton, its just a kind of factory, which always returns the same object, but doesn't make it singleton... as long as there can be more than one instance of a class it can't be a singleton. Any reason this pattern is top-rated?</p>\n\n<pre><code>public sealed class Singleton\n{\n private static readonly Singleton _instance = new Singleton();\n\n private Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n return _instance;\n }\n }\n}\n</code></pre>\n\n<p>Static initializers are considered thread-safe.. I don't know but you shouldn't use idioms of singleton at all, if you wrap my code above its not more than 3 lines... and inheriting from a singleton doesn't make any sense either.</p>\n"
},
{
"answer_id": 1473953,
"author": "uvw",
"author_id": 146204,
"author_profile": "https://Stackoverflow.com/users/146204",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static class LazyGlobal<T> where T : new()\n{\n public static T Instance\n {\n get { return TType.Instance; }\n }\n\n private static class TType\n {\n public static readonly T Instance = new T();\n }\n}\n\n// user code:\n{\n LazyGlobal<Foo>.Instance.Bar();\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>public delegate T Func<T>();\n\npublic static class CustomGlobalActivator<T>\n{\n public static Func<T> CreateInstance { get; set; }\n}\n\npublic static class LazyGlobal<T>\n{\n public static T Instance\n {\n get { return TType.Instance; }\n }\n\n private static class TType\n {\n public static readonly T Instance = CustomGlobalActivator<T>.CreateInstance();\n }\n}\n\n{\n // setup code:\n // CustomGlobalActivator<Foo>.CreateInstance = () => new Foo(instanceOf_SL_or_IoC.DoSomeMagicReturning<FooDependencies>());\n CustomGlobalActivator<Foo>.CreateInstance = () => instanceOf_SL_or_IoC.PleaseResolve<Foo>();\n // ...\n // user code:\n LazyGlobal<Foo>.Instance.Bar();\n}\n</code></pre>\n"
},
{
"answer_id": 1474006,
"author": "JDunkerley",
"author_id": 79965,
"author_profile": "https://Stackoverflow.com/users/79965",
"pm_score": 0,
"selected": false,
"text": "<p>Saw one a while ago which uses reflection to access a private (or public) default constructor:</p>\n\n<pre><code>public static class Singleton<T>\n{\n private static object lockVar = new object();\n private static bool made;\n private static T _singleton = default(T);\n\n /// <summary>\n /// Get The Singleton\n /// </summary>\n public static T Get\n {\n get\n {\n if (!made)\n {\n lock (lockVar)\n {\n if (!made)\n {\n ConstructorInfo cInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);\n if (cInfo != null)\n _singleton = (T)cInfo.Invoke(new object[0]);\n else\n throw new ArgumentException(\"Type Does Not Have A Default Constructor.\");\n made = true;\n }\n }\n }\n\n return _singleton;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1591097,
"author": "w0land",
"author_id": 234186,
"author_profile": "https://Stackoverflow.com/users/234186",
"pm_score": 1,
"selected": false,
"text": "<p>Try this generic Singleton class implementing the Singleton design pattern in a thread safe and lazy way (thx to wcell).</p>\n\n<pre><code>public abstract class Singleton<T> where T : class\n{\n /// <summary>\n /// Returns the singleton instance.\n /// </summary>\n public static T Instance\n {\n get\n {\n return SingletonAllocator.instance;\n }\n }\n\n internal static class SingletonAllocator\n {\n internal static T instance;\n\n static SingletonAllocator()\n {\n CreateInstance(typeof(T));\n }\n\n public static T CreateInstance(Type type)\n {\n ConstructorInfo[] ctorsPublic = type.GetConstructors(\n BindingFlags.Instance | BindingFlags.Public);\n\n if (ctorsPublic.Length > 0)\n throw new Exception(\n type.FullName + \" has one or more public constructors so the property cannot be enforced.\");\n\n ConstructorInfo ctorNonPublic = type.GetConstructor(\n BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]);\n\n if (ctorNonPublic == null)\n {\n throw new Exception(\n type.FullName + \" doesn't have a private/protected constructor so the property cannot be enforced.\");\n }\n\n try\n {\n return instance = (T)ctorNonPublic.Invoke(new object[0]);\n }\n catch (Exception e)\n {\n throw new Exception(\n \"The Singleton couldnt be constructed, check if \" + type.FullName + \" has a default constructor\", e);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6756793,
"author": "Rick",
"author_id": 767923,
"author_profile": "https://Stackoverflow.com/users/767923",
"pm_score": 1,
"selected": false,
"text": "<p>The Double-Check Locking [Lea99] idiom provided by Microsoft <a href=\"http://msdn.microsoft.com/en-us/library/ff650316.aspx\" rel=\"nofollow\">here</a> is amazingly similar to your provided code, unfortunately, this fails the ECMA CLI standard for a puritan view of thread-safe code and may not work correctly in all situations.</p>\n\n<p>In a multi-threaded program, different threads could try to instantiate a class simultaneously. For this reason, a Singleton implementation that relies on an if statement to check whether the instance is null <strong>will not be thread-safe</strong>. Don't write code like that!</p>\n\n<p>A simple, yet effective means of creating a thread-safe singleton is to use a nested class to instantiate it. The following is an example of a lazy instantiation singleton:</p>\n\n<pre><code>public sealed class Singleton\n{ \n private Singleton() { }\n\n public static Singleton Instance\n {\n get\n {\n return SingletonCreator.instance;\n }\n }\n\n private class SingletonCreator\n {\n static SingletonCreator() { }\n internal static readonly Singleton instance = new Singleton();\n }\n}\n</code></pre>\n\n<p><em>Usage:</em></p>\n\n<pre><code>Singleton s1 = Singleton.Instance;\nSingleton s2 = Singleton.Instance;\nif (s1.Equals(s2))\n{\n Console.WriteLine(\"Thread-Safe Singleton objects are the same\");\n}\n</code></pre>\n\n<p><strong>Generic Solution:</strong></p>\n\n<pre><code>public class Singleton<T>\n where T : class, new()\n{\n private Singleton() { }\n\n public static T Instance \n { \n get \n { \n return SingletonCreator.instance; \n } \n } \n\n private class SingletonCreator \n {\n static SingletonCreator() { }\n\n internal static readonly T instance = new T();\n }\n}\n</code></pre>\n\n<p><em>Usage:</em></p>\n\n<pre><code>class TestClass { }\n\nSingleton s1 = Singleton<TestClass>.Instance;\nSingleton s2 = Singleton<TestClass>.Instance;\nif (s1.Equals(s2))\n{\n Console.WriteLine(\"Thread-Safe Generic Singleton objects are the same\");\n}\n</code></pre>\n\n<p>Lastly, here is a somewhat releated and usefull suggestion - to help avoid deadlocks that can be caused by using the lock keyword, consider adding the following attribute to help protect code in only public static methods:</p>\n\n<pre><code>using System.Runtime.CompilerServices;\n[MethodImpl (MethodImplOptions.Synchronized)]\npublic static void MySynchronizedMethod()\n{\n}\n</code></pre>\n\n<p><em>References:</em></p>\n\n<ol>\n<li>C# Cookbook (O'Reilly), Jay Hilyard & Stephen Teilhet</li>\n<li>C# 3.0 Design Patterns (O'Reilly), Judith Bishop</li>\n<li><a href=\"http://en.csharp-online.net/Singleton_design_pattern%3A_Thread-safe_Singleton\" rel=\"nofollow\">CSharp-Online.Net</a> - Singleton design pattern: Thread-safe Singleton</li>\n</ol>\n"
},
{
"answer_id": 7703835,
"author": "101010",
"author_id": 451007,
"author_profile": "https://Stackoverflow.com/users/451007",
"pm_score": 0,
"selected": false,
"text": "<p>I submit this to the group. It seems to be thread-safe, generic and follows the pattern. You can inherit from it. This is cobbled together from what others have said.</p>\n\n<pre><code>public class Singleton<T> where T : class\n{\n class SingletonCreator\n {\n static SingletonCreator() { }\n\n internal static readonly T Instance =\n typeof(T).InvokeMember(typeof(T).Name,\n BindingFlags.CreateInstance |\n BindingFlags.Instance |\n BindingFlags.Public |\n BindingFlags.NonPublic,\n null, null, null) as T;\n }\n\n public static T Instance\n {\n get { return SingletonCreator.Instance; }\n }\n}\n</code></pre>\n\n<p>Intended implementation:</p>\n\n<pre><code>public class Foo: Singleton<Foo>\n{\n private Foo() { }\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>Foo.Instance.SomeMethod();\n</code></pre>\n"
},
{
"answer_id": 7891899,
"author": "Alexandr",
"author_id": 670082,
"author_profile": "https://Stackoverflow.com/users/670082",
"pm_score": 3,
"selected": false,
"text": "<p>This is my point using .NET 4</p>\n\n<pre><code>public class Singleton<T> where T : class, new()\n {\n Singleton (){}\n\n private static readonly Lazy<T> instance = new Lazy<T>(()=> new T());\n\n public static T Instance { get { return instance.Value; } } \n }\n</code></pre>\n"
},
{
"answer_id": 14446722,
"author": "Saw",
"author_id": 452748,
"author_profile": "https://Stackoverflow.com/users/452748",
"pm_score": 0,
"selected": false,
"text": "<p>As in <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">wikipedia</a>:</p>\n\n<blockquote>\n <p>the singleton pattern is a design pattern that <strong>restricts the\n instantiation of a class</strong> to one object</p>\n</blockquote>\n\n<p>I beleave that there is no guaranteed way to do it using generics, if you have restricted the instantiation of the singleton itself, how to restrict the instantiation of the main class, I think it is not possible to do that, and implementing this simple pattern is not that hard, take this way using the static constructor and private set:</p>\n\n<pre><code>public class MyClass\n{\n private MyClass()\n {\n\n }\n\n static MyClass()\n {\n Instance = new MyClass();\n }\n\n public static MyClass Instance { get; private set; }\n}\n</code></pre>\n\n<p>OR:</p>\n\n<pre><code>public class MyClass\n {\n private MyClass()\n {\n\n }\n\n static MyClass()\n {\n Instance = new MyClass();\n }\n\n private static MyClass instance;\n\n\n\n public static MyClass Instance\n {\n get\n {\n return instance;\n }\n private set\n {\n instance = value;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 46208920,
"author": "MaurGi",
"author_id": 3443489,
"author_profile": "https://Stackoverflow.com/users/3443489",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me:</p>\n\n<pre><code>public static class Singleton<T> \n{\n private static readonly object Sync = new object();\n\n public static T GetSingleton(ref T singletonMember, Func<T> initializer)\n {\n if (singletonMember == null)\n {\n lock (Sync)\n {\n if (singletonMember == null)\n singletonMember = initializer();\n }\n }\n return singletonMember;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>private static MyType _current;\npublic static MyType Current = Singleton<MyType>.GetSingleton(ref _current, () => new MyType());\n</code></pre>\n\n<p>Consume the singleton:</p>\n\n<pre><code>MyType.Current. ...\n</code></pre>\n"
},
{
"answer_id": 51169324,
"author": "Eran Peled",
"author_id": 5929496,
"author_profile": "https://Stackoverflow.com/users/5929496",
"pm_score": 0,
"selected": false,
"text": "<p>No Matter which exmaple you choose, always check for concurrency using Parallel.For!\n( loop in which iterations may run in parallel)</p>\n\n<p>put in Singleton C'tor :</p>\n\n<pre><code> private Singleton ()\n {\n Console.WriteLine(\"usage of the Singleton for the first time\");\n }\n</code></pre>\n\n<p>put in Main : </p>\n\n<pre><code>Parallel.For(0, 10,\n index => {\n Thread tt = new Thread(new ThreadStart(Singleton.Instance.SomePrintMethod));\n tt.Start();\n });\n</code></pre>\n"
},
{
"answer_id": 72757098,
"author": "Tore Aurstad",
"author_id": 741368,
"author_profile": "https://Stackoverflow.com/users/741368",
"pm_score": 0,
"selected": false,
"text": "<p>In many solutions today, people use service lifetime of singleton with dependency injection, as .NET offers this out of the box. If you still want to create a generic singleton pattern in your code where you might also consider initializing the type T to a initialized singleton object, 'settable once' and thread safe, here is a possible way to do it.</p>\n<pre><code> public sealed class Singleton<T> where T : class, new()\n {\n private static Lazy<T> InstanceProxy\n {\n get\n {\n if (_instanceObj?.IsValueCreated != true)\n {\n _instanceObj = new Lazy<T>(() => new T());\n }\n return _instanceObj;\n }\n }\n\n private static Lazy<T>? _instanceObj;\n\n\n public static T Instance { get { return InstanceProxy.Value; } } \n\n public static void Init(Lazy<T> instance)\n {\n if (_instanceObj?.IsValueCreated == true)\n {\n throw new ArgumentException($"A Singleton for the type <T> is already set"); \n }\n _instanceObj = instance ?? throw new ArgumentNullException(nameof(instance)); \n }\n\n private Singleton()\n { \n }\n }\n</code></pre>\n<p>The class is sealed and with a private constructor, it accepts types which are classes and must offer a public parameterless constructor 'new'. It uses the Lazy to achieve built in thread safety. You can init also the type T Singleton object for convenience. It is only allowed if a Singleton is not first set. Obviously, you should only init a Singleton of type T early on in your program, such as when the application or service / API starts up. The code will throw an ArgumentException if the Init method is called twice or more times for the type T.</p>\n<p>You can use it like this :\nSome model class :</p>\n<pre><code>public class Aeroplane\n{\n public string? Model { get; set; }\n public string? Manufacturer { get; set; }\n public int YearBuilt { get; set; }\n public int PassengerCount { get; set; }\n}\n</code></pre>\n<p>Usage sample :</p>\n<pre><code>var aeroplane = new Aeroplane\n{\n Manufacturer = "Boeing",\n Model = "747",\n PassengerCount = 350,\n YearBuilt = 2005\n};\n\nvar aeroPlane3 = Singleton<Aeroplane>.Instance;\nvar aeroPlane4 = Singleton<Aeroplane>.Instance;\n\nConsole.WriteLine($"Aeroplane3 and aeroplane4 is same object? {Object.ReferenceEquals(aeroPlane3, aeroPlane4)}");\n</code></pre>\n<p>Outputs 'true'.</p>\n<p>Trying to re-init type T Singleton to another object fails :</p>\n<pre><code>var aeroplane2 = new Aeroplane\n{\n Manufacturer = "Sopwith Aviation Company",\n Model = "Sophwith Camel",\n PassengerCount = 1,\n YearBuilt = 1917\n};\n\nSingleton<Aeroplane>.Init(new Lazy<Aeroplane>(aeroplane2));\n</code></pre>\n<p>You can of course just access the Singleton with initing it - it will call the default public constructor. Possible you could have a way of setting a custom constructor here instead of passing an object as a sort of 'factory pattern'.</p>\n<pre><code>var aeroplaneDefaultInstantiated = Singleton<Aeroplane>.Instance; \n</code></pre>\n<p>Default instantiation - calls the parameterless public constructor of type T.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
]
| I have the following C# singleton pattern, is there any way of improving it?
```
public class Singleton<T> where T : class, new()
{
private static object _syncobj = new object();
private static volatile T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncobj)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public Singleton()
{ }
}
```
Preferred usage example:
```
class Foo : Singleton<Foo>
{
}
```
**Related**:
[An obvious singleton implementation for .NET?](https://stackoverflow.com/questions/953259/an-obvious-singleton-implementation-for-net) | According to Jon Skeet in [Implementing the Singleton Pattern in C#](https://csharpindepth.com/articles/Singleton) the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.
Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton. |
100,104 | <p>I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.</p>
<p>I've managed to get it working by using the <a href="http://www.mysql.com/products/connector/net/" rel="nofollow noreferrer">MySQL Connector/.NET</a>:</p>
<pre><code>MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.AppendLine(reader.GetString("myColumn"));
}
this.txtResults.Text = sb.ToString();
}
</code></pre>
<p>This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and <strong>run it locally</strong>. </p>
<p>I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).</p>
<p>The database is hosted on the same server as the silverlight app if that makes any difference.</p>
<p><strong>EDIT</strong>
Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?</p>
<p>Surely, I cannot be the first person who'd like to use a database to power a silverlight application?</p>
| [
{
"answer_id": 100286,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 2,
"selected": false,
"text": "<p>Silverlight does not have any capability to directly access database servers. What you can do is to expose your database operations through web services (ASMX or WCF, even non-.NET!) and use Silverlight to access those services.</p>\n"
},
{
"answer_id": 100409,
"author": "Kristian J.",
"author_id": 4588,
"author_profile": "https://Stackoverflow.com/users/4588",
"pm_score": 2,
"selected": false,
"text": "<p>Having DB connections directly to the server from the client side is usually a bad idea. I don't know how easy it is to decompile a Silverlight app, but I would guess it's possible in some way. Then you're basically giving away your DB credentials to your users.</p>\n"
},
{
"answer_id": 262839,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 3,
"selected": true,
"text": "<p>The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services.</p>\n\n<p>What may be easiest for you to do right now would be to use a .NET service on a web server or maybe a PHP REST service, and then point your Silverlight app at that service. By doing so, you're protecting your database not only from people snooping through it, but more importantly, you're restricting what people can do to your database. If your data is supposed to be read-only, and your service's contract only allows reading operations, you're set. Alternatively, your service may negotiate sessions with credentials, again, set up through WCF.</p>\n\n<p>WCF can be a client-only, server-only, or client-server connector platform. What you choose will affect the code you write, but it's all going to be independent of your database. Your code can be structured such that it's a one-to-one mapping to your database table, or it can be far more abstract (you can set up classes that represent full logical views if you choose).</p>\n"
},
{
"answer_id": 2950640,
"author": "MatthiasS",
"author_id": 163725,
"author_profile": "https://Stackoverflow.com/users/163725",
"pm_score": 3,
"selected": false,
"text": "<p>While the \"official\" answer is to use WCF to push a service to Silverlight, I kind of figure that anyone using MySQL would probably not be using a complete ASP.NET solution. My solution was to build a PHP webservice (like Rob suggested) to interact with the MySQL database and have the Silverlight access it in a RESTful manner. </p>\n\n<p>Here is beginning of a three part tutorial for using Silverlight to access a MySQL database through a PHP web service:</p>\n\n<p><a href=\"http://www.designersilverlight.com/2010/05/23/php-mysql-and-silverlight-the-complete-tutorial-part-1/\" rel=\"noreferrer\">PHP, MySQL and Silverlight: The Complete Tutorial</a></p>\n"
},
{
"answer_id": 5463132,
"author": "angularsen",
"author_id": 134761,
"author_profile": "https://Stackoverflow.com/users/134761",
"pm_score": 2,
"selected": false,
"text": "<p>I just got this working; ASP.NET4 site with Silverlight4 content on Linux Ubuntu 10 / Apache2 server. Content is developed using Visual Studio 2010. VS2008 should work fine too.</p>\n\n<p>Server:</p>\n\n<ul>\n<li>Setup a Linux server with Apache2 and MySQL, there are tons of guides on this.\n<ul>\n<li>Make sure MySQL is accessible from the development PC and optionally from the Internet. See here for details: <a href=\"http://dev.mysql.com/doc/refman/5.5/en/access-denied.html\" rel=\"nofollow\">Causes of Access-Denied Errors</a>.</li>\n<li>Setup the database table structures and add some content for testing later. In our example we assume you have the table 'persons' with the column 'name'.</li>\n</ul></li>\n<li>Since Silverlight is a client-side technology you are pretty much good-to-go and can host the application with a simple HTML page.</li>\n<li>A web service is required between Silverlight and MySQL. Microsoft's WCF RIA is one flavor, but requires .NET. On the plus-side, you get to host ASP.NET4 pages as well. Here is a thorough guide to setting it up: <a href=\"http://www.integratedwebsystems.com/2010/11/setting-up-mono-2-8-with-asp-net-4-0-and-mvc2-on-ubuntu-with-mysql-membership/\" rel=\"nofollow\">Setting up Mono 2.8 with Asp.Net 4.0 and MVC2 on Ubuntu with MySql Membership</a></li>\n</ul>\n\n<p>Visual Studio:</p>\n\n<ul>\n<li>Install latest <a href=\"http://dev.mysql.com/downloads/connector/net/\" rel=\"nofollow\">MySQL Connector/Net</a> and restart VS</li>\n<li>Add your MySQL database as data source\n<ul>\n<li>Open Server Explorer -> Add data connection -> Select 'MySQL Database'</li>\n<li>Fill in credentials and test connection</li>\n</ul></li>\n</ul>\n\n<p>Setting up the site with MySQL access:</p>\n\n<p>Here is a guide I found helpful: <a href=\"http://manaspatnaik.com/blog/index.php/technology/silverlight-4/step-by-step-guide-to-wcf-ria-enabled-sl4-application-with-entity-framework/404\" rel=\"nofollow\">Step By Step Guide to WCF RIA enabled SL4 application with Entity Framework</a></p>\n\n<ul>\n<li>Create or open a Silverlight project. \n<ul>\n<li>The server-side project is typically named 'ProjectName.Web'</li>\n<li>The client-side project is typically named 'ProjectName'</li>\n</ul></li>\n<li>Add 'ADO.NET Entity Data Model' to the server project. This will be a model of your database structure.\n<ul>\n<li>Select 'Generate from database'</li>\n<li>Choose the MySQL database connection you created</li>\n<li>Select the tables you want to access</li>\n</ul></li>\n<li>Build your solution now before proceeding.</li>\n<li>Add 'Domain Service Class' to the server project, f.ex. 'FooDomain'. This will make the database entities available to the client-side Silverlight code.\n<ul>\n<li>In 'Available DataContext/ObjectContext classes:' select the Entity Framework model you created in the previous step.</li>\n<li>Check the entities you want to access and check 'Enable editing' where appropriate</li>\n<li>Check 'Generate associated classes for metadata'</li>\n</ul></li>\n<li>Build your solution again to generate 'FooDomainContext', based on 'FooDomain' in server project. </li>\n</ul>\n\n<p>Testing:</p>\n\n<p>Let's get data from MySQL into Silverlight. Assuming there is a table named 'persons' with column name 'name', we can bind a list box to show the names of the persons. </p>\n\n<p>First add a Silverlight page, let's say 'Home'.\nIn Home.xaml add:</p>\n\n<pre><code><ListBox x:Name=\"TestList\" Width=\"100\" />\n</code></pre>\n\n<p>In Home.xaml.cs file add:</p>\n\n<pre><code>public partial class Home : Page\n{\n public Home()\n {\n InitializeComponent();\n\n Loaded += Home_Loaded;\n }\n\n void Home_Loaded(object sender, RoutedEventArgs e)\n {\n var context = new FooDomainContext();\n var query = context.Load(context.GetPersonsQuery());\n TestList.ItemsSource = query.Entities;\n TestList.DisplayMemberPath = \"name\";\n }\n}\n</code></pre>\n\n<p>Here we assume you named your domain service 'FooDomain', and this would generate the 'FooDomainContext' class used.</p>\n\n<p>Hopefully, if all is set up properly, you will now see a list of person names when running your Silverlight project.</p>\n\n<p><strong>Edit:</strong> ASP.NET is not optional, but required for the WCF RIA web service used in my example.</p>\n"
},
{
"answer_id": 20823112,
"author": "mjb",
"author_id": 520848,
"author_profile": "https://Stackoverflow.com/users/520848",
"pm_score": 1,
"selected": false,
"text": "<p>You can get data from MySQL by using Web Services.</p>\n\n<p>Walkthrough:</p>\n\n<p>Step 1: Create Web Services</p>\n\n<p>Step 2: Add Service Reference to Silverlight</p>\n\n<p><hr />\n<b>Step 1: Create Web Services</b></p>\n\n<p>Add a new Silverlight project.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ccdis.png\" alt=\"Add a new Silverlight project\"></p>\n\n<p>Create a new Web Service. Right click on the web project > Add > New Item</p>\n\n<p><img src=\"https://i.stack.imgur.com/mlYL2.png\" alt=\"Create a new Web Service\"></p>\n\n<p>Select \"Web Service\".</p>\n\n<p><img src=\"https://i.stack.imgur.com/dZyyu.png\" alt=\"enter image description here\"></p>\n\n<p>Initial code of a new Web Service.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Web;\nusing System.Web.Services;\n\nnamespace SilverlightApplication1.Web\n{\n /// <summary>\n /// Summary description for WebService1\n /// </summary>\n [WebService(Namespace = \"http://tempuri.org/\")]\n [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n [System.ComponentModel.ToolboxItem(false)]\n public class WebService1 : System.Web.Services.WebService\n {\n [WebMethod]\n public string HelloWorld()\n {\n return \"Hello World\";\n }\n }\n}\n</code></pre>\n\n<p>In order for the Web Service able to connect to MySQL, we need to add a reference of MySql.Data.DLL into the web project and add the Using statement at top of the Web Service class:</p>\n\n<pre><code>using MySql.Data.MySqlClient; \n</code></pre>\n\n<p><strong>HelloWorld()</strong> is an initial sample method created by Visual Studio. You may want to delete it as it is not needed. I'm going to create 2 simple method to demonstrate how Web Services are used to communicate between SilverLight and MySQL.</p>\n\n<p>First method: <strong>ExecuteScalar()</strong></p>\n\n<p>This method is simple. Get a single object from MySQL.</p>\n\n<pre><code>public string ExecuteScalar(string sql)\n{\n try\n {\n string result = \"\";\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n result = cmd.ExecuteScalar() + \"\";\n conn.Close();\n }\n }\n return result;\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n} \n</code></pre>\n\n<p>Second method: <strong>ExecuteNonQuery()</strong></p>\n\n<p>For single SQL execution. Example of SQL type: INSERT, UPDATE, DELETE.</p>\n\n<pre><code>public string ExecuteNonQuery(string sql)\n{\n try\n {\n long i = 0;\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n i = cmd.ExecuteNonQuery();\n conn.Close();\n }\n }\n return i + \" row(s) affected by the last command, no resultset returned.\";\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n} \n</code></pre>\n\n<p>This is how the Web Service looks like after adding the two methods above:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Web;\nusing System.Web.Services;\nusing MySql.Data.MySqlClient;\n\nnamespace SilverlightApplication1.Web\n{\n [WebService(Namespace = \"http://tempuri.org/\")]\n [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n [System.ComponentModel.ToolboxItem(false)]\n public class WebService1 : System.Web.Services.WebService\n {\n string constr = \"server=localhost;user=root;pwd=1234;database=test;\";\n\n [WebMethod]\n public string ExecuteScalar(string sql)\n {\n try\n {\n string result = \"\";\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n result = cmd.ExecuteScalar() + \"\";\n conn.Close();\n }\n }\n return result;\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n }\n\n [WebMethod]\n public string ExecuteNonQuery(string sql)\n {\n try\n {\n long i = 0;\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n i = cmd.ExecuteNonQuery();\n conn.Close();\n }\n }\n return i + \" row(s) affected by the last command, no resultset returned.\";\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n } \n }\n} \n</code></pre>\n\n<p>You will notice that an attribute of <strong>[WebMethod]</strong> is added to the methods.</p>\n\n<p>Rebuild the project and let the Web Service be ready for next step.</p>\n\n<p><img src=\"https://i.stack.imgur.com/sQbIk.png\" alt=\"Rebuild the project\"></p>\n\n<p><em>Web Service Access Permission</em></p>\n\n<p>Please note that, by default, Web Service only allow those Silverlight that is hosted at the same domain with the Web Service to access. If the Silverlight application is hosted on another website/domain, Web Service will deny the communication. Therefore we have to configure the permission for the Web Service to be accessed by Silverlight which is hosted at different domain.</p>\n\n<p>You have to create two additional files: <em>clientaccesspolicy.xml</em> and <em>crossdomain.xml</em>.</p>\n\n<p>These files has to be put at the root of the domain where the Web Services are hosted.</p>\n\n<p>Example: <code><a href=\"http://www.mywebsite.com/clientaccesspolicy.xml\" rel=\"nofollow noreferrer\">http://www.mywebsite.com/clientaccesspolicy.xml</a></code> and <code><a href=\"http://www.mywebsite.com/crossdomain.xml\" rel=\"nofollow noreferrer\">http://www.mywebsite.com/crossdomain.xml</a></code></p>\n\n<p><em>clientaccesspolicy.xml</em></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<access-policy>\n <cross-domain-access>\n <policy>\n <allow-from http-request-headers=\"SOAPAction\">\n <domain uri=\"*\"/>\n </allow-from>\n <grant-to>\n <resource path=\"/\" include-subpaths=\"true\"/>\n </grant-to>\n </policy>\n </cross-domain-access>\n</access-policy>\n</code></pre>\n\n<p>If you only want to allow the Web Service to be accessed by specific domain (example: www.myanotherwebsite.com), you can add it within . Example:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<access-policy>\n <cross-domain-access>\n <policy>\n <allow-from http-request-headers=\"SOAPAction\">\n <domain uri=\"http://www.myanotherwebsite.com\"/>\n </allow-from>\n <grant-to>\n <resource path=\"/\" include-subpaths=\"true\"/>\n </grant-to>\n </policy>\n </cross-domain-access>\n</access-policy>\n</code></pre>\n\n<p><em>crossdomain.xml</em></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<!DOCTYPE cross-domain-policy SYSTEM \n\"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n<cross-domain-policy>\n <allow-http-request-headers-from domain=\"*\" headers=\"SOAPAction,Content-Type\"/>\n</cross-domain-policy>\n</code></pre>\n\n<p>To understand more about this, please read: <a href=\"http://msdn.microsoft.com/en-us/library/cc197955%28v=vs.95%29.aspx\" rel=\"nofollow noreferrer\">Making a Service Available Across Domain Boundaries (MSDN)</a></p>\n\n<hr />\n\n<p><strong>Step 2: Add Service Reference to Silverlight</strong></p>\n\n<p>Add a Service Reference to Silverlight.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Ezrkn.png\" alt=\"Add a Service Reference to Silverlight\"></p>\n\n<p>Type the address of the Web Service and press [Go].</p>\n\n<p>Example of address: <a href=\"http://www.mywebsite.com/MyCoolWebService.asmx\" rel=\"nofollow noreferrer\">http://www.mywebsite.com/MyCoolWebService.asmx</a></p>\n\n<p>Change the Namespace to your favor, and press [OK].</p>\n\n<p><img src=\"https://i.stack.imgur.com/wPGCl.png\" alt=\"Web Service Browser\"></p>\n\n<p>Visual Studio will analyze the Web Service, do the data binding and create a class.</p>\n\n<p>Before continue coding, let's us see what methods that we can use in the new created class. Right click the new class and select [View in Object Browser].</p>\n\n<p><img src=\"https://i.stack.imgur.com/3VECS.png\" alt=\"View in Object Browser\"></p>\n\n<p>The class that we are going to use is WebService1SoapClient (in this example). The naming is based on the Service name. If we name our service class as MyCoolWebService, then MyCoolWebServiceSoapClient will be chosen as the name of the class in Silverlight. At the right panel, two methods and two events are highlighted. Those are the methods used to call the Web Services.</p>\n\n<p><img src=\"https://i.stack.imgur.com/RoH50.png\" alt=\"Object of WebService1SoapClient\"></p>\n\n<p>Lets create a simple Silverlight application by adding a Textbox and two Buttons.</p>\n\n<p>In this example, user will key in SQL query directly into the Textbox.</p>\n\n<p>Button of [ExecuteScalar] will send the SQL to the Web Service and retrieve data back. (SELECT, SHOW, etc.)</p>\n\n<p>Button of [ExecuteNonQuery] will send the SQL to the Web Service for execution only. (INSERT, UPDATE, DELETE, etc.)</p>\n\n<p><img src=\"https://i.stack.imgur.com/vbZ1g.png\" alt=\"Design a simple SilverLight App\"></p>\n\n<p>This is the initial code behind of MainPage.xaml:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing System.Windows.Shapes;\n\nnamespace SilverlightApplication1\n{\n public partial class MainPage : UserControl\n {\n public MainPage()\n {\n InitializeComponent();\n }\n\n private void btExecuteScalar_Click(object sender, RoutedEventArgs e)\n {\n }\n\n private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)\n {\n }\n }\n}\n</code></pre>\n\n<p>Now, these are what we are going to do here:</p>\n\n<ul>\n<li>Declare the service as static object at class level:\nServiceReference1.WebService1SoapClient </li>\n<li>Create the service completed event of the two methods. </li>\n<li>Call the service in the event of button click. </li>\n<li>Display the service result: MessageBox.Show()</li>\n</ul>\n\n<p><br /></p>\n\n<pre><code>public partial class MainPage : UserControl\n{\n ServiceReference1.WebService1SoapClient myService;\n\n public MainPage()\n {\n InitializeComponent();\n myService = new ServiceReference1.WebService1SoapClient();\n myService.ExecuteScalarCompleted += myService_ExecuteScalarCompleted;\n myService.ExecuteNonQueryCompleted += myService_ExecuteNonQueryCompleted;\n }\n\n void myService_ExecuteNonQueryCompleted(object sender, \n ServiceReference1.ExecuteNonQueryCompletedEventArgs e)\n {\n MessageBox.Show(e.Result);\n }\n\n void myService_ExecuteScalarCompleted(object sender, \n ServiceReference1.ExecuteScalarCompletedEventArgs e)\n {\n MessageBox.Show(e.Result);\n }\n\n private void btExecuteScalar_Click(object sender, RoutedEventArgs e)\n {\n myService.ExecuteScalarAsync(textBox1.Text);\n }\n\n private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)\n {\n myService.ExecuteNonQueryAsync(textBox1.Text);\n }\n}\n</code></pre>\n\n<p>Press [F5], run and test the Silverlight application.</p>\n\n<p><img src=\"https://i.stack.imgur.com/E1YNH.png\" alt=\"Testing\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/U8dUW.png\" alt=\"Testing\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/JP2qO.png\" alt=\"Testing\"></p>\n\n<p>Together with your creativity, I believe you can do something more than this for now Smile | :)</p>\n\n<p>If you have done any changes to the Web Service, maybe you added new Service (new web methods), you have to update the Service Reference at Silverlight to re-bind the Services. You might want to update the Web Service address, if you uploaded the files to a different web hosting.</p>\n\n<p><img src=\"https://i.stack.imgur.com/RtGb3.png\" alt=\"update the Service Reference\"></p>\n\n<p>Happy coding.</p>\n\n<p>Read More:</p>\n\n<ol>\n<li><a href=\"http://www.codeproject.com/Articles/633789/Connecting-MySQL-From-SilverLight-With-Web-Service\" rel=\"nofollow noreferrer\">Original Post - Connecting MySQL From SilverLight With Web Services - CodeProject.com (written by me)</a><br /></li>\n<li><a href=\"http://www.codeproject.com/Articles/263087/Access-a-Web-Service-from-a-Silverlight-Applicatio\" rel=\"nofollow noreferrer\">Access a Web Service from a Silverlight Application</a><br /></li>\n<li><a href=\"http://support.microsoft.com/kb/308359\" rel=\"nofollow noreferrer\">HOW TO: Write a Simple Web Service by Using Visual C# .NET</a><br /></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/cc197940%28v=vs.95%29.aspx\" rel=\"nofollow noreferrer\">How to: Build a Service for Silverlight Clients</a></li>\n</ol>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8521/"
]
| I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.
I've managed to get it working by using the [MySQL Connector/.NET](http://www.mysql.com/products/connector/net/):
```
MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.AppendLine(reader.GetString("myColumn"));
}
this.txtResults.Text = sb.ToString();
}
```
This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and **run it locally**.
I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).
The database is hosted on the same server as the silverlight app if that makes any difference.
**EDIT**
Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?
Surely, I cannot be the first person who'd like to use a database to power a silverlight application? | The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services.
What may be easiest for you to do right now would be to use a .NET service on a web server or maybe a PHP REST service, and then point your Silverlight app at that service. By doing so, you're protecting your database not only from people snooping through it, but more importantly, you're restricting what people can do to your database. If your data is supposed to be read-only, and your service's contract only allows reading operations, you're set. Alternatively, your service may negotiate sessions with credentials, again, set up through WCF.
WCF can be a client-only, server-only, or client-server connector platform. What you choose will affect the code you write, but it's all going to be independent of your database. Your code can be structured such that it's a one-to-one mapping to your database table, or it can be far more abstract (you can set up classes that represent full logical views if you choose). |
100,106 | <pre><code>sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%
@{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{
$_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}
</code></pre>
<p>update: I thought the word "puzzle" would imply this, but: <em>I</em> know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it.</p>
| [
{
"answer_id": 100503,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 3,
"selected": false,
"text": "<p>It takes two arrayrefs and returns a new arrayref with the contents of the second array rearranged such that the second part comes before the first part, split at a point based on the memory location of the first array. When the second array is empty or contains one item, just returns a copy of the second array. Equivalent to the following:</p>\n\n<pre><code>sub foo {\n my ($list1, $list2) = @_;\n my @output;\n if (@$list2 > 0) {\n my $split = $list1 % @$list2;\n @output = @$list2[$split .. $#$list2, 0 .. ($split - 1)];\n } else {\n @output = @$list2;\n }\n return \\@output;\n}\n</code></pre>\n\n<p><code>$list1 % @$list2</code> essentially picks a random place to split the array, based on <code>$list</code> which evaluates to the memory address of $list when evaluated in a numeric context.</p>\n\n<p>The original mostly uses a lot of tautologies involving punctuation variables to obfuscate. e.g.</p>\n\n<ul>\n<li><code>!$| | $|</code> is always 1</li>\n<li><code>@- - @+</code> is always 0</li>\n</ul>\n\n<p>Updated to note that <code>perltidy</code> was very helpful deciphering here, but it choked on <code>!!$^^^!$^^</code>, which it reformats to <code>!!$^ ^ ^ !$^ ^</code>, which is invalid Perl; it should be <code>!!$^^ ^ !$^^</code>. This might be the cause of RWendi's compile error.</p>\n"
},
{
"answer_id": 147257,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "<p>I found this command helpful, when working on my other answer.</p>\n\n<p><code>perl -MO=Concise,foo,-terse,-compact obpuz.pl > obpuz.out</code></p>\n\n<p><a href=\"http://search.cpan.org/~rgarcia/perl-5.10.0/ext/B/B/Concise.pm\" rel=\"nofollow noreferrer\">B::Concise</a></p>\n"
},
{
"answer_id": 147456,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 5,
"selected": true,
"text": "<h3>Here is how you figure out how to de-obfuscate this subroutine.</h3>\n\n<p><em>Sorry for the length</em></p>\n\n<p>First let's tidy up the code, and add useful comments.</p>\n\n<pre><code>sub foo {\n [\n (\n # ($#{$_[1]})\n $#{\n $_[\n ! ( $| | $| )\n # $OUTPUT_AUTOFLUSH === $|\n # $| is usually 0\n # ! ( $| | $| )\n # ! ( 0 | 0 )\n # ! ( 0 )\n # 1\n ]\n }\n\n *\n\n # @{$_[1]}\n @{\n $_[\n !!$_ ^ !$_\n\n # !! 1 ^ ! 1\n # ! 0 ^ 0\n # 1 ^ 0\n # 1\n\n # !! 0 ^ ! 0\n # ! 1 ^ 1\n # 0 ^ 1\n # 1\n ]\n }\n )\n\n ?\n\n\n # @{$_[1]}\n @{\n $_[\n !$. . !!$.\n # $INPUT_LINE_NUMBER === $.\n # $. starts at 1\n # !$. . !!$.\n # ! 1 . !! 1\n # 0 . ! 0\n # 0 . 1\n # 01\n ]\n }\n\n [\n # $_[0]\n $_[\n # @LAST_MATCH_START - @LAST_MATCH_END\n # 0\n @- - @+\n ]\n\n %\n\n\n # @{$_[1]}\n @{\n $_[\n $= =~ /(?=)/ / !$` #( fix highlighting )`/\n # $= is usually 60\n # /(?=)/ will match, returns 1\n # $` will be ''\n # 1 / ! ''\n # 1 / ! 0\n # 1 / 1\n # 1\n ]\n }\n\n ..\n\n # $#{$_[1]}\n $#{\n $_[\n $? ? !!$? : !$?\n\n # $CHILD_ERROR === $?\n # $? ? !!$? : !$?\n\n # 0 ? !! 0 : ! 0\n # 0 ? 0 : 1\n # 1\n\n # 1 ? !! 1 : ! 1\n # 1 ? 1 : 0\n # 1\n ]\n }\n\n ,\n\n # ( 0 )\n (\n $) ? !$) : !!$)\n\n # $EFFECTIVE_GROUP_ID === $)\n\n # $) ? !$) : !!$)\n\n # 0 ? ! 0 : !! 0\n # 0 ? 1 : 0\n # 0\n\n # 1 ? ! 1 : !! 1\n # 1 ? 0 : 1\n # 0\n )\n\n ..\n\n # $_[0]\n $_[\n $- - $- # 0\n\n # $LAST_PAREN_MATCH = $-\n\n # 1 - 1 == 0\n # 5 - 5 == 0\n ]\n\n %\n\n # @{$_[1]}\n @{\n $_[\n $] / $]\n # $] === The version + patchlevel / 1000 of the Perl interpreter.\n\n # 1 / 1 == 1\n # 5 / 5 == 1\n ]\n }\n\n -\n\n # ( 1 )\n (\n !!$+ + !$+\n\n # !! 1 + ! 1\n # ! 0 + 0\n # 1 + 0\n # 1\n )\n ]\n\n :\n\n # @{$_[1]}\n @{\n $_[\n !!$^^ ^ !$^^\n\n # !! 1 ^ ! 1\n # ! 0 ^ 0\n # 1 ^ 0\n # 1\n\n # !! 0 ^ ! 0\n # ! 1 ^ 1\n # 0 ^ 1\n # 1\n ]\n }\n ]\n}\n</code></pre>\n\n<p>Now let's remove some of the obfuscation.</p>\n\n<pre><code>sub foo{\n [\n (\n $#{$_[1]} * @{$_[1]}\n )\n\n ?\n\n @{$_[1]}[\n ( $_[0] % @{$_[1]} ) .. $#{$_[1]}\n\n ,\n\n 0 .. ( $_[0] % @{$_[1]} - 1 )\n ]\n\n :\n\n @{$_[1]}\n ]\n}\n</code></pre>\n\n<p>Now that we have some idea of what is going on, let's name the variables.</p>\n\n<pre><code>sub foo{\n my( $item_0, $arr_1 ) = @_;\n my $len_1 = @$arr_1;\n\n [\n # This essentially just checks that the length of $arr_1 is greater than 1\n ( ( $len_1 -1 ) * $len_1 )\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 5 -1 ) * 5 )\n # 4 * 5\n # 20\n # 20 ? 1 : 0 == 1\n\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 2 -1 ) * 2 )\n # 1 * 2\n # 2\n # 2 ? 1 : 0 == 1\n\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 1 -1 ) * 1 )\n # 0 * 1\n # 0\n # 0 ? 1 : 0 == 0\n\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 0 -1 ) * 0 )\n # -1 * 0\n # 0\n # 0 ? 1 : 0 == 0\n\n ?\n\n @{$arr_1}[\n ( $item_0 % $len_1 ) .. ( $len_1 -1 ),\n 0 .. ( $item_0 % $len_1 - 1 )\n ]\n\n :\n\n # If we get here, @$arr_1 is either empty or has only one element\n @$arr_1\n ]\n}\n</code></pre>\n\n<p>Let's refactor the code to make it a little bit more readable.</p>\n\n<pre><code>sub foo{\n my( $item_0, $arr_1 ) = @_;\n my $len_1 = @$arr_1;\n\n if( $len_1 > 1 ){\n return [\n @{$arr_1}[\n ( $item_0 % $len_1 ) .. ( $len_1 -1 ),\n 0 .. ( $item_0 % $len_1 - 1 )\n ]\n ];\n }elsif( $len_1 ){\n return [ @$arr_1 ];\n }else{\n return [];\n }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17389/"
]
| ```
sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%
@{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{
$_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}
```
update: I thought the word "puzzle" would imply this, but: *I* know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it. | ### Here is how you figure out how to de-obfuscate this subroutine.
*Sorry for the length*
First let's tidy up the code, and add useful comments.
```
sub foo {
[
(
# ($#{$_[1]})
$#{
$_[
! ( $| | $| )
# $OUTPUT_AUTOFLUSH === $|
# $| is usually 0
# ! ( $| | $| )
# ! ( 0 | 0 )
# ! ( 0 )
# 1
]
}
*
# @{$_[1]}
@{
$_[
!!$_ ^ !$_
# !! 1 ^ ! 1
# ! 0 ^ 0
# 1 ^ 0
# 1
# !! 0 ^ ! 0
# ! 1 ^ 1
# 0 ^ 1
# 1
]
}
)
?
# @{$_[1]}
@{
$_[
!$. . !!$.
# $INPUT_LINE_NUMBER === $.
# $. starts at 1
# !$. . !!$.
# ! 1 . !! 1
# 0 . ! 0
# 0 . 1
# 01
]
}
[
# $_[0]
$_[
# @LAST_MATCH_START - @LAST_MATCH_END
# 0
@- - @+
]
%
# @{$_[1]}
@{
$_[
$= =~ /(?=)/ / !$` #( fix highlighting )`/
# $= is usually 60
# /(?=)/ will match, returns 1
# $` will be ''
# 1 / ! ''
# 1 / ! 0
# 1 / 1
# 1
]
}
..
# $#{$_[1]}
$#{
$_[
$? ? !!$? : !$?
# $CHILD_ERROR === $?
# $? ? !!$? : !$?
# 0 ? !! 0 : ! 0
# 0 ? 0 : 1
# 1
# 1 ? !! 1 : ! 1
# 1 ? 1 : 0
# 1
]
}
,
# ( 0 )
(
$) ? !$) : !!$)
# $EFFECTIVE_GROUP_ID === $)
# $) ? !$) : !!$)
# 0 ? ! 0 : !! 0
# 0 ? 1 : 0
# 0
# 1 ? ! 1 : !! 1
# 1 ? 0 : 1
# 0
)
..
# $_[0]
$_[
$- - $- # 0
# $LAST_PAREN_MATCH = $-
# 1 - 1 == 0
# 5 - 5 == 0
]
%
# @{$_[1]}
@{
$_[
$] / $]
# $] === The version + patchlevel / 1000 of the Perl interpreter.
# 1 / 1 == 1
# 5 / 5 == 1
]
}
-
# ( 1 )
(
!!$+ + !$+
# !! 1 + ! 1
# ! 0 + 0
# 1 + 0
# 1
)
]
:
# @{$_[1]}
@{
$_[
!!$^^ ^ !$^^
# !! 1 ^ ! 1
# ! 0 ^ 0
# 1 ^ 0
# 1
# !! 0 ^ ! 0
# ! 1 ^ 1
# 0 ^ 1
# 1
]
}
]
}
```
Now let's remove some of the obfuscation.
```
sub foo{
[
(
$#{$_[1]} * @{$_[1]}
)
?
@{$_[1]}[
( $_[0] % @{$_[1]} ) .. $#{$_[1]}
,
0 .. ( $_[0] % @{$_[1]} - 1 )
]
:
@{$_[1]}
]
}
```
Now that we have some idea of what is going on, let's name the variables.
```
sub foo{
my( $item_0, $arr_1 ) = @_;
my $len_1 = @$arr_1;
[
# This essentially just checks that the length of $arr_1 is greater than 1
( ( $len_1 -1 ) * $len_1 )
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 5 -1 ) * 5 )
# 4 * 5
# 20
# 20 ? 1 : 0 == 1
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 2 -1 ) * 2 )
# 1 * 2
# 2
# 2 ? 1 : 0 == 1
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 1 -1 ) * 1 )
# 0 * 1
# 0
# 0 ? 1 : 0 == 0
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 0 -1 ) * 0 )
# -1 * 0
# 0
# 0 ? 1 : 0 == 0
?
@{$arr_1}[
( $item_0 % $len_1 ) .. ( $len_1 -1 ),
0 .. ( $item_0 % $len_1 - 1 )
]
:
# If we get here, @$arr_1 is either empty or has only one element
@$arr_1
]
}
```
Let's refactor the code to make it a little bit more readable.
```
sub foo{
my( $item_0, $arr_1 ) = @_;
my $len_1 = @$arr_1;
if( $len_1 > 1 ){
return [
@{$arr_1}[
( $item_0 % $len_1 ) .. ( $len_1 -1 ),
0 .. ( $item_0 % $len_1 - 1 )
]
];
}elsif( $len_1 ){
return [ @$arr_1 ];
}else{
return [];
}
}
``` |
100,107 | <p>I'm investigating the following <code>java.lang.VerifyError</code></p>
<pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴Mt̴MÚw€mçw€mp:”MŒŒ
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
</code></pre>
<p>It occurs when the jboss server in which the servlet is deployed is started.
It is compiled with jdk-1.5.0_11 and I tried to recompile it with jdk-1.5.0_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.</p>
<p>When I changed the method name and got the following error:</p>
<pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources ØÅN|ØÅNÚw€mçw€mX#ÖM|XÔM
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
</code></pre>
<p>You can see that more of the method signature is shown.</p>
<p>The actual method signature is</p>
<pre><code> private PgasePdfTable getMonthData(int month, int year, Collection dayTypes,
Collection calendarDays,
HashMap bcSpecialDays,
Collection activityPeriods,
Locale locale, MessageResources resources) throws Exception {
</code></pre>
<p>I already tried looking at it with <code>javap</code> and that gives the method signature as it should be.</p>
<p>When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.</p>
<p>The rest of the application runs okay, only that one servlet is out of order.
Any ideas where to look would be helpful.</p>
| [
{
"answer_id": 100131,
"author": "Lars Westergren",
"author_id": 15627,
"author_profile": "https://Stackoverflow.com/users/15627",
"pm_score": 1,
"selected": false,
"text": "<p>This page may give you some hints -\n<a href=\"http://www.zanthan.com/itymbi/archives/000337.html\" rel=\"nofollow noreferrer\">http://www.zanthan.com/itymbi/archives/000337.html</a></p>\n\n<p>There may be a subtle bug in the body of that method that javac fails to spot. Difficult to diagnose unless you post the whole method here. </p>\n\n<p>You could start by declaring as many variables as possible as final... that would have caught the bug mentioned on the zanthan site, and is often a good practice anyways.</p>\n"
},
{
"answer_id": 100134,
"author": "p3t0r",
"author_id": 16685,
"author_profile": "https://Stackoverflow.com/users/16685",
"pm_score": 5,
"selected": false,
"text": "<p><code>java.lang.VerifyError</code> are the worst.</p>\n\n<p>You would get this error if the bytecode size of your method exceeds the 64kb limit; but you would probably have noticed that.</p>\n\n<p>Are you 100% sure this class isn't present in the classpath elsewhere in your application, maybe in another jar?</p>\n\n<p>Also, from your stacktrace, is the character encoding of the source file (<code>utf-8</code>?) Is that correct?</p>\n"
},
{
"answer_id": 101364,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 3,
"selected": false,
"text": "<p>One thing you might try is using <code>-Xverify:all</code> which will verify bytecode on load and sometimes gives helpful error messages if the bytecode is invalid. </p>\n"
},
{
"answer_id": 918001,
"author": "Mike Miller",
"author_id": 16138,
"author_profile": "https://Stackoverflow.com/users/16138",
"pm_score": 2,
"selected": false,
"text": "<p>I was getting this problem due to pack200 mangling a class file. A bit of searching turned this <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6313847\" rel=\"nofollow noreferrer\">java bug</a> up. Basically, setting <code>--effort=4</code> caused the problem to go away.</p>\n\n<p>Using java 1.5.0_17 (though it cropped up in every single variant of java 1.5 I tried it in).</p>\n"
},
{
"answer_id": 2041695,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 3,
"selected": false,
"text": "<p>VerifyError means that the class file contains bytecode that is syntactically correct but violates some semantic restriction e.g. a jump target that crosses method boundaries.</p>\n\n<p>Basically, a VerifyError can only occur when there is a compiler bug, or when the class file gets corrupted in some other way (e.g. through faulty RAM or a failing HD).</p>\n\n<p>Try compiling with a different JDK version and on a different machine.</p>\n"
},
{
"answer_id": 2518002,
"author": "Kevin Panko",
"author_id": 125389,
"author_profile": "https://Stackoverflow.com/users/125389",
"pm_score": 9,
"selected": true,
"text": "<p><code>java.lang.VerifyError</code> can be the result when you have compiled against a different library than you are using at runtime.</p>\n\n<p>For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in <code>org.apache.*</code> namespace) were found at runtime, so <code>ClassNotFoundException</code> was <strong><em>not</em></strong> the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time.</p>\n\n<p>Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws <code>VerifyError</code> when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns <code>String</code> and then stores that return value in a field that holds a <code>List</code>.</p>\n"
},
{
"answer_id": 5184091,
"author": "Flow",
"author_id": 194894,
"author_profile": "https://Stackoverflow.com/users/194894",
"pm_score": 4,
"selected": false,
"text": "<p>As Kevin Panko said, it's mostly because of library change.\nSo in some cases a \"clean\" of the project (directory) followed by a build does the trick.</p>\n"
},
{
"answer_id": 13850988,
"author": "Bitcoin Cash - ADA enthusiast",
"author_id": 1369016,
"author_profile": "https://Stackoverflow.com/users/1369016",
"pm_score": 3,
"selected": false,
"text": "<p>I fixed this error on Android by making the project I was importing a library, as described here <a href=\"http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject\" rel=\"noreferrer\">http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject</a></p>\n\n<p>Previously, I was just referencing the project (not making it a library) and I was getting this strange VerifyError.</p>\n\n<p>Hope it helps someone.</p>\n"
},
{
"answer_id": 16060251,
"author": "18446744073709551615",
"author_id": 755804,
"author_profile": "https://Stackoverflow.com/users/755804",
"pm_score": 2,
"selected": false,
"text": "<p>I have fixed a similar java.lang.VerifyError issue by replacing</p>\n\n<pre><code> catch (MagickException e)\n</code></pre>\n\n<p>with</p>\n\n<pre><code> catch (Exception e)\n</code></pre>\n\n<p>where <code>MagickException</code> was defined in a library project (on which my project has a dependency).</p>\n\n<p>After that I have got a <code>java.lang.NoClassDefFoundError</code> about a class from the same library (fixed according to <a href=\"https://stackoverflow.com/a/9898820/755804\">https://stackoverflow.com/a/9898820/755804</a> ).</p>\n"
},
{
"answer_id": 16478995,
"author": "Martin Konicek",
"author_id": 90998,
"author_profile": "https://Stackoverflow.com/users/90998",
"pm_score": 2,
"selected": false,
"text": "<p>This can happen on Android when you're trying to load a library that was compiled against Oracle's JDK.</p>\n\n<p><a href=\"https://groups.google.com/forum/?fromgroups=#!topic/asynchttpclient/Ml6bOndZbDY\" rel=\"nofollow\">Here is the problem</a> for Ning Async HTTP client.</p>\n"
},
{
"answer_id": 16634043,
"author": "Michal Vician",
"author_id": 915756,
"author_profile": "https://Stackoverflow.com/users/915756",
"pm_score": 3,
"selected": false,
"text": "<p>In my case my Android project depends on another Java project compiled for Java 7. <code>java.lang.VerifyError</code> disappeared after I changed Compiler Compliance Level of that Java project to 6.0</p>\n\n<p>Later I found out that this is a Dalvik issue: <a href=\"https://groups.google.com/forum/?fromgroups#!topic/android-developers/sKsMTZ42pwE\" rel=\"noreferrer\">https://groups.google.com/forum/?fromgroups#!topic/android-developers/sKsMTZ42pwE</a></p>\n"
},
{
"answer_id": 17974044,
"author": "user2484130",
"author_id": 2484130,
"author_profile": "https://Stackoverflow.com/users/2484130",
"pm_score": 1,
"selected": false,
"text": "<p>Well in my case, my project A had a dependency on another, say X(A was using some of the classes defined in X). So when I added X as a reference project in the build path of A , I got this error. However when I removed X as the referenced project and included X's jar as one of the libraries, the problem was solved.</p>\n"
},
{
"answer_id": 23325795,
"author": "ViliusK",
"author_id": 517381,
"author_profile": "https://Stackoverflow.com/users/517381",
"pm_score": 2,
"selected": false,
"text": "<p>In my case I had to remove this block:</p>\n\n<pre><code>compileOptions {\n sourceCompatibility JavaVersion.VERSION_1_7\n targetCompatibility JavaVersion.VERSION_1_7\n}\n</code></pre>\n\n<p>It was showing error near <code>Fragment.showDialog()</code> method call.</p>\n"
},
{
"answer_id": 23436701,
"author": "demongolem",
"author_id": 236247,
"author_profile": "https://Stackoverflow.com/users/236247",
"pm_score": 1,
"selected": false,
"text": "<p>Check for multiple versions of the same jar file on your classpath. </p>\n\n<p>For example, I had opennlp-tools-1.3.0.jar and opennlp-tools-1.5.3.jar on my classpath and got this error. The solution was to delete opennlp-tools-1.3.0.jar.</p>\n"
},
{
"answer_id": 25902807,
"author": "Alexander Wessel",
"author_id": 1845794,
"author_profile": "https://Stackoverflow.com/users/1845794",
"pm_score": 1,
"selected": false,
"text": "<p>Another reason for this error can be the combination of AspectJ <= 1.6.11 with JRE > 6.</p>\n\n<p>See <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=353467\" rel=\"nofollow\">Eclipse Bug 353467</a> and <a href=\"http://kieker.uni-kiel.de/trac/ticket/307\" rel=\"nofollow\">Kieker ticket 307</a> for details.</p>\n\n<p>This is especially true when everything works fine on JRE 6 and moving to JRE7 breaks things. </p>\n"
},
{
"answer_id": 25902833,
"author": "Alexander Wessel",
"author_id": 1845794,
"author_profile": "https://Stackoverflow.com/users/1845794",
"pm_score": 1,
"selected": false,
"text": "<p>CGLIB < 2.2 with JRE > 6 could trigger similar errors, see <a href=\"https://stackoverflow.com/questions/14456692/should-i-upgrade-to-cglib-3-0\">\"Should I upgrade to CGLIB 3.0?\"</a> and some commentary at <a href=\"https://jira.spring.io/browse/SPR-9669\" rel=\"nofollow noreferrer\">Spring SPR-9669</a>.</p>\n\n<p>This is especially true when everything works fine on JRE 6 and simply switching to JRE7 breaks things.</p>\n"
},
{
"answer_id": 27640213,
"author": "Sandeep Jindal",
"author_id": 231567,
"author_profile": "https://Stackoverflow.com/users/231567",
"pm_score": 0,
"selected": false,
"text": "<p>Though the reason mentioned by Kevin is correct, but I would definitely check below before moving to something else:</p>\n\n<ol>\n<li>Check the <code>cglibs</code> in my classpath. </li>\n<li>Check the <code>hibernate</code> versions in my classpath.</li>\n</ol>\n\n<p>Chances are good that having multiple or conflicting version of any of the above could cause unexpected issues like the one in question.</p>\n"
},
{
"answer_id": 29471655,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Minimal example that generates the error</strong></p>\n\n<p>One simple possibility is to use <a href=\"https://github.com/Sable/jasmin\" rel=\"nofollow noreferrer\">Jasmin</a>, or to manually edit the bytecode with a binary file editor.</p>\n\n<p>Lets create <code>void</code> method without a <code>return</code> instruction (generated by the <code>return;</code> statement in Java), which the JVMS says is illegal.</p>\n\n<p>In Jasmin we could write:</p>\n\n<pre><code>.class public Main\n.super java/lang/Object\n\n.method public static main([Ljava/lang/String;)V\n aload_0 ; Just so that we won't get another verify error for empty code.\n.end method\n</code></pre>\n\n<p>We then do <code>javac Main.j</code> and <code>javap -v Main</code> says that we have compiled:</p>\n\n<pre><code>public static void main(java.lang.String[]);\n descriptor: ([Ljava/lang/String;)V\n flags: ACC_PUBLIC, ACC_STATIC\n Code:\n stack=1, locals=1, args_size=1\n 0: aload_0\n</code></pre>\n\n<p>so really there is no return instruction.</p>\n\n<p>Now if we try to run <code>java Main</code> we get:</p>\n\n<pre><code>Error: A JNI error has occurred, please check your installation and try again\nException in thread \"main\" java.lang.VerifyError: (class: NoReturn, method: main signature: ([Ljava/lang/String;)V) Falling off the end of the code\n at java.lang.Class.getDeclaredMethods0(Native Method)\n at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)\n at java.lang.Class.privateGetMethodRecursive(Class.java:3048)\n at java.lang.Class.getMethod0(Class.java:3018)\n at java.lang.Class.getMethod(Class.java:1784)\n at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)\n at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)\n</code></pre>\n\n<p>This error can never happen in Java normally, since the Java compiler adds an implicit <code>return</code> to <code>void</code> methods for us. This is why we don't need to add a <code>return</code> to our <code>main</code> methods. You can check this with <code>javap</code>.</p>\n\n<p><strong>JVMS</strong></p>\n\n<p>VerifyError happens when you try to run certain types of illegal class file as specified by <a href=\"https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.8\" rel=\"nofollow noreferrer\">JVMS 7 chapter 4.5</a></p>\n\n<p>The JVMS says that when Java loads a file, it must run a series of checks to see that the class file is OK before running it.</p>\n\n<p>Such errors cannot be generated on a single compile and run cycle of Java code, because <a href=\"https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.10\" rel=\"nofollow noreferrer\">JVMS 7 4.10 says</a>:</p>\n\n<blockquote>\n <p>Even though a compiler for the Java programming language must only produce class files that satisfy all the static and structural constraints [...\n ]</p>\n</blockquote>\n\n<p>So to see a minimal failure example, we will need to generate the source code without <code>javac</code>.</p>\n"
},
{
"answer_id": 30029807,
"author": "Toumi",
"author_id": 1934704,
"author_profile": "https://Stackoverflow.com/users/1934704",
"pm_score": 1,
"selected": false,
"text": "<p>It could also happen when you have a lot of module imports with maven.\nThere will be two or more classes having exactly the same name ( same qualified name).\nThis error is resulting from difference of interpretation between compile time and runtime.</p>\n"
},
{
"answer_id": 35424866,
"author": "Ulhas N",
"author_id": 4345265,
"author_profile": "https://Stackoverflow.com/users/4345265",
"pm_score": 1,
"selected": false,
"text": "<p>If you are migrating to java7 or using java7 then generally this error can be seen. I faced above errors and struggled a lot to find out the root cause, I would suggest to try adding <strong>\"-XX:-UseSplitVerifier\"</strong> JVM argument while running your application.</p>\n"
},
{
"answer_id": 35481346,
"author": "anand krish",
"author_id": 2147814,
"author_profile": "https://Stackoverflow.com/users/2147814",
"pm_score": 0,
"selected": false,
"text": "<p>java.lang.VerifyError means your compiled bytecode is referring to something that Android cannot find. This verifyError Issues me only with <strong>kitkat4.4 and lesser version not in above version</strong> of that even I ran the same build in both Devices. when I used jackson json parser of older version it shows java.lang.verifyerror</p>\n\n<pre><code>compile 'com.fasterxml.jackson.core:jackson-databind:2.2.+'\ncompile 'com.fasterxml.jackson.core:jackson-core:2.2.+'\ncompile 'com.fasterxml.jackson.core:jackson-annotations:2.2.+'\n</code></pre>\n\n<p>Then I have changed the Dependancy to the <strong>latest version 2.2 to 2.7</strong> without the <strong>core library</strong>, then it works. which means the Methods and other contents of <strong>core</strong> is migrated to the latest version of <strong>Databind2.7</strong>. This fix my Issues.</p>\n\n<pre><code>compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.0-rc3'\ncompile 'com.fasterxml.jackson.core:jackson-databind:2.7.0-rc3'\n</code></pre>\n"
},
{
"answer_id": 47990158,
"author": "Jat Rahul",
"author_id": 9144643,
"author_profile": "https://Stackoverflow.com/users/9144643",
"pm_score": 0,
"selected": false,
"text": "<p>please remove any unusable jar file and try to run. and its work for me i added a jcommons jar file and also another jcommons.1.0.14 jar file so remove jcommons and its working for me</p>\n"
},
{
"answer_id": 48088835,
"author": "Aashirwad Sinha",
"author_id": 9171082,
"author_profile": "https://Stackoverflow.com/users/9171082",
"pm_score": -1,
"selected": false,
"text": "<p>In my case, I was getting verify error with below stack trace</p>\n\n<pre><code>jasperreports-server-cp-6.4.0-bin\\buildomatic\\build.xml:61: The following error occurred while executing this line:\nTIB_js-jrs-cp_6.4.0_bin\\jasperreports-server-cp-6.4.0-bin\\buildomatic\\bin\\setup.xml:320: java.lang.VerifyError: (class: org/apache/commons/codec/binary/Base64OutputStream, method: <init> signature: (Ljava/io/OutputStream;ZI[B)V) Incompatible argument to function\n at com.jaspersoft.jasperserver.crypto.KeystoreManager.createKeystore(KeystoreManager.java:257)\n at com.jaspersoft.jasperserver.crypto.KeystoreManager.init(KeystoreManager.java:224)\n at com.jaspersoft.buildomatic.crypto.KeystoreTask.execute(KeystoreTask.java:64)\n at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)\n at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\n at org.apache.tools.ant.Task.perform(Task.java:348)\n at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68)\n at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)\n at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\n at org.apache.tools.ant.Task.perform(Task.java:348)\n at org.apache.tools.ant.Target.execute(Target.java:435)\n at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:169)\n at org.apache.tools.ant.taskdefs.ImportTask.importResource(ImportTask.java:222)\n at org.apache.tools.ant.taskdefs.ImportTask.execute(ImportTask.java:163)\n at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\n at org.apache.tools.ant.Task.perform(Task.java:348)\n at org.apache.tools.ant.Target.execute(Target.java:435)\n at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:180)\n at org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:93)\n at org.apache.tools.ant.Main.runBuild(Main.java:826)\n at org.apache.tools.ant.Main.startAnt(Main.java:235)\n at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)\n at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)\n</code></pre>\n\n<p>I got it resolved by removing classpath entry for commons-codec-1.3.jar, there was a mismatch in version of this jar with the one comes with Jasper.</p>\n"
},
{
"answer_id": 57858197,
"author": "Eduardo Morales",
"author_id": 11731597,
"author_profile": "https://Stackoverflow.com/users/11731597",
"pm_score": 0,
"selected": false,
"text": "<p>write on file:</p>\n\n<pre><code>{Wildfly-home}\\modules\\system\\layers\\base\\org\\picketbox\\main \n</code></pre>\n\n<p>into dependencies next: <code><module name=\"sun.jdk\"/></code></p>\n"
},
{
"answer_id": 60530452,
"author": "CoolMind",
"author_id": 2914140,
"author_profile": "https://Stackoverflow.com/users/2914140",
"pm_score": 1,
"selected": false,
"text": "<p>After updating <code>Gradle</code> in <em>Android Studio 3.6.1</em> crashes happened on API 19 in release build.</p>\n\n<p>There was a <code>Glide</code> library <a href=\"https://github.com/bumptech/glide/issues/3152#issuecomment-601699075\" rel=\"nofollow noreferrer\">error</a>. Solution is to rewrite <a href=\"https://github.com/bumptech/glide/blob/master/library/proguard-rules.txt\" rel=\"nofollow noreferrer\">proguard-rules.txt</a>.</p>\n\n<p>Also downgrading <code>Gradle</code> works (<code>classpath 'com.android.tools.build:gradle:3.5.3'</code>), but it is an outdated solution, don't use it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15490/"
]
| I'm investigating the following `java.lang.VerifyError`
```
java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴Mt̴MÚw€mçw€mp:”MŒŒ
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
```
It occurs when the jboss server in which the servlet is deployed is started.
It is compiled with jdk-1.5.0\_11 and I tried to recompile it with jdk-1.5.0\_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.
When I changed the method name and got the following error:
```
java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources ØÅN|ØÅNÚw€mçw€mX#ÖM|XÔM
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
```
You can see that more of the method signature is shown.
The actual method signature is
```
private PgasePdfTable getMonthData(int month, int year, Collection dayTypes,
Collection calendarDays,
HashMap bcSpecialDays,
Collection activityPeriods,
Locale locale, MessageResources resources) throws Exception {
```
I already tried looking at it with `javap` and that gives the method signature as it should be.
When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.
The rest of the application runs okay, only that one servlet is out of order.
Any ideas where to look would be helpful. | `java.lang.VerifyError` can be the result when you have compiled against a different library than you are using at runtime.
For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in `org.apache.*` namespace) were found at runtime, so `ClassNotFoundException` was ***not*** the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time.
Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws `VerifyError` when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns `String` and then stores that return value in a field that holds a `List`. |
100,161 | <p>I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.</p>
<p>I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?</p>
<p>EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back.</p>
| [
{
"answer_id": 100180,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 2,
"selected": false,
"text": "<p>Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.\nConsider using this startup parameters when running eclipse:</p>\n\n<pre><code>-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M\n</code></pre>\n"
},
{
"answer_id": 101164,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>With those options, I manage to limit the memory used to 700Mo (which is quite high, but still workable with my 2 Go)</p>\n\n<pre><code>-vmargs\n-Xms128m\n-Xmx384m\n-Xssv2m\n-XX:PermSize=128m\n-XX:MaxPermSize=128m\n-XX:CompileThreshold=5\n-XX:+UseParallelGC\n-Dcom.sun.management.jmxremote\n</code></pre>\n\n<p>And consider also to launch</p>\n\n<pre><code>C:\\[jdk1.6.0_0x path]\\bin\\jconsole.exe\n</code></pre>\n\n<p>And choose 'Connection / New connection / 'eclipse' to monitor the memory used by eclipse<br>\n(which is why I use '-Dcom.sun.management.jmxremote')</p>\n\n<p>Other options are available <a href=\"http://my.opera.com/karmazilla/blog/2007/03/13/good-riddance-permgen-outofmemoryerror\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 113194,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 2,
"selected": false,
"text": "<p>The more plugins you have, the more memory Eclipse will consume. 3.4 includes more plugins by default than 3.3, and so on, and so on, as more and more developers clamor for features to be included.</p>\n\n<p>Go to Window->Show View, and start typing \"plug in\", and one of the options will be the Plug In Registry. Open that view, and click on the arrow to show active plugins only. These are the plugins actually loaded into memory. My Eclipse 3.3 currently has 89 out of 445 or so plugins loaded. You can then selectively start disabling plugins from the Help menu, once you see which ones you won't use (right now, for instance, I\"m not using Mylyn, but I hope to in the future).</p>\n"
},
{
"answer_id": 131719,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>To add to my previous answer and to your recent update:</p>\n\n<blockquote>\n <p>Eclipse just hangs for ~30 seconds, then magically comes back.</p>\n</blockquote>\n\n<p>That is usually a sign for a failed network access with a timeout (and the associated 'freeze' while the application is waiting for said timeout).</p>\n\n<p>try typing 'net use' in a DOS prompt, and check if you have net path declared there, some of them you could get rid off ('net use /D aUselessPath'). To be sure, check also the shares that you declare (net share).</p>\n\n<hr>\n\n<p>Since you are with Vista, try also to deactivate <strong><a href=\"http://www.speedyvista.com/services/Superfetch.php\" rel=\"nofollow noreferrer\">superfetch</a></strong> and see if you still experience those freezes (both for eclipse and Firefox).<br>\nOpen a CMD prompt with administrative privileges and enter \"net stop superfetch\" to stop the SuperFetch service.<br>\nIt is not a good long-term solution though, just a quick check to make. Superfetch should be kept on, and will actually restart on your next reboot, since the service is set to start automatically at each Windows session.<br>\nAgain, this is just to see if there is any connection between that service and your freezes.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
]
| I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.
I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?
EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back. | Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.
Consider using this startup parameters when running eclipse:
```
-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M
``` |
100,170 | <p>I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.</p>
<p>What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple. </p>
<p>Is there a way to check if there are any symlinks pointing to a particular folder?</p>
| [
{
"answer_id": 100200,
"author": "skymt",
"author_id": 18370,
"author_profile": "https://Stackoverflow.com/users/18370",
"pm_score": 7,
"selected": true,
"text": "<p>I'd use the find command.</p>\n\n<pre><code>find . -lname /particular/folder\n</code></pre>\n\n<p>That will recursively search the current directory for symlinks to <code>/particular/folder</code>. Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called \"folder\":</p>\n\n<pre><code>find . -lname '*folder'\n</code></pre>\n\n<p>From there you would need to weed out any false positives.</p>\n"
},
{
"answer_id": 100203,
"author": "bfabry",
"author_id": 924607,
"author_profile": "https://Stackoverflow.com/users/924607",
"pm_score": 1,
"selected": false,
"text": "<pre><code>find / -lname 'fullyqualifiedpathoffile'\n</code></pre>\n"
},
{
"answer_id": 100205,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "<p>For hardlinks, you can get the inode of your directory with one of the \"ls\" options (<code>-i</code>, I think).</p>\n\n<p>Then a <code>find</code> with <code>-inum</code> will locate all common hardlinks.</p>\n\n<p>For softlinks, you may have to do an <code>ls -l</code> on all files looking for the text after \"->\" and normalizing it to make sure it's an absolute path.</p>\n"
},
{
"answer_id": 100208,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>There isn't really any direct way to check for such symlinks. Consider that you might have a filesystem that isn't mounted all the time (eg. an external USB drive), which could contain symlinks to another volume on the system.</p>\n\n<p>You could do something with:</p>\n\n<pre><code>for a in `find / -type l`; do echo \"$a -> `readlink $a`\"; done | grep destfolder\n</code></pre>\n\n<p>I note that FreeBSD's <code>find</code> does not support the <code>-lname</code> option, which is why I ended up with the above.</p>\n"
},
{
"answer_id": 100212,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 2,
"selected": false,
"text": "<p>Apart from looking at all other folders if there are links pointing to the original folder, I don't think it is possible. If it is, I would be interested.</p>\n"
},
{
"answer_id": 3892002,
"author": "no1uknow",
"author_id": 470396,
"author_profile": "https://Stackoverflow.com/users/470396",
"pm_score": 3,
"selected": false,
"text": "<pre><code>find . -type l -printf '%p -> %l\\n'\n</code></pre>\n"
},
{
"answer_id": 9682527,
"author": "JJK",
"author_id": 1266260,
"author_profile": "https://Stackoverflow.com/users/1266260",
"pm_score": 3,
"selected": false,
"text": "<p>You can audit symlinks with <a href=\"http://linux.die.net/man/8/symlinks\" rel=\"nofollow noreferrer\">the <code>symlinks</code> program</a> written by Mark Lord -- it will scan an entire filesystem, normalize symlink paths to absolute form and print them to stdout.</p>\n"
},
{
"answer_id": 20904085,
"author": "Lunar Mushrooms",
"author_id": 986020,
"author_profile": "https://Stackoverflow.com/users/986020",
"pm_score": 1,
"selected": false,
"text": "<pre><code>find /foldername -type l -exec ls -lad {} \\;\n</code></pre>\n"
},
{
"answer_id": 68560106,
"author": "Thomas Tempelmann",
"author_id": 43615,
"author_profile": "https://Stackoverflow.com/users/43615",
"pm_score": 0,
"selected": false,
"text": "<p>To any programmers looking here (cmdline tool questions probably should instead go to unix.stackexchange.com nowadays):</p>\n<p>You should know that the Linux/BSD function <code>fts_open()</code> gives you an easy-to-use iterator for traversing all sub directory contents while also detecting such symlink recursions.</p>\n<p>Most command line tools use this function to handle this case for them. Those that don't often have trouble with symlink recursions because doing this "by hand" is difficult (any anyone being aware of it should just use the above function instead).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
| I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.
What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple.
Is there a way to check if there are any symlinks pointing to a particular folder? | I'd use the find command.
```
find . -lname /particular/folder
```
That will recursively search the current directory for symlinks to `/particular/folder`. Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called "folder":
```
find . -lname '*folder'
```
From there you would need to weed out any false positives. |
100,209 | <p>I have an OWL ontology and I am using Pellet to do reasoning over it. Like most ontologies it starts by including various standard ontologies:</p>
<pre><code><rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:owl="http://www.w3.org/2002/07/owl#">
</code></pre>
<p>I know that some reasoners have these standard ontologies 'built-in', but Pellet doesn't. Is there any way I can continue to use Pellet when I am offline & can't access them? (Or if their URL goes offline, like dublincore.org did last week for routine maintenance)</p>
| [
{
"answer_id": 103736,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 1,
"selected": false,
"text": "<p>Make local copies of the four files and replace the remote URLs with local URIs (i.e. file://... or serve them from your own box: <a href=\"http://localhost..\" rel=\"nofollow noreferrer\">http://localhost..</a>.).</p>\n"
},
{
"answer_id": 202158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Pellet recognizes all of these namespaces when loading and should not attempt to dereference the URIs. If it does, it suggests the application using Pellet is doing something incorrectly.</p>\n\n<p>You may find more help on <a href=\"http://lists.owldl.com/mailman/listinfo/pellet-users/\" rel=\"nofollow noreferrer\">the pellet-users mailing list</a>.</p>\n"
},
{
"answer_id": 915857,
"author": "Kendall Clark",
"author_id": 54661,
"author_profile": "https://Stackoverflow.com/users/54661",
"pm_score": 2,
"selected": false,
"text": "<p>A generalized solution to this problem -- access to ontologies w/out public Web access -- is described in <a href=\"http://clarkparsia.com/weblog/2009/03/16/local-ontology-repositories-with-pellet/\" rel=\"nofollow noreferrer\">Local Ontology Repositories with Pellet</a>. Enjoy.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12405/"
]
| I have an OWL ontology and I am using Pellet to do reasoning over it. Like most ontologies it starts by including various standard ontologies:
```
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:owl="http://www.w3.org/2002/07/owl#">
```
I know that some reasoners have these standard ontologies 'built-in', but Pellet doesn't. Is there any way I can continue to use Pellet when I am offline & can't access them? (Or if their URL goes offline, like dublincore.org did last week for routine maintenance) | Pellet recognizes all of these namespaces when loading and should not attempt to dereference the URIs. If it does, it suggests the application using Pellet is doing something incorrectly.
You may find more help on [the pellet-users mailing list](http://lists.owldl.com/mailman/listinfo/pellet-users/). |
100,210 | <p>Given a <code>datetime.time</code> value in Python, is there a standard way to add an integer number of seconds to it, so that <code>11:34:59</code> + 3 = <code>11:35:02</code>, for example?</p>
<p>These obvious ideas don't work:</p>
<pre><code>>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
</code></pre>
<p>In the end I have written functions like this:</p>
<pre><code>def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
</code></pre>
<p>I can't help thinking that I'm missing an easier way to do this though.</p>
<h3>Related</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent">python time + timedelta equivalent</a></li>
</ul>
| [
{
"answer_id": 100250,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding a <code>datetime.datetime</code> to a <code>datetime.timedelta</code>. If you only want the time portion, you can call the <code>time()</code> method on the resultant <code>datetime.datetime</code> object to get it.</p>\n"
},
{
"answer_id": 100345,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 10,
"selected": true,
"text": "<p>You can use full <code>datetime</code> variables with <code>timedelta</code>, and by providing a dummy date then using <code>time</code> to just get the time value.</p>\n\n<p>For example:</p>\n\n<pre><code>import datetime\na = datetime.datetime(100,1,1,11,34,59)\nb = a + datetime.timedelta(0,3) # days, seconds, then other fields.\nprint(a.time())\nprint(b.time())\n</code></pre>\n\n<p>results in the two values, three seconds apart:</p>\n\n<pre><code>11:34:59\n11:35:02\n</code></pre>\n\n<p>You could also opt for the more readable</p>\n\n<pre><code>b = a + datetime.timedelta(seconds=3)\n</code></pre>\n\n<p>if you're so inclined.</p>\n\n<hr>\n\n<p>If you're after a function that can do this, you can look into using <code>addSecs</code> below:</p>\n\n<pre><code>import datetime\n\ndef addSecs(tm, secs):\n fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)\n fulldate = fulldate + datetime.timedelta(seconds=secs)\n return fulldate.time()\n\na = datetime.datetime.now().time()\nb = addSecs(a, 300)\nprint(a)\nprint(b)\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code> 09:11:55.775695\n 09:16:55\n</code></pre>\n"
},
{
"answer_id": 100404,
"author": "unmounted",
"author_id": 11596,
"author_profile": "https://Stackoverflow.com/users/11596",
"pm_score": 5,
"selected": false,
"text": "<p>One little thing, might add clarity to override the default value for seconds</p>\n\n<pre><code>>>> b = a + datetime.timedelta(seconds=3000)\n>>> b\ndatetime.datetime(1, 1, 1, 12, 24, 59)\n</code></pre>\n"
},
{
"answer_id": 100776,
"author": "Paul Stephenson",
"author_id": 5536,
"author_profile": "https://Stackoverflow.com/users/5536",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks to @Pax Diablo, @bvmou and @Arachnid for the suggestion of using full datetimes throughout. If I have to accept datetime.time objects from an external source, then this seems to be an alternative <code>add_secs_to_time()</code> function:</p>\n\n<pre><code>def add_secs_to_time(timeval, secs_to_add):\n dummy_date = datetime.date(1, 1, 1)\n full_datetime = datetime.datetime.combine(dummy_date, timeval)\n added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)\n return added_datetime.time()\n</code></pre>\n\n<p>This verbose code can be compressed to this one-liner:</p>\n\n<pre><code>(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()\n</code></pre>\n\n<p>but I think I'd want to wrap that up in a function for code clarity anyway.</p>\n"
},
{
"answer_id": 101947,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 6,
"selected": false,
"text": "<p>As others here have stated, you can just use full datetime objects throughout:</p>\n\n<pre><code>from datetime import datetime, date, time, timedelta\nsometime = time(8,00) # 8am\nlater = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()\n</code></pre>\n\n<p>However, I think it's worth explaining why full datetime objects are required. Consider what would happen if I added 2 hours to 11pm. What's the correct behavior? An exception, because you can't have a time larger than 11:59pm? Should it wrap back around?</p>\n\n<p>Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you're not allowed to add timedelta objects to time objects.</p>\n"
},
{
"answer_id": 6839259,
"author": "rescdsk",
"author_id": 88198,
"author_profile": "https://Stackoverflow.com/users/88198",
"pm_score": 3,
"selected": false,
"text": "<p>If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends <code>datetime.time</code> with the ability to do arithmetic. When you go past midnight, it wraps around zero. Now, \"What time will it be, 24 hours from now\" has a lot of corner cases, including daylight savings time, leap seconds, historical timezone changes, and so on. But sometimes you really do need the simple case, and that's what this will do.</p>\n\n<p>Your example would be written:</p>\n\n<pre><code>>>> import datetime\n>>> import nptime\n>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)\nnptime(11, 35, 2)\n</code></pre>\n\n<p><code>nptime</code> inherits from <code>datetime.time</code>, so any of those methods should be usable, too.</p>\n\n<p>It's available from PyPi as <code>nptime</code> (\"non-pedantic time\"), or on GitHub: <a href=\"https://github.com/tgs/nptime\" rel=\"noreferrer\">https://github.com/tgs/nptime</a></p>\n"
},
{
"answer_id": 46653858,
"author": "Bart Van Loon",
"author_id": 8485638,
"author_profile": "https://Stackoverflow.com/users/8485638",
"pm_score": 3,
"selected": false,
"text": "<p>For completeness' sake, here's the way to do it with <a href=\"http://arrow.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\"><code>arrow</code></a> (better dates and times for Python):</p>\n\n<pre><code>sometime = arrow.now()\nabitlater = sometime.shift(seconds=3)\n</code></pre>\n"
},
{
"answer_id": 48315879,
"author": "user2387567",
"author_id": 2387567,
"author_profile": "https://Stackoverflow.com/users/2387567",
"pm_score": 4,
"selected": false,
"text": "<p>You cannot simply add number to <code>datetime</code> because it's unclear what unit is used: seconds, hours, weeks...</p>\n\n<p>There is <code>timedelta</code> class for manipulations with date and time. <code>datetime</code> minus <code>datetime</code> gives <code>timedelta</code>, <code>datetime</code> plus <code>timedelta</code> gives <code>datetime</code>, two <code>datetime</code> objects cannot be added although two <code>timedelta</code> can.</p>\n\n<p>Create <code>timedelta</code> object with how many seconds you want to add and add it to <code>datetime</code> object:</p>\n\n<pre><code>>>> from datetime import datetime, timedelta\n>>> t = datetime.now() + timedelta(seconds=3000)\n>>> print(t)\ndatetime.datetime(2018, 1, 17, 21, 47, 13, 90244)\n</code></pre>\n\n<p>There is same concept in C++: <code>std::chrono::duration</code>.</p>\n"
},
{
"answer_id": 57498235,
"author": "blthayer",
"author_id": 11052174,
"author_profile": "https://Stackoverflow.com/users/11052174",
"pm_score": 0,
"selected": false,
"text": "<p>Old question, but I figured I'd throw in a function that handles timezones. The key parts are passing the <code>datetime.time</code> object's <code>tzinfo</code> attribute into combine, and then using <code>timetz()</code> instead of <code>time()</code> on the resulting dummy datetime. This answer partly inspired by the other answers here.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def add_timedelta_to_time(t, td):\n \"\"\"Add a timedelta object to a time object using a dummy datetime.\n\n :param t: datetime.time object.\n :param td: datetime.timedelta object.\n\n :returns: datetime.time object, representing the result of t + td.\n\n NOTE: Using a gigantic td may result in an overflow. You've been\n warned.\n \"\"\"\n # Create a dummy date object.\n dummy_date = date(year=100, month=1, day=1)\n\n # Combine the dummy date with the given time.\n dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)\n\n # Add the timedelta to the dummy datetime.\n new_datetime = dummy_datetime + td\n\n # Return the resulting time, including timezone information.\n return new_datetime.timetz()\n</code></pre>\n\n<p>And here's a really simple test case class (using built-in <code>unittest</code>):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import unittest\nfrom datetime import datetime, timezone, timedelta, time\n\nclass AddTimedeltaToTimeTestCase(unittest.TestCase):\n \"\"\"Test add_timedelta_to_time.\"\"\"\n\n def test_wraps(self):\n t = time(hour=23, minute=59)\n td = timedelta(minutes=2)\n t_expected = time(hour=0, minute=1)\n t_actual = add_timedelta_to_time(t=t, td=td)\n self.assertEqual(t_expected, t_actual)\n\n def test_tz(self):\n t = time(hour=4, minute=16, tzinfo=timezone.utc)\n td = timedelta(hours=10, minutes=4)\n t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)\n t_actual = add_timedelta_to_time(t=t, td=td)\n self.assertEqual(t_expected, t_actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n"
},
{
"answer_id": 65920435,
"author": "VengaVenga",
"author_id": 4798335,
"author_profile": "https://Stackoverflow.com/users/4798335",
"pm_score": 2,
"selected": false,
"text": "<p>In a real world environment it's never a good idea to work solely with <code>time</code>, always use <code>datetime</code>, even better <code>utc</code>, to avoid conflicts like overnight, daylight saving, different timezones between user and server etc.</p>\n<p>So I'd recommend this approach:</p>\n<pre><code>import datetime as dt\n\n_now = dt.datetime.now() # or dt.datetime.now(dt.timezone.utc)\n_in_5_sec = _now + dt.timedelta(seconds=5)\n\n# get '14:39:57':\n_in_5_sec.strftime('%H:%M:%S')\n</code></pre>\n"
},
{
"answer_id": 71674257,
"author": "Ziggity",
"author_id": 17013800,
"author_profile": "https://Stackoverflow.com/users/17013800",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't already have a timedelta object, another possibility would be to just initialize a new time object instead with the attributes of the old one and add values where needed:</p>\n<pre><code> new_time:time = time(\n hour=curr_time.hour + n_hours,\n minute=curr_time.minute + n_minutes,\n seconds=curr_time.second + n_seconds\n )\n</code></pre>\n<p>Admittedly this only works if you make a few assumptions about your values, since overflow is not handled here. But I just thought it was worth to keep this in mind\nas it can save a line or two</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5536/"
]
| Given a `datetime.time` value in Python, is there a standard way to add an integer number of seconds to it, so that `11:34:59` + 3 = `11:35:02`, for example?
These obvious ideas don't work:
```
>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
```
In the end I have written functions like this:
```
def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
```
I can't help thinking that I'm missing an easier way to do this though.
### Related
* [python time + timedelta equivalent](https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent) | You can use full `datetime` variables with `timedelta`, and by providing a dummy date then using `time` to just get the time value.
For example:
```
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
```
results in the two values, three seconds apart:
```
11:34:59
11:35:02
```
You could also opt for the more readable
```
b = a + datetime.timedelta(seconds=3)
```
if you're so inclined.
---
If you're after a function that can do this, you can look into using `addSecs` below:
```
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
```
This outputs:
```
09:11:55.775695
09:16:55
``` |
100,211 | <p>I just installed Glassfish V2 on my local machine just to play around with it.</p>
<p>I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.</p>
<p>For instance,</p>
<pre><code>http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC
</code></pre>
<p>How do I retrieve the "name" param in my Java code?</p>
| [
{
"answer_id": 100396,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 3,
"selected": true,
"text": "<p>Like this:</p>\n\n<pre><code>@Path(\"/helloWorld\")\n@Consumes({\"application/xml\", \"application/json\"})\n@Produces({\"application/xml\", \"application/json\"})\n@Singleton\npublic class MyService {\n @GET\n public String getRequest(@QueryParam(\"name\") String name) {\n return \"Name was \" + name;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100424,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 0,
"selected": false,
"text": "<p>By putting:</p>\n\n<pre><code>@Context\nprivate UriInfo context;\n</code></pre>\n\n<p>in your HelloWorld class, can you access the</p>\n\n<pre><code>context.getQueryParameters() ;\n</code></pre>\n\n<p>method to get a map of parameters?</p>\n\n<p><a href=\"http://docs.sun.com/app/docs/doc/820-4867/ggrby?a=view\" rel=\"nofollow noreferrer\">http://docs.sun.com/app/docs/doc/820-4867/ggrby?a=view</a></p>\n\n<p>Seems to suggest you can :)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4004/"
]
| I just installed Glassfish V2 on my local machine just to play around with it.
I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.
For instance,
```
http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC
```
How do I retrieve the "name" param in my Java code? | Like this:
```
@Path("/helloWorld")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
@Singleton
public class MyService {
@GET
public String getRequest(@QueryParam("name") String name) {
return "Name was " + name;
}
}
``` |
100,216 | <p>I'm trying to integrate running Fitnesse tests from MSBuild im my nightly build on TFS.</p>
<p>In an attempt to make it self contained I would like to start the seleniumRC server only when it's needed from fitness.</p>
<p>I've seen that there is a "Command Line Fixture" but it's written in java can I use that?</p>
| [
{
"answer_id": 100638,
"author": "David Laing",
"author_id": 13238,
"author_profile": "https://Stackoverflow.com/users/13238",
"pm_score": 0,
"selected": false,
"text": "<p>What about writing a simple .NET app that does a Process.Start(\"selenumRC commandline\") which gets run by your build script?</p>\n\n<p>If you aren't too far down the Selenium route; might I suggest that you look at similar .NET browser automation tools; specifically WatiN or ArtOfTest. The \"stacks\" in these are completely .NET, so getting them running on different machines is much easier.</p>\n"
},
{
"answer_id": 100647,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 2,
"selected": true,
"text": "<p>I think you might be able to. You can call any process easily in MSBuild using the <a href=\"http://msdn.microsoft.com/en-us/library/x8zx72cd.aspx\" rel=\"nofollow noreferrer\"></a> task. However, the problem with doing this is that the exec task will wait for the Selinium process to finish before continuing, which is not the bahaviour you want. You want to run the process, keep it running during your build and then tear it down as your build finishes.</p>\n\n<p>Therefore, I think you are probably going to need to create a custom MSBuild task to do this. See the following post for an example of a tasks that someone has created that will run asynchronously returning control back to the build script:</p>\n\n<p><a href=\"http://blog.eleutian.com/2007/03/01/AsyncExecMsBuildTask.aspx\" rel=\"nofollow noreferrer\">http://blog.eleutian.com/2007/03/01/AsyncExecMsBuildTask.aspx</a></p>\n\n<p>And for an example of calling a Java program from MSBuild (but in this case synchronously) take a look at my task that calls <a href=\"http://teamprise.com/products/build/\" rel=\"nofollow noreferrer\">Ant from MSBuild</a> here </p>\n\n<p><a href=\"http://teamprise.com/products/build/\" rel=\"nofollow noreferrer\">http://teamprise.com/products/build/</a></p>\n\n<p>As part of your MSBuild task, you will want to output the process id that you created to an output property so that at the end of your build script you can call another custom MSBuild task that kills the process. It can do this by looking for the process id passed in as a variable in MSBuild and then call <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx\" rel=\"nofollow noreferrer\">Process.Kill</a> method i.e.</p>\n\n<pre><code>Process process = Process.GetProcessById(ProcessId);\nprocess.Kill();\n</code></pre>\n\n<p>That said, you would need to be careful to ensure that your kill task was always executed in MSBuild by making sure it was included during error paths etc in the build. You could probably make things a bit more resilient by making the selenium RC starter task look for other seleniumRC processes and killing them before starting a new one - that way if a process didn't get closed properly for some reason, it would only run until the next build.</p>\n\n<p>Anyway - my answer sounds like a lot of work so hopefully someone else will come up with an easier way. You might be able to create the seleniumRC process in the test suite start up of the FitNesse tests and kill it in the suite tear down, or you might be able to write a custom task that extends your FitNesse runner tasks and fires up seleiniumRC asynronously before running the test process and then kills it afterwards.</p>\n\n<p>Good luck,</p>\n\n<p>Martin.</p>\n"
},
{
"answer_id": 119925,
"author": "HAXEN",
"author_id": 11434,
"author_profile": "https://Stackoverflow.com/users/11434",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for your replies!</p>\n\n<p>This is how I've done so far.</p>\n\n<p>I made a fit fixture (very simple) that starts a process with the supplied command line, in my case startSelenium.bat. The fixture returns the ProcessID so I can store that in my fitnesse context and close that session later.</p>\n\n<p>I can now make a SuiteSetUp page in my fitnesse test that looks like this.</p>\n\n<p>|RunCommandFixture|</p>\n\n<p>|Commandline|RunCommand?|</p>\n\n<p>|C:\\Projects...\\startSeleniumRC.bat|>>seleniumprocess|</p>\n\n<p>and a SuiteTearDown like this</p>\n\n<p>|RunCommandFixture|</p>\n\n<p>|ProcessID|StopCommand?|\n|<\n\n<p>That works for me. No selenium RC starts by request from my fitnesse test.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11434/"
]
| I'm trying to integrate running Fitnesse tests from MSBuild im my nightly build on TFS.
In an attempt to make it self contained I would like to start the seleniumRC server only when it's needed from fitness.
I've seen that there is a "Command Line Fixture" but it's written in java can I use that? | I think you might be able to. You can call any process easily in MSBuild using the task. However, the problem with doing this is that the exec task will wait for the Selinium process to finish before continuing, which is not the bahaviour you want. You want to run the process, keep it running during your build and then tear it down as your build finishes.
Therefore, I think you are probably going to need to create a custom MSBuild task to do this. See the following post for an example of a tasks that someone has created that will run asynchronously returning control back to the build script:
<http://blog.eleutian.com/2007/03/01/AsyncExecMsBuildTask.aspx>
And for an example of calling a Java program from MSBuild (but in this case synchronously) take a look at my task that calls [Ant from MSBuild](http://teamprise.com/products/build/) here
<http://teamprise.com/products/build/>
As part of your MSBuild task, you will want to output the process id that you created to an output property so that at the end of your build script you can call another custom MSBuild task that kills the process. It can do this by looking for the process id passed in as a variable in MSBuild and then call [Process.Kill](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) method i.e.
```
Process process = Process.GetProcessById(ProcessId);
process.Kill();
```
That said, you would need to be careful to ensure that your kill task was always executed in MSBuild by making sure it was included during error paths etc in the build. You could probably make things a bit more resilient by making the selenium RC starter task look for other seleniumRC processes and killing them before starting a new one - that way if a process didn't get closed properly for some reason, it would only run until the next build.
Anyway - my answer sounds like a lot of work so hopefully someone else will come up with an easier way. You might be able to create the seleniumRC process in the test suite start up of the FitNesse tests and kill it in the suite tear down, or you might be able to write a custom task that extends your FitNesse runner tasks and fires up seleiniumRC asynronously before running the test process and then kills it afterwards.
Good luck,
Martin. |
100,228 | <p>I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements <strong>must</strong> be present, and there could be more than one of them.</p>
<p>I tried doing the following, but XMLSpy complains that "The content model contains the elements <element name="DateConstant"> and <element name="DateConstant"> which cannot be uniquely determined.":</p>
<pre><code> <xs:choice>
<xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:choice>
</code></pre>
<p>Can this be done (and if so, how)?</p>
<p>Some clarification:
I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either.
Gizmo's answer matches my requirements, but it's impractical for a larger number of elements.
Hurst's answer allows two or more elements of the same name, which I don't want.</p>
| [
{
"answer_id": 100313,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 6,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code><xs:choice>\n <xs:sequence>\n <xs:element name=\"Elem1\" />\n <xs:element name=\"Elem2\" minOccurs=\"0\" />\n <xs:element name=\"Elem3\" minOccurs=\"0\" />\n </xs:sequence>\n <xs:sequence>\n <xs:element name=\"Elem2\" />\n <xs:element name=\"Elem3\" minOccurs=\"0\" />\n </xs:sequence>\n <xs:element name=\"Elem3\" />\n</xs:choice>\n</code></pre>\n\n<p>Doing so, you force either to choose the first element and then the rest is optional, either the second element and the rest is optional, either the third element.</p>\n\n<p>This should do what you want, I hope.</p>\n\n<p>Of course, you could place the sub-sequences into groups, to avoid to duplicate an element in each sequence if you realize you miss one.</p>\n"
},
{
"answer_id": 100589,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 4,
"selected": false,
"text": "<p>According to the technical article on MSDN titled <strong>Understanding XML Schema</strong>\nat <a href=\"http://msdn.microsoft.com/en-us/library/aa468557.aspx#understandxsd_topic5\" rel=\"noreferrer\" title=\"Defining Complex Types\">http://msdn.microsoft.com/en-us/library/aa468557.aspx#understandxsd_topic5</a>\nyou can take advantage of constraints such as <em>minOccurs</em> on the choice definition (compositor) itself:</p>\n\n<p><em>\"Using occurrence constraints on a compositor applies to the entire group as a whole\"</em></p>\n\n<p>(See the more sophisticated example that uses nested complex types and the AuthorType example)</p>\n\n<p>You stated your requirement as \"at least one of the elements must be present, and there could be more than one of them\". Thus, I propose you try the following:</p>\n\n<pre><code><xs:choice minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:element name=\"DateConstant\" type=\"...\"/>\n <xs:element name=\"TimeConstant\" type=\"...\"/>\n</xs:choice>\n</code></pre>\n"
},
{
"answer_id": 14313107,
"author": "Enigmatic",
"author_id": 1357443,
"author_profile": "https://Stackoverflow.com/users/1357443",
"pm_score": 2,
"selected": false,
"text": "<p>@hurst,</p>\n\n<p>Unfortunately you have failed to understand the original question. Placing minOccurs=\"1\" on the choice is satisfied automatically when ALL elements that have minOccurs=\"0\" are contained as options.</p>\n\n<p>Thus you have failed to account for the \"at least one\" required by the original poster, because no elements correctly satisfies 1 occurrance of two completely optional elements.</p>\n\n<p>So far I am unable to find a solution to this as minOccur/maxOccur both relate to the group in which they are defined and DO NOT relate to an overall number of nodes. Nor can you use the choice element to define the same named element more than once or it becomes \"ambiguous\". I have seen some examples use references instead of elements of a specific type, but I believe this fails the microsoft XSD parser.</p>\n\n<pre><code><xs:choice minOccurs=\"1\" maxOccurs=\"1\">\n <xs:sequence minOccurs=\"1\" maxOccurs=\"1\">\n <xs:element name=\"Elem1\" minOccurs=\"1\" maxOccurs=\"1\" />\n <xs:element name=\"Elem2\" minOccurs=\"0\" maxOccurs=\"1\" />\n </xs:sequence>\n <xs:sequence >\n <xs:element name=\"Elem2\" minOccurs=\"1\" maxOccurs=\"1\" />\n </xs:sequence>\n</xs:choice>\n</code></pre>\n\n<p>Here you can see that either you have the first sequence (which MUST have Elem1 but may have Elem2 optionally), or you have the second sequence (which MUST have Elem2).</p>\n\n<p>Hence you now have \"any one or more\" of these 2 elements. Of course this gets exponentially more complex the more options you have as you need to provide additional choices for all possible combinations.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18603/"
]
| I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements **must** be present, and there could be more than one of them.
I tried doing the following, but XMLSpy complains that "The content model contains the elements <element name="DateConstant"> and <element name="DateConstant"> which cannot be uniquely determined.":
```
<xs:choice>
<xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:choice>
```
Can this be done (and if so, how)?
Some clarification:
I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either.
Gizmo's answer matches my requirements, but it's impractical for a larger number of elements.
Hurst's answer allows two or more elements of the same name, which I don't want. | Try this:
```
<xs:choice>
<xs:sequence>
<xs:element name="Elem1" />
<xs:element name="Elem2" minOccurs="0" />
<xs:element name="Elem3" minOccurs="0" />
</xs:sequence>
<xs:sequence>
<xs:element name="Elem2" />
<xs:element name="Elem3" minOccurs="0" />
</xs:sequence>
<xs:element name="Elem3" />
</xs:choice>
```
Doing so, you force either to choose the first element and then the rest is optional, either the second element and the rest is optional, either the third element.
This should do what you want, I hope.
Of course, you could place the sub-sequences into groups, to avoid to duplicate an element in each sequence if you realize you miss one. |
100,235 | <p>For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A FileWatcher is not required but it could be useful. </p>
<pre><code>class PersistentDictionary<T,V> : IDictionary<T,V>
{
public PersistentDictionary(string filename)
{
}
}
</code></pre>
<p>Requirements: </p>
<ul>
<li>Open Source, with no dependency on native code (no sqlite) </li>
<li>Ideally a very short and simple implementation</li>
<li>When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.</li>
</ul>
<p><strong>Similar Questions</strong> </p>
<ul>
<li><a href="https://stackoverflow.com/questions/108435/persistent-binary-tree-hash-table-in-net">Persistent Binary Tree / Hash table in .Net</a></li>
<li><a href="https://stackoverflow.com/questions/408401/disk-backed-dictionary-cache-for-c">Disk backed dictionary/cache for c#</a></li>
<li><a href="http://izlooite.blogspot.com/2011/04/persistent-dictionary.html" rel="noreferrer"><code>PersistentDictionary<Key,Value></code></a></li>
</ul>
| [
{
"answer_id": 100672,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds cool, but how will you get around changes to the stored value (if it was a reference type) itself? If its immutable then all is well but if not you're kinda stuffed :-)</p>\n\n<p>If you're not dealing with immutable values, I would suspect a better approach would be to handle persistence at the value level and to just rebuild the dictionary as necessary.</p>\n\n<p>(edited to add a clarification)</p>\n"
},
{
"answer_id": 100682,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>Just use serialization. Look at the BinaryFormatter class.</p>\n"
},
{
"answer_id": 168381,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of anything to solve your problem. It will need to be a fixed size structure, so that you can meet the requirements of being able to rewrite records without rewriting the entire file.</p>\n\n<p>This means normal strings are out.</p>\n"
},
{
"answer_id": 176561,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "<p>Like Douglas said, you need to know the fixed size of your types (both T and V). Also, variable-length instances in the object grid referenced by any of those instances are out.</p>\n\n<p>Still, implementing a dictionary backed by a file is quite simple and you can use the <code>BinaryWriter</code> class to write the types to disk, after inheriting or encapsulating the <code>Dictionary<TKey, TValue></code> class.</p>\n"
},
{
"answer_id": 482984,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 6,
"selected": true,
"text": "<ul>\n<li><p><a href=\"http://bplusdotnet.sourceforge.net/\" rel=\"noreferrer\"><strong>bplustreedotnet</strong></a></p>\n\n<p>The bplusdotnet package is a library of cross compatible data structure implementations in C#, java, and Python which are useful for applications which need to store and retrieve persistent information. The bplusdotnet data structures make it easy to <strong>store string keys associated with values permanently</strong>.</p></li>\n<li><p><a href=\"http://www.codeplex.com/ManagedEsent\" rel=\"noreferrer\"><strong>ESENT Managed Interface</strong></a></p>\n\n<p><em>Not 100% managed code but it's worth mentioning it as unmanaged library itself is already part of every windows XP/2003/Vista/7 box</em></p>\n\n<p>ESENT is an embeddable database storage engine (ISAM) which is part of Windows. It provides reliable, transacted, concurrent, high-performance data storage with row-level locking, write-ahead logging and snapshot isolation. This is a managed wrapper for the ESENT Win32 API.</p></li>\n<li><p><a href=\"https://github.com/github/Akavache\" rel=\"noreferrer\"><strong>Akavache</strong></a></p>\n\n<p>*Akavache is an asynchronous, persistent key-value cache created for writing native desktop and mobile applications in C#. Think of it like memcached for desktop apps.</p></li>\n</ul>\n\n<p><strike>\n- <a href=\"http://www.itu.dk/research/c5/\" rel=\"noreferrer\"><strong>The C5 Generic Collection Library</strong></a></p>\n\n<p>C5 provides functionality and data structures not provided by the standard .Net <code>System.Collections.Generic</code> namespace, such as <strong>persistent tree data structures</strong>, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes.\n</strike></p>\n"
},
{
"answer_id": 482997,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 3,
"selected": false,
"text": "<p>one way is to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms684493(VS.85).aspx\" rel=\"noreferrer\">Extensible Storage Engine</a> built into windoows to store your stuff. It's a native win database that supports indexing, transactions etc... </p>\n"
},
{
"answer_id": 482999,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "<p>Consider a memory mapped file. I'm not sure if there is direct support in .NET, but you could pinvoke the Win32 calls. </p>\n"
},
{
"answer_id": 483063,
"author": "axel_c",
"author_id": 20272,
"author_profile": "https://Stackoverflow.com/users/20272",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't actually used it, but this project apparently provides an mmap()-like implementation in C#</p>\n\n<p><a href=\"http://netdev.usr.dico.unimi.it/software/csharp/mmap/index.html\" rel=\"nofollow noreferrer\">Mmap</a></p>\n"
},
{
"answer_id": 483292,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I am not much of a programmer, but wouldn't creating a really simple XML format to store your data do the trick?</p>\n\n<pre><code><dico> \n <dicEntry index=\"x\">\n <key>MyKey</key>\n <val type=\"string\">My val</val>\n </dicEntry>\n ...\n</dico>\n</code></pre>\n\n<p>From there, you load the XML file DOM and fill up your dictionary as you like,</p>\n\n<pre><code>XmlDocument xdocDico = new XmlDocument();\nstring sXMLfile;\npublic loadDico(string sXMLfile, [other args...])\n{\n xdocDico.load(sXMLfile);\n // Gather whatever you need and load it into your dico\n}\npublic flushDicInXML(string sXMLfile, dictionary dicWhatever)\n{\n // Dump the dic in the XML doc & save\n}\npublic updateXMLDOM(index, key, value)\n{\n // Update a specific value of the XML DOM based on index or key\n}\n</code></pre>\n\n<p>Then whenever you want, you can update the DOM and save it on disk. </p>\n\n<p><code>xdocDico.save(sXMLfile);</code></p>\n\n<p>If you can afford to keep the DOM in memory performance-wise, it's pretty easy to deal with. Depending on your requirements, you may not even need the dictionary at all.</p>\n"
},
{
"answer_id": 483316,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 4,
"selected": false,
"text": "<p>Let me analyze this:</p>\n\n<ol>\n<li>Retrieve information by key</li>\n<li>Persistant storage</li>\n<li>Do not want to write back the whole file when 1 value changes</li>\n<li>Should survive crashes</li>\n</ol>\n\n<p>I think you want a database.</p>\n\n<p>Edit: I think you are searching for the wrong thing. Search for a database that fits your requirements. And change some of your requirements, because I think it will be difficult to meet them all.</p>\n"
},
{
"answer_id": 491543,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>I think your issue is likely to be that last point:</p>\n\n<blockquote>\n <p>When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.</p>\n</blockquote>\n\n<p>This is exactly what a DB does - you're basically describing a simple file based table structure.</p>\n\n<p>We can illustrate the problem by looking at strings.</p>\n\n<p>Strings in memory are flexible things - you don't need to know the length of a string in C# when you declare its type.</p>\n\n<p>In data storage strings and everything else are fixed sizes. Your saved dictionary on disk is just a collection of bytes, in order.</p>\n\n<p>If you replace a value in the middle it either has to be exactly the same size or you will have to <em>rewrite every byte that comes after it</em>.</p>\n\n<p>This is why most databases restrict text and blob fields to fixed sizes. New features like <code>varchar(max)</code>/<code>varbinary(max)</code> in Sql 2005+ are actually clever simplifications to the row only actually storing a pointer to the real data.</p>\n\n<p>You can't use the fixed sizes with your example because it's generic - you don't know what type you're going to be storing so you can't pad the values out to a maximum size.</p>\n\n<p>You could do:</p>\n\n<pre><code>class PersistantDictionary<T,V> : Dictionary<T,V>\n where V:struct\n</code></pre>\n\n<p>...as value types don't vary in storage size, although you would have to be careful with your implementation to save the right amount of storage for each type.</p>\n\n<p>However your model wouldn't be very performant - if you look at how SQL server and Oracle deal with table changes they don't change the values like this. Instead they flag the old record as a ghost, and add a new record with the new value. Old ghosted records are cleaned up later when the DB is less busy.</p>\n\n<p>I think you're trying to reinvent the wheel: </p>\n\n<ul>\n<li><p>If you're dealing with large amounts of data then you really need to check out using a full-blown DB. MySql or SqlLite are both good, but you're not going to find a good, simple, open-source and lite implementation.</p></li>\n<li><p>If you aren't dealing with loads of data then I'd go for whole file serialisation, and there are already plenty of good suggestions here on how to do that.</p></li>\n</ul>\n"
},
{
"answer_id": 492357,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>I'd recommend <a href=\"http://www.microsoft.com/express/sql/\" rel=\"nofollow noreferrer\">SQL Server Express</a> or other database.</p>\n\n<ul>\n<li>It's free.</li>\n<li>It integrates very well with C#, including LINQ.</li>\n<li>It's faster than a homemade solution.</li>\n<li>It's more reliable than a homemade solution.</li>\n<li>It's way more powerful than a simple disk-based data structure, so it'll be easy to do more in the future.</li>\n<li>SQL is an industry standard, so other developers will understand your program more easily, and you'll have a skill that is useful in the future.</li>\n</ul>\n"
},
{
"answer_id": 495516,
"author": "Ray Hidayat",
"author_id": 49643,
"author_profile": "https://Stackoverflow.com/users/49643",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote up an implementation myself based on a very similar (I think identical) requirement I had on another project a while ago. When I did it, one thing I realised was that most of the time you'll be doing writes, you only do a read rarely when the program crashes or when it's closed. So the idea is to make the writes as fast as possible. What I did was make a very simple class which would just write a log of all the operations (additions and deletions) to the dictionary as things occurred. So after a while you get a lot of repeating between keys. Because of that, once the object detects a certain amount of repetition, it'll clear the log and rewrite it so each key and its value only appears once. </p>\n\n<p>Unfortunately, you can't subclass Dictionary because you can't override anything in it. This is my simple implementation, I haven't tested it though I'm sorry, I thought you might want the idea though. Feel free to use it and change it as much as you like. </p>\n\n<pre><code>class PersistentDictManager {\n const int SaveAllThreshold = 1000;\n\n PersistentDictManager(string logpath) {\n this.LogPath = logpath;\n this.mydictionary = new Dictionary<string, string>();\n this.LoadData();\n }\n\n public string LogPath { get; private set; }\n\n public string this[string key] {\n get{ return this.mydictionary[key]; }\n set{\n string existingvalue;\n if(!this.mydictionary.TryGetValue(key, out existingvalue)) { existingvalue = null; }\n if(string.Equals(value, existingvalue)) { return; }\n this[key] = value;\n\n // store in log\n if(existingvalue != null) { // was an update (not a create)\n if(this.IncrementSaveAll()) { return; } // because we're going to repeat a key the log\n }\n this.LogStore(key, value);\n }\n }\n\n public void Remove(string key) {\n if(!this.mydictionary.Remove(key)) { return; }\n if(this.IncrementSaveAll()) { return; } // because we're going to repeat a key in the log\n this.LogDelete(key);\n }\n\n private void CreateWriter() {\n if(this.writer == null) {\n this.writer = new BinaryWriter(File.Open(this.LogPath, FileMode.Open)); \n }\n }\n\n private bool IncrementSaveAll() {\n ++this.saveallcount;\n if(this.saveallcount >= PersistentDictManager.SaveAllThreshold) {\n this.SaveAllData();\n return true;\n }\n else { return false; }\n }\n\n private void LoadData() {\n try{\n using(BinaryReader reader = new BinaryReader(File.Open(LogPath, FileMode.Open))) {\n while(reader.PeekChar() != -1) {\n string key = reader.ReadString();\n bool isdeleted = reader.ReadBoolean();\n if(isdeleted) { this.mydictionary.Remove(key); }\n else {\n string value = reader.ReadString();\n this.mydictionary[key] = value;\n }\n }\n }\n }\n catch(FileNotFoundException) { }\n }\n\n private void LogDelete(string key) {\n this.CreateWriter();\n this.writer.Write(key);\n this.writer.Write(true); // yes, key was deleted\n }\n\n private void LogStore(string key, string value) {\n this.CreateWriter();\n this.writer.Write(key);\n this.writer.Write(false); // no, key was not deleted\n this.writer.Write(value);\n }\n\n private void SaveAllData() {\n if(this.writer != null) {\n this.writer.Close();\n this.writer = null;\n }\n using(BinaryWriter writer = new BinaryWriter(File.Open(this.LogPath, FileMode.Create))) {\n foreach(KeyValuePair<string, string> kv in this.mydictionary) {\n writer.Write(kv.Key);\n writer.Write(false); // is not deleted flag\n writer.Write(kv.Value);\n }\n }\n }\n\n private readonly Dictionary<string, string> mydictionary;\n private int saveallcount = 0;\n private BinaryWriter writer = null;\n}\n</code></pre>\n"
},
{
"answer_id": 498476,
"author": "Timur Fanshteyn",
"author_id": 49557,
"author_profile": "https://Stackoverflow.com/users/49557",
"pm_score": 2,
"selected": false,
"text": "<p>I was working on porting EHCache to .NET. Take a look at the project </p>\n\n<p><a href=\"http://sourceforge.net/projects/thecache/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/thecache/</a></p>\n\n<p>Persistent caching is core functionality that is already implemented. All main Unit Tests are passing. I got a bit stuck on distributed caching, but you do not need that part.</p>\n"
},
{
"answer_id": 499018,
"author": "Mouk",
"author_id": 60795,
"author_profile": "https://Stackoverflow.com/users/60795",
"pm_score": 1,
"selected": false,
"text": "<p>Check this blog out:</p>\n\n<p><a href=\"http://ayende.com/Blog/archive/2009/01/17/rhino.dht-ndash-persistent-amp-distributed-storage.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2009/01/17/rhino.dht-ndash-persistent-amp-distributed-storage.aspx</a></p>\n\n<p>Looks to be exactly what you are looking for. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
]
| For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A FileWatcher is not required but it could be useful.
```
class PersistentDictionary<T,V> : IDictionary<T,V>
{
public PersistentDictionary(string filename)
{
}
}
```
Requirements:
* Open Source, with no dependency on native code (no sqlite)
* Ideally a very short and simple implementation
* When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.
**Similar Questions**
* [Persistent Binary Tree / Hash table in .Net](https://stackoverflow.com/questions/108435/persistent-binary-tree-hash-table-in-net)
* [Disk backed dictionary/cache for c#](https://stackoverflow.com/questions/408401/disk-backed-dictionary-cache-for-c)
* [`PersistentDictionary<Key,Value>`](http://izlooite.blogspot.com/2011/04/persistent-dictionary.html) | * [**bplustreedotnet**](http://bplusdotnet.sourceforge.net/)
The bplusdotnet package is a library of cross compatible data structure implementations in C#, java, and Python which are useful for applications which need to store and retrieve persistent information. The bplusdotnet data structures make it easy to **store string keys associated with values permanently**.
* [**ESENT Managed Interface**](http://www.codeplex.com/ManagedEsent)
*Not 100% managed code but it's worth mentioning it as unmanaged library itself is already part of every windows XP/2003/Vista/7 box*
ESENT is an embeddable database storage engine (ISAM) which is part of Windows. It provides reliable, transacted, concurrent, high-performance data storage with row-level locking, write-ahead logging and snapshot isolation. This is a managed wrapper for the ESENT Win32 API.
* [**Akavache**](https://github.com/github/Akavache)
\*Akavache is an asynchronous, persistent key-value cache created for writing native desktop and mobile applications in C#. Think of it like memcached for desktop apps.
- [**The C5 Generic Collection Library**](http://www.itu.dk/research/c5/)
C5 provides functionality and data structures not provided by the standard .Net `System.Collections.Generic` namespace, such as **persistent tree data structures**, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes. |
100,236 | <p>How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?</p>
<p>I ask because I am using the following:</p>
<pre><code>str.Replace( "<TAG1>", Convert.ToChar(0x01).ToString() );
</code></pre>
<p>and I feel that there must be a better way than this. Any Ideas?</p>
<p>Update:</p>
<p>Also If I use this methodology, do I need to worry about unicode & ASCII clashing?</p>
| [
{
"answer_id": 100244,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "<p>I believe you can use <code>\\uXXXX</code> to insert specified codes into your string.</p>\n\n<p>ETA: I just tested it and it works. :-)</p>\n\n<pre><code>using System;\nclass Uxxxx {\n public static void Main() {\n Console.WriteLine(\"\\u20AC\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100309,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Also If I use this methodology, do I need to worry about unicode & ASCII clashing?</p>\n</blockquote>\n\n<p>Your first problem will be your tags clashing with ASCII. Once you get to TAG10, you will clash with 0x0A: line feed. If you ensure that you will never get more than nine tags, you should be safe. Unicode-encoding (or rather: UTF8) is identical to ASCII-encoding when the byte-values are between 0 and 127. They only differ when the top-bit is set. </p>\n"
},
{
"answer_id": 1176383,
"author": "bzlm",
"author_id": 7724,
"author_profile": "https://Stackoverflow.com/users/7724",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>and I feel that there must be a better\n way than this. Any Ideas?</p>\n</blockquote>\n\n<p>It looks as if you're trying to <strong>manipulate a binary chunk using textual tools</strong>. If you want to insert the byte <code>0x01</code>, for example, you're not manipulating text anymore, since you don't care what that byte <em>might</em> represent, and since it looks like you don't even care which encoding you'll be outputting. </p>\n\n<p>A better way would be to treat the thing you're manipulating as a binary chunk of data, which would let you insert bits and bytes easily, without using brittle workarounds and worrying about side effects. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
]
| How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?
I ask because I am using the following:
```
str.Replace( "<TAG1>", Convert.ToChar(0x01).ToString() );
```
and I feel that there must be a better way than this. Any Ideas?
Update:
Also If I use this methodology, do I need to worry about unicode & ASCII clashing? | I believe you can use `\uXXXX` to insert specified codes into your string.
ETA: I just tested it and it works. :-)
```
using System;
class Uxxxx {
public static void Main() {
Console.WriteLine("\u20AC");
}
}
``` |
100,242 | <p>You can use </p>
<p>SelectFolder() to get a folder</p>
<p>or </p>
<p>GetOpenFolderitem(filter as string) to get files</p>
<p>but can you select either a folder or file? ( or for that matter selecting multiple files )</p>
| [
{
"answer_id": 100251,
"author": "Enrique",
"author_id": 17134,
"author_profile": "https://Stackoverflow.com/users/17134",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming you're using .Net I think you'll need to create your own control (or buy one). </p>\n"
},
{
"answer_id": 153820,
"author": "Nathan Black",
"author_id": 3265,
"author_profile": "https://Stackoverflow.com/users/3265",
"pm_score": 0,
"selected": false,
"text": "<p>It's not possible via any of the built-in APIs. There might be a plugin to do it, but I don't think there's OS support for it.</p>\n"
},
{
"answer_id": 170102,
"author": "Philip Regan",
"author_id": 11976,
"author_profile": "https://Stackoverflow.com/users/11976",
"pm_score": 4,
"selected": true,
"text": "<p>The MonkeyBread plugin allows this in the OpenDialogMBS class.</p>\n\n<p><a href=\"http://www.monkeybreadsoftware.net/pluginhelp/navigation-opendialogmbs.shtml\" rel=\"nofollow noreferrer\">http://www.monkeybreadsoftware.net/pluginhelp/navigation-opendialogmbs.shtml</a></p>\n\n<pre><code>OpenDialogMBS.AllowFolderSelection as Boolean\nproperty, Navigation, MBS Util Plugin (OpenDialog), class OpenDialogMBS, Plugin version: 7.5, Mac OS X: Works, Windows: Does nothing, Linux x86: Does nothing, Feedback.\n\nFunction: Whether folders can be selected.\nExample: \ndim o as OpenDialogMBS\ndim i,c as integer\ndim f as FolderItem\n\no=new OpenDialogMBS\no.ShowHiddenFiles=true\no.PromptText=\"Select one or more files/folders:\"\no.MultipleSelection=false\no.ActionButtonLabel=\"Open files/folders\"\no.CancelButtonLabel=\"no, thanks.\"\no.WindowTitle=\"This is a window title.\"\no.ClientName=\"Client Name?\"\no.AllowFolderSelection=true\no.ShowDialog\n\nc=o.FileCount\nif c>0 then\n for i=0 to c-1\n f=o.Files(i)\n\n FileList.List.AddRow f.AbsolutePath\n next\nend if\n\n\nNotes: \nDefault is false.\nSetting this to true on Windows or Linux has no effect there.\n(Read and Write property)\n</code></pre>\n"
},
{
"answer_id": 7366663,
"author": "Eduo",
"author_id": 737796,
"author_profile": "https://Stackoverflow.com/users/737796",
"pm_score": 0,
"selected": false,
"text": "<p>A bit late, but it's been included in recent versions. I'll put it here in case someone stumbles like me in this question:</p>\n\n<p><a href=\"http://docs.realsoftware.com/index.php/OpenDialog.MultiSelect\" rel=\"nofollow\">RealBasic Multiple Selection: OpenDialog.MultiSelect</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10472/"
]
| You can use
SelectFolder() to get a folder
or
GetOpenFolderitem(filter as string) to get files
but can you select either a folder or file? ( or for that matter selecting multiple files ) | The MonkeyBread plugin allows this in the OpenDialogMBS class.
<http://www.monkeybreadsoftware.net/pluginhelp/navigation-opendialogmbs.shtml>
```
OpenDialogMBS.AllowFolderSelection as Boolean
property, Navigation, MBS Util Plugin (OpenDialog), class OpenDialogMBS, Plugin version: 7.5, Mac OS X: Works, Windows: Does nothing, Linux x86: Does nothing, Feedback.
Function: Whether folders can be selected.
Example:
dim o as OpenDialogMBS
dim i,c as integer
dim f as FolderItem
o=new OpenDialogMBS
o.ShowHiddenFiles=true
o.PromptText="Select one or more files/folders:"
o.MultipleSelection=false
o.ActionButtonLabel="Open files/folders"
o.CancelButtonLabel="no, thanks."
o.WindowTitle="This is a window title."
o.ClientName="Client Name?"
o.AllowFolderSelection=true
o.ShowDialog
c=o.FileCount
if c>0 then
for i=0 to c-1
f=o.Files(i)
FileList.List.AddRow f.AbsolutePath
next
end if
Notes:
Default is false.
Setting this to true on Windows or Linux has no effect there.
(Read and Write property)
``` |
100,247 | <p>I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels. </p>
<p>What assembly and/or class should I use?</p>
| [
{
"answer_id": 100292,
"author": "Roy Tang",
"author_id": 18494,
"author_profile": "https://Stackoverflow.com/users/18494",
"pm_score": 1,
"selected": false,
"text": "<p>Of course I googled already and found the PngBitmapDecoder class, but it doesn't seem to be available in .Net 2.0? </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.pngbitmapdecoder.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.pngbitmapdecoder.aspx</a></p>\n\n<p>The above link mentions it's in the PresentationCore assembly which I don't seem to have included with .Net 2.0</p>\n"
},
{
"answer_id": 100293,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx\" rel=\"noreferrer\">Bitmap</a> class from System.Drawing.dll assembly:</p>\n\n<pre><code>Bitmap bitmap = new Bitmap(@\"C:\\image.png\");\nColor clr = bitmap.GetPixel(0, 0);\n</code></pre>\n"
},
{
"answer_id": 3205805,
"author": "ArekBulski",
"author_id": 386893,
"author_profile": "https://Stackoverflow.com/users/386893",
"pm_score": 1,
"selected": false,
"text": "<p>Well, Bitmap class can read a PNG file and access pixels. Can it see transparent pixels? PNG supports transparency while BMP does not. But still, it works.</p>\n\n<pre><code>Bitmap bitmap = new Bitmap(\"icn_loading_animated3a.png\");\npictureBox1.Image = bitmap;\nColor pixel5by10 = bitmap.GetPixel(5, 10);\n</code></pre>\n\n<p>Code above read my little picture and then read a transparent pixel. Color class has RGBA values, and the pixel I read was in recognized as transparent. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18494/"
]
| I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels.
What assembly and/or class should I use? | [Bitmap](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx) class from System.Drawing.dll assembly:
```
Bitmap bitmap = new Bitmap(@"C:\image.png");
Color clr = bitmap.GetPixel(0, 0);
``` |
100,291 | <p>Imagine I have an function which goes through one million/billion strings and checks smth in them.</p>
<p>f.ex:</p>
<pre><code>foreach (String item in ListOfStrings)
{
result.add(CalculateSmth(item));
}
</code></pre>
<p>it consumes lot's of time, because CalculateSmth is very time consuming function.</p>
<p>I want to ask: how to integrate multithreading in this kinda process?</p>
<p>f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.</p>
<p>Maybe anyone can show some examples or articles.. </p>
<p>Forgot to mention I need it in .NET 2.0</p>
| [
{
"answer_id": 100307,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 5,
"selected": true,
"text": "<p>You could try the <a href=\"http://msdn.microsoft.com/en-us/concurrency/default.aspx\" rel=\"noreferrer\">Parallel extensions</a> (part of .NET 4.0)</p>\n\n<p>These allow you to write something like:</p>\n\n<pre><code>Parallel.Foreach (ListOfStrings, (item) => \n result.add(CalculateSmth(item));\n);\n</code></pre>\n\n<p>Of course result.add would need to be thread safe.</p>\n"
},
{
"answer_id": 100314,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 1,
"selected": false,
"text": "<p>Not that I have any good articles here right now, but what you want to do is something along Producer-Consumer with a Threadpool.</p>\n\n<p>The Producers loops through and creates tasks (which in this case could be to just queue up the items in a List or Stack). The Consumers are, say, five threads that reads one item off the stack, consumes it by calculating it, and then stores it else where.</p>\n\n<p>This way the multithreading is limited to just those five threads, and they will all have work to do up until the stack is empty.</p>\n\n<p>Things to think about:</p>\n\n<ul>\n<li>Put protection on the input and output list, such as a mutex.</li>\n<li>If the order is important, make sure that the output order is maintained. One example could be to store them in a SortedList or something like that.</li>\n<li>Make sure that the CalculateSmth is thread safe, that it doesn't use any global state.</li>\n</ul>\n"
},
{
"answer_id": 100338,
"author": "Mats Wiklander",
"author_id": 5140,
"author_profile": "https://Stackoverflow.com/users/5140",
"pm_score": 2,
"selected": false,
"text": "<p>The first question you must answer is whether you should be using threading</p>\n\n<p>If your function CalculateSmth() is basically CPU-bound, i.e. heavy in CPU-usage and basically no I/O-usage, then I have a hard time seeing the point of using threads, since the threads will be competing over the same resource, in this case the CPU.</p>\n\n<p>If your CalculateSmth() is using both CPU and I/O, then it might be a point in using threading.</p>\n\n<p>I totally agree with the comment to my answer. I made a erroneous assumption that we were talking about a single CPU with one core, but these days we have multi-core CPUs, my bad.</p>\n"
},
{
"answer_id": 100352,
"author": "noocyte",
"author_id": 11220,
"author_profile": "https://Stackoverflow.com/users/11220",
"pm_score": 4,
"selected": false,
"text": "<p>The Parallel extensions is cool, but this can also be done just by using the threadpool like this:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Threading;\n\nnamespace noocyte.Threading\n{\n class CalcState\n {\n public CalcState(ManualResetEvent reset, string input) {\n Reset = reset;\n Input = input;\n }\n public ManualResetEvent Reset { get; private set; }\n public string Input { get; set; }\n }\n\n class CalculateMT\n {\n List<string> result = new List<string>();\n List<ManualResetEvent> events = new List<ManualResetEvent>();\n\n private void Calc() {\n List<string> aList = new List<string>();\n aList.Add(\"test\");\n\n foreach (var item in aList)\n {\n CalcState cs = new CalcState(new ManualResetEvent(false), item);\n events.Add(cs.Reset);\n ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), cs);\n }\n WaitHandle.WaitAll(events.ToArray());\n }\n\n private void Calculate(object s)\n {\n CalcState cs = s as CalcState;\n cs.Reset.Set();\n result.Add(cs.Input);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100363,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 4,
"selected": false,
"text": "<p>Note that concurrency doesn't magically give you more resource. You need to establish what is slowing CalculateSmth down.</p>\n\n<p>For example, if it's CPU-bound (and you're on a single core) then the same number of CPU ticks will go to the code, whether you execute them sequentially or in parallel. Plus you'd get some overhead from managing the threads. Same argument applies to other constraints (e.g. I/O)</p>\n\n<p>You'll only get performance gains in this if CalculateSmth is leaving resource free during its execution, that could be used by another instance. That's not uncommon. For example, if the task involves IO followed by some CPU stuff, then process 1 could be doing the CPU stuff while process 2 is doing the IO. As mats points out, a chain of producer-consumer units can achieve this, if you have the infrastructure.</p>\n"
},
{
"answer_id": 100799,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 3,
"selected": false,
"text": "<p>You need to split up the work you want to do in parallel. Here is an example of how you can split the work in two:</p>\n\n<pre><code>List<string> work = (some list with lots of strings)\n\n// Split the work in two\nList<string> odd = new List<string>();\nList<string> even = new List<string>();\nfor (int i = 0; i < work.Count; i++)\n{\n if (i % 2 == 0)\n {\n even.Add(work[i]);\n }\n else\n {\n odd.Add(work[i]);\n }\n}\n\n// Set up to worker delegates\nList<Foo> oddResult = new List<Foo>();\nAction oddWork = delegate { foreach (string item in odd) oddResult.Add(CalculateSmth(item)); };\n\nList<Foo> evenResult = new List<Foo>();\nAction evenWork = delegate { foreach (string item in even) evenResult.Add(CalculateSmth(item)); };\n\n// Run two delegates asynchronously\nIAsyncResult evenHandle = evenWork.BeginInvoke(null, null);\nIAsyncResult oddHandle = oddWork.BeginInvoke(null, null);\n\n// Wait for both to finish\nevenWork.EndInvoke(evenHandle);\noddWork.EndInvoke(oddHandle);\n\n// Merge the results from the two jobs\nList<Foo> allResults = new List<Foo>();\nallResults.AddRange(oddResult);\nallResults.AddRange(evenResult);\n\nreturn allResults;\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369/"
]
| Imagine I have an function which goes through one million/billion strings and checks smth in them.
f.ex:
```
foreach (String item in ListOfStrings)
{
result.add(CalculateSmth(item));
}
```
it consumes lot's of time, because CalculateSmth is very time consuming function.
I want to ask: how to integrate multithreading in this kinda process?
f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.
Maybe anyone can show some examples or articles..
Forgot to mention I need it in .NET 2.0 | You could try the [Parallel extensions](http://msdn.microsoft.com/en-us/concurrency/default.aspx) (part of .NET 4.0)
These allow you to write something like:
```
Parallel.Foreach (ListOfStrings, (item) =>
result.add(CalculateSmth(item));
);
```
Of course result.add would need to be thread safe. |
100,365 | <p>In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.</p>
<p>I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. <strong>I've narrowed it down to cake using this auto model feature instead of throwing and error</strong>! So i have no idea what's wrong!</p>
<p>Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful!</p>
| [
{
"answer_id": 100426,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 2,
"selected": false,
"text": "<p>There's always the possibility to actually create the model file and set var $useTable = false.<br>\nIf this is not what you're asking for and the model and its associations actually do exist, but Cake seems to be unable to find them, you'll have to triple check the names of all models and their class names in both the actual model definition and in the association definitions.</p>\n\n<p>AFAIK you can't disable the auto modelling.</p>\n"
},
{
"answer_id": 100442,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 1,
"selected": false,
"text": "<p>Use </p>\n\n<pre><code>var $useTable = false;\n</code></pre>\n\n<p>in your model definition.</p>\n"
},
{
"answer_id": 106985,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Cake 1.2</strong></p>\n\n<p>It's a hack and it's ugly cus you need to edit core cake files but this is how i do it:\n\\cake\\libs\\class_registry.php : line 127ish</p>\n\n<pre><code>if (App::import($type, $plugin . $class)) {\n ${$class} =& new $class($options);\n} elseif ($type === 'Model') {\n /* Print out whatever debug info we have then exit */\n pr($objects);\n die(\"unable to find class $type, $plugin$class\");\n /* We don't want to base this on the app model */\n ${$class} =& new AppModel($options);\n}\n</code></pre>\n\n<p><strong>Cake 2</strong></p>\n\n<p>Costa recommends changing $strict to true in the init function on line 95 of <code>Cake\\Utility\\ClassRegistry.php</code></p>\n\n<p><a href=\"http://api.cakephp.org/2.3/class-ClassRegistry.html#_init\" rel=\"nofollow noreferrer\">See Cake Api Docs for init</a></p>\n\n<p><a href=\"https://github.com/cakephp/cakephp/blob/c989624f8053f28d2ac37f5e84dc436965235177/lib/Cake/Utility/ClassRegistry.php#L96\" rel=\"nofollow noreferrer\">ClassRegistry.php - init function </a></p>\n"
},
{
"answer_id": 146898,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 1,
"selected": false,
"text": "<p>Delete all <strong>cached files</strong> (all files under app/tmp, keep the folders)</p>\n\n<p>In most cases where models seem to be acting in unexpected ways, often they dont include changes you've made, it is because that cake is useing an old cached version of the model. </p>\n"
},
{
"answer_id": 764114,
"author": "dr Hannibal Lecter",
"author_id": 78928,
"author_profile": "https://Stackoverflow.com/users/78928",
"pm_score": 0,
"selected": false,
"text": "<p>Uh...where do we start. First, as Alexander suggested, clear your app cache.</p>\n\n<p>If you still get the same behaviour, there is probably something wrong with the class and/or file names.</p>\n\n<p>Remember <a href=\"http://book.cakephp.org/view/23/File-and-Classname-Conventions\" rel=\"nofollow noreferrer\">the rules</a>, for controller:</p>\n\n<pre><code>* classname: BlastsController\n* filename: blasts_controller.php\n</code></pre>\n\n<p>for model:</p>\n\n<pre><code>* classname: Blast\n* filename: blast.php\n</code></pre>\n\n<p>Don't foget to <a href=\"http://book.cakephp.org/view/47/Inflections\" rel=\"nofollow noreferrer\">handle the irregular inflections</a> properly.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
]
| In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.
I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. **I've narrowed it down to cake using this auto model feature instead of throwing and error**! So i have no idea what's wrong!
Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful! | **Cake 1.2**
It's a hack and it's ugly cus you need to edit core cake files but this is how i do it:
\cake\libs\class\_registry.php : line 127ish
```
if (App::import($type, $plugin . $class)) {
${$class} =& new $class($options);
} elseif ($type === 'Model') {
/* Print out whatever debug info we have then exit */
pr($objects);
die("unable to find class $type, $plugin$class");
/* We don't want to base this on the app model */
${$class} =& new AppModel($options);
}
```
**Cake 2**
Costa recommends changing $strict to true in the init function on line 95 of `Cake\Utility\ClassRegistry.php`
[See Cake Api Docs for init](http://api.cakephp.org/2.3/class-ClassRegistry.html#_init)
[ClassRegistry.php - init function](https://github.com/cakephp/cakephp/blob/c989624f8053f28d2ac37f5e84dc436965235177/lib/Cake/Utility/ClassRegistry.php#L96) |
100,376 | <p>Anyone know how to do picture overlay or appear on top of each other in HTML? The effect will be something like the marker/icon appear on Google Map where the user can specify the coordinate of the second picture appear on the first picture.</p>
<p>Thanks.</p>
| [
{
"answer_id": 100402,
"author": "Subimage",
"author_id": 10596,
"author_profile": "https://Stackoverflow.com/users/10596",
"pm_score": 2,
"selected": false,
"text": "<p>Use a DIV tag and CSS absolute positioning, with the z-index property.</p>\n\n<p><a href=\"http://www.w3.org/TR/CSS2/visuren.html\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/visuren.html</a></p>\n"
},
{
"answer_id": 100405,
"author": "user9419",
"author_id": 9419,
"author_profile": "https://Stackoverflow.com/users/9419",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://www.echoecho.com/csslayers.htm\" rel=\"nofollow noreferrer\">css layers</a>. </p>\n"
},
{
"answer_id": 100417,
"author": "Johannes Hädrich",
"author_id": 18246,
"author_profile": "https://Stackoverflow.com/users/18246",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <code><div></code> containers to seperate content into multiple layers. Therefore the div containers have to be positioned absolutely and marked with a z-index. for instance:</p>\n\n<pre><code><div style=\"position: absolute; z-index:100\">This is in background</div> \n<div style=\"position: absolute; z-index:5000\">This is in foreground</div> \n</code></pre>\n\n<p>Of course the content also can contains images, etc.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14790/"
]
| Anyone know how to do picture overlay or appear on top of each other in HTML? The effect will be something like the marker/icon appear on Google Map where the user can specify the coordinate of the second picture appear on the first picture.
Thanks. | You can use `<div>` containers to seperate content into multiple layers. Therefore the div containers have to be positioned absolutely and marked with a z-index. for instance:
```
<div style="position: absolute; z-index:100">This is in background</div>
<div style="position: absolute; z-index:5000">This is in foreground</div>
```
Of course the content also can contains images, etc. |
100,415 | <p>I'm looking for an open source, cross platform (Windows & Linux at least) command line tool to take some code (C++, but multiple languages would be sweet), and spit out valid a XHTML representation of that code, with syntax highlighting included.</p>
<p>Ideally the XHTML should just wrap the code with <code><span></code> and <code><div></code> tags with different classes so I can supply the CSS code and change the colouration, but that's an optional extra.</p>
<p>Does anyone know of such an application?</p>
| [
{
"answer_id": 100439,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.vim.org/\" rel=\"nofollow noreferrer\">Vim</a> can save any code it highlights to \"colored\" HTML (it runs on several platforms). There is <a href=\"http://www.gnu.org/software/src-highlite/\" rel=\"nofollow noreferrer\">GNU hightlight</a> too. And tons of others.</p>\n"
},
{
"answer_id": 100446,
"author": "f4nt",
"author_id": 14838,
"author_profile": "https://Stackoverflow.com/users/14838",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure how helpful this will be, but my team uses doxygen to produce documentation, which happens to provide color syntax highlighting on our code views as well as a side bonus. Never really needed it, but it does it.</p>\n"
},
{
"answer_id": 100447,
"author": "Sergey Skoblikov",
"author_id": 12151,
"author_profile": "https://Stackoverflow.com/users/12151",
"pm_score": 2,
"selected": false,
"text": "<p>There is very good one, driven by XML, fast and opensource: <a href=\"http://sourceforge.net/projects/colorer/\" rel=\"nofollow noreferrer\"><a href=\"http://sourceforge.net/projects/colorer/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/colorer/</a></a></p>\n"
},
{
"answer_id": 100481,
"author": "Chris Charabaruk",
"author_id": 5697,
"author_profile": "https://Stackoverflow.com/users/5697",
"pm_score": 2,
"selected": false,
"text": "<p>I don't recall if <a href=\"http://qbnz.com/highlighter/\" rel=\"nofollow noreferrer\">GeSHi</a> has a command-line program but even if it doesn't, it shouldn't be hard to whip one up. It does a great job of taking code and generating pretty, coloured HTML/XHTML, even with line numbers (or every X line numbers, even) and other helpful features.</p>\n"
},
{
"answer_id": 100502,
"author": "Subimage",
"author_id": 10596,
"author_profile": "https://Stackoverflow.com/users/10596",
"pm_score": 0,
"selected": false,
"text": "<p>If you're ok with using ruby, you want <a href=\"http://coderay.rubychan.de/\" rel=\"nofollow noreferrer\">coderay</a>.</p>\n"
},
{
"answer_id": 100545,
"author": "shodanex",
"author_id": 11589,
"author_profile": "https://Stackoverflow.com/users/11589",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.gnu.org/software/enscript/\" rel=\"nofollow noreferrer\">Enscript</a> looks like what you are asking for :</p>\n\n<ol>\n<li>spit HTML (or PS, or RTF) from ascii files</li>\n<li>It includes features for `pretty-printing' (language-sensitive code highlighting) in several programming languages. </li>\n</ol>\n"
},
{
"answer_id": 900463,
"author": "Martin Geisler",
"author_id": 110204,
"author_profile": "https://Stackoverflow.com/users/110204",
"pm_score": 4,
"selected": true,
"text": "<p>I can recommend <a href=\"http://pygments.org/\" rel=\"noreferrer\">Pygments</a>. It's easy to work with and supports a lot of languages. It does what you want, i.e., it wraps the code in <code><span></code> tags:</p>\n\n<pre><code>from pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\n\ncode = 'print \"Hello World\"'\nprint highlight(code, PythonLexer(), HtmlFormatter())\n</code></pre>\n\n<p>gives</p>\n\n<pre><code><div class=\"highlight\">\n<pre><span class=\"k\">print</span> <span class=\"s\">&quot;Hello World&quot;</span></pre>\n</div>\n</code></pre>\n\n<p>and you can then use one of the supplied style sheets of make your own.</p>\n\n<p>You can also call it via it's <code>pygmentize</code> script. The script can format the output in different ways: HTML, LaTeX, ANSI color terminal output.</p>\n"
},
{
"answer_id": 2128994,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 0,
"selected": false,
"text": "<p>I'll add <a href=\"http://www.shrinkrays.net/tools/csharp-syntax-highlighter.aspx\" rel=\"nofollow noreferrer\">my own one to the list</a>, it colors C# but could be adapted for C, C++ and Java. \nIt produces the inline styles by default and a pre tag.</p>\n\n<p>The source is there in C#, you'll need to grab mono/monodevelop and compile it as as a console app, so it's not shrink wrapped in that respect.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
]
| I'm looking for an open source, cross platform (Windows & Linux at least) command line tool to take some code (C++, but multiple languages would be sweet), and spit out valid a XHTML representation of that code, with syntax highlighting included.
Ideally the XHTML should just wrap the code with `<span>` and `<div>` tags with different classes so I can supply the CSS code and change the colouration, but that's an optional extra.
Does anyone know of such an application? | I can recommend [Pygments](http://pygments.org/). It's easy to work with and supports a lot of languages. It does what you want, i.e., it wraps the code in `<span>` tags:
```
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
code = 'print "Hello World"'
print highlight(code, PythonLexer(), HtmlFormatter())
```
gives
```
<div class="highlight">
<pre><span class="k">print</span> <span class="s">"Hello World"</span></pre>
</div>
```
and you can then use one of the supplied style sheets of make your own.
You can also call it via it's `pygmentize` script. The script can format the output in different ways: HTML, LaTeX, ANSI color terminal output. |
100,416 | <p>In SQL Server 2000/2005,</p>
<p>Is it possible to force the default value to be written to already existing rows when adding a new column to a table <strong>without</strong> using NOT NULL on the new column?</p>
| [
{
"answer_id": 100560,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 1,
"selected": false,
"text": "<p>I doubt it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx</a></p>\n\n<p>The approach recommended by Microsoft is as follows (taken from the url above)</p>\n\n<pre><code>UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL\nALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL\n</code></pre>\n"
},
{
"answer_id": 100563,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 4,
"selected": true,
"text": "<p>You need two statements. First create the column with not null. Then change the not null constraint to nullable</p>\n\n<pre><code>alter table mytable add mycolumn varchar(10) not null default ('a value')\nalter table mytable alter column mycolumn varchar(10) null\n</code></pre>\n"
},
{
"answer_id": 103373,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>I understand your question, but you are saying that for future records, NULL (unknown, indeterminate or whatever your semantics are) is acceptable (but if it is left off in an insert, there will be a default), but that for all the existing data, you are going to go ahead and assign it the default.</p>\n\n<p>I would have to look hard at this situation and ask why you are even going to allow NULLs in future records at all - given none of the historical records will have it, and there is a default in place for future records.</p>\n"
},
{
"answer_id": 36855554,
"author": "sandeep rawat",
"author_id": 6085803,
"author_profile": "https://Stackoverflow.com/users/6085803",
"pm_score": 0,
"selected": false,
"text": "<p><code>ALTER TABLE {TABLENAME} \n ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \n CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n [**WITH VALUES]**</code></p>\n\n<p><strong>WITH VALUES</strong> can be used to store the default value in the new column for each existing row in the table.</p>\n\n<p>more detail on MSDN link .\n<a href=\"https://msdn.microsoft.com/en-in/library/ms190273.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-in/library/ms190273.aspx</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7241/"
]
| In SQL Server 2000/2005,
Is it possible to force the default value to be written to already existing rows when adding a new column to a table **without** using NOT NULL on the new column? | You need two statements. First create the column with not null. Then change the not null constraint to nullable
```
alter table mytable add mycolumn varchar(10) not null default ('a value')
alter table mytable alter column mycolumn varchar(10) null
``` |
100,435 | <p>I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another. </p>
<pre><code>root
--link 1
(...)
--link 10
--link 11
(...)
--link 20
</code></pre>
<p>However, sitemap file MUST have a root which I cannot seem to suppress.</p>
<p>Any thoughts?</p>
<p>-Edoode</p>
| [
{
"answer_id": 101374,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 2,
"selected": true,
"text": "<p>Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy \"root\" node?</p>\n\n<p>You should be able to tell your SiteMapProvider to use different site maps for the menu.</p>\n\n<p>The other question I have is what's the purpose of having multiple sitemap files? I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.</p>\n\n<p>That being said, I would come up with a homegrown menu system. You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure.</p>\n"
},
{
"answer_id": 849136,
"author": "Tim Scarborough",
"author_id": 432226,
"author_profile": "https://Stackoverflow.com/users/432226",
"pm_score": 2,
"selected": false,
"text": "<p>You can suppress the root node by doing the following:</p>\n\n<pre><code>SiteMapDataSource ds = new SiteMapDataSource();\nds.SiteMapProvider = \"providername\";\nds.ShowStartingNode = false;\nTreeView1.DataSource = ds;\nTreeView1.DataBind();\n</code></pre>\n\n<p>I use this method to hide the root node for tree views.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
]
| I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another.
```
root
--link 1
(...)
--link 10
--link 11
(...)
--link 20
```
However, sitemap file MUST have a root which I cannot seem to suppress.
Any thoughts?
-Edoode | Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy "root" node?
You should be able to tell your SiteMapProvider to use different site maps for the menu.
The other question I have is what's the purpose of having multiple sitemap files? I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.
That being said, I would come up with a homegrown menu system. You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure. |
100,444 | <p>I'm trying to automate a gdb session using the <code>--command</code> flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:</p>
<pre><code>set args /home/shlomi/conf/bugs/kde/font-break.txt
b IA__FcFontMatch
r
</code></pre>
<p>However, I'm getting the following:</p>
<pre>
shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb...
GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i586-mandriva-linux-gnu"...
(no debugging symbols found)
Function "IA__FcFontMatch" not defined.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal]
</pre>
<p>So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load?</p>
<p>I recall that I was able to do something, but cannot recall what.</p>
| [
{
"answer_id": 100501,
"author": "Shlomi Fish",
"author_id": 7709,
"author_profile": "https://Stackoverflow.com/users/7709",
"pm_score": 8,
"selected": true,
"text": "<p>Replying to myself, I'd like to give the answer that someone gave me on IRC:</p>\n\n<pre>\n(gdb) apropos pending\nactions -- Specify the actions to be taken at a tracepoint\nset breakpoint -- Breakpoint specific settings\nset breakpoint pending -- Set debugger's behavior regarding pending breakpoints\nshow breakpoint -- Breakpoint specific settings\nshow breakpoint pending -- Show debugger's behavior regarding pending breakpoints\n</pre>\n\n<p>And so <strong>set breakpoint pending on</strong> does the trick; it is used in <code>cmds.gdb</code> like e.g.</p>\n\n<pre><code>set breakpoint pending on\nbreak <source file name>:<line number>\n</code></pre>\n"
},
{
"answer_id": 1123235,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 3,
"selected": false,
"text": "<p>With no symbols.</p>\n\n<pre><code>objdump -t /lib/libacl.so\nSYMBOL TABLE:\nno symbols\nobjdump -T /lib/libacl.so\n...\n00002bd0 g DF .text 000000d0 ACL_1.0 acl_delete_entry\n...\n\n\n(gdb) break 0x0002bd0 \n\n(gdb) x/20i acl_delete_entry\n0x2bd0 <acl_delete_entry>: stwu r1,-32(r1)\n0x2bd4 <acl_delete_entry+4>: mflr r0\n0x2bd8 <acl_delete_entry+8>: stw r29,20(r1)\n0x2bdc <acl_delete_entry+12>: stw r30,24(r1)\n0x2be0 <acl_delete_entry+16>: mr r29,r4\n0x2be4 <acl_delete_entry+20>: li r4,28972\n</code></pre>\n"
},
{
"answer_id": 11568944,
"author": "äxl",
"author_id": 1539082,
"author_profile": "https://Stackoverflow.com/users/1539082",
"pm_score": 4,
"selected": false,
"text": "<p>OT: In terminal it would look like this to debug Caja in one line:</p>\n\n<pre><code>gdb -ex \"set breakpoint pending on\" -ex \"break gdk_x_error\" -ex run --args caja --sync\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7709/"
]
| I'm trying to automate a gdb session using the `--command` flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:
```
set args /home/shlomi/conf/bugs/kde/font-break.txt
b IA__FcFontMatch
r
```
However, I'm getting the following:
```
shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb...
GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i586-mandriva-linux-gnu"...
(no debugging symbols found)
Function "IA__FcFontMatch" not defined.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal]
```
So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load?
I recall that I was able to do something, but cannot recall what. | Replying to myself, I'd like to give the answer that someone gave me on IRC:
```
(gdb) apropos pending
actions -- Specify the actions to be taken at a tracepoint
set breakpoint -- Breakpoint specific settings
set breakpoint pending -- Set debugger's behavior regarding pending breakpoints
show breakpoint -- Breakpoint specific settings
show breakpoint pending -- Show debugger's behavior regarding pending breakpoints
```
And so **set breakpoint pending on** does the trick; it is used in `cmds.gdb` like e.g.
```
set breakpoint pending on
break <source file name>:<line number>
``` |
100,504 | <p>Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.</p>
| [
{
"answer_id": 100513,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "<p>MySQL 3 and 4 (and 5):</p>\n\n<pre><code>desc tablename\n</code></pre>\n\n<p>which is an alias for</p>\n\n<pre><code>show fields from tablename\n</code></pre>\n\n<p>SQL Server (from 2000) and MySQL 5:</p>\n\n<pre><code>select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS \nwhere TABLE_NAME = 'tablename'\n</code></pre>\n\n<p>Completing the answer: like people below have said, in SQL Server you can also use the stored procedure <code>sp_help</code></p>\n\n<pre><code>exec sp_help 'tablename'\n</code></pre>\n"
},
{
"answer_id": 100515,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 1,
"selected": false,
"text": "<p>If you just want the column names, then</p>\n\n<pre><code>select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'\n</code></pre>\n\n<p>On MS SQL Server, for more information on the table such as the types of the columns, use</p>\n\n<pre><code>sp_help 'tablename'\n</code></pre>\n"
},
{
"answer_id": 100526,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 4,
"selected": false,
"text": "<p>SQL-92 standard defines INFORMATION_SCHEMA which conforming rdbms's like MS SQL Server support. The following works for MS SQL Server 2000/2005/2008 and MySql 5 and above</p>\n\n<pre><code>select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'\n</code></pre>\n\n<p>MS SQl Server Specific:</p>\n\n<pre><code>exec sp_help 'myTable'\n</code></pre>\n\n<p>This solution returns several result sets within which is the information you desire, where as the former gives you exactly what you want.</p>\n\n<p>Also just for completeness you can query the sys tables directly. This is not recommended as the schema can change between versions of SQL Server and INFORMATION_SCHEMA is a layer of abstraction above these tables. But here it is anyway for SQL Server 2000</p>\n\n<pre><code>select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')\n</code></pre>\n"
},
{
"answer_id": 100529,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": 1,
"selected": false,
"text": "<p>MySQL is the same:</p>\n\n<pre><code>select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'\n</code></pre>\n"
},
{
"answer_id": 100534,
"author": "jules",
"author_id": 18655,
"author_profile": "https://Stackoverflow.com/users/18655",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the provided system views to do this:</p>\n\n<p>eg</p>\n\n<pre><code>select * from INFORMATION_SCHEMA.COLUMNS\nwhere table_name = '[table name]'\n</code></pre>\n\n<p>alternatively, you can use the system proc <strong>sp_help</strong></p>\n\n<p>eg</p>\n\n<pre><code>sp_help '[table name]'\n</code></pre>\n"
},
{
"answer_id": 100585,
"author": "Steve Obbayi",
"author_id": 11190,
"author_profile": "https://Stackoverflow.com/users/11190",
"pm_score": 2,
"selected": false,
"text": "<p>This is also MySQL Specific:</p>\n\n<pre><code>show fields from [tablename];\n</code></pre>\n\n<p>this doesnt just show the table names but it also pulls out all the info about the fields.</p>\n"
},
{
"answer_id": 100792,
"author": "Z99",
"author_id": 18307,
"author_profile": "https://Stackoverflow.com/users/18307",
"pm_score": 0,
"selected": false,
"text": "<p>MySQL</p>\n\n<pre><code>describe tablename\n</code></pre>\n"
},
{
"answer_id": 100848,
"author": "Rene",
"author_id": 17323,
"author_profile": "https://Stackoverflow.com/users/17323",
"pm_score": 2,
"selected": false,
"text": "<p>For those looking for an answer in Oracle:</p>\n\n<pre><code>SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLENAME'\n</code></pre>\n"
},
{
"answer_id": 101458,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "<p>PostgreSQL understands the</p>\n\n<pre><code>select column_name from information_schema.columns where table_name = 'myTable'\n</code></pre>\n\n<p>syntax. If you're working in the psql shell, you can also use</p>\n\n<pre><code>\\d myTable\n</code></pre>\n\n<p>for a description (columns, and their datatypes and constraints)</p>\n"
},
{
"answer_id": 104877,
"author": "8jean",
"author_id": 10011,
"author_profile": "https://Stackoverflow.com/users/10011",
"pm_score": 2,
"selected": false,
"text": "<p>Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use \"<code>pragma table_info()</code>\"</p>\n\n<pre><code>sqlite> pragma table_info('table_name');\ncid name type notnull dflt_value pk \n---------- ---------- ---------- ---------- ---------- ----------\n0 id integer 99 1 \n1 name 0 0 \n</code></pre>\n"
},
{
"answer_id": 104923,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 2,
"selected": false,
"text": "<p>In Sybase SQL Anywhere, the columns and table information are stored separately, so you need a join:</p>\n\n<pre><code>select c.column_name from systabcol c \n key join systab t on t.table_id=c.table_id \n where t.table_name='tablename'\n</code></pre>\n"
},
{
"answer_id": 108464,
"author": "brabster",
"author_id": 2362,
"author_profile": "https://Stackoverflow.com/users/2362",
"pm_score": 1,
"selected": false,
"text": "<p>For IBM DB2 (will double check this on Monday to be sure.)</p>\n\n<pre><code>SELECT TABNAME,COLNAME from SYSCAT.COLUMNS where TABNAME='MYTABLE'\n</code></pre>\n"
},
{
"answer_id": 74591209,
"author": "Ranushka Lakmal Sankalpa",
"author_id": 6712167,
"author_profile": "https://Stackoverflow.com/users/6712167",
"pm_score": 0,
"selected": false,
"text": "<p><strong>select COLUMN_NAME1,COLUMN_NAME2 from SCHEMA_NAME.TABLE_NAME\nwhere TABLE_NAME.COLUMN_NAME = 'COLUMN_NAME1';</strong></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856916/"
]
| Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well. | MySQL 3 and 4 (and 5):
```
desc tablename
```
which is an alias for
```
show fields from tablename
```
SQL Server (from 2000) and MySQL 5:
```
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tablename'
```
Completing the answer: like people below have said, in SQL Server you can also use the stored procedure `sp_help`
```
exec sp_help 'tablename'
``` |
100,533 | <p>Is it possible to do like this:</p>
<pre><code>interface IDBBase {
DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
...
}
class DBBase : IDBBase {
public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
...
}
}
</code></pre>
<p>I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:</p>
<pre><code>genClass<typeOj>
{
typeOj instOj;
public genClass(typeOj o)
{ instOj=o; }
public typeOj getType()
{ return instOj; }
</code></pre>
<p>...</p>
<pre><code>interface IDBBase
{
DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
...
}
class DBBase : IDBBase
{
public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
{
...
}
}
</code></pre>
| [
{
"answer_id": 100562,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>No it's not possible. Method should have same signature that one declared in the interface.</p>\n\n<p>However you can use type parameter constraints:</p>\n\n<pre><code>interface IDBClass<T> where T:IDbCommand\n{\n void Test(T cmd);\n}\n\nclass DBClass:IDBClass<SqlCommand>\n{\n public void Test(SqlCommand cmd)\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100570,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 1,
"selected": false,
"text": "<p>Try compiling it. The compiler will report an error if <code>DBBase</code> doesn't implement <code>IDBBase</code>.</p>\n"
},
{
"answer_id": 100575,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>No, it's not possible. I tried compiling this:</p>\n\n<pre><code>interface Interface1 { }\nclass Class1 : Interface1 {}\n\ninterface Interface2 { void Foo(Interface1 i1);}\nclass Class2 : Interface2 {void Foo(Class1 c1) {}}\n</code></pre>\n\n<p>And I got this error:</p>\n\n<blockquote>\n <p><em>'Class2' does not implement interface member 'Interface2.Foo(Interface1)'</em></p>\n</blockquote>\n"
},
{
"answer_id": 100576,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)\" rel=\"nofollow noreferrer\">Covariance and contravariance</a> are not widely supported as of C# 3.0, except for assigning method groups to delegates. You can emulate it a bit by using private interface implementation and call public method with more specific parameters:</p>\n\n<pre><code>class DBBase : IDBBase {\n\n DataTable IDBBase.getDataTableSql(DataTable curTable, IDbCommand cmd) {\n return getDataTableSql(curTable, (SqlCommand)cmd); // of course you should do some type checks\n }\n\n public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {\n ...\n }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is it possible to do like this:
```
interface IDBBase {
DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
...
}
class DBBase : IDBBase {
public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
...
}
}
```
I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:
```
genClass<typeOj>
{
typeOj instOj;
public genClass(typeOj o)
{ instOj=o; }
public typeOj getType()
{ return instOj; }
```
...
```
interface IDBBase
{
DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
...
}
class DBBase : IDBBase
{
public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
{
...
}
}
``` | No it's not possible. Method should have same signature that one declared in the interface.
However you can use type parameter constraints:
```
interface IDBClass<T> where T:IDbCommand
{
void Test(T cmd);
}
class DBClass:IDBClass<SqlCommand>
{
public void Test(SqlCommand cmd)
{
}
}
``` |
100,624 | <p>How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this <em>almost</em> works for me:</p>
<pre><code>proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"
</code></pre>
<p>The problem is that when <code>proc2</code> finishes before <code>proc1</code>, the parent process will still wait for <code>proc1</code>. On Unix one would use <code>waitpid(0)</code> in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?</p>
| [
{
"answer_id": 100886,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": true,
"text": "<p>It might seem overkill, but, here it goes:</p>\n\n<pre><code>import Queue, thread, subprocess\n\nresults= Queue.Queue()\ndef process_waiter(popen, description, que):\n try: popen.wait()\n finally: que.put( (description, popen.returncode) )\nprocess_count= 0\n\nproc1= subprocess.Popen( ['python', 'mytest.py'] )\nthread.start_new_thread(process_waiter,\n (proc1, \"1 finished\", results))\nprocess_count+= 1\n\nproc2= subprocess.Popen( ['python', 'mytest.py'] )\nthread.start_new_thread(process_waiter,\n (proc2, \"2 finished\", results))\nprocess_count+= 1\n\n# etc\n\nwhile process_count > 0:\n description, rc= results.get()\n print \"job\", description, \"ended with rc =\", rc\n process_count-= 1\n</code></pre>\n"
},
{
"answer_id": 111225,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 3,
"selected": false,
"text": "<p>Twisted has an <a href=\"http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.interfaces.IReactorProcess.html\" rel=\"noreferrer\">asynchronous process-spawning API</a> which works on Windows. There are actually several different implementations, many of which are not so great, but you can switch between them without changing your code.</p>\n"
},
{
"answer_id": 149327,
"author": "user23475",
"author_id": 23475,
"author_profile": "https://Stackoverflow.com/users/23475",
"pm_score": 2,
"selected": false,
"text": "<p>Twisted on Windows will perform an active wait under the covers. If you don't want to use threads, you will have to use the win32 API to avoid polling. Something like this:</p>\n\n<pre><code>import win32process\nimport win32event\n\n# Note: CreateProcess() args are somewhat cryptic, look them up on MSDN\nproc1, thread1, pid1, tid1 = win32process.CreateProcess(...)\nproc2, thread2, pid2, tid2 = win32process.CreateProcess(...)\nthread1.close()\nthread2.close()\n\nprocesses = {proc1: \"proc1\", proc2: \"proc2\"}\n\nwhile processes:\n handles = processes.keys()\n # Note: WaitForMultipleObjects() supports at most 64 processes at a time\n index = win32event.WaitForMultipleObjects(handles, False, win32event.INFINITE)\n finished = handles[index]\n exitcode = win32process.GetExitCodeProcess(finished)\n procname = processes.pop(finished)\n finished.close()\n print \"Subprocess %s finished with exit code %d\" % (procname, exitcode)\n</code></pre>\n"
},
{
"answer_id": 573196,
"author": "Ted Mielczarek",
"author_id": 69326,
"author_profile": "https://Stackoverflow.com/users/69326",
"pm_score": 3,
"selected": false,
"text": "<p>Building on zseil's answer, you can do this with a mix of subprocess and win32 API calls. I used straight ctypes, because my Python doesn't happen to have win32api installed. I'm just spawning sleep.exe from MSYS here as an example, but clearly you could spawn any process you like. I use OpenProcess() to get a HANDLE from the process' PID, and then WaitForMultipleObjects to wait for any process to finish.</p>\n\n<pre><code>import ctypes, subprocess\nfrom random import randint\nSYNCHRONIZE=0x00100000\nINFINITE = -1\nnumprocs = 5\nhandles = {}\n\nfor i in xrange(numprocs):\n sleeptime = randint(5,10)\n p = subprocess.Popen([r\"c:\\msys\\1.0\\bin\\sleep.exe\", str(sleeptime)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)\n h = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE, False, p.pid)\n handles[h] = p.pid\n print \"Spawned Process %d\" % p.pid\n\nwhile len(handles) > 0:\n print \"Waiting for %d children...\" % len(handles)\n arrtype = ctypes.c_long * len(handles)\n handle_array = arrtype(*handles.keys())\n ret = ctypes.windll.kernel32.WaitForMultipleObjects(len(handle_array), handle_array, False, INFINITE)\n h = handle_array[ret]\n ctypes.windll.kernel32.CloseHandle(h)\n print \"Process %d done\" % handles[h]\n del handles[h]\nprint \"All done!\"\n</code></pre>\n"
},
{
"answer_id": 20292161,
"author": "Giampaolo Rodolà",
"author_id": 376587,
"author_profile": "https://Stackoverflow.com/users/376587",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"https://code.google.com/p/psutil/\" rel=\"nofollow\">psutil</a>:</p>\n\n<pre><code>>>> import subprocess\n>>> import psutil\n>>> \n>>> proc1 = subprocess.Popen(['python','mytest.py'])\n>>> proc2 = subprocess.Popen(['python','mytest.py']) \n>>> ls = [psutil.Process(proc1.pid), psutil.Process(proc2.pid)]\n>>>\n>>> gone, alive = psutil.wait_procs(ls, timeout=3)\n</code></pre>\n\n<p>'gone' and 'alive' are lists indicating which processes are gone and which ones are still alive.</p>\n\n<p>Optionally you can specify a callback which gets invoked every time one of the watched processes terminates:</p>\n\n<pre><code>>>> def on_terminate(proc):\n... print \"%s terminated\" % proc\n...\n>>> gone, alive = psutil.wait_procs(ls, timeout=3, callback=on_terminate)\n</code></pre>\n"
},
{
"answer_id": 64832681,
"author": "Thomas Grainger",
"author_id": 833093,
"author_profile": "https://Stackoverflow.com/users/833093",
"pm_score": 1,
"selected": false,
"text": "<p>you can use <a href=\"https://psutil.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">psutil</a></p>\n<pre><code>import psutil\n\nwith psutil.Popen(["python", "mytest.py"]) as proc1, psutil.Popen(\n ["python", "mytest.py"]\n) as proc2:\n gone, alive = psutil.wait_procs([proc1, proc2], timeout=3)\n</code></pre>\n<p>'gone' and 'alive' are lists indicating which processes are gone and which ones are still alive.</p>\n<p>Optionally you can specify a callback which gets invoked every time one of the watched processes terminates:</p>\n<pre><code>def on_terminate(proc):\n print "%s terminated" % proc\n\ngone, alive = psutil.wait_procs(ls, timeout=3, callback=on_terminate)\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12166/"
]
| How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this *almost* works for me:
```
proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"
```
The problem is that when `proc2` finishes before `proc1`, the parent process will still wait for `proc1`. On Unix one would use `waitpid(0)` in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows? | It might seem overkill, but, here it goes:
```
import Queue, thread, subprocess
results= Queue.Queue()
def process_waiter(popen, description, que):
try: popen.wait()
finally: que.put( (description, popen.returncode) )
process_count= 0
proc1= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
(proc1, "1 finished", results))
process_count+= 1
proc2= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
(proc2, "2 finished", results))
process_count+= 1
# etc
while process_count > 0:
description, rc= results.get()
print "job", description, "ended with rc =", rc
process_count-= 1
``` |
100,631 | <p>After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration.</p>
<pre><code> Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets`
</code></pre>
<p>Restarting the mongrels (not the MySQL server) fixes it.</p>
<p>How can we fix this?</p>
| [
{
"answer_id": 100688,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 1,
"selected": false,
"text": "<p>The connection to the MySQL server is probably timing out.</p>\n\n<p>You should be able to increase the timeout in MySQL, but for a proper fix, have your code check that the database connection is still alive, and re-connect if it's not.</p>\n"
},
{
"answer_id": 100703,
"author": "Z99",
"author_id": 18307,
"author_profile": "https://Stackoverflow.com/users/18307",
"pm_score": 1,
"selected": false,
"text": "<p>Do you monitor the number of open MySQL connections or threads? What is your mysql.ini settings for max_connections?</p>\n\n<pre><code>mysql> show status;\n</code></pre>\n\n<p>Look at Connections, Max_used_connections, Threads_connected, and Threads_created.</p>\n\n<p>You may need to increase the limits in your MySQL configuration, or perhaps rails is not closing the connection properly*.</p>\n\n<p><em>Note: I've only used Ruby on Rails briefly...</em></p>\n\n<p>The MySQL documentation for server status is in <a href=\"http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html</a>.</p>\n"
},
{
"answer_id": 101250,
"author": "Laurie Young",
"author_id": 7473,
"author_profile": "https://Stackoverflow.com/users/7473",
"pm_score": 6,
"selected": true,
"text": "<p>This is probably caused by the persistent connections to MySQL going away (time out is likely if it's happening over night) and Ruby on Rails is failing to restore the connection, which it should be doing by default:</p>\n\n<p>In the file vendor/rails/actionpack/lib/action_controller/dispatcher.rb is the code:</p>\n\n<pre><code>if defined?(ActiveRecord)\n before_dispatch { ActiveRecord::Base.verify_active_connections! }\n to_prepare(:activerecord_instantiate_observers) {ActiveRecord::Base.instantiate_observers }\nend\n</code></pre>\n\n<p>The method <code>verify_active_connections!</code> performs several actions, one of which is to recreate any expired connections.</p>\n\n<p>The most likely cause of this error is that this is because a <a href=\"https://en.wikipedia.org/wiki/Monkey_patch\" rel=\"noreferrer\">monkey patch</a> has redefined the dispatcher to not call <code>verify_active_connections!</code>, or <code>verify_active_connections!</code> has been changed, etc.</p>\n"
},
{
"answer_id": 101522,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 2,
"selected": false,
"text": "<p>As the other contributors to this thread have said, it is most likely that MySQL server has closed the connection to your Ruby on Rails application because of inactivity. The default timeout is 28800 seconds, or 8 hours. </p>\n\n<pre><code>set-variable = wait_timeout=86400\n</code></pre>\n\n<p>Adding this line to your <code>/etc/my.cnf</code> will raise the timeout to 24 hours\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#option_mysqld_wait_timeout\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#option_mysqld_wait_timeout</a>.</p>\n\n<p>Although the documentation doesn't indicate it, a value of 0 <em>may</em> disable the timeout completely, but you would need to experiment as this is just speculation.</p>\n\n<p>There are however three other situations that I know of that can generate that error. The first is the MySQL server being restarted. This will obviously drop all the connections, but as the MySQL client is passive, and this won't be noticed till you do the next query.</p>\n\n<p>The second condition is if someone kills your query from the MySQL command line, and this also drops the connection, because it could leave the client in an undefined state.</p>\n\n<p>The last is if your MySQL server restarts itself due to a fatal internal error. That is, if you are doing a simple query against a table and instantly see 'MySQL has gone away', I'd take a close look at your server's logs to check for hardware error, or database corruption.</p>\n"
},
{
"answer_id": 1175186,
"author": "mixonic",
"author_id": 142061,
"author_profile": "https://Stackoverflow.com/users/142061",
"pm_score": 6,
"selected": false,
"text": "<p>Ruby on Rails 2.3 has a reconnect option for your database connection:</p>\n\n<pre><code>production:\n # Your settings\n reconnect: true\n</code></pre>\n\n<p>See:</p>\n\n<ul>\n<li><p><a href=\"http://guides.rubyonrails.org/2_3_release_notes.html#reconnecting-mysql-connections\" rel=\"noreferrer\"><em>Ruby on Rails 2.3 Release Notes</em>, sub section <em>4.8 Reconnecting MySQL Connections</em></a>.</p></li>\n<li><p><em><a href=\"http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4?pli=1\" rel=\"noreferrer\">MySQL auto-reconnect revisited</a></em></p></li>\n</ul>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 7586762,
"author": "Graeme Irwin",
"author_id": 969552,
"author_profile": "https://Stackoverflow.com/users/969552",
"pm_score": 1,
"selected": false,
"text": "<p>Using reconnect: true in the database.yml will cause the database connection to be re-established AFTER the ActiveRecord::StatementInvalid error is raised (As Dave Cheney mentioned).</p>\n\n<p>Unfortunately adding a retry on the database operation seemed necessary to guard against the connection timeout:</p>\n\n<pre><code>begin\n do_some_active_record_operation\nrescue ActiveRecord::StatementInvalid => e\n Rails.logger.debug(\"Got statement invalid #{e.message} ... trying again\")\n # Second attempt, now that db connection is re-established\n do_some_active_record_operation\nend\n</code></pre>\n"
},
{
"answer_id": 8220766,
"author": "Ryan Allen",
"author_id": 977719,
"author_profile": "https://Stackoverflow.com/users/977719",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem in a Ruby on Rails 3 application, using the <code>mysql2</code> gem. I copied out the offending query and tried running it in MySQL directly, and I got the same error, \"MySQL server has gone away.\".</p>\n\n<p>The query in question was very, very large. A very large insert (+1 MB). The field I was trying to insert into was a TEXT column and their max size is 64 KB. Rather than throwing an errorm, the connection went away.</p>\n\n<p>I increased the size of the field and got the same thing, so I'm still not sure what the exact issue was. The point is that it was in the database due to some strange query. Anyway!</p>\n"
},
{
"answer_id": 17870784,
"author": "Abdo",
"author_id": 226255,
"author_profile": "https://Stackoverflow.com/users/226255",
"pm_score": 2,
"selected": false,
"text": "<p>First, determine the max_connections in MySQL:</p>\n\n<pre><code>show variables like \"max_connections\";\n</code></pre>\n\n<p>You need to make sure that the number of connections you're making in your Ruby on Rails application is less than the maximum allowed number of connections. Note that extra connections can be coming from your <a href=\"http://en.wikipedia.org/wiki/Cron\" rel=\"nofollow\">cron</a> jobs, delayed_job processes (each would have the same pool size in your <code>database.yml</code>), etc.</p>\n\n<p>Monitor the SQL connections as you go through your application, run processes, etc. by doing the following in MySQL:</p>\n\n<pre><code>show status where variable_name = 'Threads_connected';\n</code></pre>\n\n<p>You might want to consider closing connections after a <code>Thread</code> finishes execution as database connections do not get closed automatically (I think this is less of an issue with Ruby on Rails 4 applications <a href=\"https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb\" rel=\"nofollow\">Reaper</a>):</p>\n\n<pre><code>Thread.new do\n begin\n # Thread work here\n ensure\n begin\n if (ActiveRecord::Base.connection && ActiveRecord::Base.connection.active?)\n ActiveRecord::Base.connection.close\n end\n rescue\n end\n end\nend\n</code></pre>\n"
},
{
"answer_id": 21074557,
"author": "Matt Connolly",
"author_id": 365932,
"author_profile": "https://Stackoverflow.com/users/365932",
"pm_score": 3,
"selected": false,
"text": "<p>Try <code>ActiveRecord::Base.connection.verify!</code> in Ruby on Rails 4. Verify pings the server and reconnects if it is not connected.</p>\n"
},
{
"answer_id": 22247839,
"author": "mahemoff",
"author_id": 18706,
"author_profile": "https://Stackoverflow.com/users/18706",
"pm_score": 0,
"selected": false,
"text": "<p>Something else to check is Unicorn config is correct. See before_fork and after_fork handling of ActiveRecord connection here: <a href=\"https://gist.github.com/nebiros/2776085#file-unicorn-rb\" rel=\"nofollow\">https://gist.github.com/nebiros/2776085#file-unicorn-rb</a></p>\n"
},
{
"answer_id": 23895554,
"author": "Isaac Betesh",
"author_id": 1633753,
"author_profile": "https://Stackoverflow.com/users/1633753",
"pm_score": 3,
"selected": false,
"text": "<p>I had this problem when sending really large statements to MySQL. MySQL limits the size of statements and will close the connection if you go over the limit.</p>\n\n<pre><code>set global max_allowed_packet = 1048576; # 2^20 bytes (1 MB) was enough in my case\n</code></pre>\n"
},
{
"answer_id": 67589849,
"author": "Joshua Pinter",
"author_id": 293280,
"author_profile": "https://Stackoverflow.com/users/293280",
"pm_score": 0,
"selected": false,
"text": "<h3>While forking in Rails.</h3>\n<p>For anyone running into this while forking in Rails, try clearing the existing connections before forking and then establish a new connection for each fork, like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># Clear existing connections before forking to ensure they do not get inherited.\n::ActiveRecord::Base.clear_all_connections! \n\nfork do\n # Establish a new connection for each fork.\n ::ActiveRecord::Base.establish_connection \n \n # The rest of the code for each fork...\nend\n</code></pre>\n<p>See this StackOverflow answer here: <a href=\"https://stackoverflow.com/a/8915353/293280\">https://stackoverflow.com/a/8915353/293280</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18666/"
]
| After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration.
```
Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets`
```
Restarting the mongrels (not the MySQL server) fixes it.
How can we fix this? | This is probably caused by the persistent connections to MySQL going away (time out is likely if it's happening over night) and Ruby on Rails is failing to restore the connection, which it should be doing by default:
In the file vendor/rails/actionpack/lib/action\_controller/dispatcher.rb is the code:
```
if defined?(ActiveRecord)
before_dispatch { ActiveRecord::Base.verify_active_connections! }
to_prepare(:activerecord_instantiate_observers) {ActiveRecord::Base.instantiate_observers }
end
```
The method `verify_active_connections!` performs several actions, one of which is to recreate any expired connections.
The most likely cause of this error is that this is because a [monkey patch](https://en.wikipedia.org/wiki/Monkey_patch) has redefined the dispatcher to not call `verify_active_connections!`, or `verify_active_connections!` has been changed, etc. |
100,633 | <p>Why is it bad practice to declare variables on one line?</p>
<p>e.g.</p>
<pre><code>private String var1, var2, var3
</code></pre>
<p>instead of: </p>
<pre><code>private String var1;
private String var2;
private String var3;
</code></pre>
| [
{
"answer_id": 100639,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 3,
"selected": false,
"text": "<p>Because in some languages, var2 and var3 in your example would <em>not</em> be strings, they would be variants (untyped).</p>\n"
},
{
"answer_id": 100650,
"author": "Michel",
"author_id": 7198,
"author_profile": "https://Stackoverflow.com/users/7198",
"pm_score": 4,
"selected": false,
"text": "<p>In my opinion, the main goal of having each variable on a separate line would be to facilitate the job of Version Control tools.</p>\n\n<p>If several variables are on the same line you risk having conflicts for unrelated modifications by different developers.</p>\n"
},
{
"answer_id": 100653,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 0,
"selected": false,
"text": "<p>Agree with edg, and also because it is more readable and easy for maintenance to have each variable on separate line. You immediately see the type, scope and other modifiers and when you change a modifier it applies only to the variable you want - that avoids errors.</p>\n"
},
{
"answer_id": 100659,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>With separate lines, you have the opportunity to add a comment on each line describing the use of the variable (if it isn't clear from its name).</p>\n"
},
{
"answer_id": 100660,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my reasons:</p>\n\n<ul>\n<li>Readability, easier to spot if you know there's only one on each line</li>\n<li>Version control, less intra-line changes, more single-line additions, changes, or deletions, easier to merge from one branch to another</li>\n</ul>\n"
},
{
"answer_id": 100662,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 4,
"selected": false,
"text": "<p>In C++ :</p>\n\n<pre><code>int * i, j;\n</code></pre>\n\n<p>i is of type int *, j is of type int.\nThe distinction is too easily missed.</p>\n\n<p>Besides having them on one line each makes it easier to add some comments later</p>\n"
},
{
"answer_id": 100664,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>I think that there are various reasons, but they all boil down to that the first is just less readable and more prone to failure because a single line is doing more than one thing.</p>\n\n<p>And all that for no real gain, and don't you tell me you find two lines of saved space is a real gain.</p>\n\n<p>It's a similar thing to what happens when you have</p>\n\n<pre><code>if ((foo = some_function()) == 0) {\n //do something\n}\n</code></pre>\n\n<p>Of course this example is much worse than yours. </p>\n"
},
{
"answer_id": 100671,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>To be honest I am not against it. I think that its perfectly feasible to group similar variables on the same line e.g.</p>\n\n<p>float fMin, fMax;</p>\n\n<p>however I steer clear when the variables are unrelated e.g.</p>\n\n<p>int iBalance, iColor;</p>\n"
},
{
"answer_id": 100673,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>to be more apparent to you when using Version Control tools (covered by Michel)</li>\n<li>to be more readable to you when you have the simplest overflow/underflow or compile error and your eyes failed to point out the obvious</li>\n<li>to defend the opposite (i.e. multi-variable single-line declaration) has less pros (\"code textual vertical visibility\" being a singleton)</li>\n</ol>\n"
},
{
"answer_id": 100674,
"author": "Henrik Heimbuerger",
"author_id": 6278,
"author_profile": "https://Stackoverflow.com/users/6278",
"pm_score": 3,
"selected": false,
"text": "<p>In C/C++, you also have the problem that the * used to indicate a pointer type only applies to the directly following identifier. So a rather common mistake of inexperienced developers is to write</p>\n\n<pre><code>int* var1, var2, var3;\n</code></pre>\n\n<p>and expecting all three variables to be of type 'int pointer', whereas for the compiler this reads as</p>\n\n<pre><code>int* var1;\nint var2;\nint var3;\n</code></pre>\n\n<p>making only var1 a pointer.</p>\n"
},
{
"answer_id": 100679,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 2,
"selected": false,
"text": "<p>What about the case such as:</p>\n\n<pre><code>public static final int NORTH = 0,\n EAST = 1,\n SOUTH = 2,\n WEST = 3;\n</code></pre>\n\n<p>Is that considered bad practice as well? I would consider that okay as it counters some of the points previously made: </p>\n\n<ul>\n<li>they would all definitely be the same type (in my statically typed Java-world)</li>\n<li>comments can be added for each</li>\n<li>if you have to change the type for one, you probably have to do it for all, and all four can be done in one change </li>\n</ul>\n\n<p>So in an (albeit smelly code) example, is there reasons you wouldn't do that?</p>\n"
},
{
"answer_id": 100680,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 0,
"selected": false,
"text": "<p>It is bad practice mostly when you can and want to initialize variables on the deceleration. An example where this might not be so bad is:</p>\n\n<pre><code>string a,b;\nif (Foo())\n{\n a = \"Something\";\n b = \"Something else\";\n}\nelse\n{\n a = \"Some other thing\";\n b = \"Out of examples\";\n}\n</code></pre>\n"
},
{
"answer_id": 100701,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Why is that bad practice? I don't think it is, as long as your code is still readable.</p>\n\n<pre><code>//not much use\nint i, j, k;\n\n//better\nint counter, \n childCounter, \n percentComplete;\n</code></pre>\n"
},
{
"answer_id": 100791,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 0,
"selected": false,
"text": "<p>Generally it is, for the version control and commenting reasons discussed by others, and I'd apply that in 95% of all cases. however there are circumstances where it does make sense, for example if I'm coding graphics and I want a couple of variables to represent texture coordinates (always referenced by convention as s and t) then the declaring them as</p>\n\n<p>int s, t; // texture coordinates</p>\n\n<p>IMHO enhances code readability both by shortening the code and by making it explicit that these two variables belong together (of course some would argue for using a single point class variable in this case). </p>\n"
},
{
"answer_id": 100847,
"author": "Vihung",
"author_id": 15452,
"author_profile": "https://Stackoverflow.com/users/15452",
"pm_score": 2,
"selected": false,
"text": "<p>Relevance. </p>\n\n<p>Just because two variables are of type String does not mean they are closely related to each other. </p>\n\n<p>If the two (or more) variables are closely related by function, rather then variable type, then maybe they could be declared together. i.e. only if it makes sense for a reader of your program to see the two variables together should they actually be placed together</p>\n"
},
{
"answer_id": 51964331,
"author": "jaskirat singh",
"author_id": 8074053,
"author_profile": "https://Stackoverflow.com/users/8074053",
"pm_score": 0,
"selected": false,
"text": "<p>while attempting this question <a href=\"https://www.interviewbit.com/problems/remove-element-from-array/\" rel=\"nofollow noreferrer\">https://www.interviewbit.com/problems/remove-element-from-array/</a></p>\n\n<p>Method 1 gives Memory Limit exceeded for this code:</p>\n\n<p>Type 1:</p>\n\n<pre><code>int i,j;\n</code></pre>\n\n<p>Type 2:</p>\n\n<pre><code>int i;\nint j;\n</code></pre>\n\n<p>type 1: Gives Memory Limit Exceeded</p>\n\n<pre><code>int removeElement (int* A, int n1, int B) \n{\n int k=0, i;\n for(i=0;i<n1;i++)\n if(A[i]!=B)\n {\n A[k]=A[i];\n k++;\n } \n return k;\n}\n</code></pre>\n\n<p>Whereas type 2 works perfectly fine</p>\n\n<pre><code>int removeElement (int* A, int n1, int B) \n{\n int k=0;\n int i;\n for(i=0;i<n1;i++)\n if(A[i]!=B)\n {\n A[k]=A[i];\n k++;\n } \n return k;\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
]
| Why is it bad practice to declare variables on one line?
e.g.
```
private String var1, var2, var3
```
instead of:
```
private String var1;
private String var2;
private String var3;
``` | I think that there are various reasons, but they all boil down to that the first is just less readable and more prone to failure because a single line is doing more than one thing.
And all that for no real gain, and don't you tell me you find two lines of saved space is a real gain.
It's a similar thing to what happens when you have
```
if ((foo = some_function()) == 0) {
//do something
}
```
Of course this example is much worse than yours. |
100,645 | <p>Are there any tools available for calculating Cyclomatic Complexity in Javascript? </p>
<p>I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write.</p>
| [
{
"answer_id": 198179,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 3,
"selected": false,
"text": "<p>Since cyclomatic complexity is evaluated counting the number of keyword\n\"if, switch, while for break\" etc.. every tools that works with C will do the job, like\nsourcemonitor:\n<a href=\"http://www.campwoodsw.com/sourcemonitor.html\" rel=\"noreferrer\">http://www.campwoodsw.com/sourcemonitor.html</a></p>\n\n<p>Actually, on javascript the more you try to modulize your code, the more you will slow it down, so take it with a grain of salt ;)</p>\n\n<p>EDIT:\nI <strong>Really</strong> can't understand what's going on on this answer, I get another downvote, when in my answer I tell a good tool for calculating cyclomatic complexity in javascript,\nand this in particular works very well.</p>\n\n<p>For the second assertion, mine is a comment that comes from experience, I never tell <em>don't modulize your js code</em>, I only tell to <em>make attention in doing it</em>, because often there is a tradeoff with speed, and when I talk of speed I mean that 2 different slowdown can happen: at <em>download time</em> and at <em>execution time</em> (and in slow device like pda/smartphone this is important).</p>\n\n<p>Since tools like this often drive developer into writing more code trying to chase the smaller index possible,\nbut in js more code unfortunately means that slowdowns can happen, and the <strong>overuse</strong> of these tools is bad.\nSurelly these tools can give you hints of <strong>where</strong> your code can be improved, but you've to master how to use the tool and not blindy rely on it.</p>\n\n<p>So if you downvote me again, please write a comment in which you explain why you do so, the discussion can only benefit from this, thank you and sorry for the vent.</p>\n"
},
{
"answer_id": 6968692,
"author": "Arne",
"author_id": 882177,
"author_profile": "https://Stackoverflow.com/users/882177",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the ccm tool from <a href=\"https://web.archive.org/web/20150219013605/http://www.blunck.info/ccm.html\" rel=\"nofollow noreferrer\">ARCHIVE of blunck.info</a> or the github repo <a href=\"https://github.com/jonasblunck/ccm\" rel=\"nofollow noreferrer\">jonasblunck/ccm</a></p>\n<p>It supports JavaScript, C/C++ and C#. It's free, runs on Windows (can be run on Linux and Mac OS X as well - using the Mono framework).</p>\n"
},
{
"answer_id": 11240663,
"author": "Jakob Borg",
"author_id": 247563,
"author_profile": "https://Stackoverflow.com/users/247563",
"pm_score": 2,
"selected": false,
"text": "<p>There's now also Yardstick: <a href=\"https://github.com/calmh/yardstick\" rel=\"nofollow\">https://github.com/calmh/yardstick</a></p>\n\n<p>It tries to calculate cyclomatic complexity for idiomatic Javascript, handling more cases than for example jscheckstyle.</p>\n"
},
{
"answer_id": 13453464,
"author": "Phil Booth",
"author_id": 47348,
"author_profile": "https://Stackoverflow.com/users/47348",
"pm_score": 5,
"selected": false,
"text": "<p>I helped write a tool to perform software complexity analysis on JavaScript projects:</p>\n\n<p><a href=\"https://github.com/escomplex/complexity-report\" rel=\"noreferrer\">complexity-report</a></p>\n\n<p>It reports a bunch of different complexity metrics: lines of code, number of parameters, cyclomatic complexity, cyclomatic density, Halstead complexity measures, the maintainability index, first-order density, change cost and core size.</p>\n\n<p>It is released under the MIT license and built using Node.js and the <a href=\"http://esprima.org/\" rel=\"noreferrer\">Esprima</a> JavaScript parser. It can be installed via npm, like so:</p>\n\n<pre><code>npm i -g complexity-report\n</code></pre>\n"
},
{
"answer_id": 15815677,
"author": "SavoryBytes",
"author_id": 131944,
"author_profile": "https://Stackoverflow.com/users/131944",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://jshint.com/about/\" rel=\"nofollow noreferrer\">JSHint</a> recently <a href=\"https://github.com/jshint/jshint/pull/593\" rel=\"nofollow noreferrer\">added support</a> for calculating code metrics.</p>\n<p>You can set maximum values for:</p>\n<ul>\n<li><a href=\"https://jshint.com/docs/options/#maxparams\" rel=\"nofollow noreferrer\"><code>maxparams</code></a> - the number of formal parameters allowed</li>\n<li><a href=\"https://jshint.com/docs/options/#maxdepth\" rel=\"nofollow noreferrer\"><code>maxdepth</code></a> - how deeply nested code blocks should be</li>\n<li><a href=\"https://jshint.com/docs/options/#maxstatements\" rel=\"nofollow noreferrer\"><code>maxstatements</code></a> - the number of statements allowed per function</li>\n<li><a href=\"https://jshint.com/docs/options/#maxcomplexity\" rel=\"nofollow noreferrer\"><code>maxcomplexity</code></a> - the maximum cyclomatic complexity</li>\n</ul>\n<h3>Examples</h3>\n<p><em>Maximum number of formal parameters allowed per function</em></p>\n<pre class=\"lang-js prettyprint-override\"><code>/*jshint maxparams:3 */\n\nfunction login(request, onSuccess) {\n // ...\n}\n\n// JSHint: Too many parameters per function (4).\nfunction logout(request, isManual, whereAmI, onSuccess) {\n // ...\n}\n</code></pre>\n<p><em>Maximum number of nested code blocks allowed per function</em></p>\n<pre class=\"lang-js prettyprint-override\"><code>/*jshint maxdepth:2 */\n\nfunction main(meaning) {\n var day = true;\n\n if (meaning === 42) {\n while (day) {\n shuffle();\n\n if (tired) { // JSHint: Blocks are nested too deeply (3).\n sleep();\n }\n }\n }\n}\n</code></pre>\n<p><em>Maximum number of statements allowed per function</em></p>\n<pre class=\"lang-js prettyprint-override\"><code>/*jshint maxstatements:4 */\n\nfunction main() {\n var i = 0;\n var j = 0;\n\n // Function declarations count as one statement. Their bodies\n // don't get taken into account for the outer function.\n function inner() {\n var i2 = 1;\n var j2 = 1;\n\n return i2 + j2;\n }\n\n j = i + j;\n return j; // JSHint: Too many statements per function. (5)\n}\n</code></pre>\n"
},
{
"answer_id": 15873058,
"author": "jsoverson",
"author_id": 60737,
"author_profile": "https://Stackoverflow.com/users/60737",
"pm_score": 4,
"selected": false,
"text": "<p>For completeness in the answers, I was looking for the same tool some time ago and didn't find anything that worked well for visualization so I wrote <a href=\"http://github.com/jsoverson/plato\">plato</a></p>\n\n<p>Sample reports for :</p>\n\n<ul>\n<li><a href=\"http://jsoverson.github.com/plato/examples/jquery/\">jquery</a></li>\n<li><a href=\"http://jsoverson.github.com/plato/examples/grunt/\">grunt</a></li>\n<li><a href=\"http://jsoverson.github.com/plato/examples/marionette/\">marionettejs</a></li>\n</ul>\n\n<p>It uses phil's complexity-report (mentioned above) and also aggregates data from jshint (and eventually, others).</p>\n"
},
{
"answer_id": 19219676,
"author": "automaticAllDramatic",
"author_id": 1156254,
"author_profile": "https://Stackoverflow.com/users/1156254",
"pm_score": 3,
"selected": false,
"text": "<p>The new version of <a href=\"http://jshint.com\" rel=\"noreferrer\">http://jshint.com</a> is out and has a very good cyclomatic complexity calculator</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932/"
]
| Are there any tools available for calculating Cyclomatic Complexity in Javascript?
I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write. | I helped write a tool to perform software complexity analysis on JavaScript projects:
[complexity-report](https://github.com/escomplex/complexity-report)
It reports a bunch of different complexity metrics: lines of code, number of parameters, cyclomatic complexity, cyclomatic density, Halstead complexity measures, the maintainability index, first-order density, change cost and core size.
It is released under the MIT license and built using Node.js and the [Esprima](http://esprima.org/) JavaScript parser. It can be installed via npm, like so:
```
npm i -g complexity-report
``` |
100,654 | <p>I've got a c# application that plays simple wav files through directsound. With the test data I had, the code worked fine. However when I used real-world data, it produced a very unhelpful error on creation of the secondary buffer: "ArgumentException: Value does not fall within the expected range."</p>
<p>The test wavs had a 512kbps bit rate, 16bit audio sample size, and 32kHz audio sample rate. The new wavs is 1152kbps, 24bit and 48kHz respectively. How can I get directsound to cope with these larger values, or if not how can I programatically detect these values before attempting to play the file?</p>
<p>it's managed DirectX v9.00.1126 I'm using, and I've included some sample code below:</p>
<pre><code>using DS = Microsoft.DirectX.DirectSound;
...
DS.Device device = new DS.Device();
device.SetCooperativeLevel(this, CooperativeLevel.Normal);
...
BufferDescription bufferDesc = new BufferDescription();
bufferDesc.ControlEffects = false;
...
try
{
SecondaryBuffer sound = new SecondaryBuffer(path, bufferDesc, device);
sound.Play(0, BufferPlayFlags.Default);
}
...
</code></pre>
<p>Additional info: the real-world wav files won't play in windows media player either, telling me a codec is needed to play the file, while they play fine in winamp.</p>
<p>Additional info 2: Comparing the bytes of the working test data and the bad real-world data, I can see that past the RIFF chunk, the bad data has a "bext" chunk, that the internet informs me is metadata associated with the broadcast audio extension, while the test data goes straight into a fmt chunk. There /is/ a fmt chunk in the bad data, so I don't know if it's badly-formed or if the loaders should be looking further for fmt data. I can see if I can get some information on this rouge bext chunk from the people supplying me the data - if they can remove it my code may still work.</p>
| [
{
"answer_id": 100675,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 4,
"selected": true,
"text": "<p>Not all soundcards support 24 bit sample playback, and even when they do, they often have to be exclusively opened in that mode. There is a similar issue with sample rates. Your soundcard may be operating at 44.1kHz, in which case 48kHz needs to be resampled to be played.</p>\n\n<p>I have written an open source .NET audio library called <a href=\"http://www.codeplex.com/naudio\" rel=\"noreferrer\">NAudio</a> which will allow you to find out what sample rate and bit depth a given WAV file is. It also offers alternative ways of playing back audio (e.g. through the Wav... APIs), and the ability to resample files using the DMO resampler object.</p>\n"
},
{
"answer_id": 100699,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the sampling issue, WAV is just a container format and the audio could be compressed in any of a myriad of audio formats (just like AVI is a container of video). So you could use a tool like <a href=\"http://www.headbands.com/gspot/download.html\" rel=\"nofollow noreferrer\">GSpot</a> to find out if your WAV is encoded in a non-standard format in and install the codec. Winamp has more codecs installed by default than WMP, which would explain the Winamp plays it and WMP doesn't.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11801/"
]
| I've got a c# application that plays simple wav files through directsound. With the test data I had, the code worked fine. However when I used real-world data, it produced a very unhelpful error on creation of the secondary buffer: "ArgumentException: Value does not fall within the expected range."
The test wavs had a 512kbps bit rate, 16bit audio sample size, and 32kHz audio sample rate. The new wavs is 1152kbps, 24bit and 48kHz respectively. How can I get directsound to cope with these larger values, or if not how can I programatically detect these values before attempting to play the file?
it's managed DirectX v9.00.1126 I'm using, and I've included some sample code below:
```
using DS = Microsoft.DirectX.DirectSound;
...
DS.Device device = new DS.Device();
device.SetCooperativeLevel(this, CooperativeLevel.Normal);
...
BufferDescription bufferDesc = new BufferDescription();
bufferDesc.ControlEffects = false;
...
try
{
SecondaryBuffer sound = new SecondaryBuffer(path, bufferDesc, device);
sound.Play(0, BufferPlayFlags.Default);
}
...
```
Additional info: the real-world wav files won't play in windows media player either, telling me a codec is needed to play the file, while they play fine in winamp.
Additional info 2: Comparing the bytes of the working test data and the bad real-world data, I can see that past the RIFF chunk, the bad data has a "bext" chunk, that the internet informs me is metadata associated with the broadcast audio extension, while the test data goes straight into a fmt chunk. There /is/ a fmt chunk in the bad data, so I don't know if it's badly-formed or if the loaders should be looking further for fmt data. I can see if I can get some information on this rouge bext chunk from the people supplying me the data - if they can remove it my code may still work. | Not all soundcards support 24 bit sample playback, and even when they do, they often have to be exclusively opened in that mode. There is a similar issue with sample rates. Your soundcard may be operating at 44.1kHz, in which case 48kHz needs to be resampled to be played.
I have written an open source .NET audio library called [NAudio](http://www.codeplex.com/naudio) which will allow you to find out what sample rate and bit depth a given WAV file is. It also offers alternative ways of playing back audio (e.g. through the Wav... APIs), and the ability to resample files using the DMO resampler object. |
100,678 | <pre><code>LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&pUnkReturn, 0);
</code></pre>
<p>The value of result after the call is 0</p>
<p>I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .</p>
<p>Necessary Information before this call :</p>
<pre><code>const UINT CMotionUtils::s_MaxGetTaskInterface = RegisterWindowMessage(_T("NI:Max:GetTaskInterface"));
</code></pre>
<p>The value of <code>s_MaxGetTaskInterface</code> i get here is 49896 . </p>
<p>The value of hWnd is also proper . I checked that with Spy++ ( Visual Studio tool ) .</p>
<p>Microft Spy++ Messages window shows me the following for this window . </p>
<pre><code><00001> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000
<00002> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000
</code></pre>
<p>Please help me to get a valid address stored in pUnkReturn after the call . </p>
| [
{
"answer_id": 100692,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>When I Googled for <code>NI:Max:GetTaskInterface</code> I couldn't find anything. In general, how a window will handle a given message depends entirely on the window concerned. Does the window (specified by <code>hWnd</code>) even support the <code>NI:Max:GetTaskInterface</code> message?</p>\n"
},
{
"answer_id": 100700,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>You're going to have to provide more information - what is \"GetTaskInterface\" (Google provides no results). SendMessage will return with whatever value is returned from the WndProc that handles the message \"s_MaxGetTaskInterface\". If it's not handled, you will get zero back and your pointer will still be NULL.</p>\n"
},
{
"answer_id": 100979,
"author": "Alan",
"author_id": 2958,
"author_profile": "https://Stackoverflow.com/users/2958",
"pm_score": 0,
"selected": false,
"text": "<p>You'll need to tell us what <code>pUnkReturn</code> is and how it's defined.</p>\n\n<p>You'll also need to tell us what the handler for s_MaxGetTaskInterface is expecting.</p>\n\n<p>If you expect the handler to populate whatever is pointed to by pUnkReturn, then you'll need to call SendMessage with (WPARAM)pUnkReturn, however if the handler returns a pointer, then call as you're doing now.</p>\n"
},
{
"answer_id": 101008,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>I think the & in &pUnkReturn is needed, based on the hungarian prefix. I expect pUnkReturn to have type IUnknown*. The message receiver will provide the IUnknown*. The address where it will store that IUnknown* is an IUnknown**. Hence, this code passes in &pUnkReturn and the message receiver writes to *(IUnknown**)wParam.</p>\n"
},
{
"answer_id": 272756,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "<p>Is the destination hWnd in the same process? If not, you won't be able to pass (or return) a pointer through the message. Note that Windows implements marshalling for built-in messages.</p>\n"
},
{
"answer_id": 272945,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is not with how you are calling SendMessage(). The problem is in your implementation of the message handler for the \"NI:Max:GetTaskInterface\" registered message.</p>\n\n<p>The value that SendMessage() returns is the same as the value that is returned from your message handler. If you need pUnkReturn to be an out-val, then your message handler must populate it.</p>\n\n<p>Let's see the code for your message handler.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| ```
LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&pUnkReturn, 0);
```
The value of result after the call is 0
I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .
Necessary Information before this call :
```
const UINT CMotionUtils::s_MaxGetTaskInterface = RegisterWindowMessage(_T("NI:Max:GetTaskInterface"));
```
The value of `s_MaxGetTaskInterface` i get here is 49896 .
The value of hWnd is also proper . I checked that with Spy++ ( Visual Studio tool ) .
Microft Spy++ Messages window shows me the following for this window .
```
<00001> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000
<00002> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000
```
Please help me to get a valid address stored in pUnkReturn after the call . | I think the & in &pUnkReturn is needed, based on the hungarian prefix. I expect pUnkReturn to have type IUnknown\*. The message receiver will provide the IUnknown\*. The address where it will store that IUnknown\* is an IUnknown\*\*. Hence, this code passes in &pUnkReturn and the message receiver writes to \*(IUnknown\*\*)wParam. |
100,689 | <p>I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item. Is there a way to make the whole item clickable?</p>
| [
{
"answer_id": 100706,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 3,
"selected": true,
"text": "<p>Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as block too:</p>\n\n<pre><code>a {\n display: block;\n width: 100%;\n}\n</code></pre>\n"
},
{
"answer_id": 100742,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you only have the text in the <a> ... </a>, that's the only part that can be clicked on. Move your graphics, etc. inside the link.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
]
| I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item. Is there a way to make the whole item clickable? | Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as block too:
```
a {
display: block;
width: 100%;
}
``` |
100,721 | <p>I am using <code>DirectoryInfo.GetDirectories()</code> recursively to find the all the sub-directories under a given path.
However, I want to exclude the System folders and there is no clear way for that.
In FindFirstFile/FindNextFile things were clearer with the attributes.</p>
| [
{
"answer_id": 100760,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>You'd probably have to loop through the results and reject those with the attributes that you don't want (use the Attributes property).</p>\n"
},
{
"answer_id": 100822,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "<p>@rslite is right, .NET doesn't give such filtering out-of-box, but it's not hard to implement:</p>\n\n<pre><code>static IEnumerable<string> GetNonSystemDirs(string path)\n{\n var dirs = from d in Directory.GetDirectories(path)\n let inf = new DirectoryInfo(d)\n where (inf.Attributes & FileAttributes.System) == 0\n select d;\n\n foreach (var dir in dirs)\n {\n yield return dir;\n foreach (var subDir in GetNonSystemDirs(dir))\n {\n yield return subDir;\n }\n }\n}\n</code></pre>\n\n<p>MSDN links:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.attributes.aspx\" rel=\"nofollow noreferrer\">FileSystemInfo.Attributes Property</a> </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx\" rel=\"nofollow noreferrer\">FileAttributes Enumeration</a></p>\n"
},
{
"answer_id": 100877,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 2,
"selected": false,
"text": "<p>This is a great example of a scenario where Linq and extension methods make things really clean and easy.</p>\n\n<pre><code>public static DirectoryInfo[] GetNonSystemDirectories(\n this DirectoryInfo directory,\n string searchPattern,\n SearchOption searchOption)\n{\n return directory.GetDirectories(searchPattern, searchOption)\n .Where(subDir => (subDir.Attributes & FileAttributes.System) == 0)\n .ToArray();\n}\n</code></pre>\n\n<p>If you're building a .net v2 application, then you can use <a href=\"http://www.albahari.com/nutshell/linqbridge.html\" rel=\"nofollow noreferrer\">LinqBridge</a> to give you access to all the cool Linq to objects methods (like Where() and ToArray() above).</p>\n\n<p><strong>Edit</strong></p>\n\n<p>In .net v4 you'd use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.enumeratedirectories.aspx\" rel=\"nofollow noreferrer\">EnumerateDirectories</a> instead of <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.getdirectories.aspx\" rel=\"nofollow noreferrer\">GetDirectories</a> which allows you to iterate over the results without building an array in memory first.</p>\n\n<pre><code>public static IEnumerable<DirectoryInfo> EnumerateNonSystemDirectories(\n this DirectoryInfo directory,\n string searchPattern,\n SearchOption searchOption)\n{\n return directory.EnumerateDirectories(searchPattern, searchOption)\n .Where(subDir => (subDir.Attributes & FileAttributes.System) == 0);\n}\n</code></pre>\n"
},
{
"answer_id": 22290845,
"author": "electricalbah",
"author_id": 1899556,
"author_profile": "https://Stackoverflow.com/users/1899556",
"pm_score": 0,
"selected": false,
"text": "<p>Using the ultimate Sweet Linq</p>\n\n<pre><code> IEnumerable<string> directories = new DirectoryInfo(path).GetDirectories().Where(a => (a.Attributes & FileAttributes.System) == 0).Select(a => a.FullName);\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am using `DirectoryInfo.GetDirectories()` recursively to find the all the sub-directories under a given path.
However, I want to exclude the System folders and there is no clear way for that.
In FindFirstFile/FindNextFile things were clearer with the attributes. | @rslite is right, .NET doesn't give such filtering out-of-box, but it's not hard to implement:
```
static IEnumerable<string> GetNonSystemDirs(string path)
{
var dirs = from d in Directory.GetDirectories(path)
let inf = new DirectoryInfo(d)
where (inf.Attributes & FileAttributes.System) == 0
select d;
foreach (var dir in dirs)
{
yield return dir;
foreach (var subDir in GetNonSystemDirs(dir))
{
yield return subDir;
}
}
}
```
MSDN links:
[FileSystemInfo.Attributes Property](http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.attributes.aspx)
[FileAttributes Enumeration](http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx) |
100,732 | <p>I've seen several examples of code like this:</p>
<pre><code>if not someobj:
#do something
</code></pre>
<p>But I'm wondering why not doing:</p>
<pre><code>if someobj == None:
#do something
</code></pre>
<p>Is there any difference? Does one have an advantage over the other?</p>
| [
{
"answer_id": 100762,
"author": "Sylvain Defresne",
"author_id": 5353,
"author_profile": "https://Stackoverflow.com/users/5353",
"pm_score": 9,
"selected": true,
"text": "<p>In the first test, Python try to convert the object to a <code>bool</code> value if it is not already one. Roughly, <strong>we are asking the object : are you meaningful or not ?</strong> This is done using the following algorithm :</p>\n\n<ol>\n<li><p>If the object has a <code>__nonzero__</code> special method (as do numeric built-ins, <code>int</code> and <code>float</code>), it calls this method. It must either return a <code>bool</code> value which is then directly used, or an <code>int</code> value that is considered <code>False</code> if equal to zero.</p></li>\n<li><p>Otherwise, if the object has a <code>__len__</code> special method (as do container built-ins, <code>list</code>, <code>dict</code>, <code>set</code>, <code>tuple</code>, ...), it calls this method, considering a container <code>False</code> if it is empty (length is zero).</p></li>\n<li><p>Otherwise, the object is considered <code>True</code> unless it is <code>None</code> in which case, it is considered <code>False</code>.</p></li>\n</ol>\n\n<p>In the second test, the object is compared for equality to <code>None</code>. Here, <strong>we are asking the object, \"Are you equal to this other value?\"</strong> This is done using the following algorithm :</p>\n\n<ol>\n<li><p>If the object has a <code>__eq__</code> method, it is called, and the return value is then converted to a <code>bool</code>value and used to determine the outcome of the <code>if</code>.</p></li>\n<li><p>Otherwise, if the object has a <code>__cmp__</code> method, it is called. This function must return an <code>int</code> indicating the order of the two object (<code>-1</code> if <code>self < other</code>, <code>0</code> if <code>self == other</code>, <code>+1</code> if <code>self > other</code>).</p></li>\n<li><p>Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the <code>is</code> operator).</p></li>\n</ol>\n\n<p>There is another test possible using the <code>is</code> operator. <strong>We would be asking the object, \"Are you this particular object?\"</strong></p>\n\n<p>Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values (<code>None</code> meaning not initialized for a member field for exemple, or when using the <code>getattr</code> or the <code>__getitem__</code> methods).</p>\n\n<p>To summarize, we have :</p>\n\n<pre><code>>>> class A(object):\n... def __repr__(self):\n... return 'A()'\n... def __nonzero__(self):\n... return False\n\n>>> class B(object):\n... def __repr__(self):\n... return 'B()'\n... def __len__(self):\n... return 0\n\n>>> class C(object):\n... def __repr__(self):\n... return 'C()'\n... def __cmp__(self, other):\n... return 0\n\n>>> class D(object):\n... def __repr__(self):\n... return 'D()'\n... def __eq__(self, other):\n... return True\n\n>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:\n... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \\\n... (repr(obj), bool(obj), obj == None, obj is None)\n '': bool(obj) -> False, obj == None -> False, obj is None -> False\n (): bool(obj) -> False, obj == None -> False, obj is None -> False\n []: bool(obj) -> False, obj == None -> False, obj is None -> False\n {}: bool(obj) -> False, obj == None -> False, obj is None -> False\n 0: bool(obj) -> False, obj == None -> False, obj is None -> False\n 0.0: bool(obj) -> False, obj == None -> False, obj is None -> False\n A(): bool(obj) -> False, obj == None -> False, obj is None -> False\n B(): bool(obj) -> False, obj == None -> False, obj is None -> False\n C(): bool(obj) -> True, obj == None -> True, obj is None -> False\n D(): bool(obj) -> True, obj == None -> True, obj is None -> False\nNone: bool(obj) -> False, obj == None -> True, obj is None -> True\n</code></pre>\n"
},
{
"answer_id": 100764,
"author": "badp",
"author_id": 13992,
"author_profile": "https://Stackoverflow.com/users/13992",
"pm_score": 5,
"selected": false,
"text": "<p>Because <code>None</code> is not the only thing that is considered false.</p>\n\n<pre><code>if not False:\n print \"False is false.\"\nif not 0:\n print \"0 is false.\"\nif not []:\n print \"An empty list is false.\"\nif not ():\n print \"An empty tuple is false.\"\nif not {}:\n print \"An empty dict is false.\"\nif not \"\":\n print \"An empty string is false.\"\n</code></pre>\n\n<p><code>False</code>, <code>0</code>, <code>()</code>, <code>[]</code>, <code>{}</code> and <code>\"\"</code> are all different from <code>None</code>, so your two code snippets are <em>not</em> equivalent.</p>\n\n<p>Moreover, consider the following:</p>\n\n<pre><code>>>> False == 0\nTrue\n>>> False == ()\nFalse\n</code></pre>\n\n<p><code>if object:</code> is <em>not</em> an equality check. <code>0</code>, <code>()</code>, <code>[]</code>, <code>None</code>, <code>{}</code>, etc. <em>are</em> all different from each other, but they all <em>evaluate</em> to False.</p>\n\n<p>This is the \"magic\" behind short circuiting expressions like:</p>\n\n<pre><code>foo = bar and spam or eggs\n</code></pre>\n\n<p>which is shorthand for:</p>\n\n<pre><code>if bar:\n foo = spam\nelse:\n foo = eggs\n</code></pre>\n\n<p>although you really should write:</p>\n\n<pre><code>foo = spam if bar else egg\n</code></pre>\n"
},
{
"answer_id": 100766,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 2,
"selected": false,
"text": "<p>These two comparisons serve different purposes. The former checks for boolean value of something, the second checks for identity with None value.</p>\n"
},
{
"answer_id": 100768,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>For one the first example is shorter and looks nicer. As per the other posts what you choose also depends on what you really want to do with the comparison.</p>\n"
},
{
"answer_id": 100771,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a> recommends to use <em><strong>is</strong></em> or <em><strong>is not</strong></em> if you are testing for None-ness</p>\n<blockquote>\n<pre><code>- Comparisons to singletons like None should always be done with\n 'is' or 'is not', never the equality operators.\n</code></pre>\n</blockquote>\n<p>On the other hand if you are testing for more than None-ness, you should use the boolean operator.</p>\n"
},
{
"answer_id": 100775,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is \"it depends\".</p>\n\n<p>I use the first example if I consider 0, \"\", [] and False (list not exhaustive) to be equivalent to None in this context.</p>\n"
},
{
"answer_id": 100828,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, I chose a consistent approach across languages: I do <code>if (var)</code> (or equivalent) only if var is declared as boolean (or defined as such, in C we don't have a specific type). I even prefix these variables with a <code>b</code> (so it would be <code>bVar</code> actually) to be sure I won't accidentally use another type here.<br>\nI don't really like implicit casting to boolean, even less when there are numerous, complex rules.</p>\n\n<p>Of course, people will disagree. Some go farther, I see <code>if (bVar == true)</code> in the Java code at my work (too redundant for my taste!), others love too much compact syntax, going <code>while (line = getNextLine())</code> (too ambiguous for me).</p>\n"
},
{
"answer_id": 100903,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": false,
"text": "<p>These are actually both poor practices. Once upon a time, it was considered OK to casually treat None and False as similar. However, since Python 2.2 this is not the best policy.</p>\n\n<p>First, when you do an <code>if x</code> or <code>if not x</code> kind of test, Python has to implicitly convert <code>x</code> to boolean. The rules for the <code>bool</code> function describe a raft of things which are False; everything else is True. If the value of x wasn't properly boolean to begin with, this implicit conversion isn't really the clearest way to say things. </p>\n\n<p>Before Python 2.2, there was no bool function, so it was even less clear.</p>\n\n<p>Second, you shouldn't really test with <code>== None</code>. You should use <code>is None</code> and <code>is not None</code>.</p>\n\n<p>See PEP 8, <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a>. </p>\n\n<blockquote>\n<pre><code>- Comparisons to singletons like None should always be done with\n 'is' or 'is not', never the equality operators.\n\n Also, beware of writing \"if x\" when you really mean \"if x is not None\"\n -- e.g. when testing whether a variable or argument that defaults to\n None was set to some other value. The other value might have a type\n (such as a container) that could be false in a boolean context!\n</code></pre>\n</blockquote>\n\n<p>How many singletons are there? Five: <code>None</code>, <code>True</code>, <code>False</code>, <code>NotImplemented</code> and <code>Ellipsis</code>. Since you're really unlikely to use <code>NotImplemented</code> or <code>Ellipsis</code>, and you would never say <code>if x is True</code> (because simply <code>if x</code> is a lot clearer), you'll only ever test <code>None</code>.</p>\n"
},
{
"answer_id": 100974,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 2,
"selected": false,
"text": "<p>If you ask</p>\n\n<pre><code>if not spam:\n print \"Sorry. No SPAM.\"\n</code></pre>\n\n<p>the <em>__nonzero__</em> method of <em>spam</em> gets called. From the Python manual:</p>\n\n<blockquote>\n <p><strong>__nonzero__</strong>(<em>self</em>)\n Called to implement truth value testing, and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined (see below). If a class defines neither __len__() nor __nonzero__(), all its instances are considered true.</p>\n</blockquote>\n\n<p>If you ask</p>\n\n<pre><code>if spam == None:\n print \"Sorry. No SPAM here either.\"\n</code></pre>\n\n<p>the <em>__eq__</em> method of <em>spam</em> gets called with the argument <em>None</em>.</p>\n\n<p>For more information of the customization possibilities have a look at the Python documenation at <a href=\"https://docs.python.org/reference/datamodel.html#basic-customization\" rel=\"nofollow noreferrer\">https://docs.python.org/reference/datamodel.html#basic-customization</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
]
| I've seen several examples of code like this:
```
if not someobj:
#do something
```
But I'm wondering why not doing:
```
if someobj == None:
#do something
```
Is there any difference? Does one have an advantage over the other? | In the first test, Python try to convert the object to a `bool` value if it is not already one. Roughly, **we are asking the object : are you meaningful or not ?** This is done using the following algorithm :
1. If the object has a `__nonzero__` special method (as do numeric built-ins, `int` and `float`), it calls this method. It must either return a `bool` value which is then directly used, or an `int` value that is considered `False` if equal to zero.
2. Otherwise, if the object has a `__len__` special method (as do container built-ins, `list`, `dict`, `set`, `tuple`, ...), it calls this method, considering a container `False` if it is empty (length is zero).
3. Otherwise, the object is considered `True` unless it is `None` in which case, it is considered `False`.
In the second test, the object is compared for equality to `None`. Here, **we are asking the object, "Are you equal to this other value?"** This is done using the following algorithm :
1. If the object has a `__eq__` method, it is called, and the return value is then converted to a `bool`value and used to determine the outcome of the `if`.
2. Otherwise, if the object has a `__cmp__` method, it is called. This function must return an `int` indicating the order of the two object (`-1` if `self < other`, `0` if `self == other`, `+1` if `self > other`).
3. Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the `is` operator).
There is another test possible using the `is` operator. **We would be asking the object, "Are you this particular object?"**
Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values (`None` meaning not initialized for a member field for exemple, or when using the `getattr` or the `__getitem__` methods).
To summarize, we have :
```
>>> class A(object):
... def __repr__(self):
... return 'A()'
... def __nonzero__(self):
... return False
>>> class B(object):
... def __repr__(self):
... return 'B()'
... def __len__(self):
... return 0
>>> class C(object):
... def __repr__(self):
... return 'C()'
... def __cmp__(self, other):
... return 0
>>> class D(object):
... def __repr__(self):
... return 'D()'
... def __eq__(self, other):
... return True
>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \
... (repr(obj), bool(obj), obj == None, obj is None)
'': bool(obj) -> False, obj == None -> False, obj is None -> False
(): bool(obj) -> False, obj == None -> False, obj is None -> False
[]: bool(obj) -> False, obj == None -> False, obj is None -> False
{}: bool(obj) -> False, obj == None -> False, obj is None -> False
0: bool(obj) -> False, obj == None -> False, obj is None -> False
0.0: bool(obj) -> False, obj == None -> False, obj is None -> False
A(): bool(obj) -> False, obj == None -> False, obj is None -> False
B(): bool(obj) -> False, obj == None -> False, obj is None -> False
C(): bool(obj) -> True, obj == None -> True, obj is None -> False
D(): bool(obj) -> True, obj == None -> True, obj is None -> False
None: bool(obj) -> False, obj == None -> True, obj is None -> True
``` |
100,774 | <p>The following JavaScript supposes to read the popular tags from an XML file and applies the XSL Stylesheet and output to the browser as HTML.</p>
<pre><code>function ShowPopularTags() {
xml = XMLDocLoad("http://localhost/xml/tags/popular.xml?s=94987898");
xsl = XMLDocLoad("http://localhost/xml/xsl/popular-tags.xsl");
if (window.ActiveXObject) {
// code for IE
ex = xml.transformNode(xsl);
ex = ex.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ex;
} else if (document.implementation && document.implementation.createDocument) {
// code for Mozilla, Firefox, Opera, etc.
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("popularTags").appendChild(resultDocument);
var ihtml = document.getElementById("popularTags").innerHTML;
ihtml = ihtml.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ihtml;
}
}
ShowPopularTags();
</code></pre>
<p>The issue with this script is sometime it manages to output the resulting HTML code, sometime it doesn't. Anyone knows where is going wrong?</p>
| [
{
"answer_id": 100887,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "<p>Well, that code follows entirely different paths for IE and everything-else. I assume the problem is limited to one of them. What browsers have you tried it on, and which exhibit this error?</p>\n\n<p>The only other thing I can think of is that the popularTags element may not exist when you're trying to do stuff to it. How is this function being executed? In an onload/domready event?</p>\n"
},
{
"answer_id": 100930,
"author": "poh",
"author_id": 17074,
"author_profile": "https://Stackoverflow.com/users/17074",
"pm_score": 0,
"selected": false,
"text": "<p>Dan. IE executes the script with no issue. I am facing the problem in Firefox. The popularTags element exists in the HTML document that calls the function.</p>\n\n<pre>\n<div id=\"popularTags\" style=\"line-height:18px\"></div>\n<script language=\"javascript\" type=\"text/javascript\">\n function ShowPopularTags()\n {\n xml=XMLDocLoad(\"http://localhost/xml/tags/popular.xml?s=29497105\");\n xsl=XMLDocLoad(\"http://localhost/xml/xsl/popular-tags.xsl\");\n\n if (window.ActiveXObject){\n // code for IE\n ex=xml.transformNode(xsl);\n ex = ex.replace(/\\\\/g, \"\");\n document.getElementById(\"popularTags\").innerHTML=ex;\n }\n else if (document.implementation && document.implementation.createDocument){\n // code for Mozilla, Firefox, Opera, etc.\n xsltProcessor=new XSLTProcessor();\n xsltProcessor.importStylesheet(xsl);\n resultDocument = xsltProcessor.transformToFragment(xml,document);\n document.getElementById(\"popularTags\").appendChild(resultDocument);\n\n var ihtml = document.getElementById(\"popularTags\").innerHTML;\n ihtml = ihtml.replace(/\\\\/g, \"\");\n document.getElementById(\"popularTags\").innerHTML = ihtml;\n }\n }\n\n ShowPopularTags();\n</script> \n\n</pre>\n"
},
{
"answer_id": 101048,
"author": "Twan",
"author_id": 6702,
"author_profile": "https://Stackoverflow.com/users/6702",
"pm_score": 1,
"selected": false,
"text": "<p>To avoid problems with things loading in parallel (as hinted by Dan), it is always a good idea to call such scripting only when the page has fully loaded.</p>\n\n<p>Ideally you put the script-tags in the page head and call ShowPopularTags(); in the body Onload item. I.e.</p>\n\n<pre><code><BODY onLoad=\"ShowPopularTags();\">\n</code></pre>\n\n<p>That way you are completely sure that your document.getElementById(\"popularTags\") doesn't fail because the scripting is called before the HTML containing the element is fully loaded.</p>\n\n<p>Also, can we see your XMLDocLoad function? If that contains non-sequential elements as well, you might be facing a problem where the XSLT transformation takes place before the objects xml and xsl are fully loaded.</p>\n"
},
{
"answer_id": 110729,
"author": "poh",
"author_id": 17074,
"author_profile": "https://Stackoverflow.com/users/17074",
"pm_score": 0,
"selected": false,
"text": "<p>The following is the XMLDocLoad function.</p>\n\n<pre>\nfunction XMLDocLoad(fname)\n{\n var xmlDoc;\n\n if (window.ActiveXObject){\n // code for IE\n xmlDoc=new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async=false;\n xmlDoc.load(fname);\n\n return(xmlDoc);\n }\n else if(document.implementation && document.implementation.createDocument){\n // code for Mozilla, Firefox, Opera, etc.\n xmlDoc=document.implementation.createDocument(\"\",\"\",null);\n\n xmlDoc.async=false;\n xmlDoc.load(fname);\n\n return(xmlDoc);\n\n }\n else{\n alert('Your browser cannot handle this script');\n }\n\n\n}\n</pre>\n"
},
{
"answer_id": 110853,
"author": "Twan",
"author_id": 6702,
"author_profile": "https://Stackoverflow.com/users/6702",
"pm_score": 2,
"selected": true,
"text": "<p>Are you forced into the synchronous solution you are using now, or is an asynchronous solution an option as well? I recall Firefox has had it's share of problems with synchronous calls in the past, and I don't know how much of that is still carried with it. I have seen situations where the entire Firefox interface would lock up for as long as the request was running (which, depending on timeout settings, can take a very long time).</p>\n\n<p>It would require a bit more work on your end, but the solution would be something like the following. This is the code I use for handling XSLT stuff with Ajax (rewrote it slightly because my code is object oriented and contains a loop that parses out the appropriate XSL document from the XML document first loaded)</p>\n\n<p>Note: make sure you declare your version of oCurrentRequest and oXMLRequest outside of the functions, since it will be carried over.</p>\n\n<pre><code>if (window.XMLHttpRequest)\n{\n oCurrentRequest = new XMLHttpRequest();\n oCurrentRequest.onreadystatechange = processReqChange;\n oCurrentRequest.open('GET', sURL, true);\n oCurrentRequest.send(null);\n}\nelse if (window.ActiveXObject)\n{\n oCurrentRequest = new ActiveXObject('Microsoft.XMLHTTP');\n if (oCurrentRequest)\n {\n oCurrentRequest.onreadystatechange = processReqChange;\n oCurrentRequest.open('GET', sURL, true);\n oCurrentRequest.send();\n }\n}\n</code></pre>\n\n<p>After this you'd just need a function named processReqChange that contains something like the following:</p>\n\n<pre><code>function processReqChange()\n{\n if (oCurrentRequest.readyState == 4)\n {\n if (oCurrentRequest.status == 200)\n {\n oXMLRequest = oCurrentRequest;\n oCurrentRequest = null;\n loadXSLDoc();\n }\n }\n}\n</code></pre>\n\n<p>And ofcourse you'll need to produce a second set of functions to handle the XSL loading (starting from loadXSLDoc on, for example).</p>\n\n<p>Then at the end of you processXSLReqChange you can grab your XML result and XSL result and do the transformation.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17074/"
]
| The following JavaScript supposes to read the popular tags from an XML file and applies the XSL Stylesheet and output to the browser as HTML.
```
function ShowPopularTags() {
xml = XMLDocLoad("http://localhost/xml/tags/popular.xml?s=94987898");
xsl = XMLDocLoad("http://localhost/xml/xsl/popular-tags.xsl");
if (window.ActiveXObject) {
// code for IE
ex = xml.transformNode(xsl);
ex = ex.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ex;
} else if (document.implementation && document.implementation.createDocument) {
// code for Mozilla, Firefox, Opera, etc.
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("popularTags").appendChild(resultDocument);
var ihtml = document.getElementById("popularTags").innerHTML;
ihtml = ihtml.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ihtml;
}
}
ShowPopularTags();
```
The issue with this script is sometime it manages to output the resulting HTML code, sometime it doesn't. Anyone knows where is going wrong? | Are you forced into the synchronous solution you are using now, or is an asynchronous solution an option as well? I recall Firefox has had it's share of problems with synchronous calls in the past, and I don't know how much of that is still carried with it. I have seen situations where the entire Firefox interface would lock up for as long as the request was running (which, depending on timeout settings, can take a very long time).
It would require a bit more work on your end, but the solution would be something like the following. This is the code I use for handling XSLT stuff with Ajax (rewrote it slightly because my code is object oriented and contains a loop that parses out the appropriate XSL document from the XML document first loaded)
Note: make sure you declare your version of oCurrentRequest and oXMLRequest outside of the functions, since it will be carried over.
```
if (window.XMLHttpRequest)
{
oCurrentRequest = new XMLHttpRequest();
oCurrentRequest.onreadystatechange = processReqChange;
oCurrentRequest.open('GET', sURL, true);
oCurrentRequest.send(null);
}
else if (window.ActiveXObject)
{
oCurrentRequest = new ActiveXObject('Microsoft.XMLHTTP');
if (oCurrentRequest)
{
oCurrentRequest.onreadystatechange = processReqChange;
oCurrentRequest.open('GET', sURL, true);
oCurrentRequest.send();
}
}
```
After this you'd just need a function named processReqChange that contains something like the following:
```
function processReqChange()
{
if (oCurrentRequest.readyState == 4)
{
if (oCurrentRequest.status == 200)
{
oXMLRequest = oCurrentRequest;
oCurrentRequest = null;
loadXSLDoc();
}
}
}
```
And ofcourse you'll need to produce a second set of functions to handle the XSL loading (starting from loadXSLDoc on, for example).
Then at the end of you processXSLReqChange you can grab your XML result and XSL result and do the transformation. |
100,808 | <p>I want to receive the following <code>HTTP</code> request in <code>PHP:</code></p>
<pre><code>Content-type: multipart/form-data;boundary=main_boundary
--main_boundary
Content-type: text/xml
<?xml version='1.0'?>
<content>
Some content goes here
</content>
--main_boundary
Content-type: multipart/mixed;boundary=sub_boundary
--sub_boundary
Content-type: application/octet-stream
File A contents
--sub_boundary
Content-type: application/octet-stream
File B contents
--sub_boundary
--main_boundary--
</code></pre>
<p>(Note: I have indented the sub-parts only to make it more readable for this post.)</p>
<p>I'm not very fluent in PHP and would like to get some help/pointers to figure out how to receive this kind of multipart form request in PHP code. I have once written some code where I received a standard HTML form and then I could access the form elements by using their name as index key in the <code>$HTTP_GET_VARS</code> array, but in this case there are no form element names, and the form data parts are not linear (i.e. sub parts = multilevel array).</p>
<p>Grateful for any help!</p>
<p>/Robert</p>
| [
{
"answer_id": 100825,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": -1,
"selected": false,
"text": "<p>Uploadeds files will be accessible through the $_FILE global variable, other parameters will be accessible trough the $_GET global variable.</p>\n"
},
{
"answer_id": 100874,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 3,
"selected": true,
"text": "<p><code>$HTTP_GET_VARS</code>, <code>$HTTP_POST_VARS</code>, etc. is an obsolete notation, you should be using <code>$_GET</code>, <code>$_POST</code>, etc.</p>\n\n<p>Now, the file contents should be in the <code>$_FILES</code> global array, whereas, if there are no element names, I'm not sure about whether the rest of the content will show up in <code>$_POST</code>. Anyway, if <code>always_populate_raw_post_data</code> setting is true in <em>php.ini</em>, the data should be in <code>$HTTP_RAW_POST_DATA</code>. Also, the whole request should show up when reading <em>php://input</em>.</p>\n"
},
{
"answer_id": 18263855,
"author": "Heavy_Bullets",
"author_id": 2059170,
"author_profile": "https://Stackoverflow.com/users/2059170",
"pm_score": 1,
"selected": false,
"text": "<p>You should note: </p>\n\n<p>“php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype=”multipart/form-data”</p>\n\n<p>From php manual... so it seems php://input is not available </p>\n\n<p>Cannot comment yet but this is intened to complement pilsetnieks answer</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7891/"
]
| I want to receive the following `HTTP` request in `PHP:`
```
Content-type: multipart/form-data;boundary=main_boundary
--main_boundary
Content-type: text/xml
<?xml version='1.0'?>
<content>
Some content goes here
</content>
--main_boundary
Content-type: multipart/mixed;boundary=sub_boundary
--sub_boundary
Content-type: application/octet-stream
File A contents
--sub_boundary
Content-type: application/octet-stream
File B contents
--sub_boundary
--main_boundary--
```
(Note: I have indented the sub-parts only to make it more readable for this post.)
I'm not very fluent in PHP and would like to get some help/pointers to figure out how to receive this kind of multipart form request in PHP code. I have once written some code where I received a standard HTML form and then I could access the form elements by using their name as index key in the `$HTTP_GET_VARS` array, but in this case there are no form element names, and the form data parts are not linear (i.e. sub parts = multilevel array).
Grateful for any help!
/Robert | `$HTTP_GET_VARS`, `$HTTP_POST_VARS`, etc. is an obsolete notation, you should be using `$_GET`, `$_POST`, etc.
Now, the file contents should be in the `$_FILES` global array, whereas, if there are no element names, I'm not sure about whether the rest of the content will show up in `$_POST`. Anyway, if `always_populate_raw_post_data` setting is true in *php.ini*, the data should be in `$HTTP_RAW_POST_DATA`. Also, the whole request should show up when reading *php://input*. |
100,812 | <p>Not for the first time, I've accidentally done "svn switch" from somewhere below the root of my project. This switches that subdirectory only, but how do I undo this?</p>
<p>If I try switching the subdirectory back to the original branch I get:</p>
<pre><code>"svn: Directory 'subdir\_svn' containing working copy admin area is missing"
</code></pre>
<p><strong>Update</strong>: I've got changes in the subdir, so I don't want to do a delete. </p>
<p>In the short term I've fixed it by reapplying the changes, but I was after a way to get Subversion to re-switch back to where I came from... or is this a missing feature?</p>
| [
{
"answer_id": 100823,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "<p>Quick hack: Delete the directory, go one level up, and run svn update.</p>\n"
},
{
"answer_id": 100870,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": -1,
"selected": false,
"text": "<pre><code>svn revert <dir>\n</code></pre>\n\n<p>Or, yes, delete it and grab another copy.</p>\n"
},
{
"answer_id": 101176,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 3,
"selected": false,
"text": "<p>Without knowing exactly how you did the switch and how your directory and repository layout is, it's hard to say what went wrong in your case.</p>\n\n<p>There is no way to really \"revert\" a switch. Generally, svn switch can be undone by a switch back to the original location, i.e. when the original location is at svn://url/to/orig/dir, then the following should work:</p>\n\n<p>Switching a subdirectory to a different part of the repository</p>\n\n<pre><code>svn switch svn://path/to/switched/dir/ subdir\n</code></pre>\n\n<p>... and switching it back again</p>\n\n<pre><code>svn switch svn://url/to/orig/dir subdir\n</code></pre>\n\n<p>In your case it sounds as if you tried to switch a directory that is not part of your working copy.</p>\n"
},
{
"answer_id": 17536978,
"author": "durron597",
"author_id": 1768232,
"author_profile": "https://Stackoverflow.com/users/1768232",
"pm_score": 1,
"selected": false,
"text": "<p>I fixed this by checking in the changes in the switched directory, deleting the .svn files and the misplaced files, then using <code>svn checkout <rootUrl></code> followed by <code>svn update -r HEAD --force</code>.</p>\n\n<p>I don't think there's a clean way to do it.</p>\n"
},
{
"answer_id": 36919270,
"author": "Amol Patil",
"author_id": 1811749,
"author_profile": "https://Stackoverflow.com/users/1811749",
"pm_score": 0,
"selected": false,
"text": "<p>if the latest changes are just the switch then,</p>\n\n<p>Right click on common parent directory, tortoise svn->\nGo to svn logs. Right click on version before SVN Switch and select Revert to this revision.</p>\n"
},
{
"answer_id": 39392669,
"author": "CFWhitman",
"author_id": 3199068,
"author_profile": "https://Stackoverflow.com/users/3199068",
"pm_score": 0,
"selected": false,
"text": "<p>It seems like it works to run another switch back to the the proper path to the directory you are actually in. That is, if you ran:</p>\n\n<pre><code>svn switch file:///srv/svn/someproject/branch/27\n</code></pre>\n\n<p>while you were in someproject/subdir, then run</p>\n\n<pre><code>svn switch file:///srv/svn/someproject/branch/26/subdir\n</code></pre>\n\n<p>and then run your original switch from the correct place.</p>\n\n<p>This seems to restore order.</p>\n"
},
{
"answer_id": 53404577,
"author": "dash-tom-bang",
"author_id": 65845,
"author_profile": "https://Stackoverflow.com/users/65845",
"pm_score": 0,
"selected": false,
"text": "<p>My use case seemed simple; I wanted to switch back to the directory with the current directory's name rooted at the parent directory's URL. The hassle here, of course, is getting and then copying the parent directory's URL. This script in Windows batch did it for me. Bash users can do it much more easily but the gist is here. It seems like this functionality would be trivial to fold into SVN directly...</p>\n\n<p>You may need to add quotes around the parameter to switch but I'll leave that to you. In case it's not obvious, you need to run this in the directory that you want to \"unswitch\". It doesn't take parameters or anything at this time although that's a pretty straight forward addition should you be so inclined (just <code>cd \\d %1</code> at the top if <code>%1</code> isn't empty).</p>\n\n<p><strong>svn-unswitch.bat</strong></p>\n\n<pre><code>@echo off\nsetlocal\n\nfor /f \"tokens=*\" %%u in ('svn info --show-item url ..') do set \"PARENT_URL=%%u\"\ncall :SetDirName %CD%\nsvn switch %PARENT_URL%/%DIRNAME%\ngoto :eof\n\n:SetDirName\n set DIRNAME=%~nx1\n goto :eof\n</code></pre>\n\n<p>Certified: <em>Works On My Machine!</em></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17641/"
]
| Not for the first time, I've accidentally done "svn switch" from somewhere below the root of my project. This switches that subdirectory only, but how do I undo this?
If I try switching the subdirectory back to the original branch I get:
```
"svn: Directory 'subdir\_svn' containing working copy admin area is missing"
```
**Update**: I've got changes in the subdir, so I don't want to do a delete.
In the short term I've fixed it by reapplying the changes, but I was after a way to get Subversion to re-switch back to where I came from... or is this a missing feature? | Quick hack: Delete the directory, go one level up, and run svn update. |
100,824 | <p>The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)</p>
<pre><code>namespace StructsVsClasses
{
class Program
{
static void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
Console.ReadKey();
}
}
struct sampleStruct
{
public int IntegerValue;
}
class sampleClass
{
public int IntegerValue;
}
}
</code></pre>
| [
{
"answer_id": 100856,
"author": "Grimtron",
"author_id": 17378,
"author_profile": "https://Stackoverflow.com/users/17378",
"pm_score": 1,
"selected": false,
"text": "<p>I guess it's OK to show the difference as far as value/reference types are concerned this way. It might be a little bit cleaner to use methods for the console output, though.</p>\n\n<p>As you said your \"someone\" was new to development this might not be too important, but there is a nice list of further differences between classes and structs in C# here:</p>\n\n<p><a href=\"http://www.jaggersoft.com/pubs/StructsVsClasses.htm\" rel=\"nofollow noreferrer\">C# struct/classes differences</a></p>\n"
},
{
"answer_id": 100882,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Well, your <em>explanation</em> isn't an explanation at all, it's an observation of behavior, which is different.</p>\n\n<p>If you want an explanation of what the difference is, then you need a piece of text <em>explaining</em> it. And the behavior explained can be ed with the code.</p>\n\n<p>The page linked to by Grimtron is good for detailing all the individual differences between a class and a struct, and pieces of it would serve as a <em>overview explanation</em>, in particular read the following items:</p>\n\n<ul>\n<li>Exists on stack or heap?</li>\n<li>Inheritance differences?</li>\n</ul>\n\n<p>But I wouldn't link to that page as an <em>explanation</em> for what the differences are. It's like trying to describe what a car is, and just listing up all the parts that make up a car. You still need to understand the big picture to understand what a car is, and such a list would not be able to give you that.</p>\n\n<p>In my mind, an explanation is something that tells you how something works, and then all the details follow naturally from that.</p>\n\n<p>For instance, if you understand the basic underlying principles behind a value type vs. a reference type, a lot of the details on that page makes sense, <em>if you think about it</em>.</p>\n\n<p>For instance, a value type (struct) is allocated where it is declared, inline, so to speak. It takes up stack space, or makes a class bigger in memory. A reference type, however, is a pointer, which has a fixed size, to <em>somewhere else in memory where the actual object is stored</em>.</p>\n\n<p>With the above explanation, the following details makes sense:</p>\n\n<ul>\n<li>A struct variable cannot be null (ie. it always takes up the necessary space)</li>\n<li>An object reference can be null (ie. the pointer can point to nothing)</li>\n<li>A struct does not add pressure to garbage collection (garbage collection works with the heap, which is where objects live in that <em>somewhere else</em> space)</li>\n<li>Always have a default constructor. Since you can declare any value-type variable (which is basically a kind of struct), without giving it a value, there must be some underlying magic that clears up that space (remember I said it took up space anyhow)</li>\n</ul>\n\n<p>Other things, like all the things related to inheritance, needs their own part in the explanation.</p>\n\n<p>And so on...</p>\n"
},
{
"answer_id": 100924,
"author": "Brad Bruce",
"author_id": 5008,
"author_profile": "https://Stackoverflow.com/users/5008",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li><p>I don't see what you're trying to show with your sample. </p></li>\n<li><p>The way I explain it to people is \"A structure <em>holds</em> stuff. A class <em>does</em> something with it\".</p></li>\n</ol>\n"
},
{
"answer_id": 100981,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 0,
"selected": false,
"text": "<p>lassevk,</p>\n\n<p>Thanks for that (semantic nitpicking aside :=) - however, maybe I wasn't as clear as I could be, I was trying to <em>show</em> rather than <em>tell</em> as to someone new to development, a block of prose like that means about as much as the average bit of Star Trek-esque technobabble.</p>\n\n<p>The page Grimtron linked to, and your text will certainly be useful once my newbie is more familiar/comfortable with .net and programming in general, I'm sure!</p>\n"
},
{
"answer_id": 101153,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": true,
"text": "<p>The difference might be easier to understand when the struct/class is a member of another class.</p>\n\n<p>Example with class:</p>\n\n<pre><code>class PointClass {\n int double X;\n int double Y;\n}\n\nclass Circle {\n PointClass Center = new PointClass() { X = 0, Y = 0; }\n}\n\nstatic void Main() {\n Circle c = new Circle();\n Console.WriteLine(c.Center.X);\n c.Center.X = 42;\n Console.WriteLine(c.Center.X);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>0\n42\n</code></pre>\n\n<p>Example with struct:</p>\n\n<pre><code>struct Point {\n int double X;\n int double Y;\n}\n\nclass Circle {\n PointStruct Center = new PointStruct() { X = 0, Y = 0; }\n}\n\nstatic void Main() {\n Circle c = new Circle();\n Console.WriteLine(c.Center.X);\n c.Center.X = 42;\n Console.WriteLine(c.Center.X);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>0\n0\n</code></pre>\n"
},
{
"answer_id": 747259,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 1,
"selected": false,
"text": "<p>A <strong>structure</strong> is a limp, lifeless arrangement of data. Flaccid and passive.</p>\n\n<p>A <strong>class</strong> explodes into action in the blink of a constructor. Bursting with vitality a class is the superhero of the modern [programming] world.</p>\n"
},
{
"answer_id": 751240,
"author": "Prashant Cholachagudda",
"author_id": 85606,
"author_profile": "https://Stackoverflow.com/users/85606",
"pm_score": 0,
"selected": false,
"text": "<p>The very basic difference is that Structure is Value Types and Class is Reference Type</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
]
| The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)
```
namespace StructsVsClasses
{
class Program
{
static void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
Console.ReadKey();
}
}
struct sampleStruct
{
public int IntegerValue;
}
class sampleClass
{
public int IntegerValue;
}
}
``` | The difference might be easier to understand when the struct/class is a member of another class.
Example with class:
```
class PointClass {
int double X;
int double Y;
}
class Circle {
PointClass Center = new PointClass() { X = 0, Y = 0; }
}
static void Main() {
Circle c = new Circle();
Console.WriteLine(c.Center.X);
c.Center.X = 42;
Console.WriteLine(c.Center.X);
}
```
Output:
```
0
42
```
Example with struct:
```
struct Point {
int double X;
int double Y;
}
class Circle {
PointStruct Center = new PointStruct() { X = 0, Y = 0; }
}
static void Main() {
Circle c = new Circle();
Console.WriteLine(c.Center.X);
c.Center.X = 42;
Console.WriteLine(c.Center.X);
}
```
Output:
```
0
0
``` |
100,829 | <p>I'm trying to write a script to allow me to log in to a console servers 48 ports so that I can quickly determine what devices are connected to each serial line.</p>
<p>Essentially I want to be able to have a script that, given a list of hosts/ports, telnets to the first device in the list and leaves me in interactive mode so that I can log in and confirm the device, then when I close the telnet session, connects to the next session in the list.</p>
<p>The problem I'm facing is that if I start a telnet session from within an executable bash script, the session terminates immediately, rather than waiting for input.</p>
<p>For example, given the following code:</p>
<pre><code>$ cat ./telnetTest.sh
#!/bin/bash
while read line
do
telnet $line
done
$
</code></pre>
<p>When I run the command 'echo "hostname" | testscript.sh' I receive the following output:</p>
<pre><code>$ echo "testhost" | ./telnetTest.sh
Trying 192.168.1.1...
Connected to testhost (192.168.1.1).
Escape character is '^]'.
Connection closed by foreign host.
$
</code></pre>
<p>Does anyone know of a way to stop the telnet session being closed automatically?</p>
| [
{
"answer_id": 100842,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you could try bash -i to force the session to be in interactive mode.</p>\n"
},
{
"answer_id": 100879,
"author": "user11323",
"author_id": 11323,
"author_profile": "https://Stackoverflow.com/users/11323",
"pm_score": 3,
"selected": false,
"text": "<p>I think you should look at <strong>expect</strong> program. It`s present in all modern linux distros. Here is some exmaple script:</p>\n\n<pre><code>#!/usr/bin/expect -f\nspawn telnet $host_name\nexpect {\n \"T0>\" {}\n -re \"Connection refused|No route to host|Invalid argument|lookup failure\"\n {send_user \"\\r******* connection error, bye.\\n\";exit}\n default {send_user \"\\r******* connection error (telnet timeout),\n bye.\\n\";exit}\n}\nsend \"command\\n\"\nexpect -timeout 1 \"something\"\n</code></pre>\n\n<p><strong>spawn</strong> command start remote login program (telnet, ssh, netcat etc)</p>\n\n<p><strong>expext</strong> command used to... hm.. expect something from remote session</p>\n\n<p><strong>send</strong> - sending commands</p>\n\n<p><strong>send_user</strong> - to print comments to stdout</p>\n"
},
{
"answer_id": 100897,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 0,
"selected": false,
"text": "<p>The problem in your example is that you link the input of your script (and indirectly of <code>telnet</code>) to the output of the <code>echo</code>. So after <code>echo</code> is done and <code>telnet</code> is started, there is no more input to read. A simple fix could be to replace <code>echo \"testhost\"</code> by <code>{ echo \"testhost\"; cat; }</code>.</p>\n\n<p>Edit: <code>telnet</code> doesn't seem to like taking input from a pipe. However, <code>netcat</code> does and is probably just suitable in this case.</p>\n"
},
{
"answer_id": 101016,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 4,
"selected": true,
"text": "<p>You need to redirect the Terminal input to the <code>telnet</code> process. This should be <code>/dev/tty</code>. So your script will look something like:</p>\n\n<pre><code>#!/bin/bash\n\nfor HOST in `cat`\ndo\n echo Connecting to $HOST...\n telnet $HOST </dev/tty\ndone\n</code></pre>\n"
},
{
"answer_id": 101819,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 0,
"selected": false,
"text": "<p>@muz \nI have a setting with ssh, no telnet, so i can't test if your problem is telnet related, but running the following script logs me successively to the different machines asking for a password. </p>\n\n<pre><code>for i in adele betty\ndo\nssh all@$i\ndone\n</code></pre>\n"
},
{
"answer_id": 102126,
"author": "Murali Suriar",
"author_id": 6306,
"author_profile": "https://Stackoverflow.com/users/6306",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks Dave - it was the TTY redirection that I was missing.</p>\n\n<p>The complete solution I used, for those who are interested:</p>\n\n<pre><code>#!/bin/bash\n\nTTY=`tty` # Find out what tty we have been invoked from.\nfor i in `cat hostnames.csv` # List of hosts/ports\ndo\n # Separate port/host into separate variables\n host=`echo $i | awk -F, '{ print $1 }'`\n port=`echo $i | awk -F, '{ print $2 }'`\n telnet $host $port < $TTY # Connect to the current device\ndone\n</code></pre>\n"
},
{
"answer_id": 1661098,
"author": "Prashant Ghodke",
"author_id": 200933,
"author_profile": "https://Stackoverflow.com/users/200933",
"pm_score": 1,
"selected": false,
"text": "<p>Telnet to Server using Shell Script Example:</p>\n\n<p><code>Test3.sh</code> File:</p>\n\n<pre><code>#!/bin/sh\n\n#SSG_details is file from which script will read ip adress and uname/password\n#to telnet.\n\nSSG_detail=/opt/Telnet/SSG_detail.txt\n\ncat $SSG_detail | while read ssg_det ; do\n\n ssg_ip=`echo $ssg_det|awk '{print $1}'`\n ssg_user=`echo $ssg_det|awk '{print $2}'`\n ssg_pwd=`echo $ssg_det|awk '{print $3}'`\n\n\n echo \" IP to telnet:\" $ssg_ip\n echo \" ssg_user:\" $ssg_user\n echo \" ssg_pwd:\" $ssg_pwd\n\n sh /opt/Telnet/Call_Telenet.sh $ssg_ip $ssg_user $ssg_pwd \n\ndone\n\n\nexit 0\n</code></pre>\n\n<p>The <code>Call_Telenet.sh</code> script is as follows:</p>\n\n<pre><code>#!/bin/sh\n\nDELAY=1 \nCOMM1='config t' #/* 1st commands to be run*/\nCOMM2='show run'\nCOMM3=''\nCOMM4=''\nCOMM5='exit'\nCOMM6='wr'\nCOMM7='ssg service-cache refresh all'\nCOMM8='exit' #/* 8th command to be run */\n\n\ntelnet $1 >> $logfile 2>> $logfile |&\nsleep $DELAY\necho -p $2 >> $logfile 2>> $logfile\nsleep $DELAY\necho -p $3 >> $logfile 2>> $logfile\nsleep $DELAY\necho -p $4 >> $logfile 2>> $logfile\nsleep $DELAY\necho -p $5 >> $logfile 2>> $logfile\nsleep $DELAY\n\nsleep $DELAY\nsleep $DELAY\nsleep $DELAY\necho -p $COMM7 >> $logfile 2>> $logfile\nsleep $DELAY\necho -p $COMM8 >> $logfile 2>> $logfile\nsleep $DELAY\n\nexit 0\n</code></pre>\n\n<p>Run the above file as follows:</p>\n\n<pre><code>$> ./test3.sh \n</code></pre>\n"
},
{
"answer_id": 1661161,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 0,
"selected": false,
"text": "<p>If your environment is X11-based, a possibility is to open an xterm running telnet:</p>\n\n<pre><code>xterm -e telnet $host $port\n</code></pre>\n\n<p>Operations in xterm are interactive and shell script is halted until xterm termination.</p>\n"
},
{
"answer_id": 7426783,
"author": "Graham",
"author_id": 946149,
"author_profile": "https://Stackoverflow.com/users/946149",
"pm_score": 0,
"selected": false,
"text": "<p>Try these links.</p>\n\n<p><a href=\"http://planetozh.com/blog/2004/02/telnet-script/\" rel=\"nofollow\">http://planetozh.com/blog/2004/02/telnet-script/</a></p>\n\n<p><a href=\"http://www.unix.com/unix-dummies-questions-answers/193-telnet-script.html\" rel=\"nofollow\">http://www.unix.com/unix-dummies-questions-answers/193-telnet-script.html</a></p>\n\n<pre><code>#!/bin/sh\n( echo open hostname\nsleep 5\necho username\nsleep 1\necho password\nsleep 1\necho some more output, etc. ) | telnet\n</code></pre>\n\n<p>They worked for me :D</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306/"
]
| I'm trying to write a script to allow me to log in to a console servers 48 ports so that I can quickly determine what devices are connected to each serial line.
Essentially I want to be able to have a script that, given a list of hosts/ports, telnets to the first device in the list and leaves me in interactive mode so that I can log in and confirm the device, then when I close the telnet session, connects to the next session in the list.
The problem I'm facing is that if I start a telnet session from within an executable bash script, the session terminates immediately, rather than waiting for input.
For example, given the following code:
```
$ cat ./telnetTest.sh
#!/bin/bash
while read line
do
telnet $line
done
$
```
When I run the command 'echo "hostname" | testscript.sh' I receive the following output:
```
$ echo "testhost" | ./telnetTest.sh
Trying 192.168.1.1...
Connected to testhost (192.168.1.1).
Escape character is '^]'.
Connection closed by foreign host.
$
```
Does anyone know of a way to stop the telnet session being closed automatically? | You need to redirect the Terminal input to the `telnet` process. This should be `/dev/tty`. So your script will look something like:
```
#!/bin/bash
for HOST in `cat`
do
echo Connecting to $HOST...
telnet $HOST </dev/tty
done
``` |
100,832 | <p>I would like to repeatedly capture snippets of audio on a Nokia mobile phone with a Java Midlet. My current experience is that using the code in Sun's documentation (see: <a href="http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html</a>) and wrapping this in a "while(true)" loop works, but the application slowly consumes all the memory on the phone and the program eventually throws an exception and fails to initiate further recordings.</p>
<p>The consumed memory isn't Java heap memory---my example program (below) shows that Java memory stays roughly static at around 185,000 bytes---but there is some kind of memory leak in the underlying supporting library provided by Nokia; I believe the memory leak occurs because if you try and start another (non-Java) application (e.g. web browser) after running the Java application for a while, the phone kills that application with a warning about lack of memory.</p>
<p>I've tried several different approaches from that taken by Sun's canonical example in the documentation (initialize everything each time round the loop, initialize as much as possible only once, call as many of the deallocate-style functions which shouldn't be strictly necessary etc.). None appear to be successful. Below is a simple example program which I believe should work, but crashes after running for 15 minutes or so on both the N80 (despite a firmware update) and N95. Other forums report this problem too, but the solutions presented there do not appear to work (for example, see: <a href="http://discussion.forum.nokia.com/forum/showthread.php?t=129876" rel="nofollow noreferrer">http://discussion.forum.nokia.com/forum/showthread.php?t=129876</a>).</p>
<pre><code>import javax.microedition.media.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Standalone extends MIDlet {
protected void startApp() {
final Form form = new Form("Test audio recording");
final StringItem status = new StringItem("Status","");
form.append(status);
final Command exit = new Command("Exit", Command.EXIT, 1);
form.addCommand(exit);
form.setCommandListener(new CommandListener() {
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exit) {
destroyApp(false);
notifyDestroyed();
}
}
});
Thread t = new Thread(){
public void run() {
int counter = 0;
while(true) {
//Code cut 'n' paste from Sun JSR135 javadocs for RecordControl:
try {
Player p = Manager.createPlayer("capture://audio");
p.realize();
RecordControl rc = (RecordControl)p.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
p.start();
Thread.currentThread().sleep(5000);
rc.commit();
p.close();
} catch (Exception e) {
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory()+
": Error: "+e);
break;
}
counter++;
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory());
System.gc(); //One forum post suggests this, but doesn't help
this.yield();
}
}
};
t.start();
final Display display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void pauseApp() {}
protected void destroyApp(boolean bool) {}
}
</code></pre>
| [
{
"answer_id": 100871,
"author": "Sarien",
"author_id": 1994377,
"author_profile": "https://Stackoverflow.com/users/1994377",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should file a bugreport instead of trying to work around that.</p>\n"
},
{
"answer_id": 109485,
"author": "Fostah",
"author_id": 16524,
"author_profile": "https://Stackoverflow.com/users/16524",
"pm_score": 1,
"selected": false,
"text": "<p>There is a known memory leak with the N-series Nokia devices. It is not specific to Java and is in the underbelly of the OS somewhere.</p>\n\n<p>Recently working on a game that targeted the Nokia N90, I had similar problems. I would run into memory problems that would accumulate over several different restarts of the application. The solution was just to reduce the overall quality and the amount of resources in the game...</p>\n\n<p>I would recommend attempting to update your firmware as newer versions supposedly address this problem. However, Nokia does not make it very easy to upgrade the firmware, in most cases you have to send the device off to Nokia. And, if this app is not just for your own personal use, you have to expect anyone using the N-series devices to not have the latest firmware.</p>\n\n<p>Finally, I would recommend spending some time looking around Forum Nokia as I know there are posts related to memory leaks and the N-series devices. Here is a post that seems to address the problem you are having.</p>\n\n<p><a href=\"http://discussion.forum.nokia.com/forum/showthread.php?t=123486\" rel=\"nofollow noreferrer\">http://discussion.forum.nokia.com/forum/showthread.php?t=123486</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18699/"
]
| I would like to repeatedly capture snippets of audio on a Nokia mobile phone with a Java Midlet. My current experience is that using the code in Sun's documentation (see: <http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html>) and wrapping this in a "while(true)" loop works, but the application slowly consumes all the memory on the phone and the program eventually throws an exception and fails to initiate further recordings.
The consumed memory isn't Java heap memory---my example program (below) shows that Java memory stays roughly static at around 185,000 bytes---but there is some kind of memory leak in the underlying supporting library provided by Nokia; I believe the memory leak occurs because if you try and start another (non-Java) application (e.g. web browser) after running the Java application for a while, the phone kills that application with a warning about lack of memory.
I've tried several different approaches from that taken by Sun's canonical example in the documentation (initialize everything each time round the loop, initialize as much as possible only once, call as many of the deallocate-style functions which shouldn't be strictly necessary etc.). None appear to be successful. Below is a simple example program which I believe should work, but crashes after running for 15 minutes or so on both the N80 (despite a firmware update) and N95. Other forums report this problem too, but the solutions presented there do not appear to work (for example, see: <http://discussion.forum.nokia.com/forum/showthread.php?t=129876>).
```
import javax.microedition.media.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Standalone extends MIDlet {
protected void startApp() {
final Form form = new Form("Test audio recording");
final StringItem status = new StringItem("Status","");
form.append(status);
final Command exit = new Command("Exit", Command.EXIT, 1);
form.addCommand(exit);
form.setCommandListener(new CommandListener() {
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exit) {
destroyApp(false);
notifyDestroyed();
}
}
});
Thread t = new Thread(){
public void run() {
int counter = 0;
while(true) {
//Code cut 'n' paste from Sun JSR135 javadocs for RecordControl:
try {
Player p = Manager.createPlayer("capture://audio");
p.realize();
RecordControl rc = (RecordControl)p.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
p.start();
Thread.currentThread().sleep(5000);
rc.commit();
p.close();
} catch (Exception e) {
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory()+
": Error: "+e);
break;
}
counter++;
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory());
System.gc(); //One forum post suggests this, but doesn't help
this.yield();
}
}
};
t.start();
final Display display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void pauseApp() {}
protected void destroyApp(boolean bool) {}
}
``` | There is a known memory leak with the N-series Nokia devices. It is not specific to Java and is in the underbelly of the OS somewhere.
Recently working on a game that targeted the Nokia N90, I had similar problems. I would run into memory problems that would accumulate over several different restarts of the application. The solution was just to reduce the overall quality and the amount of resources in the game...
I would recommend attempting to update your firmware as newer versions supposedly address this problem. However, Nokia does not make it very easy to upgrade the firmware, in most cases you have to send the device off to Nokia. And, if this app is not just for your own personal use, you have to expect anyone using the N-series devices to not have the latest firmware.
Finally, I would recommend spending some time looking around Forum Nokia as I know there are posts related to memory leaks and the N-series devices. Here is a post that seems to address the problem you are having.
<http://discussion.forum.nokia.com/forum/showthread.php?t=123486> |
100,853 | <p>While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it?</p>
| [
{
"answer_id": 100875,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 1,
"selected": false,
"text": "<p>The difference is that the # symbol specifies a data binding directive, that is resolved at data binding time (for example, when you call Page.DataBind ) and the = sign specifies an evaluation expression just evaluates and prints to the HTML output when that line is processed.</p>\n\n<p>Edit: Just adding that only inside <%# %> you have acces to databinding functions like Eval. </p>\n"
},
{
"answer_id": 100888,
"author": "Johannes Hädrich",
"author_id": 18246,
"author_profile": "https://Stackoverflow.com/users/18246",
"pm_score": 5,
"selected": true,
"text": "<p><code><%=</code> is a equivalent to <code><% Repsonse.Write()</code></p>\n\n<p>You can write any content out here: for example </p>\n\n<pre><code><%=myProperty + \" additional Text\" %>\n</code></pre>\n\n<p><code><%#</code> is a binding expression. You can retrieve any public value in the current context (for example in GridViews). But you cannot mix content here.</p>\n\n<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms178366.aspx\" rel=\"nofollow noreferrer\">MSDN</a> for more information.</p>\n"
},
{
"answer_id": 100894,
"author": "Andrew Myhre",
"author_id": 5152,
"author_profile": "https://Stackoverflow.com/users/5152",
"pm_score": 1,
"selected": false,
"text": "<p><%= is shorthand for Response.Write().<br>\n<%# indicates that you're working with the data container in a data bound control.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018/"
]
| While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it? | `<%=` is a equivalent to `<% Repsonse.Write()`
You can write any content out here: for example
```
<%=myProperty + " additional Text" %>
```
`<%#` is a binding expression. You can retrieve any public value in the current context (for example in GridViews). But you cannot mix content here.
Take a look at [MSDN](http://msdn.microsoft.com/en-us/library/ms178366.aspx) for more information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.