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
|
---|---|---|---|---|---|---|
135,909 | <p>I run into this occasionally and always forget how to do it.</p>
<p>One of those things that pop up ever so often.</p>
<p>Also, what's the formula to convert angles expressed in radians to degrees and back again?</p>
| [
{
"answer_id": 135925,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>180 degrees = PI * radians</p>\n"
},
{
"answer_id": 135927,
"author": "thesmallprint",
"author_id": 12765,
"author_profile": "https://Stackoverflow.com/users/12765",
"pm_score": 3,
"selected": false,
"text": "<p>x rads in degrees - > x*180/pi<br/>\nx degrees in rads -> x*pi/180<br/></p>\n\n<p>I guess if you wanted to make a function for this [in PHP]:</p>\n\n<pre><code>function convert($type, $num) {\n if ($type == \"rads\") {\n $result = $num*180/pi();\n }\n\n if ($type == \"degs\") {\n $result = $num*pi()/180;\n }\n\n return $result;\n }\n</code></pre>\n\n<p>Yes, that could probably be written better.</p>\n"
},
{
"answer_id": 135930,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 9,
"selected": true,
"text": "<pre><code>radians = degrees * (pi/180)\n\ndegrees = radians * (180/pi)\n</code></pre>\n\n<p>As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion <a href=\"https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi\">here</a></p>\n"
},
{
"answer_id": 135931,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 0,
"selected": false,
"text": "<p>360 degrees is 2*PI radians</p>\n\n<p>You can find the conversion formulas at: <a href=\"http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees</a>.</p>\n"
},
{
"answer_id": 135932,
"author": "Hannes Ovrén",
"author_id": 13565,
"author_profile": "https://Stackoverflow.com/users/13565",
"pm_score": 0,
"selected": false,
"text": "<p>360 degrees = 2*pi radians</p>\n\n<p>That means deg2rad(x) = x*pi/180 and rad2deg(x) = 180x/pi;</p>\n"
},
{
"answer_id": 135935,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 4,
"selected": false,
"text": "<p>a complete circle in radians is 2*pi. A complete circle in degrees is 360. To go from degrees to radians, it's (d/360) * 2*pi, or d*pi/180.</p>\n"
},
{
"answer_id": 135937,
"author": "manobes",
"author_id": 5161,
"author_profile": "https://Stackoverflow.com/users/5161",
"pm_score": 0,
"selected": false,
"text": "<p>pi Radians = 180 degrees</p>\n\n<p>So 1 degree = pi/180 radians</p>\n\n<p>or 1 radian = 180/pi degrees</p>\n"
},
{
"answer_id": 135939,
"author": "Axeman",
"author_id": 22108,
"author_profile": "https://Stackoverflow.com/users/22108",
"pm_score": -1,
"selected": false,
"text": "<pre><code>radians = (degrees/360) * 2 * pi\n</code></pre>\n"
},
{
"answer_id": 9961946,
"author": "Warpling",
"author_id": 522498,
"author_profile": "https://Stackoverflow.com/users/522498",
"pm_score": 1,
"selected": false,
"text": "<p>This works well enough for me :)</p>\n\n<pre><code>// deg2rad * degrees = radians\n#define deg2rad (3.14159265/180.0)\n// rad2deg * radians = degrees\n#define rad2deg (180/3.14159265)\n</code></pre>\n"
},
{
"answer_id": 37829037,
"author": "Rayiez",
"author_id": 2155902,
"author_profile": "https://Stackoverflow.com/users/2155902",
"pm_score": 3,
"selected": false,
"text": "<p>In javascript you can do it this way</p>\n\n<pre><code>radians = degrees * (Math.PI/180);\n\ndegrees = radians * (180/Math.PI);\n</code></pre>\n"
},
{
"answer_id": 42229595,
"author": "Koray",
"author_id": 1266873,
"author_profile": "https://Stackoverflow.com/users/1266873",
"pm_score": 0,
"selected": false,
"text": "<p>For double in c# this might be helpful:</p>\n\n<pre><code> public static double Conv_DegreesToRadians(this double degrees)\n {\n //return degrees * (Math.PI / 180d);\n return degrees * 0.017453292519943295d;\n }\n public static double Conv_RadiansToDegrees(this double radians)\n {\n //return radians * (180d / Math.PI);\n return radians * 57.295779513082323d;\n }\n</code></pre>\n"
},
{
"answer_id": 62242217,
"author": "Netsi1964",
"author_id": 192080,
"author_profile": "https://Stackoverflow.com/users/192080",
"pm_score": 0,
"selected": false,
"text": "<p>Here is some code which extends Object with <code>rad(deg)</code>, <code>deg(rad)</code> and also two more useful functions: <code>getAngle(point1,point2)</code> and <code>getDistance(point1,point2)</code> where a point needs to have a <code>x</code> and <code>y</code> property.</p>\n\n<pre><code>Object.prototype.rad = (deg) => Math.PI/180 * deg;\nObject.prototype.deg = (rad) => 180/Math.PI * rad;\nObject.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);\nObject.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
]
| I run into this occasionally and always forget how to do it.
One of those things that pop up ever so often.
Also, what's the formula to convert angles expressed in radians to degrees and back again? | ```
radians = degrees * (pi/180)
degrees = radians * (180/pi)
```
As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion [here](https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi) |
135,919 | <p>I haven't been able to find an adequate answer to what exactly the following error means:</p>
<p><code>java.net.SocketException: Software caused connection abort: recv failed</code> </p>
<p>Notes:</p>
<ul>
<li>This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail.</li>
<li>The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case).</li>
<li>The URI is definitely available (as confirmed by asking the browser to do the fetch).</li>
</ul>
<p>Relevant code:</p>
<pre><code>BufferedReader reader;
try {
URL url = new URL(URI);
reader = new BufferedReader(new InputStreamReader(url.openStream())));
} catch( MalformedURLException e ) {
throw new IOException("Expecting a well-formed URL: " + e);
}//end try: Have a stream
String buffer;
StringBuilder result = new StringBuilder();
while( null != (buffer = reader.readLine()) ) {
result.append(buffer);
}//end while: Got the contents.
reader.close();
</code></pre>
| [
{
"answer_id": 135983,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 2,
"selected": false,
"text": "<p>Are you accessing http data? Can you use the HttpClient library instead of the standard library? The library has more options and will provide better error messages.</p>\n\n<p><a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"nofollow noreferrer\">http://hc.apache.org/httpclient-3.x/</a></p>\n"
},
{
"answer_id": 135985,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 2,
"selected": false,
"text": "<p>The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.</p>\n"
},
{
"answer_id": 135991,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 6,
"selected": true,
"text": "<p>This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.</p>\n"
},
{
"answer_id": 8652823,
"author": "Anantharaman",
"author_id": 1118833,
"author_profile": "https://Stackoverflow.com/users/1118833",
"pm_score": 2,
"selected": false,
"text": "<p>Try adding 'autoReconnect=true' to the jdbc connection string</p>\n"
},
{
"answer_id": 10246311,
"author": "Michael J. Gray",
"author_id": 468904,
"author_profile": "https://Stackoverflow.com/users/468904",
"pm_score": 1,
"selected": false,
"text": "<p>This will happen from time to time either when a connection times out or when a remote host terminates their connection (closed application, computer shutdown, etc). You can avoid this by managing sockets yourself and handling disconnections in your application via its communications protocol and then calling <code>shutdownInput</code> and <code>shutdownOutput</code> to clear up the session.</p>\n"
},
{
"answer_id": 12111883,
"author": "trinity",
"author_id": 1622969,
"author_profile": "https://Stackoverflow.com/users/1622969",
"pm_score": 1,
"selected": false,
"text": "<p>Look if you have another service or program running on the http port. It happened to me when I tried to use the port and it was taken by another program.</p>\n"
},
{
"answer_id": 19904978,
"author": "Maroš Košina",
"author_id": 1769533,
"author_profile": "https://Stackoverflow.com/users/1769533",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using Netbeans to manage Tomcat, try to disable HTTP monitor in Tools - Servers</p>\n"
},
{
"answer_id": 23220205,
"author": "desbocages",
"author_id": 3560512,
"author_profile": "https://Stackoverflow.com/users/3560512",
"pm_score": 5,
"selected": false,
"text": "<p>This also happens if your TLS client is unable to be authenticate by the server configured to require client authentication.</p>\n"
},
{
"answer_id": 25479748,
"author": "Sergio",
"author_id": 3974252,
"author_profile": "https://Stackoverflow.com/users/3974252",
"pm_score": 0,
"selected": false,
"text": "<p>I too had this problem. My solution was:</p>\n\n<pre><code>sc.setSoLinger(true, 10);\n</code></pre>\n\n<p>COPY FROM A WEBSITE -->By using the <code>setSoLinger()</code> method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.</p>\n\n<p>Maybe it is not the answer to everybody but to some people.</p>\n"
},
{
"answer_id": 29322850,
"author": "rustyx",
"author_id": 485343,
"author_profile": "https://Stackoverflow.com/users/485343",
"pm_score": 4,
"selected": false,
"text": "<p>This error occurs when a connection is closed abruptly (when a TCP connection is reset while there is still data in the send buffer). The condition is very similar to a much more common 'Connection reset by peer'. It can happen sporadically when connecting over the Internet, but also systematically if the timing is right (e.g. with keep-alive connections on localhost).</p>\n\n<p>An HTTP client should just re-open the connection and retry the request. It is important to understand that when a connection is in this state, there is no way out of it other than to close it. Any attempt to send or receive will produce the same error.</p>\n\n<p>Don't use <code>URL.open()</code>, use Apache-Commons <a href=\"https://hc.apache.org/httpcomponents-client-ga/\" rel=\"noreferrer\">HttpClient</a> which has a retry mechanism, connection pooling, keep-alive and many other features.</p>\n\n<p>Sample usage:</p>\n\n<pre><code>HttpClient httpClient = HttpClients.custom()\n .setConnectionTimeToLive(20, TimeUnit.SECONDS)\n .setMaxConnTotal(400).setMaxConnPerRoute(400)\n .setDefaultRequestConfig(RequestConfig.custom()\n .setSocketTimeout(30000).setConnectTimeout(5000).build())\n .setRetryHandler(new DefaultHttpRequestRetryHandler(5, true))\n .build();\n// the httpClient should be re-used because it is pooled and thread-safe.\n\nHttpGet request = new HttpGet(uri);\nHttpResponse response = httpClient.execute(request);\nreader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));\n// handle response ...\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12815/"
]
| I haven't been able to find an adequate answer to what exactly the following error means:
`java.net.SocketException: Software caused connection abort: recv failed`
Notes:
* This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail.
* The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case).
* The URI is definitely available (as confirmed by asking the browser to do the fetch).
Relevant code:
```
BufferedReader reader;
try {
URL url = new URL(URI);
reader = new BufferedReader(new InputStreamReader(url.openStream())));
} catch( MalformedURLException e ) {
throw new IOException("Expecting a well-formed URL: " + e);
}//end try: Have a stream
String buffer;
StringBuilder result = new StringBuilder();
while( null != (buffer = reader.readLine()) ) {
result.append(buffer);
}//end while: Got the contents.
reader.close();
``` | This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors. |
135,929 | <p>I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.</p>
<pre><code>declare @ConstraintName varchar(255)
set @ConstraintName = 'PK_Whatever'
IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
--can't drop primary keys
END
</code></pre>
<p>The error I get is:</p>
<pre><code>Incorrect syntax near 'END'.
</code></pre>
<p>If I add something after the comment, i.e. <code>PRINT @ConstraintName</code>, it works fine.</p>
| [
{
"answer_id": 135962,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>I can't say for sure in SQL Server, but in Oracle PL/SQL you would put a NULL statement in a block that you want to do nothing:</p>\n\n<pre><code>BEGIN\n -- This is a comment\n NULL;\nEND\n</code></pre>\n"
},
{
"answer_id": 136002,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 4,
"selected": true,
"text": "<p>No, you cannot have an empty if block (or one that contains only comments).</p>\n\n<p>You don't say why you would want this. If you are just trying to comment out the contents of the if for debugging, you should comment the entire if.</p>\n"
},
{
"answer_id": 136020,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 1,
"selected": false,
"text": "<p>No, I don't think you can. If you want to temporarily comment that out, you'll probably need to just put a /* ... */ around the entire statement.</p>\n"
},
{
"answer_id": 136250,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 1,
"selected": false,
"text": "<p>It's not the comment. It's that you have an empty if block. You have to have at least one statement in there. Putting in a print statement might be your best bet.</p>\n"
},
{
"answer_id": 139140,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 1,
"selected": false,
"text": "<p>Since you can't have an \"empty\" blocks (thanks Charles Graham), I'll place a comment above the if-statement for the intention of the conditional (thanks BlackWasp), and then have a comment within the begin..end block that describes a dummy declare (thanks GiLM).</p>\n\n<p>Do you think this is how I should comment the code?</p>\n\n<pre><code>declare @ConstraintName varchar(255)\nset @ConstraintName = 'PK_Whatever'\n\n--can't drop primary keys\nIF LEFT(@ConstraintName, 2) = 'PK'\nBEGIN\n --do nothing here\n DECLARE @Dummy bit --required to compile\nEND\n</code></pre>\n"
},
{
"answer_id": 140477,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Would it not be better to design your SQL statement around items you do wish to drop constraints for? So If you wish to remove the ability for this then</p>\n\n<pre><code>If left(@constraintname,2 <> 'PK'\nBEGIN\n -- Drop your constraint here\n ALTER TABLE dbo.mytable DROP constraint ... -- etc\nEND\n</code></pre>\n"
},
{
"answer_id": 141005,
"author": "GilM",
"author_id": 10192,
"author_profile": "https://Stackoverflow.com/users/10192",
"pm_score": 2,
"selected": false,
"text": "<p><code>SELECT NULL</code> will generate a result-set and could affect client apps. Seems better to do something that will have no effect, like:</p>\n\n<pre><code>IF LEFT(@ConstraintName, 2) = 'PK'\nBEGIN\n DECLARE @Dummy bit -- Do nothing here, but this is required to compile\nEND\n</code></pre>\n"
},
{
"answer_id": 497854,
"author": "Omer Bokhari",
"author_id": 56829,
"author_profile": "https://Stackoverflow.com/users/56829",
"pm_score": 0,
"selected": false,
"text": "<p>i know it doesn't answer your original question as to whether you can place just a comment inside a block, but why not inverse your conditional so the block only executes if <> 'PK'?</p>\n\n<pre><code>-- drop only if not primary\nIF LEFT (@ConstraintName, 2) <> 'PK'\nBEGIN\n --do something here\nEND\n</code></pre>\n"
},
{
"answer_id": 19792263,
"author": "Alex KeySmith",
"author_id": 141022,
"author_profile": "https://Stackoverflow.com/users/141022",
"pm_score": 2,
"selected": false,
"text": "<p>Good tips here: <a href=\"https://stackoverflow.com/questions/6954336/how-to-do-nothing-in-sql-server\">How to do nothing in SQL Server</a></p>\n\n<pre><code>BEGIN\n DONOTHING:\nEND\n</code></pre>\n\n<p>So you're just defining a label.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73794/"
]
| I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.
```
declare @ConstraintName varchar(255)
set @ConstraintName = 'PK_Whatever'
IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
--can't drop primary keys
END
```
The error I get is:
```
Incorrect syntax near 'END'.
```
If I add something after the comment, i.e. `PRINT @ConstraintName`, it works fine. | No, you cannot have an empty if block (or one that contains only comments).
You don't say why you would want this. If you are just trying to comment out the contents of the if for debugging, you should comment the entire if. |
135,934 | <p>I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll. I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with. Instead, I need to access it by Pinvoking it.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/aa454995.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa454995.aspx</a> for documentation on the function. The function takes in a struct that defines the parameters of the dialog. e.g. where to save the file, what resolution to use.</p>
<p>I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout. I also imagine that the code would involve [DllImport("aygshell.dll")]. Any sample code of how to call this would be much appreciated.</p>
| [
{
"answer_id": 138398,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 0,
"selected": false,
"text": "<p>I've not been able to test this, but your struct/function should look something like this:</p>\n\n<pre><code>struct SHCAMERACAPTURE {\n public Int32 cbSize;\n public IntPtr hwndOwner;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] \n public string szFile;\n\n [MarshalAs(UnmanagedType.LPStr)] \n string pszInitialDir;\n\n [MarshalAs(UnmanagedType.LPStr)] \n string pszDefaultFileName;\n\n [MarshalAs(UnmanagedType.LPStr)] \n string pszTitle;\n\n Int32 StillQuality;\n Int32 VideoTypes;\n Int32 nResolutionWidth;\n Int32 nResolutionHeight;\n Int32 nVideoTimeLimit;\n Int32 Mode;\n}\n\n[DllImport(\"aygshell.dll\")]\nstatic extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);\n</code></pre>\n\n<p>AFAIK, you don't need to explicitly set StructLayout on SHCAMERCAPTURE as there's nothing unusual about its layout.</p>\n\n<p>Once you get this working, you might want to post your findings to pinvoke.net for others to make use of!</p>\n"
},
{
"answer_id": 140281,
"author": "Peter Walke",
"author_id": 12497,
"author_profile": "https://Stackoverflow.com/users/12497",
"pm_score": 1,
"selected": false,
"text": "<p>Groky, this is a good start... Thanks for getting this started. I tried wiring this up, but get a NotSupportedException.</p>\n\n<p>I've pasted the text from my test app below. Note that I tried decorating the struct with [StructLayout(LayoutKind.Sequential)]. I've also made all members public to eliminate any issues with object accessability.</p>\n\n<pre><code>public partial class Form1 : Form\n{\n [DllImport(\"aygshell.dll\")]\n static extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);\n\n [StructLayout(LayoutKind.Sequential)]\n struct SHCAMERACAPTURE\n {\n public Int32 cbSize;\n public IntPtr hwndOwner;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string szFile;\n [MarshalAs(UnmanagedType.LPStr)]\n public string pszInitialDir;\n [MarshalAs(UnmanagedType.LPStr)]\n public string pszDefaultFileName;\n [MarshalAs(UnmanagedType.LPStr)]\n public string pszTitle;\n public Int32 StillQuality;\n public Int32 VideoTypes;\n public Int32 nResolutionWidth;\n public Int32 nResolutionHeight;\n public Int32 nVideoTimeLimit;\n public Int32 Mode;\n }\n private void ShowCamera()\n {\n SHCAMERACAPTURE captureData = new SHCAMERACAPTURE\n {\n cbSize = sizeof (Int64),\n hwndOwner = (IntPtr)0,\n szFile = \"\\\\My Documents\",\n pszDefaultFileName = \"picture.jpg\",\n pszTitle = \"Camera Demo\",\n StillQuality = 0,\n VideoTypes = 1,\n nResolutionWidth = 480,\n nResolutionHeight = 640,\n nVideoTimeLimit = 0,\n Mode = 0\n };\n SHCameraCapture(ref captureData);\n }\n private void button1_Click(object sender, EventArgs e)\n {\n ShowCamera();\n }\n</code></pre>\n"
},
{
"answer_id": 619763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>this code works....</p>\n\n<pre><code>#region Enumerations\n\npublic enum CAMERACAPTURE_STILLQUALITY\n{\n CAMERACAPTURE_STILLQUALITY_DEFAULT = 0,\n CAMERACAPTURE_STILLQUALITY_LOW = 1,\n CAMERACAPTURE_STILLQUALITY_NORMAL = 2,\n CAMERACAPTURE_STILLQUALITY_HIGH = 3\n}\npublic enum CAMERACAPTURE_VIDEOTYPES\n{\n CAMERACAPTURE_VIDEOTYPE_ALL = 0xFFFF,\n CAMERACAPTURE_VIDEOTYPE_STANDARD = 1,\n CAMERACAPTURE_VIDEOTYPE_MESSAGING = 2\n}\n\npublic enum CAMERACAPTURE_MODE\n{\n CAMERACAPTURE_MODE_STILL = 0,\n CAMERACAPTURE_MODE_VIDEOONLY = 1,\n CAMERACAPTURE_MODE_VIDEOWITHAUDIO = 2\n}\n\n#endregion //Enumerations\n\n#region Structures\n\n[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]\npublic struct struSHCAMERACAPTURE\n{\n public uint cbSize;\n public IntPtr hwndOwner;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public String szFile;\n [MarshalAs(UnmanagedType.LPTStr)]\n public String pszInitialDir; //LPCTSTR\n [MarshalAs(UnmanagedType.LPTStr)]\n public String pszDefaultFileName; //LPCTSTR\n [MarshalAs(UnmanagedType.LPTStr)]\n public String pszTitle; //LPCTSTR\n public CAMERACAPTURE_STILLQUALITY StillQuality;\n public CAMERACAPTURE_VIDEOTYPES VideoTypes;\n public uint nResolutionWidth;\n public uint nResolutionHeight;\n public uint nVideoTimeLimit;\n public CAMERACAPTURE_MODE Mode;\n}\n#endregion //Structures\n\n#region API\n[DllImport(\"Aygshell.dll\", SetLastError = true,CharSet=CharSet.Unicode)]\npublic static extern int SHCameraCapture\n(\n ref struSHCAMERACAPTURE pshCamCapture\n);\n\nprivate string StartImager(String strImgDir, String strImgFile, uint uintImgHeight,\n uint uintImgWidth)\n\ntry\n{\n struSHCAMERACAPTURE shCamCapture = new struSHCAMERACAPTURE();\n\n shCamCapture.cbSize = (uint)Marshal.SizeOf(shCamCapture);\n shCamCapture.hwndOwner = IntPtr.Zero;\n shCamCapture.szFile = \"\\\\\" + strImgFile; //strImgDir + \"\\\\\" + strImgFile;\n shCamCapture.pszInitialDir = \"\\\\\"; // strImgDir;\n shCamCapture.pszDefaultFileName = strImgFile;\n shCamCapture.pszTitle = \"PTT Image Capture\";\n shCamCapture.StillQuality = 0; // CAMERACAPTURE_STILLQUALITY.CAMERACAPTURE_STILLQUALITY_NORMAL;\n shCamCapture.VideoTypes = CAMERACAPTURE_VIDEOTYPES.CAMERACAPTURE_VIDEOTYPE_STANDARD;\n shCamCapture.nResolutionHeight = 0; // uintImgHeight;\n shCamCapture.nResolutionWidth = 0; // uintImgWidth;\n shCamCapture.nVideoTimeLimit = 10;\n shCamCapture.Mode = 0; // CAMERACAPTURE_MODE.CAMERACAPTURE_MODE_STILL;\n\n //IntPtr intptrCamCaptr = IntPtr.Zero;\n\n //Marshal.StructureToPtr(shCamCapture, intptrCamCaptr, true);\n\n int intResult = SHCameraCapture(ref shCamCapture);\n if (intResult != 0)\n {\n Win32Exception Win32 = new Win32Exception(intResult);\n MessageBox.Show(\"Error: \" + Win32.Message);\n } \n\n return strCaptrErr;\n}\n\ncatch (Exception ex)\n{\n MessageBox.Show(\"Error StartImager : \" + ex.ToString() + \" - \" + strCaptrErr\n , \"Nomad Imager Test\");\n return \"\";\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497/"
]
| I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll. I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with. Instead, I need to access it by Pinvoking it.
See <http://msdn.microsoft.com/en-us/library/aa454995.aspx> for documentation on the function. The function takes in a struct that defines the parameters of the dialog. e.g. where to save the file, what resolution to use.
I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout. I also imagine that the code would involve [DllImport("aygshell.dll")]. Any sample code of how to call this would be much appreciated. | this code works....
```
#region Enumerations
public enum CAMERACAPTURE_STILLQUALITY
{
CAMERACAPTURE_STILLQUALITY_DEFAULT = 0,
CAMERACAPTURE_STILLQUALITY_LOW = 1,
CAMERACAPTURE_STILLQUALITY_NORMAL = 2,
CAMERACAPTURE_STILLQUALITY_HIGH = 3
}
public enum CAMERACAPTURE_VIDEOTYPES
{
CAMERACAPTURE_VIDEOTYPE_ALL = 0xFFFF,
CAMERACAPTURE_VIDEOTYPE_STANDARD = 1,
CAMERACAPTURE_VIDEOTYPE_MESSAGING = 2
}
public enum CAMERACAPTURE_MODE
{
CAMERACAPTURE_MODE_STILL = 0,
CAMERACAPTURE_MODE_VIDEOONLY = 1,
CAMERACAPTURE_MODE_VIDEOWITHAUDIO = 2
}
#endregion //Enumerations
#region Structures
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
public struct struSHCAMERACAPTURE
{
public uint cbSize;
public IntPtr hwndOwner;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public String szFile;
[MarshalAs(UnmanagedType.LPTStr)]
public String pszInitialDir; //LPCTSTR
[MarshalAs(UnmanagedType.LPTStr)]
public String pszDefaultFileName; //LPCTSTR
[MarshalAs(UnmanagedType.LPTStr)]
public String pszTitle; //LPCTSTR
public CAMERACAPTURE_STILLQUALITY StillQuality;
public CAMERACAPTURE_VIDEOTYPES VideoTypes;
public uint nResolutionWidth;
public uint nResolutionHeight;
public uint nVideoTimeLimit;
public CAMERACAPTURE_MODE Mode;
}
#endregion //Structures
#region API
[DllImport("Aygshell.dll", SetLastError = true,CharSet=CharSet.Unicode)]
public static extern int SHCameraCapture
(
ref struSHCAMERACAPTURE pshCamCapture
);
private string StartImager(String strImgDir, String strImgFile, uint uintImgHeight,
uint uintImgWidth)
try
{
struSHCAMERACAPTURE shCamCapture = new struSHCAMERACAPTURE();
shCamCapture.cbSize = (uint)Marshal.SizeOf(shCamCapture);
shCamCapture.hwndOwner = IntPtr.Zero;
shCamCapture.szFile = "\\" + strImgFile; //strImgDir + "\\" + strImgFile;
shCamCapture.pszInitialDir = "\\"; // strImgDir;
shCamCapture.pszDefaultFileName = strImgFile;
shCamCapture.pszTitle = "PTT Image Capture";
shCamCapture.StillQuality = 0; // CAMERACAPTURE_STILLQUALITY.CAMERACAPTURE_STILLQUALITY_NORMAL;
shCamCapture.VideoTypes = CAMERACAPTURE_VIDEOTYPES.CAMERACAPTURE_VIDEOTYPE_STANDARD;
shCamCapture.nResolutionHeight = 0; // uintImgHeight;
shCamCapture.nResolutionWidth = 0; // uintImgWidth;
shCamCapture.nVideoTimeLimit = 10;
shCamCapture.Mode = 0; // CAMERACAPTURE_MODE.CAMERACAPTURE_MODE_STILL;
//IntPtr intptrCamCaptr = IntPtr.Zero;
//Marshal.StructureToPtr(shCamCapture, intptrCamCaptr, true);
int intResult = SHCameraCapture(ref shCamCapture);
if (intResult != 0)
{
Win32Exception Win32 = new Win32Exception(intResult);
MessageBox.Show("Error: " + Win32.Message);
}
return strCaptrErr;
}
catch (Exception ex)
{
MessageBox.Show("Error StartImager : " + ex.ToString() + " - " + strCaptrErr
, "Nomad Imager Test");
return "";
}
``` |
135,938 | <p>It's not a matter of life or death but I wonder if this could be possible:</p>
<p>I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once.</p>
<p>so now it looks like this:</p>
<pre><code> private function addListeners():void {
addEventListener(FormEvent.SHOW_FORM, formListener);
addEventListener(FormEvent.SEND_FORM, formListener);
addEventListener(FormEvent.CANCEL_FORM, formListener);
}
private function formListener(event:formEvent):void {
switch(event.type){
case "show.form":
// handle show form stuff
break;
case "send.form":
// handle send form stuff
break;
case "cancel.form":
// handle cancel form stuff
break;
}
}
</code></pre>
<p>but instead of adding every event one at the time I would rather be doing something like</p>
<pre><code> private function addListeners():void {
addEventListener(FormEvent.*, formListener);
}
</code></pre>
<p>I wonder if something like this is possible, i would love it. I work with loads of events :)</p>
| [
{
"answer_id": 136258,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of any routines that let you do that directly, but you could write your own. The syntax here won't be perfect, but here's a first pass:</p>\n\n<pre><code>private function addMultipleEventListeners( evts:Array, callback:function ):void\n{\n for each( var evt:Event in evts )\n {\n addEventListener( evt, callback );\n }\n}\n</code></pre>\n\n<p>You could then call that routine like so:</p>\n\n<pre><code>var evts:Array = [ FormEvent.SHOW_FORM, FormEvent.SEND_FORM, FormEvent.CANCEL_FORM ];\naddMultipleEventListeners( evts, formListener );\n</code></pre>\n"
},
{
"answer_id": 137417,
"author": "Brian Hodge",
"author_id": 20628,
"author_profile": "https://Stackoverflow.com/users/20628",
"pm_score": 4,
"selected": true,
"text": "<p>You only really need one event listener in this case anyhow. That listener will be listening for any change with the form and a parameter equal to what the change was becomes available to the event listener function. I will show you, but please remember that this is a pseudo situation and normally I wouldn't dispatch an event off of something as simple as a method call because the dispatch is implied so there is no real need to listen for it.</p>\n\n<p>First the Custom Event</p>\n\n<pre><code>\npackage com.yourDomain.events\n{\n import flash.events.Event;\n public class FormEvent extends Event\n {\n //Public Properties\n public static const CANCEL_FORM:int = \"0\";\n public static const SHOW_FORM:int = \"1\";\n public static const SEND_FORM:int = \"2\";\n\n public static const STATE_CHANGED:String = \"stateChanged\";\n\n //Private Properties\n private var formState:int;\n\n public function FormEvent(formState:int):void\n {\n super(STATE_CHANGED);\n formState = formState;\n }\n }\n}\n</code>\n</pre>\n\n<p>So we have just created our custom event class and we have set it up so that we can catch the state through the listener function as I will demonstrate once done with the pseudo form class that will dispatch the for said custom event.</p>\n\n<p>Remember that this is all hypothetical as I have no idea what your code looks like or how your implementing things. What is important is to notice that when I dispatch the event I need to send a parameter with it that reflects what the new state is.</p>\n\n<pre>\n<code>\npackage com.yourDomain.ui\n{\n import flash.events.Event;\n import flash.events.EventDispatcher;\n import com.yourDomain.events.FormEvent;\n public class Form extends EventDispatcher\n {\n public function Form():void\n {\n //Anything you want form to do upon instantiation goes here.\n }\n public function cancelForm():void\n {\n dispatchEvent(new Event(FormEvent.CANCEL_FORM);\n }\n public function showForm():void\n {\n dispatchEvent(new Event(FormEvent.SHOW_FORM);\n }\n public function sendForm():void\n {\n dispatchEvent(new Event(FormEvent.SEND_FORM);\n }\n }\n}\n</code>\n</pre>\n\n<p>And finally we create the document class that will listen for it. Please know that I realize it isn't logical to create a listener that fires when you call a method of a class because you obviously know you called the method, but for this example it will due.</p>\n\n<pre>\n<code>\npackage com.yourDomain.ui\n{\n import com.yourDomain.ui.Form;\n import com.yourDomain.events.FormEvent;\n //Form is in the same package so we need not import it.\n public class MainDocumentClass\n {\n private var _theForm:Form;\n\n public function MainDocumentClass():void\n {\n _theForm = new Form();\n _theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true);\n /*\n The following three method calls each cause the\n FormEvent.STATE_CHANGE event to be dispatched. \n onFormStateChange is notified and checks what \n the last change actually was.\n */\n _theForm.cancelForm();\n _theForm.showForm();\n _theForm.sendForm();\n }\n private function onFormStateChange(e:FormEvent):void\n {\n switch(e.formState)\n {\n case CANCEL_FORM:\n trace('The form was canceled');\n break;\n case SHOW_FORM:\n trace('The form was revealed');\n break;\n case SEND_FORM:\n trace('The form was sent');\n break;\n }\n }\n } \n}\n</code>\n</pre>\n\n<p>I hope that this was helpful, its late and I may have to revise some things later, but this should help get an understanding of how to make your own events and to customize how things work.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
]
| It's not a matter of life or death but I wonder if this could be possible:
I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once.
so now it looks like this:
```
private function addListeners():void {
addEventListener(FormEvent.SHOW_FORM, formListener);
addEventListener(FormEvent.SEND_FORM, formListener);
addEventListener(FormEvent.CANCEL_FORM, formListener);
}
private function formListener(event:formEvent):void {
switch(event.type){
case "show.form":
// handle show form stuff
break;
case "send.form":
// handle send form stuff
break;
case "cancel.form":
// handle cancel form stuff
break;
}
}
```
but instead of adding every event one at the time I would rather be doing something like
```
private function addListeners():void {
addEventListener(FormEvent.*, formListener);
}
```
I wonder if something like this is possible, i would love it. I work with loads of events :) | You only really need one event listener in this case anyhow. That listener will be listening for any change with the form and a parameter equal to what the change was becomes available to the event listener function. I will show you, but please remember that this is a pseudo situation and normally I wouldn't dispatch an event off of something as simple as a method call because the dispatch is implied so there is no real need to listen for it.
First the Custom Event
```
package com.yourDomain.events
{
import flash.events.Event;
public class FormEvent extends Event
{
//Public Properties
public static const CANCEL_FORM:int = "0";
public static const SHOW_FORM:int = "1";
public static const SEND_FORM:int = "2";
public static const STATE_CHANGED:String = "stateChanged";
//Private Properties
private var formState:int;
public function FormEvent(formState:int):void
{
super(STATE_CHANGED);
formState = formState;
}
}
}
```
So we have just created our custom event class and we have set it up so that we can catch the state through the listener function as I will demonstrate once done with the pseudo form class that will dispatch the for said custom event.
Remember that this is all hypothetical as I have no idea what your code looks like or how your implementing things. What is important is to notice that when I dispatch the event I need to send a parameter with it that reflects what the new state is.
```
package com.yourDomain.ui
{
import flash.events.Event;
import flash.events.EventDispatcher;
import com.yourDomain.events.FormEvent;
public class Form extends EventDispatcher
{
public function Form():void
{
//Anything you want form to do upon instantiation goes here.
}
public function cancelForm():void
{
dispatchEvent(new Event(FormEvent.CANCEL_FORM);
}
public function showForm():void
{
dispatchEvent(new Event(FormEvent.SHOW_FORM);
}
public function sendForm():void
{
dispatchEvent(new Event(FormEvent.SEND_FORM);
}
}
}
```
And finally we create the document class that will listen for it. Please know that I realize it isn't logical to create a listener that fires when you call a method of a class because you obviously know you called the method, but for this example it will due.
```
package com.yourDomain.ui
{
import com.yourDomain.ui.Form;
import com.yourDomain.events.FormEvent;
//Form is in the same package so we need not import it.
public class MainDocumentClass
{
private var _theForm:Form;
public function MainDocumentClass():void
{
_theForm = new Form();
_theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true);
/*
The following three method calls each cause the
FormEvent.STATE_CHANGE event to be dispatched.
onFormStateChange is notified and checks what
the last change actually was.
*/
_theForm.cancelForm();
_theForm.showForm();
_theForm.sendForm();
}
private function onFormStateChange(e:FormEvent):void
{
switch(e.formState)
{
case CANCEL_FORM:
trace('The form was canceled');
break;
case SHOW_FORM:
trace('The form was revealed');
break;
case SEND_FORM:
trace('The form was sent');
break;
}
}
}
}
```
I hope that this was helpful, its late and I may have to revise some things later, but this should help get an understanding of how to make your own events and to customize how things work. |
135,944 | <p>Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data. I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver.</p>
<p>mssql_get_last_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code.</p>
<p>Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver?</p>
| [
{
"answer_id": 135963,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": true,
"text": "<p>Are you talking about SQL Server error codes, e.g. RAISERRROR or other failures? If so, last time I checked in PHP you need to ask for @@ERROR (e.g. select @@error) instead.</p>\n\n<p>If it is a return code, you must explicitly catch it, e.g.</p>\n\n<pre><code>DECLARE @return_code INT\nEXEC @return_code = your_stored_procedure 1123\nSELECT @return_code\n</code></pre>\n"
},
{
"answer_id": 135972,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<p>To get a numeric error code from mssql you can do a select that looks something like </p>\n\n<pre><code>SELECT @@ERROR AS ErrorCode\n</code></pre>\n\n<p>Which SHOULD return the correct error code.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12308/"
]
| Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data. I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver.
mssql\_get\_last\_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code.
Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver? | Are you talking about SQL Server error codes, e.g. RAISERRROR or other failures? If so, last time I checked in PHP you need to ask for @@ERROR (e.g. select @@error) instead.
If it is a return code, you must explicitly catch it, e.g.
```
DECLARE @return_code INT
EXEC @return_code = your_stored_procedure 1123
SELECT @return_code
``` |
135,971 | <p>If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical.</p>
<p>I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders.</p>
<p>Certainly a script that starts:</p>
<pre><code>classes=`mktemp`
for i in `find . -name "*.jar"`
do
echo "File: $i" > $classes
jar tf $i > $classes
...
done
</code></pre>
<p>with some clever sort/uniq/diff/grep/awk later on has potential, but I was wondering if anyone knows of any existing solutions.</p>
| [
{
"answer_id": 136252,
"author": "ferbs",
"author_id": 22406,
"author_profile": "https://Stackoverflow.com/users/22406",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://classpathhelper.sourceforge.net/\" rel=\"nofollow noreferrer\">Classpath Helper</a> is an Eclipse plug-in that helps a little bit.</p>\n"
},
{
"answer_id": 136292,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 2,
"selected": false,
"text": "<p>I think it wouldn't be too hard to write a tool for your self. </p>\n\n<p>You can get the classpath entries with System.getProperty(\"java.class.path\");</p>\n\n<p>And then walk through the jars, zips, or directories listed there and collect all the information about the classes and findout those that might cause trouble.</p>\n\n<p>This task would take 1 or 2 days at most. Then you can load this class directly in your application and generate a report.</p>\n\n<p>Probably java.class.path property wont's show all the classes if you run in some infrastructure with complex custom class loading ( for instance I once saw an app that load the classes from the LDAP ) but it would certainly work for most of the cases.</p>\n\n<p>Heres a tool you might find useful, I've never use it my self, but give it a try and let us know the result.</p>\n\n<p><a href=\"http://www.jgoodies.com/freeware/jpathreport/features.html\" rel=\"nofollow noreferrer\">http://www.jgoodies.com/freeware/jpathreport/features.html</a></p>\n\n<p>If you are going to create your own tool, here is the code I use for the same shell script posted before, but that I use on my Windows machine. It runs faster when there are tons of jar files.</p>\n\n<p>You can use it and modify it so instead of recursively walk a directory, read the class path and compare the .class time attribute.</p>\n\n<p>There is a Command class you can subclass if needed, I was thinking in the -execute option of \"find\" </p>\n\n<p>This my own code, so it was not intended to be \"production ready\", just to do the work. </p>\n\n<pre><code>import java.io.*;\nimport java.util.zip.*;\n\n\npublic class ListZipContent{\n public static void main( String [] args ) throws IOException {\n System.out.println( \"start \" + new java.util.Date() );\n String pattern = args.length == 1 ? args[0] : \"OracleDriver.class\";// Guess which class I was looking for :) \n File file = new File(\".\");\n FileFilter fileFilter = new FileFilter(){\n public boolean accept( File file ){\n return file.isDirectory() || file.getName().endsWith( \"jar\" );\n }\n };\n Command command = new Command( pattern );\n executeRecursively( command, file, fileFilter );\n System.out.println( \"finish \" + new java.util.Date() );\n }\n private static void executeRecursively( Command command, File dir , FileFilter filter ) throws IOException {\n if( !dir.isDirectory() ){\n System.out.println( \"not a directory \" + dir );\n return;\n }\n for( File file : dir.listFiles( filter ) ){\n if( file.isDirectory()){\n executeRecursively( command,file , filter );\n }else{\n command.executeOn( file );\n }\n }\n }\n}\nclass Command {\n\n private String pattern;\n public Command( String pattern ){\n this.pattern = pattern;\n }\n\n public void executeOn( File file ) throws IOException {\n if( pattern == null ) { \n System.out.println( \"Pattern is null \");\n return;\n }\n\n String fileName = file.getName();\n boolean jarNameAlreadyPrinted = false;\n\n ZipInputStream zis = null;\n try{\n zis = new ZipInputStream( new FileInputStream( file ) );\n\n ZipEntry ze;\n while(( ze = zis.getNextEntry() ) != null ) {\n if( ze.getName().endsWith( pattern )){\n if( !jarNameAlreadyPrinted ){\n System.out.println(\"Contents of: \" + file.getCanonicalPath() );\n jarNameAlreadyPrinted = true;\n }\n System.out.println( \" \" + ze.getName() );\n }\n zis.closeEntry();\n }\n }finally{\n if( zis != null ) try {\n zis.close();\n }catch( Throwable t ){}\n }\n }\n}\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 151373,
"author": "s_t_e_v_e",
"author_id": 21176,
"author_profile": "https://Stackoverflow.com/users/21176",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.alphaworks.ibm.com/tech/jarclassfinder\" rel=\"nofollow noreferrer\">jarclassfinder</a> is another eclipse plugin option</p>\n"
},
{
"answer_id": 4516827,
"author": "Zac Thompson",
"author_id": 58549,
"author_profile": "https://Stackoverflow.com/users/58549",
"pm_score": 3,
"selected": false,
"text": "<p>Looks like <a href=\"http://code.google.com/p/jarfish/wiki/Intro\" rel=\"noreferrer\">jarfish</a> will do what you want with its \"dupes\" command.</p>\n"
},
{
"answer_id": 4523559,
"author": "Zac Thompson",
"author_id": 58549,
"author_profile": "https://Stackoverflow.com/users/58549",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://www.jboss.org/tattletale\" rel=\"noreferrer\">Tattletale</a> tool from JBoss is another candidate: \"Spot if a class/package is located in multiple JAR files\"</p>\n"
},
{
"answer_id": 37078036,
"author": "Chris Seline",
"author_id": 738764,
"author_profile": "https://Stackoverflow.com/users/738764",
"pm_score": 2,
"selected": false,
"text": "<p>If you dislike downloading and installing stuff you can use this one line command to find jar conflicts with standard gnu tools. It is rudimentary but you can expand it as you will.</p>\n\n<pre><code>ls *.jar | xargs -n1 -iFILE unzip -l FILE | grep class | sed \"s,.* ,,\" | tr \"/\" \".\" | sort | uniq -d | xargs -n1 -iCLASS grep -l CLASS *.jar | sort -u\n</code></pre>\n\n<p>(it is a bit slow to run if you have a lot of jars)</p>\n\n<p>Explanation: \nIt lists all the files in all the jars, greps for class files, finds dupes, then greps the original jars to see where they appeared. It could be made more efficient with a more complicated script.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
]
| If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical.
I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders.
Certainly a script that starts:
```
classes=`mktemp`
for i in `find . -name "*.jar"`
do
echo "File: $i" > $classes
jar tf $i > $classes
...
done
```
with some clever sort/uniq/diff/grep/awk later on has potential, but I was wondering if anyone knows of any existing solutions. | The [Tattletale](http://www.jboss.org/tattletale) tool from JBoss is another candidate: "Spot if a class/package is located in multiple JAR files" |
135,995 | <p>So, I want to define a singleton method for an object, but I want to do it using a closure.</p>
<p>For example,</p>
<pre><code>def define_say(obj, msg)
def obj.say
puts msg
end
end
o = Object.new
define_say o, "hello world!"
o.say
</code></pre>
<p>This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method.</p>
<p>What I would like to do is something like using the "define_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method...</p>
<p>So, I would love to write it something like this:</p>
<pre><code>def define_say(obj, msg)
obj.define_singleton_method(:say) {
puts msg
}
end
</code></pre>
<p>Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this)</p>
| [
{
"answer_id": 136194,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<p>Here's an answer which does what you're looking for</p>\n\n<pre><code>def define_say(obj, msg)\n # Get a handle to the singleton class of obj\n metaclass = class << obj; self; end \n\n # add the method using define_method instead of def x.say so we can use a closure\n metaclass.send :define_method, :say do\n puts msg\n end\nend\n</code></pre>\n\n<p>Usage (paste from IRB)</p>\n\n<pre><code>>> s = \"my string\"\n=> \"my string\"\n>> define_say(s, \"I am S\")\n=> #<Proc:0xb6ed55b0@(irb):11>\n>> s.say\nI am S\n=> nil\n</code></pre>\n\n<p>For more info (and a little library which makes it less messy) read this:</p>\n\n<p><a href=\"http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html\" rel=\"nofollow noreferrer\">http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html</a></p>\n\n<p>As an aside, If you're a ruby programmer, and you HAVEN'T read that, go do it now~!</p>\n"
},
{
"answer_id": 6447238,
"author": "asymmetric",
"author_id": 112538,
"author_profile": "https://Stackoverflow.com/users/112538",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://ruby-doc.org/core-1.9.2/Object.html#method-i-define_singleton_method\" rel=\"nofollow\"><code>Object#define_singleton_method</code></a> was added to ruby-1.9.2 by the way:</p>\n\n<pre><code>def define_say(obj, msg)\n obj.define_singleton_method(:say) do\n puts msg\n end\nend\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
| So, I want to define a singleton method for an object, but I want to do it using a closure.
For example,
```
def define_say(obj, msg)
def obj.say
puts msg
end
end
o = Object.new
define_say o, "hello world!"
o.say
```
This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method.
What I would like to do is something like using the "define\_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method...
So, I would love to write it something like this:
```
def define_say(obj, msg)
obj.define_singleton_method(:say) {
puts msg
}
end
```
Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this) | Here's an answer which does what you're looking for
```
def define_say(obj, msg)
# Get a handle to the singleton class of obj
metaclass = class << obj; self; end
# add the method using define_method instead of def x.say so we can use a closure
metaclass.send :define_method, :say do
puts msg
end
end
```
Usage (paste from IRB)
```
>> s = "my string"
=> "my string"
>> define_say(s, "I am S")
=> #<Proc:0xb6ed55b0@(irb):11>
>> s.say
I am S
=> nil
```
For more info (and a little library which makes it less messy) read this:
<http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html>
As an aside, If you're a ruby programmer, and you HAVEN'T read that, go do it now~! |
136,028 | <p>I realize there is a somewhat related thread on this here:
<a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">Loading assemblies and its dependencies</a></p>
<p>But I am modifying something and this doesn't exactly apply. </p>
<pre><code>string path = Path.GetDirectoryName( pathOfAssembly );
Environment.CurrentDirectory = path;
Assembly.Load(Path.GetFileNameWithoutExtension(pastOfAssembly));
</code></pre>
<p>Is there any really reason you would do it like this? Wouldn't it make more sense to just use:</p>
<pre><code>Assembly.LoadFile(pathOfAssembly);
</code></pre>
<p>Any insight would be greatly appreciated.</p>
| [
{
"answer_id": 136072,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 4,
"selected": true,
"text": "<p>Looks like the \"Department of Redundancy Department.\"</p>\n\n<p>A lot more code than is necessary. Less is more!</p>\n\n<p><strong>Edit:</strong> On second thought, it could be that the assembly you are loading has dependencies that live in its own folder that may be required to use the first assembly. </p>\n"
},
{
"answer_id": 138243,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "<p>This can be necessary when you are developping a windows service. The working dir of a service defaults to %WinDir%, so if you want to load an assembly from the dir that your service exe resides in, this is the way to go.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
]
| I realize there is a somewhat related thread on this here:
[Loading assemblies and its dependencies](https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies)
But I am modifying something and this doesn't exactly apply.
```
string path = Path.GetDirectoryName( pathOfAssembly );
Environment.CurrentDirectory = path;
Assembly.Load(Path.GetFileNameWithoutExtension(pastOfAssembly));
```
Is there any really reason you would do it like this? Wouldn't it make more sense to just use:
```
Assembly.LoadFile(pathOfAssembly);
```
Any insight would be greatly appreciated. | Looks like the "Department of Redundancy Department."
A lot more code than is necessary. Less is more!
**Edit:** On second thought, it could be that the assembly you are loading has dependencies that live in its own folder that may be required to use the first assembly. |
136,034 | <p>I've looked around for a good example of this, but I haven't run into one yet. I want to pass a custom string array from java to oracle and back, using the IBATIS framework. Does anyone have a good link to an example? I'm calling stored procs from IBATIS.</p>
<p>Thanks</p>
| [
{
"answer_id": 137693,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 2,
"selected": false,
"text": "<p>You've got to start with a custom instance of <code>TypeHandler</code>. We'd prefer to implement the simpler <code>TypeHandlerCallback</code>, but in this scenario we need access to the underlying <code>Connection</code>.</p>\n\n<pre><code>public class ArrayTypeHandler implements TypeHandler {\n\n public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType)\n throws SQLException {\n if (param == null) {\n ps.setNull(i, Types.ARRAY);\n } else {\n Connection conn = ps.getConnection();\n Array loc = conn.createArrayOf(\"myArrayType\", (Object[]) param);\n ps.setArray(i, loc);\n }\n }\n\n public Object getResult(CallableStatement statement, int i)\n throws SQLException {\n return statement.getArray(i).getArray();\n }\n ...\n}\n</code></pre>\n\n<p>Then, to wire it up in the iBATIS config:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"arrayTest\">\n\n <parameterMap id=\"storedprocParams\" class=\"map\">\n <parameter property=\"result\" mode=\"OUT\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/>\n <parameter property=\"argument\" mode=\"IN\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/>\n </parameterMap>\n\n <procedure id=\"storedproc\" parameterMap=\"arrayTest.storedprocParams\">\n {? = call My_Array_Function( ? )}\n </procedure>\n\n</sqlMap>\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 150572,
"author": "Justin",
"author_id": 22365,
"author_profile": "https://Stackoverflow.com/users/22365",
"pm_score": 2,
"selected": false,
"text": "<p>bsanders gave me a good starting point - here's what I had to do to make it work within the RAD environment (websphere 6.2).</p>\n\n<pre><code>public Object getResult(CallableStatement statement, int i) throws SQLException {\n return statement.getArray(i).getArray(); //getting null pointer exception here\n}\n\npublic void setParameter(PreparedStatement ps, int i, Object param, String jdbcType) throws SQLException {\n if (param == null) {\n ps.setNull(i, Types.ARRAY);\n\n } else {\n String[] a = (String[]) param;\n //ARRAY aOracle = ARRAY.toARRAY(a, (OracleConnection)ps.getConnection());\n\n //com.ibm.ws.rsadapter.jdbc.WSJdbcConnection\n w = (com.ibm.ws.rsadapter.jdbc.WSJdbcConnection)ps.getConnection());\n\n //com.ibm.ws.rsadapter.jdbc.WSJdbcObject x;\n Connection nativeConnection = Connection)WSJdbcUtil.getNativeConnection((WSJdbcConnection)ps.getConnection());\n\n ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor(\"F2_LIST\", nativeConnection);\n ARRAY dataArray = new ARRAY(descriptor, nativeConnection, a);\n ps.setArray(i, dataArray);\n }\n}\n</code></pre>\n\n<p>Notice the nativeConnection I had to get, the descriptor I had to make, and so on. However, while I can pass things into the database as an array of Strings, I haven't been able to figure out why I'm not getting anything back. My OUT parameter (the getResult(CallableStatement statment, int i) is throwing a null pointer exception, even though I'm setting the out parameter in the plsql in the database.</p>\n\n<pre><code>--stored procedure to take a | delimited ids\n PROCEDURE array_test (argument IN f2_list, result OUT f2_list) \n AS\n l_procname_v VARCHAR2 (50) := 'array_test';\n l_param_list VARCHAR2 (2000)\n := l_procname_v || ' param_values: p_string: ';\n\n p_status_n NUMBER;\n p_message_v VARCHAR2 (2000);\n ret_list f2_list := new f2_list();\n l_count_v varchar2(200);\n BEGIN\n\n l_count_v := argument.COUNT;\n for x in 1..argument.count\n LOOP\n pkg_az_common_util.az_debug (package_nm,\n l_procname_v,\n pkg_az_data_type_def.debug_num,\n argument(x)\n );\n end loop;\n\n pkg_az_common_util.az_debug (package_nm,\n l_procname_v,\n pkg_az_data_type_def.debug_num,\n l_count_v\n );\n ret_list.extend();\n ret_list(1) := 'W';\n ret_list.extend();\n ret_list(2) := 'X';\n ret_list.extend();\n ret_list(3) := 'Y';\n ret_list.extend();\n ret_list(4) := 'Z';\n\n result := ret_list;\n\n\n EXCEPTION\n WHEN OTHERS\n THEN\n p_status_n := pkg_az_common_util.get_error_code;\n p_message_v :=\n TO_CHAR (p_status_n)\n || '|'\n || 'Oracle Internal Exception('\n || l_procname_v\n || ')'\n || '|'\n || TO_CHAR (SQLCODE)\n || '|'\n || SQLERRM\n || l_param_list;\n standard_pkg.log_error (package_nm,\n l_procname_v,\n SQLCODE,\n p_message_v\n );\n\n IF p_status_n = 1\n THEN\n RAISE;\n END IF;\n END array_test;\n</code></pre>\n\n<p>Here is how I'm accessing it:</p>\n\n<pre><code>Map queryParamsTest = new HashMap();\n\n String[] testArray = {\"A\", \"B\", \"C\"};\n\n queryParamsTest.put(\"argument\", testArray);\n\n\n\n DaoUtils.executeQuery(super.getSqlMapClientTemplate(),\n \"arrayTest\", queryParamsTest, queryParamsTest\n .toString()); //just executes query\n\n\n String[] resultArray = (String[])queryParamsTest.get(\"result\");\n\n for(int x = 0; x< resultArray.length; x++)\n {\n System.out.println(\"Result: \" + resultArray[x]);\n }\n\n\n\n<parameterMap id=\"storedprocParams\" class=\"map\"> \n <parameter property=\"argument\" mode=\"IN\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/> \n <parameter property=\"result\" mode=\"OUT\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/> \n </parameterMap> \n <procedure id=\"arrayTest\" parameterMap=\"storedprocParams\"> \n {call pkg_az_basic_dev.array_test(?, ? )} \n </procedure>\n</code></pre>\n\n<p>Any ideas?</p>\n"
},
{
"answer_id": 153452,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 0,
"selected": false,
"text": "<p>Try using <code>statement.getObject(i)</code> and then casting to an array.</p>\n"
},
{
"answer_id": 7833601,
"author": "tomasb",
"author_id": 881375,
"author_profile": "https://Stackoverflow.com/users/881375",
"pm_score": 1,
"selected": false,
"text": "<p>Well, guys in company found out the <strong>solution</strong>: you need to have implemented getResult method(s) in your typeHandler and provided additional attribute jdbcTypeName=ORACLE_REAL_ARRAY_TYPE in your mapper</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22365/"
]
| I've looked around for a good example of this, but I haven't run into one yet. I want to pass a custom string array from java to oracle and back, using the IBATIS framework. Does anyone have a good link to an example? I'm calling stored procs from IBATIS.
Thanks | You've got to start with a custom instance of `TypeHandler`. We'd prefer to implement the simpler `TypeHandlerCallback`, but in this scenario we need access to the underlying `Connection`.
```
public class ArrayTypeHandler implements TypeHandler {
public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType)
throws SQLException {
if (param == null) {
ps.setNull(i, Types.ARRAY);
} else {
Connection conn = ps.getConnection();
Array loc = conn.createArrayOf("myArrayType", (Object[]) param);
ps.setArray(i, loc);
}
}
public Object getResult(CallableStatement statement, int i)
throws SQLException {
return statement.getArray(i).getArray();
}
...
}
```
Then, to wire it up in the iBATIS config:
```
<?xml version="1.0"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="arrayTest">
<parameterMap id="storedprocParams" class="map">
<parameter property="result" mode="OUT" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
<parameter property="argument" mode="IN" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
</parameterMap>
<procedure id="storedproc" parameterMap="arrayTest.storedprocParams">
{? = call My_Array_Function( ? )}
</procedure>
</sqlMap>
```
Hope this helps! |
136,035 | <p>It is discouraged to simply catch <code>System.Exception</code>. Instead, only the "known" exceptions should be caught.</p>
<p>Now, this sometimes leads to unnecessary repetitive code, for example:</p>
<pre><code>try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
</code></pre>
<p>I wonder: Is there a way to catch both exceptions and only call the <code>WebId = Guid.Empty</code> call once?</p>
<p>The given example is rather simple, as it's only a <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer"><code>GUID</code></a>. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the <code>object</code>. However, if there is an unexpected exception, I still want to throw that higher.</p>
| [
{
"answer_id": 136038,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": false,
"text": "<p>Note that I did find one way to do it, but this looks more like material for <a href=\"https://en.wikipedia.org/wiki/The_Daily_WTF\" rel=\"noreferrer\">The Daily WTF</a>:</p>\n\n<pre><code>catch (Exception ex)\n{\n switch (ex.GetType().Name)\n {\n case \"System.FormatException\":\n case \"System.OverflowException\":\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 136046,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 4,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code>try\n{\n WebId = Guid.Empty;\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (FormatException)\n{\n}\ncatch (OverflowException)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 136092,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 12,
"selected": true,
"text": "<p>Catch <code>System.Exception</code> and switch on the types</p>\n<pre><code>catch (Exception ex) \n{ \n if (ex is FormatException || ex is OverflowException)\n {\n WebId = Guid.Empty;\n return;\n }\n \n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 136094,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>@Micheal</p>\n\n<p>Slightly revised version of your code:</p>\n\n<pre><code>catch (Exception ex)\n{\n Type exType = ex.GetType();\n if (exType == typeof(System.FormatException) || \n exType == typeof(System.OverflowException)\n {\n WebId = Guid.Empty;\n } else {\n throw;\n }\n}\n</code></pre>\n\n<p>String comparisons are ugly and slow.</p>\n"
},
{
"answer_id": 136114,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 8,
"selected": false,
"text": "<p>Not in C# unfortunately, as you'd need an exception filter to do it and C# doesn't expose that feature of MSIL. VB.NET does have this capability though, e.g.</p>\n\n<pre><code>Catch ex As Exception When TypeOf ex Is FormatException OrElse TypeOf ex Is OverflowException\n</code></pre>\n\n<p>What you could do is use an anonymous function to encapsulate your on-error code, and then call it in those specific catch blocks:</p>\n\n<pre><code>Action onError = () => WebId = Guid.Empty;\ntry\n{\n // something\n}\ncatch (FormatException)\n{\n onError();\n}\ncatch (OverflowException)\n{\n onError();\n}\n</code></pre>\n"
},
{
"answer_id": 419531,
"author": "Konstantin Spirin",
"author_id": 1423922,
"author_profile": "https://Stackoverflow.com/users/1423922",
"pm_score": 5,
"selected": false,
"text": "<pre><code>catch (Exception ex) when (ex is FormatException or OverflowException)\n{\n WebId = Guid.Empty;\n}\n</code></pre>\n<p>or</p>\n<pre><code>catch (Exception ex)\n{\n if (ex is not FormatException and not OverflowException)\n throw;\n\n WebId = Guid.Empty;\n}\n</code></pre>\n"
},
{
"answer_id": 3373810,
"author": "Matt",
"author_id": 179310,
"author_profile": "https://Stackoverflow.com/users/179310",
"pm_score": 4,
"selected": false,
"text": "<p>The accepted answer seems acceptable, except that CodeAnalysis/<a href=\"http://en.wikipedia.org/wiki/FxCop\" rel=\"noreferrer\">FxCop</a> will complain about the fact that it's catching a general exception type.</p>\n\n<p>Also, it seems the \"is\" operator might degrade performance slightly.</p>\n\n<p><em><a href=\"http://msdn.microsoft.com/en-us/library/ms182271.aspx\" rel=\"noreferrer\">CA1800: Do not cast unnecessarily</a></em> says to \"consider testing the result of the 'as' operator instead\", but if you do that, you'll be writing more code than if you catch each exception separately.</p>\n\n<p>Anyhow, here's what I would do:</p>\n\n<pre><code>bool exThrown = false;\n\ntry\n{\n // Something\n}\ncatch (FormatException) {\n exThrown = true;\n}\ncatch (OverflowException) {\n exThrown = true;\n}\n\nif (exThrown)\n{\n // Something else\n}\n</code></pre>\n"
},
{
"answer_id": 12222312,
"author": "bsara",
"author_id": 1203288,
"author_profile": "https://Stackoverflow.com/users/1203288",
"pm_score": 4,
"selected": false,
"text": "<p>This is a variant of Matt's answer (I feel that this is a bit cleaner)...use a method:</p>\n\n<pre><code>public void TryCatch(...)\n{\n try\n {\n // something\n return;\n }\n catch (FormatException) {}\n catch (OverflowException) {}\n\n WebId = Guid.Empty;\n}\n</code></pre>\n\n<p>Any other exceptions will be thrown and the code <code>WebId = Guid.Empty;</code> won't be hit. If you don't want other exceptions to crash your program, just add this AFTER the other two catches:</p>\n\n<pre><code>...\ncatch (Exception)\n{\n // something, if anything\n return; // only need this if you follow the example I gave and put it all in a method\n}\n</code></pre>\n"
},
{
"answer_id": 15987704,
"author": "Athari",
"author_id": 293099,
"author_profile": "https://Stackoverflow.com/users/293099",
"pm_score": 7,
"selected": false,
"text": "<p>For the sake of completeness, since <strong>.NET 4.0</strong> the code can rewritten as:</p>\n\n<pre><code>Guid.TryParse(queryString[\"web\"], out WebId);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.guid.tryparse.aspx\" rel=\"noreferrer\">TryParse</a> never throws exceptions and returns false if format is wrong, setting WebId to <code>Guid.Empty</code>.</p>\n\n<hr>\n\n<p>Since <strong>C# 7</strong> you can avoid introducing a variable on a separate line:</p>\n\n<pre><code>Guid.TryParse(queryString[\"web\"], out Guid webId);\n</code></pre>\n\n<p>You can also create methods for parsing returning tuples, which aren't available in .NET Framework yet as of version 4.6:</p>\n\n<pre><code>(bool success, Guid result) TryParseGuid(string input) =>\n (Guid.TryParse(input, out Guid result), result);\n</code></pre>\n\n<p>And use them like this:</p>\n\n<pre><code>WebId = TryParseGuid(queryString[\"web\"]).result;\n// or\nvar tuple = TryParseGuid(queryString[\"web\"]);\nWebId = tuple.success ? tuple.result : DefaultWebId;\n</code></pre>\n\n<hr>\n\n<p>Next useless update to this useless answer comes when deconstruction of out-parameters is implemented in C# 12. :)</p>\n"
},
{
"answer_id": 16623758,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 4,
"selected": false,
"text": "<h3>Cautioned and Warned: <a href=\"http://community.bartdesmet.net/blogs/bart/archive/2008/01/06/exception-handling-in-functional-style.aspx\" rel=\"noreferrer\">Yet another kind, functional style.</a></h3>\n<p>What is in the link doesn't answer your question directly, but it's trivial to extend it to look like:</p>\n<pre><code>static void Main() \n{ \n Action body = () => { ...your code... };\n\n body.Catch<InvalidOperationException>() \n .Catch<BadCodeException>() \n .Catch<AnotherException>(ex => { ...handler... })(); \n}\n</code></pre>\n<p><em>(Basically provide another empty <code>Catch</code> overload which returns itself)</em></p>\n<p>The bigger question to this is <em>why</em>. I do not think the cost outweighs the gain here :)</p>\n"
},
{
"answer_id": 19329123,
"author": "Craig Tullis",
"author_id": 618649,
"author_profile": "https://Stackoverflow.com/users/618649",
"pm_score": 10,
"selected": false,
"text": "<p><strong>EDIT:</strong> I do concur with others who are saying that, as of C# 6.0, exception filters are now a perfectly fine way to go: <code>catch (Exception ex) when (ex is ... || ex is ... )</code></p>\n<p>Except that I still kind of hate the one-long-line layout and would personally lay the code out like the following. I think this is as functional as it is aesthetic, since I believe it improves comprehension. Some may disagree:</p>\n<pre><code>catch (Exception ex) when (\n ex is ...\n || ex is ...\n || ex is ...\n)\n</code></pre>\n<p><strong>ORIGINAL:</strong></p>\n<p>I know I'm a little late to the party here, but holy smoke...</p>\n<p>Cutting straight to the chase, this kind of duplicates an earlier answer, but if you really want to perform a common action for several exception types and keep the whole thing neat and tidy within the scope of the one method, why not just use a lambda/closure/inline function to do something like the following? I mean, chances are pretty good that you'll end up realizing that you just want to make that closure a separate method that you can utilize all over the place. But then it will be super easy to do that without actually changing the rest of the code structurally. Right?</p>\n<pre><code>private void TestMethod ()\n{\n Action<Exception> errorHandler = ( ex ) => {\n // write to a log, whatever...\n };\n\n try\n {\n // try some stuff\n }\n catch ( FormatException ex ) { errorHandler ( ex ); }\n catch ( OverflowException ex ) { errorHandler ( ex ); }\n catch ( ArgumentNullException ex ) { errorHandler ( ex ); }\n}\n</code></pre>\n<p>I can't help but wonder (<strong>warning:</strong> a little irony/sarcasm ahead) why on earth go to all this effort to basically just replace the following:</p>\n<pre><code>try\n{\n // try some stuff\n}\ncatch( FormatException ex ){}\ncatch( OverflowException ex ){}\ncatch( ArgumentNullException ex ){}\n</code></pre>\n<p>...with some crazy variation of this next code smell, I mean example, only to pretend that you're saving a few keystrokes.</p>\n<pre><code>// sorta sucks, let's be honest...\ntry\n{\n // try some stuff\n}\ncatch( Exception ex )\n{\n if (ex is FormatException ||\n ex is OverflowException ||\n ex is ArgumentNullException)\n {\n // write to a log, whatever...\n return;\n }\n throw;\n}\n</code></pre>\n<p>Because it certainly isn't automatically more readable.</p>\n<p>Granted, I left the three identical instances of <code>/* write to a log, whatever... */ return;</code> out of the first example.</p>\n<p>But that's sort of my point. Y'all have heard of functions/methods, right? Seriously. Write a common <code>ErrorHandler</code> function and, like, call it from each catch block.</p>\n<p>If you ask me, the second example (with the <code>if</code> and <code>is</code> keywords) is both significantly less readable, and simultaneously significantly more error-prone during the maintenance phase of your project.</p>\n<p>The maintenance phase, for anyone who might be relatively new to programming, is going to compose 98.7% or more of the overall lifetime of your project, and the poor schmuck doing the maintenance is almost certainly going to be someone other than you. And there is a very good chance they will spend 50% of their time on the job cursing your name.</p>\n<p>And of course FxCop barks at you and so you have to <em><strong>also</strong></em> add an attribute to your code that has precisely zip to do with the running program, and is only there to tell FxCop to ignore an issue that in 99.9% of cases it is totally correct in flagging. And, sorry, I might be mistaken, but doesn't that "ignore" attribute end up actually compiled into your app?</p>\n<p>Would putting the entire <code>if</code> test on one line make it more readable? I don't think so. I mean, I did have another programmer vehemently argue once long ago that putting more code on one line would make it "run faster." But of course he was stark raving nuts. Trying to explain to him (with a straight face--which was challenging) how the interpreter or compiler would break that long line apart into discrete one-instruction-per-line statements--essentially identical to the result if he had gone ahead and just made the code readable instead of trying to out-clever the compiler--had no effect on him whatsoever. But I digress.</p>\n<p>How much <em>less</em> readable does this get when you add three more exception types, a month or two from now? (Answer: it gets a <em><strong>lot</strong></em> less readable).</p>\n<p>One of the major points, really, is that most of the point of formatting the textual source code that we're all looking at every day is to make it really, really obvious to other human beings what is actually happening when the code runs. Because the compiler turns the source code into something totally different and couldn't care less about your code formatting style. So all-on-one-line totally sucks, too.</p>\n<p>Just saying...</p>\n<pre><code>// super sucks...\ncatch( Exception ex )\n{\n if ( ex is FormatException || ex is OverflowException || ex is ArgumentNullException )\n {\n // write to a log, whatever...\n return;\n }\n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 20253816,
"author": "HodlDwon",
"author_id": 1718702,
"author_profile": "https://Stackoverflow.com/users/1718702",
"pm_score": 3,
"selected": false,
"text": "<p>Update 2015-12-15: See <a href=\"https://stackoverflow.com/a/22864936/1718702\">https://stackoverflow.com/a/22864936/1718702</a> for C#6. It's a cleaner and now standard in the language.</p>\n\n<p>Geared for people that want a <a href=\"https://stackoverflow.com/q/791390/1718702\">more elegant solution</a> to catch once and filter exceptions, I use an extension method as demonstrated below.</p>\n\n<p>I already had this extension in my library, originally written for other purposes, but it worked just perfectly for <code>type</code> checking on exceptions. Plus, imho, it looks cleaner than a bunch of <code>||</code> statements. Also, unlike the accepted answer, I prefer explicit exception handling so <code>ex is ...</code> had undesireable behaviour as derrived classes are assignable to there parent types).</p>\n\n<p><strong>Usage</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (ex.GetType().IsAnyOf(\n typeof(FormatException),\n typeof(ArgumentException)))\n{\n // Handle\n}\nelse\n throw;\n</code></pre>\n\n<p><strong>IsAnyOf.cs Extension (See Full Error Handling Example for Dependancies)</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter matches at least one of the passed in comparisons.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_comparisons\">Values to compare against.</param>\n /// <returns>True if a match is found.</returns>\n /// <exception cref=\"ArgumentNullException\"></exception>\n public static bool IsAnyOf<T>(this T p_parameter, params T[] p_comparisons)\n {\n // Validate\n p_parameter\n .CannotBeNull(\"p_parameter\");\n p_comparisons\n .CannotBeNullOrEmpty(\"p_comparisons\");\n\n // Test for any match\n foreach (var item in p_comparisons)\n if (p_parameter.Equals(item))\n return true;\n\n // Return no matches found\n return false;\n }\n }\n}\n</code></pre>\n\n<p><strong>Full Error Handling Example (Copy-Paste to new Console app)</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Common.FluentValidation;\n\nnamespace IsAnyOfExceptionHandlerSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n // High Level Error Handler (Log and Crash App)\n try\n {\n Foo();\n }\n catch (OutOfMemoryException ex)\n {\n Console.WriteLine(\"FATAL ERROR! System Crashing. \" + ex.Message);\n Console.ReadKey();\n }\n }\n\n static void Foo()\n {\n // Init\n List<Action<string>> TestActions = new List<Action<string>>()\n {\n (key) => { throw new FormatException(); },\n (key) => { throw new ArgumentException(); },\n (key) => { throw new KeyNotFoundException();},\n (key) => { throw new OutOfMemoryException(); },\n };\n\n // Run\n foreach (var FooAction in TestActions)\n {\n // Mid-Level Error Handler (Appends Data for Log)\n try\n {\n // Init\n var SomeKeyPassedToFoo = \"FooParam\";\n\n // Low-Level Handler (Handle/Log and Keep going)\n try\n {\n FooAction(SomeKeyPassedToFoo);\n }\n catch (Exception ex)\n {\n if (ex.GetType().IsAnyOf(\n typeof(FormatException),\n typeof(ArgumentException)))\n {\n // Handle\n Console.WriteLine(\"ex was {0}\", ex.GetType().Name);\n Console.ReadKey();\n }\n else\n {\n // Add some Debug info\n ex.Data.Add(\"SomeKeyPassedToFoo\", SomeKeyPassedToFoo.ToString());\n throw;\n }\n }\n }\n catch (KeyNotFoundException ex)\n {\n // Handle differently\n Console.WriteLine(ex.Message);\n\n int Count = 0;\n if (!Validate.IsAnyNull(ex, ex.Data, ex.Data.Keys))\n foreach (var Key in ex.Data.Keys)\n Console.WriteLine(\n \"[{0}][\\\"{1}\\\" = {2}]\",\n Count, Key, ex.Data[Key]);\n\n Console.ReadKey();\n }\n }\n }\n }\n}\n\nnamespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter matches at least one of the passed in comparisons.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_comparisons\">Values to compare against.</param>\n /// <returns>True if a match is found.</returns>\n /// <exception cref=\"ArgumentNullException\"></exception>\n public static bool IsAnyOf<T>(this T p_parameter, params T[] p_comparisons)\n {\n // Validate\n p_parameter\n .CannotBeNull(\"p_parameter\");\n p_comparisons\n .CannotBeNullOrEmpty(\"p_comparisons\");\n\n // Test for any match\n foreach (var item in p_comparisons)\n if (p_parameter.Equals(item))\n return true;\n\n // Return no matches found\n return false;\n }\n\n /// <summary>\n /// Validates if any passed in parameter is equal to null.\n /// </summary>\n /// <param name=\"p_parameters\">Parameters to test for Null.</param>\n /// <returns>True if one or more parameters are null.</returns>\n public static bool IsAnyNull(params object[] p_parameters)\n {\n p_parameters\n .CannotBeNullOrEmpty(\"p_parameters\");\n\n foreach (var item in p_parameters)\n if (item == null)\n return true;\n\n return false;\n }\n }\n}\n\nnamespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter is not null, throwing a detailed exception message if the test fails.\n /// </summary>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_name\">Name of tested parameter to assist with debugging.</param>\n /// <exception cref=\"ArgumentNullException\"></exception>\n public static void CannotBeNull(this object p_parameter, string p_name)\n {\n if (p_parameter == null)\n throw\n new\n ArgumentNullException(\n string.Format(\"Parameter \\\"{0}\\\" cannot be null.\",\n p_name), default(Exception));\n }\n }\n}\n\nnamespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter is not null or an empty collection, throwing a detailed exception message if the test fails.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_name\">Name of tested parameter to assist with debugging.</param>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"ArgumentOutOfRangeException\"></exception>\n public static void CannotBeNullOrEmpty<T>(this ICollection<T> p_parameter, string p_name)\n {\n if (p_parameter == null)\n throw new ArgumentNullException(\"Collection cannot be null.\\r\\nParameter_Name: \" + p_name, default(Exception));\n\n if (p_parameter.Count <= 0)\n throw new ArgumentOutOfRangeException(\"Collection cannot be empty.\\r\\nParameter_Name: \" + p_name, default(Exception));\n }\n\n /// <summary>\n /// Validates the passed in parameter is not null or empty, throwing a detailed exception message if the test fails.\n /// </summary>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_name\">Name of tested parameter to assist with debugging.</param>\n /// <exception cref=\"ArgumentException\"></exception>\n public static void CannotBeNullOrEmpty(this string p_parameter, string p_name)\n {\n if (string.IsNullOrEmpty(p_parameter))\n throw new ArgumentException(\"String cannot be null or empty.\\r\\nParameter_Name: \" + p_name, default(Exception));\n }\n }\n}\n</code></pre>\n\n<p><strong>Two Sample NUnit Unit Tests</strong></p>\n\n<p>Matching behaviour for <code>Exception</code> types is exact (ie. A child IS NOT a match for any of its parent types).</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing Common.FluentValidation;\nusing NUnit.Framework;\n\nnamespace UnitTests.Common.Fluent_Validations\n{\n [TestFixture]\n public class IsAnyOf_Tests\n {\n [Test, ExpectedException(typeof(ArgumentNullException))]\n public void IsAnyOf_ArgumentNullException_ShouldNotMatch_ArgumentException_Test()\n {\n Action TestMethod = () => { throw new ArgumentNullException(); };\n\n try\n {\n TestMethod();\n }\n catch (Exception ex)\n {\n if (ex.GetType().IsAnyOf(\n typeof(ArgumentException), /*Note: ArgumentNullException derrived from ArgumentException*/\n typeof(FormatException),\n typeof(KeyNotFoundException)))\n {\n // Handle expected Exceptions\n return;\n }\n\n //else throw original\n throw;\n }\n }\n\n [Test, ExpectedException(typeof(OutOfMemoryException))]\n public void IsAnyOf_OutOfMemoryException_ShouldMatch_OutOfMemoryException_Test()\n {\n Action TestMethod = () => { throw new OutOfMemoryException(); };\n\n try\n {\n TestMethod();\n }\n catch (Exception ex)\n {\n if (ex.GetType().IsAnyOf(\n typeof(OutOfMemoryException),\n typeof(StackOverflowException)))\n throw;\n\n /*else... Handle other exception types, typically by logging to file*/\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22864936,
"author": "Joe",
"author_id": 1324810,
"author_profile": "https://Stackoverflow.com/users/1324810",
"pm_score": 9,
"selected": false,
"text": "<p>As others have pointed out, you can have an <code>if</code> statement inside your catch block to determine what is going on. C#6 supports Exception Filters, so the following will work:</p>\n\n<pre><code>try { … }\ncatch (Exception e) when (MyFilter(e))\n{\n …\n}\n</code></pre>\n\n<p>The <code>MyFilter</code> method could then look something like this:</p>\n\n<pre><code>private bool MyFilter(Exception e)\n{\n return e is ArgumentNullException || e is FormatException;\n}\n</code></pre>\n\n<p>Alternatively, this can be all done inline (the right hand side of the when statement just has to be a boolean expression).</p>\n\n<pre><code>try { … }\ncatch (Exception e) when (e is ArgumentNullException || e is FormatException)\n{\n …\n}\n</code></pre>\n\n<p>This is different from using an <code>if</code> statement from within the <code>catch</code> block, using exception filters <strong>will not</strong> unwind the stack.</p>\n\n<p>You can download <a href=\"http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx\">Visual Studio 2015</a> to check this out.</p>\n\n<p>If you want to continue using Visual Studio 2013, you can install the following nuget package:</p>\n\n<blockquote>\n <p>Install-Package Microsoft.Net.Compilers</p>\n</blockquote>\n\n<p><a href=\"http://www.nuget.org/packages/Microsoft.Net.Compilers/\">At time of writing, this will include support for C# 6.</a></p>\n\n<blockquote>\n <p>Referencing this package will cause the project to be built using the\n specific version of the C# and Visual Basic compilers contained in the\n package, as opposed to any system installed version.</p>\n</blockquote>\n"
},
{
"answer_id": 26483624,
"author": "atlaste",
"author_id": 1031591,
"author_profile": "https://Stackoverflow.com/users/1031591",
"pm_score": 3,
"selected": false,
"text": "<p>Since I felt like these answers just touched the surface, I attempted to dig a bit deeper.</p>\n\n<p>So what we would really want to do is something that doesn't compile, say:</p>\n\n<pre><code>// Won't compile... damn\npublic static void Main()\n{\n try\n {\n throw new ArgumentOutOfRangeException();\n }\n catch (ArgumentOutOfRangeException)\n catch (IndexOutOfRangeException) \n {\n // ... handle\n }\n</code></pre>\n\n<p>The reason we want this is because we don't want the exception handler to catch things that we need later on in the process. Sure, we can catch an Exception and check with an 'if' what to do, but let's be honest, we don't really want that. (FxCop, debugger issues, uglyness)</p>\n\n<p>So why won't this code compile - and how can we hack it in such a way that it will?</p>\n\n<p>If we look at the code, what we really would like to do is forward the call. However, according to the MS Partition II, IL exception handler blocks won't work like this, which in this case makes sense because that would imply that the 'exception' object can have different types. </p>\n\n<p>Or to write it in code, we ask the compiler to do something like this (well it's not entirely correct, but it's the closest possible thing I guess):</p>\n\n<pre><code>// Won't compile... damn\ntry\n{\n throw new ArgumentOutOfRangeException();\n}\ncatch (ArgumentOutOfRangeException e) {\n goto theOtherHandler;\n}\ncatch (IndexOutOfRangeException e) {\ntheOtherHandler:\n Console.WriteLine(\"Handle!\");\n}\n</code></pre>\n\n<p>The reason that this won't compile is quite obvious: what type and value would the '$exception' object have (which are here stored in the variables 'e')? The way we want the compiler to handle this is to note that the common base type of both exceptions is 'Exception', use that for a variable to contain both exceptions, and then handle only the two exceptions that are caught. The way this is implemented in IL is as 'filter', which is available in VB.Net.</p>\n\n<p>To make it work in C#, we need a temporary variable with the correct 'Exception' base type. To control the flow of the code, we can add some branches. Here goes:</p>\n\n<pre><code> Exception ex;\n try\n {\n throw new ArgumentException(); // for demo purposes; won't be caught.\n goto noCatch;\n }\n catch (ArgumentOutOfRangeException e) {\n ex = e;\n }\n catch (IndexOutOfRangeException e) {\n ex = e;\n }\n\n Console.WriteLine(\"Handle the exception 'ex' here :-)\");\n // throw ex ?\n\nnoCatch:\n Console.WriteLine(\"We're done with the exception handling.\");\n</code></pre>\n\n<p>The obvious disadvantages for this are that we cannot re-throw properly, and -well let's be honest- that it's quite the ugly solution. The uglyness can be fixed a bit by performing branch elimination, which makes the solution slightly better:</p>\n\n<pre><code>Exception ex = null;\ntry\n{\n throw new ArgumentException();\n}\ncatch (ArgumentOutOfRangeException e)\n{\n ex = e;\n}\ncatch (IndexOutOfRangeException e)\n{\n ex = e;\n}\nif (ex != null)\n{\n Console.WriteLine(\"Handle the exception here :-)\");\n}\n</code></pre>\n\n<p>That leaves just the 're-throw'. For this to work, we need to be able to perform the handling inside the 'catch' block - and the only way to make this work is by an catching 'Exception' object. </p>\n\n<p>At this point, we can add a separate function that handles the different types of Exceptions using overload resolution, or to handle the Exception. Both have disadvantages. To start, here's the way to do it with a helper function:</p>\n\n<pre><code>private static bool Handle(Exception e)\n{\n Console.WriteLine(\"Handle the exception here :-)\");\n return true; // false will re-throw;\n}\n\npublic static void Main()\n{\n try\n {\n throw new OutOfMemoryException();\n }\n catch (ArgumentException e)\n {\n if (!Handle(e)) { throw; }\n }\n catch (IndexOutOfRangeException e)\n {\n if (!Handle(e)) { throw; }\n }\n\n Console.WriteLine(\"We're done with the exception handling.\");\n</code></pre>\n\n<p>And the other solution is to catch the Exception object and handle it accordingly. The most literal translation for this, based on the context above is this:</p>\n\n<pre><code>try\n{\n throw new ArgumentException();\n}\ncatch (Exception e)\n{\n Exception ex = (Exception)(e as ArgumentException) ?? (e as IndexOutOfRangeException);\n if (ex != null)\n {\n Console.WriteLine(\"Handle the exception here :-)\");\n // throw ?\n }\n else \n {\n throw;\n }\n}\n</code></pre>\n\n<p>So to conclude:</p>\n\n<ul>\n<li>If we don't want to re-throw, we might consider catching the right exceptions, and storing them in a temporary.</li>\n<li>If the handler is simple, and we want to re-use code, the best solution is probably to introduce a helper function.</li>\n<li>If we want to re-throw, we have no choice but to put the code in a 'Exception' catch handler, which will break FxCop and your debugger's uncaught exceptions.</li>\n</ul>\n"
},
{
"answer_id": 27366344,
"author": "Stefan T",
"author_id": 2802543,
"author_profile": "https://Stackoverflow.com/users/2802543",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/136035/catch-multiple-exceptions-at-once/136092#136092\">Joseph Daigle's Answer</a> is a good solution, but I found the following structure to be a bit tidier and less error prone.</p>\n\n<pre><code>catch(Exception ex)\n{ \n if (!(ex is SomeException || ex is OtherException)) throw;\n\n // Handle exception\n}\n</code></pre>\n\n<p>There are a few advantages of inverting the expression: </p>\n\n<ul>\n<li>A return statement is not necessary</li>\n<li>The code isn't nested</li>\n<li>There's no risk of forgetting the 'throw' or 'return' statements that in Joseph's solution are separated from the expression.</li>\n</ul>\n\n<p>It can even be compacted to a single line (though not very pretty)</p>\n\n<pre><code>catch(Exception ex) { if (!(ex is SomeException || ex is OtherException)) throw;\n\n // Handle exception\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> \nThe <a href=\"http://www.codeproject.com/Articles/853207/What-s-new-in-Csharp-Exception-Filters\" rel=\"noreferrer\">exception filtering</a> in C# 6.0 will make the syntax a bit cleaner and comes with a <a href=\"https://stackoverflow.com/a/27082164/2802543\">number of other benefits</a> over any current solution. (most notably leaving the stack unharmed)</p>\n\n<p>Here is how the same problem would look using C# 6.0 syntax:</p>\n\n<pre><code>catch(Exception ex) when (ex is SomeException || ex is OtherException)\n{\n // Handle exception\n}\n</code></pre>\n"
},
{
"answer_id": 29390908,
"author": "Maniero",
"author_id": 221800,
"author_profile": "https://Stackoverflow.com/users/221800",
"pm_score": 7,
"selected": false,
"text": "<p>If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:</p>\n<pre><code>catch (Exception ex) when (ex is FormatException || ex is OverflowException) {\n WebId = Guid.Empty;\n}\n</code></pre>\n<p>Some people think this code is the same as</p>\n<pre><code>catch (Exception ex) { \n if (ex is FormatException || ex is OverflowException) {\n WebId = Guid.Empty;\n }\n throw;\n}\n</code></pre>\n<p>But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.</p>\n<p><strike>See a <a href=\"https://roslyn.codeplex.com/discussions/541301\" rel=\"noreferrer\">discussion about this on CodePlex</a></strike>Not available anymore. And an <a href=\"http://www.volatileread.com/Wiki/Index?id=1087\" rel=\"noreferrer\">example showing the difference</a>.</p>\n"
},
{
"answer_id": 30343421,
"author": "Kashif",
"author_id": 636740,
"author_profile": "https://Stackoverflow.com/users/636740",
"pm_score": -1,
"selected": false,
"text": "<p>In c# 6.0,Exception Filters is improvements for exception handling</p>\n\n<pre><code>try\n{\n DoSomeHttpRequest();\n}\ncatch (System.Web.HttpException e)\n{\n switch (e.GetHttpCode())\n {\n case 400:\n WriteLine(\"Bad Request\");\n case 500:\n WriteLine(\"Internal Server Error\");\n default:\n WriteLine(\"Generic Error\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32931248,
"author": "SHM",
"author_id": 2924454,
"author_profile": "https://Stackoverflow.com/users/2924454",
"pm_score": 4,
"selected": false,
"text": "<p>in C# 6 the recommended approach is to use Exception Filters, here is an example:</p>\n\n<pre><code> try\n {\n throw new OverflowException();\n }\n catch(Exception e ) when ((e is DivideByZeroException) || (e is OverflowException))\n {\n // this will execute iff e is DividedByZeroEx or OverflowEx\n Console.WriteLine(\"E\");\n }\n</code></pre>\n"
},
{
"answer_id": 32998804,
"author": "Tamir Vered",
"author_id": 3256506,
"author_profile": "https://Stackoverflow.com/users/3256506",
"pm_score": 5,
"selected": false,
"text": "<p>If you don't want to use an <code>if</code> statement within the <code>catch</code> scopes, <strong><em>in <code>C# 6.0</code> you can use <code>Exception Filters</code> syntax</em></strong> which was already supported by the CLR in previews versions but existed only in <code>VB.NET</code>/<code>MSIL</code>:</p>\n\n<pre><code>try\n{\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (Exception exception) when (exception is FormatException || ex is OverflowException)\n{\n WebId = Guid.Empty;\n}\n</code></pre>\n\n<p>This code will catch the <code>Exception</code> only when it's a <code>InvalidDataException</code> or <code>ArgumentNullException</code>.</p>\n\n<p>Actually, you can put basically any condition inside that <code>when</code> clause:</p>\n\n<pre><code>static int a = 8;\n\n...\n\ncatch (Exception exception) when (exception is InvalidDataException && a == 8)\n{\n Console.WriteLine(\"Catch\");\n}\n</code></pre>\n\n<p>Note that as opposed to an <code>if</code> statement inside the <code>catch</code>'s scope, <code>Exception Filters</code> cannot throw <code>Exceptions</code>, and when they do, or when the condition is not <code>true</code>, the next <code>catch</code> condition will be evaluated instead:</p>\n\n<pre><code>static int a = 7;\n\nstatic int b = 0;\n\n...\n\ntry\n{\n throw new InvalidDataException();\n}\ncatch (Exception exception) when (exception is InvalidDataException && a / b == 2)\n{\n Console.WriteLine(\"Catch\");\n}\ncatch (Exception exception) when (exception is InvalidDataException || exception is ArgumentException)\n{\n Console.WriteLine(\"General catch\");\n}\n</code></pre>\n\n<blockquote>\n <p>Output: General catch.</p>\n</blockquote>\n\n<p>When there is more then one <code>true</code> <code>Exception Filter</code> - the first one will be accepted:</p>\n\n<pre><code>static int a = 8;\n\nstatic int b = 4;\n\n...\n\ntry\n{\n throw new InvalidDataException();\n}\ncatch (Exception exception) when (exception is InvalidDataException && a / b == 2)\n{\n Console.WriteLine(\"Catch\");\n}\ncatch (Exception exception) when (exception is InvalidDataException || exception is ArgumentException)\n{\n Console.WriteLine(\"General catch\");\n}\n</code></pre>\n\n<blockquote>\n <p>Output: Catch.</p>\n</blockquote>\n\n<p>And as you can see in the <code>MSIL</code> the code is not translated to <code>if</code> statements, but to <code>Filters</code>, and <code>Exceptions</code> cannot be throw from within the areas marked with <code>Filter 1</code> and <code>Filter 2</code> but the filter throwing the <code>Exception</code> will fail instead, also the last comparison value pushed to the stack before the <code>endfilter</code> command will determine the success/failure of the filter (<code>Catch 1</code> <strong><em>XOR</em></strong> <code>Catch 2</code> will execute accordingly):</p>\n\n<p><a href=\"https://i.stack.imgur.com/uEfE9.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uEfE9.jpg\" alt=\"Exception Filters MSIL\"></a></p>\n\n<p><em>Also, specifically <code>Guid</code> has the <a href=\"https://msdn.microsoft.com/en-us/library/system.guid.tryparse(v=vs.110).aspx\" rel=\"noreferrer\"><code>Guid.TryParse</code></a> method.</em></p>\n"
},
{
"answer_id": 39638025,
"author": "MakePeaceGreatAgain",
"author_id": 2528063,
"author_profile": "https://Stackoverflow.com/users/2528063",
"pm_score": 3,
"selected": false,
"text": "<p>So you´re repeating lots of code within every exception-switch? Sounds like extracting a method would be god idea, doesn´t it?</p>\n\n<p>So your code comes down to this:</p>\n\n<pre><code>MyClass instance;\ntry { instance = ... }\ncatch(Exception1 e) { Reset(instance); }\ncatch(Exception2 e) { Reset(instance); }\ncatch(Exception) { throw; }\n\nvoid Reset(MyClass instance) { /* reset the state of the instance */ }\n</code></pre>\n\n<p>I wonder why no-one noticed that code-duplication.</p>\n\n<p>From C#6 you furthermore have the <a href=\"https://stackoverflow.com/questions/4268223/c-sharp-exception-filter\">exception-filters</a> as already mentioned by others. So you can modify the code above to this:</p>\n\n<pre><code>try { ... }\ncatch(Exception e) when(e is Exception1 || e is Exception2)\n{ \n Reset(instance); \n}\n</code></pre>\n"
},
{
"answer_id": 43439006,
"author": "Trevor",
"author_id": 4826364,
"author_profile": "https://Stackoverflow.com/users/4826364",
"pm_score": 3,
"selected": false,
"text": "<p>Wanted to added my short answer to this already long thread. Something that hasn't been mentioned is the order of precedence of the catch statements, more specifically you need to be aware of the scope of each type of exception you are trying to catch.</p>\n\n<p>For example if you use a \"catch-all\" exception as <strong>Exception</strong> it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all <strong>Exception</strong> type at the bottom and this will be capture any exceptions that didn't cater for higher up in your try..catch block:</p>\n\n<pre><code> try\n {\n // do some work here\n }\n catch (WebException ex)\n {\n // catch a web excpetion\n }\n catch (ArgumentException ex)\n {\n // do some stuff\n }\n catch (Exception ex)\n {\n // you should really surface your errors but this is for example only\n throw new Exception(\"An error occurred: \" + ex.Message);\n }\n</code></pre>\n\n<p>I highly recommend folks review this MSDN document:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/z4c5tckx.aspx\" rel=\"noreferrer\">Exception Hierarchy</a></p>\n"
},
{
"answer_id": 47316654,
"author": "Jeffrey Rennie",
"author_id": 4987709,
"author_profile": "https://Stackoverflow.com/users/4987709",
"pm_score": 3,
"selected": false,
"text": "<p>This is a classic problem every C# developer faces eventually.</p>\n\n<p>Let me break your question into 2 questions. The first,</p>\n\n<p><strong>Can I catch multiple exceptions at once?</strong></p>\n\n<p>In short, no.</p>\n\n<p>Which leads to the next question,</p>\n\n<p><strong>How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?</strong></p>\n\n<p>Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:</p>\n\n<ol>\n<li>Initialize WebId to the fall-back value.</li>\n<li>Construct a new Guid in a temporary variable.</li>\n<li>Set WebId to the fully constructed temporary variable. Make this the final statement of the try{} block.</li>\n</ol>\n\n<p>So the code looks like:</p>\n\n<pre><code>try\n{\n WebId = Guid.Empty;\n Guid newGuid = new Guid(queryString[\"web\"]);\n // More initialization code goes here like \n // newGuid.x = y;\n WebId = newGuid;\n}\ncatch (FormatException) {}\ncatch (OverflowException) {}\n</code></pre>\n\n<p>If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.</p>\n\n<p>If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:</p>\n\n<pre><code>try\n{\n WebId = new Guid(queryString[\"web\"]);\n // More initialization code goes here.\n}\ncatch (FormatException) {\n Reset(WebId);\n}\ncatch (OverflowException) {\n Reset(WebId);\n}\n</code></pre>\n"
},
{
"answer_id": 48112962,
"author": "Fabian",
"author_id": 4226080,
"author_profile": "https://Stackoverflow.com/users/4226080",
"pm_score": 6,
"selected": false,
"text": "<p>With C# 7 <a href=\"https://stackoverflow.com/a/136038\">the answer from Michael Stum</a> can be improved while keeping the readability of a switch statement:</p>\n<pre><code>catch (Exception ex)\n{\n switch (ex)\n {\n case FormatException _:\n case OverflowException _:\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n}\n</code></pre>\n<p>Thanks to <a href=\"https://stackoverflow.com/users/361177/orace\">Orace</a> comment this can be simplified with C# 8 by omitting the discard variable:</p>\n<pre><code>catch (Exception ex)\n{\n switch (ex)\n {\n case FormatException:\n case OverflowException:\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n} \n</code></pre>\n<p>And with C# 8 as switch expression:</p>\n<pre><code>catch (Exception ex)\n{\n WebId = ex switch\n {\n _ when ex is FormatException || ex is OverflowException => Guid.Empty,\n _ => throw ex\n };\n}\n</code></pre>\n<p>As <a href=\"https://stackoverflow.com/users/7711481/nechemia-hoffmann\">Nechemia Hoffmann</a> pointed out. The latter example will cause a loss of the stacktrace. This can be prevented by using the extension method described by <a href=\"https://stackoverflow.com/a/57052791/4226080\">Jürgen Steinblock</a> to capture the stacktrace before throwing:</p>\n<pre><code>catch (Exception ex)\n{\n WebId = ex switch\n {\n _ when ex is FormatException || ex is OverflowException => Guid.Empty,\n _ => throw ex.Capture()\n };\n}\n\npublic static Exception Capture(this Exception ex)\n{\n ExceptionDispatchInfo.Capture(ex).Throw();\n return ex;\n}\n</code></pre>\n<p>Both styles can be simplified with the pattern matching enhancements of C# 9:</p>\n<pre><code>catch (Exception ex)\n{\n switch (ex)\n {\n case FormatException or OverflowException:\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n} \n\ncatch (Exception ex)\n{\n WebId = ex switch\n {\n _ when ex is FormatException or OverflowException => Guid.Empty,\n _ => throw ex.Capture()\n };\n}\n</code></pre>\n"
},
{
"answer_id": 48403612,
"author": "Żubrówka",
"author_id": 861926,
"author_profile": "https://Stackoverflow.com/users/861926",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe try to keep your code simple such as putting the common code in a method, as you would do in any other part of the code that is not inside a catch clause?</p>\n\n<p>E.g.:</p>\n\n<pre><code>try\n{\n // ...\n}\ncatch (FormatException)\n{\n DoSomething();\n}\ncatch (OverflowException)\n{\n DoSomething();\n}\n\n// ...\n\nprivate void DoSomething()\n{\n // ...\n}\n</code></pre>\n\n<p>Just how I would do it, trying to find the <em>simple is beautiful</em> pattern</p>\n"
},
{
"answer_id": 51286385,
"author": "Mat J",
"author_id": 219933,
"author_profile": "https://Stackoverflow.com/users/219933",
"pm_score": 7,
"selected": false,
"text": "<p>Exception filters are now available in c# 6+. You can do</p>\n\n<pre><code>try\n{\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (Exception ex) when(ex is FormatException || ex is OverflowException)\n{\n WebId = Guid.Empty;\n}\n</code></pre>\n\n<p>In C# 7.0+, you can combine this with pattern matching too</p>\n\n<pre><code>try\n{\n await Task.WaitAll(tasks);\n}\ncatch (Exception ex) when( ex is AggregateException ae &&\n ae.InnerExceptions.Count > tasks.Count/2)\n{\n //More than half of the tasks failed maybe..? \n}\n</code></pre>\n"
},
{
"answer_id": 53672256,
"author": "George",
"author_id": 5077953,
"author_profile": "https://Stackoverflow.com/users/5077953",
"pm_score": 1,
"selected": false,
"text": "<p>It is worth mentioning here. You can respond to the multiple combinations (Exception error and exception.message). </p>\n\n<p>I ran into a use case scenario when trying to cast control object in a datagrid, with either content as TextBox, TextBlock or CheckBox. In this case the returned Exception was the same, but the message varied.</p>\n\n<pre><code>try\n{\n //do something\n}\ncatch (Exception ex) when (ex.Message.Equals(\"the_error_message1_here\"))\n{\n//do whatever you like\n} \ncatch (Exception ex) when (ex.Message.Equals(\"the_error_message2_here\"))\n{\n//do whatever you like\n} \n</code></pre>\n"
},
{
"answer_id": 56327837,
"author": "Evgeny Gorbovoy",
"author_id": 2362847,
"author_profile": "https://Stackoverflow.com/users/2362847",
"pm_score": 0,
"selected": false,
"text": "<p>I want to suggest shortest answer (one more <strong>functional style</strong>):</p>\n\n<pre><code> Catch<FormatException, OverflowException>(() =>\n {\n WebId = new Guid(queryString[\"web\"]);\n },\n exception =>\n {\n WebId = Guid.Empty;\n });\n</code></pre>\n\n<p>For this you need to create several \"Catch\" method overloads, similar to System.Action:</p>\n\n<pre><code> [DebuggerNonUserCode]\n public static void Catch<TException1, TException2>(Action tryBlock,\n Action<Exception> catchBlock)\n {\n CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));\n }\n\n [DebuggerNonUserCode]\n public static void Catch<TException1, TException2, TException3>(Action tryBlock,\n Action<Exception> catchBlock)\n {\n CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));\n }\n</code></pre>\n\n<p>and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).</p>\n\n<p>And CatchMany implementation:</p>\n\n<pre><code> [DebuggerNonUserCode]\n public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,\n params Type[] exceptionTypes)\n {\n try\n {\n tryBlock();\n }\n catch (Exception exception)\n {\n if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);\n else throw;\n }\n }\n</code></pre>\n\n<p>p.s. I haven't put null checks for code simplicity, consider to add parameter validations.</p>\n\n<p>p.s.2 \nIf you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters. </p>\n"
},
{
"answer_id": 65602786,
"author": "Nechemia Hoffmann",
"author_id": 7711481,
"author_profile": "https://Stackoverflow.com/users/7711481",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Update for C# 9</strong></p>\n<p>Using the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements\" rel=\"noreferrer\">new pattern matching enhancements</a> made in C# 9, you can shorten the expression in the exception filter. Now, catching multiple exceptions is a simple is this:</p>\n<pre><code>try\n{\n WebId = new Guid(queryString["web"]);\n}\ncatch (Exception e) when (e is FormatException or OverflowException)\n{\n WebId = Guid.Empty;\n}\n</code></pre>\n"
},
{
"answer_id": 70051532,
"author": "Saleem Kalro",
"author_id": 4059234,
"author_profile": "https://Stackoverflow.com/users/4059234",
"pm_score": -1,
"selected": false,
"text": "<pre><code> try\n {\n WebId = new Guid(queryString["web"]);\n }\n catch (Exception ex)\n {\n string ExpTyp = ex.GetType().Name;\n if (ExpTyp == "FormatException")\n {\n WebId = Guid.Empty;\n }\n else if (ExpTyp == "OverflowException")\n {\n WebId = Guid.Empty;\n }\n }\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
| It is discouraged to simply catch `System.Exception`. Instead, only the "known" exceptions should be caught.
Now, this sometimes leads to unnecessary repetitive code, for example:
```
try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
```
I wonder: Is there a way to catch both exceptions and only call the `WebId = Guid.Empty` call once?
The given example is rather simple, as it's only a [`GUID`](http://en.wikipedia.org/wiki/Globally_unique_identifier). But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the `object`. However, if there is an unexpected exception, I still want to throw that higher. | Catch `System.Exception` and switch on the types
```
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
throw;
}
``` |
136,050 | <p>Is there a way to prevent VS2008 creating browse info file files for C++ projects.<br>
I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.</p>
<p>EDIT - it's also needed for go to declaration/definition</p>
| [
{
"answer_id": 136075,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 3,
"selected": false,
"text": "<p>In the project properties, you will find the browse information under:</p>\n\n<p>Configuration Properties -> C/C++ -> Browse Information</p>\n\n<p>Just tell it not to generate browse information. All it is used for is quickly browsing between code components (like using 'Go to Definition') and so forth. I personally like being able to quickly jump between the components, but if it is adding unnecessary time to your compile don't worry about turning it off.</p>\n"
},
{
"answer_id": 136144,
"author": "Leandro Oliveira",
"author_id": 16610,
"author_profile": "https://Stackoverflow.com/users/16610",
"pm_score": 2,
"selected": false,
"text": "<p>Try creating a folder with the same name of the ncb file (you'll have to delete the file, of course). I used this trick in the past to prevent intellisense from locking VS2005. You'll lose intellisense, though.</p>\n"
},
{
"answer_id": 1910905,
"author": "Adisak",
"author_id": 14904,
"author_profile": "https://Stackoverflow.com/users/14904",
"pm_score": 3,
"selected": true,
"text": "<p>There is a registry key for this as well: <code>[HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\9.0\\Languages\\Language Services\\C/C++]</code></p>\n\n<p>Intellisense ON</p>\n\n<pre><code>\"IntellisenseOptions\"=dword:00000000\n</code></pre>\n\n<p>Intellisense OFF</p>\n\n<pre><code>\"IntellisenseOptions\"=dword:00000007\n</code></pre>\n\n<p>Intellisense ON - NO Background UPDATE</p>\n\n<pre><code>\"IntellisenseOptions\"=dword:00000005\n</code></pre>\n\n<p>More flags are available and you can <a href=\"http://blogs.msdn.com/vcblog/archive/2007/11/19/controlling-intellisense-through-macros.aspx\" rel=\"nofollow noreferrer\">Control Intellisense through Macros</a> as well.</p>\n\n<pre><code>ISENSE_NORMAL = 0 'normal (Intellisense On)\nISENSE_NOBG = &H1 'no bg parsing (Intellisense Updating Off - although NCB file will be opened r/w and repersisted at shutdown)\nISENSE_NOQUERY = &H2 'no queries (don't run any ISense queries)\nISENSE_NCBRO = &H4 'no saving of NCB (must be set before opening NCB, doesn't affect updating or queries, just persisting of NCB)\nISENSE_OFF = &H7 \n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10897/"
]
| Is there a way to prevent VS2008 creating browse info file files for C++ projects.
I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.
EDIT - it's also needed for go to declaration/definition | There is a registry key for this as well: `[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]`
Intellisense ON
```
"IntellisenseOptions"=dword:00000000
```
Intellisense OFF
```
"IntellisenseOptions"=dword:00000007
```
Intellisense ON - NO Background UPDATE
```
"IntellisenseOptions"=dword:00000005
```
More flags are available and you can [Control Intellisense through Macros](http://blogs.msdn.com/vcblog/archive/2007/11/19/controlling-intellisense-through-macros.aspx) as well.
```
ISENSE_NORMAL = 0 'normal (Intellisense On)
ISENSE_NOBG = &H1 'no bg parsing (Intellisense Updating Off - although NCB file will be opened r/w and repersisted at shutdown)
ISENSE_NOQUERY = &H2 'no queries (don't run any ISense queries)
ISENSE_NCBRO = &H4 'no saving of NCB (must be set before opening NCB, doesn't affect updating or queries, just persisting of NCB)
ISENSE_OFF = &H7
``` |
136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod" rel="noreferrer"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod" rel="noreferrer"><code>@classmethod</code></a>?</p>
| [
{
"answer_id": 136138,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 10,
"selected": false,
"text": "<p>A <strong>staticmethod</strong> is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.</p>\n\n<p>A <strong>classmethod</strong>, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how <code>dict.fromkeys()</code>, a classmethod, returns an instance of the subclass when called on a subclass:</p>\n\n<pre><code>>>> class DictSubclass(dict):\n... def __repr__(self):\n... return \"DictSubclass\"\n... \n>>> dict.fromkeys(\"abc\")\n{'a': None, 'c': None, 'b': None}\n>>> DictSubclass.fromkeys(\"abc\")\nDictSubclass\n>>> \n</code></pre>\n"
},
{
"answer_id": 136149,
"author": "Terence Simpson",
"author_id": 22395,
"author_profile": "https://Stackoverflow.com/users/22395",
"pm_score": 8,
"selected": false,
"text": "<p>Basically <code>@classmethod</code> makes a method whose first argument is the class it's called from (rather than the class instance), <code>@staticmethod</code> does not have any implicit arguments.</p>\n"
},
{
"answer_id": 136246,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 5,
"selected": false,
"text": "<p><code>@staticmethod</code> just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:</p>\n\n<pre><code>>>> class C(object):\n... pass\n... \n>>> def f():\n... pass\n... \n>>> staticmethod(f).__get__(None, C)\n<function f at 0x5c1cf0>\n>>> classmethod(f).__get__(None, C)\n<bound method type.f of <class '__main__.C'>>\n</code></pre>\n\n<p>As a matter of fact, <code>classmethod</code> has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:</p>\n\n<pre><code>>>> class CMeta(type):\n... def foo(cls):\n... print cls\n... \n>>> class C(object):\n... __metaclass__ = CMeta\n... \n>>> C.foo()\n<class '__main__.C'>\n</code></pre>\n"
},
{
"answer_id": 1669457,
"author": "Tom Neyland",
"author_id": 64301,
"author_profile": "https://Stackoverflow.com/users/64301",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://rapd.wordpress.com/2008/07/02/python-staticmethod-vs-classmethod/\" rel=\"noreferrer\">Here</a> is a short article on this question</p>\n<blockquote>\n<p>@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.</p>\n<p>@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).</p>\n</blockquote>\n"
},
{
"answer_id": 1669524,
"author": "unutbu",
"author_id": 190597,
"author_profile": "https://Stackoverflow.com/users/190597",
"pm_score": 13,
"selected": true,
"text": "<p>Maybe a bit of example code will help: Notice the difference in the call signatures of <code>foo</code>, <code>class_foo</code> and <code>static_foo</code>:</p>\n<pre><code>class A(object):\n def foo(self, x):\n print(f"executing foo({self}, {x})")\n\n @classmethod\n def class_foo(cls, x):\n print(f"executing class_foo({cls}, {x})")\n\n @staticmethod\n def static_foo(x):\n print(f"executing static_foo({x})")\n\na = A()\n</code></pre>\n<p>Below is the usual way an object instance calls a method. The object instance, <code>a</code>, is implicitly passed as the first argument.</p>\n<pre><code>a.foo(1)\n# executing foo(<__main__.A object at 0xb7dbef0c>, 1)\n</code></pre>\n<hr />\n<p><strong>With classmethods</strong>, the class of the object instance is implicitly passed as the first argument instead of <code>self</code>.</p>\n<pre><code>a.class_foo(1)\n# executing class_foo(<class '__main__.A'>, 1)\n</code></pre>\n<p>You can also call <code>class_foo</code> using the class. In fact, if you define something to be\na classmethod, it is probably because you intend to call it from the class rather than from a class instance. <code>A.foo(1)</code> would have raised a TypeError, but <code>A.class_foo(1)</code> works just fine:</p>\n<pre><code>A.class_foo(1)\n# executing class_foo(<class '__main__.A'>, 1)\n</code></pre>\n<p>One use people have found for class methods is to create <a href=\"https://stackoverflow.com/a/1950927/190597\">inheritable alternative constructors</a>.</p>\n<hr />\n<p><strong>With staticmethods</strong>, neither <code>self</code> (the object instance) nor <code>cls</code> (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:</p>\n<pre><code>a.static_foo(1)\n# executing static_foo(1)\n\nA.static_foo('hi')\n# executing static_foo(hi)\n</code></pre>\n<p>Staticmethods are used to group functions which have some logical connection with a class to the class.</p>\n<hr />\n<p><code>foo</code> is just a function, but when you call <code>a.foo</code> you don't just get the function,\nyou get a "partially applied" version of the function with the object instance <code>a</code> bound as the first argument to the function. <code>foo</code> expects 2 arguments, while <code>a.foo</code> only expects 1 argument.</p>\n<p><code>a</code> is bound to <code>foo</code>. That is what is meant by the term "bound" below:</p>\n<pre><code>print(a.foo)\n# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>\n</code></pre>\n<p>With <code>a.class_foo</code>, <code>a</code> is not bound to <code>class_foo</code>, rather the class <code>A</code> is bound to <code>class_foo</code>.</p>\n<pre><code>print(a.class_foo)\n# <bound method type.class_foo of <class '__main__.A'>>\n</code></pre>\n<p>Here, with a staticmethod, even though it is a method, <code>a.static_foo</code> just returns\na good 'ole function with no arguments bound. <code>static_foo</code> expects 1 argument, and\n<code>a.static_foo</code> expects 1 argument too.</p>\n<pre><code>print(a.static_foo)\n# <function static_foo at 0xb7d479cc>\n</code></pre>\n<p>And of course the same thing happens when you call <code>static_foo</code> with the class <code>A</code> instead.</p>\n<pre><code>print(A.static_foo)\n# <function static_foo at 0xb7d479cc>\n</code></pre>\n"
},
{
"answer_id": 1669579,
"author": "Chris B.",
"author_id": 45176,
"author_profile": "https://Stackoverflow.com/users/45176",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Official python docs:</strong></p>\n\n<p><a href=\"http://docs.python.org/library/functions.html#classmethod\" rel=\"noreferrer\">@classmethod</a></p>\n\n<blockquote>\n <p>A class method receives the class as\n implicit first argument, just like an\n instance method receives the instance.\n To declare a class method, use this\n idiom:</p>\n\n<pre><code>class C:\n @classmethod\n def f(cls, arg1, arg2, ...): ... \n</code></pre>\n \n <p>The <code>@classmethod</code> form is a function\n <a href=\"http://docs.python.org/2/glossary.html#term-decorator\" rel=\"noreferrer\"><em>decorator</em></a> – see the description of\n function definitions in <a href=\"http://docs.python.org/2/reference/compound_stmts.html#function\" rel=\"noreferrer\"><em>Function\n definitions</em></a> for details.</p>\n \n <p>It can be called either on the class\n (such as <code>C.f()</code>) or on an instance\n (such as <code>C().f()</code>). The instance is\n ignored except for its class. If a\n class method is called for a derived\n class, the derived class object is\n passed as the implied first argument.</p>\n \n <p>Class methods are different than C++\n or Java static methods. If you want\n those, see <a href=\"http://docs.python.org/2/library/functions.html#staticmethod\" rel=\"noreferrer\"><code>staticmethod()</code></a> in this\n section.</p>\n</blockquote>\n\n<p><a href=\"http://docs.python.org/library/functions.html#staticmethod\" rel=\"noreferrer\">@staticmethod</a></p>\n\n<blockquote>\n <p>A static method does not receive an\n implicit first argument. To declare a\n static method, use this idiom:</p>\n\n<pre><code>class C:\n @staticmethod\n def f(arg1, arg2, ...): ... \n</code></pre>\n \n <p>The <code>@staticmethod</code> form is a function\n <a href=\"http://docs.python.org/2/glossary.html#term-decorator\" rel=\"noreferrer\"><em>decorator</em></a> – see the description of\n function definitions in <a href=\"http://docs.python.org/2/reference/compound_stmts.html#function\" rel=\"noreferrer\"><em>Function\n definitions</em></a> for details.</p>\n \n <p>It can be called either on the class\n (such as <code>C.f()</code>) or on an instance\n (such as <code>C().f()</code>). The instance is\n ignored except for its class.</p>\n \n <p>Static methods in Python are similar\n to those found in Java or C++. For a\n more advanced concept, see\n <a href=\"http://docs.python.org/2/library/functions.html#classmethod\" rel=\"noreferrer\"><code>classmethod()</code></a> in this section.</p>\n</blockquote>\n"
},
{
"answer_id": 9428384,
"author": "Jens Timmerman",
"author_id": 869482,
"author_profile": "https://Stackoverflow.com/users/869482",
"pm_score": 5,
"selected": false,
"text": "<p>@decorators were added in python 2.4 If you're using python < 2.4 you can use the classmethod() and staticmethod() function.</p>\n\n<p>For example, if you want to create a factory method (A function returning an instance of a different implementation of a class depending on what argument it gets) you can do something like:</p>\n\n<pre><code>class Cluster(object):\n\n def _is_cluster_for(cls, name):\n \"\"\"\n see if this class is the cluster with this name\n this is a classmethod\n \"\"\" \n return cls.__name__ == name\n _is_cluster_for = classmethod(_is_cluster_for)\n\n #static method\n def getCluster(name):\n \"\"\"\n static factory method, should be in Cluster class\n returns a cluster object for the given name\n \"\"\"\n for cls in Cluster.__subclasses__():\n if cls._is_cluster_for(name):\n return cls()\n getCluster = staticmethod(getCluster)\n</code></pre>\n\n<p>Also observe that this is a good example for using a classmethod and a static method,\nThe static method clearly belongs to the class, since it uses the class Cluster internally.\nThe classmethod only needs information about the class, and no instance of the object.</p>\n\n<p>Another benefit of making the <code>_is_cluster_for</code> method a classmethod is so a subclass can decide to change it's implementation, maybe because it is pretty generic and can handle more than one type of cluster, so just checking the name of the class would not be enough.</p>\n"
},
{
"answer_id": 13920259,
"author": "Cathal Garvey",
"author_id": 1910875,
"author_profile": "https://Stackoverflow.com/users/1910875",
"pm_score": -1,
"selected": false,
"text": "<p>A quick hack-up ofotherwise identical methods in iPython reveals that <code>@staticmethod</code> yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through <code>staticmethod()</code> during compilation (which happens prior to any code execution when you run a script).</p>\n\n<p>For the sake of code readability I'd avoid <code>@staticmethod</code> unless your method will be used for loads of work, where the nanoseconds count.</p>\n"
},
{
"answer_id": 28117800,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n<h2>What is the difference between @staticmethod and @classmethod in Python?</h2>\n</blockquote>\n<p>You may have seen Python code like this pseudocode, which demonstrates the signatures of the various method types and provides a docstring to explain each:</p>\n<pre><code>class Foo(object):\n\n def a_normal_instance_method(self, arg_1, kwarg_2=None):\n '''\n Return a value that is a function of the instance with its\n attributes, and other arguments such as arg_1 and kwarg2\n '''\n\n @staticmethod\n def a_static_method(arg_0):\n '''\n Return a value that is a function of arg_0. It does not know the \n instance or class it is called from.\n '''\n\n @classmethod\n def a_class_method(cls, arg1):\n '''\n Return a value that is a function of the class and other arguments.\n respects subclassing, it is called with the class it is called from.\n '''\n</code></pre>\n<h1>The Normal Instance Method</h1>\n<p>First I'll explain <code>a_normal_instance_method</code>. This is precisely called an "<strong>instance method</strong>". When an instance method is used, it is used as a partial function (as opposed to a total function, defined for all values when viewed in source code) that is, when used, the first of the arguments is predefined as the instance of the object, with all of its given attributes. It has the instance of the object bound to it, and it must be called from an instance of the object. Typically, it will access various attributes of the instance.</p>\n<p>For example, this is an instance of a string:</p>\n<pre><code>', '\n</code></pre>\n<p>if we use the instance method, <code>join</code> on this string, to join another iterable,\nit quite obviously is a function of the instance, in addition to being a function of the iterable list, <code>['a', 'b', 'c']</code>:</p>\n<pre><code>>>> ', '.join(['a', 'b', 'c'])\n'a, b, c'\n</code></pre>\n<h3>Bound methods</h3>\n<p>Instance methods can be bound via a dotted lookup for use later.</p>\n<p>For example, this binds the <code>str.join</code> method to the <code>':'</code> instance:</p>\n<pre><code>>>> join_with_colons = ':'.join \n</code></pre>\n<p>And later we can use this as a function that already has the first argument bound to it. In this way, it works like a partial function on the instance:</p>\n<pre><code>>>> join_with_colons('abcde')\n'a:b:c:d:e'\n>>> join_with_colons(['FF', 'FF', 'FF', 'FF', 'FF', 'FF'])\n'FF:FF:FF:FF:FF:FF'\n</code></pre>\n<h1>Static Method</h1>\n<p>The static method does <em>not</em> take the instance as an argument.</p>\n<p>It is very similar to a module level function.</p>\n<p>However, a module level function must live in the module and be specially imported to other places where it is used.</p>\n<p>If it is attached to the object, however, it will follow the object conveniently through importing and inheritance as well.</p>\n<p>An example of a static method is <code>str.maketrans</code>, moved from the <code>string</code> module in Python 3. It makes a translation table suitable for consumption by <code>str.translate</code>. It does seem rather silly when used from an instance of a string, as demonstrated below, but importing the function from the <code>string</code> module is rather clumsy, and it's nice to be able to call it from the class, as in <code>str.maketrans</code></p>\n<pre><code># demonstrate same function whether called from instance or not:\n>>> ', '.maketrans('ABC', 'abc')\n{65: 97, 66: 98, 67: 99}\n>>> str.maketrans('ABC', 'abc')\n{65: 97, 66: 98, 67: 99}\n</code></pre>\n<p>In python 2, you have to import this function from the increasingly less useful string module:</p>\n<pre><code>>>> import string\n>>> 'ABCDEFG'.translate(string.maketrans('ABC', 'abc'))\n'abcDEFG'\n</code></pre>\n<h1>Class Method</h1>\n<p>A class method is a similar to an instance method in that it takes an implicit first argument, but instead of taking the instance, it takes the class. Frequently these are used as alternative constructors for better semantic usage and it will support inheritance.</p>\n<p>The most canonical example of a builtin classmethod is <code>dict.fromkeys</code>. It is used as an alternative constructor of dict, (well suited for when you know what your keys are and want a default value for them.)</p>\n<pre><code>>>> dict.fromkeys(['a', 'b', 'c'])\n{'c': None, 'b': None, 'a': None}\n</code></pre>\n<p>When we subclass dict, we can use the same constructor, which creates an instance of the subclass.</p>\n<pre><code>>>> class MyDict(dict): 'A dict subclass, use to demo classmethods'\n>>> md = MyDict.fromkeys(['a', 'b', 'c'])\n>>> md\n{'a': None, 'c': None, 'b': None}\n>>> type(md)\n<class '__main__.MyDict'>\n</code></pre>\n<p>See the <a href=\"https://github.com/pydata/pandas/blob/master/pandas/core/frame.py\" rel=\"noreferrer\">pandas source code</a> for other similar examples of alternative constructors, and see also the official Python documentation on <a href=\"https://docs.python.org/library/functions.html#classmethod\" rel=\"noreferrer\"><code>classmethod</code></a> and <a href=\"https://docs.python.org/library/functions.html#staticmethod\" rel=\"noreferrer\"><code>staticmethod</code></a>.</p>\n"
},
{
"answer_id": 30329887,
"author": "Nathan Tregillus",
"author_id": 51847,
"author_profile": "https://Stackoverflow.com/users/51847",
"pm_score": 6,
"selected": false,
"text": "<p>I think a better question is "When would you use <code>@classmethod</code> vs <code>@staticmethod</code>?"</p>\n<p><code>@classmethod</code> allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.</p>\n<p><code>@staticmethod</code> provides marginal performance gains, but I have yet to see a productive use of a static method within a class that couldn't be achieved as a standalone function outside the class.</p>\n"
},
{
"answer_id": 33727452,
"author": "zangw",
"author_id": 3011380,
"author_profile": "https://Stackoverflow.com/users/3011380",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods\" rel=\"noreferrer\">The definitive guide on how to use static, class or abstract methods in Python</a> is one good link for this topic, and summary it as following.</p>\n\n<p><strong><code>@staticmethod</code></strong> function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.</p>\n\n<ul>\n<li>Python does not have to instantiate a bound-method for object.</li>\n<li>It eases the readability of the code, and it does not depend on the state of object itself;</li>\n</ul>\n\n<p><strong><code>@classmethod</code></strong> function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for <code>@classmethod</code> function must always be <em>cls</em> (class).</p>\n\n<ul>\n<li><em>Factory methods</em>, that are used to create an instance for a class using for example some sort of pre-processing.</li>\n<li><em>Static methods calling static methods</em>: if you split a static methods in several static methods, you shouldn't hard-code the class name but use class methods</li>\n</ul>\n"
},
{
"answer_id": 36798076,
"author": "Du D.",
"author_id": 1302259,
"author_profile": "https://Stackoverflow.com/users/1302259",
"pm_score": 7,
"selected": false,
"text": "<p>To decide whether to use <a href=\"https://docs.python.org/3/library/functions.html?highlight=staticmethod#staticmethod\" rel=\"noreferrer\">@staticmethod</a> or <a href=\"https://docs.python.org/3.5/library/functions.html?highlight=classmethod#classmethod\" rel=\"noreferrer\">@classmethod</a> you have to look inside your method. <strong>If your method accesses other variables/methods in your class then use @classmethod</strong>. On the other hand, if your method does not touches any other parts of the class then use @staticmethod.</p>\n<pre><code>class Apple:\n\n _counter = 0\n\n @staticmethod\n def about_apple():\n print('Apple is good for you.')\n\n # note you can still access other member of the class\n # but you have to use the class instance \n # which is not very nice, because you have repeat yourself\n # \n # For example:\n # @staticmethod\n # print('Number of apples have been juiced: %s' % Apple._counter)\n #\n # @classmethod\n # print('Number of apples have been juiced: %s' % cls._counter)\n #\n # @classmethod is especially useful when you move your function to another class,\n # you don't have to rename the referenced class \n\n @classmethod\n def make_apple_juice(cls, number_of_apples):\n print('Making juice:')\n for i in range(number_of_apples):\n cls._juice_this(i)\n\n @classmethod\n def _juice_this(cls, apple):\n print('Juicing apple %d...' % apple)\n cls._counter += 1\n</code></pre>\n"
},
{
"answer_id": 39589894,
"author": "Rizwan Mumtaz",
"author_id": 1224003,
"author_profile": "https://Stackoverflow.com/users/1224003",
"pm_score": 4,
"selected": false,
"text": "<p>I will try to explain the basic difference using an example.</p>\n\n<pre><code>class A(object):\n x = 0\n\n def say_hi(self):\n pass\n\n @staticmethod\n def say_hi_static():\n pass\n\n @classmethod\n def say_hi_class(cls):\n pass\n\n def run_self(self):\n self.x += 1\n print self.x # outputs 1\n self.say_hi()\n self.say_hi_static()\n self.say_hi_class()\n\n @staticmethod\n def run_static():\n print A.x # outputs 0\n # A.say_hi() # wrong\n A.say_hi_static()\n A.say_hi_class()\n\n @classmethod\n def run_class(cls):\n print cls.x # outputs 0\n # cls.say_hi() # wrong\n cls.say_hi_static()\n cls.say_hi_class()\n</code></pre>\n\n<p>1 - we can directly call static and classmethods without initializing</p>\n\n<pre><code># A.run_self() # wrong\nA.run_static()\nA.run_class()\n</code></pre>\n\n<p>2- Static method cannot call self method but can call other static and classmethod</p>\n\n<p>3- Static method belong to class and will not use object at all.</p>\n\n<p>4- Class method are not bound to an object but to a class.</p>\n"
},
{
"answer_id": 39776104,
"author": "Adam Parkin",
"author_id": 808804,
"author_profile": "https://Stackoverflow.com/users/808804",
"pm_score": 5,
"selected": false,
"text": "<p>Another consideration with respect to staticmethod vs classmethod comes up with inheritance. Say you have the following class:</p>\n<pre><code>class Foo(object):\n @staticmethod\n def bar():\n return "In Foo"\n</code></pre>\n<p>And you then want to override <code>bar()</code> in a child class:</p>\n<pre><code>class Foo2(Foo):\n @staticmethod\n def bar():\n return "In Foo2"\n</code></pre>\n<p>This works, but note that now the <code>bar()</code> implementation in the child class (<code>Foo2</code>) can no longer take advantage of anything specific to that class. For example, say <code>Foo2</code> had a method called <code>magic()</code> that you want to use in the <code>Foo2</code> implementation of <code>bar()</code>:</p>\n<pre><code>class Foo2(Foo):\n @staticmethod\n def bar():\n return "In Foo2"\n @staticmethod\n def magic():\n return "Something useful you'd like to use in bar, but now can't" \n</code></pre>\n<p>The workaround here would be to call <code>Foo2.magic()</code> in <code>bar()</code>, but then you're repeating yourself (if the name of <code>Foo2</code> changes, you'll have to remember to update that <code>bar()</code> method).</p>\n<p>To me, this is a slight violation of the <a href=\"https://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"noreferrer\">open/closed principle</a>, since a decision made in <code>Foo</code> is impacting your ability to refactor common code in a derived class (ie it's less open to extension). If <code>bar()</code> were a <code>classmethod</code> we'd be fine:</p>\n<pre><code>class Foo(object):\n @classmethod\n def bar(cls):\n return "In Foo"\n\nclass Foo2(Foo):\n @classmethod\n def bar(cls):\n return "In Foo2 " + cls.magic()\n @classmethod\n def magic(cls):\n return "MAGIC"\n\nprint Foo2().bar()\n</code></pre>\n<p>Gives: <code>In Foo2 MAGIC</code></p>\n<p>Also: historical note: Guido Van Rossum (Python's creator) once referred to <code>staticmethod</code>'s as "an accident": <a href=\"https://mail.python.org/pipermail/python-ideas/2012-May/014969.html\" rel=\"noreferrer\">https://mail.python.org/pipermail/python-ideas/2012-May/014969.html</a></p>\n<blockquote>\n<p>we all know how limited static methods are. (They're basically an accident -- back in the Python 2.2 days when I was inventing new-style classes and descriptors, I meant to implement class methods but at first I didn't understand them and accidentally implemented static methods first. Then it was too late to remove them and only provide class methods.</p>\n</blockquote>\n<p>Also: <a href=\"https://mail.python.org/pipermail/python-ideas/2016-July/041189.html\" rel=\"noreferrer\">https://mail.python.org/pipermail/python-ideas/2016-July/041189.html</a></p>\n<blockquote>\n<p>Honestly, staticmethod was something of a mistake -- I was trying to do something like Java class methods but once it was released I found what was really needed was classmethod. But it was too late to get rid of staticmethod.</p>\n</blockquote>\n"
},
{
"answer_id": 39829692,
"author": "Laxmi",
"author_id": 6755093,
"author_profile": "https://Stackoverflow.com/users/6755093",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Static Methods:</strong></p>\n\n<ul>\n<li>Simple functions with no self argument. </li>\n<li>Work on class attributes; not on instance attributes.</li>\n<li>Can be called through both class and instance.</li>\n<li>The built-in function staticmethod()is used to create them.</li>\n</ul>\n\n<p><strong>Benefits of Static Methods:</strong></p>\n\n<ul>\n<li>It localizes the function name in the classscope</li>\n<li>It moves the function code closer to where it is used</li>\n<li><p>More convenient to import versus module-level functions since each method does not have to be specially imported</p>\n\n<pre><code>@staticmethod\ndef some_static_method(*args, **kwds):\n pass\n</code></pre></li>\n</ul>\n\n<p><strong>Class Methods:</strong></p>\n\n<ul>\n<li>Functions that have first argument as classname.</li>\n<li>Can be called through both class and instance.</li>\n<li><p>These are created with classmethod in-built function.</p>\n\n<pre><code> @classmethod\n def some_class_method(cls, *args, **kwds):\n pass\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 46327819,
"author": "vijay",
"author_id": 7532407,
"author_profile": "https://Stackoverflow.com/users/7532407",
"pm_score": 3,
"selected": false,
"text": "<p>@classmethod : can be used to create a shared global access to all the instances created of that class..... like updating a record by multiple users....\nI particulary found it use ful when creating singletons as well..:)</p>\n\n<p>@static method: has nothing to do with the class or instance being associated with ...but for readability can use static method</p>\n"
},
{
"answer_id": 46664125,
"author": "Gaurang Shah",
"author_id": 2504762,
"author_profile": "https://Stackoverflow.com/users/2504762",
"pm_score": 6,
"selected": false,
"text": "<p>I started learning programming language with C++ and then Java and then Python and so this question bothered me a lot as well, until I understood the simple usage of each. </p>\n\n<p><strong>Class Method:</strong> Python unlike Java and C++ doesn't have constructor overloading. And so to achieve this you could use <code>classmethod</code>. Following example will explain this </p>\n\n<p>Let's consider we have a <code>Person</code> class which takes two arguments <code>first_name</code> and <code>last_name</code> and creates the instance of <code>Person</code>. </p>\n\n<pre><code>class Person(object):\n\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n</code></pre>\n\n<p>Now, if the requirement comes where you need to create a class using a single name only, just a <code>first_name</code>, you <strong>can't</strong> do something like this in Python. </p>\n\n<p>This will give you an error when you will try to create an object (instance).</p>\n\n<pre><code>class Person(object):\n\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n def __init__(self, first_name):\n self.first_name = first_name\n</code></pre>\n\n<p>However, you could achieve the same thing using <code>@classmethod</code> as mentioned below </p>\n\n<pre><code>class Person(object):\n\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n @classmethod\n def get_person(cls, first_name):\n return cls(first_name, \"\")\n</code></pre>\n\n<p><strong>Static Method:</strong> This is rather simple, it's not bound to instance or class and you can simply call that using class name. </p>\n\n<p>So let's say in above example you need a validation that <code>first_name</code> should not exceed 20 characters, you can simply do this. </p>\n\n<pre><code>@staticmethod \ndef validate_name(name):\n return len(name) <= 20\n</code></pre>\n\n<p>and you could simply call using <code>class name</code></p>\n\n<pre><code>Person.validate_name(\"Gaurang Shah\")\n</code></pre>\n"
},
{
"answer_id": 47591541,
"author": "Tushar Vazirani",
"author_id": 2695804,
"author_profile": "https://Stackoverflow.com/users/2695804",
"pm_score": 3,
"selected": false,
"text": "<p>Class methods, as the name suggests, are used to make changes to classes and not the objects. To make changes to classes, they will modify the class attributes(not object attributes), since that is how you update classes.\nThis is the reason that class methods take the class(conventionally denoted by 'cls') as the first argument.</p>\n\n<pre><code>class A(object):\n m=54\n\n @classmethod\n def class_method(cls):\n print \"m is %d\" % cls.m\n</code></pre>\n\n<p>Static methods on the other hand, are used to perform functionalities that are not bound to the class i.e. they will not read or write class variables. Hence, static methods do not take classes as arguments. They are used so that classes can perform functionalities that are not directly related to the purpose of the class.</p>\n\n<pre><code>class X(object):\n m=54 #will not be referenced\n\n @staticmethod\n def static_method():\n print \"Referencing/calling a variable or function outside this class. E.g. Some global variable/function.\"\n</code></pre>\n"
},
{
"answer_id": 47769396,
"author": "AbstProcDo",
"author_id": 7301792,
"author_profile": "https://Stackoverflow.com/users/7301792",
"pm_score": 2,
"selected": false,
"text": "<p>Analyze @staticmethod <strong>literally</strong> providing different insights.</p>\n\n<p>A normal method of a class is an implicit <strong>dynamic</strong> method which takes the instance as first argument.<br>\nIn contrast, a staticmethod does not take the instance as first argument, so is called <strong>'static'</strong>.</p>\n\n<p>A staticmethod is indeed such a normal function the same as those outside a class definition.<br>\nIt is luckily grouped into the class just in order to stand closer where it is applied, or you might scroll around to find it.</p>\n"
},
{
"answer_id": 48250384,
"author": "Selva",
"author_id": 2604954,
"author_profile": "https://Stackoverflow.com/users/2604954",
"pm_score": 5,
"selected": false,
"text": "<p>Let me tell the similarity between a method decorated with @classmethod vs @staticmethod first.</p>\n\n<p><strong>Similarity:</strong> Both of them can be called on the <em>Class</em> itself, rather than just the <em>instance</em> of the class. So, both of them in a sense are <em>Class's methods</em>. </p>\n\n<p><strong>Difference:</strong> A classmethod will receive the class itself as the first argument, while a staticmethod does not.</p>\n\n<p>So a static method is, in a sense, not bound to the Class itself and is just hanging in there just because it may have a related functionality. </p>\n\n<pre><code>>>> class Klaus:\n @classmethod\n def classmthd(*args):\n return args\n\n @staticmethod\n def staticmthd(*args):\n return args\n\n# 1. Call classmethod without any arg\n>>> Klaus.classmthd() \n(__main__.Klaus,) # the class gets passed as the first argument\n\n# 2. Call classmethod with 1 arg\n>>> Klaus.classmthd('chumma')\n(__main__.Klaus, 'chumma')\n\n# 3. Call staticmethod without any arg\n>>> Klaus.staticmthd() \n()\n\n# 4. Call staticmethod with 1 arg\n>>> Klaus.staticmthd('chumma')\n('chumma',)\n</code></pre>\n"
},
{
"answer_id": 51015649,
"author": "Michael Swartz",
"author_id": 1476365,
"author_profile": "https://Stackoverflow.com/users/1476365",
"pm_score": 3,
"selected": false,
"text": "<p>My contribution demonstrates the difference amongst <code>@classmethod</code>, <code>@staticmethod</code>, and instance methods, including how an instance can indirectly call a <code>@staticmethod</code>. But instead of indirectly calling a <code>@staticmethod</code> from an instance, making it private may be more \"pythonic.\" Getting something from a private method isn't demonstrated here but it's basically the same concept.</p>\n\n<pre><code>#!python3\n\nfrom os import system\nsystem('cls')\n# % % % % % % % % % % % % % % % % % % % %\n\nclass DemoClass(object):\n # instance methods need a class instance and\n # can access the instance through 'self'\n def instance_method_1(self):\n return 'called from inside the instance_method_1()'\n\n def instance_method_2(self):\n # an instance outside the class indirectly calls the static_method\n return self.static_method() + ' via instance_method_2()'\n\n # class methods don't need a class instance, they can't access the\n # instance (self) but they have access to the class itself via 'cls'\n @classmethod\n def class_method(cls):\n return 'called from inside the class_method()'\n\n # static methods don't have access to 'cls' or 'self', they work like\n # regular functions but belong to the class' namespace\n @staticmethod\n def static_method():\n return 'called from inside the static_method()'\n# % % % % % % % % % % % % % % % % % % % %\n\n# works even if the class hasn't been instantiated\nprint(DemoClass.class_method() + '\\n')\n''' called from inside the class_method() '''\n\n# works even if the class hasn't been instantiated\nprint(DemoClass.static_method() + '\\n')\n''' called from inside the static_method() '''\n# % % % % % % % % % % % % % % % % % % % %\n\n# >>>>> all methods types can be called on a class instance <<<<<\n# instantiate the class\ndemoclassObj = DemoClass()\n\n# call instance_method_1()\nprint(democlassObj.instance_method_1() + '\\n')\n''' called from inside the instance_method_1() '''\n\n# # indirectly call static_method through instance_method_2(), there's really no use\n# for this since a @staticmethod can be called whether the class has been\n# instantiated or not\nprint(democlassObj.instance_method_2() + '\\n')\n''' called from inside the static_method() via instance_method_2() '''\n\n# call class_method()\nprint(democlassObj.class_method() + '\\n')\n''' called from inside the class_method() '''\n\n# call static_method()\nprint(democlassObj.static_method())\n''' called from inside the static_method() '''\n\n\"\"\"\n# whether the class is instantiated or not, this doesn't work\nprint(DemoClass.instance_method_1() + '\\n')\n'''\nTypeError: TypeError: unbound method instancemethod() must be called with\nDemoClass instance as first argument (got nothing instead)\n'''\n\"\"\"\n</code></pre>\n"
},
{
"answer_id": 54347204,
"author": "David Schumann",
"author_id": 1175081,
"author_profile": "https://Stackoverflow.com/users/1175081",
"pm_score": 3,
"selected": false,
"text": "<p>You might want to consider the difference between:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class A:\n def foo(): # no self parameter, no decorator\n pass\n</code></pre>\n<p>and</p>\n<pre class=\"lang-py prettyprint-override\"><code>class B:\n @staticmethod\n def foo(): # no self parameter\n pass\n</code></pre>\n<p>This has changed between python2 and python3:</p>\n<p>python2:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> A.foo()\nTypeError\n>>> A().foo()\nTypeError\n>>> B.foo()\n>>> B().foo()\n</code></pre>\n<p>python3:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> A.foo()\n>>> A().foo()\nTypeError\n>>> B.foo()\n>>> B().foo()\n</code></pre>\n<p>So using <code>@staticmethod</code> for methods only called directly from the class has become optional in python3. If you want to call them from both class and instance, you still need to use the <code>@staticmethod</code> decorator.</p>\n<p>The other cases have been well covered by unutbus answer.</p>\n"
},
{
"answer_id": 56236639,
"author": "blue_note",
"author_id": 3208297,
"author_profile": "https://Stackoverflow.com/users/3208297",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Only the first argument differs</strong>:</p>\n<ul>\n<li>normal method: <strong>the current object</strong> is automatically passed as an (additional) first argument</li>\n<li>classmethod: <strong>the class of the current object</strong> is automatically passed as an (additional) fist argument</li>\n<li>staticmethod: <strong>no extra arguments</strong> are automatically passed. What you passed to the function is what you get.</li>\n</ul>\n<p>In more detail...</p>\n<h2>normal method</h2>\n<p>The "standard" method, as in every object oriented language. When an object's method is called, it is automatically given an extra argument <code>self</code> as its first argument. That is, method</p>\n<pre><code>def f(self, x, y)\n</code></pre>\n<p>must be called with 2 arguments. <code>self</code> is automatically passed, and it is <em>the object itself</em>. Similar to the <code>this</code> that magically appears in eg. java/c++, only in python it is shown explicitly.</p>\n<blockquote>\n<p>actually, the first argument does not <em>have to</em> be called <code>self</code>, but it's the standard convention, so keep it</p>\n</blockquote>\n<h2>class method</h2>\n<p>When the method is decorated</p>\n<pre><code>@classmethod\ndef f(cls, x, y)\n</code></pre>\n<p>the automatically provided argument <em>is not</em> <code>self</code>, but <em>the class of</em> <code>self</code>.</p>\n<h2>static method</h2>\n<p>When the method is decorated</p>\n<pre><code>@staticmethod\ndef f(x, y)\n</code></pre>\n<p>the method <em>is not given</em> any automatic argument at all. It is only given the parameters that it is called with.</p>\n<h1>usages</h1>\n<ul>\n<li><code>classmethod</code> is mostly used for alternative constructors.</li>\n<li><code>staticmethod</code> does not use the state of the object, or even the structure of the class itself. It could be a function external to a class. It only put inside the class for grouping functions with similar functionality (for example, like Java's <code>Math</code> class static methods)</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>class Point\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n @classmethod\n def frompolar(cls, radius, angle):\n """The `cls` argument is the `Point` class itself"""\n return cls(radius * cos(angle), radius * sin(angle))\n\n @staticmethod\n def angle(x, y):\n """this could be outside the class, but we put it here \njust because we think it is logically related to the class."""\n return atan(y, x)\n\n\np1 = Point(3, 2)\np2 = Point.frompolar(3, pi/4)\n\nangle = Point.angle(3, 2)\n\n</code></pre>\n"
},
{
"answer_id": 58951325,
"author": "Jacky1205",
"author_id": 3291269,
"author_profile": "https://Stackoverflow.com/users/3291269",
"pm_score": 3,
"selected": false,
"text": "<p>I think giving a purely Python version of <code>staticmethod</code> and <code>classmethod</code> would help to understand the difference between them at language level (Refers to <a href=\"https://docs.python.org/2/howto/descriptor.html#static-methods-and-class-methods\" rel=\"nofollow noreferrer\">Descriptor Howto Guide</a>).</p>\n<p>Both of them are non-data descriptors (It would be easier to understand them if you are familiar with <a href=\"https://docs.python.org/3/reference/datamodel.html#implementing-descriptors\" rel=\"nofollow noreferrer\">descriptors</a> first).</p>\n<pre><code>class StaticMethod(object):\n "Emulate PyStaticMethod_Type() in Objects/funcobject.c"\n\n def __init__(self, f):\n self.f = f\n\n def __get__(self, obj, objtype=None):\n return self.f\n\n\nclass ClassMethod(object):\n "Emulate PyClassMethod_Type() in Objects/funcobject.c"\n def __init__(self, f):\n self.f = f\n\n def __get__(self, obj, cls=None):\n def inner(*args, **kwargs):\n if cls is None:\n cls = type(obj)\n return self.f(cls, *args, **kwargs)\n return inner\n</code></pre>\n"
},
{
"answer_id": 58953655,
"author": "Nicolae Petridean",
"author_id": 1999605,
"author_profile": "https://Stackoverflow.com/users/1999605",
"pm_score": 3,
"selected": false,
"text": "<p>A class method receives the class as implicit first argument, just like an instance method receives the instance. It is a method which is bound to the class and not the object of the class.It has access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class. For example it can modify a class variable that will be applicable to all the instances. </p>\n\n<p>On the other hand, a static method does not receive an implicit first argument, compared to class methods or instance methods. And can’t access or modify class state. It only belongs to the class because from design point of view that is the correct way. But in terms of functionality is not bound, at runtime, to the class.</p>\n\n<p>as a guideline, use static methods as utilities, use class methods for example as factory . Or maybe to define a singleton. And use instance methods to model the state and behavior of instances.</p>\n\n<p>Hope I was clear ! </p>\n"
},
{
"answer_id": 60492563,
"author": "mirek",
"author_id": 2520298,
"author_profile": "https://Stackoverflow.com/users/2520298",
"pm_score": 0,
"selected": false,
"text": "<p>staticmethod has no access to attibutes of the object, of the class, or of parent classes in the inheritance hierarchy.\nIt can be called at the class directly (without creating an object).</p>\n\n<p>classmethod has no access to attributes of the object. It however can access attributes of the class and of parent classes in the inheritance hierarchy.\nIt can be called at the class directly (without creating an object). If called at the object then it is the same as normal method which doesn't access <code>self.<attribute(s)></code> and accesses <code>self.__class__.<attribute(s)></code> only.</p>\n\n<p>Think we have a class with <code>b=2</code>, we will create an object and re-set this to <code>b=4</code> in it.\nStaticmethod cannot access nothing from previous.\nClassmethod can access <code>.b==2</code> only, via <code>cls.b</code>.\nNormal method can access both: <code>.b==4</code> via <code>self.b</code> and <code>.b==2</code> via <code>self.__class__.b</code>.</p>\n\n<p>We could follow the KISS style (keep it simple, stupid): Don't use staticmethods and classmethods, don't use classes without instantiating them, access only the object's attributes <code>self.attribute(s)</code>. There are languages where the OOP is implemented that way and I think it is not bad idea. :)</p>\n"
},
{
"answer_id": 63197044,
"author": "Ale",
"author_id": 1593459,
"author_profile": "https://Stackoverflow.com/users/1593459",
"pm_score": 2,
"selected": false,
"text": "<p>One pretty important practical difference occurs when subclassing. If you don't mind, I'll hijack @unutbu's example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class A: \n def foo(self, x): \n print("executing foo(%s, %s)" % (self, x)) \n \n @classmethod\n def class_foo(cls, x): \n print("executing class_foo(%s, %s)" % (cls, x))\n \n @staticmethod \n def static_foo(x): \n print("executing static_foo(%s)" % x)\n\nclass B(A):\n pass\n</code></pre>\n<p>In <code>class_foo</code>, the method knows which class it is called on:</p>\n<pre class=\"lang-py prettyprint-override\"><code>A.class_foo(1)\n# => executing class_foo(<class '__main__.A'>, 1)\nB.class_foo(1)\n# => executing class_foo(<class '__main__.B'>, 1)\n</code></pre>\n<p>In <code>static_foo</code>, there is no way to determine whether it is called on <code>A</code> or <code>B</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>A.static_foo(1)\n# => executing static_foo(1)\nB.static_foo(1)\n# => executing static_foo(1)\n</code></pre>\n<p>Note that this doesn't mean you can't use other methods in a <code>staticmethod</code>, you just have to reference the class directly, which means subclasses' staticmethods will still reference the parent class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class A:\n @classmethod\n def class_qux(cls, x):\n print(f"executing class_qux({cls}, {x})")\n \n @classmethod\n def class_bar(cls, x):\n cls.class_qux(x)\n\n @staticmethod\n def static_bar(x):\n A.class_qux(x)\n\nclass B(A):\n pass\n\nA.class_bar(1)\n# => executing class_qux(<class '__main__.A'>, 1)\nB.class_bar(1)\n# => executing class_qux(<class '__main__.B'>, 1)\nA.static_bar(1)\n# => executing class_qux(<class '__main__.A'>, 1)\nB.static_bar(1)\n# => executing class_qux(<class '__main__.A'>, 1)\n</code></pre>\n"
},
{
"answer_id": 64732009,
"author": "Milovan Tomašević",
"author_id": 13155046,
"author_profile": "https://Stackoverflow.com/users/13155046",
"pm_score": 3,
"selected": false,
"text": "<p><strong><em>Instance Method</em></strong>:</p>\n<p><code>+</code> <em>Can</em> modify object instance state</p>\n<p><code>+</code> <em>Can</em> modify class state</p>\n<p><strong><em>Class Method</em></strong>:</p>\n<p><code>-</code> <em>Can't</em> modify object instance state</p>\n<p><code>+</code> <em>Can</em> modify class state</p>\n<p><strong><em>Static Method</em></strong>:</p>\n<p><code>-</code> <em>Can't</em> modify object instance state</p>\n<p><code>-</code> <em>Can't</em> modify class state</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MyClass:\n ''' \n Instance method has a mandatory first attribute self which represent the instance itself. \n Instance method must be called by a instantiated instance.\n '''\n def method(self):\n return 'instance method called', self\n \n '''\n Class method has a mandatory first attribute cls which represent the class itself. \n Class method can be called by an instance or by the class directly. \n Its most common using scenario is to define a factory method.\n '''\n @classmethod\n def class_method(cls):\n return 'class method called', cls\n \n '''\n Static method doesn’t have any attributes of instances or the class. \n It also can be called by an instance or by the class directly. \n Its most common using scenario is to define some helper or utility functions which are closely relative to the class.\n '''\n @staticmethod\n def static_method():\n return 'static method called'\n\n\nobj = MyClass()\nprint(obj.method())\nprint(obj.class_method()) # MyClass.class_method()\nprint(obj.static_method()) # MyClass.static_method()\n</code></pre>\n<p>output:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>('instance method called', <__main__.MyClass object at 0x100fb3940>)\n('class method called', <class '__main__.MyClass'>)\nstatic method called\n</code></pre>\n<p>The instance method we actually had access to the object instance , right so this was an instance off a my class object whereas with the class method we have access to the class itself. But not to any of the objects, because the class method doesn't really care about an object existing. However you can both call a class method and static method on an object instance. This is going to work it doesn't really make a difference, so again when you call static method here it's going to work and it's going to know which method you want to call.</p>\n<p>The Static methods are used to do some utility tasks, and class methods are used for factory methods. The factory methods can return class objects for different use cases.</p>\n<p>And finally, a short example for better understanding:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Student:\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n @classmethod\n def get_from_string(cls, name_string: str):\n first_name, last_name = name_string.split()\n if Student.validate_name(first_name) and Student.validate_name(last_name):\n return cls(first_name, last_name)\n else:\n print('Invalid Names')\n\n @staticmethod\n def validate_name(name):\n return len(name) <= 10\n\n\nstackoverflow_student = Student.get_from_string('Name Surname')\nprint(stackoverflow_student.first_name) # Name\nprint(stackoverflow_student.last_name) # Surname\n</code></pre>\n"
},
{
"answer_id": 65754079,
"author": "illuminato",
"author_id": 2975438,
"author_profile": "https://Stackoverflow.com/users/2975438",
"pm_score": 4,
"selected": false,
"text": "<p>Python comes with several built-in decorators. The big three are:</p>\n<pre><code>@classmethod\n@staticmethod\n@property\n</code></pre>\n<p>First let's note that any function of a class can be called with instance of this class (after we initialized this class).</p>\n<p><strong>@classmethod</strong> is the way to <strong>call function</strong> not only as an instance of a class but also <strong>directly by the class itself</strong> as its first argument.</p>\n<p><strong>@staticmethod</strong> is a way of putting a function into a class (because it logically belongs there), while indicating that it does not require access to the class (so we <strong>don't need to use <code>self</code></strong> in function definition).</p>\n<p>Let's consider the following class:</p>\n<pre><code>class DecoratorTest(object):\n\n def __init__(self):\n pass\n\n def doubler(self, x):\n return x*2\n\n @classmethod\n def class_doubler(cls, x): # we need to use 'cls' instead of 'self'; 'cls' reference to the class instead of an instance of the class\n return x*2\n\n @staticmethod\n def static_doubler(x): # no need adding 'self' here; static_doubler() could be just a function not inside the class\n return x*2\n</code></pre>\n<p>Let's see how it works:</p>\n<pre><code>decor = DecoratorTest()\n\nprint(decor.doubler(5))\n# 10\n\nprint(decor.class_doubler(5)) # a call with an instance of a class\n# 10\nprint(DecoratorTest.class_doubler(5)) # a direct call by the class itself\n# 10\n\n# staticmethod could be called in the same way as classmethod.\nprint(decor.static_doubler(5)) # as an instance of the class\n# 10\nprint(DecoratorTest.static_doubler(5)) # or as a direct call \n# 10\n</code></pre>\n<p><a href=\"https://www.codearmo.com/python-tutorial/object-orientated-programming-static-class-methods\" rel=\"nofollow noreferrer\">Here</a> you can see some use cases for those methods.</p>\n<p>Bonus: you can read about <code>@property</code> decorator <a href=\"https://www.programiz.com/python-programming/property\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 66020869,
"author": "Sia",
"author_id": 2821756,
"author_profile": "https://Stackoverflow.com/users/2821756",
"pm_score": 2,
"selected": false,
"text": "<p>tldr;</p>\n<p>A <code>staticmethod</code> is essentially a function bound to a class (and consequently its instances)</p>\n<p>A <code>classmethod</code> is essentially an inheritable <code>staticmethod</code>.</p>\n<p>For details, see the excellent answers by others.</p>\n"
},
{
"answer_id": 66049235,
"author": "Giorgos Myrianthous",
"author_id": 7131757,
"author_profile": "https://Stackoverflow.com/users/7131757",
"pm_score": 2,
"selected": false,
"text": "<p>First let's start with an example code that we'll use to understand both concepts:</p>\n<pre><code>class Employee:\n\n NO_OF_EMPLOYEES = 0\n \n def __init__(self, first_name, last_name, salary):\n self.first_name = first_name\n self.last_name = last_name\n self.salary = salary\n self.increment_employees()\n\n def give_raise(self, amount):\n self.salary += amount\n\n @classmethod\n def employee_from_full_name(cls, full_name, salary):\n split_name = full_name.split(' ')\n first_name = split_name[0]\n last_name = split_name[1]\n return cls(first_name, last_name, salary)\n\n @classmethod\n def increment_employees(cls):\n cls.NO_OF_EMPLOYEES += 1\n\n @staticmethod\n def get_employee_legal_obligations_txt():\n legal_obligations = """\n 1. An employee must complete 8 hours per working day\n 2. ...\n """\n return legal_obligations\n</code></pre>\n<hr />\n<p><strong>Class method</strong></p>\n<p>A class method accepts the class itself as an implicit argument and -optionally- any other arguments specified in the definition. It’s important to understand that a class method, does not have access to object instances (like instance methods do). Therefore, class methods cannot be used to alter the state of an instantiated object but instead, they are capable of changing the class state which is shared amongst all the instances of that class.\nClass methods are typically useful when we need to access the class itself — for example, when we want to create a factory method, that is a method that creates instances of the class. In other words, class methods can serve as alternative constructors.</p>\n<p>In our example code, an instance of <code>Employee</code> can be constructed by providing three arguments; <code>first_name</code> , <code>last_name</code> and <code>salary</code>.</p>\n<pre><code>employee_1 = Employee('Andrew', 'Brown', 85000)\nprint(employee_1.first_name)\nprint(employee_1.salary)\n\n'Andrew'\n85000\n</code></pre>\n<p>Now let’s assume that there’s a chance that the name of an Employee can be provided in a single field in which the first and last names are separated by a whitespace. In this case, we could possibly use our class method called <code>employee_from_full_name</code> that accepts three arguments in total. The first one, is the class itself, which is an implicit argument which means that it won’t be provided when calling the method — Python will automatically do this for us:</p>\n<pre><code>employee_2 = Employee.employee_from_full_name('John Black', 95000)\nprint(employee_2.first_name)\nprint(employee_2.salary)\n\n'John'\n95000\n</code></pre>\n<p>Note that it is also possible to call <code>employee_from_full_name</code> from object instances although in this context it doesn’t make a lot of sense:</p>\n<pre><code>employee_1 = Employee('Andrew', 'Brown', 85000)\nemployee_2 = employee_1.employee_from_full_name('John Black', 95000)\n</code></pre>\n<p>Another reason why we might want to create a class method, is when we need to change the state of the class. In our example, the class variable <code>NO_OF_EMPLOYEES</code> keeps track of the number of employees currently working for the company. This method is called every time a new instance of Employee is created and it updates the count accordingly:</p>\n<pre><code>employee_1 = Employee('Andrew', 'Brown', 85000)\nprint(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')\nemployee_2 = Employee.employee_from_full_name('John Black', 95000)\nprint(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')\n\nNumber of employees: 1\nNumber of employees: 2\n</code></pre>\n<hr />\n<p><strong>Static methods</strong></p>\n<p>On the other hand, in static methods neither the instance (i.e. <code>self</code>) nor the class itself (i.e. <code>cls</code>) is passed as an implicit argument. This means that such methods, are not capable of accessing the class itself or its instances.\nNow one could argue that static methods are not useful in the context of classes as they can also be placed in helper modules instead of adding them as members of the class. In object oriented programming, it is important to structure your classes into logical chunks and thus, static methods are quite useful when we need to add a method under a class simply because it logically belongs to the class.\nIn our example, the static method named <code>get_employee_legal_obligations_txt</code> simply returns a string that contains the legal obligations of every single employee of a company. This function, does not interact with the class itself nor with any instance. It could have been placed into a different helper module however, it is only relevant to this class and therefore we have to place it under the Employee class.</p>\n<p>A static method can be access directly from the class itself</p>\n<pre><code>print(Employee.get_employee_legal_obligations_txt())\n\n\n 1. An employee must complete 8 hours per working day\n 2. ...\n</code></pre>\n<p>or from an instance of the class:</p>\n<pre><code>employee_1 = Employee('Andrew', 'Brown', 85000)\nprint(employee_1.get_employee_legal_obligations_txt())\n\n\n 1. An employee must complete 8 hours per working day\n 2. ...\n</code></pre>\n<hr />\n<p><strong>References</strong></p>\n<ul>\n<li><a href=\"https://towardsdatascience.com/whats-the-difference-between-static-and-class-methods-in-python-1ef581de4351\" rel=\"nofollow noreferrer\">What's the difference between static and class methods in Python?</a></li>\n</ul>\n"
},
{
"answer_id": 66672138,
"author": "H.H",
"author_id": 9312573,
"author_profile": "https://Stackoverflow.com/users/9312573",
"pm_score": 4,
"selected": false,
"text": "<p><strong>The difference occurs when there is inheritance.</strong></p>\n<p>Suppose that there are two classes-- Parent and Child. If one wants to use @staticmethod, print_name method should be written twice because the name of the class should be written in the print line.</p>\n<pre><code>class Parent:\n _class_name = "Parent"\n\n @staticmethod\n def print_name():\n print(Parent._class_name)\n\n\nclass Child(Parent):\n _class_name = "Child"\n\n @staticmethod\n def print_name():\n print(Child._class_name)\n\n\nParent.print_name()\nChild.print_name()\n</code></pre>\n<p>However, for @classmethod, it is not required to write print_name method twice.</p>\n<pre><code>class Parent:\n _class_name = "Parent"\n\n @classmethod\n def print_name(cls):\n print(cls._class_name)\n\n\nclass Child(Parent):\n _class_name = "Child"\n\n\nParent.print_name()\nChild.print_name()\n</code></pre>\n"
},
{
"answer_id": 68459641,
"author": "Arpan Saini",
"author_id": 7353562,
"author_profile": "https://Stackoverflow.com/users/7353562",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Definition of static method and class method from it's documentation. and When to use static method and when to use class method.</strong></p>\n<ul>\n<li><p><strong>Static method</strong> are like static method in java and C#, it won't use any initialize value of the class, all it need from outside to work fine.</p>\n</li>\n<li><p><strong>class method</strong>: are generally used for inheritance override, when we over-ride a method, and then we use CLS instance to tell if we want to call method of child or parent class. in case you want to use both the methods with same name and different signature.</p>\n</li>\n</ul>\n<p>staticmethod(function) -> method</p>\n<pre><code>Convert a function to be a static method.\n\nA static method does not receive an implicit first argument.\nTo declare a static method, use this idiom:\n\n class C:\n @staticmethod\n def f(arg1, arg2, ...):\n ...\n\nIt can be called either on the class (e.g. C.f()) or on an instance\n(e.g. C().f()). The instance is ignored except for its class.\n\nStatic methods in Python are similar to those found in Java or C++.\nFor a more advanced concept, see the classmethod builtin.\n"""\n</code></pre>\n<p>classmethod(function) -> method</p>\n<pre><code>Convert a function to be a class method.\n\nA class method receives the class as implicit first argument,\njust like an instance method receives the instance.\nTo declare a class method, use this idiom:\n\n class C:\n @classmethod\n def f(cls, arg1, arg2, ...):\n ...\n\nIt can be called either on the class (e.g. C.f()) or on an instance\n(e.g. C().f()). The instance is ignored except for its class.\nIf a class method is called for a derived class, the derived class\nobject is passed as the implied first argument.\n\nClass methods are different than C++ or Java static methods.\nIf you want those, see the staticmethod builtin.\n</code></pre>\n"
},
{
"answer_id": 73852182,
"author": "David Mendes",
"author_id": 4433157,
"author_profile": "https://Stackoverflow.com/users/4433157",
"pm_score": 0,
"selected": false,
"text": "<p>I'd like to add on top of all the previous answers the following, which is not official, but adheres to standards.</p>\n<p>First of all you can look at always giving the least amount of privilege necessary. So if you don't need something specific to the instance, make it a class method. If you don't need something specific to the class, make it a static method.</p>\n<p>Second thing is consider what you can communicate by the type of method that you make it. Static Method - helper function meant to be used outside of the class itself. Class function - can be called without instantiation however is meant to be used with that class only - otherwise would've been a static method ! Instance method - meant to be used only by instances.</p>\n<p>This can help you in communicating patterns and how your code should be used.</p>\n<pre><code>class Foo:\n @classmethod\n def bar(cls, id: int = None):\n query = session.query(\n a.id,\n a.name,\n a.address,\n )\n\n if id is not None:\n query = query.filter(a.id == id)\n\n return query\n</code></pre>\n<p>For example the above -- there is no reason why the method bar could not be static. However by making it a class method you communicate that it should be used by the class itself, as opposed it being a helper function meant to be used elsewhere !</p>\n<p>Remember the above is not official, rather my personal preference</p>\n"
},
{
"answer_id": 74470227,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "<h3><code>@classmethod</code>:</h3>\n<ul>\n<li><p>can call class variables and instance, class and static methods both by <code>cls</code> and directly by class name but not instance variables.</p>\n</li>\n<li><p>can be called both by object and directly by class name.</p>\n</li>\n<li><p>needs <code>cls</code> for the 1st argument otherwise <code>@classmethod</code> cannot be called and the name of <code>cls</code> is used in convention so other names instead of <code>cls</code> still work.</p>\n</li>\n</ul>\n<h3><code>@staticmethod</code>:</h3>\n<ul>\n<li><p>can be called both by an object and directly by class name.</p>\n</li>\n<li><p>can call class variables and instance, class and static methods directly by class name but not instance variables.</p>\n</li>\n<li><p>doesn't need <code>self</code> or <code>cls</code>.</p>\n</li>\n</ul>\n<p>*In detail, I also explain about <strong>instance method</strong> in <a href=\"https://stackoverflow.com/questions/46230482/what-is-an-instance-method-in-python/74482579#74482579\"><strong>my answer</strong></a> for <a href=\"https://stackoverflow.com/questions/46230482/what-is-an-instance-method-in-python\"><strong>What is an "instance method" in Python?</strong></a></p>\n<h1><code>@classmethod</code>:</h1>\n<p>For example, <code>@classmethod</code> can call the class variable and the instance, class and static methods both by <code>cls</code> and directly by class name and <code>@classmethod</code> can be called both by object and directly by class name as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Person:\n x = "Hello"\n def __init__(self, name):\n self.name = name\n \n @classmethod # Here\n def test1(cls):\n print(cls.x) # Class variable by `cls`\n cls.test2(cls) # Instance method by `cls`\n cls.test3() # Class method by `cls`\n cls.test4() # Static method by `cls`\n print()\n print(Person.x) # Class variable by class name\n Person.test2("Test2") # Instance method by class name\n Person.test3() # Class method by class name\n Person.test4() # Static method by class name\n \n def test2(self):\n print("Test2")\n \n @classmethod\n def test3(cls):\n print("Test3")\n \n @staticmethod\n def test4():\n print("Test4")\n\nobj = Person("John")\nobj.test1() # By object\n\n# Or\n\nPerson.test1() # By class name\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Hello\nTest2\nTest3\nTest4\n\nHello\nTest2\nTest3\nTest4\n</code></pre>\n<p>And, <code>@classmethod</code> cannot call instance variables both by <code>cls</code> and directly by class name so if <code>@classmethod</code> tries to call the instance variable both by <code>cls</code> and directly by class name as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n \n @classmethod\n def test1(cls):\n print(cls.name) # Instance variable by `cls`\n \n # Or\n\n print(Person.name) # Instance variable by class name\n# ...\n\nobj = Person("John")\nobj.test1()\n\n# Or\n\nPerson.test1()\n</code></pre>\n<p>The error below occurs:</p>\n<blockquote>\n<p>AttributeError: type object 'Person' has no attribute 'name'</p>\n</blockquote>\n<p>And, if <code>@classmethod</code> doesn't have <code>cls</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n \n @classmethod\n def test1(): # Without "cls"\n print("Test1")\n \n# ...\n\nobj = Person("John")\nobj.test1()\n\n# Or\n\nPerson.test1()\n</code></pre>\n<p><code>@classmethod</code> cannot be called, then the error below occurs as shown below:</p>\n<blockquote>\n<p>TypeError: test1() takes 0 positional arguments but 1 was given</p>\n</blockquote>\n<p>And, the name of <code>cls</code> is used in convention so other name instead of <code>cls</code> still work as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n\n @classmethod\n def test1(orange):\n print(orange.x) # Class variable\n orange.test2(orange) # Instance method\n orange.test3() # Class method\n orange.test4() # Static method\n\n# ...\n\nobj = Person("John")\nobj.test1()\n\n# Or\n\nPerson.test1()\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Hello\nTest2\nTest3\nTest4\n</code></pre>\n<h1><code>@staticmethod</code>:</h1>\n<p>For example, <code>@staticmethod</code> can be called both by object and directly by class name as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Person:\n x = "Hello"\n def __init__(self, name):\n self.name = name\n\n @staticmethod # Here\n def test1():\n print("Test1")\n \n def test2(self):\n print("Test2")\n \n @classmethod\n def test3(cls):\n print("Test3")\n \n @staticmethod\n def test4():\n print("Test4")\n\nobj = Person("John")\nobj.test1() # By object\n\n# Or\n\nPerson.test1() # By class name\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Test1\n</code></pre>\n<p>And, <code>@staticmethod</code> can call the class variable and the instance, class and static methods directly by class name but not instance variable as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n \n @staticmethod\n def test1():\n print(Person.x) # Class variable\n Person.test2("Test2") # Instance method\n Person.test3() # Class method\n Person.test4() # Static method\n \n# ...\n\nobj = Person("John")\nobj.test1()\n\n# Or\n\nPerson.test1()\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Hello\nTest2\nTest3\nTest4\n</code></pre>\n<p>And, if <code>@staticmethod</code> tries to call the instance variable as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n \n @staticmethod\n def test1():\n print(Person.name) # Instance variable\n \n# ...\n\nobj = Person("John")\nobj.test1()\n\n# Or\n\nPerson.test1()\n</code></pre>\n<p>The error below occurs:</p>\n<blockquote>\n<p>AttributeError: type object 'Person' has no attribute 'name'</p>\n</blockquote>\n<p>And, <code>@staticmethod</code> doesn't need <code>self</code> or <code>cls</code> so if <code>@staticmethod</code> has <code>self</code> or <code>cls</code>, you need to pass an argument as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n \n @staticmethod\n def test1(self): # With "self"\n print(self)\n\n # Or\n\n @staticmethod\n def test1(cls): # With "cls"\n print(cls)\n\n# ...\n\nobj = Person("John")\nobj.test1("Test1") # With an argument\n\n# Or\n\nPerson.test1("Test1") # With an argument\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Test1\n</code></pre>\n<p>Otherwise, if you don't pass an argument as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code># ...\n \n @staticmethod\n def test1(self): # With "self"\n print("Test1")\n\n # Or\n\n @staticmethod\n def test1(cls): # With "cls"\n print("Test1")\n\n# ...\n\nobj = Person("John")\nobj.test1() # Without an argument\n\n# Or\n\nPerson.test1() # Without an argument\n</code></pre>\n<p>These errors below occur:</p>\n<blockquote>\n<p>TypeError: test1() missing 1 required positional argument: 'self'</p>\n</blockquote>\n<blockquote>\n<p>TypeError: test1() missing 1 required positional argument: 'cls'</p>\n</blockquote>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
| What is the difference between a function decorated with [`@staticmethod`](http://docs.python.org/library/functions.html#staticmethod) and one decorated with [`@classmethod`](http://docs.python.org/library/functions.html#classmethod)? | Maybe a bit of example code will help: Notice the difference in the call signatures of `foo`, `class_foo` and `static_foo`:
```
class A(object):
def foo(self, x):
print(f"executing foo({self}, {x})")
@classmethod
def class_foo(cls, x):
print(f"executing class_foo({cls}, {x})")
@staticmethod
def static_foo(x):
print(f"executing static_foo({x})")
a = A()
```
Below is the usual way an object instance calls a method. The object instance, `a`, is implicitly passed as the first argument.
```
a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>, 1)
```
---
**With classmethods**, the class of the object instance is implicitly passed as the first argument instead of `self`.
```
a.class_foo(1)
# executing class_foo(<class '__main__.A'>, 1)
```
You can also call `class_foo` using the class. In fact, if you define something to be
a classmethod, it is probably because you intend to call it from the class rather than from a class instance. `A.foo(1)` would have raised a TypeError, but `A.class_foo(1)` works just fine:
```
A.class_foo(1)
# executing class_foo(<class '__main__.A'>, 1)
```
One use people have found for class methods is to create [inheritable alternative constructors](https://stackoverflow.com/a/1950927/190597).
---
**With staticmethods**, neither `self` (the object instance) nor `cls` (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:
```
a.static_foo(1)
# executing static_foo(1)
A.static_foo('hi')
# executing static_foo(hi)
```
Staticmethods are used to group functions which have some logical connection with a class to the class.
---
`foo` is just a function, but when you call `a.foo` you don't just get the function,
you get a "partially applied" version of the function with the object instance `a` bound as the first argument to the function. `foo` expects 2 arguments, while `a.foo` only expects 1 argument.
`a` is bound to `foo`. That is what is meant by the term "bound" below:
```
print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
```
With `a.class_foo`, `a` is not bound to `class_foo`, rather the class `A` is bound to `class_foo`.
```
print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>
```
Here, with a staticmethod, even though it is a method, `a.static_foo` just returns
a good 'ole function with no arguments bound. `static_foo` expects 1 argument, and
`a.static_foo` expects 1 argument too.
```
print(a.static_foo)
# <function static_foo at 0xb7d479cc>
```
And of course the same thing happens when you call `static_foo` with the class `A` instead.
```
print(A.static_foo)
# <function static_foo at 0xb7d479cc>
``` |
136,098 | <p>Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request:</p>
<pre><code>[Fatal Error] :-1:-1: Premature end of file.
</code></pre>
<p>How do I stop this error from appearing for each request?</p>
| [
{
"answer_id": 136125,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 4,
"selected": false,
"text": "<p>This bug was already fixed:\n<a href=\"http://jira.codehaus.org/browse/GRAILS-3088\" rel=\"nofollow noreferrer\">http://jira.codehaus.org/browse/GRAILS-3088</a></p>\n\n<blockquote>\n <p>Premature end of file</p>\n \n <p>Affects Version/s: 1.0.3<br>\n Fix Version/s: <a href=\"http://web.archive.org/web/20080914033743/http://jira.codehaus.org/browse/GRAILS/fixforversion/14156\" rel=\"nofollow noreferrer\">1.0.4</a></p>\n \n <p>...Just a few implementation notes. We were defaulting to a q value of 0, which is incorrect according to the spec. So we now default to 1.0 which gives the correct precedence order in Firefox 3, but incorrect in Firefox 2. However, more specific XML types like application/xhtml+xml now take precendence over less specific ones if they have the same q value so this fixes the issue in Firefox 2...</p>\n</blockquote>\n"
},
{
"answer_id": 158386,
"author": "Josh",
"author_id": 16175,
"author_profile": "https://Stackoverflow.com/users/16175",
"pm_score": 3,
"selected": true,
"text": "<p>The log entry occurs when http requests are made from Firefox 3 browsers.</p>\n\n<p>The workaround on Grails 1.0.3 is to open Config.groovy in your project and find the following:</p>\n\n<pre><code>grails.mime.types = [ html: ['text/html','application/xhtml+xml'],\nxml: ['text/xml', 'application/xml'], ...\n</code></pre>\n\n<p>The second line above, pertaining to xml should be removed.</p>\n\n<p>This is a GRAILS 1.0.3 bug that has been resolved, see <a href=\"http://jira.codehaus.org/browse/GRAILS-3088\" rel=\"nofollow noreferrer\">http://jira.codehaus.org/browse/GRAILS-3088</a> for full details.</p>\n"
},
{
"answer_id": 198641,
"author": "Robert Fischer",
"author_id": 27561,
"author_profile": "https://Stackoverflow.com/users/27561",
"pm_score": 1,
"selected": false,
"text": "<p>Upgrading to a 1.0.4 snapshot is probably the best way to deal with this issue. Check out the instructions under \"Grails Development Builds\" at <a href=\"http://grails.org/Download\" rel=\"nofollow noreferrer\">the Grails Download page</a>.</p>\n\n<p>It can also be ignored without too much difficulty.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16175/"
]
| Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request:
```
[Fatal Error] :-1:-1: Premature end of file.
```
How do I stop this error from appearing for each request? | The log entry occurs when http requests are made from Firefox 3 browsers.
The workaround on Grails 1.0.3 is to open Config.groovy in your project and find the following:
```
grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'], ...
```
The second line above, pertaining to xml should be removed.
This is a GRAILS 1.0.3 bug that has been resolved, see <http://jira.codehaus.org/browse/GRAILS-3088> for full details. |
136,104 | <p>Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?</p>
| [
{
"answer_id": 136109,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms164303.aspx\" rel=\"noreferrer\">It turns out that Dev Studio only honors this setting for Web Services.</a></p>\n\n<p>For non-web services you can get this to work by adding an AfterBuild target to your project file:</p>\n\n<pre><code> <Target Name=\"AfterBuild\" DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\" Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\" Outputs=\"$(OutputPath)$(_SGenDllName)\"> \n <SGen BuildAssemblyName=\"$(TargetFileName)\" BuildAssemblyPath=\"$(OutputPath)\" References=\"@(ReferencePath)\" ShouldGenerateSerializer=\"true\" UseProxyTypes=\"false\" KeyContainer=\"$(KeyContainerName)\" KeyFile=\"$(KeyOriginatorFile)\" DelaySign=\"$(DelaySign)\" ToolPath=\"$(SGenToolPath)\">\n <Output TaskParameter=\"SerializationAssembly\" ItemName=\"SerializationAssembly\" />\n </SGen>\n </Target>\n</code></pre>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms164303.aspx\" rel=\"noreferrer\">SGen MSBuild Task</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/xzw8335a(VS.80).aspx\" rel=\"noreferrer\">AfterBuild Event</a></li>\n</ul>\n"
},
{
"answer_id": 136124,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 1,
"selected": false,
"text": "<p>It can be done manually with <a href=\"http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx\" rel=\"nofollow noreferrer\">sgen.exe</a>.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
]
| Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"? | [It turns out that Dev Studio only honors this setting for Web Services.](http://msdn.microsoft.com/en-us/library/ms164303.aspx)
For non-web services you can get this to work by adding an AfterBuild target to your project file:
```
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
<Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
</SGen>
</Target>
```
See also:
* [SGen MSBuild Task](http://msdn.microsoft.com/en-us/library/ms164303.aspx)
* [AfterBuild Event](http://msdn.microsoft.com/en-us/library/xzw8335a(VS.80).aspx) |
136,129 | <p>I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors:</p>
<ul>
<li>If background color is transparent then ForeColor is same as TextBox disabled Color.</li>
<li>If background color is set to anything else, ForeColor is a Dark Gray color.</li>
</ul>
<p>The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes.</p>
<p><img src="https://i.stack.imgur.com/60viN.png" alt="alt text"></p>
<p>Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent.</p>
| [
{
"answer_id": 136142,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried implementing the EnabledChanged event? Or are you looking for more of a \"styles\" property on the control (as far as I know, they don't exist)?</p>\n"
},
{
"answer_id": 136230,
"author": "Calvin Allen",
"author_id": 411,
"author_profile": "https://Stackoverflow.com/users/411",
"pm_score": 0,
"selected": false,
"text": "<p>Why is this an issue?</p>\n\n<p>I would personally let windows handle it. People are used to disabled items looking a certain way, so if you start trying to change every aspect of the way they look, you might start confusing your users.</p>\n"
},
{
"answer_id": 136264,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 0,
"selected": false,
"text": "<p>You will probably need to override the Paint event. All toolkits I've used so far have the same problem when the control is disabled. Just guess they let windows do the drawing of the text. As for the labels, well they are not an standard control, and that's why they are working.</p>\n"
},
{
"answer_id": 136265,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 2,
"selected": true,
"text": "<p>Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint.drawstringdisabled.aspx\" rel=\"nofollow noreferrer\">ControlPaint.DrawStringDisabled</a> method; it might be something helpful. I've used it when overriding the OnPaint event for custom controls.</p>\n\n<pre><code>ControlPaint.DrawStringDisabled(g, this.Text, this.Font, Color.Transparent,\n new Rectangle(CustomStringWidth, 5, StringSize2.Width, StringSize2.Height), StringFormat.GenericTypographic);\n</code></pre>\n"
},
{
"answer_id": 183690,
"author": "Andrew",
"author_id": 8586,
"author_profile": "https://Stackoverflow.com/users/8586",
"pm_score": 2,
"selected": false,
"text": "<p>For the textbox, you can set the readonly property to true while keeping the control enabled. You can then set the BackColor and ForeColor property to whatever you like. The user will still be able to click on the control and have a blinking cursor, but they won't be able to edit anything.</p>\n\n<p>Not sure if this extrapolates out to other control types like combo boxes or whatnot as I haven't had a chance to experiment yet, but it's worth a shot.</p>\n"
},
{
"answer_id": 17196593,
"author": "MDMoore313",
"author_id": 1298503,
"author_profile": "https://Stackoverflow.com/users/1298503",
"pm_score": 0,
"selected": false,
"text": "<p>I overrode the OnPaint method of my control with the OnPaint method below. I pasted the entire control class to make it easy to copy.</p>\n\n<pre><code>public partial class NewLabel : Label\n{\n public NewLabel()\n {\n InitializeComponent();\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n TextRenderer.DrawText(e.Graphics, this.Text.ToString(), this.Font, ClientRectangle, ForeColor);\n }\n\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19242/"
]
| I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors:
* If background color is transparent then ForeColor is same as TextBox disabled Color.
* If background color is set to anything else, ForeColor is a Dark Gray color.
The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes.

Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent. | Take a look at the [ControlPaint.DrawStringDisabled](http://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint.drawstringdisabled.aspx) method; it might be something helpful. I've used it when overriding the OnPaint event for custom controls.
```
ControlPaint.DrawStringDisabled(g, this.Text, this.Font, Color.Transparent,
new Rectangle(CustomStringWidth, 5, StringSize2.Width, StringSize2.Height), StringFormat.GenericTypographic);
``` |
136,132 | <p>I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:</p>
<pre><code>RichTextBox rtb = new RichTextBox();
Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold);
rtb.Text = "sometext";
rtb.SelectAll()
rtb.SelectionFont = boldfont;
rtb.SelectionIndent = 12;
</code></pre>
<p>There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?</p>
<p>Edit:
The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.</p>
| [
{
"answer_id": 136169,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem \"inelegant\"</p>\n"
},
{
"answer_id": 136221,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "<p>You could create some utility extension methods to make it more 'elegant' :)</p>\n\n<pre><code>public static RichTextBox Set(this RichTextBox rtb, Font font, string text)\n{ \n rtb.Text = text;\n rtb.SelectAll();\n rtb.SelectionFont = font;\n rtb.SelectionIndent = 12;\n return rtb;\n}\n</code></pre>\n\n<p>And call like this:</p>\n\n<pre><code>someRtb.Set(yourFont, \"The Text\").AndThenYouCanAddMoreAndCHainThem();\n</code></pre>\n\n<p>Edit: I see now that you are not even displaying it. Hrm, interesting, sorry i wasnt of much help with providing a Non Rtb way.</p>\n"
},
{
"answer_id": 136243,
"author": "jwalkerjr",
"author_id": 689,
"author_profile": "https://Stackoverflow.com/users/689",
"pm_score": 2,
"selected": false,
"text": "<p>I think your technique is a great way to accomplish what you're looking to do. I know what you mean...it feels kind of \"dirty\" because you're using a Winforms control for something other than it was intended for, but it just works. I've used this technique for years. Interested to see if anyone else has viable options.</p>\n"
},
{
"answer_id": 957197,
"author": "jjxtra",
"author_id": 56079,
"author_profile": "https://Stackoverflow.com/users/56079",
"pm_score": 2,
"selected": false,
"text": "<p>Is this project helpful? </p>\n\n<p><a href=\"http://www.codeproject.com/KB/string/nrtftree.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/string/nrtftree.aspx</a></p>\n"
},
{
"answer_id": 7303225,
"author": "jjxtra",
"author_id": 56079,
"author_profile": "https://Stackoverflow.com/users/56079",
"pm_score": 0,
"selected": false,
"text": "<p>I know it's been a while, but check out this stackoverflow post on converting rtf to html. It would probably be way easier to get your stuff into html, manipulate it, then either display it using html or convert it back to rtf.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/439301/convert-rtf-to-html\">Convert Rtf to HTML</a></p>\n"
},
{
"answer_id": 26768915,
"author": "ePandit",
"author_id": 676779,
"author_profile": "https://Stackoverflow.com/users/676779",
"pm_score": 1,
"selected": false,
"text": "<p>You should also suspend the layout of the richtextbox just after creation and dispose it after use.</p>\n\n<pre><code>RichTextBox rtb = new RichTextBox();\nrtb.SuspendLayout();\n//richtext processing goes here...\nrtb.Dispose();\n</code></pre>\n\n<p>And don't be shy to use richtextbox for richtext processing. Microsoft itself is doing this here in <a href=\"http://msdn.microsoft.com/en-us/library/cc488002.aspx\" rel=\"nofollow\">this</a> tutorial. :-)</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13776/"
]
| I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:
```
RichTextBox rtb = new RichTextBox();
Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold);
rtb.Text = "sometext";
rtb.SelectAll()
rtb.SelectionFont = boldfont;
rtb.SelectionIndent = 12;
```
There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?
Edit:
The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText. | You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem "inelegant" |
136,146 | <p>Examples:</p>
<pre><code>"1" yes
"-1" yes
"- 3" no
"1.2" yes
"1.2.3" no
"7e4" no (though in some cases you may want to allow scientific notation)
".123" yes
"123." yes
"." no
"-.5" yes
"007" yes
"00" yes
</code></pre>
| [
{
"answer_id": 136157,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 2,
"selected": false,
"text": "<p>This allows for optional \"+\" and \"-\" in front. And allows trailing or initial whitespace.</p>\n\n<pre><code>/^\\s*[+-]?(?:\\d+\\.?\\d*|\\d*\\.\\d+)\\s*$/\n</code></pre>\n"
},
{
"answer_id": 136160,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on the language you are coding in this functionality may already exist.</p>\n"
},
{
"answer_id": 136321,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 2,
"selected": false,
"text": "<p>Matches all specified examples, doesn't capture any groups:</p>\n\n<pre><code>^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$\n</code></pre>\n\n<p><br/>\nTo not match \"1.\" (etc):</p>\n\n<pre><code>^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)$\n</code></pre>\n\n<p><br/></p>\n\n<p>Doesn't bother with whitespace (use a trim function).</p>\n"
},
{
"answer_id": 160871,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 2,
"selected": false,
"text": "<p>There are several alternatives. First, using a zero-width look-ahead assertion allows you to make the rest of the regex simpler:</p>\n\n<pre><code>/^[-+]?(?=\\.?\\d)\\d*(?:\\.\\d*)?$/\n</code></pre>\n\n<p>If you want to avoid the look-ahead, then I'd try to discourage the regex from back-tracking:</p>\n\n<pre><code>/^[-+]?(?:\\.\\d+|\\d+(?:\\.\\d*)?)$/\n/^[-+]?(\\.\\d+|\\d+(\\.\\d*)?)$/ # if you don't mind capturing parens\n</code></pre>\n\n<p>Note that you said \"base 10\" so you might actually want to disallow extra leading zeros since \"014\" might be meant to be octal:</p>\n\n<pre><code>/^[-+]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)$/\n/^[-+]?(\\.\\d+|(0|[1-9]\\d*)(\\.\\d*)?)$/\n</code></pre>\n\n<p>Finally, you might want to replace <code>\\d</code> with <code>[0-9]</code> since some regexes don't support <code>\\d</code> or because some regexes allow <code>\\d</code> to match Unicode \"digits\" other than 0..9 such as \"ARABIC-INDIC DIGIT\"s.</p>\n\n<pre><code>/^[-+]?(?:\\.[0-9]+|(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?)$/\n/^[-+]?(\\.[0-9]+|(0|[1-9][0-9]*)(\\.[0-9]*)?)$/\n</code></pre>\n"
},
{
"answer_id": 347025,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 2,
"selected": false,
"text": "<p>The regular expression in <a href=\"http://faq.perl.org/perlfaq4.html#How_do_I_determine_w\" rel=\"nofollow noreferrer\">perlfaq4: How do I determine whether a scalar is a number/whole/integer/float?</a> does what you want, and it handles the \"e\" notation too.</p>\n\n<pre>\nwhile( <DATA> )\n {\n chomp;\n\n print /^([+-]?)(?=\\d|\\.\\d)\\d*(\\.\\d*)?([Ee]([+-]?\\d+))?$/ ?\n \"$_ Works\\n\"\n :\n \"$_ Fails\\n\"\n ;\n }\n\n__DATA__\n1\n-1\n- 3\n1.2\n1.2.3\n7e4\n.123\n123.\n.\n-.5\n</pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
]
| Examples:
```
"1" yes
"-1" yes
"- 3" no
"1.2" yes
"1.2.3" no
"7e4" no (though in some cases you may want to allow scientific notation)
".123" yes
"123." yes
"." no
"-.5" yes
"007" yes
"00" yes
``` | This allows for optional "+" and "-" in front. And allows trailing or initial whitespace.
```
/^\s*[+-]?(?:\d+\.?\d*|\d*\.\d+)\s*$/
``` |
136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and support an offset. This is hat I came up with:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| [
{
"answer_id": 136280,
"author": "Mark",
"author_id": 16363,
"author_profile": "https://Stackoverflow.com/users/16363",
"pm_score": 7,
"selected": false,
"text": "<p>Assumes a unix-like system on Python 2 you can do:</p>\n\n<pre><code>import os\ndef tail(f, n, offset=0):\n stdin,stdout = os.popen2(\"tail -n \"+n+offset+\" \"+f)\n stdin.close()\n lines = stdout.readlines(); stdout.close()\n return lines[:,-offset]\n</code></pre>\n\n<p>For python 3 you may do:</p>\n\n<pre><code>import subprocess\ndef tail(f, n, offset=0):\n proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)\n lines = proc.stdout.readlines()\n return lines[:, -offset]\n</code></pre>\n"
},
{
"answer_id": 136354,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 1,
"selected": false,
"text": "<p>For efficiency with very large files (common in logfile situations where you may want to use tail), you generally want to avoid reading the whole file (even if you do do it without reading the whole file into memory at once) However, you do need to somehow work out the offset in lines rather than characters. One possibility is reading backwards with seek() char by char, but this is very slow. Instead, its better to process in larger blocks.</p>\n\n<p>I've a utility function I wrote a while ago to read files backwards that can be used here.</p>\n\n<pre><code>import os, itertools\n\ndef rblocks(f, blocksize=4096):\n \"\"\"Read file as series of blocks from end of file to start.\n\n The data itself is in normal order, only the order of the blocks is reversed.\n ie. \"hello world\" -> [\"ld\",\"wor\", \"lo \", \"hel\"]\n Note that the file must be opened in binary mode.\n \"\"\"\n if 'b' not in f.mode.lower():\n raise Exception(\"File must be opened using binary mode.\")\n size = os.stat(f.name).st_size\n fullblocks, lastblock = divmod(size, blocksize)\n\n # The first(end of file) block will be short, since this leaves \n # the rest aligned on a blocksize boundary. This may be more \n # efficient than having the last (first in file) block be short\n f.seek(-lastblock,2)\n yield f.read(lastblock)\n\n for i in range(fullblocks-1,-1, -1):\n f.seek(i * blocksize)\n yield f.read(blocksize)\n\ndef tail(f, nlines):\n buf = ''\n result = []\n for block in rblocks(f):\n buf = block + buf\n lines = buf.splitlines()\n\n # Return all lines except the first (since may be partial)\n if lines:\n result.extend(lines[1:]) # First line may not be complete\n if(len(result) >= nlines):\n return result[-nlines:]\n\n buf = lines[0]\n\n return ([buf]+result)[-nlines:]\n\n\nf=open('file_to_tail.txt','rb')\nfor line in tail(f, 20):\n print line\n</code></pre>\n\n<p>[Edit] Added more specific version (avoids need to reverse twice)</p>\n"
},
{
"answer_id": 136368,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 7,
"selected": false,
"text": "<p>This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\\n' characters.</p>\n\n<pre><code>def tail( f, lines=20 ):\n total_lines_wanted = lines\n\n BLOCK_SIZE = 1024\n f.seek(0, 2)\n block_end_byte = f.tell()\n lines_to_go = total_lines_wanted\n block_number = -1\n blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting\n # from the end of the file\n while lines_to_go > 0 and block_end_byte > 0:\n if (block_end_byte - BLOCK_SIZE > 0):\n # read the last block we haven't yet read\n f.seek(block_number*BLOCK_SIZE, 2)\n blocks.append(f.read(BLOCK_SIZE))\n else:\n # file too small, start from begining\n f.seek(0,0)\n # only read what was not read\n blocks.append(f.read(block_end_byte))\n lines_found = blocks[-1].count('\\n')\n lines_to_go -= lines_found\n block_end_byte -= BLOCK_SIZE\n block_number -= 1\n all_read_text = ''.join(reversed(blocks))\n return '\\n'.join(all_read_text.splitlines()[-total_lines_wanted:])\n</code></pre>\n\n<p>I don't like tricky assumptions about line length when -- as a practical matter -- you can never know things like that.</p>\n\n<p>Generally, this will locate the last 20 lines on the first or second pass through the loop. If your 74 character thing is actually accurate, you make the block size 2048 and you'll tail 20 lines almost immediately.</p>\n\n<p>Also, I don't burn a lot of brain calories trying to finesse alignment with physical OS blocks. Using these high-level I/O packages, I doubt you'll see any performance consequence of trying to align on OS block boundaries. If you use lower-level I/O, then you might see a speedup.</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p><em>for Python 3.2 and up, follow the process on bytes as In text files (those opened without a <strong>\"b\"</strong> in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)).:</em></p>\n\n<p>eg: <code>f = open('C:/.../../apache_logs.txt', 'rb')</code></p>\n\n<pre><code> def tail(f, lines=20):\n total_lines_wanted = lines\n\n BLOCK_SIZE = 1024\n f.seek(0, 2)\n block_end_byte = f.tell()\n lines_to_go = total_lines_wanted\n block_number = -1\n blocks = []\n while lines_to_go > 0 and block_end_byte > 0:\n if (block_end_byte - BLOCK_SIZE > 0):\n f.seek(block_number*BLOCK_SIZE, 2)\n blocks.append(f.read(BLOCK_SIZE))\n else:\n f.seek(0,0)\n blocks.append(f.read(block_end_byte))\n lines_found = blocks[-1].count(b'\\n')\n lines_to_go -= lines_found\n block_end_byte -= BLOCK_SIZE\n block_number -= 1\n all_read_text = b''.join(reversed(blocks))\n return b'\\n'.join(all_read_text.splitlines()[-total_lines_wanted:])\n</code></pre>\n"
},
{
"answer_id": 136475,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": -1,
"selected": false,
"text": "<p>On second thought, this is probably just as fast as anything here.</p>\n\n<pre><code>def tail( f, window=20 ):\n lines= ['']*window\n count= 0\n for l in f:\n lines[count%window]= l\n count += 1\n print lines[count%window:], lines[:count%window]\n</code></pre>\n\n<p>It's a lot simpler. And it does seem to rip along at a good pace. </p>\n"
},
{
"answer_id": 280083,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 5,
"selected": false,
"text": "<p>If reading the whole file is acceptable then use a deque.</p>\n\n<pre><code>from collections import deque\ndeque(f, maxlen=n)\n</code></pre>\n\n<p>Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.</p>\n\n<pre><code>import itertools\ndef maxque(items, size):\n items = iter(items)\n q = deque(itertools.islice(items, size))\n for item in items:\n del q[0]\n q.append(item)\n return q\n</code></pre>\n\n<p>If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.</p>\n\n<pre><code>def tail(f, n):\n assert n >= 0\n pos, lines = n+1, []\n while len(lines) <= n:\n try:\n f.seek(-pos, 2)\n except IOError:\n f.seek(0)\n break\n finally:\n lines = list(f)\n pos *= 2\n return lines[-n:]\n</code></pre>\n"
},
{
"answer_id": 692616,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 6,
"selected": true,
"text": "<p>The code I ended up using. I think this is the best so far:</p>\n\n<pre><code>def tail(f, n, offset=None):\n \"\"\"Reads a n lines from f with an offset of offset lines. The return\n value is a tuple in the form ``(lines, has_more)`` where `has_more` is\n an indicator that is `True` if there are more lines in the file.\n \"\"\"\n avg_line_length = 74\n to_read = n + (offset or 0)\n\n while 1:\n try:\n f.seek(-(avg_line_length * to_read), 2)\n except IOError:\n # woops. apparently file is smaller than what we want\n # to step back, go to the beginning instead\n f.seek(0)\n pos = f.tell()\n lines = f.read().splitlines()\n if len(lines) >= to_read or pos == 0:\n return lines[-to_read:offset and -offset or None], \\\n len(lines) > to_read or pos > 0\n avg_line_length *= 1.3\n</code></pre>\n"
},
{
"answer_id": 3018671,
"author": "Eyecue",
"author_id": 359868,
"author_profile": "https://Stackoverflow.com/users/359868",
"pm_score": 2,
"selected": false,
"text": "<p>based on S.Lott's top voted answer (Sep 25 '08 at 21:43), but fixed for small files.</p>\n\n<pre><code>def tail(the_file, lines_2find=20): \n the_file.seek(0, 2) #go to end of file\n bytes_in_file = the_file.tell() \n lines_found, total_bytes_scanned = 0, 0\n while lines_2find+1 > lines_found and bytes_in_file > total_bytes_scanned: \n byte_block = min(1024, bytes_in_file-total_bytes_scanned)\n the_file.seek(-(byte_block+total_bytes_scanned), 2)\n total_bytes_scanned += byte_block\n lines_found += the_file.read(1024).count('\\n')\n the_file.seek(-total_bytes_scanned, 2)\n line_list = list(the_file.readlines())\n return line_list[-lines_2find:]\n\n #we read at least 21 line breaks from the bottom, block by block for speed\n #21 to ensure we don't get a half line\n</code></pre>\n\n<p>Hope this is useful.</p>\n"
},
{
"answer_id": 4131157,
"author": "rabbit",
"author_id": 501548,
"author_profile": "https://Stackoverflow.com/users/501548",
"pm_score": 1,
"selected": false,
"text": "<p>you can go to the end of your file with f.seek(0, 2) and then read off lines one by one with the following replacement for readline():</p>\n\n<pre><code>def readline_backwards(self, f):\n backline = ''\n last = ''\n while not last == '\\n':\n backline = last + backline\n if f.tell() <= 0:\n return backline\n f.seek(-1, 1)\n last = f.read(1)\n f.seek(-1, 1)\n backline = last\n last = ''\n while not last == '\\n':\n backline = last + backline\n if f.tell() <= 0:\n return backline\n f.seek(-1, 1)\n last = f.read(1)\n f.seek(-1, 1)\n f.seek(1, 1)\n return backline\n</code></pre>\n"
},
{
"answer_id": 4751601,
"author": "fdb",
"author_id": 260908,
"author_profile": "https://Stackoverflow.com/users/260908",
"pm_score": 1,
"selected": false,
"text": "<p>Based on Eyecue answer (Jun 10 '10 at 21:28): this class add head() and tail() method to file object.</p>\n\n<pre><code>class File(file):\n def head(self, lines_2find=1):\n self.seek(0) #Rewind file\n return [self.next() for x in xrange(lines_2find)]\n\n def tail(self, lines_2find=1): \n self.seek(0, 2) #go to end of file\n bytes_in_file = self.tell() \n lines_found, total_bytes_scanned = 0, 0\n while (lines_2find+1 > lines_found and\n bytes_in_file > total_bytes_scanned): \n byte_block = min(1024, bytes_in_file-total_bytes_scanned)\n self.seek(-(byte_block+total_bytes_scanned), 2)\n total_bytes_scanned += byte_block\n lines_found += self.read(1024).count('\\n')\n self.seek(-total_bytes_scanned, 2)\n line_list = list(self.readlines())\n return line_list[-lines_2find:]\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>f = File('path/to/file', 'r')\nf.head(3)\nf.tail(3)\n</code></pre>\n"
},
{
"answer_id": 5638389,
"author": "David Rogers",
"author_id": 704467,
"author_profile": "https://Stackoverflow.com/users/704467",
"pm_score": 1,
"selected": false,
"text": "<p>Several of these solutions have issues if the file doesn't end in \\n or in ensuring the complete first line is read.</p>\n\n<pre><code>def tail(file, n=1, bs=1024):\n f = open(file)\n f.seek(-1,2)\n l = 1-f.read(1).count('\\n') # If file doesn't end in \\n, count it anyway.\n B = f.tell()\n while n >= l and B > 0:\n block = min(bs, B)\n B -= block\n f.seek(B, 0)\n l += f.read(block).count('\\n')\n f.seek(B, 0)\n l = min(l,n) # discard first (incomplete) line if l > n\n lines = f.readlines()[-l:]\n f.close()\n return lines\n</code></pre>\n"
},
{
"answer_id": 6813975,
"author": "dimitri",
"author_id": 861232,
"author_profile": "https://Stackoverflow.com/users/861232",
"pm_score": 4,
"selected": false,
"text": "<p>Simple and fast solution with mmap:</p>\n\n<pre><code>import mmap\nimport os\n\ndef tail(filename, n):\n \"\"\"Returns last n lines from the filename. No exception handling\"\"\"\n size = os.path.getsize(filename)\n with open(filename, \"rb\") as f:\n # for Windows the mmap parameters are different\n fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)\n try:\n for i in xrange(size - 1, -1, -1):\n if fm[i] == '\\n':\n n -= 1\n if n == -1:\n break\n return fm[i + 1 if i else 0:].splitlines()\n finally:\n fm.close()\n</code></pre>\n"
},
{
"answer_id": 7047765,
"author": "papercrane",
"author_id": 892621,
"author_profile": "https://Stackoverflow.com/users/892621",
"pm_score": 5,
"selected": false,
"text": "<p>S.Lott's answer above almost works for me but ends up giving me partial lines. It turns out that it corrupts data on block boundaries because data holds the read blocks in reversed order. When ''.join(data) is called, the blocks are in the wrong order. This fixes that.</p>\n\n<pre><code>def tail(f, window=20):\n \"\"\"\n Returns the last `window` lines of file `f` as a list.\n f - a byte file-like object\n \"\"\"\n if window == 0:\n return []\n BUFSIZ = 1024\n f.seek(0, 2)\n bytes = f.tell()\n size = window + 1\n block = -1\n data = []\n while size > 0 and bytes > 0:\n if bytes - BUFSIZ > 0:\n # Seek back one whole BUFSIZ\n f.seek(block * BUFSIZ, 2)\n # read BUFFER\n data.insert(0, f.read(BUFSIZ))\n else:\n # file too small, start from begining\n f.seek(0,0)\n # only read what was not read\n data.insert(0, f.read(bytes))\n linesFound = data[0].count('\\n')\n size -= linesFound\n bytes -= BUFSIZ\n block -= 1\n return ''.join(data).splitlines()[-window:]\n</code></pre>\n"
},
{
"answer_id": 10175048,
"author": "Marko",
"author_id": 1336404,
"author_profile": "https://Stackoverflow.com/users/1336404",
"pm_score": 2,
"selected": false,
"text": "<p>I found the Popen above to be the best solution. It's quick and dirty and it works\nFor python 2.6 on Unix machine i used the following</p>\n\n<pre><code>def GetLastNLines(self, n, fileName):\n \"\"\"\n Name: Get LastNLines\n Description: Gets last n lines using Unix tail\n Output: returns last n lines of a file\n Keyword argument:\n n -- number of last lines to return\n filename -- Name of the file you need to tail into\n \"\"\"\n p = subprocess.Popen(['tail','-n',str(n),self.__fileName], stdout=subprocess.PIPE)\n soutput, sinput = p.communicate()\n return soutput\n</code></pre>\n\n<p>soutput will have will contain last n lines of the code. to iterate through soutput line by line do:</p>\n\n<pre><code>for line in GetLastNLines(50,'myfile.log').split('\\n'):\n print line\n</code></pre>\n"
},
{
"answer_id": 12762551,
"author": "Travis Bear",
"author_id": 825706,
"author_profile": "https://Stackoverflow.com/users/825706",
"pm_score": 2,
"selected": false,
"text": "<p>There are some existing implementations of tail on pypi which you can install using pip: </p>\n\n<ul>\n<li>mtFileUtil</li>\n<li>multitail</li>\n<li>log4tailer</li>\n<li>...</li>\n</ul>\n\n<p>Depending on your situation, there may be advantages to using one of these existing tools.</p>\n"
},
{
"answer_id": 13790289,
"author": "glenbot",
"author_id": 1889809,
"author_profile": "https://Stackoverflow.com/users/1889809",
"pm_score": 5,
"selected": false,
"text": "<p>Here is my answer. Pure python. Using timeit it seems pretty fast. Tailing 100 lines of a log file that has 100,000 lines:</p>\n\n<pre><code>>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=10)\n0.0014600753784179688\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=100)\n0.00899195671081543\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=1000)\n0.05842900276184082\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=10000)\n0.5394978523254395\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=100000)\n5.377126932144165\n</code></pre>\n\n<p>Here is the code:</p>\n\n<pre><code>import os\n\n\ndef tail(f, lines=1, _buffer=4098):\n \"\"\"Tail a file and get X lines from the end\"\"\"\n # place holder for the lines found\n lines_found = []\n\n # block counter will be multiplied by buffer\n # to get the block size from the end\n block_counter = -1\n\n # loop until we find X lines\n while len(lines_found) < lines:\n try:\n f.seek(block_counter * _buffer, os.SEEK_END)\n except IOError: # either file is too small, or too many lines requested\n f.seek(0)\n lines_found = f.readlines()\n break\n\n lines_found = f.readlines()\n\n # we found enough lines, get out\n # Removed this line because it was redundant the while will catch\n # it, I left it for history\n # if len(lines_found) > lines:\n # break\n\n # decrement the block counter to get the\n # next X bytes\n block_counter -= 1\n\n return lines_found[-lines:]\n</code></pre>\n"
},
{
"answer_id": 16507215,
"author": "Leifbk",
"author_id": 2374816,
"author_profile": "https://Stackoverflow.com/users/2374816",
"pm_score": 0,
"selected": false,
"text": "<p>I had to read a specific value from the last line of a file, and stumbled upon this thread. Rather than reinventing the wheel in Python, I ended up with a tiny shell script, saved as\n/usr/local/bin/get_last_netp:</p>\n\n<pre><code>#! /bin/bash\ntail -n1 /home/leif/projects/transfer/export.log | awk {'print $14'}\n</code></pre>\n\n<p>And in the Python program:</p>\n\n<pre><code>from subprocess import check_output\n\nlast_netp = int(check_output(\"/usr/local/bin/get_last_netp\"))\n</code></pre>\n"
},
{
"answer_id": 16507435,
"author": "Hal Canary",
"author_id": 2204941,
"author_profile": "https://Stackoverflow.com/users/2204941",
"pm_score": 0,
"selected": false,
"text": "<p>Not the first example using a deque, but a simpler one. This one is general: it works on any iterable object, not just a file.</p>\n\n<pre><code>#!/usr/bin/env python\nimport sys\nimport collections\ndef tail(iterable, N):\n deq = collections.deque()\n for thing in iterable:\n if len(deq) >= N:\n deq.popleft()\n deq.append(thing)\n for thing in deq:\n yield thing\nif __name__ == '__main__':\n for line in tail(sys.stdin,10):\n sys.stdout.write(line)\n</code></pre>\n"
},
{
"answer_id": 23290416,
"author": "Raj",
"author_id": 1283605,
"author_profile": "https://Stackoverflow.com/users/1283605",
"pm_score": 0,
"selected": false,
"text": "<pre><code>This is my version of tailf\n\nimport sys, time, os\n\nfilename = 'path to file'\n\ntry:\n with open(filename) as f:\n size = os.path.getsize(filename)\n if size < 1024:\n s = size\n else:\n s = 999\n f.seek(-s, 2)\n l = f.read()\n print l\n while True:\n line = f.readline()\n if not line:\n time.sleep(1)\n continue\n print line\nexcept IOError:\n pass\n</code></pre>\n"
},
{
"answer_id": 25450971,
"author": "moylop260",
"author_id": 3753497,
"author_profile": "https://Stackoverflow.com/users/3753497",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import time\n\nattemps = 600\nwait_sec = 5\nfname = \"YOUR_PATH\"\n\nwith open(fname, \"r\") as f:\n where = f.tell()\n for i in range(attemps):\n line = f.readline()\n if not line:\n time.sleep(wait_sec)\n f.seek(where)\n else:\n print line, # already has newline\n</code></pre>\n"
},
{
"answer_id": 34029605,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 3,
"selected": false,
"text": "<p>Posting an answer at the behest of commenters on <a href=\"/a/33811809/364696\">my answer to a similar question</a> where the same technique was used to mutate the last line of a file, not just get it.</p>\n\n<p>For a file of significant size, <a href=\"https://docs.python.org/3/library/mmap.html\" rel=\"nofollow noreferrer\"><code>mmap</code></a> is the best way to do this. To improve on the existing <code>mmap</code> answer, this version is portable between Windows and Linux, and should run faster (though it won't work without some modifications on 32 bit Python with files in the GB range, see the <a href=\"/a/33811809/364696\">other answer for hints on handling this, and for modifying to work on Python 2</a>).</p>\n\n<pre><code>import io # Gets consistent version of open for both Py2.7 and Py3.x\nimport itertools\nimport mmap\n\ndef skip_back_lines(mm, numlines, startidx):\n '''Factored out to simplify handling of n and offset'''\n for _ in itertools.repeat(None, numlines):\n startidx = mm.rfind(b'\\n', 0, startidx)\n if startidx < 0:\n break\n return startidx\n\ndef tail(f, n, offset=0):\n # Reopen file in binary mode\n with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:\n # len(mm) - 1 handles files ending w/newline by getting the prior line\n startofline = skip_back_lines(mm, offset, len(mm) - 1)\n if startofline < 0:\n return [] # Offset lines consumed whole file, nothing to return\n # If using a generator function (yield-ing, see below),\n # this should be a plain return, no empty list\n\n endoflines = startofline + 1 # Slice end to omit offset lines\n\n # Find start of lines to capture (add 1 to move from newline to beginning of following line)\n startofline = skip_back_lines(mm, n, startofline) + 1\n\n # Passing True to splitlines makes it return the list of lines without\n # removing the trailing newline (if any), so list mimics f.readlines()\n return mm[startofline:endoflines].splitlines(True)\n # If Windows style \\r\\n newlines need to be normalized to \\n, and input\n # is ASCII compatible, can normalize newlines with:\n # return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\\n').splitlines(True)\n</code></pre>\n\n<p>This assumes the number of lines tailed is small enough you can safely read them all into memory at once; you could also make this a generator function and manually read a line at a time by replacing the final line with:</p>\n\n<pre><code> mm.seek(startofline)\n # Call mm.readline n times, or until EOF, whichever comes first\n # Python 3.2 and earlier:\n for line in itertools.islice(iter(mm.readline, b''), n):\n yield line\n\n # 3.3+:\n yield from itertools.islice(iter(mm.readline, b''), n)\n</code></pre>\n\n<p>Lastly, this read in binary mode (necessary to use <code>mmap</code>) so it gives <code>str</code> lines (Py2) and <code>bytes</code> lines (Py3); if you want <code>unicode</code> (Py2) or <code>str</code> (Py3), the iterative approach could be tweaked to decode for you and/or fix newlines:</p>\n\n<pre><code> lines = itertools.islice(iter(mm.readline, b''), n)\n if f.encoding: # Decode if the passed file was opened with a specific encoding\n lines = (line.decode(f.encoding) for line in lines)\n if 'b' not in f.mode: # Fix line breaks if passed file opened in text mode\n lines = (line.replace(os.linesep, '\\n') for line in lines)\n # Python 3.2 and earlier:\n for line in lines:\n yield line\n # 3.3+:\n yield from lines\n</code></pre>\n\n<p>Note: I typed this all up on a machine where I lack access to Python to test. Please let me know if I typoed anything; this was similar enough to <a href=\"/a/33811809/364696\">my other answer</a> that I <em>think</em> it should work, but the tweaks (e.g. handling an <code>offset</code>) could lead to subtle errors. Please let me know in the comments if there are any mistakes.</p>\n"
},
{
"answer_id": 37176501,
"author": "WorkingRobot",
"author_id": 5662232,
"author_profile": "https://Stackoverflow.com/users/5662232",
"pm_score": -1,
"selected": false,
"text": "<p>Although this isn't really on the efficient side with big files, this code is pretty straight-forward:<br></p>\n\n<ol>\n<li>It reads the file object, <code>f</code>.</li>\n<li>It splits the string returned using newlines, <code>\\n</code>.</li>\n<li><p>It gets the array lists last indexes, using the negative sign to stand for the last indexes, and the <code>:</code> to get a subarray.<br><br></p>\n\n<pre><code>def tail(f,n):\n return \"\\n\".join(f.read().split(\"\\n\")[-n:])\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 37903261,
"author": "GL2014",
"author_id": 2117603,
"author_profile": "https://Stackoverflow.com/users/2117603",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a pretty simple implementation:</p>\n\n<pre><code>with open('/etc/passwd', 'r') as f:\n try:\n f.seek(0,2)\n s = ''\n while s.count('\\n') < 11:\n cur = f.tell()\n f.seek((cur - 10))\n s = f.read(10) + s\n f.seek((cur - 10))\n print s\n except Exception as e:\n f.readlines()\n</code></pre>\n"
},
{
"answer_id": 45960693,
"author": "Emilio",
"author_id": 6183931,
"author_profile": "https://Stackoverflow.com/users/6183931",
"pm_score": 3,
"selected": false,
"text": "<p>Update @papercrane solution to python3.\nOpen the file with <code>open(filename, 'rb')</code> and:</p>\n\n<pre><code>def tail(f, window=20):\n \"\"\"Returns the last `window` lines of file `f` as a list.\n \"\"\"\n if window == 0:\n return []\n\n BUFSIZ = 1024\n f.seek(0, 2)\n remaining_bytes = f.tell()\n size = window + 1\n block = -1\n data = []\n\n while size > 0 and remaining_bytes > 0:\n if remaining_bytes - BUFSIZ > 0:\n # Seek back one whole BUFSIZ\n f.seek(block * BUFSIZ, 2)\n # read BUFFER\n bunch = f.read(BUFSIZ)\n else:\n # file too small, start from beginning\n f.seek(0, 0)\n # only read what was not read\n bunch = f.read(remaining_bytes)\n\n bunch = bunch.decode('utf-8')\n data.insert(0, bunch)\n size -= bunch.count('\\n')\n remaining_bytes -= BUFSIZ\n block -= 1\n\n return ''.join(data).splitlines()[-window:]\n</code></pre>\n"
},
{
"answer_id": 48087596,
"author": "hrehfeld",
"author_id": 876786,
"author_profile": "https://Stackoverflow.com/users/876786",
"pm_score": 2,
"selected": false,
"text": "<p>An even cleaner python3 compatible version that doesn't insert but appends & reverses:</p>\n\n<pre><code>def tail(f, window=1):\n \"\"\"\n Returns the last `window` lines of file `f` as a list of bytes.\n \"\"\"\n if window == 0:\n return b''\n BUFSIZE = 1024\n f.seek(0, 2)\n end = f.tell()\n nlines = window + 1\n data = []\n while nlines > 0 and end > 0:\n i = max(0, end - BUFSIZE)\n nread = min(end, BUFSIZE)\n\n f.seek(i)\n chunk = f.read(nread)\n data.append(chunk)\n nlines -= chunk.count(b'\\n')\n end -= nread\n return b'\\n'.join(b''.join(reversed(data)).splitlines()[-window:])\n</code></pre>\n\n<p>use it like this:</p>\n\n<pre><code>with open(path, 'rb') as f:\n last_lines = tail(f, 3).decode('utf-8')\n</code></pre>\n"
},
{
"answer_id": 49089617,
"author": "Yannis",
"author_id": 1543017,
"author_profile": "https://Stackoverflow.com/users/1543017",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import itertools\nfname = 'log.txt'\noffset = 5\nn = 10\nwith open(fname) as f:\n n_last_lines = list(reversed([x for x in itertools.islice(f, None)][-(offset+1):-(offset+n+1):-1]))\n</code></pre>\n"
},
{
"answer_id": 50894317,
"author": "Kant Manapure",
"author_id": 914457,
"author_profile": "https://Stackoverflow.com/users/914457",
"pm_score": 0,
"selected": false,
"text": "<pre><code>abc = \"2018-06-16 04:45:18.68\"\nfilename = \"abc.txt\"\nwith open(filename) as myFile:\n for num, line in enumerate(myFile, 1):\n if abc in line:\n lastline = num\nprint \"last occurance of work at file is in \"+str(lastline) \n</code></pre>\n"
},
{
"answer_id": 50909127,
"author": "user9956608",
"author_id": 9956608,
"author_profile": "https://Stackoverflow.com/users/9956608",
"pm_score": -1,
"selected": false,
"text": "<p>I found a probably the easiest way to find the first or last N lines of a file</p>\n\n<p><strong>Last N lines of a file(For Ex:N=10)</strong></p>\n\n<pre><code>file=open(\"xyz.txt\",'r\")\nliner=file.readlines()\nfor ran in range((len(liner)-N),len(liner)):\n print liner[ran]\n</code></pre>\n\n<p><strong>First N lines of a file(For Ex:N=10)</strong></p>\n\n<pre><code>file=open(\"xyz.txt\",'r\")\nliner=file.readlines()\nfor ran in range(0,N+1):\n print liner[ran]\n</code></pre>\n"
},
{
"answer_id": 50947562,
"author": "Med sadek",
"author_id": 7450085,
"author_profile": "https://Stackoverflow.com/users/7450085",
"pm_score": -1,
"selected": false,
"text": "<p>it's so simple:</p>\n\n<pre><code>def tail(fname,nl):\nwith open(fname) as f:\n data=f.readlines() #readlines return a list\n print(''.join(data[-nl:]))\n</code></pre>\n"
},
{
"answer_id": 53842743,
"author": "Quinten Cabo",
"author_id": 6767994,
"author_profile": "https://Stackoverflow.com/users/6767994",
"pm_score": 1,
"selected": false,
"text": "<p>There is very useful <a href=\"https://pypi.org/project/file-read-backwards/\" rel=\"nofollow noreferrer\">module</a> that can do this:</p>\n\n<pre><code>from file_read_backwards import FileReadBackwards\n\nwith FileReadBackwards(\"/tmp/file\", encoding=\"utf-8\") as frb:\n\n# getting lines by lines starting from the last line up\nfor l in frb:\n print(l)\n</code></pre>\n"
},
{
"answer_id": 56141523,
"author": "Samba Siva Reddy",
"author_id": 4513845,
"author_profile": "https://Stackoverflow.com/users/4513845",
"pm_score": 2,
"selected": false,
"text": "<p>Simple : </p>\n\n<pre><code>with open(\"test.txt\") as f:\ndata = f.readlines()\ntail = data[-2:]\nprint(''.join(tail)\n</code></pre>\n"
},
{
"answer_id": 57277212,
"author": "itsjwala",
"author_id": 9485283,
"author_profile": "https://Stackoverflow.com/users/9485283",
"pm_score": 1,
"selected": false,
"text": "<p>Update for answer given by <a href=\"https://stackoverflow.com/a/280083/9485283\">A.Coady</a></p>\n\n<p>Works with <strong>python 3</strong>.</p>\n\n<p>This uses <a href=\"https://en.wikipedia.org/wiki/Exponential_search\" rel=\"nofollow noreferrer\">Exponential Search</a> and will buffer only <code>N</code> lines from back and is very efficient.</p>\n\n<pre><code>import time\nimport os\nimport sys\n\ndef tail(f, n):\n assert n >= 0\n pos, lines = n+1, []\n\n # set file pointer to end\n\n f.seek(0, os.SEEK_END)\n\n isFileSmall = False\n\n while len(lines) <= n:\n try:\n f.seek(f.tell() - pos, os.SEEK_SET)\n except ValueError as e:\n # lines greater than file seeking size\n # seek to start\n f.seek(0,os.SEEK_SET)\n isFileSmall = True\n except IOError:\n print(\"Some problem reading/seeking the file\")\n sys.exit(-1)\n finally:\n lines = f.readlines()\n if isFileSmall:\n break\n\n pos *= 2\n\n print(lines)\n\n return lines[-n:]\n\n\n\n\nwith open(\"stream_logs.txt\") as f:\n while(True):\n time.sleep(0.5)\n print(tail(f,2))\n\n</code></pre>\n"
},
{
"answer_id": 58206900,
"author": "Blaine McMahon",
"author_id": 12155298,
"author_profile": "https://Stackoverflow.com/users/12155298",
"pm_score": 0,
"selected": false,
"text": "<p>Another Solution</p>\n\n<p>if your txt file looks like this:\nmouse\nsnake\ncat\nlizard\nwolf\ndog</p>\n\n<p>you could reverse this file by simply using array indexing in python\n'''</p>\n\n<pre><code>contents=[]\ndef tail(contents,n):\n with open('file.txt') as file:\n for i in file.readlines():\n contents.append(i)\n\n for i in contents[:n:-1]:\n print(i)\n\ntail(contents,-5)\n</code></pre>\n\n<p>result: \ndog \nwolf\nlizard\ncat</p>\n"
},
{
"answer_id": 59475149,
"author": "Zhen Wang",
"author_id": 6792401,
"author_profile": "https://Stackoverflow.com/users/6792401",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest way is to use <code>deque</code>:</p>\n\n<pre><code>from collections import deque\n\ndef tail(filename, n=10):\n with open(filename) as f:\n return deque(f, n)\n</code></pre>\n"
},
{
"answer_id": 67232314,
"author": "rish_hyun",
"author_id": 11814875,
"author_profile": "https://Stackoverflow.com/users/11814875",
"pm_score": 0,
"selected": false,
"text": "<p>Well! I had a similar problem, though I only required <strong>LAST LINE ONLY</strong>,\nso I came up with my own solution</p>\n<pre><code>def get_last_line(filepath):\n try:\n with open(filepath,'rb') as f:\n f.seek(-1,os.SEEK_END)\n text = [f.read(1)]\n while text[-1] != '\\n'.encode('utf-8') or len(text)==1:\n f.seek(-2, os.SEEK_CUR)\n text.append(f.read(1))\n except Exception as e:\n pass\n return ''.join([t.decode('utf-8') for t in text[::-1]]).strip()\n</code></pre>\n<p>This function return last string in a file<br>\nI have a log file of 1.27gb and it took very very less time to find the last line (not even half a second)</p>\n"
},
{
"answer_id": 73357932,
"author": "Jacek Błocki",
"author_id": 8365731,
"author_profile": "https://Stackoverflow.com/users/8365731",
"pm_score": 0,
"selected": false,
"text": "<p>Two solutions based on counting '\\n' from file end, tail1 uses memory map, tail2 does not. Speed is similar, both are fast but mmap version is faster. Both functions return last n lines (from n+1 '\\n' to EOF) as string.</p>\n<pre><code>import mmap\ndef tail1(fn, n=5, encoding='utf8'):\n with open(fn) as f:\n mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n nn = len(mm)\n for i in range(n+1):\n nn = mm.rfind(b'\\n',0,nn)\n if nn < 0: break\n return mm[nn:].decode(encoding=encoding).strip()\n\n\ndef tail2(fn, n=5, encoding='utf8'):\n with open(fn,'rb') as f:\n for i in range(f.seek(0, 2), 0, -1):\n _ = f.seek(i)\n if f.read(1) == b'\\n': n -= 1\n if n < 0: break\n return f.read().decode(encoding=encoding).strip()\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19990/"
]
| I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and support an offset. This is hat I came up with:
```
def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
```
Is this a reasonable approach? What is the recommended way to tail log files with offsets? | The code I ended up using. I think this is the best so far:
```
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
``` |
136,172 | <p>I have a single-threaded application that loads several assemblies at runtime using the following:</p>
<pre><code>objDLL = Assembly.LoadFrom(strDLLs[i]);
</code></pre>
<p>I would like the assemblies loaded in this manner to use the same log4net.ILog reference as the rest of the assemblies do. But it appears the runtime loaded assemblies have a different reference altogether and need their own configuration. Does anyone know if a single log4net.ILog can be used across assemblies loaded at runtime using a .NET interface?</p>
<p>Here is the log4net.ILog creation and supporting code in the Program class:</p>
<pre><code> // Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
public static class Program
{
private static log4net.ILog m_Log = null;
[STAThread]
public static void Main(string[] args)
{
try
{
m_Log = log4net.LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
}
}
}
</code></pre>
| [
{
"answer_id": 136305,
"author": "JPrescottSanders",
"author_id": 19444,
"author_profile": "https://Stackoverflow.com/users/19444",
"pm_score": 2,
"selected": false,
"text": "<p>If all your assemblies implement a common interface, then you could have a property or constructor parameter that allows you to pass your local instance of ILog to the dynamically loaded assemblies. </p>\n"
},
{
"answer_id": 136369,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Something about the runtime loaded class prevents the usual one ILog per class from working. I can get a valid ILog instance, but unlike all the other instances it appears not to be configured (all the Is**Enabled flags are set to false). Perhaps the \"root\" logger is not accessible to the classes loaded at runtime???</p>\n"
},
{
"answer_id": 185626,
"author": "Jérôme Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 2,
"selected": false,
"text": "<p>You can get the same logger by specifying a literal logger name string, thus getting the same logger instance.</p>\n\n<pre><code>log4net.LogManager.GetLogger(\"SomeLogger\");\n</code></pre>\n"
},
{
"answer_id": 226240,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have a stupid solution. You can set the XmlConfiguration to the main log4net config file.</p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile=\"<configpath>\",Watch = true)]\n</code></pre>\n\n<p>It is not really beauty .. but it runs.</p>\n"
},
{
"answer_id": 12918460,
"author": "pilotcam",
"author_id": 596098,
"author_profile": "https://Stackoverflow.com/users/596098",
"pm_score": 2,
"selected": false,
"text": "<p>This answer comes 4 years late, but I just encountered the same issue. In my case, I discovered that the assembly that was being loaded (from a different folder than the calling assembly) was also loading its own instance of log4net.</p>\n\n<p>I fixed the issue by deleting the log4net.dll file from the folder where the runtime assembly was being loaded.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a single-threaded application that loads several assemblies at runtime using the following:
```
objDLL = Assembly.LoadFrom(strDLLs[i]);
```
I would like the assemblies loaded in this manner to use the same log4net.ILog reference as the rest of the assemblies do. But it appears the runtime loaded assemblies have a different reference altogether and need their own configuration. Does anyone know if a single log4net.ILog can be used across assemblies loaded at runtime using a .NET interface?
Here is the log4net.ILog creation and supporting code in the Program class:
```
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
public static class Program
{
private static log4net.ILog m_Log = null;
[STAThread]
public static void Main(string[] args)
{
try
{
m_Log = log4net.LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
}
}
}
``` | If all your assemblies implement a common interface, then you could have a property or constructor parameter that allows you to pass your local instance of ILog to the dynamically loaded assemblies. |
136,178 | <p>I'm running <a href="http://www.git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> on a file, but the change is at the end of a long line.</p>
<p>If I use cursor keys to move right, it loses colour-coding—and worse the lines don't line up—making it harder to track the change.</p>
<p>Is there a way to prevent that problem or to simply make the lines wrap instead?</p>
<p>I'm running Git 1.5.5 via mingw32.</p>
| [
{
"answer_id": 136396,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 2,
"selected": false,
"text": "<p>Not a perfect solution, but <code>gitk</code> and <code>git-gui</code> can both show this information,\nand have scrollbars.</p>\n"
},
{
"answer_id": 138989,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": -1,
"selected": false,
"text": "<p>When in trouble, I often resort to DiffMerge. Excellent diff tool that has in-line diff highlighting. Also, in the latest versions they added a mode to have an horizontal mode.</p>\n\n<p>I haven't been able to configure git to use it, though. So I do have to muck around to get both versions of the file first. </p>\n"
},
{
"answer_id": 152546,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 8,
"selected": true,
"text": "<p>The display of the output of <code>git diff</code> is handled by whatever pager you are using.</p>\n\n<p>Commonly, under Linux, <code>less</code> would be used.</p>\n\n<p>You can tell git to use a different pager by setting the <code>GIT_PAGER</code> environment variable. If you don't mind about paging (for example, your terminal allows you to scroll back) you might try explicitly setting <code>GIT_PAGER</code> to empty to stop it using a pager. Under Linux:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ GIT_PAGER='' git diff\n</code></pre>\n\n<p>Without a pager, the lines will wrap.</p>\n\n<p>If your terminal doesn't support coloured output, you can also turn this off using either the <code>--no-color</code> argument, or putting an entry in the color section of your git config file.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ GIT_PAGER='' git diff --no-color\n</code></pre>\n"
},
{
"answer_id": 891173,
"author": "singingfish",
"author_id": 36499,
"author_profile": "https://Stackoverflow.com/users/36499",
"pm_score": 4,
"selected": false,
"text": "<p>Just googled up this one. <code>GIT_PAGER='less -r'</code> works for me</p>\n"
},
{
"answer_id": 3107807,
"author": "someone45",
"author_id": 374967,
"author_profile": "https://Stackoverflow.com/users/374967",
"pm_score": 8,
"selected": false,
"text": "<p>Or if you use less as default pager just type <code>-S</code> while viewing the diff to reenable wrapping in less.</p>\n"
},
{
"answer_id": 3673836,
"author": "Shoan",
"author_id": 17404,
"author_profile": "https://Stackoverflow.com/users/17404",
"pm_score": 7,
"selected": false,
"text": "<p>You can also use <code>git config</code> to setup pager to wrap.</p>\n\n<pre><code>$ git config core.pager 'less -r' \n</code></pre>\n\n<p>Sets the pager setting for the current project.</p>\n\n<pre><code>$ git config --global core.pager 'less -r' \n</code></pre>\n\n<p>Sets the pager globally for all projects</p>\n"
},
{
"answer_id": 6103533,
"author": "John Lemberger",
"author_id": 2882,
"author_profile": "https://Stackoverflow.com/users/2882",
"pm_score": 4,
"selected": false,
"text": "<p>Mac OSX: None of the other answers except someone45's '-S' while less is running worked for me. It took the following to make word-wrap persistent:</p>\n\n<pre><code>git config --global core.pager 'less -+$LESS -FRX'\n</code></pre>\n"
},
{
"answer_id": 12499930,
"author": "Daniel Montezano",
"author_id": 1683826,
"author_profile": "https://Stackoverflow.com/users/1683826",
"pm_score": 5,
"selected": false,
"text": "<p>To use less as the pager and make line wrapping permanent you can simply enable the fold-long-lines option:</p>\n\n<pre><code>git config --global core.pager 'less -+S'\n</code></pre>\n\n<p>This way you do not have to type it while using less.</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 17597024,
"author": "AnonTidbits",
"author_id": 2573232,
"author_profile": "https://Stackoverflow.com/users/2573232",
"pm_score": 2,
"selected": false,
"text": "<p>You could simply pipe the output of git diff to more:</p>\n\n<pre><code>git diff | more\n</code></pre>\n"
},
{
"answer_id": 19253759,
"author": "lindes",
"author_id": 313756,
"author_profile": "https://Stackoverflow.com/users/313756",
"pm_score": 6,
"selected": false,
"text": "<p>With full credit to <a href=\"https://stackoverflow.com/users/187812/josh-diehl\">Josh Diehl</a> in <a href=\"https://stackoverflow.com/questions/136178/git-diff-handling-long-lines/3107807#comment18876094_3107807\">a comment</a> to <a href=\"https://stackoverflow.com/a/3107807/313756\">this answer</a>, I nevertheless feel like this ought to be an answer unto itself, so adding it:</p>\n<p>One way to deal with seeing differences in long lines is to use a word-oriented diff. This can be done with:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>git diff --word-diff\n</code></pre>\n<p>In this case, you'll get a significantly different diff output, that shows you specifically what has changed within a line.</p>\n<p>For example, instead of getting something like this:</p>\n<pre><code>diff --git a/test-file.txt b/test-file.txt\nindex 19e6adf..eb6bb81 100644\n--- a/test-file.txt\n+++ b/test-file.txt\n@@ -1 +1 @@\n-this is a short line\n+this is a slightly longer line\n</code></pre>\n<p>You might get something like this:</p>\n<pre><code>diff --git a/test-file.txt b/test-file.txt\nindex 19e6adf..eb6bb81 100644\n--- a/test-file.txt\n+++ b/test-file.txt\n@@ -1 +1 @@\nthis is a [-short-]{+slightly longer+} line\n</code></pre>\n<p>Or, with colorization, instead of this:</p>\n<p><img src=\"https://i.stack.imgur.com/SdK0E.png\" alt=\"result of just git diff\" /></p>\n<p>You might get this:</p>\n<p><img src=\"https://i.stack.imgur.com/iYZut.png\" alt=\"result of git diff --word-diff\" /></p>\n<p>Now, if you're comparing a really long line, you may still have issues with the pager situation you originally described, and which has been addressed, apparently to satisfaction, in other answers. Hopefully this gives you a new tool, though, to more easily identify what on the line has changed.</p>\n"
},
{
"answer_id": 23643093,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 4,
"selected": false,
"text": "<p>Since Git 1.5.3\n(<a href=\"http://github.com/git/git/commit/463a849\" rel=\"noreferrer\">Sep 2007</a>)</p>\n\n<p>a <code>--no-pager</code> option has been available.</p>\n\n<pre><code>git --no-pager diff\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/2183900/#2183920\">How do I prevent git diff from using a pager?</a></p>\n\n<p><a href=\"http://git.661346.n2.nabble.com/git-log-follow-doesn-t-follow-a-rename-over-a-merge-td6480971.html\" rel=\"noreferrer\">Example</a></p>\n\n<p>Starting with v2.1, wrap is the default</p>\n\n<p><a href=\"http://github.com/git/git/blob/50f84e3/Documentation/RelNotes/2.1.0.txt#L30-L37\" rel=\"noreferrer\">Git v2.1 Release Notes</a></p>\n"
},
{
"answer_id": 35142708,
"author": "user5870226",
"author_id": 5870226,
"author_profile": "https://Stackoverflow.com/users/5870226",
"pm_score": 1,
"selected": false,
"text": "<p>list the current/default config: </p>\n\n<pre><code> $ git config --global core.pager \n less -FXRS -x2\n</code></pre>\n\n<p>then update and leave out the -S like: </p>\n\n<pre><code> $ git config --global core.pager 'less -FXR -x2'\n</code></pre>\n\n<p>the -S: Causes lines longer than the screen width to be chopped rather than folded.</p>\n"
},
{
"answer_id": 35352049,
"author": "Thomson Comer",
"author_id": 498629,
"author_profile": "https://Stackoverflow.com/users/498629",
"pm_score": 3,
"selected": false,
"text": "<p>Eight years later I find a superior answer, from <a href=\"https://superuser.com/questions/777617/line-wrapping-less-in-os-x-specifically-for-use-with-git-diff\">https://superuser.com/questions/777617/line-wrapping-less-in-os-x-specifically-for-use-with-git-diff</a>:</p>\n\n<pre><code>git config core.pager `fold -w 80 | less`\n</code></pre>\n\n<p>Now you pipe the git diff through fold, first, then to less: wrapped, less page-height is correct, keep syntax highlighting.</p>\n"
},
{
"answer_id": 38125882,
"author": "infoclogged",
"author_id": 1534898,
"author_profile": "https://Stackoverflow.com/users/1534898",
"pm_score": 3,
"selected": false,
"text": "<p>Noone pointed out this till now. Its quite simple to remember and no extra configuration needs to be done in the git config</p>\n\n<pre><code>git diff --color | less -R\n</code></pre>\n"
},
{
"answer_id": 42740070,
"author": "Amin",
"author_id": 5342604,
"author_profile": "https://Stackoverflow.com/users/5342604",
"pm_score": 3,
"selected": false,
"text": "<p>When you are using \"git diff\" and it's showing several pages(you see \":\" at the end of the page)in this case you can type \"-S\" and press enter.(S should be capital). it will toggle fold long lines.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9360/"
]
| I'm running [git-diff](http://www.git-scm.com/docs/git-diff) on a file, but the change is at the end of a long line.
If I use cursor keys to move right, it loses colour-coding—and worse the lines don't line up—making it harder to track the change.
Is there a way to prevent that problem or to simply make the lines wrap instead?
I'm running Git 1.5.5 via mingw32. | The display of the output of `git diff` is handled by whatever pager you are using.
Commonly, under Linux, `less` would be used.
You can tell git to use a different pager by setting the `GIT_PAGER` environment variable. If you don't mind about paging (for example, your terminal allows you to scroll back) you might try explicitly setting `GIT_PAGER` to empty to stop it using a pager. Under Linux:
```sh
$ GIT_PAGER='' git diff
```
Without a pager, the lines will wrap.
If your terminal doesn't support coloured output, you can also turn this off using either the `--no-color` argument, or putting an entry in the color section of your git config file.
```sh
$ GIT_PAGER='' git diff --no-color
``` |
136,191 | <p>Let's say I want to write a regular expression to change all <code><abc></code>, <code><def></code>, and <code><ghi></code> tags into <code><xyz></code> tags.. and I also want to change their closing tags to <code></xyz></code>. This seems like a reasonable regex (ignore the backticks; StackOverflow has trouble with the less-than signs if I don't include them):</p>
<pre><code>`s!<(/)?(abc|def|ghi)>!<${1}xyz>!g;`
</code></pre>
<p>And it works, too. The only problem is that for opening tags, the optional $1 variable gets assigned undef, and so I get a "Use of uninitialized value..." warning.</p>
<p>What's an elegant way to fix this? I'd rather not make this into two separate regexs, one for opening tags and another for closing tags, because then there are two copies of the taglist that need to be maintained, instead of just one.</p>
<p><strong>Edit:</strong> I know I could just turn off warnings in this region of the code, but I don't consider that "elegant".</p>
| [
{
"answer_id": 136267,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 1,
"selected": false,
"text": "<p>You could just make your first match be <code>(</?)</code>, and get rid of the hard-coded <code><</code> on the \"replace\" side. Then $1 would always have either <code><</code> or <code></</code>. There may be more elegant solutions to address the warning issue, but this one should handle the practical problem.</p>\n"
},
{
"answer_id": 136268,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 1,
"selected": false,
"text": "<p>Here is one way:</p>\n\n<pre><code> s!<(/?)(abc|def|ghi)>!<$1xyz>!g;\n</code></pre>\n\n<p>Update: Removed irrelevant comment about using <code>(?:pattern)</code>.</p>\n"
},
{
"answer_id": 136274,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": -1,
"selected": false,
"text": "<p>Add</p>\n\n<pre><code>no warnings 'uninitialized';\n</code></pre>\n\n<p>or</p>\n\n<pre><code>s!<(/)?(abc|def|ghi)>! join '', '<', ${1}||'', 'xyz>' !ge;\n</code></pre>\n"
},
{
"answer_id": 136275,
"author": "mitchnull",
"author_id": 18645,
"author_profile": "https://Stackoverflow.com/users/18645",
"pm_score": 2,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>`s!(</?)(abc|def|ghi)>!${1}xyz>!g;`\n</code></pre>\n"
},
{
"answer_id": 136281,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 0,
"selected": false,
"text": "<p>To make the regex capture $1 in either case, try:</p>\n\n<pre><code> s!<(/|)?(abc|def|ghi)>!<${1}xyz>!g;\n ^\n note the pipe symbol, meaning '/' or ''\n</code></pre>\n\n<p>For '' this will capture the '' between '<' and 'abc>', and for '', capture '/' between '<' and 'abc>'.</p>\n"
},
{
"answer_id": 136317,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 4,
"selected": true,
"text": "<p>Move the question mark inside the capturing bracket. That way $1 will always be defined, but may be a zero-length string.</p>\n"
},
{
"answer_id": 136343,
"author": "Robᵩ",
"author_id": 8747,
"author_profile": "https://Stackoverflow.com/users/8747",
"pm_score": 1,
"selected": false,
"text": "<p><code>s!<(/?)(abc|def|ghi)>!<${1}xyz>!g;</code></p>\n\n<p>The only difference is changing \"(/)?\" to \"(/?)\". You have already identified several functional solution. This one has the elegance you asked for, I think.</p>\n"
},
{
"answer_id": 138328,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I'd rather not make this into two\n separate regexs, one for opening tags\n and another for closing tags, because\n then there are two copies of the\n taglist that need to be maintained</p>\n</blockquote>\n\n<p>Why? Put your taglist into a variable and interpolate that variable into as many regexes as you like. I'd consider this even whith a single regex because it's much more readable with a complicated regex (and what regex isn't complicated?).</p>\n"
},
{
"answer_id": 143459,
"author": "theorbtwo",
"author_id": 4839,
"author_profile": "https://Stackoverflow.com/users/4839",
"pm_score": 0,
"selected": false,
"text": "<p>Be careful in as much as HTML is a bit harder then it looks to be at first glance. For example, do you want to change \"<abc foo='bar'>\" to \"<xyz foo='bar'>\"? Your regex won't. Do you want to change \"<img alt='<abc>'>\"? The regex will. Instead, you might want to do something like this:</p>\n\n<pre><code>use HTML::TreeBuilder;\nmy $tree=HTML::TreeBuilder->new_from_content(\"<abc>asdf</abc>\");\nfor my $tag (qw<abc def ghi>) {\n for my $elem ($tree->look_down(_tag => $tag)) {\n $elem->tag('xyz');\n }\n}\nprint $tree->as_HTML;\n</code></pre>\n\n<p>That keeps you from having to do the fiddly bits of parsing HTML yourself.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| Let's say I want to write a regular expression to change all `<abc>`, `<def>`, and `<ghi>` tags into `<xyz>` tags.. and I also want to change their closing tags to `</xyz>`. This seems like a reasonable regex (ignore the backticks; StackOverflow has trouble with the less-than signs if I don't include them):
```
`s!<(/)?(abc|def|ghi)>!<${1}xyz>!g;`
```
And it works, too. The only problem is that for opening tags, the optional $1 variable gets assigned undef, and so I get a "Use of uninitialized value..." warning.
What's an elegant way to fix this? I'd rather not make this into two separate regexs, one for opening tags and another for closing tags, because then there are two copies of the taglist that need to be maintained, instead of just one.
**Edit:** I know I could just turn off warnings in this region of the code, but I don't consider that "elegant". | Move the question mark inside the capturing bracket. That way $1 will always be defined, but may be a zero-length string. |
136,195 | <p>We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser. </p>
<p>We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object. </p>
<p>However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:</p>
<pre><code><HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT type="text/javascript">
var field = 'hello world';
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="See field" onclick="javascript:alert(field);"/>
</BODY>
</HTML>
</code></pre>
<p>We want to access the <em>field</em> variable and assign a value to it. In VB6 the code for this was pretty straightforward:</p>
<pre><code>doc.Script.field = 'newValue'
</code></pre>
<p>However, in C# we've had to resort to other tricks, like this: </p>
<pre><code>Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null);
</code></pre>
<p>The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".</p>
<p>That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable <code>field</code>. </p>
<p>Has anyone had any experience doing this type of operation before?</p>
| [
{
"answer_id": 136213,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 0,
"selected": false,
"text": "<p>The usual method we use is to add a hidden text input box (the ASP.Net control version) on the page. That way you can easily set its value in the C# codebehind and read the value in client side JavaScript (and vice-versa, of course).</p>\n"
},
{
"answer_id": 141381,
"author": "Esteban Brenes",
"author_id": 14177,
"author_profile": "https://Stackoverflow.com/users/14177",
"pm_score": 3,
"selected": true,
"text": "<p>These two articles helped us find a solution to our problem. They outline the basics of what one needs to know:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/mshtml_automation.aspx\" rel=\"nofollow noreferrer\">Microsoft Web Browser Automation using C#</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/advhost.aspx?target=idochostuihandler\" rel=\"nofollow noreferrer\">Using MSHTML Advanced Hosting Interfaces</a></p>\n\n<p>So we implemented a DocHostUIHandler interface and that allowed us to set a UIHandler, allowing us to reference the method from Javascript.</p>\n"
},
{
"answer_id": 200168,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 2,
"selected": false,
"text": "<p>If you use the webBrowser control, you can assign a c# object to the \nobjectForScripting property\n<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx</a></p>\n\n<p>after that you can use window.external in your javascript to interact with your c# object from javascript</p>\n\n<p>if you use an activeX version for some reason, you can pass javascript: urls to programmatically sets your variable, or you can syncronize your script using a webservice/ database/file or simply using the method you suggested.</p>\n"
},
{
"answer_id": 1763769,
"author": "EndangeringSpecies",
"author_id": 208334,
"author_profile": "https://Stackoverflow.com/users/208334",
"pm_score": 3,
"selected": false,
"text": "<p>I think what you are looking for is the <code>eval()</code> method in Javascript. You can call it from C# like this:</p>\n\n<pre><code>webBrowser1.Document.InvokeScript(\"eval\", new String[] {\"1 + 2\"});\n</code></pre>\n\n<p>This code will evaluate <code>\"1 + 2\"</code> and return <code>\"3\"</code>. I would imagine that if you were to put in</p>\n\n<pre><code>InvokeScript(\"eval\", new String[] {\"varName = 3\"})\n</code></pre>\n\n<p>you would get that variable assigned to 3 if it is globally visible in the file.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14177/"
]
| We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser.
We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object.
However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:
```
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT type="text/javascript">
var field = 'hello world';
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="See field" onclick="javascript:alert(field);"/>
</BODY>
</HTML>
```
We want to access the *field* variable and assign a value to it. In VB6 the code for this was pretty straightforward:
```
doc.Script.field = 'newValue'
```
However, in C# we've had to resort to other tricks, like this:
```
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null);
```
The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".
That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable `field`.
Has anyone had any experience doing this type of operation before? | These two articles helped us find a solution to our problem. They outline the basics of what one needs to know:
[Microsoft Web Browser Automation using C#](http://www.codeproject.com/KB/cs/mshtml_automation.aspx)
[Using MSHTML Advanced Hosting Interfaces](http://www.codeproject.com/KB/cs/advhost.aspx?target=idochostuihandler)
So we implemented a DocHostUIHandler interface and that allowed us to set a UIHandler, allowing us to reference the method from Javascript. |
136,204 | <p>Not really getting the point of the map function. Can anyone explain with examples its use?</p>
<p>Are there any performance benefits to using this instead of a loop or is it just sugar?</p>
| [
{
"answer_id": 136228,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 7,
"selected": true,
"text": "<p>Any time you want to generate a list based another list:</p>\n\n<pre><code># Double all elements of a list\nmy @double = map { $_ * 2 } (1,2,3,4,5);\n# @double = (2,4,6,8,10);\n</code></pre>\n\n<p>Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute:</p>\n\n<pre><code># @user_objects is a list of objects having a unique_id() method\nmy %users = map { $_->unique_id() => $_ } @user_objects;\n# %users = ( $id => $obj, $id => $obj, ...);\n</code></pre>\n\n<p>It's a really general purpose tool, you have to just start using it to find good uses in your applications. </p>\n\n<p>Some might prefer verbose looping code for readability purposes, but personally, I find <code>map</code> more readable.</p>\n"
},
{
"answer_id": 136242,
"author": "Craig H",
"author_id": 2328,
"author_profile": "https://Stackoverflow.com/users/2328",
"pm_score": 3,
"selected": false,
"text": "<p>The map function runs an expression on each element of a list, and returns the list results. Lets say I had the following list</p>\n\n<pre><code>@names = (\"andrew\", \"bob\", \"carol\" );\n</code></pre>\n\n<p>and I wanted to capitalize the first letter of each of these names. I could loop through them and call ucfirst of each element, or I could just do the following</p>\n\n<pre><code>@names = map (ucfirst, @names);\n</code></pre>\n"
},
{
"answer_id": 136248,
"author": "axblount",
"author_id": 1729005,
"author_profile": "https://Stackoverflow.com/users/1729005",
"pm_score": 2,
"selected": false,
"text": "<p>It's used anytime you would like to create a new list from an existing list.</p>\n\n<p>For instance you could map a parsing function on a list of strings to convert them to integers.</p>\n"
},
{
"answer_id": 136295,
"author": "AndrewJFord",
"author_id": 6154,
"author_profile": "https://Stackoverflow.com/users/6154",
"pm_score": 2,
"selected": false,
"text": "<p>To paraphrase \"Effective Perl Programming\" by Hall & Schwartz,\nmap can be abused, but I think that it's best used to create a new list from an existing list.</p>\n\n<p>Create a list of the squares of 3,2, & 1:</p>\n\n<pre><code>@numbers = (3,2,1);\n@squares = map { $_ ** 2 } @numbers;\n</code></pre>\n"
},
{
"answer_id": 136327,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": false,
"text": "<p>See also the <a href=\"http://en.wikipedia.org/wiki/Schwartzian_transform\" rel=\"noreferrer\">Schwartzian transform</a> for advanced usage of map.</p>\n"
},
{
"answer_id": 136331,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 4,
"selected": false,
"text": "<p>It's also handy for making lookup hashes:</p>\n\n<pre><code>my %is_boolean = map { $_ => 1 } qw(true false);\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>my %is_boolean = ( true => 1, false => 1 );\n</code></pre>\n\n<p>There's not much savings there, but suppose you wanted to define <code>%is_US_state</code>?</p>\n"
},
{
"answer_id": 136342,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>Generate password:</p>\n\n<pre><code>$ perl -E'say map {chr(32 + 95 * rand)} 1..16'\n# -> j'k=$^o7\\l'yi28G\n</code></pre>\n"
},
{
"answer_id": 136363,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 5,
"selected": false,
"text": "<p>The <code>map</code> function is used to transform lists. It's basically syntactic sugar for replacing certain types of <code>for[each]</code> loops. Once you wrap your head around it, you'll see uses for it everywhere:</p>\n<pre><code>my @uppercase = map { uc } @lowercase;\nmy @hex = map { sprintf "0x%x", $_ } @decimal;\nmy %hash = map { $_ => 1 } @array;\nsub join_csv { join ',', map {'"' . $_ . '"' } @_ }\n</code></pre>\n"
},
{
"answer_id": 136383,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 5,
"selected": false,
"text": "<p>First of all, it's a simple way of transforming an array: rather than saying e.g.</p>\n\n<pre><code>my @raw_values = (...);\nmy @derived_values;\nfor my $value (@raw_values) {\n push (@derived_values, _derived_value($value));\n}\n</code></pre>\n\n<p>you can say</p>\n\n<pre><code>my @raw_values = (...);\nmy @derived_values = map { _derived_value($_) } @raw_values;\n</code></pre>\n\n<p>It's also useful for building up a quick lookup table: rather than e.g.</p>\n\n<pre><code>my $sentence = \"...\";\nmy @stopwords = (...);\nmy @foundstopwords;\nfor my $word (split(/\\s+/, $sentence)) {\n for my $stopword (@stopwords) {\n if ($word eq $stopword) {\n push (@foundstopwords, $word);\n }\n }\n}\n</code></pre>\n\n<p>you could say</p>\n\n<pre><code>my $sentence = \"...\";\nmy @stopwords = (...);\nmy %is_stopword = map { $_ => 1 } @stopwords;\nmy @foundstopwords = grep { $is_stopword{$_} } split(/\\s+/, $sentence);\n</code></pre>\n\n<p>It's also useful if you want to derive one list from another, but don't particularly need to have a temporary variable cluttering up the place, e.g. rather than</p>\n\n<pre><code>my %params = ( username => '...', password => '...', action => $action );\nmy @parampairs;\nfor my $param (keys %params) {\n push (@parampairs, $param . '=' . CGI::escape($params{$param}));\n}\nmy $url = $ENV{SCRIPT_NAME} . '?' . join('&amp;', @parampairs);\n</code></pre>\n\n<p>you say the much simpler</p>\n\n<pre><code>my %params = ( username => '...', password => '...', action => $action );\nmy $url = $ENV{SCRIPT_NAME} . '?'\n . join('&amp;', map { $_ . '=' . CGI::escape($params{$_}) } keys %params);\n</code></pre>\n\n<p>(Edit: fixed the missing \"keys %params\" in that last line)</p>\n"
},
{
"answer_id": 136609,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 2,
"selected": false,
"text": "<p>You use map to transform a list and assign the results to another list, grep to filter a list and assign the results to another list. The \"other\" list can be the same variable as the list you are transforming/filtering.</p>\n\n<pre><code>my @array = ( 1..5 );\n@array = map { $_+5 } @array;\nprint \"@array\\n\";\n@array = grep { $_ < 7 } @array;\nprint \"@array\\n\";\n</code></pre>\n"
},
{
"answer_id": 136693,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "<p>It allows you to transform a list as an <em>expression</em> rather than in <em>statements</em>. Imagine a hash of soldiers defined like so: </p>\n\n<pre><code>{ name => 'John Smith'\n, rank => 'Lieutenant'\n, serial_number => '382-293937-20'\n};\n</code></pre>\n\n<p>then you can operate on the list of names separately.</p>\n\n<p>For example,</p>\n\n<pre><code>map { $_->{name} } values %soldiers\n</code></pre>\n\n<p>is an <em>expression</em>. It can go anywhere an expression is allowed--except you can't assign to it. </p>\n\n<pre><code>${[ sort map { $_->{name} } values %soldiers ]}[-1]\n</code></pre>\n\n<p>indexes the array, taking the max. </p>\n\n<pre><code>my %soldiers_by_sn = map { $->{serial_number} => $_ } values %soldiers;\n</code></pre>\n\n<p>I find that one of the advantages of operational expressions is that it cuts down on the bugs that come from temporary variables. </p>\n\n<p>If Mr. McCoy wants to filter out all the Hatfields for consideration, you can add that check with minimal coding. </p>\n\n<pre><code>my %soldiers_by_sn \n = map { $->{serial_number}, $_ } \n grep { $_->{name} !~ m/Hatfield$/ } \n values %soldiers\n ;\n</code></pre>\n\n<p>I can continue chaining these expression so that if my interaction with this data has to reach deep for a particular purpose, I don't have to write a lot of code that pretends I'm going to do a lot more. </p>\n"
},
{
"answer_id": 137617,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 3,
"selected": false,
"text": "<p>The map function is an idea from the functional programming paradigm. In functional programming, functions are first-class objects, meaning that they can be passed as arguments to other functions. Map is a simple but a very useful example of this. It takes as its arguments a function (lets call it <code>f</code>) and a list <code>l</code>. <code>f</code> has to be a function taking one argument, and map simply applies <code>f</code> to every element of the list <code>l</code>. <code>f</code> can do whatever you need done to every element: add one to every element, square every element, write every element to a database, or open a web browser window for every element, which happens to be a valid URL.</p>\n\n<p>The advantage of using <code>map</code> is that it nicely encapsulates iterating over the elements of the list. All you have to do is say \"do <code>f</code> to every element, and it is up to <code>map</code> to decide how best to do that. For example <code>map</code> may be implemented to split up its work among multiple threads, and it would be totally transparent to the caller.</p>\n\n<p>Note, that <code>map</code> is not at all specific to Perl. It is a standard technique used by functional languages. It can even be implemented in C using function pointers, or in C++ using \"function objects\".</p>\n"
},
{
"answer_id": 138362,
"author": "kixx",
"author_id": 11260,
"author_profile": "https://Stackoverflow.com/users/11260",
"pm_score": 4,
"selected": false,
"text": "<p><strong>map</strong> is used to create a list by transforming the elements of another list.</p>\n<p><strong>grep</strong> is used to create a list by filtering elements of another list.</p>\n<p><strong>sort</strong> is used to create a list by sorting the elements of another list.</p>\n<p>Each of these operators receives a code block (or an expression) which is used to transform, filter or compare elements of the list.</p>\n<p>For <strong>map</strong>, the result of the block becomes one (or more) element(s) in the new list. The current element is aliased to $_.</p>\n<p>For <strong>grep</strong>, the boolean result of the block decides if the element of the original list will be copied into the new list. The current element is aliased to $_.</p>\n<p>For <strong>sort</strong>, the block receives two elements (aliased to $a and $b) and is expected to return one of -1, 0 or 1, indicating whether $a is greater, equal or less than $b.</p>\n<p>The <a href=\"http://en.wikipedia.org/wiki/Schwartzian_transform\" rel=\"nofollow noreferrer\">Schwartzian Transform</a> uses these operators to efficiently cache values (properties) to be used in sorting a list, especially when computing these properties has a non-trivial cost.</p>\n<p>It works by creating an intermediate array which has as elements array references with the original element and the computed value by which we want to sort. This array is passed to sort, which compares the already computed values, creating another intermediate array (this one is sorted) which in turn is passed to another map which throws away the cached values, thus restoring the array to its initial list elements (but in the desired order now).</p>\n<p>Example (creates a list of files in the current directory sorted by the time of their last modification):</p>\n<pre><code>@file_list = glob('*');\n@file_modify_times = map { [ $_, (stat($_))[8] ] } @file_list;\n@files_sorted_by_mtime = sort { $a->[1] <=> $b->[1] } @file_modify_times;\n@sorted_files = map { $_->[0] } @files_sorted_by_mtime;\n</code></pre>\n<p>By chaining the operators together, no declaration of variables is needed for the intermediate arrays;</p>\n<pre><code>@sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, (stat($_))[8] ] } glob('*');\n</code></pre>\n<p>You can also filter the list before sorting by inserting a <strong>grep</strong> (if you want to filter on the same cached value):</p>\n<p>Example (a list of the files modified in the last 24 hours sorted the last modification time):</p>\n<pre><code> @sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } grep { $_->[1] > (time - 24 * 3600 } map { [ $_, (stat($_))[8] ] } glob('*');\n</code></pre>\n"
},
{
"answer_id": 140475,
"author": "jimtut",
"author_id": 13563,
"author_profile": "https://Stackoverflow.com/users/13563",
"pm_score": 1,
"selected": false,
"text": "<p>As others have said, map creates lists from lists. Think of \"mapping\" the contents of one list into another. Here's some code from a CGI program to take a list of patent numbers and print hyperlinks to the patent applications:</p>\n\n<pre><code>my @patents = ('7,120,721', '6,809,505', '7,194,673');\nprint join(\", \", map { \"<a href=\\\"http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=/netahtml/srchnum.htm&r=0&f=S&l=50&TERM1=$_\\\">$_</a>\" } @patents);\n</code></pre>\n"
},
{
"answer_id": 153853,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 1,
"selected": false,
"text": "<p><p>As others have said, map is most useful for transforming a list. What hasn't been mentioned is the difference between map and an \"equivalent\" for loop.\n<p>One difference is that for doesn't work well for an expression that modifies the list its iterating over. One of these terminates, and the other doesn't:</p>\n\n<pre><code>perl -e '@x=(\"x\"); map { push @x, $_ } @x'\nperl -e '@x=(\"x\"); push @x, $_ for @x'\n</code></pre>\n\n<p><p>Another small difference is that the <em>context</em> inside the map block is a list context, but the for loop imparts a void context.</p>\n"
},
{
"answer_id": 449477,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 3,
"selected": false,
"text": "<p>\"Just sugar\" is harsh. Remember, a loop is just sugar -- if's and goto can do everything loop constructs do and more.</p>\n\n<p>Map is a high enough level function that it helps you hold much more complex operations in your head, so you can code and debug bigger problems.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
| Not really getting the point of the map function. Can anyone explain with examples its use?
Are there any performance benefits to using this instead of a loop or is it just sugar? | Any time you want to generate a list based another list:
```
# Double all elements of a list
my @double = map { $_ * 2 } (1,2,3,4,5);
# @double = (2,4,6,8,10);
```
Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute:
```
# @user_objects is a list of objects having a unique_id() method
my %users = map { $_->unique_id() => $_ } @user_objects;
# %users = ( $id => $obj, $id => $obj, ...);
```
It's a really general purpose tool, you have to just start using it to find good uses in your applications.
Some might prefer verbose looping code for readability purposes, but personally, I find `map` more readable. |
136,233 | <p>in tcsh I'm trying to redirect STDERR from a command from my .aliases file.</p>
<p>I found that I can redirect STDERR from the command line like this. . .</p>
<pre><code>$ (xemacs > /dev/tty) >& /dev/null
</code></pre>
<p>. . . but when I put this in my .aliases file I get an alias loop. . .</p>
<pre><code>$ cat .aliases
alias xemacs '(xemacs > /dev/tty ) >& /dev/null'
$ xemacs &
Alias loop.
$
</code></pre>
<p>. . . so I put a backslash before the command in .aliases, which allows the command to run. . .</p>
<pre><code>$ cat .aliases
alias xemacs '(\xemacs > /dev/tty ) >& /dev/null'
$ xemacs &
[1] 17295
$
</code></pre>
<p>. . . but now I can't give the command any arguments:</p>
<pre><code>$ xemacs foo.txt &
Badly placed ()'s.
[1] Done ( \xemacs > /dev/tty ) >& /dev/null
$
</code></pre>
<p>Can anyone offer any solutions? Thank you in advance!</p>
<hr>
<p>UPDATE: I'm still curious if it's possible to redirect STDERR in tcsh from .aliases, but as has been suggested here, I ended up with a shell script:</p>
<pre><code>#!/bin/sh
# wrapper script to suppress messages sent to STDERR on launch
# from the command line.
/usr/bin/xemacs "$@" 2>/dev/null
</code></pre>
| [
{
"answer_id": 136313,
"author": "Dominic Eidson",
"author_id": 5042,
"author_profile": "https://Stackoverflow.com/users/5042",
"pm_score": 4,
"selected": true,
"text": "<p>I suspect this is a case where NOT using an alias is the best option - try using a shell script instead:</p>\n\n<pre><code>#!/bin/tcsh\n\n(xemacs $* > /dev/tty ) >& /dev/null\n</code></pre>\n"
},
{
"answer_id": 307638,
"author": "J. A. Faucett",
"author_id": 18503,
"author_profile": "https://Stackoverflow.com/users/18503",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>alias emacs '(\\emacs \\!* > /dev/tty) >& /dev/null'\n</code></pre>\n\n<p>The \"badly placed ()'s\" message comes from misplacing the input parameter to emacs. Without the \"<code>\\!*</code>\" in the alias definition, \"<code>emacs abc</code>\" becomes </p>\n\n<pre><code>(/usr/bin/emacs > /dev/tty) >& /dev/null abc\n</code></pre>\n\n<p>With the \"<code>\\!*</code>\" included, \"<code>emacs abc</code>\" becomes </p>\n\n<pre><code>(/usr/bin/emacs abc > /dev/tty) >& /dev/null\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| in tcsh I'm trying to redirect STDERR from a command from my .aliases file.
I found that I can redirect STDERR from the command line like this. . .
```
$ (xemacs > /dev/tty) >& /dev/null
```
. . . but when I put this in my .aliases file I get an alias loop. . .
```
$ cat .aliases
alias xemacs '(xemacs > /dev/tty ) >& /dev/null'
$ xemacs &
Alias loop.
$
```
. . . so I put a backslash before the command in .aliases, which allows the command to run. . .
```
$ cat .aliases
alias xemacs '(\xemacs > /dev/tty ) >& /dev/null'
$ xemacs &
[1] 17295
$
```
. . . but now I can't give the command any arguments:
```
$ xemacs foo.txt &
Badly placed ()'s.
[1] Done ( \xemacs > /dev/tty ) >& /dev/null
$
```
Can anyone offer any solutions? Thank you in advance!
---
UPDATE: I'm still curious if it's possible to redirect STDERR in tcsh from .aliases, but as has been suggested here, I ended up with a shell script:
```
#!/bin/sh
# wrapper script to suppress messages sent to STDERR on launch
# from the command line.
/usr/bin/xemacs "$@" 2>/dev/null
``` | I suspect this is a case where NOT using an alias is the best option - try using a shell script instead:
```
#!/bin/tcsh
(xemacs $* > /dev/tty ) >& /dev/null
``` |
136,278 | <p>For example, I rarely need:</p>
<pre><code>using System.Text;
</code></pre>
<p>but it's always there by default. I assume the application will use more memory if your code contains unnecessary <a href="http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx" rel="noreferrer">using directives</a>. But is there anything else I should be aware of?</p>
<p>Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?</p>
<hr>
<p><em>Edit: Note that this question is not about the unrelated concept called a <a href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx" rel="noreferrer">using statement</a>, designed to help one manage resources by ensuring that when an object goes out of scope, its <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx" rel="noreferrer">IDisposable.Dispose</a> method is called. See <a href="https://stackoverflow.com/questions/75401/uses-of-using-in-c">Uses of "using" in C#</a>.</em></p>
| [
{
"answer_id": 136285,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 9,
"selected": true,
"text": "<p>It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.</p>\n\n<p>Mainly, it's just to clean up for personal preference.</p>\n"
},
{
"answer_id": 136287,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "<p>Your application will not use more memory. It's for the compiler to find classes you use in the code files. It really doesn't hurt beyond not being clean.</p>\n"
},
{
"answer_id": 136290,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 0,
"selected": false,
"text": "<p>The 'using' statement does not affect performance as it is merely a helper in qualifying the names of your identifiers. So instead of having to type, <em>System.IO.Path.Combine(...)</em>, you can simply type, <em>Path.Combine(...)</em> if you have <em>using System.IO</em>.</p>\n"
},
{
"answer_id": 136293,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>Do not forget that the compiler do a lot of work to optimize everything when building your project. Using that is used in a lot of place or 1 shouldn't do a different once compiled.</p>\n"
},
{
"answer_id": 136310,
"author": "Josh Sklare",
"author_id": 21277,
"author_profile": "https://Stackoverflow.com/users/21277",
"pm_score": 2,
"selected": false,
"text": "<p>It’s personal preference mainly. I clean them up myself (ReSharper does a good job of telling me when there’s unneeded using statements).</p>\n<p>One could say that it might decrease the time to compile, but with computer and compiler speeds these days, it just wouldn’t make any perceptible impact.</p>\n"
},
{
"answer_id": 136314,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": 1,
"selected": false,
"text": "<p>They are just used as a shortcut. For example, you'd have to write:\nSystem.Int32 each time if you did not have a using System; on top.</p>\n\n<p>Removing unused ones just makes your code look cleaner.</p>\n"
},
{
"answer_id": 136320,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 5,
"selected": false,
"text": "<p>There's no IL construct that corresponds to <code>using</code>. Thus, the <code>using</code> statements do not increase your application memory, as there is no code or data that is generated for it.</p>\n\n<p><code>Using</code> is used at compile time only for the purposes of resolving short type names to fully qualified type names. Thus, the only negative effect unnecessary <code>using</code> can have is slowing the compile time a little bit and taking a bit more memory during compilation. I wouldn't be worried about that though.</p>\n\n<p>Thus, the only real negative effect of having <code>using</code> statements you don't need is on intellisense, as the list of potential matches for completion while you type increases.</p>\n"
},
{
"answer_id": 136326,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 2,
"selected": false,
"text": "<p>You may have name clashes if you call your classes like the (unused) classes in the namespace. In the case of System.Text, you'll have a problem if you define a class named \"Encoder\".</p>\n\n<p>Anyways this is usually a minor problem, and detected by the compiler.</p>\n"
},
{
"answer_id": 136494,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>Leaving extra <code>using</code> directives is fine. There is a little value in removing them, but not much. For example, it makes my IntelliSense completion lists shorter, and therefore easier to navigate.</p>\n\n<p>The compiled assemblies are not affected by extraneous <code>using</code> directives.</p>\n\n<p>Sometimes I put them inside a <code>#region</code>, and leave it collapsed; this makes viewing the file a little cleaner. IMO, this is one of the few good uses of <code>#region</code>.</p>\n"
},
{
"answer_id": 136540,
"author": "CheeZe5",
"author_id": 22431,
"author_profile": "https://Stackoverflow.com/users/22431",
"pm_score": 1,
"selected": false,
"text": "<p>The using statement just keeps you from qualifying the types you use. I personally like to clean them up. Really it depends on how a loc metric is used</p>\n"
},
{
"answer_id": 136630,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 5,
"selected": false,
"text": "<p>Code cleanliness <i>is</i> important.</p>\n\n<p>One starts to get the feeling that the code may be unmaintained and on the browfield path when one sees superfluous usings. In essence, when I see some unused using statements, a little yellow flag goes up in the back of my brain telling me to \"proceed with caution.\" And reading production code should never give you that feeling.</p>\n\n<p>So clean up your usings. Don't be sloppy. Inspire confidence. Make your code pretty. Give another dev that warm-fuzzy feeling.</p>\n"
},
{
"answer_id": 136646,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 9,
"selected": false,
"text": "<p>There <strong>are</strong> few reasons for removing unused using(s)/namespaces, besides coding preference: </p>\n\n<ul>\n<li>removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where the compiler must search all namespaces for extension methods for possible better matches, generic type inference and lambda expressions involving generic types)</li>\n<li>can potentially help to avoid name collision in future builds when new types are added to the unused namespaces that have the same name as some types in the used namespaces.</li>\n<li>will reduce the number of items in the editor auto completion list when coding, posibly leading to faster typing (in C# 3.0 this can also reduce the list of extension methods shown) </li>\n</ul>\n\n<p>What removing the unused namespaces <strong>won't</strong> do:</p>\n\n<ul>\n<li>alter in any way the output of the compiler.</li>\n<li>alter in any way the execution of the compiled program (faster loading, or better performance). </li>\n</ul>\n\n<p>The resulting assembly is the same with or without unused using(s) removed.</p>\n"
},
{
"answer_id": 22016204,
"author": "Timothy Gonzalez",
"author_id": 2646126,
"author_profile": "https://Stackoverflow.com/users/2646126",
"pm_score": 1,
"selected": false,
"text": "<p>Having only the namespaces that you actually use allows you to keep your code documented.</p>\n\n<p>You can easily find what parts of your code are calling one another by any search tool.</p>\n\n<p>If you have unused namespaces this means nothing, when running a search.</p>\n\n<p>I'm working on cleaning up namespaces now, because I'm constantly asked what parts of the application are accessing the same data one way or another.</p>\n\n<p>I know which parts are accessing data each way due to the data access being separated by namespaces e.g. directly through a database and in-directly through a web service.</p>\n\n<p>I can't think of a simpler way to do this all at once.</p>\n\n<p>If you just want your code to be a black box (to the developers), then yes it doesn't matter. But if you need to maintain it over time it is valuable documentation like all other code.</p>\n"
},
{
"answer_id": 50764491,
"author": "Masd",
"author_id": 3381362,
"author_profile": "https://Stackoverflow.com/users/3381362",
"pm_score": 2,
"selected": false,
"text": "<p>if you want to maintain your code clean, not used <code>using</code> statements should be removed from the file. the benefits appears very clear when you work in a collaborative team that need to understand your code, think all your code must be maintained, less code = less work, the benefits are long term.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
]
| For example, I rarely need:
```
using System.Text;
```
but it's always there by default. I assume the application will use more memory if your code contains unnecessary [using directives](http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx). But is there anything else I should be aware of?
Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?
---
*Edit: Note that this question is not about the unrelated concept called a [using statement](http://msdn.microsoft.com/en-us/library/yh598w02.aspx), designed to help one manage resources by ensuring that when an object goes out of scope, its [IDisposable.Dispose](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) method is called. See [Uses of "using" in C#](https://stackoverflow.com/questions/75401/uses-of-using-in-c).* | It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference. |
136,288 | <p>I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database.</p>
<p>Could someone look at my code and see where a problem could occur?</p>
<pre><code><?php
$title = "Edit News";
include("../includes/header.php");
include("../includes/database.php");
$done = false;
$expected = array('newstitle', 'newscontent', 'id');
if ($_GET && !$_POST) {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
}
else {
$id = NULL;
}
if ($id) {
$sql = "SELECT * FROM news WHERE id = $id";
$result = mysql_query($sql) or die ("Error connecting to database...");
$row = mysql_fetch_assoc($result);
}
// if form has been submitted, update record
if (array_key_exists('update', $_POST)) {
// prepare expected items for insertion into database
foreach ($_POST as $key => $value) {
if (in_array($key, $expected)) {
${$key} = mysql_real_escape_string($value);
}
}
// abandon the process if primary key invalid
if (!is_numeric($id)) {
die('Invalid request');
}
// prepare the SQL query
$query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id";
// submit the query
$done = mysql_query($query) or die("Error connecting to database...");
}
}
// redirect page if $id is invalid
if ($done) {
header("Location: $ROOT/admin/listnews.php");
exit;
}
?>
</code></pre>
| [
{
"answer_id": 136316,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 0,
"selected": false,
"text": "<p>If you run that UPDATE from the mysql cli with the same data the user sends does it update?</p>\n\n<p>If not check for escaping characters.</p>\n"
},
{
"answer_id": 136345,
"author": "Doug Moore",
"author_id": 13179,
"author_profile": "https://Stackoverflow.com/users/13179",
"pm_score": 3,
"selected": false,
"text": "<pre><code>if ($_GET && !$_POST) { \n</code></pre>\n\n<p>...</p>\n\n<pre><code>if (array_key_exists('update', $_POST)) { \n</code></pre>\n\n<p>Won't that ensure the update code never fires?</p>\n"
},
{
"answer_id": 136348,
"author": "stukelly",
"author_id": 5891,
"author_profile": "https://Stackoverflow.com/users/5891",
"pm_score": 0,
"selected": false,
"text": "<p>Should $content and $title in the line below be $newstitle and $newscontent?</p>\n\n<pre><code>// prepare the SQL query \n$query = \"UPDATE news SET title = '$newstitle', content = '$newscontent' WHERE id = $id\";\n</code></pre>\n"
},
{
"answer_id": 136359,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 0,
"selected": false,
"text": "<p>Couple of things to try and narrow down the problem:</p>\n\n<ul>\n<li>echo out some debug text just inside the <code>if (array_key_exists('update', $_POST)) </code> block to make sure you're actually getting in there. The top of your \"if\" is <code>if($_GET && !$_POST)</code>, so you may need to change this <code>$_POST</code> to <code>$_GET</code></li>\n<li>have you tried echoing out <code>$query</code> just before the db call? Does it run on the command line mysql interface ok?</li>\n<li>if my reading of your <code>foreach ($_POST as $key => $value)</code> is correct, you'll end up setting variables with the same names as those in <code>$expected</code> - (<code>$newstitle, $newscontent, $id</code>) - but in your sql reference <code>$content</code> and <code>$title</code>. They may be the cause of this bug, but something to keep an eye out for.</li>\n</ul>\n"
},
{
"answer_id": 136375,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 0,
"selected": false,
"text": "<p>It's a little hard to know exactly what's going on without seeing the HTML source of your form, but I think that the</p>\n\n<pre><code>if (array_key_exists('update', $_POST)) {\n</code></pre>\n\n<p>block needs to be moved out of the outer if, since it will never be executed if it's there.</p>\n\n<p>If you don't want to use some sort of testing framework, <code>print()</code> is your friend when it comes to debugging your code. Try to find what's executing and what's not; you'll quickly discover which of your assumptions are incorrect, and therefore where the bug is.</p>\n"
},
{
"answer_id": 136379,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>Take this if statement out of the nested if:</p>\n\n<pre>\n<code>\n if (array_key_exists('update', $_POST)) { \n...\n}\n</code>\n</pre>\n\n<p>and then add this conditional:</p>\n\n<pre>\n\n<code>\n if (count($_POST) && array_key_exists('update', $_POST)) { \n...\n}\n</code>\n</pre>\n\n<p>I'm pretty sure that will take care of your problem.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database.
Could someone look at my code and see where a problem could occur?
```
<?php
$title = "Edit News";
include("../includes/header.php");
include("../includes/database.php");
$done = false;
$expected = array('newstitle', 'newscontent', 'id');
if ($_GET && !$_POST) {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
}
else {
$id = NULL;
}
if ($id) {
$sql = "SELECT * FROM news WHERE id = $id";
$result = mysql_query($sql) or die ("Error connecting to database...");
$row = mysql_fetch_assoc($result);
}
// if form has been submitted, update record
if (array_key_exists('update', $_POST)) {
// prepare expected items for insertion into database
foreach ($_POST as $key => $value) {
if (in_array($key, $expected)) {
${$key} = mysql_real_escape_string($value);
}
}
// abandon the process if primary key invalid
if (!is_numeric($id)) {
die('Invalid request');
}
// prepare the SQL query
$query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id";
// submit the query
$done = mysql_query($query) or die("Error connecting to database...");
}
}
// redirect page if $id is invalid
if ($done) {
header("Location: $ROOT/admin/listnews.php");
exit;
}
?>
``` | ```
if ($_GET && !$_POST) {
```
...
```
if (array_key_exists('update', $_POST)) {
```
Won't that ensure the update code never fires? |
136,362 | <p>Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness.</p>
<p>Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try:</p>
<pre><code>mvn compile
</code></pre>
<p>inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path.</p>
<p>If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land.</p>
<p>I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.</p>
| [
{
"answer_id": 136395,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 1,
"selected": false,
"text": "<p>I think the best way to handle it is to make Bar a Maven project just like Foo, and then <code>mvn install</code> it so it is available in your local Maven repository. The drawback is that you have to install that project every time you want Maven to see the changes you make to Bar.</p>\n"
},
{
"answer_id": 136397,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 5,
"selected": true,
"text": "<p>Maybe you are referencing the other project via Eclipse configure-> build path only. This works as long as you use Eclipse to build your project.</p>\n\n<p>Try running first <code>mvn install</code> in project Bar (in order to put Bar in your Maven repository), and then add the dependency to Foo's pom.xml.</p>\n\n<p>That should work!.</p>\n"
},
{
"answer_id": 136403,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 1,
"selected": false,
"text": "<p>Not a complete answer:<br>\nBar's pom needs to include Foo in order to use maven to compile it.<br>\nI'm interested in this question too, but from the perspective of how to get eclipse to recognise a maven-added dependency is actually another project in the same workspace. I currently alter the build path after performing <code>mvn eclipse:eclipse</code></p>\n"
},
{
"answer_id": 136706,
"author": "Micke",
"author_id": 19392,
"author_profile": "https://Stackoverflow.com/users/19392",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the <a href=\"https://www.eclipse.org/m2e/\" rel=\"nofollow noreferrer\">m2eclipse</a> plugin. It will automatically and dynamically update the project build path when you change the pom. There is no need for running <code>mvn eclipse:eclipse</code>.</p>\n\n<p>The plugin will also detect if any dependency is in the same workspace and add that project to the build path.</p>\n\n<p>Ideally, if you use m2eclipse, you would never change the project build path manually. You would always edit pom.xml instead, which is the proper way to do it.</p>\n\n<p>As has been previously stated, Maven will not know about the Eclipse project build path. You do need to add all dependencies to the pom, and you need to make sure all dependencies are built and installed first by running <code>mvn install</code>.</p>\n\n<p>If you want to build both projects with a single command then you might find <a href=\"http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Project_Aggregation\" rel=\"nofollow noreferrer\">project aggregation</a> interesting.</p>\n"
},
{
"answer_id": 137525,
"author": "alexguev",
"author_id": 436199,
"author_profile": "https://Stackoverflow.com/users/436199",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to try an alternative approach, where you have a parent maven project and two children project. let's say:</p>\n\n<p>Parent (pom.xml has references to both children projects/modules)\n --> A (depends on B)\n --> B</p>\n\n<p>then when you run mvn eclipse:eclipse from the root of Parent, maven will generate eclipse projects for A and B, and it will have B as a required project in the classpath of A.</p>\n\n<p>You can run mvn install from the root of Parent to get both projects to compile.</p>\n\n<p>To complete your setup, you'll have to import both A and B into Eclipse, making sure you don't check \"Copy projects into workspace\".</p>\n"
},
{
"answer_id": 44821136,
"author": "Andreas Covidiot",
"author_id": 1915920,
"author_profile": "https://Stackoverflow.com/users/1915920",
"pm_score": 0,
"selected": false,
"text": "<p>If you reference a local project, but its version has been updated (usually increased), it could maybe only be found in your local repo and you have to update the (likely fixed) version of it in your POM(s).</p>\n\n<hr>\n\n<p>We have a \"common project\" (used everywhere) which does not necessarily need to be versioned since we tag it via source control. so either</p>\n\n<ul>\n<li>keeping it at a fixed version or</li>\n<li>referencing it with the special <code>LATEST</code> version</li>\n</ul>\n\n<p>are good workarounds to always be on the safe side.</p>\n"
},
{
"answer_id": 46817944,
"author": "Tezra",
"author_id": 6893866,
"author_profile": "https://Stackoverflow.com/users/6893866",
"pm_score": 2,
"selected": false,
"text": "<p>I just needed to do this and I needed it to build with the external mvn clean install command. Here is the proper way to configure this in Eclipse. (With project B as a dependency of A)</p>\n\n<ol>\n<li>Open the pom.xml for project A in Eclipse.</li>\n<li>Go to the <code>Dependencies</code> tab.</li>\n<li>Click the <code>Add...</code> button in the middle of the page (for the left side Dependencies box)</li>\n<li>In the popup, there should be a box under a line with text above it saying <code>Enter groupId, artifactId or sha1 prefix or pattern (*):</code>. Enter the artifact ID for project B into this box.</li>\n<li>Double click the jar you want to add as a dependency to this project\n\n<ol>\n<li>You may need to update the project after. </li>\n<li>Right click project A in you Package explorer</li>\n<li>Maven -> Update Project...</li>\n<li>Then hit OK in the popup.</li>\n</ol></li>\n</ol>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8178/"
]
| Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness.
Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try:
```
mvn compile
```
inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path.
If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land.
I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works. | Maybe you are referencing the other project via Eclipse configure-> build path only. This works as long as you use Eclipse to build your project.
Try running first `mvn install` in project Bar (in order to put Bar in your Maven repository), and then add the dependency to Foo's pom.xml.
That should work!. |
136,401 | <p>This could be weird, Have you ever come across a blog which you wanted to read in the chronological order? And that blog could be old, with several hundred posts. When i add this feed to my feed reader, say googlereader, the latest feed comes on top and as i scroll down further, the older posts appear. This could be frustrating if you want to read it from the beginning. Is there any reader that does this? Or, i would love to do this as a pet project, (preferably in c#), how exactly should i go about it? Also, are there any .NET libraries which i can use to work on RSS feeds? I have not done any RSS feed programming before.</p>
<p><strong>EDIT</strong> I would like to know if there are any technical limitations to this. This was jsut one interesting problem that I encountered that i thought could be tackled programmatically.</p>
| [
{
"answer_id": 136416,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 2,
"selected": false,
"text": "<p>In Google Reader, when you're reading a feed, there is a \"Feed settings...\" menu with the options: \"Sort by newest\", \"Sort by oldest\".</p>\n\n<p>Folders have the same options under the menu \"Folder settings...\"</p>\n\n<p>No programming required.</p>\n"
},
{
"answer_id": 136422,
"author": "y0mbo",
"author_id": 417,
"author_profile": "https://Stackoverflow.com/users/417",
"pm_score": 2,
"selected": false,
"text": "<p>I think you might have trouble with this. Many RSS feeds only keep the latest 10 or so posts, so there would be no way to provide the older data from the feed since the blog started.</p>\n"
},
{
"answer_id": 136424,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>This should be fairly easy with any language...all you would need to do is read the feed xml into a DOM structure (nearly all languauges including C# have a DomDocument class)</p>\n\n<p>You should then be able to simply loop through the item nodes in reverse order...</p>\n\n<p>see: <a href=\"http://msdn.microsoft.com/en-us/library/ms756177(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms756177(VS.85).aspx</a></p>\n\n<p>As other said, depending on the rss feed, you may only get a finite amount of items.</p>\n"
},
{
"answer_id": 136438,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 1,
"selected": false,
"text": "<p>In Google Reader, you can have it display the items in a folder (feed) from either Newest to Oldest, or Oldest to Newest. To do this, select the feed, select the \"Feed settings\" drop down, and select \"Sort by oldest\". I'm not sure how far back Google Reader goes, but possibly all the way since it first started monitoring the feed.</p>\n"
},
{
"answer_id": 160792,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 3,
"selected": true,
"text": "<p>If you do decide to roll your own C# application to do this, it is very straightforward in the current version of the .NET Framework.</p>\n\n<p>Look for the <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx\" rel=\"nofollow noreferrer\">System.ServiceModel.Syndication</a> namespace. That has classes related to RSS and Atom feeds. I wrote some code recently that generates a feed from a database using these classes, and adds geocodes to the feed items. I had the same problem where i needed to reverse the order of the items in the feed, because my database query returned them in the opposite order I wanted my users to see.</p>\n\n<p>What I did was to simply hold the list of <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationitem.aspx\" rel=\"nofollow noreferrer\">SyndicationItem</a> objects for the feed in my own <code>List<SyndicationItem></code> data structure until right before I want to write the feed to disk. Then I would do something like this:</p>\n\n<pre><code>private SyndicationFeed m_feed;\nprivate List<SyndicationItem> m_items;\n\n...snip...\n\nm_items.Reverse();\nm_feed.Items = m_items;\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
]
| This could be weird, Have you ever come across a blog which you wanted to read in the chronological order? And that blog could be old, with several hundred posts. When i add this feed to my feed reader, say googlereader, the latest feed comes on top and as i scroll down further, the older posts appear. This could be frustrating if you want to read it from the beginning. Is there any reader that does this? Or, i would love to do this as a pet project, (preferably in c#), how exactly should i go about it? Also, are there any .NET libraries which i can use to work on RSS feeds? I have not done any RSS feed programming before.
**EDIT** I would like to know if there are any technical limitations to this. This was jsut one interesting problem that I encountered that i thought could be tackled programmatically. | If you do decide to roll your own C# application to do this, it is very straightforward in the current version of the .NET Framework.
Look for the [System.ServiceModel.Syndication](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx) namespace. That has classes related to RSS and Atom feeds. I wrote some code recently that generates a feed from a database using these classes, and adds geocodes to the feed items. I had the same problem where i needed to reverse the order of the items in the feed, because my database query returned them in the opposite order I wanted my users to see.
What I did was to simply hold the list of [SyndicationItem](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationitem.aspx) objects for the feed in my own `List<SyndicationItem>` data structure until right before I want to write the feed to disk. Then I would do something like this:
```
private SyndicationFeed m_feed;
private List<SyndicationItem> m_items;
...snip...
m_items.Reverse();
m_feed.Items = m_items;
``` |
136,413 | <p>I have a Flex application where I'm using a Canvas to contain several other components. On that Canvas there is a Button which is used to invoke a particular flow through the system. Clicking anywhere else on the Canvas should cause cause a details pane to appear showing more information about the record represented by this control.</p>
<p>The problem I'm having is that because the button sits inside the Canvas any time the user clicks the Button the click event is fired on both the Button and the Canvas. Is there any way to avoid having the click event fired on the Canvas object if the user clicks on an area covered up by another component?</p>
<p>I've created a simple little test application to demonstrate the problem:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
private function onCanvasClick(event:Event):void {
text.text = text.text + "\n" + "Canvas Clicked";
}
private function onButtonClick(event:Event):void {
text.text = text.text + "\n" + "Button Clicked";
}
]]>
</mx:Script>
<mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)">
<mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/>
</mx:Canvas>
<mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/>
</mx:Application>
</code></pre>
<p>As it stands when you click the button you will see two entries made in the text box, "Button Clicked" followed by "Canvas Clicked" even though the mouse was clicked only once.</p>
<p>I'd like to find a way that I could avoid having the second entry made such that when I click the Button only the "Button Clicked" entry is made, but if I were to click anywhere else in the Canvas the "Canvas Clicked" entry would still appear.</p>
| [
{
"answer_id": 136569,
"author": "Laplie Anderson",
"author_id": 14204,
"author_profile": "https://Stackoverflow.com/users/14204",
"pm_score": 4,
"selected": true,
"text": "<p>The event continues on because event.bubbles is set to true. This means everything in the display heirarchy gets the event. To stop the event from continuing, you call </p>\n\n<pre><code>event.stopImmediatePropagation()\n</code></pre>\n"
},
{
"answer_id": 136571,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>I have 2 ideas, first try this:</p>\n\n<pre>\n<code>\nbtn.addEventListener(MouseEvent.Click,function(event:MouseEvent):void{\n event.stopImmediatePropagation();\n ...\n});\n</code>\n</pre>\n\n<p>if that doesn't work, see if you can add the click listener to the canvas and not the button and check the target property on the event object. something like:</p>\n\n<pre>\n<code>\nbtn.addEventListener(MouseEvent.Click,function(event:MouseEvent):void{\n if(event.target == btn){\n ...\n }\n else{\n ...\n }\n});\n</code>\n</pre>\n\n<p>Again, these are some ideas of the top of my head...I'll create a small test app and see if these work...</p>\n"
},
{
"answer_id": 139444,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 1,
"selected": false,
"text": "<p>Laplie's answer worked like a charm. For those interested the updated code looks like this:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\">\n <mx:Script>\n <![CDATA[\n private function onCanvasClick(event:Event):void {\n text.text = text.text + \"\\n\" + \"Canvas Clicked\";\n }\n\n private function onButtonClick(event:Event):void {\n text.text = text.text + \"\\n\" + \"Button Clicked\";\n event.stopImmediatePropagation();\n }\n ]]>\n </mx:Script>\n\n <mx:Canvas x=\"97\" y=\"91\" width=\"200\" height=\"200\" backgroundColor=\"red\" click=\"onCanvasClick(event)\">\n <mx:Button x=\"67\" y=\"88\" label=\"Button\" click=\"onButtonClick(event)\"/>\n </mx:Canvas>\n <mx:Text id=\"text\" x=\"97\" y=\"330\" text=\"Text\" width=\"200\" height=\"129\"/>\n</mx:Application>\n</code></pre>\n\n<p>The only difference is the one additional line in the onButtonClick method.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
]
| I have a Flex application where I'm using a Canvas to contain several other components. On that Canvas there is a Button which is used to invoke a particular flow through the system. Clicking anywhere else on the Canvas should cause cause a details pane to appear showing more information about the record represented by this control.
The problem I'm having is that because the button sits inside the Canvas any time the user clicks the Button the click event is fired on both the Button and the Canvas. Is there any way to avoid having the click event fired on the Canvas object if the user clicks on an area covered up by another component?
I've created a simple little test application to demonstrate the problem:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
private function onCanvasClick(event:Event):void {
text.text = text.text + "\n" + "Canvas Clicked";
}
private function onButtonClick(event:Event):void {
text.text = text.text + "\n" + "Button Clicked";
}
]]>
</mx:Script>
<mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)">
<mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/>
</mx:Canvas>
<mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/>
</mx:Application>
```
As it stands when you click the button you will see two entries made in the text box, "Button Clicked" followed by "Canvas Clicked" even though the mouse was clicked only once.
I'd like to find a way that I could avoid having the second entry made such that when I click the Button only the "Button Clicked" entry is made, but if I were to click anywhere else in the Canvas the "Canvas Clicked" entry would still appear. | The event continues on because event.bubbles is set to true. This means everything in the display heirarchy gets the event. To stop the event from continuing, you call
```
event.stopImmediatePropagation()
``` |
136,419 | <p>I need to determine the current year in Java as an integer. I could just use <code>java.util.Date()</code>, but it is deprecated.</p>
| [
{
"answer_id": 136434,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 11,
"selected": true,
"text": "<p>For Java 8 onwards:</p>\n<pre><code>int year = Year.now().getValue();\n</code></pre>\n<p>For older version of Java:</p>\n<pre><code>int year = Calendar.getInstance().get(Calendar.YEAR);\n</code></pre>\n"
},
{
"answer_id": 136445,
"author": "conmulligan",
"author_id": 1467,
"author_profile": "https://Stackoverflow.com/users/1467",
"pm_score": 4,
"selected": false,
"text": "<p>The easiest way is to get the year from Calendar.</p>\n\n<pre><code>// year is stored as a static member\nint year = Calendar.getInstance().get(Calendar.YEAR);\n</code></pre>\n"
},
{
"answer_id": 136455,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 5,
"selected": false,
"text": "<p>This simplest (using Calendar, sorry) is:</p>\n\n<pre><code> int year = Calendar.getInstance().get(Calendar.YEAR);\n</code></pre>\n\n<p>There is also the new <a href=\"https://jsr-310.dev.java.net/\" rel=\"noreferrer\">Date and Time API JSR</a>, as well as <a href=\"http://joda-time.sourceforge.net/\" rel=\"noreferrer\">Joda Time</a></p>\n"
},
{
"answer_id": 136543,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 2,
"selected": false,
"text": "<p>If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because <code>java.util.Date</code> is mutable. <code>java.util.Calendar</code> has performance problems when its fields get updated, and is clunky for datetime arithmetic. </p>\n"
},
{
"answer_id": 137770,
"author": "maxp",
"author_id": 21152,
"author_profile": "https://Stackoverflow.com/users/21152",
"pm_score": -1,
"selected": false,
"text": "<p>I use special functions in my library to work with days/month/year ints -</p>\n\n<pre><code>int[] int_dmy( long timestamp ) // remember month is [0..11] !!!\n{\n Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );\n return new int[] { \n cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )\n };\n};\n\n\nint[] int_dmy( Date d ) { \n ...\n}\n</code></pre>\n"
},
{
"answer_id": 138019,
"author": "Ewan Makepeace",
"author_id": 9731,
"author_profile": "https://Stackoverflow.com/users/9731",
"pm_score": -1,
"selected": false,
"text": "<p>You can do the whole thing using Integer math without needing to instantiate a calendar:</p>\n\n<pre><code>return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);\n</code></pre>\n\n<p>May be off for an hour or two at new year but I don't get the impression that is an issue?</p>\n"
},
{
"answer_id": 6761567,
"author": "basZero",
"author_id": 356815,
"author_profile": "https://Stackoverflow.com/users/356815",
"pm_score": 3,
"selected": false,
"text": "<p>If you want the year of any date object, I used the following method:</p>\n\n<pre><code>public static int getYearFromDate(Date date) {\n int result = -1;\n if (date != null) {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n result = cal.get(Calendar.YEAR);\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 27107237,
"author": "maral04",
"author_id": 4112413,
"author_profile": "https://Stackoverflow.com/users/4112413",
"pm_score": 2,
"selected": false,
"text": "<p>As some people answered above:</p>\n\n<p>If you want to use the variable later, better use:</p>\n\n<pre><code>int year;\n\nyear = Calendar.getInstance().get(Calendar.YEAR);\n</code></pre>\n\n<p>If you need the year for just a condition you better use:</p>\n\n<pre><code>Calendar.getInstance().get(Calendar.YEAR)\n</code></pre>\n\n<p>For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year):</p>\n\n<pre><code>import java.util.Calendar;\nimport java.util.Scanner;\n\npublic static void main (String[] args){\n\n Scanner scannernumber = new Scanner(System.in);\n int year;\n\n /*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/\n\n do{\n System.out.print(\"Year (Between \"+((Calendar.getInstance().get(Calendar.YEAR))-200)+\" and \"+Calendar.getInstance().get(Calendar.YEAR)+\") : \");\n year = scannernumber.nextInt();\n }while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));\n}\n</code></pre>\n"
},
{
"answer_id": 28891864,
"author": "Raffi Khatchadourian",
"author_id": 405326,
"author_profile": "https://Stackoverflow.com/users/405326",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use Java 8's <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a>:</p>\n\n<pre><code>import java.time.LocalDate;\n//...\nint year = LocalDate.now().getYear();\n</code></pre>\n"
},
{
"answer_id": 30019752,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 4,
"selected": false,
"text": "<h1>tl;dr</h1>\n<pre><code>ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )\n .getYear()\n</code></pre>\n<h1>Time Zone</h1>\n<p><a href=\"https://stackoverflow.com/a/28891864/642706\">The answer</a> by <a href=\"https://stackoverflow.com/users/405326/raffi-khatchadourian\">Raffi Khatchadourian</a> wisely shows how to use the new <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time package</a> in Java 8. But that answer fails to address the critical issue of time zone in determining a date.</p>\n<blockquote>\n<p>int year = LocalDate.now().getYear();</p>\n</blockquote>\n<p>That code depends on the JVM's current default time zone. The default zone is used in determining what today’s date is. Remember, for example, that in the moment after midnight in Paris the date in Montréal is still 'yesterday'.</p>\n<p>So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code <em>at any moment</em> changing the JVM's current default. Better to specify the time zone.</p>\n<p>By the way, always use <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"noreferrer\">proper time zone names</a> as <a href=\"https://www.iana.org/time-zones\" rel=\"noreferrer\">defined by the IANA</a>. Never use the 3-4 letter codes that are neither standardized nor unique.</p>\n<h1>java.time</h1>\n<p>Example in java.time of Java 8.</p>\n<pre><code>int year = ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) ).getYear() ;\n</code></pre>\n<h1>Joda-Time</h1>\n<p>Some idea as above, but using the <a href=\"http://www.joda.org/joda-time/\" rel=\"noreferrer\">Joda-Time</a> 2.7 library.</p>\n<pre><code>int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;\n</code></pre>\n<h1>Incrementing/Decrementing Year</h1>\n<p>If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.</p>\n<p>Example in <em>java.time</em>.</p>\n<pre><code>ZonedDateTime zdt = \n ZonedDateTime\n .now( ZoneId.of( "Africa/Casablanca" ) )\n .minusYears( 1 ) \n;\n</code></pre>\n<p>Example in Joda-Time 2.7.</p>\n<pre><code>DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;\n</code></pre>\n"
},
{
"answer_id": 33700141,
"author": "assylias",
"author_id": 829571,
"author_profile": "https://Stackoverflow.com/users/829571",
"pm_score": 8,
"selected": false,
"text": "<p>Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#now--\" rel=\"noreferrer\">the <code>Year::now</code> method</a>:</p>\n\n<pre><code>int year = Year.now().getValue();\n</code></pre>\n"
},
{
"answer_id": 44138205,
"author": "Zhurov Konstantin",
"author_id": 6643968,
"author_profile": "https://Stackoverflow.com/users/6643968",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use 2 methods from <code>java.time.YearMonth</code>( Since Java 8 ):</p>\n\n<pre><code>import java.time.YearMonth;\n...\nint year = YearMonth.now().getYear();\nint month = YearMonth.now().getMonthValue();\n</code></pre>\n"
},
{
"answer_id": 57391538,
"author": "KayV",
"author_id": 3956731,
"author_profile": "https://Stackoverflow.com/users/3956731",
"pm_score": 3,
"selected": false,
"text": "<p>Use the following code for java 8 :</p>\n\n<pre><code>LocalDate localDate = LocalDate.now();\nint year = localDate.getYear();\nint month = localDate.getMonthValue();\nint date = localDate.getDayOfMonth();\n</code></pre>\n"
},
{
"answer_id": 58837485,
"author": "Alex Martian",
"author_id": 5499118,
"author_profile": "https://Stackoverflow.com/users/5499118",
"pm_score": -1,
"selected": false,
"text": "<p>In Java version 8+ can (advised to) use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> library. <a href=\"https://www.iso.org/iso-8601-date-and-time-format.html\" rel=\"nofollow noreferrer\">ISO 8601</a> sets standard way to write dates: <code>YYYY-MM-DD</code> and <code>java.time.Instant</code> uses it, so (for <code>UTC</code>):</p>\n\n<pre><code>import java.time.Instant;\nint myYear = Integer.parseInt(Instant.now().toString().substring(0,4));\n</code></pre>\n\n<p>P.S. just in case (and shorted for getting <code>String</code>, not <code>int</code>), using <code>Calendar</code> looks better and can be made zone-aware.</p>\n"
},
{
"answer_id": 62329383,
"author": "Mayur Satav",
"author_id": 8379852,
"author_profile": "https://Stackoverflow.com/users/8379852",
"pm_score": 0,
"selected": false,
"text": "<p>In my case none of the above is worked. So After trying lot of solutions i found below one and it worked for me</p>\n\n<pre><code>import java.util.Scanner;\nimport java.util.Date;\n\npublic class Practice\n{ \n public static void main(String[] args)\n {\n Date d=new Date(); \n int year=d.getYear();\n int currentYear=year+1900; \n\n System.out.println(currentYear);\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 73637810,
"author": "Maximiliano Salibe",
"author_id": 14881639,
"author_profile": "https://Stackoverflow.com/users/14881639",
"pm_score": 0,
"selected": false,
"text": "<p>I may add that a simple way to get the current year as an integer is importing\njava.time.LocalDate and, then:</p>\n<pre><code>import java.time.LocalDate;\nint yourVariable = LocalDate.now().getYear()\n</code></pre>\n<p>Hope this helps!</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318/"
]
| I need to determine the current year in Java as an integer. I could just use `java.util.Date()`, but it is deprecated. | For Java 8 onwards:
```
int year = Year.now().getValue();
```
For older version of Java:
```
int year = Calendar.getInstance().get(Calendar.YEAR);
``` |
136,432 | <p>I have a client/server system that performs communication using XML transferred using HTTP requests and responses with the client using Perl's LWP and the server running Perl's CGI.pm through Apache. In addition the stream is encrypted using SSL with certificates for both the server and all clients.</p>
<p>This system works well, except that periodically the client needs to send really large amounts of data. An obvious solution would be to compress the data on the client side, send it over, and decompress it on the server. Rather than implement this myself, I was hoping to use Apache's mod_deflate's "Input Decompression" as described <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html" rel="nofollow noreferrer">here</a>.</p>
<p>The description warns:</p>
<blockquote>
<p>If you evaluate the request body yourself, don't trust the Content-Length header! The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream.</p>
</blockquote>
<p>So if I provide a Content-Length value which matches the compressed data size, the data is truncated. This is because mod_deflate decompresses the stream, but CGI.pm only reads to the Content-Length limit.</p>
<p>Alternatively, if I try to outsmart it and override the Content-Length header with the decompressed data size, LWP complains and resets the value to the compressed length, leaving me with the same problem.</p>
<p>Finally, I attempted to hack the part of LWP which does the correction. The original code is:</p>
<pre><code> # Set (or override) Content-Length header
my $clen = $request_headers->header('Content-Length');
if (defined($$content_ref) && length($$content_ref)) {
$has_content = length($$content_ref);
if (!defined($clen) || $clen ne $has_content) {
if (defined $clen) {
warn "Content-Length header value was wrong, fixed";
hlist_remove(\@h, 'Content-Length');
}
push(@h, 'Content-Length' => $has_content);
}
}
elsif ($clen) {
warn "Content-Length set when there is no content, fixed";
hlist_remove(\@h, 'Content-Length');
}
</code></pre>
<p>And I changed the push line to:</p>
<pre><code> push(@h, 'Content-Length' => $clen);
</code></pre>
<p>Unfortunately this causes some problem where content (truncated or not) doesn't even get to my CGI script.</p>
<p>Has anyone made this work? I found <a href="http://hype-free.blogspot.com/2007/07/compressed-http.html" rel="nofollow noreferrer">this</a> which does compression on a file before uploading, but not compressing a generic request.</p>
| [
{
"answer_id": 137279,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": -1,
"selected": false,
"text": "<p>I am not sure if I am following you with what you want, but I have a custom get/post module, that I use to do some non standard stuff. The below code will read in anything sent via post, or STDIN.</p>\n\n<pre><code>read(STDIN, $query_string, $ENV{'CONTENT_LENGTH'});\n</code></pre>\n\n<p>Instead of using using $ENV's value use your's. I hope this helps, and sorry if it doesn't.</p>\n"
},
{
"answer_id": 138095,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can change the Content-Length like that. It would confuse Apache, because mod_deflate wouldn't know how much compressed data to read. What about having the client add an X-Uncompressed-Length header, and then use a modified version of CGI.pm that uses X-Uncompressed-Length (if present) instead of Content-Length? (Actually, you probably don't need to modify CGI.pm. Just set <code>$ENV{'CONTENT_LENGTH'}</code> to the appropriate value before initializing the CGI object or calling any CGI functions.)</p>\n\n<p>Or, use a lower-level module that uses the bucket brigade to tell how much data to read.</p>\n"
},
{
"answer_id": 139464,
"author": "Ranguard",
"author_id": 12850,
"author_profile": "https://Stackoverflow.com/users/12850",
"pm_score": 1,
"selected": false,
"text": "<p>Although you said you didn't want to do the compression yourself, there are lots of perl modules which will do both sides for you, <a href=\"http://search.cpan.org/dist/Compress-Zlib/\" rel=\"nofollow noreferrer\">Compress::Zlib</a> for example. </p>\n\n<p>I have a cheat (with a .net part of the company) where I get passed XML as a separate parameter posted in, then can handle it as if it was a string rather than faffing about with SOAP like stuff. </p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22410/"
]
| I have a client/server system that performs communication using XML transferred using HTTP requests and responses with the client using Perl's LWP and the server running Perl's CGI.pm through Apache. In addition the stream is encrypted using SSL with certificates for both the server and all clients.
This system works well, except that periodically the client needs to send really large amounts of data. An obvious solution would be to compress the data on the client side, send it over, and decompress it on the server. Rather than implement this myself, I was hoping to use Apache's mod\_deflate's "Input Decompression" as described [here](http://httpd.apache.org/docs/2.0/mod/mod_deflate.html).
The description warns:
>
> If you evaluate the request body yourself, don't trust the Content-Length header! The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream.
>
>
>
So if I provide a Content-Length value which matches the compressed data size, the data is truncated. This is because mod\_deflate decompresses the stream, but CGI.pm only reads to the Content-Length limit.
Alternatively, if I try to outsmart it and override the Content-Length header with the decompressed data size, LWP complains and resets the value to the compressed length, leaving me with the same problem.
Finally, I attempted to hack the part of LWP which does the correction. The original code is:
```
# Set (or override) Content-Length header
my $clen = $request_headers->header('Content-Length');
if (defined($$content_ref) && length($$content_ref)) {
$has_content = length($$content_ref);
if (!defined($clen) || $clen ne $has_content) {
if (defined $clen) {
warn "Content-Length header value was wrong, fixed";
hlist_remove(\@h, 'Content-Length');
}
push(@h, 'Content-Length' => $has_content);
}
}
elsif ($clen) {
warn "Content-Length set when there is no content, fixed";
hlist_remove(\@h, 'Content-Length');
}
```
And I changed the push line to:
```
push(@h, 'Content-Length' => $clen);
```
Unfortunately this causes some problem where content (truncated or not) doesn't even get to my CGI script.
Has anyone made this work? I found [this](http://hype-free.blogspot.com/2007/07/compressed-http.html) which does compression on a file before uploading, but not compressing a generic request. | I don't think you can change the Content-Length like that. It would confuse Apache, because mod\_deflate wouldn't know how much compressed data to read. What about having the client add an X-Uncompressed-Length header, and then use a modified version of CGI.pm that uses X-Uncompressed-Length (if present) instead of Content-Length? (Actually, you probably don't need to modify CGI.pm. Just set `$ENV{'CONTENT_LENGTH'}` to the appropriate value before initializing the CGI object or calling any CGI functions.)
Or, use a lower-level module that uses the bucket brigade to tell how much data to read. |
136,435 | <p>How to allow <code>TextBlock</code>'s text to be selectable?</p>
<p>I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?</p>
| [
{
"answer_id": 136675,
"author": "Bruce",
"author_id": 6310,
"author_profile": "https://Stackoverflow.com/users/6310",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not sure if you can make a TextBlock selectable, but another option would be to use a RichTextBox - it is like a TextBox as you suggested, but supports the formatting you want.</p>\n"
},
{
"answer_id": 137406,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 4,
"selected": false,
"text": "<p>Create ControlTemplate for the TextBlock and put a TextBox inside with readonly property set.\nOr just use TextBox and make it readonly, then you can change the TextBox.Style to make it looks like TextBlock.</p>\n"
},
{
"answer_id": 2506504,
"author": "MSB",
"author_id": 300663,
"author_profile": "https://Stackoverflow.com/users/300663",
"pm_score": 9,
"selected": true,
"text": "<p>Use a <code>TextBox</code> with these settings instead to make it read only and to look like a <code>TextBlock</code> control.</p>\n<pre><code><TextBox Background="Transparent"\n BorderThickness="0"\n Text="{Binding Text, Mode=OneWay}"\n IsReadOnly="True"\n TextWrapping="Wrap" />\n</code></pre>\n"
},
{
"answer_id": 3132657,
"author": "Richard",
"author_id": 20038,
"author_profile": "https://Stackoverflow.com/users/20038",
"pm_score": 1,
"selected": false,
"text": "<p>There is an alternative solution that might be adaptable to the RichTextBox oultined in this <a href=\"http://beta.blogs.microsoft.co.il/blogs/eshaham/archive/2009/07/06/selectable-text-control.aspx\" rel=\"nofollow noreferrer\">blog post</a> - it used a trigger to swap out the control template when the use hovers over the control - should help with performance</p>\n"
},
{
"answer_id": 4145443,
"author": "Ilya Serbis",
"author_id": 355438,
"author_profile": "https://Stackoverflow.com/users/355438",
"pm_score": 1,
"selected": false,
"text": "<pre><code>\nnew TextBox\n{\n Text = text,\n TextAlignment = TextAlignment.Center,\n TextWrapping = TextWrapping.Wrap,\n IsReadOnly = true,\n Background = Brushes.Transparent,\n BorderThickness = new Thickness()\n {\n Top = 0,\n Bottom = 0,\n Left = 0,\n Right = 0\n }\n};\n</code>\n</pre>\n"
},
{
"answer_id": 7399948,
"author": "Saraf Talukder",
"author_id": 690310,
"author_profile": "https://Stackoverflow.com/users/690310",
"pm_score": 2,
"selected": false,
"text": "<p>TextBlock does not have a template. So inorder to achieve this, we need to use a TextBox whose style is changed to behave as a textBlock. </p>\n\n<pre><code><Style x:Key=\"TextBlockUsingTextBoxStyle\" BasedOn=\"{x:Null}\" TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"BorderBrush\" Value=\"{StaticResource TextBoxBorder}\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Padding\" Value=\"1\"/>\n <Setter Property=\"AllowDrop\" Value=\"true\"/>\n <Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\"/>\n <Setter Property=\"ScrollViewer.PanningMode\" Value=\"VerticalFirst\"/>\n <Setter Property=\"Stylus.IsFlicksEnabled\" Value=\"False\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBox BorderThickness=\"{TemplateBinding BorderThickness}\" IsReadOnly=\"True\" Text=\"{TemplateBinding Text}\" Background=\"{x:Null}\" BorderBrush=\"{x:Null}\" />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 9231349,
"author": "jdearana",
"author_id": 207949,
"author_profile": "https://Stackoverflow.com/users/207949",
"pm_score": 4,
"selected": false,
"text": "<p>Apply this style to your TextBox and that's it (inspired from <a href=\"https://web.archive.org/web/20130601215415/http://beta.blogs.microsoft.co.il/blogs/eshaham/archive/2009/07/06/selectable-text-control.aspx\" rel=\"nofollow noreferrer\">this article</a>):</p>\n\n<pre><code><Style x:Key=\"SelectableTextBlockLikeStyle\" TargetType=\"TextBox\" BasedOn=\"{StaticResource {x:Type TextBox}}\">\n <Setter Property=\"IsReadOnly\" Value=\"True\"/>\n <Setter Property=\"IsTabStop\" Value=\"False\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"Padding\" Value=\"-2,0,0,0\"/>\n <!-- The Padding -2,0,0,0 is required because the TextBox\n seems to have an inherent \"Padding\" of about 2 pixels.\n Without the Padding property,\n the text seems to be 2 pixels to the left\n compared to a TextBlock\n -->\n <Style.Triggers>\n <MultiTrigger>\n <MultiTrigger.Conditions>\n <Condition Property=\"IsMouseOver\" Value=\"False\" />\n <Condition Property=\"IsFocused\" Value=\"False\" />\n </MultiTrigger.Conditions>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBlock Text=\"{TemplateBinding Text}\" \n FontSize=\"{TemplateBinding FontSize}\"\n FontStyle=\"{TemplateBinding FontStyle}\"\n FontFamily=\"{TemplateBinding FontFamily}\"\n FontWeight=\"{TemplateBinding FontWeight}\"\n TextWrapping=\"{TemplateBinding TextWrapping}\"\n Foreground=\"{DynamicResource NormalText}\"\n Padding=\"0,0,0,0\"\n />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </MultiTrigger>\n </Style.Triggers>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 24609144,
"author": "Robert Važan",
"author_id": 1981276,
"author_profile": "https://Stackoverflow.com/users/1981276",
"pm_score": -1,
"selected": false,
"text": "<p>I've implemented <a href=\"http://blog.angeloflogic.com/2014/07/selectabletextblock-in-junglecontrols.html\" rel=\"nofollow\">SelectableTextBlock</a> in my opensource controls library. You can use it like this:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><jc:SelectableTextBlock Text=\"Some text\" />\n</code></pre>\n"
},
{
"answer_id": 32870521,
"author": "Billy Willoughby",
"author_id": 4810862,
"author_profile": "https://Stackoverflow.com/users/4810862",
"pm_score": 5,
"selected": false,
"text": "<p>I have been unable to find any example of really answering the question. All the answers used a Textbox or RichTextbox. I needed a solution that allowed me to use a TextBlock, and this is the solution I created. </p>\n\n<p>I believe the correct way to do this is to extend the TextBlock class. This is the code I used to extend the TextBlock class to allow me to select the text and copy it to clipboard. \"sdo\" is the namespace reference I used in the WPF. </p>\n\n<p><strong>WPF Using Extended Class:</strong></p>\n\n<pre><code>xmlns:sdo=\"clr-namespace:iFaceCaseMain\"\n\n<sdo:TextBlockMoo x:Name=\"txtResults\" Background=\"Black\" Margin=\"5,5,5,5\" \n Foreground=\"GreenYellow\" FontSize=\"14\" FontFamily=\"Courier New\"></TextBlockMoo>\n</code></pre>\n\n<p><strong>Code Behind for Extended Class:</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public partial class TextBlockMoo : TextBlock \n{\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler TextSelected;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n TextRange otr = new TextRange(this.ContentStart, this.ContentEnd);\n otr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));\n\n TextRange ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.White));\n\n SelectedText = ntr.Text;\n if (!(TextSelected == null))\n {\n TextSelected(SelectedText);\n }\n }\n}\n</code></pre>\n\n<p><strong>Example Window Code:</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> public ucExample(IInstanceHost host, ref String WindowTitle, String ApplicationID, String Parameters)\n {\n InitializeComponent();\n /*Used to add selected text to clipboard*/\n this.txtResults.TextSelected += txtResults_TextSelected;\n }\n\n void txtResults_TextSelected(string SelectedText)\n {\n Clipboard.SetText(SelectedText);\n }\n</code></pre>\n"
},
{
"answer_id": 35091222,
"author": "Jack Pines",
"author_id": 4474923,
"author_profile": "https://Stackoverflow.com/users/4474923",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.textblock.istextselectionenabled.aspx\">Windows Dev Center</a>:</p>\n\n<blockquote>\n <p><strong>TextBlock.IsTextSelectionEnabled property</strong></p>\n \n <p>[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see\n the <a href=\"http://go.microsoft.com/fwlink/p/?linkid=619132\">archive</a> ]</p>\n \n <p>Gets or sets a value that indicates whether text selection is enabled\n in the <a href=\"https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.textblock.aspx\">TextBlock</a>, either through user action or calling\n selection-related API.</p>\n</blockquote>\n"
},
{
"answer_id": 36224662,
"author": "Titwan",
"author_id": 509932,
"author_profile": "https://Stackoverflow.com/users/509932",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Really nice and easy solution, exactly what I wanted !\n</code></pre>\n\n<p>I bring some small modifications</p>\n\n<pre><code>public class TextBlockMoo : TextBlock \n{\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler OnTextSelected;\n protected void RaiseEvent()\n {\n if (OnTextSelected != null){OnTextSelected(SelectedText);}\n }\n\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n Brush _saveForeGroundBrush;\n Brush _saveBackGroundBrush;\n\n TextRange _ntr = null;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n\n if (_ntr!=null) {\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);\n }\n\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n _ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n\n // keep saved\n _saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);\n _saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);\n // change style\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));\n\n SelectedText = _ntr.Text;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43947726,
"author": "SimperT",
"author_id": 4367485,
"author_profile": "https://Stackoverflow.com/users/4367485",
"pm_score": 3,
"selected": false,
"text": "<p>While the question does say 'Selectable' I believe the intentional results is to get the text to the clipboard. This can easily and elegantly be achieved by adding a Context Menu and menu item called copy that puts the Textblock Text property value in clipboard. Just an idea anyway.</p>\n"
},
{
"answer_id": 45627524,
"author": "torvin",
"author_id": 332528,
"author_profile": "https://Stackoverflow.com/users/332528",
"pm_score": 7,
"selected": false,
"text": "<p>All the answers here are just using a <code>TextBox</code> or trying to implement text selection manually, which leads to poor performance or non-native behaviour (blinking caret in <code>TextBox</code>, no keyboard support in manual implementations etc.)</p>\n\n<p>After hours of digging around and reading the <a href=\"https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/FlowDocumentScrollViewer.cs,694a70a8f6818358\" rel=\"noreferrer\">WPF source code</a>, I instead discovered a way of enabling the native WPF text selection for <code>TextBlock</code> controls (or really any other controls). Most of the functionality around text selection is implemented in <code>System.Windows.Documents.TextEditor</code> system class. </p>\n\n<p>To enable text selection for your control you need to do two things:</p>\n\n<ol>\n<li><p>Call <code>TextEditor.RegisterCommandHandlers()</code> once to register class\nevent handlers</p></li>\n<li><p>Create an instance of <code>TextEditor</code> for each instance of your class and pass the underlying instance of your <code>System.Windows.Documents.ITextContainer</code> to it</p></li>\n</ol>\n\n<p>There's also a requirement that your control's <code>Focusable</code> property is set to <code>True</code>.</p>\n\n<p>This is it! Sounds easy, but unfortunately <code>TextEditor</code> class is marked as internal. So I had to write a reflection wrapper around it:</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>class TextEditorWrapper\n{\n private static readonly Type TextEditorType = Type.GetType(\"System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty(\"IsReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty(\"TextView\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod(\"RegisterCommandHandlers\", \n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n private static readonly Type TextContainerType = Type.GetType(\"System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty(\"TextView\");\n\n private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty(\"TextContainer\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n public static TextEditorWrapper CreateFor(TextBlock tb)\n {\n var textContainer = TextContainerProp.GetValue(tb);\n\n var editor = new TextEditorWrapper(textContainer, tb, false);\n IsReadOnlyProp.SetValue(editor._editor, true);\n TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));\n\n return editor;\n }\n\n private readonly object _editor;\n\n public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)\n {\n _editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, \n null, new[] { textContainer, uiScope, isUndoEnabled }, null);\n }\n}\n</code></pre>\n\n<p>I also created a <code>SelectableTextBlock</code> derived from <code>TextBlock</code> that takes the steps noted above:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n }\n}\n</code></pre>\n\n<p>Another option would be to create an attached property for <code>TextBlock</code> to enable text selection on demand. In this case, to disable the selection again, one needs to detach a <code>TextEditor</code> by using the reflection equivalent of this code:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>_editor.TextContainer.TextView = null;\n_editor.OnDetach();\n_editor = null;\n</code></pre>\n"
},
{
"answer_id": 53296378,
"author": "Angel T",
"author_id": 2814337,
"author_profile": "https://Stackoverflow.com/users/2814337",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public MainPage()\n{\n this.InitializeComponent();\n ...\n ...\n ...\n //Make Start result text copiable\n TextBlockStatusStart.IsTextSelectionEnabled = true;\n}\n</code></pre>\n"
},
{
"answer_id": 55397367,
"author": "Rauland",
"author_id": 602152,
"author_profile": "https://Stackoverflow.com/users/602152",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to @torvin's answer and as @Dave Huang mentioned in the comments if you have <code>TextTrimming=\"CharacterEllipsis\"</code> enabled the application crashes when you hover over the ellipsis.</p>\n\n<p>I tried other options mentioned in the thread about using a TextBox but it really doesn't seem to be the solution either as it doesn't show the 'ellipsis' and also if the text is too long to fit the container selecting the content of the textbox 'scrolls' internally which isn't a TextBlock behaviour.</p>\n\n<p>I think the best solution is @torvin's answer but has the nasty crash when hovering over the ellipsis. </p>\n\n<p>I know it isn't pretty, but subscribing/unsubscribing internally to unhandled exceptions and handling the exception was the only way I found of solving this problem, please share if somebody has a better solution :)</p>\n\n<pre><code>public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n\n this.Loaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;\n };\n this.Unloaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n };\n }\n\n private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n if (!string.IsNullOrEmpty(e?.Exception?.StackTrace))\n {\n if (e.Exception.StackTrace.Contains(\"System.Windows.Controls.TextBlock.GetTextPositionFromDistance\"))\n {\n e.Handled = true;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67036133,
"author": "Nicke Manarin",
"author_id": 1735672,
"author_profile": "https://Stackoverflow.com/users/1735672",
"pm_score": 0,
"selected": false,
"text": "<p>Just use a <code>FlowDocument</code> inside a <code>FlowDocumentScrollViewer</code>, passing your inlines to the element.\nYou can control the style of the element, in my case I added a small border.</p>\n<pre class=\"lang-xml prettyprint-override\"><code><FlowDocumentScrollViewer Grid.Row="2" Margin="5,3" BorderThickness="1" \n BorderBrush="{DynamicResource Element.Border}" \n VerticalScrollBarVisibility="Auto">\n <FlowDocument>\n <Paragraph>\n <Bold>Some bold text in the paragraph.</Bold>\n Some text that is not bold.\n </Paragraph>\n\n <List>\n <ListItem>\n <Paragraph>ListItem 1</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 2</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 3</Paragraph>\n </ListItem>\n </List>\n </FlowDocument>\n</FlowDocumentScrollViewer>\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/vXYTk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vXYTk.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 68139947,
"author": "Shakti",
"author_id": 741147,
"author_profile": "https://Stackoverflow.com/users/741147",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what worked for me. I created a class TextBlockEx that is derived from TextBox and is set read-only, and text wrap in the constructor.</p>\n<pre><code>public class TextBlockEx : TextBox\n{\n public TextBlockEx()\n {\n base.BorderThickness = new Thickness(0);\n IsReadOnly = true;\n TextWrapping = TextWrapping.Wrap;\n //Background = Brushes.Transparent; // Uncomment to get parent's background color\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69110678,
"author": "Michael Wagner",
"author_id": 12470516,
"author_profile": "https://Stackoverflow.com/users/12470516",
"pm_score": 0,
"selected": false,
"text": "<p>I agree most answers here do not create a selectable Text<strong>Block</strong>. @Billy Willoughby's worked well however it didn't have a visible cue for selection. I'd like to extend his extension which can highlight text as it is selected. It also incorporates double and triple click selection. You can add a context menu with a "Copy" if needed.\nIt uses the <code>Background</code> property to "highlight" the selection so it is limited in that it will overwrite <code>Run.Background</code></p>\n<p><a href=\"https://github.com/mwagnerEE/WagnerControls\" rel=\"nofollow noreferrer\">https://github.com/mwagnerEE/WagnerControls</a></p>\n"
},
{
"answer_id": 74535160,
"author": "altair",
"author_id": 1516045,
"author_profile": "https://Stackoverflow.com/users/1516045",
"pm_score": 0,
"selected": false,
"text": "<p>Added Selection & SelectionChanged Event to torvin's code</p>\n<pre><code>public class SelectableTextBlock : TextBlock\n{\n\n static readonly Type TextEditorType\n = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");\n\n static readonly PropertyInfo IsReadOnlyProp\n = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly PropertyInfo TextViewProp\n = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly MethodInfo RegisterMethod\n = TextEditorType.GetMethod("RegisterCommandHandlers",\n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n static readonly Type TextContainerType\n = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");\n static readonly PropertyInfo TextContainerTextViewProp\n = TextContainerType.GetProperty("TextView");\n\n static readonly PropertyInfo TextContainerTextSelectionProp\n = TextContainerType.GetProperty("TextSelection");\n\n static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n //private readonly TextEditorWrapper _editor;\n object? textContainer;\n object? editor;\n public TextSelection TextSelection { get; private set; }\n\n public SelectableTextBlock()\n {\n textContainer = TextContainerProp.GetValue(this);\n\n editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,\n null, new[] { textContainer, this, false }, null);\n\n\n IsReadOnlyProp.SetValue(editor, true);\n TextViewProp.SetValue(editor, TextContainerTextViewProp.GetValue(textContainer));\n\n TextSelection = (TextSelection)TextContainerTextSelectionProp.GetValue(textContainer);\n TextSelection.Changed += (s, e) => OnSelectionChanged?.Invoke(this, e);\n }\n\n public event EventHandler OnSelectionChanged;\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133/"
]
| How to allow `TextBlock`'s text to be selectable?
I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable? | Use a `TextBox` with these settings instead to make it read only and to look like a `TextBlock` control.
```
<TextBox Background="Transparent"
BorderThickness="0"
Text="{Binding Text, Mode=OneWay}"
IsReadOnly="True"
TextWrapping="Wrap" />
``` |
136,436 | <p>I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'. </p>
<p>I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up?</p>
<p>Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for. </p>
<p>Thanks.</p>
| [
{
"answer_id": 136675,
"author": "Bruce",
"author_id": 6310,
"author_profile": "https://Stackoverflow.com/users/6310",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not sure if you can make a TextBlock selectable, but another option would be to use a RichTextBox - it is like a TextBox as you suggested, but supports the formatting you want.</p>\n"
},
{
"answer_id": 137406,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 4,
"selected": false,
"text": "<p>Create ControlTemplate for the TextBlock and put a TextBox inside with readonly property set.\nOr just use TextBox and make it readonly, then you can change the TextBox.Style to make it looks like TextBlock.</p>\n"
},
{
"answer_id": 2506504,
"author": "MSB",
"author_id": 300663,
"author_profile": "https://Stackoverflow.com/users/300663",
"pm_score": 9,
"selected": true,
"text": "<p>Use a <code>TextBox</code> with these settings instead to make it read only and to look like a <code>TextBlock</code> control.</p>\n<pre><code><TextBox Background="Transparent"\n BorderThickness="0"\n Text="{Binding Text, Mode=OneWay}"\n IsReadOnly="True"\n TextWrapping="Wrap" />\n</code></pre>\n"
},
{
"answer_id": 3132657,
"author": "Richard",
"author_id": 20038,
"author_profile": "https://Stackoverflow.com/users/20038",
"pm_score": 1,
"selected": false,
"text": "<p>There is an alternative solution that might be adaptable to the RichTextBox oultined in this <a href=\"http://beta.blogs.microsoft.co.il/blogs/eshaham/archive/2009/07/06/selectable-text-control.aspx\" rel=\"nofollow noreferrer\">blog post</a> - it used a trigger to swap out the control template when the use hovers over the control - should help with performance</p>\n"
},
{
"answer_id": 4145443,
"author": "Ilya Serbis",
"author_id": 355438,
"author_profile": "https://Stackoverflow.com/users/355438",
"pm_score": 1,
"selected": false,
"text": "<pre><code>\nnew TextBox\n{\n Text = text,\n TextAlignment = TextAlignment.Center,\n TextWrapping = TextWrapping.Wrap,\n IsReadOnly = true,\n Background = Brushes.Transparent,\n BorderThickness = new Thickness()\n {\n Top = 0,\n Bottom = 0,\n Left = 0,\n Right = 0\n }\n};\n</code>\n</pre>\n"
},
{
"answer_id": 7399948,
"author": "Saraf Talukder",
"author_id": 690310,
"author_profile": "https://Stackoverflow.com/users/690310",
"pm_score": 2,
"selected": false,
"text": "<p>TextBlock does not have a template. So inorder to achieve this, we need to use a TextBox whose style is changed to behave as a textBlock. </p>\n\n<pre><code><Style x:Key=\"TextBlockUsingTextBoxStyle\" BasedOn=\"{x:Null}\" TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"BorderBrush\" Value=\"{StaticResource TextBoxBorder}\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Padding\" Value=\"1\"/>\n <Setter Property=\"AllowDrop\" Value=\"true\"/>\n <Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\"/>\n <Setter Property=\"ScrollViewer.PanningMode\" Value=\"VerticalFirst\"/>\n <Setter Property=\"Stylus.IsFlicksEnabled\" Value=\"False\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBox BorderThickness=\"{TemplateBinding BorderThickness}\" IsReadOnly=\"True\" Text=\"{TemplateBinding Text}\" Background=\"{x:Null}\" BorderBrush=\"{x:Null}\" />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 9231349,
"author": "jdearana",
"author_id": 207949,
"author_profile": "https://Stackoverflow.com/users/207949",
"pm_score": 4,
"selected": false,
"text": "<p>Apply this style to your TextBox and that's it (inspired from <a href=\"https://web.archive.org/web/20130601215415/http://beta.blogs.microsoft.co.il/blogs/eshaham/archive/2009/07/06/selectable-text-control.aspx\" rel=\"nofollow noreferrer\">this article</a>):</p>\n\n<pre><code><Style x:Key=\"SelectableTextBlockLikeStyle\" TargetType=\"TextBox\" BasedOn=\"{StaticResource {x:Type TextBox}}\">\n <Setter Property=\"IsReadOnly\" Value=\"True\"/>\n <Setter Property=\"IsTabStop\" Value=\"False\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"Padding\" Value=\"-2,0,0,0\"/>\n <!-- The Padding -2,0,0,0 is required because the TextBox\n seems to have an inherent \"Padding\" of about 2 pixels.\n Without the Padding property,\n the text seems to be 2 pixels to the left\n compared to a TextBlock\n -->\n <Style.Triggers>\n <MultiTrigger>\n <MultiTrigger.Conditions>\n <Condition Property=\"IsMouseOver\" Value=\"False\" />\n <Condition Property=\"IsFocused\" Value=\"False\" />\n </MultiTrigger.Conditions>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBlock Text=\"{TemplateBinding Text}\" \n FontSize=\"{TemplateBinding FontSize}\"\n FontStyle=\"{TemplateBinding FontStyle}\"\n FontFamily=\"{TemplateBinding FontFamily}\"\n FontWeight=\"{TemplateBinding FontWeight}\"\n TextWrapping=\"{TemplateBinding TextWrapping}\"\n Foreground=\"{DynamicResource NormalText}\"\n Padding=\"0,0,0,0\"\n />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </MultiTrigger>\n </Style.Triggers>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 24609144,
"author": "Robert Važan",
"author_id": 1981276,
"author_profile": "https://Stackoverflow.com/users/1981276",
"pm_score": -1,
"selected": false,
"text": "<p>I've implemented <a href=\"http://blog.angeloflogic.com/2014/07/selectabletextblock-in-junglecontrols.html\" rel=\"nofollow\">SelectableTextBlock</a> in my opensource controls library. You can use it like this:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><jc:SelectableTextBlock Text=\"Some text\" />\n</code></pre>\n"
},
{
"answer_id": 32870521,
"author": "Billy Willoughby",
"author_id": 4810862,
"author_profile": "https://Stackoverflow.com/users/4810862",
"pm_score": 5,
"selected": false,
"text": "<p>I have been unable to find any example of really answering the question. All the answers used a Textbox or RichTextbox. I needed a solution that allowed me to use a TextBlock, and this is the solution I created. </p>\n\n<p>I believe the correct way to do this is to extend the TextBlock class. This is the code I used to extend the TextBlock class to allow me to select the text and copy it to clipboard. \"sdo\" is the namespace reference I used in the WPF. </p>\n\n<p><strong>WPF Using Extended Class:</strong></p>\n\n<pre><code>xmlns:sdo=\"clr-namespace:iFaceCaseMain\"\n\n<sdo:TextBlockMoo x:Name=\"txtResults\" Background=\"Black\" Margin=\"5,5,5,5\" \n Foreground=\"GreenYellow\" FontSize=\"14\" FontFamily=\"Courier New\"></TextBlockMoo>\n</code></pre>\n\n<p><strong>Code Behind for Extended Class:</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public partial class TextBlockMoo : TextBlock \n{\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler TextSelected;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n TextRange otr = new TextRange(this.ContentStart, this.ContentEnd);\n otr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));\n\n TextRange ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.White));\n\n SelectedText = ntr.Text;\n if (!(TextSelected == null))\n {\n TextSelected(SelectedText);\n }\n }\n}\n</code></pre>\n\n<p><strong>Example Window Code:</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> public ucExample(IInstanceHost host, ref String WindowTitle, String ApplicationID, String Parameters)\n {\n InitializeComponent();\n /*Used to add selected text to clipboard*/\n this.txtResults.TextSelected += txtResults_TextSelected;\n }\n\n void txtResults_TextSelected(string SelectedText)\n {\n Clipboard.SetText(SelectedText);\n }\n</code></pre>\n"
},
{
"answer_id": 35091222,
"author": "Jack Pines",
"author_id": 4474923,
"author_profile": "https://Stackoverflow.com/users/4474923",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.textblock.istextselectionenabled.aspx\">Windows Dev Center</a>:</p>\n\n<blockquote>\n <p><strong>TextBlock.IsTextSelectionEnabled property</strong></p>\n \n <p>[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see\n the <a href=\"http://go.microsoft.com/fwlink/p/?linkid=619132\">archive</a> ]</p>\n \n <p>Gets or sets a value that indicates whether text selection is enabled\n in the <a href=\"https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.textblock.aspx\">TextBlock</a>, either through user action or calling\n selection-related API.</p>\n</blockquote>\n"
},
{
"answer_id": 36224662,
"author": "Titwan",
"author_id": 509932,
"author_profile": "https://Stackoverflow.com/users/509932",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Really nice and easy solution, exactly what I wanted !\n</code></pre>\n\n<p>I bring some small modifications</p>\n\n<pre><code>public class TextBlockMoo : TextBlock \n{\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler OnTextSelected;\n protected void RaiseEvent()\n {\n if (OnTextSelected != null){OnTextSelected(SelectedText);}\n }\n\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n Brush _saveForeGroundBrush;\n Brush _saveBackGroundBrush;\n\n TextRange _ntr = null;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n\n if (_ntr!=null) {\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);\n }\n\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n _ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n\n // keep saved\n _saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);\n _saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);\n // change style\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));\n\n SelectedText = _ntr.Text;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43947726,
"author": "SimperT",
"author_id": 4367485,
"author_profile": "https://Stackoverflow.com/users/4367485",
"pm_score": 3,
"selected": false,
"text": "<p>While the question does say 'Selectable' I believe the intentional results is to get the text to the clipboard. This can easily and elegantly be achieved by adding a Context Menu and menu item called copy that puts the Textblock Text property value in clipboard. Just an idea anyway.</p>\n"
},
{
"answer_id": 45627524,
"author": "torvin",
"author_id": 332528,
"author_profile": "https://Stackoverflow.com/users/332528",
"pm_score": 7,
"selected": false,
"text": "<p>All the answers here are just using a <code>TextBox</code> or trying to implement text selection manually, which leads to poor performance or non-native behaviour (blinking caret in <code>TextBox</code>, no keyboard support in manual implementations etc.)</p>\n\n<p>After hours of digging around and reading the <a href=\"https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/FlowDocumentScrollViewer.cs,694a70a8f6818358\" rel=\"noreferrer\">WPF source code</a>, I instead discovered a way of enabling the native WPF text selection for <code>TextBlock</code> controls (or really any other controls). Most of the functionality around text selection is implemented in <code>System.Windows.Documents.TextEditor</code> system class. </p>\n\n<p>To enable text selection for your control you need to do two things:</p>\n\n<ol>\n<li><p>Call <code>TextEditor.RegisterCommandHandlers()</code> once to register class\nevent handlers</p></li>\n<li><p>Create an instance of <code>TextEditor</code> for each instance of your class and pass the underlying instance of your <code>System.Windows.Documents.ITextContainer</code> to it</p></li>\n</ol>\n\n<p>There's also a requirement that your control's <code>Focusable</code> property is set to <code>True</code>.</p>\n\n<p>This is it! Sounds easy, but unfortunately <code>TextEditor</code> class is marked as internal. So I had to write a reflection wrapper around it:</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>class TextEditorWrapper\n{\n private static readonly Type TextEditorType = Type.GetType(\"System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty(\"IsReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty(\"TextView\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod(\"RegisterCommandHandlers\", \n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n private static readonly Type TextContainerType = Type.GetType(\"System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty(\"TextView\");\n\n private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty(\"TextContainer\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n public static TextEditorWrapper CreateFor(TextBlock tb)\n {\n var textContainer = TextContainerProp.GetValue(tb);\n\n var editor = new TextEditorWrapper(textContainer, tb, false);\n IsReadOnlyProp.SetValue(editor._editor, true);\n TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));\n\n return editor;\n }\n\n private readonly object _editor;\n\n public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)\n {\n _editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, \n null, new[] { textContainer, uiScope, isUndoEnabled }, null);\n }\n}\n</code></pre>\n\n<p>I also created a <code>SelectableTextBlock</code> derived from <code>TextBlock</code> that takes the steps noted above:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n }\n}\n</code></pre>\n\n<p>Another option would be to create an attached property for <code>TextBlock</code> to enable text selection on demand. In this case, to disable the selection again, one needs to detach a <code>TextEditor</code> by using the reflection equivalent of this code:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>_editor.TextContainer.TextView = null;\n_editor.OnDetach();\n_editor = null;\n</code></pre>\n"
},
{
"answer_id": 53296378,
"author": "Angel T",
"author_id": 2814337,
"author_profile": "https://Stackoverflow.com/users/2814337",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public MainPage()\n{\n this.InitializeComponent();\n ...\n ...\n ...\n //Make Start result text copiable\n TextBlockStatusStart.IsTextSelectionEnabled = true;\n}\n</code></pre>\n"
},
{
"answer_id": 55397367,
"author": "Rauland",
"author_id": 602152,
"author_profile": "https://Stackoverflow.com/users/602152",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to @torvin's answer and as @Dave Huang mentioned in the comments if you have <code>TextTrimming=\"CharacterEllipsis\"</code> enabled the application crashes when you hover over the ellipsis.</p>\n\n<p>I tried other options mentioned in the thread about using a TextBox but it really doesn't seem to be the solution either as it doesn't show the 'ellipsis' and also if the text is too long to fit the container selecting the content of the textbox 'scrolls' internally which isn't a TextBlock behaviour.</p>\n\n<p>I think the best solution is @torvin's answer but has the nasty crash when hovering over the ellipsis. </p>\n\n<p>I know it isn't pretty, but subscribing/unsubscribing internally to unhandled exceptions and handling the exception was the only way I found of solving this problem, please share if somebody has a better solution :)</p>\n\n<pre><code>public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n\n this.Loaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;\n };\n this.Unloaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n };\n }\n\n private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n if (!string.IsNullOrEmpty(e?.Exception?.StackTrace))\n {\n if (e.Exception.StackTrace.Contains(\"System.Windows.Controls.TextBlock.GetTextPositionFromDistance\"))\n {\n e.Handled = true;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67036133,
"author": "Nicke Manarin",
"author_id": 1735672,
"author_profile": "https://Stackoverflow.com/users/1735672",
"pm_score": 0,
"selected": false,
"text": "<p>Just use a <code>FlowDocument</code> inside a <code>FlowDocumentScrollViewer</code>, passing your inlines to the element.\nYou can control the style of the element, in my case I added a small border.</p>\n<pre class=\"lang-xml prettyprint-override\"><code><FlowDocumentScrollViewer Grid.Row="2" Margin="5,3" BorderThickness="1" \n BorderBrush="{DynamicResource Element.Border}" \n VerticalScrollBarVisibility="Auto">\n <FlowDocument>\n <Paragraph>\n <Bold>Some bold text in the paragraph.</Bold>\n Some text that is not bold.\n </Paragraph>\n\n <List>\n <ListItem>\n <Paragraph>ListItem 1</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 2</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 3</Paragraph>\n </ListItem>\n </List>\n </FlowDocument>\n</FlowDocumentScrollViewer>\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/vXYTk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vXYTk.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 68139947,
"author": "Shakti",
"author_id": 741147,
"author_profile": "https://Stackoverflow.com/users/741147",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what worked for me. I created a class TextBlockEx that is derived from TextBox and is set read-only, and text wrap in the constructor.</p>\n<pre><code>public class TextBlockEx : TextBox\n{\n public TextBlockEx()\n {\n base.BorderThickness = new Thickness(0);\n IsReadOnly = true;\n TextWrapping = TextWrapping.Wrap;\n //Background = Brushes.Transparent; // Uncomment to get parent's background color\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69110678,
"author": "Michael Wagner",
"author_id": 12470516,
"author_profile": "https://Stackoverflow.com/users/12470516",
"pm_score": 0,
"selected": false,
"text": "<p>I agree most answers here do not create a selectable Text<strong>Block</strong>. @Billy Willoughby's worked well however it didn't have a visible cue for selection. I'd like to extend his extension which can highlight text as it is selected. It also incorporates double and triple click selection. You can add a context menu with a "Copy" if needed.\nIt uses the <code>Background</code> property to "highlight" the selection so it is limited in that it will overwrite <code>Run.Background</code></p>\n<p><a href=\"https://github.com/mwagnerEE/WagnerControls\" rel=\"nofollow noreferrer\">https://github.com/mwagnerEE/WagnerControls</a></p>\n"
},
{
"answer_id": 74535160,
"author": "altair",
"author_id": 1516045,
"author_profile": "https://Stackoverflow.com/users/1516045",
"pm_score": 0,
"selected": false,
"text": "<p>Added Selection & SelectionChanged Event to torvin's code</p>\n<pre><code>public class SelectableTextBlock : TextBlock\n{\n\n static readonly Type TextEditorType\n = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");\n\n static readonly PropertyInfo IsReadOnlyProp\n = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly PropertyInfo TextViewProp\n = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly MethodInfo RegisterMethod\n = TextEditorType.GetMethod("RegisterCommandHandlers",\n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n static readonly Type TextContainerType\n = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");\n static readonly PropertyInfo TextContainerTextViewProp\n = TextContainerType.GetProperty("TextView");\n\n static readonly PropertyInfo TextContainerTextSelectionProp\n = TextContainerType.GetProperty("TextSelection");\n\n static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n //private readonly TextEditorWrapper _editor;\n object? textContainer;\n object? editor;\n public TextSelection TextSelection { get; private set; }\n\n public SelectableTextBlock()\n {\n textContainer = TextContainerProp.GetValue(this);\n\n editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,\n null, new[] { textContainer, this, false }, null);\n\n\n IsReadOnlyProp.SetValue(editor, true);\n TextViewProp.SetValue(editor, TextContainerTextViewProp.GetValue(textContainer));\n\n TextSelection = (TextSelection)TextContainerTextSelectionProp.GetValue(textContainer);\n TextSelection.Changed += (s, e) => OnSelectionChanged?.Invoke(this, e);\n }\n\n public event EventHandler OnSelectionChanged;\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424554/"
]
| I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'.
I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up?
Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for.
Thanks. | Use a `TextBox` with these settings instead to make it read only and to look like a `TextBlock` control.
```
<TextBox Background="Transparent"
BorderThickness="0"
Text="{Binding Text, Mode=OneWay}"
IsReadOnly="True"
TextWrapping="Wrap" />
``` |
136,443 | <p>We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block:</p>
<pre><code>public PageSizer(string href, int index)
{
HRef = href;
PageIndex = index;
}
</code></pre>
<p>Copy and pasted from IE7, ends up like this:</p>
<pre>
public PageSizer(string href, int index){ HRef = href; PageIndex = index; }
</pre>
<p>Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this:</p>
<pre><code><pre><code>public PageSizer(string href, int index)
{
HRef = href;
PageIndex = index;
}
</code></pre>
</code></pre>
<p>So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way?</p>
<blockquote>
<p>Update: <strong>this specifically has to do with <code><pre></code> <code><code></code> blocks that are being modified at runtime via JavaScript.</strong> The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.</p>
</blockquote>
| [
{
"answer_id": 136510,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": -1,
"selected": false,
"text": "<p>Remove the inner <code><code></code>. IE's copy/paste behavior could see that as an inline tag and forget about the visible whitespace.</p>\n"
},
{
"answer_id": 136586,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 4,
"selected": false,
"text": "<p>Here's the issue:</p>\n\n<p>Your code colorization script replaces line breaks with <br /> tags. When copying/pasting, IE7 apparently doesn't translate the <br /> tag into a linebreak like it does for the screen.</p>\n\n<p>In other words, your code becomes this:</p>\n\n<pre><code>public PageSizer(string href, int index)<br />{<br /> HRef = href;<br /> PageIndex = index;<br /> }</code></pre>\n\n<p>But you want it to become this:</p>\n\n<pre><code>\npublic PageSizer(string href, int index)<br />\n{<br />\n HRef = href;<br />\n PageIndex = index;<br />\n}<br />\n</code></pre>\n\n<p>In the latest version of prettify.js on Google Code, the line responsible is line 1001 (part of recombineTagsAndDecorations):</p>\n\n<pre><code>\nhtml.push(htmlChunk.replace(newlineRe, '<br />'));\n</code></pre>\n\n<p>Edited, based on the comments:<br>\nFor IE7, this is what the line should probably be changed to:</p>\n\n<pre><code>\nhtml.push(htmlChunk.replace(newlineRe, '\\n'));\n</code></pre>\n\n<p>(Assuming newlineRe is a placeholder).</p>\n\n<p>This fix also holds up in Chrome, and FFX3... I'm not sure which (if any) browsers need the <br /> tags.</p>\n\n<p><strong>Update:</strong>\nMore information in my second response:<br>\n<a href=\"https://stackoverflow.com/questions/136443/why-doesnt-ie7-copy-precode-blocks-to-the-clipboard-correctly#156069\">Why doesn't IE7 copy <pre><code> blocks to the clipboard correctly?</a></p>\n"
},
{
"answer_id": 136698,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "<p>This looks like a bug in IE, <em>BR</em> tags inside the <em>PRE</em> or <em>CODE</em> are not being converted into newlines in the plain text copy buffer. The rich text copy buffer is fine, so the paste works as expected for applications like <em>wordpad</em>.</p>\n\n<p>The prettify script, that colours the code, removes <strong>all</strong> the whitespace and replaces it with HTML tags for spaces and new lines. The generated code looks something like this:</p>\n\n<pre>\n<pre><code>code<br/>&nbsp;&nbsp;code<br/>&nbsp;&nbsp;code<br/>code</code></pre>\n</pre>\n\n<p>The <em>PRE</em> and <em>CODE</em> tags are rendered by defaults with the CSS style of <strong><em>{whitespace: pre}</em></strong>. In this case, IE is failing to turn the <em>BR</em> tags into newlines. It would work on your original HTML because IE will successfully turn actual newlines into newlines.</p>\n\n<p>In order to fix it you have 3 options. (I am presuming you want nice HTML <strong>and</strong> the ability to work well with and without javascript enabled on the client):</p>\n\n<ol>\n<li><p>You could place the code inside a normal div and use CSS to render it using <strong><em>{whitespace: pre}</em></strong>. This is a simple solution, although might not please an HTML markup purist.</p></li>\n<li><p>You could have two copies of the code, one using proper <em>PRE</em> / <em>CODE</em> tags and another in a normal div. In your CSS you hide the normal div. Using javascript you prettify the normal div and hide the pre/code version.</p></li>\n<li><p>Modify the prettify script to recognise that it is acting on a <em>PRE</em> or <em>CODE</em> element and to not replace the whitespace in that event.</p></li>\n</ol>\n\n<hr>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li><p>What is important is not the HTML in your source, but the HTML that is generated after the prettify script has ran on it.</p></li>\n<li><p>This bug is still present even if the white-space mode of the <em>PRE</em> is changed to <em>normal</em> using CSS.</p></li>\n</ul>\n"
},
{
"answer_id": 155826,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 0,
"selected": false,
"text": "<p>bad news : none of the proposed fixes work. Modifying prettify.js around line 1000</p>\n\n<pre><code>html.push(htmlChunk.replace(newlineRe, '\\n'));\n</code></pre>\n\n<p>This causes double-spacing in other browsers, and <em>still</em> doesn't solve the IE7 copy to notepad problem! So even if I selectively detected IE7, this \"fix\" doesn't fix anything.</p>\n\n<p>I guess maybe it is simply a bug in IE7 having to do with JavaScript rebuilding a <code><pre></code> element -- no matter how many \\n newlines I put in there, nothing changes w/r/t to the paste to notepad behavior.</p>\n"
},
{
"answer_id": 156069,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 0,
"selected": false,
"text": "<p>@Jeff Atwood\nIt's the right idea, but the implementation still needs work. I guess my air code just didn't cut it :)</p>\n\n<p>I suspect that the fix I mentioned earlier doesn't work because prettify is doing some additional processing on the text after line ~1000 is called.</p>\n\n<p>Trying to track the content backwards from when it's added to the page, I came across this comment around line 1227:</p>\n\n<pre><code>\n// Replace <br>s with line-feeds so that copying and pasting works\n// on IE 6.\n// Doing this on other browsers breaks lots of stuff since \\r\\n is\n// treated as two newlines on Firefox, and doing this also slows\n// down rendering.\n</code></pre>\n\n<p>When I took the isIE6 condition off of the code, it mostly worked in IE7 (there was an extra line break at the top and bottom), and Firefox 3... But I'd assume that it causes issues with older versions of FFX.</p>\n\n<p>At the very least, it appears that IE7 will require \\r\\n, instead of just \\n. Figuring out exactly what will work with which browsers will take a more extensive test setup than I have handy at the moment.</p>\n\n<p>Anyway, inserting the \\r\\n for IE7 appears to be basically what needs to happen. I'll keep poking around prettify to see if I can narrow it down further.</p>\n\n<p><strong>UPDATE:</strong> IE7 appears to strip newline characters (\\r or \\n) from strings that are assigned to an innerHTML property. It looks like they need to be added back in, around line 1227.</p>\n\n<p>A correct solution would probably mean inserting a placeholder tag around line 1000, and then replacing it around line 1227.</p>\n"
},
{
"answer_id": 159582,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 6,
"selected": true,
"text": "<p>It seems that this is a known bug for IE6 and prettify.js has a workaround for it. Specifically it replaces the BR tags with '\\r\\n'.</p>\n\n<p>By modifying the check to allow for IE6 or 7 then the cut-and-paste will work correctly from IE7, but it will render with a <em>newline</em> followed by a <em>space</em>. By checking for IE7 and providing just a '\\r' instead of a '\\r\\n' it will continue to cut-and-paste and render correctly.</p>\n\n<p>Add this code to prettify.js:</p>\n\n<pre><code>function _pr_isIE7() {\n var isIE7 = navigator && navigator.userAgent &&\n /\\bMSIE 7\\./.test(navigator.userAgent);\n _pr_isIE7 = function () { return isIE7; };\n return isIE7;\n}\n</code></pre>\n\n<p>and then modify the prettyPrint function as follows:</p>\n\n<pre><code> function prettyPrint(opt_whenDone) {\n var isIE6 = _pr_isIE6();\n+ var isIE7 = _pr_isIE7();\n</code></pre>\n\n<p>...</p>\n\n<pre><code>- if (isIE6 && cs.tagName === 'PRE') {\n+ if ((isIE6 || isIE7) && cs.tagName === 'PRE') {\n var lineBreaks = cs.getElementsByTagName('br');\n+ var newline;\n+ if (isIE6) {\n+ newline = '\\r\\n';\n+ } else {\n+ newline = '\\r';\n+ }\n for (var j = lineBreaks.length; --j >= 0;) {\n var lineBreak = lineBreaks[j];\n lineBreak.parentNode.replaceChild(\n- document.createTextNode('\\r\\n'), lineBreak);\n+ document.createTextNode(newline), lineBreak);\n }\n</code></pre>\n\n<p>You can see a <a href=\"http://andrjohn.myzen.co.uk/soTest/136443.html\" rel=\"noreferrer\">working example here</a>.</p>\n\n<p><strong>Note:</strong> I haven't tested the original workaround in IE6, so I'm guessing it renders without the space caused by the '\\n' that is seen in IE7, otherwise the fix is simpler.</p>\n"
},
{
"answer_id": 8017026,
"author": "jlo",
"author_id": 949248,
"author_profile": "https://Stackoverflow.com/users/949248",
"pm_score": 1,
"selected": false,
"text": "<p>This site has addressed the issue: <a href=\"http://www.developerfusion.com/tools/convert/csharp-to-vb/\" rel=\"nofollow\">http://www.developerfusion.com/tools/convert/csharp-to-vb/</a></p>\n\n<p>I suggest a \"Copy to Clipboard\" button as part of the code display box.\nThis button would copy version of the displayed information as plain text.\nThe plain text could be stored as an internal page property.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
]
| We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block:
```
public PageSizer(string href, int index)
{
HRef = href;
PageIndex = index;
}
```
Copy and pasted from IE7, ends up like this:
```
public PageSizer(string href, int index){ HRef = href; PageIndex = index; }
```
Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this:
```
<pre><code>public PageSizer(string href, int index)
{
HRef = href;
PageIndex = index;
}
</code></pre>
```
So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way?
>
> Update: **this specifically has to do with `<pre>` `<code>` blocks that are being modified at runtime via JavaScript.** The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.
>
>
> | It seems that this is a known bug for IE6 and prettify.js has a workaround for it. Specifically it replaces the BR tags with '\r\n'.
By modifying the check to allow for IE6 or 7 then the cut-and-paste will work correctly from IE7, but it will render with a *newline* followed by a *space*. By checking for IE7 and providing just a '\r' instead of a '\r\n' it will continue to cut-and-paste and render correctly.
Add this code to prettify.js:
```
function _pr_isIE7() {
var isIE7 = navigator && navigator.userAgent &&
/\bMSIE 7\./.test(navigator.userAgent);
_pr_isIE7 = function () { return isIE7; };
return isIE7;
}
```
and then modify the prettyPrint function as follows:
```
function prettyPrint(opt_whenDone) {
var isIE6 = _pr_isIE6();
+ var isIE7 = _pr_isIE7();
```
...
```
- if (isIE6 && cs.tagName === 'PRE') {
+ if ((isIE6 || isIE7) && cs.tagName === 'PRE') {
var lineBreaks = cs.getElementsByTagName('br');
+ var newline;
+ if (isIE6) {
+ newline = '\r\n';
+ } else {
+ newline = '\r';
+ }
for (var j = lineBreaks.length; --j >= 0;) {
var lineBreak = lineBreaks[j];
lineBreak.parentNode.replaceChild(
- document.createTextNode('\r\n'), lineBreak);
+ document.createTextNode(newline), lineBreak);
}
```
You can see a [working example here](http://andrjohn.myzen.co.uk/soTest/136443.html).
**Note:** I haven't tested the original workaround in IE6, so I'm guessing it renders without the space caused by the '\n' that is seen in IE7, otherwise the fix is simpler. |
136,444 | <p>I'm working on an embedded linux system in C, I'm looking for the source code to the equivalet of SendARP in Windows. Any pointers?</p>
| [
{
"answer_id": 136492,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>This may be of interest: <a href=\"http://cvs.linux-ha.org/viewcvs/viewcvs.cgi/linux-ha/resources/heartbeat/SendArp.in?rev=1.4\" rel=\"nofollow noreferrer\">http://cvs.linux-ha.org/viewcvs/viewcvs.cgi/linux-ha/resources/heartbeat/SendArp.in?rev=1.4</a></p>\n\n<p>It is an implmenetation in a Bourne Shell script.</p>\n"
},
{
"answer_id": 136511,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 0,
"selected": false,
"text": "<p>I've never seen anything specifically for ARP, but I think you can send any kind of packet you want using <a href=\"http://www.tcpdump.org/pcap3_man.html\" rel=\"nofollow noreferrer\">libpcap</a> and the appropriate RFCs.</p>\n"
},
{
"answer_id": 137384,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 3,
"selected": true,
"text": "<p>Take a look at <a href=\"http://freshmeat.net/projects/arping/\" rel=\"nofollow noreferrer\">arping</a>. The quick and dirty way of sending an arp would be to do:</p>\n\n<pre><code>\nfoo = system(\"/somepath/arping somehost\");\n</code></pre>\n\n<p>But a look through the arping source should be able to give you a better solution.</p>\n\n<p>For the all-out solution though, you can construct your own by hand and use either a raw socket or <a href=\"http://www.tcpdump.org/\" rel=\"nofollow noreferrer\">libpcap</a> to send it.</p>\n\n<hr>\n\n<p>btw. If all you're trying to do is force an arp to be sent (but necessarily from you) you could achieve that by deleting any arp entry that you already have for your host. The next access to that address will require an arp to be sent.</p>\n\n<p>eg. /usr/sbin/arp -d destination_host_ip</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15797/"
]
| I'm working on an embedded linux system in C, I'm looking for the source code to the equivalet of SendARP in Windows. Any pointers? | Take a look at [arping](http://freshmeat.net/projects/arping/). The quick and dirty way of sending an arp would be to do:
```
foo = system("/somepath/arping somehost");
```
But a look through the arping source should be able to give you a better solution.
For the all-out solution though, you can construct your own by hand and use either a raw socket or [libpcap](http://www.tcpdump.org/) to send it.
---
btw. If all you're trying to do is force an arp to be sent (but necessarily from you) you could achieve that by deleting any arp entry that you already have for your host. The next access to that address will require an arp to be sent.
eg. /usr/sbin/arp -d destination\_host\_ip |
136,456 | <p>I need to explain to the client why dupes are showing up between 2 supposedly different exams. It's been 20 years since Prob and Stats.</p>
<p>I have a generated Multiple choice exam.
There are 192 questions in the database,
100 are chosen at random (no dupes).</p>
<p>Obviously, there is a 100% chance of there being at least 8 dupes between any two exams so generated. (Pigeonhole principle)</p>
<p>How do I calculate the probability of there being
25 dupes?
50 dupes?
75 dupes?</p>
<p>-- Edit after the fact --
I ran this through excel, taking sums of the probabilities from n-100,
For this particular problem, the probabilities were</p>
<pre><code>n P(n+ dupes)
40 97.5%
52 ~50%
61 ~0
</code></pre>
| [
{
"answer_id": 136471,
"author": "Chris",
"author_id": 19290,
"author_profile": "https://Stackoverflow.com/users/19290",
"pm_score": 0,
"selected": false,
"text": "<p>Its probably higher than you think. I won't attempt to duplicate this article: <a href=\"http://en.wikipedia.org/wiki/Birthday_paradox\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Birthday_paradox</a></p>\n"
},
{
"answer_id": 136524,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 0,
"selected": false,
"text": "<p>Once you've created the first exam, there are 92 questions that have never been used, and 100 that have. If you now generate another exam, with 100 questions in in it, you are chosing from a set of 92 questions that have never been used, and 100 that have. Clearly you are going to get quite a few duplicates. </p>\n\n<p>You would expect to get (100/192) * 100 duplicates, i.e. in any two randomly chosen exams, there will (on average) be 52 duplicate questions.</p>\n\n<p>If you want the probability that there are 25, or 75, or whatever, then you have two choices. </p>\n\n<p>a) Work out the maths</p>\n\n<p>b) Simulate a few runs on a computer</p>\n"
},
{
"answer_id": 136553,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Erm, this is really really hazy for me. But there are (192 choose 100) possible exams, right?</p>\n\n<p>And there are (100 choose N) ways of picking N dupes, each with (92 choose 100-N) ways of picking the rest of the questions, no?</p>\n\n<p>So isn't the probability of picking N dupes just:</p>\n\n<p>(100 choose N) * (92 choose 100-N) / (192 choose 100)</p>\n\n<p>EDIT: So if you want the chances of <em>N or more</em> dupes instead of exactly N, you have to sum the top half of that fraction for all values of N from the minimum number of dupes up to 100.</p>\n\n<p>Errrr, maybe...</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18907/"
]
| I need to explain to the client why dupes are showing up between 2 supposedly different exams. It's been 20 years since Prob and Stats.
I have a generated Multiple choice exam.
There are 192 questions in the database,
100 are chosen at random (no dupes).
Obviously, there is a 100% chance of there being at least 8 dupes between any two exams so generated. (Pigeonhole principle)
How do I calculate the probability of there being
25 dupes?
50 dupes?
75 dupes?
-- Edit after the fact --
I ran this through excel, taking sums of the probabilities from n-100,
For this particular problem, the probabilities were
```
n P(n+ dupes)
40 97.5%
52 ~50%
61 ~0
``` | Erm, this is really really hazy for me. But there are (192 choose 100) possible exams, right?
And there are (100 choose N) ways of picking N dupes, each with (92 choose 100-N) ways of picking the rest of the questions, no?
So isn't the probability of picking N dupes just:
(100 choose N) \* (92 choose 100-N) / (192 choose 100)
EDIT: So if you want the chances of *N or more* dupes instead of exactly N, you have to sum the top half of that fraction for all values of N from the minimum number of dupes up to 100.
Errrr, maybe... |
136,458 | <p>How would I have a <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used? </p>
<p>It would also be nice if the back button would reload the original URL.</p>
<p>I am trying to record JavaScript state in the URL.</p>
| [
{
"answer_id": 136496,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": false,
"text": "<p>I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look <em>just like the real bank</em>!</p>\n<p>Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...</p>\n<p><em>[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an <a href=\"https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history\" rel=\"nofollow noreferrer\">HTML5 technique</a> that allows the URL to be modified as long as it is from the same origin]</em></p>\n"
},
{
"answer_id": 136506,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 8,
"selected": false,
"text": "<p>If you want it to work in browsers that don't support <code>history.pushState</code> and <code>history.popState</code> yet, the \"old\" way is to set the fragment identifier, which won't cause a page reload.</p>\n\n<p>The basic idea is to set the <code>window.location.hash</code> property to a value that contains whatever state information you need, then either use the <a href=\"https://developer.mozilla.org/en/DOM/window.onhashchange\" rel=\"noreferrer\">window.onhashchange event</a>, or for older browsers that don't support <code>onhashchange</code> (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using <code>setInterval</code> for example) and update the page. You will also need to check the hash value on page load to set up the initial content.</p>\n\n<p>If you're using jQuery there's a <a href=\"http://benalman.com/projects/jquery-hashchange-plugin/\" rel=\"noreferrer\">hashchange plugin</a> that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.</p>\n\n<p>One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.</p>\n"
},
{
"answer_id": 136517,
"author": "Jethro Larson",
"author_id": 22425,
"author_profile": "https://Stackoverflow.com/users/22425",
"pm_score": 3,
"selected": false,
"text": "<p>Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.</p>\n\n<p>Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: <a href=\"http://site.com/page.html\" rel=\"noreferrer\">http://site.com/page.html</a> becomes <a href=\"http://site.com/page.html#item1\" rel=\"noreferrer\">http://site.com/page.html#item1</a> . This technique is often used in hijax(AJAX + preserve history). </p>\n\n<p>When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action. </p>\n\n<p>I hope that sets you on the right path. </p>\n"
},
{
"answer_id": 136555,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 5,
"selected": false,
"text": "<p>window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.</p>\n\n<p>If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.</p>\n\n<p>If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.</p>\n"
},
{
"answer_id": 136950,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 2,
"selected": false,
"text": "<p>There is a Yahoo YUI component (Browser History Manager) which can handle this: <a href=\"http://developer.yahoo.com/yui/history/\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/history/</a></p>\n"
},
{
"answer_id": 702930,
"author": "user58670",
"author_id": 58670,
"author_profile": "https://Stackoverflow.com/users/58670",
"pm_score": 1,
"selected": false,
"text": "<p>I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.</p>\n\n<p>So like let's say the user is at the page: <code>http://domain.com/site/page.html</code>\nThen the browser can let me do <code>location.append = new.html</code>\nand the page becomes: <code>http://domain.com/site/page.htmlnew.html</code> and the browser does not change it. </p>\n\n<p>Or just allow the person to change get parameter, so let's <code>location.get = me=1&page=1</code>.</p>\n\n<p>So original page becomes <code>http://domain.com/site/page.html?me=1&page=1</code> and it does not refresh. </p>\n\n<p>The problem with # is that the data is not cached (at least I don't think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-<a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a> page are able to cache data and do not spend time on re-loading the data.</p>\n\n<p>From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a <code>div</code> is used to handle different method overtime, that data is not stored for each history state.</p>\n"
},
{
"answer_id": 4222584,
"author": "clu3",
"author_id": 513116,
"author_profile": "https://Stackoverflow.com/users/513116",
"pm_score": 8,
"selected": true,
"text": "<p>With HTML 5, use the <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html\" rel=\"noreferrer\"><code>history.pushState</code> function</a>. As an example:</p>\n\n<pre><code><script type=\"text/javascript\">\nvar stateObj = { foo: \"bar\" };\nfunction change_my_url()\n{\n history.pushState(stateObj, \"page 2\", \"bar.html\");\n}\nvar link = document.getElementById('click');\nlink.addEventListener('click', change_my_url, false);\n</script>\n</code></pre>\n\n<p>and a href:</p>\n\n<pre><code><a href=\"#\" id='click'>Click to change url to bar.html</a>\n</code></pre>\n\n<hr>\n\n<p>If you want to change the URL without adding an entry to the back button list, use <code>history.replaceState</code> instead.</p>\n"
},
{
"answer_id": 4659443,
"author": "Jonathon Hill",
"author_id": 168815,
"author_profile": "https://Stackoverflow.com/users/168815",
"pm_score": 2,
"selected": false,
"text": "<p>Facebook's photo gallery does this using a #hash in the URL. Here are some example URLs:</p>\n\n<p>Before clicking 'next':</p>\n\n<pre><code>/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507\n</code></pre>\n\n<p>After clicking 'next':</p>\n\n<pre><code>/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507\n</code></pre>\n\n<p>Note the hash-bang (#!) immediately followed by the new URL.</p>\n"
},
{
"answer_id": 5731590,
"author": "Hash",
"author_id": 214341,
"author_profile": "https://Stackoverflow.com/users/214341",
"pm_score": 2,
"selected": false,
"text": "<p>There's a jquery plugin <a href=\"http://www.asual.com/jquery/address/\" rel=\"nofollow\">http://www.asual.com/jquery/address/</a></p>\n\n<p>I think this is what you need.</p>\n"
},
{
"answer_id": 19258379,
"author": "Ilia",
"author_id": 1455661,
"author_profile": "https://Stackoverflow.com/users/1455661",
"pm_score": 3,
"selected": false,
"text": "<p><em>jQuery</em> has a great plugin for changing browsers' URL, called <strong><a href=\"https://github.com/salvan13/jquery-pusher\" rel=\"noreferrer\">jQuery-pusher</a></strong>.</p>\n<p>JavaScript <code>pushState</code> and jQuery could be used together, like:</p>\n<p><code>history.pushState(null, null, $(this).attr('href'));</code></p>\n<p><strong>Example:</strong></p>\n<pre><code>$('a').click(function (event) {\n\n // Prevent default click action\n event.preventDefault(); \n\n // Detect if pushState is available\n if(history.pushState) {\n history.pushState(null, null, $(this).attr('href'));\n }\n return false;\n});\n</code></pre>\n<br>\n<p>Using only <em>JavaScript</em> <code>history.pushState()</code>, which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.</p>\n<p><strong>Example:</strong></p>\n<p><code>window.history.pushState("object", "Your New Title", "/new-url");</code></p>\n<p><strong>The pushState() method:</strong></p>\n<p><code>pushState()</code> takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:</p>\n<ol>\n<li><p><em>state object</em> — The state object is a JavaScript object which is associated with the new history entry created by <code>pushState()</code>. Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.</p>\n<p>The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to <code>pushState()</code>, the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.</p>\n</li>\n<li><p><em>title</em> — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.</p>\n</li>\n<li><p><em>URL</em> — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to <code>pushState()</code>, but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, <code>pushState()</code> will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 19665941,
"author": "Tusko Trush",
"author_id": 1627681,
"author_profile": "https://Stackoverflow.com/users/1627681",
"pm_score": 1,
"selected": false,
"text": "<p>my code is:</p>\n\n<pre><code>//change address bar\nfunction setLocation(curLoc){\n try {\n history.pushState(null, null, curLoc);\n return false;\n } catch(e) {}\n location.hash = '#' + curLoc;\n}\n</code></pre>\n\n<p>and action:</p>\n\n<pre><code>setLocation('http://example.com/your-url-here');\n</code></pre>\n\n<p>and example</p>\n\n<pre><code>$(document).ready(function(){\n $('nav li a').on('click', function(){\n if($(this).hasClass('active')) {\n\n } else {\n setLocation($(this).attr('href'));\n }\n return false;\n });\n});\n</code></pre>\n\n<p>That's all :)</p>\n"
},
{
"answer_id": 24365301,
"author": "Adam Hey",
"author_id": 2261245,
"author_profile": "https://Stackoverflow.com/users/2261245",
"pm_score": 0,
"selected": false,
"text": "<p>I've had success with:</p>\n\n<pre><code>location.hash=\"myValue\";\n</code></pre>\n\n<p>It just adds <code>#myValue</code> to the current URL. If you need to trigger an event on page Load, you can use the same <code>location.hash</code> to check for the relevant value. Just remember to remove the <code>#</code> from the value returned by <code>location.hash</code> e.g.</p>\n\n<pre><code>var articleId = window.location.hash.replace(\"#\",\"\");\n</code></pre>\n"
},
{
"answer_id": 50036569,
"author": "Veshraj Joshi",
"author_id": 2347438,
"author_profile": "https://Stackoverflow.com/users/2347438",
"pm_score": 2,
"selected": false,
"text": "<p>What is working for me is - <code>history.replaceState()</code> function which is as follows - </p>\n\n<pre><code>history.replaceState(data,\"Title of page\"[,'url-of-the-page']);\n</code></pre>\n\n<p>This will not reload page, you can make use of it with event of javascript</p>\n"
},
{
"answer_id": 54715005,
"author": "sam",
"author_id": 7538821,
"author_profile": "https://Stackoverflow.com/users/7538821",
"pm_score": 2,
"selected": false,
"text": "<p>A more simple answer i present,</p>\n\n<pre><code>window.history.pushState(null, null, \"/abc\")\n</code></pre>\n\n<p>this will add <code>/abc</code> after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to \"<a href=\"https://stackoverflow.com/abc\">https://stackoverflow.com/abc</a>\"</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393/"
]
| How would I have a [JavaScript](http://en.wikipedia.org/wiki/JavaScript) action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL. | With HTML 5, use the [`history.pushState` function](http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html). As an example:
```
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
```
and a href:
```
<a href="#" id='click'>Click to change url to bar.html</a>
```
---
If you want to change the URL without adding an entry to the back button list, use `history.replaceState` instead. |
136,467 | <p>short:</p>
<p>Is there a way in Ruby to DRY-ify this:</p>
<pre><code>def entry_point_one
begin
do_something
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
def entry_point_two
begin
do_something_else
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
</code></pre>
<p>longer:</p>
<p>I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do_something, especially since the interpreter makes use of recursion.</p>
<p>As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this:</p>
<pre><code>def entry_point_one
re_raise_known_exceptions {do_something}
end
def entry_point_two
re_raise_known_exceptions {do_something_else}
end
def re_raise_known_exceptions
yield
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
</code></pre>
<p>But that makes the method re-raise-known-exceptions show up in the back trace.</p>
<p>edit: I guess what I want would be something like a C pre-processing macro</p>
| [
{
"answer_id": 136541,
"author": "Patrick Huizinga",
"author_id": 15200,
"author_profile": "https://Stackoverflow.com/users/15200",
"pm_score": 2,
"selected": false,
"text": "<p>while thinking about it a bit more, I came up with this:</p>\n\n<pre><code>interpreter_block {do_something}\n\ndef interpreter_block\n yield\nrescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc\n raise exc.exception(exc.message)\nend\n</code></pre>\n\n<p>Although it's still not quiet what I would like to have, at least now the extra entry in the back trace has become somewhat better looking.</p>\n"
},
{
"answer_id": 136791,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 0,
"selected": false,
"text": "<p>If you have all of the information you need in the exceptions, and you do not need the backtrace at all, you can just define your own error and raise that, instead of reraising the existing exception. This will give it a fresh backtrace. (Of course, presumably your sample code is incomplete and there is other processing happening in the rescue block -- otherwise your best bet is to just let the error bubble up naturally.)</p>\n\n<pre><code>class MyError < StandardError; end\n\ndef interpreter_block\n yield\nrescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc\n raise MyError\nend\n</code></pre>\n"
},
{
"answer_id": 137389,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>You can just use the splat on an array.</p>\n\n<p>Straight from IRB:</p>\n\n<pre><code>COMMON_ERRORS = [ArgumentError, RuntimeError] # add your own \n\ndef f\n yield\nrescue *COMMON_ERRORS => err\n puts \"Got an error of type #{err.class}\"\nend\n\n\nf{ raise ArgumentError.new }\nGot an error of type ArgumentError\n\nf{ raise 'abc' }\nGot an error of type RuntimeError\n</code></pre>\n"
},
{
"answer_id": 138975,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 1,
"selected": false,
"text": "<p>It might be slightly evil, but I think you can simply remove the line from the backtrace ;-)</p>\n\n<pre><code>COMMON_ERRORS = [ArgumentError, RuntimeError]\n\ndef interpreter_block\n yield\nrescue *COMMON_ERRORS => err\n err.backtrace.delete_if{ |line| line=~/interpreter_block/ }\n raise err\nend\n</code></pre>\n\n<p>I'm not sure it's such a good idea though. You'll have a hell of a lot of fun debugging your interpreter afterward ;-)</p>\n\n<p>Side note: <a href=\"http://treetop.rubyforge.org/\" rel=\"nofollow noreferrer\">Treetop</a> may be of interest to you.</p>\n"
},
{
"answer_id": 1517699,
"author": "Peter Wagenet",
"author_id": 181916,
"author_profile": "https://Stackoverflow.com/users/181916",
"pm_score": 1,
"selected": false,
"text": "<p>This is a touch hackish, but as far as cleaning up the backtrace goes, something like this works nicely:</p>\n\n<pre><code>class Interpreter\n\n def method1\n error_catcher{ puts 1 / 0 }\n end\n\n def error_catcher\n yield\n rescue => err\n err.set_backtrace(err.backtrace - err.backtrace[1..2])\n raise err\n end\n\nend\n</code></pre>\n\n<p>The main trick is this line <code>err.set_backtrace(err.backtrace - err.backtrace[1..2])</code>. Without it, we get the following (from IRB):</p>\n\n<pre><code>ZeroDivisionError: divided by 0\n from (irb):43:in `/'\n from (irb):43:in `block in method1'\n from (irb):47:in `error_catcher'\n from (irb):43:in `method1'\n from (irb):54\n from /Users/peterwagenet/.ruby_versions/ruby-1.9.1-p129/bin/irb:12:in `<main>'\n</code></pre>\n\n<p>What we don't want in there are the second and third lines. So we remove them, ending up with:</p>\n\n<pre><code>ZeroDivisionError: divided by 0\n from (irb):73:in `/'\n from (irb):73:in `method1'\n from (irb):84\n from /Users/peterwagenet/.ruby_versions/ruby-1.9.1-p129/bin/irb:12:in `<main>'\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15200/"
]
| short:
Is there a way in Ruby to DRY-ify this:
```
def entry_point_one
begin
do_something
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
def entry_point_two
begin
do_something_else
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
```
longer:
I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do\_something, especially since the interpreter makes use of recursion.
As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this:
```
def entry_point_one
re_raise_known_exceptions {do_something}
end
def entry_point_two
re_raise_known_exceptions {do_something_else}
end
def re_raise_known_exceptions
yield
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
```
But that makes the method re-raise-known-exceptions show up in the back trace.
edit: I guess what I want would be something like a C pre-processing macro | while thinking about it a bit more, I came up with this:
```
interpreter_block {do_something}
def interpreter_block
yield
rescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc
raise exc.exception(exc.message)
end
```
Although it's still not quiet what I would like to have, at least now the extra entry in the back trace has become somewhat better looking. |
136,474 | <p>I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:</p>
<pre><code>Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
</code></pre>
<p>While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is</p>
<pre><code>Vector itemsVector = getItems();
Random rand = new Random(System.currentTimeMillis()); // would make this static to the class
List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
// be sure to use Vector.remove() or you may get the same item twice
subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}
</code></pre>
<p>Any suggestions on better ways to draw out a random subset from a Collection?</p>
| [
{
"answer_id": 136513,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 2,
"selected": false,
"text": "<p>Your second solution of using Random to pick element seems sound, however:</p>\n\n<ul>\n<li><p>Depending on how sensitive your data is, I suggest using some sort of hashing method to scramble the random number seed. For a good case study, see <a href=\"http://itmanagement.earthweb.com/entdev/article.php/11070_616221_3\" rel=\"nofollow noreferrer\">How We Learned to Cheat at Online Poker</a> (but this link is 404 as of 2015-12-18). Alternative URLs (found via a Google search on the article title in double quotes) include:</p>\n\n<ul>\n<li><a href=\"http://www.developer.com/tech/article.php/616221/How-We-Learned-to-Cheat-at-Online-Poker-A-Study-in-Software-Security.htm\" rel=\"nofollow noreferrer\">How We Learned to Cheat at Online Poker</a> — apparently the original publisher.</li>\n<li><a href=\"http://www.datamation.com/entdev/article.php/616221/How-We-Learned-to-Cheat-at-Online-Poker-A-Study-in-Software-Security.htm\" rel=\"nofollow noreferrer\">How We Learned to Cheat at Online Poker</a></li>\n<li><a href=\"https://www.cigital.com/papers/download/developer_gambling.php\" rel=\"nofollow noreferrer\">How We Learned to Cheat at Online Poker</a><br>\n </li>\n</ul></li>\n<li><p>Vector is synchronized. If possible, use ArrayList instead to improve performance.</p></li>\n</ul>\n"
},
{
"answer_id": 136544,
"author": "mmr",
"author_id": 21981,
"author_profile": "https://Stackoverflow.com/users/21981",
"pm_score": 0,
"selected": false,
"text": "<p>How much does remove cost? Because if that needs to rewrite the array to a new chunk of memory, then you've done O(5n) operations in the second version, rather than the O(n) you wanted before.</p>\n\n<p>You could create an array of booleans set to false, and then:</p>\n\n<pre><code>for (int i = 0; i < 5; i++){\n int r = rand.nextInt(itemsVector.size());\n while (boolArray[r]){\n r = rand.nextInt(itemsVector.size());\n }\n subsetList.add(itemsVector[r]);\n boolArray[r] = true;\n}\n</code></pre>\n\n<p>This approach works if your subset is smaller than your total size by a significant margin. As those sizes get close to one another (ie, 1/4 the size or something), you'd get more collisions on that random number generator. In that case, I'd make a list of integers the size of your larger array, and then shuffle that list of integers, and pull off the first elements from that to get your (non-colliding) indeces. That way, you have the cost of O(n) in building the integer array, and another O(n) in the shuffle, but no collisions from an internal while checker and less than the potential O(5n) that remove may cost.</p>\n"
},
{
"answer_id": 136550,
"author": "daniel",
"author_id": 19741,
"author_profile": "https://Stackoverflow.com/users/19741",
"pm_score": 0,
"selected": false,
"text": "<p>I'd personal opt for your initial implementation: very concise. Performance testing will show how well it scales. I've implemented a very similar block of code in a decently abused method and it scaled sufficiently. The particular code relied on arrays containing >10,000 items as well.</p>\n"
},
{
"answer_id": 136631,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "<p>Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a useful saving when N << M.</p>\n\n<p>Knuth also discusses these algorithms - I believe that would be Vol 3 \"Sorting and Searching\", but my set is packed pending a move of house so I can't formally check that.</p>\n"
},
{
"answer_id": 136730,
"author": "daniel",
"author_id": 19741,
"author_profile": "https://Stackoverflow.com/users/19741",
"pm_score": 3,
"selected": false,
"text": "<p>@Jonathan,</p>\n\n<p>I believe this is the solution you're talking about:</p>\n\n<pre><code>void genknuth(int m, int n)\n{ for (int i = 0; i < n; i++)\n /* select m of remaining n-i */\n if ((bigrand() % (n-i)) < m) {\n cout << i << \"\\n\";\n m--;\n }\n}\n</code></pre>\n\n<p>It's on page 127 of Programming Pearls by Jon Bentley and is based off of Knuth's implementation.</p>\n\n<p>EDIT: I just saw a further modification on page 129:</p>\n\n<pre><code>void genshuf(int m, int n)\n{ int i,j;\n int *x = new int[n];\n for (i = 0; i < n; i++)\n x[i] = i;\n for (i = 0; i < m; i++) {\n j = randint(i, n-1);\n int t = x[i]; x[i] = x[j]; x[j] = t;\n }\n sort(x, x+m);\n for (i = 0; i< m; i++)\n cout << x[i] << \"\\n\";\n}\n</code></pre>\n\n<p>This is based on the idea that \"...we need shuffle only the first <em>m</em> elements of the array...\"</p>\n"
},
{
"answer_id": 136765,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Set<Integer> s = new HashSet<Integer>()\n// add random indexes to s\nwhile(s.size() < 5)\n{\n s.add(rand.nextInt(itemsVector.size()))\n}\n// iterate over s and put the items in the list\nfor(Integer i : s)\n{\n out.add(itemsVector.get(i));\n}\n</code></pre>\n"
},
{
"answer_id": 136769,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote <a href=\"http://gregbeech.com/blog/shuffle-and-takerandom-extension-methods-for-ienumerable-t\" rel=\"nofollow noreferrer\">an efficient implementation of this</a> a few weeks back. It's in C# but the translation to Java is trivial (essentially the same code). The plus side is that it's also completely unbiased (which some of the existing answers aren't) - <a href=\"http://gregbeech.com/blog/determining-the-bias-of-a-shuffle-algorithm\" rel=\"nofollow noreferrer\">a way to test that is here</a>.</p>\n\n<p>It's based on a Durstenfeld implementation of the Fisher-Yates shuffle.</p>\n"
},
{
"answer_id": 136858,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 3,
"selected": false,
"text": "<p>If you're trying to select k distinct elements from a list of n, the methods you gave above will be O(n) or O(kn), because removing an element from a Vector will cause an arraycopy to shift all the elements down.</p>\n\n<p>Since you're asking for the best way, it depends on what you are allowed to do with your input list. </p>\n\n<p>If it's acceptable to modify the input list, as in your examples, then you can simply swap k random elements to the beginning of the list and return them in O(k) time like this:</p>\n\n<pre><code>public static <T> List<T> getRandomSubList(List<T> input, int subsetSize)\n{\n Random r = new Random();\n int inputSize = input.size();\n for (int i = 0; i < subsetSize; i++)\n {\n int indexToSwap = i + r.nextInt(inputSize - i);\n T temp = input.get(i);\n input.set(i, input.get(indexToSwap));\n input.set(indexToSwap, temp);\n }\n return input.subList(0, subsetSize);\n}\n</code></pre>\n\n<p>If the list must end up in the same state it began, you can keep track of the positions you swapped, and then return the list to its original state after copying your selected sublist. This is still an O(k) solution.</p>\n\n<p>If, however, you cannot modify the input list at all and k is much less than n (like 5 from 100), it would be much better not to remove selected elements each time, but simply select each element, and if you ever get a duplicate, toss it out and reselect. This will give you O(kn / (n-k)) which is still close to O(k) when n dominates k. (For example, if k is less than n / 2, then it reduces to O(k)).</p>\n\n<p>If k not dominated by n, and you cannot modify the list, you might as well copy your original list, and use your first solution, because O(n) will be just as good as O(k).</p>\n\n<p>As others have noted, if you are depending on strong randomness where every sublist is possible (and unbiased), you'll definitely need something stronger than <code>java.util.Random</code>. See <code>java.security.SecureRandom</code>.</p>\n"
},
{
"answer_id": 137250,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c#\">This</a> is a very similar question on stackoverflow.</p>\n\n<p>To summarize my favorite answers from that page (furst one from user Kyle):</p>\n\n<ul>\n<li><strong>O(n) solution</strong>: Iterate through your list, and copy out an element (or reference thereto) with probability (#needed / #remaining). Example: if k = 5 and n = 100, then you take the first element with prob 5/100. If you copy that one, then you choose the next with prob 4/99; but if you didn't take the first one, the prob is 5/99.</li>\n<li><strong>O(k log k) or O(k<sup>2</sup>)</strong>: Build a sorted list of k indices (numbers in {0, 1, ..., n-1}) by randomly choosing a number < n, then randomly choosing a number < n-1, etc. At each step, you need to recallibrate your choice to avoid collisions and keep the probabilities even. As an example, if k=5 and n=100, and your first choice is 43, your next choice is in the range [0, 98], and if it's >=43, then you add 1 to it. So if your second choice is 50, then you add 1 to it, and you have {43, 51}. If your next choice is 51, you add <em>2</em> to it to get {43, 51, 53}.</li>\n</ul>\n\n<p>Here is some pseudopython -</p>\n\n<pre><code># Returns a container s with k distinct random numbers from {0, 1, ..., n-1}\ndef ChooseRandomSubset(n, k):\n for i in range(k):\n r = UniformRandom(0, n-i) # May be 0, must be < n-i\n q = s.FirstIndexSuchThat( s[q] - q > r ) # This is the search.\n s.InsertInOrder(q ? r + q : r + len(s)) # Inserts right before q.\n return s \n</code></pre>\n\n<p>I'm saying that the time complexity is O(k<sup>2</sup>) <strong>or</strong> O(k log k) because it depends on how quickly you can search and insert into your container for s. If s is a normal list, one of those operations is linear, and you get k^2. However, if you're willing to build s as a balanced binary tree, you can get out the O(k log k) time.</p>\n"
},
{
"answer_id": 9550317,
"author": "user967710",
"author_id": 967710,
"author_profile": "https://Stackoverflow.com/users/967710",
"pm_score": 0,
"selected": false,
"text": "<p>two solutions I don't think appear here - the corresponds is quite long, and contains some links, however, I don't think all of the posts relate to the problem of choosing a subst of K elemetns out of a set of N elements. [By \"set\", I refer to the mathematical term, i.e. all elements appear once, order is not important].</p>\n\n<p>Sol 1:</p>\n\n<pre><code>//Assume the set is given as an array:\nObject[] set ....;\nfor(int i=0;i<K; i++){\nrandomNumber = random() % N;\n print set[randomNumber];\n //swap the chosen element with the last place\n temp = set[randomName];\n set[randomName] = set[N-1];\n set[N-1] = temp;\n //decrease N\n N--;\n}\n</code></pre>\n\n<p>This looks similar to the answer daniel gave, but it actually is very different. It is of O(k) run time.</p>\n\n<p>Another solution is to use some math:\nconsider the array indexes as Z_n and so we can choose randomly 2 numbers, x which is co-prime to n, i.e. chhose gcd(x,n)=1, and another, a, which is \"starting point\" - then the series: a % n,a+x % n, a+2*x % n,...a+(k-1)*x%n is a sequence of distinct numbers (as long as k<=n).</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4459/"
]
| I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:
```
Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
```
While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is
```
Vector itemsVector = getItems();
Random rand = new Random(System.currentTimeMillis()); // would make this static to the class
List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
// be sure to use Vector.remove() or you may get the same item twice
subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}
```
Any suggestions on better ways to draw out a random subset from a Collection? | Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a useful saving when N << M.
Knuth also discusses these algorithms - I believe that would be Vol 3 "Sorting and Searching", but my set is packed pending a move of house so I can't formally check that. |
136,485 | <p>I want to copy and paste text from a Office 2007 document (docx) into a textarea. On Window, using Firefox 3, there is additional jiberish that gets put into the field:</p>
<pre><code>...Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal
0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false
false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <!--[if gte mso 9]>...
</code></pre>
<p>Seems to be the style information and conditional comments from the newer document structure. Any ideas on how to parse this out, or prevent this from happening? Possibilities are Javascript on the front side, or Java on the back side.</p>
| [
{
"answer_id": 136567,
"author": "Lincoln Johnson",
"author_id": 13419,
"author_profile": "https://Stackoverflow.com/users/13419",
"pm_score": -1,
"selected": false,
"text": "<p>I find the easiest way to eliminate this random jibberish is to copy the text you want, paste it into notepad or a similar plaintext editor, copy it from notepad, then paste it into the field.</p>\n\n<p>Also, running it through a script or application that strips out the \"smart\" quotes and em/en dashes isn't a bad idea either.</p>\n"
},
{
"answer_id": 155893,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 1,
"selected": false,
"text": "<p>Similar to Lincoln's idea, you can use <a href=\"http://www.stevemiller.net/puretext/\" rel=\"nofollow noreferrer\">PureText</a> to automate the process. Basically, you press its hotkey instead of <kbd>Ctrl</kbd>+<kbd>V</kbd> (I have mine set to <kbd>Win</kbd>+<kbd>V</kbd>), and it pastes the plain text version of whatever is on your clipboard. I'm not sure if that will remove the extra data that Office has added, but it's worth a try.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21980/"
]
| I want to copy and paste text from a Office 2007 document (docx) into a textarea. On Window, using Firefox 3, there is additional jiberish that gets put into the field:
```
...Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal
0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false
false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <!--[if gte mso 9]>...
```
Seems to be the style information and conditional comments from the newer document structure. Any ideas on how to parse this out, or prevent this from happening? Possibilities are Javascript on the front side, or Java on the back side. | Similar to Lincoln's idea, you can use [PureText](http://www.stevemiller.net/puretext/) to automate the process. Basically, you press its hotkey instead of `Ctrl`+`V` (I have mine set to `Win`+`V`), and it pastes the plain text version of whatever is on your clipboard. I'm not sure if that will remove the extra data that Office has added, but it's worth a try. |
136,500 | <p>I have a string in a node and I'd like to split the string on '?' and return the last item in the array.</p>
<p>For example, in the block below:</p>
<pre><code><a>
<xsl:attribute name="href">
/newpage.aspx?<xsl:value-of select="someNode"/>
</xsl:attribute>
Link text
</a>
</code></pre>
<p>I'd like to split the <code>someNode</code> value.</p>
<p>Edit:
Here's the VB.Net that I use to load the Xsl for my Asp.Net page:</p>
<pre><code>Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl")
Dim myXsltSettings As New XsltSettings()
Dim myXMLResolver As New XmlUrlResolver()
myXsltSettings.EnableScript = True
myXsltSettings.EnableDocumentFunction = True
myXslDoc = New XslCompiledTransform(False)
myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver)
Dim myStringBuilder As New StringBuilder()
Dim myXmlWriter As XmlWriter = Nothing
Dim myXmlWriterSettings As New XmlWriterSettings()
myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto
myXmlWriterSettings.Indent = True
myXmlWriterSettings.OmitXmlDeclaration = True
myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings)
myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter)
Return myStringBuilder.ToString()
</code></pre>
<p><strong>Update:</strong> here's <a href="http://gist.github.com/360186" rel="noreferrer">an example of splitting XML on a particular node</a></p>
| [
{
"answer_id": 136531,
"author": "Jacob",
"author_id": 22107,
"author_profile": "https://Stackoverflow.com/users/22107",
"pm_score": 4,
"selected": false,
"text": "<p>If you can use XSLT 2.0 or higher, you can use <code>tokenize(string, separator)</code>: </p>\n\n<pre><code>tokenize(\"XPath is fun\", \"\\s+\")\nResult: (\"XPath\", \"is\", \"fun\")\n</code></pre>\n\n<p>See the <a href=\"http://www.w3schools.com/xpath/xpath_functions.asp\" rel=\"nofollow noreferrer\">w3schools XPath function reference</a>.</p>\n\n<p>By default, .NET does not support XSLT 2.0, let alone XSLT 3.0. The only known 2.0+ processors for .NET are <a href=\"http://saxonica.com\" rel=\"nofollow noreferrer\">Saxon for .NET</a> with <a href=\"http://www.ikvm.net/\" rel=\"nofollow noreferrer\">IKVM</a>, <a href=\"http://exselt.net\" rel=\"nofollow noreferrer\">Exselt</a>, a .NET XSLT 3.0 processor currently in beta, and <a href=\"http://xmlprime.com\" rel=\"nofollow noreferrer\">XMLPrime</a> XSLT 2.0 processor.</p>\n"
},
{
"answer_id": 136549,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 1,
"selected": false,
"text": "<p>XSLT 1.0 doesn't have a split function per se, but you could potentially achieve what you're trying to do with the substring-before and substring-after functions.</p>\n\n<p>Alternatively, if you're using a Microsoft XSLT engine, you could use inline C#.</p>\n"
},
{
"answer_id": 136848,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up using the <a href=\"http://msdn.microsoft.com/en-gb/library/ms256455(VS.80).aspx\" rel=\"noreferrer\"><code>substring-after()</code></a> function. Here's what worked for me:</p>\n\n<pre><code><a>\n <xsl:attribute name=\"href\">\n /newpage.aspx?<xsl:value-of select=\"substring-after(someNode, '?')\"/>\n </xsl:attribute>\n Link text\n</a>\n</code></pre>\n\n<p>Even after setting the version of my XSLT to 2.0, I still got a \"<code>'tokenize()' is an unknown XSLT function.</code>\" error when trying to use <code>tokenize()</code>.</p>\n"
},
{
"answer_id": 138235,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": "<p>Just for the record, if you're doing this with 1.0, and you really need a split/tokenise, you need the <a href=\"http://www.exslt.org/str/functions/tokenize/\" rel=\"nofollow noreferrer\">xslt extensions</a>.</p>\n"
},
{
"answer_id": 141022,
"author": "mortenbpost",
"author_id": 17577,
"author_profile": "https://Stackoverflow.com/users/17577",
"pm_score": 7,
"selected": true,
"text": "<p>Use a recursive method:</p>\n\n<pre><code><xsl:template name=\"output-tokens\">\n <xsl:param name=\"list\" /> \n <xsl:variable name=\"newlist\" select=\"concat(normalize-space($list), ' ')\" /> \n <xsl:variable name=\"first\" select=\"substring-before($newlist, ' ')\" /> \n <xsl:variable name=\"remaining\" select=\"substring-after($newlist, ' ')\" /> \n <id>\n <xsl:value-of select=\"$first\" /> \n </id>\n <xsl:if test=\"$remaining\">\n <xsl:call-template name=\"output-tokens\">\n <xsl:with-param name=\"list\" select=\"$remaining\" /> \n </xsl:call-template>\n </xsl:if>\n</xsl:template>\n</code></pre>\n"
},
{
"answer_id": 141205,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 2,
"selected": false,
"text": "<p>.NET doesn't support XSLT 2.0, unfortunately. I'm pretty sure that it supports EXSLT, which has a <a href=\"http://www.exslt.org/str/functions/split/str.split.html\" rel=\"nofollow noreferrer\">split()</a> function. Microsoft has an <a href=\"http://msdn.microsoft.com/en-us/library/aa468553.aspx\" rel=\"nofollow noreferrer\">older page</a> on its implementation of EXSLT. </p>\n"
},
{
"answer_id": 2867303,
"author": "Paul Wagland",
"author_id": 97627,
"author_profile": "https://Stackoverflow.com/users/97627",
"pm_score": 3,
"selected": false,
"text": "<p>Adding another possibility, if your template engine supports <a href=\"http://www.exslt.org/\" rel=\"noreferrer\">EXSLT</a>, then you could use <a href=\"http://www.exslt.org/str/functions/tokenize/index.html\" rel=\"noreferrer\">tokenize()</a> from that.</p>\n\n<p>For example:</p>\n\n<pre><code><xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:str=\"http://exslt.org/strings\"\n extension-element-prefixes=\"str\">\n\n...\n <a>\n <xsl:attribute name=\"href\">\n <xsl:text>/newpage.aspx?</xsl:text>\n <xsl:value-of select=\"str:tokenize(someNode)[2]\"/>\n </xsl:attribute> \n </a>\n...\n</xsl:stylesheet>\n</code></pre>\n"
},
{
"answer_id": 6160502,
"author": "Lav G",
"author_id": 184347,
"author_profile": "https://Stackoverflow.com/users/184347",
"pm_score": 2,
"selected": false,
"text": "<p>You can write a template using <code>string-before</code> and <code>string-after</code> functions and use it across. I wrote a <a href=\"http://lavgupta.com/2008/05/xsl-template-to-split-to-string.html\" rel=\"nofollow\">blog</a> on this.</p>\n\n<p>Finally came up with a xslt template that would split a delimited string into substrings.\nI don’t claim it’s the smartest script, but surely solves my problem.</p>\n\n<p>Stylesheet:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:template match=\"/\">\n<xsl:for-each select=\"Paths/Item\">\n<xsl:call-template name=\"SplitText\">\n<xsl:with-param name=\"inputString\" select=\"Path\"/>\n<xsl:with-param name=\"delimiter\" select=\"Delimiter\"/>\n</xsl:call-template>\n<br/>\n</xsl:for-each>\n</xsl:template>\n<xsl:template name=\"SplitText\">\n<xsl:param name=\"inputString\"/>\n<xsl:param name=\"delimiter\"/>\n<xsl:choose>\n<xsl:when test=\"contains($inputString, $delimiter)\">\n<xsl:value-of select=\"substring-before($inputString,$delimiter)\"/>\n<xsl:text disable-output-escaping = \"no\"> </xsl:text>\n<xsl:call-template name=\"SplitText\">\n<xsl:with-param name=\"inputString\" select=\"substring-after($inputString,$delimiter)\"/>\n<xsl:with-param name=\"delimiter\" select=\"$delimiter\"/>\n</xsl:call-template>\n</xsl:when>\n<xsl:otherwise>\n<xsl:choose>\n<xsl:when test=\"$inputString = ''\">\n<xsl:text></xsl:text>\n</xsl:when>\n<xsl:otherwise>\n<xsl:value-of select=\"$inputString\"/>\n<xsl:text> </xsl:text>\n</xsl:otherwise>\n</xsl:choose>\n</xsl:otherwise>\n</xsl:choose>\n</xsl:template>\n</xsl:stylesheet>\n</code></pre>\n\n<p>XML file (to be transformed) :</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"textSpliter.xslt\"?>\n<Paths>\n <Item>\n <Path>C:\\ProgramFiles\\SomeWierdSoftware</Path>\n <Delimiter>\\</Delimiter>\n </Item>\n</Paths> \n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
]
| I have a string in a node and I'd like to split the string on '?' and return the last item in the array.
For example, in the block below:
```
<a>
<xsl:attribute name="href">
/newpage.aspx?<xsl:value-of select="someNode"/>
</xsl:attribute>
Link text
</a>
```
I'd like to split the `someNode` value.
Edit:
Here's the VB.Net that I use to load the Xsl for my Asp.Net page:
```
Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl")
Dim myXsltSettings As New XsltSettings()
Dim myXMLResolver As New XmlUrlResolver()
myXsltSettings.EnableScript = True
myXsltSettings.EnableDocumentFunction = True
myXslDoc = New XslCompiledTransform(False)
myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver)
Dim myStringBuilder As New StringBuilder()
Dim myXmlWriter As XmlWriter = Nothing
Dim myXmlWriterSettings As New XmlWriterSettings()
myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto
myXmlWriterSettings.Indent = True
myXmlWriterSettings.OmitXmlDeclaration = True
myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings)
myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter)
Return myStringBuilder.ToString()
```
**Update:** here's [an example of splitting XML on a particular node](http://gist.github.com/360186) | Use a recursive method:
```
<xsl:template name="output-tokens">
<xsl:param name="list" />
<xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" />
<xsl:variable name="first" select="substring-before($newlist, ' ')" />
<xsl:variable name="remaining" select="substring-after($newlist, ' ')" />
<id>
<xsl:value-of select="$first" />
</id>
<xsl:if test="$remaining">
<xsl:call-template name="output-tokens">
<xsl:with-param name="list" select="$remaining" />
</xsl:call-template>
</xsl:if>
</xsl:template>
``` |
136,505 | <p>I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits.</p>
<p>Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs?</p>
| [
{
"answer_id": 136532,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 3,
"selected": false,
"text": "<p>By definition, a UUID is 32 hexadecimal digits, separated in 5 groups by hyphens, just as you have described. You shouldn't miss any with your regular expression.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Uuid#Definition\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Uuid#Definition</a></p>\n"
},
{
"answer_id": 136591,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 6,
"selected": true,
"text": "<p>I agree that by definition your regex does not miss any UUID. However it may be useful to note that if you are searching especially for Microsoft's Globally Unique Identifiers (GUIDs), there are five equivalent string representations for a GUID:</p>\n\n<pre><code>\"ca761232ed4211cebacd00aa0057b223\" \n\n\"CA761232-ED42-11CE-BACD-00AA0057B223\" \n\n\"{CA761232-ED42-11CE-BACD-00AA0057B223}\" \n\n\"(CA761232-ED42-11CE-BACD-00AA0057B223)\" \n\n\"{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}\" \n</code></pre>\n"
},
{
"answer_id": 3999043,
"author": "JimP",
"author_id": 178688,
"author_profile": "https://Stackoverflow.com/users/178688",
"pm_score": 5,
"selected": false,
"text": "<p><code>[\\w]{8}(-[\\w]{4}){3}-[\\w]{12}</code> has worked for me in most cases.</p>\n\n<p>Or if you want to be really specific <code>[\\w]{8}-[\\w]{4}-[\\w]{4}-[\\w]{4}-[\\w]{12}</code>.</p>\n"
},
{
"answer_id": 6640851,
"author": "Ivelin",
"author_id": 805030,
"author_profile": "https://Stackoverflow.com/users/805030",
"pm_score": 9,
"selected": false,
"text": "<p>The regex for uuid is:</p>\n<pre><code>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n</code></pre>\n<p>If you want to enforce the full string to match this regex, you will sometimes (your matcher API may have a method) need to surround above expression with <code>^...$</code>, that is</p>\n<pre><code>^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\n</code></pre>\n"
},
{
"answer_id": 12843265,
"author": "Matthew F. Robben",
"author_id": 1532867,
"author_profile": "https://Stackoverflow.com/users/1532867",
"pm_score": 7,
"selected": false,
"text": "<p>@ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:</p>\n\n<p><code>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}</code></p>\n\n<p>Would have just commented this but not enough rep :)</p>\n"
},
{
"answer_id": 14166194,
"author": "Gajus",
"author_id": 368691,
"author_profile": "https://Stackoverflow.com/users/368691",
"pm_score": 7,
"selected": false,
"text": "<blockquote>\n <p>Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.</p>\n</blockquote>\n\n<p>source: <a href=\"http://en.wikipedia.org/wiki/Uuid#Definition\">http://en.wikipedia.org/wiki/Uuid#Definition</a></p>\n\n<p>Therefore, this is technically more correct:</p>\n\n<pre><code>/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/\n</code></pre>\n"
},
{
"answer_id": 14712056,
"author": "Bruno Bronosky",
"author_id": 117471,
"author_profile": "https://Stackoverflow.com/users/117471",
"pm_score": 3,
"selected": false,
"text": "<p>In python re, you can span from numberic to upper case alpha. So..</p>\n\n<pre><code>import re\ntest = \"01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK\"\nre.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars\n## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']\nre.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars\n## ['01234ABCDEF', '01234', 'ABCDEF']\nre.compile(r'[0-F]+', re.I).findall(test) # Good\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\nre.compile(r'[0-f]+', re.I).findall(test) # Good\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\nre.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\nre.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\n</code></pre>\n\n<p>That makes the simplest Python UUID regex:</p>\n\n<pre><code>re_uuid = re.compile(\"[0-F]{8}-([0-F]{4}-){3}[0-F]{12}\", re.I)\n</code></pre>\n\n<p>I'll leave it as an exercise to the reader to use timeit to compare the performance of these.</p>\n\n<p>Enjoy.\nKeep it Pythonic™!</p>\n\n<p><strong>NOTE:</strong> Those spans will also match <code>:;<=>?@'</code> so, if you suspect that could give you false positives, don't take the shortcut. (Thank you Oliver Aubert for pointing that out in the comments.)</p>\n"
},
{
"answer_id": 16026126,
"author": "Christopher Smith",
"author_id": 60871,
"author_profile": "https://Stackoverflow.com/users/60871",
"pm_score": 3,
"selected": false,
"text": "<p>So, I think Richard Bronosky actually has the best answer to date, but I think you can do a bit to make it somewhat simpler (or at least terser):</p>\n\n<pre><code>re_uuid = re.compile(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', re.I)\n</code></pre>\n"
},
{
"answer_id": 23117267,
"author": "Anton K",
"author_id": 209406,
"author_profile": "https://Stackoverflow.com/users/209406",
"pm_score": 3,
"selected": false,
"text": "<p>Variant for C++:</p>\n\n<pre><code>#include <regex> // Required include\n\n...\n\n// Source string \nstd::wstring srcStr = L\"String with GIUD: {4d36e96e-e325-11ce-bfc1-08002be10318} any text\";\n\n// Regex and match\nstd::wsmatch match;\nstd::wregex rx(L\"(\\\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\\\})\", std::regex_constants::icase);\n\n// Search\nstd::regex_search(srcStr, match, rx);\n\n// Result\nstd::wstring strGUID = match[1];\n</code></pre>\n"
},
{
"answer_id": 24387746,
"author": "iGEL",
"author_id": 362378,
"author_profile": "https://Stackoverflow.com/users/362378",
"pm_score": 5,
"selected": false,
"text": "<pre><code>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/i\n</code></pre>\n\n<p>Gajus' regexp rejects UUID V1-3 and 5, even though they are valid.</p>\n"
},
{
"answer_id": 34841029,
"author": "abufct",
"author_id": 1319925,
"author_profile": "https://Stackoverflow.com/users/1319925",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$UUID_RE = join '-', map { \"[0-9a-f]{$_}\" } 8, 4, 4, 4, 12;\n</code></pre>\n\n<p>BTW, allowing only 4 on one of the positions is only valid for UUIDv4.\nBut v4 is not the only UUID version that exists.\nI have met v1 in my practice as well.</p>\n"
},
{
"answer_id": 38162719,
"author": "Quanlong",
"author_id": 622662,
"author_profile": "https://Stackoverflow.com/users/622662",
"pm_score": 3,
"selected": false,
"text": "<p>For UUID generated on OS X with <code>uuidgen</code>, the regex pattern is </p>\n\n<pre><code>[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}\n</code></pre>\n\n<p>Verify with </p>\n\n<pre><code>uuidgen | grep -E \"[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}\"\n</code></pre>\n"
},
{
"answer_id": 38191078,
"author": "Ivan Gabriele",
"author_id": 2736233,
"author_profile": "https://Stackoverflow.com/users/2736233",
"pm_score": 7,
"selected": false,
"text": "<p>If you want to check or validate <strong>a specific UUID version</strong>, here are the corresponding regexes.</p>\n\n<blockquote>\n <p>Note that <strong>the only difference is the version number</strong>, which is explained in <code>4.1.3. Version</code> chapter of <a href=\"https://www.ietf.org/rfc/rfc4122.txt\">UUID 4122 RFC</a>.</p>\n</blockquote>\n\n<p>The version number is the first character of the third group : <code>[VERSION_NUMBER][0-9A-F]{3}</code> :</p>\n\n<ul>\n<li><p>UUID v1 :</p>\n\n<pre><code>/^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n</code></pre></li>\n<li><p>UUID v2 :</p>\n\n<pre><code>/^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n</code></pre></li>\n<li><p>UUID v3 :</p>\n\n<pre><code>/^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n</code></pre></li>\n<li><p>UUID v4 :</p>\n\n<pre><code>/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n</code></pre></li>\n<li><p>UUID v5 :</p>\n\n<pre><code>/^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 58833439,
"author": "asherbret",
"author_id": 2016436,
"author_profile": "https://Stackoverflow.com/users/2016436",
"pm_score": 2,
"selected": false,
"text": "<p>For bash:</p>\n\n<pre><code>grep -E \"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}\"\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>$> echo \"f2575e6a-9bce-49e7-ae7c-bff6b555bda4\" | grep -E \"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}\"\nf2575e6a-9bce-49e7-ae7c-bff6b555bda4\n</code></pre>\n"
},
{
"answer_id": 61022108,
"author": "Walf",
"author_id": 315024,
"author_profile": "https://Stackoverflow.com/users/315024",
"pm_score": 3,
"selected": false,
"text": "<p>If using Posix regex (<code>grep -E</code>, MySQL, etc.), this may be easier to read & remember:</p>\n<pre><code>[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\n</code></pre>\n<p><strong>Edit:</strong> Perl & PCRE flavours also support Posix character classes so this'll work with them. For those, change the <code>(…)</code> to a non-capturing subgroup <code>(?:…)</code>.</p>\n"
},
{
"answer_id": 62872109,
"author": "gildniy",
"author_id": 1992866,
"author_profile": "https://Stackoverflow.com/users/1992866",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the working REGEX: <a href=\"https://www.regextester.com/99148\" rel=\"noreferrer\">https://www.regextester.com/99148</a></p>\n<pre><code>const regex = [0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}\n</code></pre>\n"
},
{
"answer_id": 65312002,
"author": "Oxydron",
"author_id": 1891899,
"author_profile": "https://Stackoverflow.com/users/1891899",
"pm_score": 1,
"selected": false,
"text": "<p>Wanted to give my contribution, as my regex cover all cases from OP and correctly group all relevant data on the group method (you don't need to post process the string to get each part of the uuid, this regex already get it for you)</p>\n<pre><code>([\\d\\w]{8})-?([\\d\\w]{4})-?([\\d\\w]{4})-?([\\d\\w]{4})-?([\\d\\w]{12})|[{0x]*([\\d\\w]{8})[0x, ]{4}([\\d\\w]{4})[0x, ]{4}([\\d\\w]{4})[0x, {]{5}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})\n</code></pre>\n"
},
{
"answer_id": 71296472,
"author": "Vlad",
"author_id": 12250254,
"author_profile": "https://Stackoverflow.com/users/12250254",
"pm_score": 0,
"selected": false,
"text": "<p>Official <a href=\"https://www.npmjs.com/package/uuid\" rel=\"nofollow noreferrer\">uuid library</a> uses following regex:</p>\n<pre><code>/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i\n</code></pre>\n<p>See <a href=\"https://github.com/uuidjs/uuid/blob/main/src/regex.js\" rel=\"nofollow noreferrer\">reference</a></p>\n"
},
{
"answer_id": 72568589,
"author": "Hitesh Kalwani",
"author_id": 4611516,
"author_profile": "https://Stackoverflow.com/users/4611516",
"pm_score": 0,
"selected": false,
"text": "<p>Generalize one, where underscore is also neglected properly and only alphanumeric values are allowed with the pattern of 8-4-4-4-12.</p>\n<p><code>^[^\\W_]{8}(-[^\\W_]{4}){4}[^\\W_]{8}$</code></p>\n<p>or</p>\n<p><code>^[^\\W_]{8}(-[^\\W_]{4}){3}-[^\\W_]{12}$</code></p>\n<p>both give you the same result, but the last one is more readable. And I would like to recommend the website where one can learn as well as test the Regular expression properly: <a href=\"https://regexr.com/\" rel=\"nofollow noreferrer\">https://regexr.com/</a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
| I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits.
Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs? | I agree that by definition your regex does not miss any UUID. However it may be useful to note that if you are searching especially for Microsoft's Globally Unique Identifiers (GUIDs), there are five equivalent string representations for a GUID:
```
"ca761232ed4211cebacd00aa0057b223"
"CA761232-ED42-11CE-BACD-00AA0057B223"
"{CA761232-ED42-11CE-BACD-00AA0057B223}"
"(CA761232-ED42-11CE-BACD-00AA0057B223)"
"{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}"
``` |
136,536 | <p>FYI: I am running on dotnet 3.5 SP1</p>
<p>I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder).
After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of <code>myDataset.tables(0).Rows(0)("ID")</code>, but it is System.DBNull (despite the fact that the row was inserted).</p>
<p>(Note: I do not want to explicitly write a new stored procedure to do this!)</p>
<p>One method often posted <a href="http://forums.asp.net/t/951025.aspx" rel="noreferrer">http://forums.asp.net/t/951025.aspx</a> modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so:</p>
<pre><code>SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()"
InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
</code></pre>
<p>Apparently, this seemed to work for many people in the past, but does not work for me.</p>
<p>Another technique: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&SiteID=1" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&SiteID=1</a> doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter).</p>
<p>Does anyone know the answer to this???</p>
| [
{
"answer_id": 137331,
"author": "Jon Adams",
"author_id": 2291,
"author_profile": "https://Stackoverflow.com/users/2291",
"pm_score": 1,
"selected": false,
"text": "<p>If those other methods didn't work for you, the .Net provided tools (SqlDataAdapter) etc. don't really offer much else regarding flexibility. You generally need to take it to the next level and start doing stuff manually. Stored procedure would be one way to keep using the SqlDataAdapter. Otherwise, you need to move to another data access tool as the .Net data libraries have limits since they design to be simple. If your model doesn't work with their vision, you have to roll your own code at some point/level.</p>\n"
},
{
"answer_id": 137468,
"author": "dbugger",
"author_id": 15754,
"author_profile": "https://Stackoverflow.com/users/15754",
"pm_score": 2,
"selected": false,
"text": "<p>The insert command can be instructed to update the inserted record using either output parameters or the first returned record (or both) using the UpdatedRowSource property...</p>\n\n<pre><code>InsertCommand.UpdatedRowSource = UpdateRowSource.Both;\n</code></pre>\n\n<p>If you wanted to use a stored procedure, you'd be done. But you want to use a raw command (aka the output of the command builder), which doesn't allow for either a) output parameters or b) returning a record. Why is this? Well for a) this is what your InsertCommand will look like...</p>\n\n<pre><code>INSERT INTO [SomeTable] ([Name]) VALUES (@Name)\n</code></pre>\n\n<p>There's no way to enter an output parameter in the command. So what about b)? Unfortunately, the DataAdapter executes the Insert command by calling the commands ExecuteNonQuery method. This does not return any records, so there is no way for the adapter to update the inserted record.</p>\n\n<p>So you need to either use a stored proc, or give up on using the DataAdapter.</p>\n"
},
{
"answer_id": 159901,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": -1,
"selected": false,
"text": "<p>Have you looked into using LINQ instead? I understand this doesn't address your actual question, but if you are using .NET 3.5 you really ought to try using LINQ. In fact, with the advent of Code First EntityFramework, I think you could easily choose either LINQ to SQL or EF as relatively lightweight alternatives to rolling your own DAL.</p>\n"
},
{
"answer_id": 2028699,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, this works for me :</p>\n\n<pre><code>SqlDataAdapter.InsertCommand.CommandText += \"; SELECT MyTableID = SCOPE_IDENTITY()\" InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;\n</code></pre>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 2377462,
"author": "Pedrao",
"author_id": 286036,
"author_profile": "https://Stackoverflow.com/users/286036",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. It was just solved when I cloned the command generated by the commandbuilder. It looks that even when you change the commandText of the insertcommand, it keeps getting the command generated by the Commandbuilder...\nHere it's the code that I used to clone the command...</p>\n\n<pre><code> private static void CloneBuilderCommand(System.Data.Common.DbCommand toClone,System.Data.Common.DbCommand repository)\n {\n repository.CommandText = toClone.CommandText;\n //Copying parameters\n if (toClone.Parameters.Count == 0) return;//No parameters to clone? go away!\n System.Data.Common.DbParameter[] parametersArray= new System.Data.Common.DbParameter[toClone.Parameters.Count];\n toClone.Parameters.CopyTo(parametersArray, 0);\n toClone.Parameters.Clear();//Removing association before link to the repository one\n repository.Parameters.AddRange(parametersArray); \n }\n</code></pre>\n"
},
{
"answer_id": 2514144,
"author": "Rob Vermeulen",
"author_id": 150187,
"author_profile": "https://Stackoverflow.com/users/150187",
"pm_score": 2,
"selected": false,
"text": "<p>What works for me is configuring a MissingSchemaAction:</p>\n\n<pre><code>SqlCommandBuilder commandBuilder = new SqlCommandBuilder(myDataAdapter);\nmyDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;\n</code></pre>\n\n<p>This lets me retrieve the primary key (if it is an identity, or autonumber) after an insert.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 4375297,
"author": "Jay Kidd",
"author_id": 533475,
"author_profile": "https://Stackoverflow.com/users/533475",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want to (a) insert one record into table, (b) use a DataSet, and (c) not use a stored procedure, then you can follow this:</p>\n\n<ol>\n<li><p>Create your dataAdapter, but in the select statement add WHERE 1=0, so that you don't have to download the entire table - optional step for performance</p></li>\n<li><p>Create a custom INSERT statement with scope identity select statement and an output parameter.</p></li>\n<li><p>Do the normal processing, filling the dataset, adding the record and saving the table update.</p></li>\n<li><p>Should now be able to extract the identity from the parameter directly.</p></li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code> '-- post a new entry and return the column number\n ' get the table stucture\n Dim ds As DataSet = New DataSet()\n Dim da As SqlDataAdapter = New SqlDataAdapter(String.Concat(\"SELECT * FROM [\", fileRegisterSchemaName, \"].[\", fileRegisterTableName, \"] WHERE 1=0\"), sqlConnectionString)\n Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)\n\n ' since we want the identity column back (FileID), we need to write our own INSERT statement\n da.InsertCommand = New SqlCommand(String.Concat(\"INSERT INTO [\", fileRegisterSchemaName, \"].[\", fileRegisterTableName, \"] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT @FileID = SCOPE_IDENTITY();\"))\n da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord\n With da.InsertCommand.Parameters\n .Add(\"@FileName\", SqlDbType.VarChar, 1024, \"FileName\")\n .Add(\"@User\", SqlDbType.VarChar, 24, \"User\")\n .Add(\"@Date\", SqlDbType.DateTime, 0, \"Date\")\n .Add(\"@Table\", SqlDbType.VarChar, 128, \"FileName\")\n ' allow the @FileID to be returned back to us\n .Add(\"@FileID\", SqlDbType.Int, 0, \"FileID\")\n .Item(\"@FileID\").Direction = ParameterDirection.Output\n End With\n\n ' copy the table structure from the server and create a reference to the table(dt)\n da.Fill(ds, fileRegisterTableName)\n Dim dt As DataTable = ds.Tables(fileRegisterTableName)\n\n ' add a new record\n Dim dr As DataRow = dt.NewRow()\n dr(\"FileName\") = fileName\n dr(\"User\") = String.Concat(Environment.UserDomainName, \"\\\", Environment.UserName)\n dr(\"Date\") = DateTime.Now()\n dr(\"Table\") = targetTableName\n dt.Rows.Add(dr)\n\n ' save the new record\n da.Update(dt)\n\n ' return the FileID (Identity)\n Return da.InsertCommand.Parameters(\"@FileID\").Value\n</code></pre>\n\n<p>But thats pretty long winded to do the same thing as this...</p>\n\n<pre><code>' add the file record\n Dim sqlCmd As SqlCommand = New SqlCommand(String.Concat(\"INSERT INTO [\", fileRegisterSchemaName, \"].[\", fileRegisterTableName, \"] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT SCOPE_IDENTITY();\"), New SqlConnection(sqlConnectionString))\n With sqlCmd.Parameters\n .AddWithValue(\"@FileName\", fileName)\n .AddWithValue(\"@User\", String.Concat(Environment.UserDomainName, \"\\\", Environment.UserName))\n .AddWithValue(\"@Date\", DateTime.Now())\n .AddWithValue(\"@Table\", targetTableName)\n End With\n sqlCmd.Connection.Open()\n Return sqlCmd.ExecuteScalar\n</code></pre>\n"
},
{
"answer_id": 7255577,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 2,
"selected": false,
"text": "<p>I found the answer that works for me here: <a href=\"http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-ado-net/4933/Have-soln-but-need-understanding-return-IDENTITY-issue\" rel=\"nofollow\">http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-ado-net/4933/Have-soln-but-need-understanding-return-IDENTITY-issue</a></p>\n\n<p>Code that worked (from the site - attributed to Girish)</p>\n\n<pre><code>//_dataCommand is an instance of SqlDataAdapter\n//connection is an instance of ConnectionProvider which has a property called DBConnection of type SqlConnection\n//_dataTable is an instance of DataTable\n\nSqlCommandBuilder bldr = new SqlCommandBuilder(_dataCommand);\nSqlCommand cmdInsert = new SqlCommand(bldr.GetInsertCommand().CommandText, connection.DBConnection);\ncmdInsert.CommandText += \";Select SCOPE_IDENTITY() as id\";\n\nSqlParameter[] aParams = new\nSqlParameter[bldr.GetInsertCommand().Parameters.Count];\nbldr.GetInsertCommand().Parameters.CopyTo(aParams, 0);\nbldr.GetInsertCommand().Parameters.Clear();\n\nfor(int i=0 ; i < aParams.Length; i++)\n{\n cmdInsert.Parameters.Add(aParams[i]);\n}\n\n_dataCommand.InsertCommand = cmdInsert;\n_dataCommand.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n_dataCommand.Update(_dataTable);\n</code></pre>\n"
},
{
"answer_id": 7280103,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Another way using just a command object. </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim sb As New StringBuilder\nsb.Append(\" Insert into \")\nsb.Append(tbl)\nsb.Append(\" \")\nsb.Append(cnames)\nsb.Append(\" values \")\nsb.Append(cvals)\nsb.Append(\";Select SCOPE_IDENTITY() as id\") 'add identity selection\n\nDim sql As String = sb.ToString\n\nDim cmd As System.Data.Common.DbCommand = connection.CreateCommand\ncmd.Connection = connection\ncmd.CommandText = sql\ncmd.CommandType = CommandType.Text\ncmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord\n\n'retrieve the new identity value, and update the object\nDim dec as decimal = CType(cmd.ExecuteScalar, Decimal)\n</code></pre>\n"
},
{
"answer_id": 7613506,
"author": "Ray Fitzharris",
"author_id": 973478,
"author_profile": "https://Stackoverflow.com/users/973478",
"pm_score": 3,
"selected": false,
"text": "<p>This is a problem that I've run into before, the bug seems to be that when you call\nda.Update(ds);\nthe parameters array of the insert command gets reset to the inital list that was created form your command builder, it removes your added output parameters for the identity.</p>\n\n<p>The solution is to create a new dataAdapter and copy in the commands, then use this new one to do your da.update(ds);</p>\n\n<p>like</p>\n\n<pre><code>SqlDataAdapter da = new SqlDataAdapter(\"select Top 0 \" + GetTableSelectList(dt) + \n\"FROM \" + tableName,_sqlConnectString);\nSqlCommandBuilder custCB = new SqlCommandBuilder(da);\ncustCB.QuotePrefix = \"[\";\ncustCB.QuoteSuffix = \"]\";\nda.TableMappings.Add(\"Table\", dt.TableName);\n\nda.UpdateCommand = custCB.GetUpdateCommand();\nda.InsertCommand = custCB.GetInsertCommand();\nda.DeleteCommand = custCB.GetDeleteCommand();\n\nda.InsertCommand.CommandText = String.Concat(da.InsertCommand.CommandText, \n\"; SELECT \",GetTableSelectList(dt),\" From \", tableName, \n\" where \",pKeyName,\"=SCOPE_IDENTITY()\");\n\nSqlParameter identParam = new SqlParameter(\"@Identity\", SqlDbType.BigInt, 0, pKeyName);\nidentParam.Direction = ParameterDirection.Output;\nda.InsertCommand.Parameters.Add(identParam);\n\nda.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n\n//new adaptor for performing the update \nSqlDataAdapter daAutoNum = new SqlDataAdapter();\ndaAutoNum.DeleteCommand = da.DeleteCommand;\ndaAutoNum.InsertCommand = da.InsertCommand;\ndaAutoNum.UpdateCommand = da.UpdateCommand;\n\ndaAutoNum.Update(dt);\n</code></pre>\n"
},
{
"answer_id": 12105428,
"author": "David",
"author_id": 266281,
"author_profile": "https://Stackoverflow.com/users/266281",
"pm_score": 2,
"selected": false,
"text": "<p>The issue for me was where the code was placed.</p>\n\n<p>Add the code in the RowUpdating event handler, something like this:</p>\n\n<pre><code>void dataSet_RowUpdating(object sender, SqlRowUpdatingEventArgs e)\n{\n if (e.StatementType == StatementType.Insert)\n {\n e.Command.CommandText += \"; SELECT ID = SCOPE_IDENTITY()\";\n e.Command.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29109100,
"author": "Vadim Rapp",
"author_id": 3830865,
"author_profile": "https://Stackoverflow.com/users/3830865",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, it's even easier, no need in any custom commands. When you create tableadapter in dataset designer, specify \"refresh the data table\" in Advanced Options of the wizard. With that, after you issue dataadapter.update mydataset , you will find identify column in the datatable populated with the new value from the database.</p>\n"
},
{
"answer_id": 40614940,
"author": "esc",
"author_id": 2594731,
"author_profile": "https://Stackoverflow.com/users/2594731",
"pm_score": 0,
"selected": false,
"text": "<p>My solution:</p>\n\n<pre><code>SqlDataAdapter da = new SqlDataAdapter(\"SELECT * FROM Mytable;\" , sqlConnection);\n\nSqlCommandBuilder cb = new SqlCommandBuilder(da);\n\nda.DeleteCommand = (SqlCommand)cb.GetDeleteCommand().Clone();\nda.UpdateCommand = (SqlCommand)cb.GetUpdateCommand().Clone();\n\nSqlCommand insertCmd = (SqlCommand)cb.GetInsertCommand().Clone();\n\ninsertCmd.CommandText += \";SET @Id = SCOPE_IDENTITY();\";\ninsertCmd.Parameters.Add(\"@Id\", SqlDbType.Int, 0, \"Id\").Direction = ParameterDirection.Output;\nda.InsertCommand = insertCmd;\nda.InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;\n\ncb.Dispose();\n</code></pre>\n"
},
{
"answer_id": 67707913,
"author": "Kechkouch",
"author_id": 7439988,
"author_profile": "https://Stackoverflow.com/users/7439988",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that the changes you made to the <strong>InsertCommand</strong> are not taken into consideration when using the <em><strong>SqlDataAdapter.Update(DataSet)</strong></em> Method.\nthe perfect solution is to clone the <strong>InsertCommand</strong> generated by the <strong>CommandBuilder</strong>.</p>\n<pre><code>SqlCommandBuilder cb = new SqlCommandBuilder(da);\ncb.ConflictOption = ConflictOption.OverwriteChanges;\n\nda.InsertCommand = cb.GetInsertCommand().Clone();\nda.InsertCommand.CommandText += "; SELECT idTable = SCOPE_IDENTITY()";\nda.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n\nda.Update(dt);\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8678/"
]
| FYI: I am running on dotnet 3.5 SP1
I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder).
After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of `myDataset.tables(0).Rows(0)("ID")`, but it is System.DBNull (despite the fact that the row was inserted).
(Note: I do not want to explicitly write a new stored procedure to do this!)
One method often posted <http://forums.asp.net/t/951025.aspx> modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so:
```
SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()"
InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
```
Apparently, this seemed to work for many people in the past, but does not work for me.
Another technique: <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&SiteID=1> doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter).
Does anyone know the answer to this??? | This is a problem that I've run into before, the bug seems to be that when you call
da.Update(ds);
the parameters array of the insert command gets reset to the inital list that was created form your command builder, it removes your added output parameters for the identity.
The solution is to create a new dataAdapter and copy in the commands, then use this new one to do your da.update(ds);
like
```
SqlDataAdapter da = new SqlDataAdapter("select Top 0 " + GetTableSelectList(dt) +
"FROM " + tableName,_sqlConnectString);
SqlCommandBuilder custCB = new SqlCommandBuilder(da);
custCB.QuotePrefix = "[";
custCB.QuoteSuffix = "]";
da.TableMappings.Add("Table", dt.TableName);
da.UpdateCommand = custCB.GetUpdateCommand();
da.InsertCommand = custCB.GetInsertCommand();
da.DeleteCommand = custCB.GetDeleteCommand();
da.InsertCommand.CommandText = String.Concat(da.InsertCommand.CommandText,
"; SELECT ",GetTableSelectList(dt)," From ", tableName,
" where ",pKeyName,"=SCOPE_IDENTITY()");
SqlParameter identParam = new SqlParameter("@Identity", SqlDbType.BigInt, 0, pKeyName);
identParam.Direction = ParameterDirection.Output;
da.InsertCommand.Parameters.Add(identParam);
da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
//new adaptor for performing the update
SqlDataAdapter daAutoNum = new SqlDataAdapter();
daAutoNum.DeleteCommand = da.DeleteCommand;
daAutoNum.InsertCommand = da.InsertCommand;
daAutoNum.UpdateCommand = da.UpdateCommand;
daAutoNum.Update(dt);
``` |
136,548 | <p>In C++ you can initialize a variable in an if statement, like so:</p>
<pre><code>if (CThing* pThing = GetThing())
{
}
</code></pre>
<p>Why would one consider this bad or good style? What are the benefits and disadvantages?</p>
<p>Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:</p>
<pre><code>if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
</code></pre>
<p>If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.</p>
<p><a href="https://stackoverflow.com/questions/136373/initializing-a-variable-in-a-conditional-statment">Question borrowed from here, similar topic but PHP.</a></p>
| [
{
"answer_id": 136590,
"author": "Luke",
"author_id": 327,
"author_profile": "https://Stackoverflow.com/users/327",
"pm_score": 2,
"selected": false,
"text": "<p>This <strike><strong>should</strong></strike>doesn't work in C++ <strike>since</strike>even though it supports <a href=\"http://www.codepedia.com/1/ShortCircuitEval\" rel=\"nofollow noreferrer\">short circuiting evaluation</a>. <strike>Maybe</strike>Don't try the following:</p>\n\n<pre><code>if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))\n{\n}\n</code></pre>\n\n<p>err.. see <a href=\"https://stackoverflow.com/questions/136548/procon-initializing-a-variable-in-a-conditional-statement-c#136695\">Wesley Tarle's answer</a></p>\n"
},
{
"answer_id": 136621,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 2,
"selected": false,
"text": "<p>One reason I don't normally do that is because of the common bug from a missed '=' in a conditional test. I use lint with the error/warnings set to catch those. It will then yell about all assignments inside conditionals.</p>\n"
},
{
"answer_id": 136627,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 2,
"selected": false,
"text": "<p>About the advantages:</p>\n\n<p>It's always recommended to define variables when you first need them, not a line before. This is for improved readability of your code, since one can tell what CThing is without scrolling and searching where it was defined.</p>\n\n<p>Also reducing scope to a loop/if block, causes the variable to be unreferenced after the execution of the code block, which makes it a candidate for Garbage Collection (if the language supports this feature).</p>\n"
},
{
"answer_id": 136643,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 2,
"selected": false,
"text": "<p>Just an FYI some of the older Microsoft C++ compliers(Visual Studios 6, and .NET 2003 I think) don't quite follow the scoping rule in some instances.</p>\n\n<pre><code>for(int i = 0; i > 20; i++) {\n // some code\n}\n\ncout << i << endl;\n</code></pre>\n\n<p>I should be out of scope, but that was/is valid code. I believe it was played off as a feature, but in my opinion it's just non compliance. Not adhering to the standards is bad. Just as a web developer about IE and Firefox.</p>\n\n<p>Can someone with VS check and see if that's still valid?</p>\n"
},
{
"answer_id": 136645,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 0,
"selected": false,
"text": "<p>You can also enclose the assignment in an extra set of ( ) to prevent the warning message.</p>\n"
},
{
"answer_id": 136660,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 0,
"selected": false,
"text": "<p>I see that as kind of dangerous. The code below is much safer and the enclosing braces will still limit the scope of pThing in the way you want.</p>\n\n<p>I'm assuming GetThing() sometimes returns NULL which is why I put that funny clause in the if() statement. It prevents IsReallySomething() being called on a NULL pointer.</p>\n\n<pre><code>{\n CThing *pThing = GetThing();\n if(pThing ? pThing->IsReallySomeThing() : false)\n {\n // Do whatever\n }\n}\n</code></pre>\n"
},
{
"answer_id": 136695,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 6,
"selected": true,
"text": "<p>The important thing is that a declaration in C++ is not an expression.</p>\n\n<pre><code>bool a = (CThing* pThing = GetThing()); // not legit!!\n</code></pre>\n\n<p>You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.</p>\n\n<pre><code>if(A *a = new A)\n{\n // this is legit and a is scoped here\n}\n</code></pre>\n\n<p>How can we know whether a is defined between one term and another in an expression?</p>\n\n<pre><code>if((A *a = new A) && a->test())\n{\n // was a really declared before a->test?\n}\n</code></pre>\n\n<p>Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:</p>\n\n<pre><code>if (CThing* pThing = GetThing())\n{\n if(pThing->IsReallySomeThing())\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 136728,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 0,
"selected": false,
"text": "<p>also notice that if you're writing C++ code you want to make the compiler warning about \"=\" in a conditional statement (that isn't part of a declaration) an error.</p>\n"
},
{
"answer_id": 136742,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>It's acceptable and good coding practice. However, people who don't come from a low-level coding background would probably disagree.</p>\n"
},
{
"answer_id": 2103015,
"author": "Daniel Daranas",
"author_id": 96780,
"author_profile": "https://Stackoverflow.com/users/96780",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if (CThing* pThing = GetThing())\n</code></pre>\n\n<p>It is <strong>bad style</strong>, because inside the <code>if</code> you are not providing a boolean expression. You are providing a <code>CThing*</code>.</p>\n\n<pre><code>CThing* pThing = GetThing();\nif (pThing != NULL)\n</code></pre>\n\n<p>This is good style.</p>\n"
},
{
"answer_id": 50222062,
"author": "proski",
"author_id": 2962407,
"author_profile": "https://Stackoverflow.com/users/2962407",
"pm_score": 2,
"selected": false,
"text": "<p>So many things. First of all, bare pointers. Please avoid them by all means. Use references, optional, unique_ptr, shared_ptr. As the last resort, write your own class that deals with pointer ownership and nothing else.</p>\n\n<p>Use uniform initialization if you can require C++11 (C++14 preferred to avoid C++11 defects): - it avoids = vs == confusion and it's stricter at checking the arguments if there are any.</p>\n\n<pre><code>if (CThing thing {})\n{\n}\n</code></pre>\n\n<p>Make sure to implement <code>operator bool</code> to get predictable conversion from CThing to bool. However, keep in mind that other people reading the code would not see <code>operator bool</code> right away. Explicit method calls are generally more readable and reassuring. If you can require C++17, use initializer syntax.</p>\n\n<pre><code>if (CThing thing {}; thing.is_good())\n{\n}\n</code></pre>\n\n<p>If C++17 is not an option, use a declaration above if as others have suggested.</p>\n\n<pre><code>{\n CThing thing {};\n if (thing.is_good())\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 57270774,
"author": "Roman2452809",
"author_id": 2452809,
"author_profile": "https://Stackoverflow.com/users/2452809",
"pm_score": 2,
"selected": false,
"text": "<p>You can have initialization statements inside <code>if</code> and <code>switch</code> since <strong>C++17</strong>.</p>\n\n<p>Your code would now be:</p>\n\n<pre><code>if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())\n{\n // use pThing here\n}\n// pThing is out of scope here\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
]
| In C++ you can initialize a variable in an if statement, like so:
```
if (CThing* pThing = GetThing())
{
}
```
Why would one consider this bad or good style? What are the benefits and disadvantages?
Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:
```
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
```
If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.
[Question borrowed from here, similar topic but PHP.](https://stackoverflow.com/questions/136373/initializing-a-variable-in-a-conditional-statment) | The important thing is that a declaration in C++ is not an expression.
```
bool a = (CThing* pThing = GetThing()); // not legit!!
```
You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.
```
if(A *a = new A)
{
// this is legit and a is scoped here
}
```
How can we know whether a is defined between one term and another in an expression?
```
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
```
Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:
```
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
``` |
136,554 | <p>I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.</p>
<p>Ideas?</p>
<pre><code>#!/usr/bin/expect --
spawn $env(SHELL)
match_max 100000
set timeout 2
send "echo This will print timed out\r"
expect {
timeout { puts "timed out at step 1" }
"foo " { puts "it said foo at step 1"}
}
puts "Starting test two\r"
send "echo This will not print timed out\r"
expect -re {
timeout { puts "timed out at step 2" ; exit }
"foo " { puts "it said foo at step 2"}
}
</code></pre>
| [
{
"answer_id": 136590,
"author": "Luke",
"author_id": 327,
"author_profile": "https://Stackoverflow.com/users/327",
"pm_score": 2,
"selected": false,
"text": "<p>This <strike><strong>should</strong></strike>doesn't work in C++ <strike>since</strike>even though it supports <a href=\"http://www.codepedia.com/1/ShortCircuitEval\" rel=\"nofollow noreferrer\">short circuiting evaluation</a>. <strike>Maybe</strike>Don't try the following:</p>\n\n<pre><code>if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))\n{\n}\n</code></pre>\n\n<p>err.. see <a href=\"https://stackoverflow.com/questions/136548/procon-initializing-a-variable-in-a-conditional-statement-c#136695\">Wesley Tarle's answer</a></p>\n"
},
{
"answer_id": 136621,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 2,
"selected": false,
"text": "<p>One reason I don't normally do that is because of the common bug from a missed '=' in a conditional test. I use lint with the error/warnings set to catch those. It will then yell about all assignments inside conditionals.</p>\n"
},
{
"answer_id": 136627,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 2,
"selected": false,
"text": "<p>About the advantages:</p>\n\n<p>It's always recommended to define variables when you first need them, not a line before. This is for improved readability of your code, since one can tell what CThing is without scrolling and searching where it was defined.</p>\n\n<p>Also reducing scope to a loop/if block, causes the variable to be unreferenced after the execution of the code block, which makes it a candidate for Garbage Collection (if the language supports this feature).</p>\n"
},
{
"answer_id": 136643,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 2,
"selected": false,
"text": "<p>Just an FYI some of the older Microsoft C++ compliers(Visual Studios 6, and .NET 2003 I think) don't quite follow the scoping rule in some instances.</p>\n\n<pre><code>for(int i = 0; i > 20; i++) {\n // some code\n}\n\ncout << i << endl;\n</code></pre>\n\n<p>I should be out of scope, but that was/is valid code. I believe it was played off as a feature, but in my opinion it's just non compliance. Not adhering to the standards is bad. Just as a web developer about IE and Firefox.</p>\n\n<p>Can someone with VS check and see if that's still valid?</p>\n"
},
{
"answer_id": 136645,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 0,
"selected": false,
"text": "<p>You can also enclose the assignment in an extra set of ( ) to prevent the warning message.</p>\n"
},
{
"answer_id": 136660,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 0,
"selected": false,
"text": "<p>I see that as kind of dangerous. The code below is much safer and the enclosing braces will still limit the scope of pThing in the way you want.</p>\n\n<p>I'm assuming GetThing() sometimes returns NULL which is why I put that funny clause in the if() statement. It prevents IsReallySomething() being called on a NULL pointer.</p>\n\n<pre><code>{\n CThing *pThing = GetThing();\n if(pThing ? pThing->IsReallySomeThing() : false)\n {\n // Do whatever\n }\n}\n</code></pre>\n"
},
{
"answer_id": 136695,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 6,
"selected": true,
"text": "<p>The important thing is that a declaration in C++ is not an expression.</p>\n\n<pre><code>bool a = (CThing* pThing = GetThing()); // not legit!!\n</code></pre>\n\n<p>You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.</p>\n\n<pre><code>if(A *a = new A)\n{\n // this is legit and a is scoped here\n}\n</code></pre>\n\n<p>How can we know whether a is defined between one term and another in an expression?</p>\n\n<pre><code>if((A *a = new A) && a->test())\n{\n // was a really declared before a->test?\n}\n</code></pre>\n\n<p>Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:</p>\n\n<pre><code>if (CThing* pThing = GetThing())\n{\n if(pThing->IsReallySomeThing())\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 136728,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 0,
"selected": false,
"text": "<p>also notice that if you're writing C++ code you want to make the compiler warning about \"=\" in a conditional statement (that isn't part of a declaration) an error.</p>\n"
},
{
"answer_id": 136742,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>It's acceptable and good coding practice. However, people who don't come from a low-level coding background would probably disagree.</p>\n"
},
{
"answer_id": 2103015,
"author": "Daniel Daranas",
"author_id": 96780,
"author_profile": "https://Stackoverflow.com/users/96780",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if (CThing* pThing = GetThing())\n</code></pre>\n\n<p>It is <strong>bad style</strong>, because inside the <code>if</code> you are not providing a boolean expression. You are providing a <code>CThing*</code>.</p>\n\n<pre><code>CThing* pThing = GetThing();\nif (pThing != NULL)\n</code></pre>\n\n<p>This is good style.</p>\n"
},
{
"answer_id": 50222062,
"author": "proski",
"author_id": 2962407,
"author_profile": "https://Stackoverflow.com/users/2962407",
"pm_score": 2,
"selected": false,
"text": "<p>So many things. First of all, bare pointers. Please avoid them by all means. Use references, optional, unique_ptr, shared_ptr. As the last resort, write your own class that deals with pointer ownership and nothing else.</p>\n\n<p>Use uniform initialization if you can require C++11 (C++14 preferred to avoid C++11 defects): - it avoids = vs == confusion and it's stricter at checking the arguments if there are any.</p>\n\n<pre><code>if (CThing thing {})\n{\n}\n</code></pre>\n\n<p>Make sure to implement <code>operator bool</code> to get predictable conversion from CThing to bool. However, keep in mind that other people reading the code would not see <code>operator bool</code> right away. Explicit method calls are generally more readable and reassuring. If you can require C++17, use initializer syntax.</p>\n\n<pre><code>if (CThing thing {}; thing.is_good())\n{\n}\n</code></pre>\n\n<p>If C++17 is not an option, use a declaration above if as others have suggested.</p>\n\n<pre><code>{\n CThing thing {};\n if (thing.is_good())\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 57270774,
"author": "Roman2452809",
"author_id": 2452809,
"author_profile": "https://Stackoverflow.com/users/2452809",
"pm_score": 2,
"selected": false,
"text": "<p>You can have initialization statements inside <code>if</code> and <code>switch</code> since <strong>C++17</strong>.</p>\n\n<p>Your code would now be:</p>\n\n<pre><code>if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())\n{\n // use pThing here\n}\n// pThing is out of scope here\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10888/"
]
| I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.
Ideas?
```
#!/usr/bin/expect --
spawn $env(SHELL)
match_max 100000
set timeout 2
send "echo This will print timed out\r"
expect {
timeout { puts "timed out at step 1" }
"foo " { puts "it said foo at step 1"}
}
puts "Starting test two\r"
send "echo This will not print timed out\r"
expect -re {
timeout { puts "timed out at step 2" ; exit }
"foo " { puts "it said foo at step 2"}
}
``` | The important thing is that a declaration in C++ is not an expression.
```
bool a = (CThing* pThing = GetThing()); // not legit!!
```
You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.
```
if(A *a = new A)
{
// this is legit and a is scoped here
}
```
How can we know whether a is defined between one term and another in an expression?
```
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
```
Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:
```
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
``` |
136,580 | <p>I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites. </p>
<p>I wrote the following code:</p>
<pre><code>composite.addListener (SWT.Paint, new Listener () {
public void handleEvent (Event e) {
GC gc = e.gc;
Rectangle rect = composite.getClientArea ();
Color color1 = new Color (display, 0, 0, 0);
Color color2 = new Color (display, 255, 255, 255);
gc.setForeground(color1);
gc.setBackground(color2);
gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true);
}
});
</code></pre>
<p>This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite. </p>
<p>In these areas, the background is just the plain gray you get when drawing an empty canvas. </p>
<p>I've tried forcing the Labels to inherit the background like so:</p>
<pre><code>label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either
</code></pre>
<p>But this leaves me with the same default gray and no gradient behind the components on top of the Composite. </p>
<p>Any suggestions for getting the gradient to be the background of each element?</p>
<p>I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements. </p>
<p>Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient. </p>
<p>[edit] I uploaded an example upto twitpic <a href="http://twitpic.com/d5qz" rel="nofollow noreferrer">here</a>.</p>
<p>Thanks,</p>
<p>Brian Gianforcaro</p>
| [
{
"answer_id": 136668,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": -1,
"selected": false,
"text": "<p>The first thing I would try is to <a href=\"http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet95.java\" rel=\"nofollow noreferrer\">capture an image from the widget</a> and paint the portion of the image where the child widget is located onto the child widget directly.\n<p>\nIf that doesn't work, try using the same paint listener for both widget, but before to set the GC's transform to after transforming the GC to translate coordinates to the label's coordinate space:</p>\n\n<pre><code>Listener listener = new Listener () {\n public void handleEvent (Event e) {\n GC gc = e.gc;\n Rectangle rect = composite.getClientArea ();\n Point offset = ((Control)e.widget).toControl(composite.toDisplay(0, 0));\n Color color1 = new Color (display, 0, 0, 0);\n Color color2 = new Color (display, 255, 255, 255);\n gc.setForeground(color1);\n gc.setBackground(color2);\n gc.fillGradientRectangle (rect.x + offset.x, rect.y + offset.y,\n rect.width, rect.height , true);\n }\n}\ncomposite.addListener (SWT.Paint, listener);\nlabel.addListener(SWT.Paint, listener);\n</code></pre>\n\n<p>Also, be careful to dispose any Color instances you create after you are done with them. Otherwise you will leak system resources and eventually run out.</p>\n"
},
{
"answer_id": 138693,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 4,
"selected": true,
"text": "<p>Use <strong>composite.setBackgroundMode(SWT.INHERIT_DEFAULT)</strong>, but do not paint the composite directly - paint an image and set it as the background image using <strong>composite.setBackgroundImage(Image)</strong>. Unless I'm missing a trick, this means you only have to regenerate the image when the composite is resized too.</p>\n\n<p>You should be able to cut'n'paste this code as is to see what I mean:</p>\n\n<pre><code>import org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.*;\nimport org.eclipse.swt.layout.*;\nimport org.eclipse.swt.widgets.*;\n\n/**\n * SWT composite with transparent label\n * \n * @author McDowell\n */\npublic class Sweet {\n\n private Image imageGradient;\n private Label label;\n private Composite composite;\n\n private void createComponents(Shell parent) {\n composite = new Composite(parent, SWT.NONE);\n composite.addListener(SWT.Resize, new Listener() {\n public void handleEvent(Event e) {\n changeImage();\n }\n });\n composite.setLayout(new FormLayout());\n composite.setBackgroundMode(SWT.INHERIT_DEFAULT);\n\n label = new Label(composite, SWT.None);\n label.setText(\"Hello, World!\");\n }\n\n private void changeImage() {\n Image oldImage = imageGradient;\n\n Display display = composite.getDisplay();\n Rectangle rect = composite.getClientArea();\n imageGradient = new Image(display, rect.width, rect.height);\n GC gc = new GC(imageGradient);\n try {\n Color color1 = new Color(display, 200, 200, 255);\n try {\n Color color2 = new Color(display, 255, 255, 255);\n try {\n gc.setForeground(color1);\n gc.setBackground(color2);\n gc.fillGradientRectangle(rect.x, rect.y, rect.width,\n rect.height, true);\n } finally {\n color2.dispose();\n }\n } finally {\n color1.dispose();\n }\n } finally {\n gc.dispose();\n }\n composite.setBackgroundImage(imageGradient);\n\n if (oldImage != null) {\n oldImage.dispose();\n }\n }\n\n private void openShell(Display display) {\n Shell shell = new Shell(display);\n try {\n shell.setSize(200, 100);\n shell.setLayout(new FillLayout());\n createComponents(shell);\n shell.open();\n while (!shell.isDisposed()) {\n if (!display.readAndDispatch()) {\n display.sleep();\n }\n }\n } finally {\n if (!shell.isDisposed()) {\n shell.dispose();\n }\n }\n }\n\n public void run() {\n Display display = Display.getDefault();\n try {\n openShell(display);\n } finally {\n display.dispose();\n }\n }\n\n public void dispose() {\n if (imageGradient != null) {\n imageGradient.dispose();\n }\n }\n\n public static void main(String[] args) {\n Sweet sweet = new Sweet();\n try {\n sweet.run();\n } finally {\n sweet.dispose();\n }\n }\n\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
]
| I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites.
I wrote the following code:
```
composite.addListener (SWT.Paint, new Listener () {
public void handleEvent (Event e) {
GC gc = e.gc;
Rectangle rect = composite.getClientArea ();
Color color1 = new Color (display, 0, 0, 0);
Color color2 = new Color (display, 255, 255, 255);
gc.setForeground(color1);
gc.setBackground(color2);
gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true);
}
});
```
This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite.
In these areas, the background is just the plain gray you get when drawing an empty canvas.
I've tried forcing the Labels to inherit the background like so:
```
label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either
```
But this leaves me with the same default gray and no gradient behind the components on top of the Composite.
Any suggestions for getting the gradient to be the background of each element?
I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements.
Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient.
[edit] I uploaded an example upto twitpic [here](http://twitpic.com/d5qz).
Thanks,
Brian Gianforcaro | Use **composite.setBackgroundMode(SWT.INHERIT\_DEFAULT)**, but do not paint the composite directly - paint an image and set it as the background image using **composite.setBackgroundImage(Image)**. Unless I'm missing a trick, this means you only have to regenerate the image when the composite is resized too.
You should be able to cut'n'paste this code as is to see what I mean:
```
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* SWT composite with transparent label
*
* @author McDowell
*/
public class Sweet {
private Image imageGradient;
private Label label;
private Composite composite;
private void createComponents(Shell parent) {
composite = new Composite(parent, SWT.NONE);
composite.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event e) {
changeImage();
}
});
composite.setLayout(new FormLayout());
composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
label = new Label(composite, SWT.None);
label.setText("Hello, World!");
}
private void changeImage() {
Image oldImage = imageGradient;
Display display = composite.getDisplay();
Rectangle rect = composite.getClientArea();
imageGradient = new Image(display, rect.width, rect.height);
GC gc = new GC(imageGradient);
try {
Color color1 = new Color(display, 200, 200, 255);
try {
Color color2 = new Color(display, 255, 255, 255);
try {
gc.setForeground(color1);
gc.setBackground(color2);
gc.fillGradientRectangle(rect.x, rect.y, rect.width,
rect.height, true);
} finally {
color2.dispose();
}
} finally {
color1.dispose();
}
} finally {
gc.dispose();
}
composite.setBackgroundImage(imageGradient);
if (oldImage != null) {
oldImage.dispose();
}
}
private void openShell(Display display) {
Shell shell = new Shell(display);
try {
shell.setSize(200, 100);
shell.setLayout(new FillLayout());
createComponents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} finally {
if (!shell.isDisposed()) {
shell.dispose();
}
}
}
public void run() {
Display display = Display.getDefault();
try {
openShell(display);
} finally {
display.dispose();
}
}
public void dispose() {
if (imageGradient != null) {
imageGradient.dispose();
}
}
public static void main(String[] args) {
Sweet sweet = new Sweet();
try {
sweet.run();
} finally {
sweet.dispose();
}
}
}
``` |
136,581 | <p>Is there a way to keep the "Loading..." graphic from appearing when cfdiv refreshes? I'd like to prevent the flicker of loading the graphic then loading the new html.</p>
| [
{
"answer_id": 140429,
"author": "bhinks",
"author_id": 5877,
"author_profile": "https://Stackoverflow.com/users/5877",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think there is currently a way to do this programmatically within the <code>cfdiv</code> tag. If you really want to get rid of that \"Loading...\" message and the image, there are a couple places you can look. </p>\n\n<p>You can rename or delete the image, which is located at: <strong>CFIDE\\scripts\\ajax\\resources\\cf\\images\\loading.gif</strong></p>\n\n<p>That only gets rid of the animation. The \"Loading...\" text can be blanked out to an empty string, and is defined in: <strong>CFIDE\\scripts\\ajax\\messages\\cfmessage.js</strong></p>\n\n<p>Making these changes will obviously have an impact on tags other than <code>cfdiv</code>, but if you are looking to eliminate this behavior in one place, I'm sure you won't mind killing it everywhere else too. :)</p>\n\n<p>I'd love to see a cleaner way to do this if anybody else has any ideas. </p>\n"
},
{
"answer_id": 140576,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 3,
"selected": true,
"text": "<p>By adding these lines at the bottom of the header, it overwrites the \"Loading...\" html and seems to prevent the flickering effect in both IE and FireFox: </p>\n\n<pre><code> <script language=\"JavaScript\"> \n _cf_loadingtexthtml=\"\"; \n </script> \n</code></pre>\n\n<p>While this seems to do the trick, it would be nice if there was an officially supported way to customize the loading animation on a per page or per control basis. Hopefully they add support for that in ColdFusion9.</p>\n"
},
{
"answer_id": 2268563,
"author": "freddy v",
"author_id": 273779,
"author_profile": "https://Stackoverflow.com/users/273779",
"pm_score": 0,
"selected": false,
"text": "<p>You can create functions to change the message prior calling the ajax load that can set the message and image to a new value.</p>\n\n<pre><code>function loadingOrder(){\n _cf_loadingtexthtml=\"Loading Order Form <image src='/CFIDE/scripts/ajax/resources/cf/images/loading.gif'>\"; \n}\n\nfunction loadingNavigation(){\n _cf_loadingtexthtml=\"Loading Menu <image src='/CFIDE/scripts/ajax/resources/cf/images/loading_nav.gif'>\"; \n}\n</code></pre>\n\n<p>(these will eventually be rolled into a single function that will take both a text_value and an image_path parameter) </p>\n\n<p>In some of my processes that load both a main and left nav cfdiv I use a function like this:</p>\n\n<pre><code>function locateCreateOrder(){\n loadingOrder();\n ColdFusion.navigate('/functional_areas/orders/orders_actions/cf9_act_orders_index.cfm','main_content');\n loadingNavigation();\n ColdFusion.navigate('/functional_areas/products/products_actions/cf9_products_menu.cfm','left_menu');\n}\n</code></pre>\n"
},
{
"answer_id": 2386627,
"author": "Mohamad",
"author_id": 276959,
"author_profile": "https://Stackoverflow.com/users/276959",
"pm_score": 1,
"selected": false,
"text": "<p>This is by no means a comprehensive or an elegant solution, but I found using negative margins on adjacent elements can \"cover\" the animation. I don't know if this method works in all cases, but for my particular case it worked. The animation appeared next to a binded text field, to the right of which was a submit button. The layer was floated to the right. I used negative margin on the submit button and it covered the animation without affecting the layer alignment.</p>\n\n<p>Another measure I did was to check the layer structure, and added the following code to my css be sure:</p>\n\n<pre><code>#TitleNameloadingicon {visibility:hidden;}\n#TitleName_cf_button {visibility:hidden;}\n#TitleNameautosuggest {background-color:#ffffff;}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
]
| Is there a way to keep the "Loading..." graphic from appearing when cfdiv refreshes? I'd like to prevent the flicker of loading the graphic then loading the new html. | By adding these lines at the bottom of the header, it overwrites the "Loading..." html and seems to prevent the flickering effect in both IE and FireFox:
```
<script language="JavaScript">
_cf_loadingtexthtml="";
</script>
```
While this seems to do the trick, it would be nice if there was an officially supported way to customize the loading animation on a per page or per control basis. Hopefully they add support for that in ColdFusion9. |
136,604 | <p>Sorry if the title is poorly descriptive, but I can't do better right now =(</p>
<p>So, I have this master-detail scheme, with the detail being a tree structure (one to many self relation) with n levels (on SQLServer 2005)</p>
<p>I need to copy a detail structure from one master to the another using a stored procedure, by passing the source master id and the target master id as parameters (the target is new, so it doesn't has details).</p>
<p>I'm having troubles, and asking for your kind help in finding a way to keep track of parent id's and inserting the children without using cursors or nasty things like that...</p>
<p><img src="https://i.stack.imgur.com/hBzdZ.jpg" alt="table model for the problem"></p>
<p>This is a sample model, of course, and what I'm trying to do is to copy the detail structure from one master to other. In fact, I'm creating a new master using an existing one as template.</p>
| [
{
"answer_id": 136677,
"author": "Mladen",
"author_id": 21404,
"author_profile": "https://Stackoverflow.com/users/21404",
"pm_score": 0,
"selected": false,
"text": "<p>you'll have to provide create table and insert into statements for little sample data.\nand expected results based on this sample data.</p>\n"
},
{
"answer_id": 137162,
"author": "GilM",
"author_id": 10192,
"author_profile": "https://Stackoverflow.com/users/10192",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand the problem, this might be what you want:</p>\n\n<pre><code>INSERT dbo.Master VALUES (@NewMaster_ID, @NewDescription)\n\nINSERT dbo.Detail (parent_id, master_id, [name])\nSELECT detail_ID, @NewMaster_ID, [name]\nFROM dbo.Detail \nWHERE master_id = @OldMaster_ID\n\nUPDATE NewChild\nSET parent_id = NewParent.detail_id\nFROM dbo.Detail NewChild\nJOIN dbo.Detail OldChild\nON NewChild.parent_id = OldChild.detail_id\nJOIN dbo.Detail NewParent\nON NewParent.parent_id = OldChild.parent_ID\nWHERE NewChild.master_id = @NewMaster_ID\nAND NewParent.master_id = @NewMaster_ID\nAND OldChild.master_id = @OldMaster_ID\n</code></pre>\n\n<p>The trick is to use the old <code>detail_id</code> as the new <code>parent_id</code> in the initial insert. Then join back to the old set of rows using this relationship, and update the new <code>parent_id</code> values.</p>\n\n<p>I assumed that <code>detail_id</code> is an IDENTITY value. If you assign them yourself, you'll need to provide details, but there's a similar solution.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6359/"
]
| Sorry if the title is poorly descriptive, but I can't do better right now =(
So, I have this master-detail scheme, with the detail being a tree structure (one to many self relation) with n levels (on SQLServer 2005)
I need to copy a detail structure from one master to the another using a stored procedure, by passing the source master id and the target master id as parameters (the target is new, so it doesn't has details).
I'm having troubles, and asking for your kind help in finding a way to keep track of parent id's and inserting the children without using cursors or nasty things like that...

This is a sample model, of course, and what I'm trying to do is to copy the detail structure from one master to other. In fact, I'm creating a new master using an existing one as template. | If I understand the problem, this might be what you want:
```
INSERT dbo.Master VALUES (@NewMaster_ID, @NewDescription)
INSERT dbo.Detail (parent_id, master_id, [name])
SELECT detail_ID, @NewMaster_ID, [name]
FROM dbo.Detail
WHERE master_id = @OldMaster_ID
UPDATE NewChild
SET parent_id = NewParent.detail_id
FROM dbo.Detail NewChild
JOIN dbo.Detail OldChild
ON NewChild.parent_id = OldChild.detail_id
JOIN dbo.Detail NewParent
ON NewParent.parent_id = OldChild.parent_ID
WHERE NewChild.master_id = @NewMaster_ID
AND NewParent.master_id = @NewMaster_ID
AND OldChild.master_id = @OldMaster_ID
```
The trick is to use the old `detail_id` as the new `parent_id` in the initial insert. Then join back to the old set of rows using this relationship, and update the new `parent_id` values.
I assumed that `detail_id` is an IDENTITY value. If you assign them yourself, you'll need to provide details, but there's a similar solution. |
136,615 | <p>How can I <em>programmatically</em> determine if I have access to a server (TCP) with a given IP address and port using C#?</p>
| [
{
"answer_id": 136625,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 5,
"selected": true,
"text": "<p>Assuming you mean through a TCP socket:</p>\n\n<pre><code>IPAddress IP;\nif(IPAddress.TryParse(\"127.0.0.1\",out IP)){\n Socket s = new Socket(AddressFamily.InterNetwork,\n SocketType.Stream,\n ProtocolType.Tcp);\n\n try{ \n s.Connect(IPs[0], port);\n }\n catch(Exception ex){\n // something went wrong\n }\n}\n</code></pre>\n\n<p>For more information: <a href=\"http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4</a></p>\n"
},
{
"answer_id": 136644,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 4,
"selected": false,
"text": "<p>Declare string address and int port and you are ready to connect through the TcpClient class.</p>\n\n<pre><code>System.Net.Sockets.TcpClient client = new TcpClient();\ntry\n{\n client.Connect(address, port);\n Console.WriteLine(\"Connection open, host active\");\n} catch (SocketException ex)\n{\n Console.WriteLine(\"Connection could not be established due to: \\n\" + ex.Message);\n}\nfinally\n{\n client.Close();\n}\n</code></pre>\n"
},
{
"answer_id": 136648,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": -1,
"selected": false,
"text": "<p>This should do it </p>\n\n<pre><code>bool ssl;\nssl = false;\nint maxWaitMillisec;\nmaxWaitMillisec = 20000;\nint port = 555;\n\nsuccess = socket.Connect(\"Your ip address\",port,ssl,maxWaitMillisec);\n\n\nif (success != true) {\n\n MessageBox.Show(socket.LastErrorText);\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 137251,
"author": "Kepboy",
"author_id": 21429,
"author_profile": "https://Stackoverflow.com/users/21429",
"pm_score": 4,
"selected": false,
"text": "<p>You could use the Ping class (.NET 2.0 and above)</p>\n\n<pre>\n Ping x = new Ping();\n PingReply reply = x.Send(IPAddress.Parse(\"127.0.0.1\"));\n\n if(reply.Status == IPStatus.Success)\n Console.WriteLine(\"Address is accessible\");\n</pre>\n\n<p>You might want to use the asynchronous methods in a production system to allow cancelling, etc.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How can I *programmatically* determine if I have access to a server (TCP) with a given IP address and port using C#? | Assuming you mean through a TCP socket:
```
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
```
For more information: <http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4> |
136,617 | <p>How do I programmatically force an onchange event on an input?</p>
<p>I've tried something like this:</p>
<pre><code>var code = ele.getAttribute('onchange');
eval(code);
</code></pre>
<p>But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.</p>
| [
{
"answer_id": 136633,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": -1,
"selected": false,
"text": "<p>if you're using jQuery you would have:</p>\n\n<pre><code>$('#elementId').change(function() { alert('Do Stuff'); });\n</code></pre>\n\n<p>or MS AJAX:</p>\n\n<pre><code>$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });\n</code></pre>\n\n<p>Or in the raw HTML of the element:</p>\n\n<pre><code><input type=\"text\" onchange=\"alert('Do Stuff');\" id=\"myElement\" />\n</code></pre>\n\n<p>After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:</p>\n\n<pre><code>$addHandler($get('elementId'), 'change', elementChanged);\nfunction elementChanged(){\n alert('Do Stuff!');\n}\nfunction editElement(){\n var el = $get('elementId');\n el.value = 'something new';\n elementChanged();\n}\n</code></pre>\n\n<p>Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.</p>\n\n<p>Or, if you <em>are</em> using the Microsoft AJAX framework you can access all the event handlers via:</p>\n\n<pre><code>$get('elementId')._events\n</code></pre>\n\n<p>It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.</p>\n"
},
{
"answer_id": 136636,
"author": "Kolten",
"author_id": 13959,
"author_profile": "https://Stackoverflow.com/users/13959",
"pm_score": 6,
"selected": false,
"text": "<p>ugh don't use eval for <em>anything</em>. Well, there are certain things, but they're extremely rare.\nRather, you would do this:</p>\n\n<pre><code>document.getElementById(\"test\").onchange()\n</code></pre>\n\n<p>Look here for more options:\n<a href=\"http://jehiah.cz/archive/firing-javascript-events-properly\" rel=\"noreferrer\">http://jehiah.cz/archive/firing-javascript-events-properly</a></p>\n"
},
{
"answer_id": 136768,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from the bottom of <a href=\"http://dev.jquery.com/view/trunk/qunit/testrunner.js\" rel=\"nofollow noreferrer\">QUnit</a></p>\n\n<pre><code>function triggerEvent( elem, type, event ) {\n if ( $.browser.mozilla || $.browser.opera ) {\n event = document.createEvent(\"MouseEvents\");\n event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,\n 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n elem.dispatchEvent( event );\n } else if ( $.browser.msie ) {\n elem.fireEvent(\"on\"+type);\n }\n}\n</code></pre>\n\n<p>You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.</p>\n\n<p>To use this function:</p>\n\n<pre><code>var event;\ntriggerEvent(ele, \"change\", event);\n</code></pre>\n\n<p>This will basically fire the real DOM event as if something had actually changed.</p>\n"
},
{
"answer_id": 136810,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 5,
"selected": false,
"text": "<p>For some reason ele.onchange() is throwing a \"method not found\" expception for me in IE on my page, so I ended up using this function from the link <a href=\"https://stackoverflow.com/users/13959/kolten\">Kolten</a> provided and calling fireEvent(ele, 'change'), which worked:</p>\n\n<pre><code>function fireEvent(element,event){\n if (document.createEventObject){\n // dispatch for IE\n var evt = document.createEventObject();\n return element.fireEvent('on'+event,evt)\n }\n else{\n // dispatch for firefox + others\n var evt = document.createEvent(\"HTMLEvents\");\n evt.initEvent(event, true, true ); // event type,bubbling,cancelable\n return !element.dispatchEvent(evt);\n }\n}\n</code></pre>\n\n<p>I did however, create a test page that confirmed calling should onchange() work:</p>\n\n<pre><code><input id=\"test1\" name=\"test1\" value=\"Hello\" onchange=\"alert(this.value);\"/>\n<input type=\"button\" onclick=\"document.getElementById('test1').onchange();\" value=\"Say Hello\"/>\n</code></pre>\n\n<p>Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.</p>\n"
},
{
"answer_id": 340330,
"author": "Danita",
"author_id": 26481,
"author_profile": "https://Stackoverflow.com/users/26481",
"pm_score": 7,
"selected": false,
"text": "<p>In jQuery I mostly use:</p>\n\n<pre><code>$(\"#element\").trigger(\"change\");\n</code></pre>\n"
},
{
"answer_id": 36447918,
"author": "STEEL ITBOY",
"author_id": 5901075,
"author_profile": "https://Stackoverflow.com/users/5901075",
"pm_score": -1,
"selected": false,
"text": "<p>Using JQuery you can do the following:</p>\n\n<pre><code>// for the element which uses ID\n$(\"#id\").trigger(\"change\");\n\n// for the element which uses class name\n$(\".class_name\").trigger(\"change\");\n</code></pre>\n"
},
{
"answer_id": 36648958,
"author": "Miscreant",
"author_id": 1851055,
"author_profile": "https://Stackoverflow.com/users/1851055",
"pm_score": 9,
"selected": true,
"text": "<p>Create an <code>Event</code> object and pass it to the <code>dispatchEvent</code> method of the element:</p>\n<pre><code>var element = document.getElementById('just_an_example');\nvar event = new Event('change');\nelement.dispatchEvent(event);\n</code></pre>\n<p>This will trigger event listeners regardless of whether they were registered by calling the <code>addEventListener</code> method or by setting the <code>onchange</code> property of the element.</p>\n<hr />\n<p>By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.</p>\n<p>If you want the event to bubble, you need to pass a second argument to the <code>Event</code> constructor:</p>\n<pre><code>var event = new Event('change', { bubbles: true });\n</code></pre>\n<hr />\n<p>Information about browser compability:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#Browser_Compatibility\" rel=\"noreferrer\">dispatchEvent()</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/Event#Browser_compatibility\" rel=\"noreferrer\">Event()</a></li>\n</ul>\n"
},
{
"answer_id": 52884431,
"author": "Peter Lo",
"author_id": 10073434,
"author_profile": "https://Stackoverflow.com/users/10073434",
"pm_score": 2,
"selected": false,
"text": "<p>This is the most correct answer for IE and Chrome::</p>\n<pre class=\"lang-js prettyprint-override\"><code>var element = document.getElementById('xxxx');\nvar evt = document.createEvent('HTMLEvents');\nevt.initEvent('change', false, true);\nelement.dispatchEvent(evt);\n</code></pre>\n"
},
{
"answer_id": 54902366,
"author": "Hareesh Seela",
"author_id": 10569864,
"author_profile": "https://Stackoverflow.com/users/10569864",
"pm_score": -1,
"selected": false,
"text": "<p>For triggering any event in Javascript.</p>\n\n<pre><code> document.getElementById(\"yourid\").addEventListener(\"change\", function({\n //your code here\n})\n</code></pre>\n"
},
{
"answer_id": 61263659,
"author": "Wntiv Senyh",
"author_id": 13160456,
"author_profile": "https://Stackoverflow.com/users/13160456",
"pm_score": 1,
"selected": false,
"text": "<p>If you add all your events with this snippet of code:</p>\n\n<pre><code>//put this somewhere in your JavaScript:\nHTMLElement.prototype.addEvent = function(event, callback){\n if(!this.events)this.events = {};\n if(!this.events[event]){\n this.events[event] = [];\n var element = this;\n this['on'+event] = function(e){\n var events = element.events[event];\n for(var i=0;i<events.length;i++){\n events[i](e||event);\n }\n }\n }\n this.events[event].push(callback);\n}\n//use like this:\nelement.addEvent('change', function(e){...});\n</code></pre>\n\n<p>then you can just use <code>element.on<EVENTNAME>()</code> where <code><EVENTNAME></code> is the name of your event, and that will call all events with <code><EVENTNAME></code></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
]
| How do I programmatically force an onchange event on an input?
I've tried something like this:
```
var code = ele.getAttribute('onchange');
eval(code);
```
But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute. | Create an `Event` object and pass it to the `dispatchEvent` method of the element:
```
var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);
```
This will trigger event listeners regardless of whether they were registered by calling the `addEventListener` method or by setting the `onchange` property of the element.
---
By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.
If you want the event to bubble, you need to pass a second argument to the `Event` constructor:
```
var event = new Event('change', { bubbles: true });
```
---
Information about browser compability:
* [dispatchEvent()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#Browser_Compatibility)
* [Event()](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event#Browser_compatibility) |
136,628 | <p>I have a model and two views set up like this:</p>
<pre><code>Model ---> OSortFilterProxyModel ---> OListView
Model ------------------------------> OTableView
</code></pre>
<p>When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work?</p>
| [
{
"answer_id": 136936,
"author": "Caleb Huitt - cjhuitt",
"author_id": 9876,
"author_profile": "https://Stackoverflow.com/users/9876",
"pm_score": 2,
"selected": false,
"text": "<p>What is probably happening is that the views do have two different models. One is your original model, the other is the sort filter model.</p>\n\n<p>I'm not sure if this would work, and it depends on what Qt considers \"activated\", but you could connect a function to each of the view's activated slots. These will pass you a model index. You'll have to send the model index through the proxy model in the appropriate direction (mapFromSource and mapToSource). Then, call the setCurrentIndex on the other view.</p>\n\n<p>The documentation for the activated signal states that what is considered \"activated\" varies by platform. There might be other signals you could latch onto, such as the selection model's selection changed signal. You might have to do a different call to change the selection as seen by the user. And finally, it might be possible or even easier to do in a derived QSelectionModel, as long as you remember about mapping to/from the source model.</p>\n"
},
{
"answer_id": 444590,
"author": "Henrik Hartz",
"author_id": 50830,
"author_profile": "https://Stackoverflow.com/users/50830",
"pm_score": 1,
"selected": false,
"text": "<p>Not quite sure how your model subclass is implemented - but the selection depends on persistent model indexes being correct. Can you provide some source code? Are you using the same selection model on both?</p>\n"
},
{
"answer_id": 7471773,
"author": "j_kubik",
"author_id": 455304,
"author_profile": "https://Stackoverflow.com/users/455304",
"pm_score": 1,
"selected": false,
"text": "<p>You propably need to use <a href=\"http://doc.qt.nokia.com/latest/qitemselectionmodel.html#select-2\" rel=\"nofollow\">void QItemSelectionModel::select</a> combined with <a href=\"http://doc.qt.nokia.com/latest/qabstractproxymodel.html#mapSelectionFromSource\" rel=\"nofollow\">QAbstractProxyModel::mapSelectionFromSource</a> and <a href=\"http://doc.qt.nokia.com/latest/qabstractproxymodel.html#mapSelectionToSource\" rel=\"nofollow\">QAbstractProxyModel::mapSelectionToSource</a>. In QListView's selectionChange signal handler you should have </p>\n\n<pre><code>tableView->selection()->select(\n proxyModel->mapSelectionToSource(selected),\n QItemSelectionModel::ClearAndSelect);\n</code></pre>\n\n<p>and analogically with mapSelectionFromSource in QTableView's signalChange signal handler. </p>\n\n<p>Note that i am not sure if Qt will prevent infinite recursion when table will change selection of list which in turn will change selection of table and so on...</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
]
| I have a model and two views set up like this:
```
Model ---> OSortFilterProxyModel ---> OListView
Model ------------------------------> OTableView
```
When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work? | What is probably happening is that the views do have two different models. One is your original model, the other is the sort filter model.
I'm not sure if this would work, and it depends on what Qt considers "activated", but you could connect a function to each of the view's activated slots. These will pass you a model index. You'll have to send the model index through the proxy model in the appropriate direction (mapFromSource and mapToSource). Then, call the setCurrentIndex on the other view.
The documentation for the activated signal states that what is considered "activated" varies by platform. There might be other signals you could latch onto, such as the selection model's selection changed signal. You might have to do a different call to change the selection as seen by the user. And finally, it might be possible or even easier to do in a derived QSelectionModel, as long as you remember about mapping to/from the source model. |
136,635 | <p>We have a .NET 2.0 application which we normally run on IIS6, and used to run fine on IIS7, but recently after installing SP1 for Vista IIS7 seems to be choking on a line in the Web.Config file:</p>
<pre><code><system.web AllowLocation="true">
</code></pre>
<p>Is it safe to remove the AllowLocation attribute? What does this attribute do?</p>
| [
{
"answer_id": 136676,
"author": "ironsam",
"author_id": 3539,
"author_profile": "https://Stackoverflow.com/users/3539",
"pm_score": 0,
"selected": false,
"text": "<p>Having this set to true should enable any <code><location></code> sections in your web.config, so you should be fine to remove it if there's none in there.</p>\n"
},
{
"answer_id": 136931,
"author": "Raelshark",
"author_id": 19678,
"author_profile": "https://Stackoverflow.com/users/19678",
"pm_score": 2,
"selected": true,
"text": "<p>From MSDN:</p>\n\n<blockquote>\n <p>When set to false, the AllowLocation property indicates that the section is accessed by native-code readers. Therefore, the use of the location attribute is not allowed, because the native-code readers do not support the concept of location.</p>\n</blockquote>\n\n<p>The default value is true, so you should be able to remove it with no effect on your application.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8432/"
]
| We have a .NET 2.0 application which we normally run on IIS6, and used to run fine on IIS7, but recently after installing SP1 for Vista IIS7 seems to be choking on a line in the Web.Config file:
```
<system.web AllowLocation="true">
```
Is it safe to remove the AllowLocation attribute? What does this attribute do? | From MSDN:
>
> When set to false, the AllowLocation property indicates that the section is accessed by native-code readers. Therefore, the use of the location attribute is not allowed, because the native-code readers do not support the concept of location.
>
>
>
The default value is true, so you should be able to remove it with no effect on your application. |
136,642 | <p>I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me.</p>
<p>Example input:</p>
<blockquote>
<p>Is this thing on??? or what???</p>
</blockquote>
<p>Desired output:</p>
<blockquote>
<p>Is this thing on? or what?</p>
</blockquote>
<p>I'm using <a href="http://php.net/preg_replace" rel="nofollow noreferrer">preg_replace()</a> in PHP.</p>
| [
{
"answer_id": 136654,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 4,
"selected": true,
"text": "<pre><code>preg_replace('{\\?+}', '?', 'Is this thing on??? or what???');\n</code></pre>\n\n<p>That is, you only have to escape the question mark, the plus in \"\\?+\" means that we're replacing every instance with one or more characters, though I suspect \"\\?{2,}\" might be even better and more efficient (replacing every instance with two or more question mark characters.</p>\n"
},
{
"answer_id": 136655,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "<p><code>preg_replace( '{\\\\?+}', '?', $text );</code></p>\n\n<p>should do it.</p>\n\n<p>You need to escape the question mark itself with a backslash, and then escape the backslash itself with another backslash.</p>\n\n<p>It's situations like this where C#'s <a href=\"http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx\" rel=\"nofollow noreferrer\">verbatim strings</a> are nice.</p>\n"
},
{
"answer_id": 136656,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<p>This should work (I have tested it):</p>\n\n<pre><code>preg_replace('/\\?+/', '?', $subject);\n</code></pre>\n"
},
{
"answer_id": 136664,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "<pre><code>preg_replace('/\\?{2,}/','?',$text)\n</code></pre>\n"
},
{
"answer_id": 136684,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 1,
"selected": false,
"text": "<p>this should do it</p>\n\n<pre><code>preg_replace('/(\\?+)/m', '?', 'what is going in here????');\n</code></pre>\n\n<p>the question mark needs to be escaped and the m is for multiline mode.</p>\n\n<p>This was a good web site to try it out at <a href=\"http://regex.larsolavtorvik.com/\" rel=\"nofollow noreferrer\">http://regex.larsolavtorvik.com/</a></p>\n"
},
{
"answer_id": 136705,
"author": "David Lay",
"author_id": 6359,
"author_profile": "https://Stackoverflow.com/users/6359",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried the pattern</p>\n\n<pre><code>[?]+\n</code></pre>\n\n<p>with the replacement of <code>?</code> ?</p>\n"
},
{
"answer_id": 136916,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 0,
"selected": false,
"text": "<pre><code>str_replace('??', '?', 'Replace ??? in this text');\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
]
| I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me.
Example input:
>
> Is this thing on??? or what???
>
>
>
Desired output:
>
> Is this thing on? or what?
>
>
>
I'm using [preg\_replace()](http://php.net/preg_replace) in PHP. | ```
preg_replace('{\?+}', '?', 'Is this thing on??? or what???');
```
That is, you only have to escape the question mark, the plus in "\?+" means that we're replacing every instance with one or more characters, though I suspect "\?{2,}" might be even better and more efficient (replacing every instance with two or more question mark characters. |
136,672 | <p>I'd like to log stuff in my Sharepoint Web Parts, but I want it to go into the ULS. Most examples that I've found log into the Event Log or some other file, but I did not really find one yet for logging into the ULS.</p>
<p>Annoyingly, Microsoft.SharePoint.Diagnostics Classes are all marked Internal. I did find <a href="http://www.codeplex.com/SharePointOfView/SourceControl/FileView.aspx?itemId=244213&changeSetId=13835" rel="nofollow noreferrer">one example</a> of how to use them anyway through reflection, but that looks really risky and unstable, because Microsoft may change that class with any hotfix they want.</p>
<p>The Sharepoint Documentation wasn't really helpful either - lots of Administrator info about what ULS is and how to configure it, but i have yet to find an example of supported code to actually log my own events.</p>
<p>Any hints or tips?</p>
<p><strong>Edit:</strong> As you may see from the age of this question, this is for SharePoint 2007. In SharePoint 2010, you can use SPDiagnosticsService.Local and then <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spdiagnosticsservicebase.writetrace.aspx" rel="nofollow noreferrer">WriteTrace</a>. See the answer from Jürgen below.</p>
| [
{
"answer_id": 137836,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 4,
"selected": true,
"text": "<p>Yes this is possible, see this MSDN article: <a href=\"http://msdn2.microsoft.com/hi-in/library/aa979595(en-us).aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/hi-in/library/aa979595(en-us).aspx</a></p>\n\n<p>And here is some sample code in C#:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing Microsoft.SharePoint.Administration;\n\nnamespace ManagedTraceProvider\n{\nclass Program\n{\n static void Main(string[] args)\n {\n TraceProvider.RegisterTraceProvider();\n\n TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.High, Guid.Empty, \"MyExeName\", \"Product Name\", \"Category Name\", \"Sample Message\");\n TraceProvider.WriteTrace(TraceProvider.TagFromString(\"abcd\"), TraceProvider.TraceSeverity.Monitorable, Guid.NewGuid(), \"MyExeName\", \"Product Name\", \"Category Name\", \"Sample Message\");\n\n TraceProvider.UnregisterTraceProvider();\n }\n}\n\nstatic class TraceProvider\n{\n static UInt64 hTraceLog;\n static UInt64 hTraceReg;\n\n static class NativeMethods\n {\n internal const int TRACE_VERSION_CURRENT = 1;\n internal const int ERROR_SUCCESS = 0;\n internal const int ERROR_INVALID_PARAMETER = 87;\n internal const int WNODE_FLAG_TRACED_GUID = 0x00020000;\n\n internal enum TraceFlags\n {\n TRACE_FLAG_START = 1,\n TRACE_FLAG_END = 2,\n TRACE_FLAG_MIDDLE = 3,\n TRACE_FLAG_ID_AS_ASCII = 4\n }\n\n // Copied from Win32 APIs\n [StructLayout(LayoutKind.Sequential)]\n internal struct EVENT_TRACE_HEADER_CLASS\n {\n internal byte Type;\n internal byte Level;\n internal ushort Version;\n }\n\n // Copied from Win32 APIs\n [StructLayout(LayoutKind.Sequential)]\n internal struct EVENT_TRACE_HEADER\n {\n internal ushort Size;\n internal ushort FieldTypeFlags;\n internal EVENT_TRACE_HEADER_CLASS Class;\n internal uint ThreadId;\n internal uint ProcessId;\n internal Int64 TimeStamp;\n internal Guid Guid;\n internal uint ClientContext;\n internal uint Flags;\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n internal struct ULSTraceHeader\n {\n internal ushort Size;\n internal uint dwVersion;\n internal uint Id;\n internal Guid correlationID;\n internal TraceFlags dwFlags;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n internal string wzExeName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n internal string wzProduct;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n internal string wzCategory;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 800)]\n internal string wzMessage;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct ULSTrace\n {\n internal EVENT_TRACE_HEADER Header;\n internal ULSTraceHeader ULSHeader;\n }\n\n // Copied from Win32 APIs\n internal enum WMIDPREQUESTCODE\n {\n WMI_GET_ALL_DATA = 0,\n WMI_GET_SINGLE_INSTANCE = 1,\n WMI_SET_SINGLE_INSTANCE = 2,\n WMI_SET_SINGLE_ITEM = 3,\n WMI_ENABLE_EVENTS = 4,\n WMI_DISABLE_EVENTS = 5,\n WMI_ENABLE_COLLECTION = 6,\n WMI_DISABLE_COLLECTION = 7,\n WMI_REGINFO = 8,\n WMI_EXECUTE_METHOD = 9\n }\n\n // Copied from Win32 APIs\n internal unsafe delegate uint EtwProc(NativeMethods.WMIDPREQUESTCODE requestCode, IntPtr requestContext, uint* bufferSize, IntPtr buffer);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode)]\n internal static extern unsafe uint RegisterTraceGuids([In] EtwProc cbFunc, [In] void* context, [In] ref Guid controlGuid, [In] uint guidCount, IntPtr guidReg, [In] string mofImagePath, [In] string mofResourceName, out ulong regHandle);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode)]\n internal static extern uint UnregisterTraceGuids([In]ulong regHandle);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode)]\n internal static extern UInt64 GetTraceLoggerHandle([In]IntPtr Buffer);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n internal static extern uint TraceEvent([In]UInt64 traceHandle, [In]ref ULSTrace evnt);\n }\n\n public enum TraceSeverity\n {\n Unassigned = 0,\n CriticalEvent = 1,\n WarningEvent = 2,\n InformationEvent = 3,\n Exception = 4,\n Assert = 7,\n Unexpected = 10,\n Monitorable = 15,\n High = 20,\n Medium = 50,\n Verbose = 100,\n }\n\n public static void WriteTrace(uint tag, TraceSeverity level, Guid correlationGuid, string exeName, string productName, string categoryName, string message)\n {\n const ushort sizeOfWCHAR = 2;\n NativeMethods.ULSTrace ulsTrace = new NativeMethods.ULSTrace();\n\n // Pretty standard code needed to make things work\n ulsTrace.Header.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTrace));\n ulsTrace.Header.Flags = NativeMethods.WNODE_FLAG_TRACED_GUID;\n ulsTrace.ULSHeader.dwVersion = NativeMethods.TRACE_VERSION_CURRENT;\n ulsTrace.ULSHeader.dwFlags = NativeMethods.TraceFlags.TRACE_FLAG_ID_AS_ASCII;\n ulsTrace.ULSHeader.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTraceHeader));\n\n // Variables communicated to SPTrace\n ulsTrace.ULSHeader.Id = tag;\n ulsTrace.Header.Class.Level = (byte)level;\n ulsTrace.ULSHeader.wzExeName = exeName;\n ulsTrace.ULSHeader.wzProduct = productName;\n ulsTrace.ULSHeader.wzCategory = categoryName;\n ulsTrace.ULSHeader.wzMessage = message;\n ulsTrace.ULSHeader.correlationID = correlationGuid;\n\n // Pptionally, to improve performance by reducing the amount of data copied around,\n // the Size parameters can be reduced by the amount of unused buffer in the Message\n if (message.Length < 800)\n {\n ushort unusedBuffer = (ushort) ((800 - (message.Length + 1)) * sizeOfWCHAR);\n ulsTrace.Header.Size -= unusedBuffer;\n ulsTrace.ULSHeader.Size -= unusedBuffer;\n }\n\n if (hTraceLog != 0)\n NativeMethods.TraceEvent(hTraceLog, ref ulsTrace);\n }\n\n public static unsafe void RegisterTraceProvider()\n {\n SPFarm farm = SPFarm.Local;\n Guid traceGuid = farm.TraceSessionGuid;\n uint result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPtr.Zero, null, null, out hTraceReg);\n System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);\n }\n\n public static void UnregisterTraceProvider()\n {\n uint result = NativeMethods.UnregisterTraceGuids(hTraceReg);\n System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);\n }\n\n public static uint TagFromString(string wzTag)\n {\n System.Diagnostics.Debug.Assert(wzTag.Length == 4);\n return (uint) (wzTag[0] << 24 | wzTag[1] << 16 | wzTag[2] << 8 | wzTag[3]);\n }\n\n static unsafe uint ControlCallback(NativeMethods.WMIDPREQUESTCODE RequestCode, IntPtr Context, uint* InOutBufferSize, IntPtr Buffer)\n {\n uint Status;\n switch (RequestCode)\n {\n case NativeMethods.WMIDPREQUESTCODE.WMI_ENABLE_EVENTS:\n hTraceLog = NativeMethods.GetTraceLoggerHandle(Buffer);\n Status = NativeMethods.ERROR_SUCCESS;\n break;\n case NativeMethods.WMIDPREQUESTCODE.WMI_DISABLE_EVENTS:\n hTraceLog = 0;\n Status = NativeMethods.ERROR_SUCCESS;\n break;\n default:\n Status = NativeMethods.ERROR_INVALID_PARAMETER;\n break;\n }\n\n *InOutBufferSize = 0;\n return Status;\n }\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 395767,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>This DID NOT work for me, and hung up my webpart consistently. I had it working for a second and then not. And only, only when I removed the Trace register/unregister/etc statements would it work.</p>\n\n<p>So I recommend this excellent article which worked for me:\n<a href=\"http://sharepoint.namics.com/2008/05/logging_in_webparts.html\" rel=\"nofollow noreferrer\">http://sharepoint.namics.com/2008/05/logging_in_webparts.html</a></p>\n\n<p>Essentially, you should use:</p>\n\n<p>Common Infrastructure Libraries for .NET.</p>\n\n<p>I downloaded it from here:\n<a href=\"http://netcommon.sourceforge.net/\" rel=\"nofollow noreferrer\">http://netcommon.sourceforge.net/</a></p>\n\n<p>I used gacutil (or the control pane/admin tools/.net config tool) to add the 2.0/release dll's to the gac.</p>\n\n<p>I added references to my code to the dll's (from the download). Everything compiled.</p>\n\n<p>I had to create a directory and empty log file, and bam! on the first web part load it worked. I tried for hours and hours to get logging for my web part and this worked wonderfully, and it's a good standard, like log4j.</p>\n"
},
{
"answer_id": 6388191,
"author": "Jürgen",
"author_id": 803520,
"author_profile": "https://Stackoverflow.com/users/803520",
"pm_score": 1,
"selected": false,
"text": "<p>Here you find another great article about logging with SharePoint:\n<a href=\"http://www.parago.de/2011/01/how-to-implement-a-custom-sharepoint-2010-logging-service-for-uls-and-windows-event-log/\" rel=\"nofollow\">http://www.parago.de/2011/01/how-to-implement-a-custom-sharepoint-2010-logging-service-for-uls-and-windows-event-log/</a></p>\n"
},
{
"answer_id": 17389756,
"author": "Amit Bhagat",
"author_id": 836551,
"author_profile": "https://Stackoverflow.com/users/836551",
"pm_score": 2,
"selected": false,
"text": "<p>The credit goes to: <a href=\"http://msdn.microsoft.com/en-us/library/gg512103(v=office.14).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/gg512103(v=office.14).aspx</a><br>\nI have just published a post on my blog, but pasting the code here.</p>\n\n<p>Define name of your solution in the code for following line:</p>\n\n<pre><code>private const string PRODUCT_NAME = \"My Custom Solution\";\n</code></pre>\n\n<p>Following are sample code on how to use it:</p>\n\n<pre><code>UlsLogging.LogInformation(\"This is information message\");\nUlsLogging.LogInformation(\"{0}This is information message\",\"Information:\"); \n\nUlsLogging.LogWarning(\"This is warning message\");\nUlsLogging.LogWarning(\"{0}This is warning message\", \"Warning:\"); \n\nUlsLogging.LogError(\"This is error message\");\nUlsLogging.LogError(\"{0}This is error message\",\"Error:\"); \n</code></pre>\n\n<p>Following is the code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.SharePoint.Administration;\nnamespace MyLoggingApp\n{\n public class UlsLogging : SPDiagnosticsServiceBase\n {\n // Product name\n private const string PRODUCT_NAME = \"My Custom Solution\";\n\n #region private variables\n\n // Current instance\n private static UlsLogging _current;\n\n // area\n private static SPDiagnosticsArea _area;\n\n // category\n private static SPDiagnosticsCategory _catError;\n private static SPDiagnosticsCategory _catWarning;\n private static SPDiagnosticsCategory _catLogging;\n\n #endregion\n\n private static class CategoryName\n {\n public const string Error = \"Error\";\n public const string Warning = \"Warning\";\n public const string Logging = \"Logging\";\n }\n\n private static UlsLogging Current\n {\n get\n {\n if (_current == null)\n {\n _current = new UlsLogging();\n }\n return _current;\n }\n }\n\n // Get Area\n private static SPDiagnosticsArea Area\n {\n get\n {\n if (_area == null)\n {\n _area = UlsLogging.Current.Areas[PRODUCT_NAME];\n }\n return _area;\n }\n }\n\n // Get error category\n private static SPDiagnosticsCategory CategoryError\n {\n get\n {\n if (_catError == null)\n {\n _catError = Area.Categories[CategoryName.Error];\n }\n return _catError;\n }\n }\n\n // Get warning category\n private static SPDiagnosticsCategory CategoryWarning\n {\n get\n {\n if (_catWarning == null)\n {\n _catWarning = Area.Categories[CategoryName.Warning];\n }\n return _catWarning;\n }\n }\n\n // Get logging category\n private static SPDiagnosticsCategory CategoryLogging\n {\n get\n {\n if (_catLogging == null)\n {\n _catLogging = Area.Categories[CategoryName.Logging];\n }\n return _catLogging;\n }\n }\n\n private UlsLogging()\n : base(PRODUCT_NAME, SPFarm.Local)\n {\n }\n\n protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()\n {\n var cat = new List<SPDiagnosticsCategory>{\n new SPDiagnosticsCategory(CategoryName.Error, TraceSeverity.High,EventSeverity.Error),\n new SPDiagnosticsCategory(CategoryName.Warning, TraceSeverity.Medium,EventSeverity.Warning),\n new SPDiagnosticsCategory(CategoryName.Logging,TraceSeverity.Verbose,EventSeverity.Information)\n };\n var areas = new List<SPDiagnosticsArea>();\n areas.Add(new SPDiagnosticsArea(PRODUCT_NAME, cat));\n\n return areas;\n }\n\n // Log Error\n public static void LogError(string msg)\n {\n UlsLogging.Current.WriteTrace(0, CategoryError, TraceSeverity.High, msg);\n }\n public static void LogError(string msg,params object[] args)\n {\n UlsLogging.Current.WriteTrace(0, CategoryError, TraceSeverity.High, msg,args);\n }\n\n // Log Warning\n public static void LogWarning(string msg)\n {\n UlsLogging.Current.WriteTrace(0, CategoryWarning, TraceSeverity.Medium, msg);\n }\n public static void LogWarning(string msg, params object[] args)\n {\n UlsLogging.Current.WriteTrace(0, CategoryWarning, TraceSeverity.Medium, msg,args);\n }\n\n // Log Information\n public static void LogInformation(string msg)\n {\n UlsLogging.Current.WriteTrace(0, CategoryLogging, TraceSeverity.Verbose, msg); \n }\n public static void LogInformation(string msg,params object[] args)\n {\n UlsLogging.Current.WriteTrace(0, CategoryLogging, TraceSeverity.Verbose, msg,args);\n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23607513,
"author": "Vikas Kottari",
"author_id": 2757125,
"author_profile": "https://Stackoverflow.com/users/2757125",
"pm_score": 1,
"selected": false,
"text": "<p>Try Below Code:\n(add this reference:\n using Microsoft.SharePoint.Administration;)</p>\n\n<pre><code>try\n {\n\n SPSecurity.RunWithElevatedPrivileges(delegate()\n {\n SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;\n diagSvc.WriteTrace(123456, new SPDiagnosticsCategory(\"Category_Name_Here\", TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable, \"{0}:{1}\", new object[] { \"Method_Name\", \"Error_Message\"});\n });\n }\n catch (Exception ex)\n {\n }\n</code></pre>\n\n<p>Now open uls viewer and filter by your category name.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
| I'd like to log stuff in my Sharepoint Web Parts, but I want it to go into the ULS. Most examples that I've found log into the Event Log or some other file, but I did not really find one yet for logging into the ULS.
Annoyingly, Microsoft.SharePoint.Diagnostics Classes are all marked Internal. I did find [one example](http://www.codeplex.com/SharePointOfView/SourceControl/FileView.aspx?itemId=244213&changeSetId=13835) of how to use them anyway through reflection, but that looks really risky and unstable, because Microsoft may change that class with any hotfix they want.
The Sharepoint Documentation wasn't really helpful either - lots of Administrator info about what ULS is and how to configure it, but i have yet to find an example of supported code to actually log my own events.
Any hints or tips?
**Edit:** As you may see from the age of this question, this is for SharePoint 2007. In SharePoint 2010, you can use SPDiagnosticsService.Local and then [WriteTrace](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spdiagnosticsservicebase.writetrace.aspx). See the answer from Jürgen below. | Yes this is possible, see this MSDN article: <http://msdn2.microsoft.com/hi-in/library/aa979595(en-us).aspx>
And here is some sample code in C#:
```
using System;
using System.Runtime.InteropServices;
using Microsoft.SharePoint.Administration;
namespace ManagedTraceProvider
{
class Program
{
static void Main(string[] args)
{
TraceProvider.RegisterTraceProvider();
TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.High, Guid.Empty, "MyExeName", "Product Name", "Category Name", "Sample Message");
TraceProvider.WriteTrace(TraceProvider.TagFromString("abcd"), TraceProvider.TraceSeverity.Monitorable, Guid.NewGuid(), "MyExeName", "Product Name", "Category Name", "Sample Message");
TraceProvider.UnregisterTraceProvider();
}
}
static class TraceProvider
{
static UInt64 hTraceLog;
static UInt64 hTraceReg;
static class NativeMethods
{
internal const int TRACE_VERSION_CURRENT = 1;
internal const int ERROR_SUCCESS = 0;
internal const int ERROR_INVALID_PARAMETER = 87;
internal const int WNODE_FLAG_TRACED_GUID = 0x00020000;
internal enum TraceFlags
{
TRACE_FLAG_START = 1,
TRACE_FLAG_END = 2,
TRACE_FLAG_MIDDLE = 3,
TRACE_FLAG_ID_AS_ASCII = 4
}
// Copied from Win32 APIs
[StructLayout(LayoutKind.Sequential)]
internal struct EVENT_TRACE_HEADER_CLASS
{
internal byte Type;
internal byte Level;
internal ushort Version;
}
// Copied from Win32 APIs
[StructLayout(LayoutKind.Sequential)]
internal struct EVENT_TRACE_HEADER
{
internal ushort Size;
internal ushort FieldTypeFlags;
internal EVENT_TRACE_HEADER_CLASS Class;
internal uint ThreadId;
internal uint ProcessId;
internal Int64 TimeStamp;
internal Guid Guid;
internal uint ClientContext;
internal uint Flags;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct ULSTraceHeader
{
internal ushort Size;
internal uint dwVersion;
internal uint Id;
internal Guid correlationID;
internal TraceFlags dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
internal string wzExeName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
internal string wzProduct;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
internal string wzCategory;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 800)]
internal string wzMessage;
}
[StructLayout(LayoutKind.Sequential)]
internal struct ULSTrace
{
internal EVENT_TRACE_HEADER Header;
internal ULSTraceHeader ULSHeader;
}
// Copied from Win32 APIs
internal enum WMIDPREQUESTCODE
{
WMI_GET_ALL_DATA = 0,
WMI_GET_SINGLE_INSTANCE = 1,
WMI_SET_SINGLE_INSTANCE = 2,
WMI_SET_SINGLE_ITEM = 3,
WMI_ENABLE_EVENTS = 4,
WMI_DISABLE_EVENTS = 5,
WMI_ENABLE_COLLECTION = 6,
WMI_DISABLE_COLLECTION = 7,
WMI_REGINFO = 8,
WMI_EXECUTE_METHOD = 9
}
// Copied from Win32 APIs
internal unsafe delegate uint EtwProc(NativeMethods.WMIDPREQUESTCODE requestCode, IntPtr requestContext, uint* bufferSize, IntPtr buffer);
// Copied from Win32 APIs
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
internal static extern unsafe uint RegisterTraceGuids([In] EtwProc cbFunc, [In] void* context, [In] ref Guid controlGuid, [In] uint guidCount, IntPtr guidReg, [In] string mofImagePath, [In] string mofResourceName, out ulong regHandle);
// Copied from Win32 APIs
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
internal static extern uint UnregisterTraceGuids([In]ulong regHandle);
// Copied from Win32 APIs
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
internal static extern UInt64 GetTraceLoggerHandle([In]IntPtr Buffer);
// Copied from Win32 APIs
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern uint TraceEvent([In]UInt64 traceHandle, [In]ref ULSTrace evnt);
}
public enum TraceSeverity
{
Unassigned = 0,
CriticalEvent = 1,
WarningEvent = 2,
InformationEvent = 3,
Exception = 4,
Assert = 7,
Unexpected = 10,
Monitorable = 15,
High = 20,
Medium = 50,
Verbose = 100,
}
public static void WriteTrace(uint tag, TraceSeverity level, Guid correlationGuid, string exeName, string productName, string categoryName, string message)
{
const ushort sizeOfWCHAR = 2;
NativeMethods.ULSTrace ulsTrace = new NativeMethods.ULSTrace();
// Pretty standard code needed to make things work
ulsTrace.Header.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTrace));
ulsTrace.Header.Flags = NativeMethods.WNODE_FLAG_TRACED_GUID;
ulsTrace.ULSHeader.dwVersion = NativeMethods.TRACE_VERSION_CURRENT;
ulsTrace.ULSHeader.dwFlags = NativeMethods.TraceFlags.TRACE_FLAG_ID_AS_ASCII;
ulsTrace.ULSHeader.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTraceHeader));
// Variables communicated to SPTrace
ulsTrace.ULSHeader.Id = tag;
ulsTrace.Header.Class.Level = (byte)level;
ulsTrace.ULSHeader.wzExeName = exeName;
ulsTrace.ULSHeader.wzProduct = productName;
ulsTrace.ULSHeader.wzCategory = categoryName;
ulsTrace.ULSHeader.wzMessage = message;
ulsTrace.ULSHeader.correlationID = correlationGuid;
// Pptionally, to improve performance by reducing the amount of data copied around,
// the Size parameters can be reduced by the amount of unused buffer in the Message
if (message.Length < 800)
{
ushort unusedBuffer = (ushort) ((800 - (message.Length + 1)) * sizeOfWCHAR);
ulsTrace.Header.Size -= unusedBuffer;
ulsTrace.ULSHeader.Size -= unusedBuffer;
}
if (hTraceLog != 0)
NativeMethods.TraceEvent(hTraceLog, ref ulsTrace);
}
public static unsafe void RegisterTraceProvider()
{
SPFarm farm = SPFarm.Local;
Guid traceGuid = farm.TraceSessionGuid;
uint result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPtr.Zero, null, null, out hTraceReg);
System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);
}
public static void UnregisterTraceProvider()
{
uint result = NativeMethods.UnregisterTraceGuids(hTraceReg);
System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);
}
public static uint TagFromString(string wzTag)
{
System.Diagnostics.Debug.Assert(wzTag.Length == 4);
return (uint) (wzTag[0] << 24 | wzTag[1] << 16 | wzTag[2] << 8 | wzTag[3]);
}
static unsafe uint ControlCallback(NativeMethods.WMIDPREQUESTCODE RequestCode, IntPtr Context, uint* InOutBufferSize, IntPtr Buffer)
{
uint Status;
switch (RequestCode)
{
case NativeMethods.WMIDPREQUESTCODE.WMI_ENABLE_EVENTS:
hTraceLog = NativeMethods.GetTraceLoggerHandle(Buffer);
Status = NativeMethods.ERROR_SUCCESS;
break;
case NativeMethods.WMIDPREQUESTCODE.WMI_DISABLE_EVENTS:
hTraceLog = 0;
Status = NativeMethods.ERROR_SUCCESS;
break;
default:
Status = NativeMethods.ERROR_INVALID_PARAMETER;
break;
}
*InOutBufferSize = 0;
return Status;
}
}
```
} |
136,682 | <p>I've got a code like this : </p>
<pre><code>Dim Document As New mshtml.HTMLDocument
Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2)
iDoc.write(html)
iDoc.close()
</code></pre>
<p>However when I load an HTML like this it executes all Javascripts in it as well as doing request to some resources from "html" code.</p>
<p>I want to disable javascript and all other popups (such as certificate error).</p>
<p>My aim is to use DOM from mshtml document to extract some tags from the HTML in a reliable way (instead of bunch of regexes). </p>
<p>Or is there another IE/Office DLL which I can just load an HTML wihtout thinking about IE related popups or active scripts?</p>
| [
{
"answer_id": 139224,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>If you have the 'html' as a string already, and you just want access to the DOM view of it, why \"render\" it to a browser control at all?</p>\n\n<p>I'm not familiar with .Net technology, but there has to be some sort of StringToDOM/StringToJSON type of thing that would better suit your needs.</p>\n\n<p>Likewise, if the 'html' variable you are using above is a URL, then just use wget or similar to retrieve the markup as a string, and parse with an applicable tool.</p>\n\n<p>I'd look for a .Net XML/DOM library and use that. (again, I would figure that this would be part of the language, but I'm not sure)</p>\n\n<p>PS after a quick Google I found this (<a href=\"http://www.van-steenbeek.net/?q=explorer_domparser_parsefromstring\" rel=\"nofollow noreferrer\">source</a>). Not sure if it would help, if you were to use this in your HTMLDocument instead.</p>\n\n<pre><code> if(typeof(DOMParser) == 'undefined') {\n DOMParser = function() {}\n DOMParser.prototype.parseFromString = function(str, contentType) {\n if(typeof(ActiveXObject) != 'undefined') {\n var xmldata = new ActiveXObject('MSXML.DomDocument');\n xmldata.async = false;\n xmldata.loadXML(str);\n return xmldata;\n } else if(typeof(XMLHttpRequest) != 'undefined') {\n var xmldata = new XMLHttpRequest;\n if(!contentType) {\n contentType = 'application/xml';\n }\n xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);\n if(xmldata.overrideMimeType) {\n xmldata.overrideMimeType(contentType);\n }\n xmldata.send(null);\n return xmldata.responseXML;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 193424,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you're screenscraping some resource, then trying to programmatically do something w/ the resulting HTML?</p>\n\n<p>If you know it is valid XHTML ahead of time, then load the XHTML string (which is really XML) into an <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx\" rel=\"nofollow noreferrer\">XmlDocument</a> object, and work with it that way.</p>\n\n<p>Otherwise, if it is potentially invalid, or not properly formed, HTML then you'll need something like <a href=\"http://code.whytheluckystiff.net/hpricot/\" rel=\"nofollow noreferrer\">hpricot</a> (but that is a Ruby library)</p>\n"
},
{
"answer_id": 1031463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Dim Document As New mshtml.HTMLDocument\nDim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2)\n'add this code\niDoc.designMode=\"On\"\niDoc.write(html)iDoc.close()\n</code></pre>\n"
},
{
"answer_id": 1692558,
"author": "Glenn",
"author_id": 81251,
"author_profile": "https://Stackoverflow.com/users/81251",
"pm_score": 0,
"selected": false,
"text": "<p>If I remember correctly MSHTML automatically inherits the settings of IE. </p>\n\n<p>So if you disable javascript in internet explorer for the user that is executing the code then Javascript shouldn't run in MSHTML either.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I've got a code like this :
```
Dim Document As New mshtml.HTMLDocument
Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2)
iDoc.write(html)
iDoc.close()
```
However when I load an HTML like this it executes all Javascripts in it as well as doing request to some resources from "html" code.
I want to disable javascript and all other popups (such as certificate error).
My aim is to use DOM from mshtml document to extract some tags from the HTML in a reliable way (instead of bunch of regexes).
Or is there another IE/Office DLL which I can just load an HTML wihtout thinking about IE related popups or active scripts? | ```
Dim Document As New mshtml.HTMLDocument
Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2)
'add this code
iDoc.designMode="On"
iDoc.write(html)iDoc.close()
``` |
136,696 | <p>I have a Hashtable<Integer, Sport> called sportMap and a list of sportIds (List<Integer> sportIds) from my backing bean. The Sport object has a List<String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport?</p>
<pre><code><h:dataTable value="#{bean.sportIds}" var="_sportId" >
<c:forEach items="#{bean.sportMap[_sportId].equipmentList}" var="_eqp">
<h:outputText value="#{_eqp}"></h:outputText>
<br/>
</c:forEach>
</h:dataTable>
</code></pre>
<p>I get the following exception when trying to run this JSP code.</p>
<pre> 15:57:59,438 ERROR [ExceptionFilter] exception root cause
javax.servlet.ServletException: javax.servlet.jsp.JspTagException:
Don't know how to iterate over supplied "items" in &lt;forEach&gt;</pre>
<p>Here's a print out of my environment</p>
<pre>
Server: JBossWeb/2.0.1.GA
Servlet Specification: 2.5
JSP version: 2.1
JSTL version: 1.2
Java Version: 1.5.0_14
</pre>
<p>Note: The following does work using a JSF tag. It prints out the list of equipment for each sport specified in the list of sportIds. </p>
<pre><code><h:dataTable value="#{bean.sportIds}" var="_sportId" >
<h:outputText value="#{bean.sportMap[_sportId].equipmentList}">
</h:outputText>
</h:dataTable>
</code></pre>
<p>I would like to use the c:forEach tag. Does anyone know if this is possible? If not, anyone have suggestions? In the end I want a stacked list instead of the comma seperated list provided by equipmentList.toString(); (Also, don't want to override toString()).</p>
| [
{
"answer_id": 137188,
"author": "user13229",
"author_id": 13229,
"author_profile": "https://Stackoverflow.com/users/13229",
"pm_score": -1,
"selected": false,
"text": "<p>Two issues: </p>\n\n<ol>\n<li>A dataTable can only have the following children: header facet, footer facet, column. Anything else is not going to be evaluated correctly. </li>\n<li>JSTL tags cannot be interweaved with JSF components. The JSTL tags are evaluated when the component tree is created. JSF components are evaluated when the page is rendered. Thus, the c:forEach tag is only evaluated once - when the component tree is created, which is likely before \"#{bean.sportIds}\" is available. </li>\n</ol>\n\n<p>Either use a JSF component library that provides the looping like you desire, build one that does the looping you desire, or refactor the beans so that instead of looping over the sportIds, loop over a list of sports where each sport has its id and equipment.</p>\n"
},
{
"answer_id": 140587,
"author": "Joe Dean",
"author_id": 5917,
"author_profile": "https://Stackoverflow.com/users/5917",
"pm_score": 3,
"selected": true,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/136696/can-i-use-a-hashtable-in-a-unified-el-expression-on-a-cforeach-tag-using-jsf-12#137188\">keith30xi.myopenid.com</a></p>\n\n<p><strong>Not TRUE in JSF 1.2</strong>. According to the <a href=\"http://wiki.java.net/bin/view/Projects/JavaServerFacesSpecFaq#12coreTags\" rel=\"nofollow noreferrer\">java.net wiki faq</a> they should work together as expected. </p>\n\n<p>Here's an extract from each faq:</p>\n\n<blockquote>\n <p><strong>JSF 1.1 FAQ</strong><br/>\n Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when?</p>\n \n <p>A. The forEach tag does not work with JavaServer Faces technology, version 1.0 and 1.1 tags due to an incompatibility between the strategies used by JSTL and and JavaServer \n Faces technology. Instead, you could use a renderer, such as the Table renderer used by the dataTable tag, that performs its own iteration. The if, choose and when tags work, but the JavaServer Faces tags nested within these tags must have explicit identifiers.</p>\n \n <p><strong><em>This shortcoming has been fixed in JSF 1.2.</em></strong></p>\n \n <p><strong>JSF 1.2 FAQ</strong> <br/>\n Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when?</p>\n \n <p>A. Yes. A new feature of JSP 2.1, called JSP Id Consumer allows these tags to work as expected. </p>\n</blockquote>\n\n<p>Has anyone used JSF tags with JSTL core tags specifically forEach?</p>\n"
},
{
"answer_id": 287013,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem once, and I couldn't find a solution using dataTable.\nThe problem is that the var <strong>_sportId</strong> can be read only by the dataTable component.</p>\n\n<p>If you need to do a loop inside a loop, you can use a dataTable inside a dataTable: </p>\n\n<pre><code><h:dataTable value=\"#{bean.sportIds}\" var=\"_sportId\" > \n <h:dataTable value=\"#{bean.sportMap[_sportId].equipmentList}\" var=\"_eqp\">\n <h:outputText value=\"#{_eqp}\"></h:outputText>\n </h:dataTable>\n</h:dataTable>\n</code></pre>\n\n<p>But in this case each of yours equipmentList items is printed inside a table row. It was not a great solution form me.</p>\n\n<p>I chose to use a normal html table instead of a dataTable:</p>\n\n<pre><code><table>\n <c:forEach items=\"#{bean.sportIds}\" var=\"_sportId\">\n <tr>\n <td>\n <c:forEach items=\"#{bean.sportMap[_sportId].equipmentList\" var=\"_eqp\">\n <h:outputText value=\"#{_eqp} \" />\n </c:forEach>\n </td>\n </tr>\n </c:forEach>\n</table>\n</code></pre>\n\n<p>It works. If you need some specific dataTable functionality like binding and row mapping, you can obtain it in an easy way using the <strong>f:setPropertyActionListener</strong> tag.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917/"
]
| I have a Hashtable<Integer, Sport> called sportMap and a list of sportIds (List<Integer> sportIds) from my backing bean. The Sport object has a List<String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport?
```
<h:dataTable value="#{bean.sportIds}" var="_sportId" >
<c:forEach items="#{bean.sportMap[_sportId].equipmentList}" var="_eqp">
<h:outputText value="#{_eqp}"></h:outputText>
<br/>
</c:forEach>
</h:dataTable>
```
I get the following exception when trying to run this JSP code.
```
15:57:59,438 ERROR [ExceptionFilter] exception root cause
javax.servlet.ServletException: javax.servlet.jsp.JspTagException:
Don't know how to iterate over supplied "items" in <forEach>
```
Here's a print out of my environment
```
Server: JBossWeb/2.0.1.GA
Servlet Specification: 2.5
JSP version: 2.1
JSTL version: 1.2
Java Version: 1.5.0_14
```
Note: The following does work using a JSF tag. It prints out the list of equipment for each sport specified in the list of sportIds.
```
<h:dataTable value="#{bean.sportIds}" var="_sportId" >
<h:outputText value="#{bean.sportMap[_sportId].equipmentList}">
</h:outputText>
</h:dataTable>
```
I would like to use the c:forEach tag. Does anyone know if this is possible? If not, anyone have suggestions? In the end I want a stacked list instead of the comma seperated list provided by equipmentList.toString(); (Also, don't want to override toString()). | @[keith30xi.myopenid.com](https://stackoverflow.com/questions/136696/can-i-use-a-hashtable-in-a-unified-el-expression-on-a-cforeach-tag-using-jsf-12#137188)
**Not TRUE in JSF 1.2**. According to the [java.net wiki faq](http://wiki.java.net/bin/view/Projects/JavaServerFacesSpecFaq#12coreTags) they should work together as expected.
Here's an extract from each faq:
>
> **JSF 1.1 FAQ**
>
> Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when?
>
>
> A. The forEach tag does not work with JavaServer Faces technology, version 1.0 and 1.1 tags due to an incompatibility between the strategies used by JSTL and and JavaServer
> Faces technology. Instead, you could use a renderer, such as the Table renderer used by the dataTable tag, that performs its own iteration. The if, choose and when tags work, but the JavaServer Faces tags nested within these tags must have explicit identifiers.
>
>
> ***This shortcoming has been fixed in JSF 1.2.***
>
>
> **JSF 1.2 FAQ**
>
> Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when?
>
>
> A. Yes. A new feature of JSP 2.1, called JSP Id Consumer allows these tags to work as expected.
>
>
>
Has anyone used JSF tags with JSTL core tags specifically forEach? |
136,703 | <p>I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.</p>
<p>Equivalent of this if you know Cocoa:</p>
<pre><code>NSString *string = [NSString stringWithContentsOfFile:file];
</code></pre>
| [
{
"answer_id": 136710,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>The standard C++ library doesn't provide a function to do this.</p>\n"
},
{
"answer_id": 136743,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<p>Best I can do is 5 lines:</p>\n\n<pre><code>#include <fstream>\n#include <vector>\nusing namespace std;\n\nifstream f(\"filename.txt\");\nf.seekg(0, ios::end);\nvector<char> buffer(f.tellg());\nf.seekg(0, ios::beg);\nf.read(&buffer[0], buffer.size());\n</code></pre>\n"
},
{
"answer_id": 136748,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 4,
"selected": false,
"text": "<p>Its almost possible with an istream_iterator (3 lines!)</p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <string>\n#include <sstream>\n\nusing namespace std;\n\nint main()\n{\n ifstream file(\"filename.txt\");\n string fileContents;\n\n copy(istreambuf_iterator<char>(file),\n istreambuf_iterator<char>(),\n back_inserter(fileContents));\n}\n</code></pre>\n\n<p>Edited - got rid of intermediate string stream, now copies straight into the string, and now using istreambuf_iterator, which ignores whitespace (thanks Martin York for your comment).</p>\n"
},
{
"answer_id": 136883,
"author": "njsf",
"author_id": 4995,
"author_profile": "https://Stackoverflow.com/users/4995",
"pm_score": 2,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>#include <fstream>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nint main( void )\n{\n stringstream os(stringstream::out);\n os << ifstream(\"filename.txt\").rdbuf();\n string s(os.str());\n cout << s << endl;\n}\n</code></pre>\n"
},
{
"answer_id": 137086,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 0,
"selected": false,
"text": "<p>If you do it like the following (but properly wrapped up nicely unlike below), you can read in the file without worrying about a 0x1A byte in the file (for example) cutting the reading of the file short. The previously suggested methods will choke on a 0x1A (for example) in a file.</p>\n\n<pre><code>\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstdlib>\nusing namespace std;\n\nint main() {\n FILE* in = fopen(\"filename.txt\", \"rb\");\n if (in == NULL) {\n return EXIT_FAILURE;\n }\n if (fseek(in, 0, SEEK_END) != 0) {\n fclose(in);\n return EXIT_FAILURE;\n }\n const long filesize = ftell(in);\n if (filesize == -1) {\n fclose(in);\n return EXIT_FAILURE;\n }\n vector<unsigned char> buffer(filesize);\n if (fseek(in, 0, SEEK_SET) != 0 || fread(&buffer[0], sizeof(buffer[0]), buffer.size(), in) != buffer.size() || ferror(in) != 0) {\n fclose(in);\n return EXIT_FAILURE;\n }\n fclose(in);\n}\n</code></pre>\n\n<p>But, yeh, it's not an already-implemented 1-liner though.</p>\n\n<p>Edit: 0x1A wasn't a good example as ios_base::binary will cover that. However, even then C++ streams often give me trouble when reading in png files all at once with .read(). Using the C way works better. Just can't remember a good example to show why. It was probably with .read()ing a binary file in blocks in a loop instead that can be a problem with C++ streams. So, disregard this post.</p>\n"
},
{
"answer_id": 137117,
"author": "Rexxar",
"author_id": 10016,
"author_profile": "https://Stackoverflow.com/users/10016",
"pm_score": 5,
"selected": true,
"text": "<p>We can do it but it's a long line :</p>\n\n<pre><code>#include<fstream>\n#include<iostream>\n#include<iterator>\n#include<string>\n\nusing namespace std;\n\nint main()\n{\n // The one-liner\n string fileContents(istreambuf_iterator<char>(ifstream(\"filename.txt\")), istreambuf_iterator<char>());\n\n // Check result\n cout << fileContents;\n}\n</code></pre>\n\n<p>Edited : use \"istreambuf_iterator\" instead of \"istream_iterator\"</p>\n"
},
{
"answer_id": 3599675,
"author": "Puppy",
"author_id": 298661,
"author_profile": "https://Stackoverflow.com/users/298661",
"pm_score": 0,
"selected": false,
"text": "<pre><code>std::string temp, file; std::ifstream if(filename); while(getline(if, temp)) file += temp;\n</code></pre>\n\n<p>It's not a short or single-statement line, but it is one line and it's really not that bad.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10184/"
]
| I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.
Equivalent of this if you know Cocoa:
```
NSString *string = [NSString stringWithContentsOfFile:file];
``` | We can do it but it's a long line :
```
#include<fstream>
#include<iostream>
#include<iterator>
#include<string>
using namespace std;
int main()
{
// The one-liner
string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>());
// Check result
cout << fileContents;
}
```
Edited : use "istreambuf\_iterator" instead of "istream\_iterator" |
136,727 | <p>From my understanding of the CSS spec, a table above or below a paragraph should collapse vertical margins with it. However, that's not happening here:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
margin: 100px;
border: solid red 2px;
}
p {
margin: 100px
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>
This is a one-celled table with 100px margin all around.
</td>
</tr>
</table>
<p>This is a paragraph with 100px margin all around.</p></code></pre>
</div>
</div>
</p>
<p>I thought there would be 100px between the two elements, but there are 200px -- the margins aren't collapsing. </p>
<p>Why not?</p>
<p><strong>Edit:</strong> It appears to be the table's fault: if I duplicate the table and duplicate the paragraph, the two paragraphs will collapse margins. The two tables won't. And, as noted above, a table won't collapse margins with a paragraph. Is this compliant behaviour?</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
margin: 100px;
border: solid red 2px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>
This is a one-celled table with 100px margin all around.
</td>
</tr>
</table>
<table>
<tr>
<td>
This is a one-celled table with 100px margin all around.
</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
margin: 100px
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This is a paragraph with 100px margin all around.</p>
<p>This is a paragraph with 100px margin all around.</p></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 136774,
"author": "flash",
"author_id": 11539,
"author_profile": "https://Stackoverflow.com/users/11539",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is down to different browser implementations of CSS. I've just tried your code, and Firefox3 doesn't collapse the vertical margin, but IE7 and Safari3.1.2 do.</p>\n"
},
{
"answer_id": 136803,
"author": "hubbardr",
"author_id": 22457,
"author_profile": "https://Stackoverflow.com/users/22457",
"pm_score": -1,
"selected": false,
"text": "<p>My understanding is that the vertical margins only collapse between the table and caption [1]. Otherwise a table should behave as any other block element [2] (ie 2 elements both with 100px margins = 200px between them).</p>\n\n<ol>\n<li><a href=\"http://www.w3.org/TR/CSS2/tables.html#q5\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/tables.html#q5</a></li>\n<li><a href=\"http://www.w3.org/TR/CSS2/box.html\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/box.html</a></li>\n</ol>\n"
},
{
"answer_id": 136816,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>Margin collapsing is only defined for block elements. Try it - add <code>display: block</code> to the table styles, and suddenly it works (and alters the display of the table...)</p>\n<p>Tables are special. In the CSS specs, they're not <em>quite</em> block elements - special rules apply to size and position, both of their children (obviously), and of the <code>table</code> element itself.</p>\n<h3>Relevant specs:</h3>\n<p><a href=\"http://www.w3.org/TR/CSS21/box.html#collapsing-margins\" rel=\"noreferrer\">http://www.w3.org/TR/CSS21/box.html#collapsing-margins</a><br />\n<a href=\"http://www.w3.org/TR/CSS21/visuren.html#block-box\" rel=\"noreferrer\">http://www.w3.org/TR/CSS21/visuren.html#block-box</a></p>\n"
},
{
"answer_id": 136873,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "<p>I originally thought that Firefox 3 isn't honouring <a href=\"http://www.w3.org/TR/CSS21/visuren.html#block-boxes\" rel=\"nofollow noreferrer\">this part of the CSS specification</a>:</p>\n\n<blockquote>\n <p>Several values of the 'display' property make an element block-level: 'block','list-item', and 'run-in' (part of the time; see run-in boxes), and 'table'.</p>\n</blockquote>\n\n<p>I say that because the spec says the following about <a href=\"http://www.w3.org/TR/CSS21/box.html#collapsing-margins\" rel=\"nofollow noreferrer\">collapsing margins</a>...</p>\n\n<blockquote>\n <p>Two or more adjoining vertical margins of block boxes in the normal flow collapse.</p>\n</blockquote>\n\n<p>...and setting the table's style to <code>display: block</code> makes the margin collapse as you'd expect and setting it back to <code>display: table</code> undoes the collapsing again.</p>\n\n<p>But looking at it again, <a href=\"http://www.w3.org/TR/CSS21/visuren.html#block-boxes\" rel=\"nofollow noreferrer\">the spec also says this</a> (emphasis mine):</p>\n\n<blockquote>\n <p>Block-level elements (<strong>except for display 'table' elements</strong>, which are described in a later chapter) generate a principal block box... Principal block boxes participate in a block formatting context.</p>\n</blockquote>\n\n<p>And then, in the <a href=\"http://www.w3.org/TR/CSS21/visuren.html#block-formatting\" rel=\"nofollow noreferrer\">Block Formatting Context</a> section:</p>\n\n<blockquote>\n <p>Vertical margins between adjacent block boxes in a block formatting context collapse. </p>\n</blockquote>\n\n<p>Reading that makes me think it's correct that margins between a table (which doesn't participate in a block formatting context) and a paragraph (which does) shouldn't collapse.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| From my understanding of the CSS spec, a table above or below a paragraph should collapse vertical margins with it. However, that's not happening here:
```css
table {
margin: 100px;
border: solid red 2px;
}
p {
margin: 100px
}
```
```html
<table>
<tr>
<td>
This is a one-celled table with 100px margin all around.
</td>
</tr>
</table>
<p>This is a paragraph with 100px margin all around.</p>
```
I thought there would be 100px between the two elements, but there are 200px -- the margins aren't collapsing.
Why not?
**Edit:** It appears to be the table's fault: if I duplicate the table and duplicate the paragraph, the two paragraphs will collapse margins. The two tables won't. And, as noted above, a table won't collapse margins with a paragraph. Is this compliant behaviour?
```css
table {
margin: 100px;
border: solid red 2px;
}
```
```html
<table>
<tr>
<td>
This is a one-celled table with 100px margin all around.
</td>
</tr>
</table>
<table>
<tr>
<td>
This is a one-celled table with 100px margin all around.
</td>
</tr>
</table>
```
```css
p {
margin: 100px
}
```
```html
<p>This is a paragraph with 100px margin all around.</p>
<p>This is a paragraph with 100px margin all around.</p>
``` | Margin collapsing is only defined for block elements. Try it - add `display: block` to the table styles, and suddenly it works (and alters the display of the table...)
Tables are special. In the CSS specs, they're not *quite* block elements - special rules apply to size and position, both of their children (obviously), and of the `table` element itself.
### Relevant specs:
<http://www.w3.org/TR/CSS21/box.html#collapsing-margins>
<http://www.w3.org/TR/CSS21/visuren.html#block-box> |
136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| [
{
"answer_id": 136759,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.autohotkey.com/\" rel=\"noreferrer\">AutoHotKey</a> is perfect for this kind of tasks (keyboard automation / remapping)</p>\n\n<p>Script to send \"A\" 100 times:</p>\n\n<pre><code>Send {A 100}\n</code></pre>\n\n<p>That's all</p>\n\n<p><strong>EDIT</strong>: to send the keys to an specific application:</p>\n\n<pre><code>WinActivate Word\nSend {A 100}\n</code></pre>\n"
},
{
"answer_id": 136780,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 7,
"selected": true,
"text": "<p>Install the <a href=\"https://github.com/mhammond/pywin32\" rel=\"noreferrer\">pywin32</a> extensions. Then you can do the following:</p>\n\n<pre><code>import win32com.client as comclt\nwsh= comclt.Dispatch(\"WScript.Shell\")\nwsh.AppActivate(\"Notepad\") # select another application\nwsh.SendKeys(\"a\") # send the keys you want\n</code></pre>\n\n<p>Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start <a href=\"http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_pkoy.mspx?mfr=true\" rel=\"noreferrer\">here</a>, perhaps.</p>\n\n<p><strong>EDIT:</strong> Sending F11 </p>\n\n<pre><code>import win32com.client as comctl\nwsh = comctl.Dispatch(\"WScript.Shell\")\n\n# Google Chrome window title\nwsh.AppActivate(\"icanhazip.com\")\nwsh.SendKeys(\"{F11}\")\n</code></pre>\n"
},
{
"answer_id": 136786,
"author": "Martin W",
"author_id": 14199,
"author_profile": "https://Stackoverflow.com/users/14199",
"pm_score": 2,
"selected": false,
"text": "<p>If you're platform is Windows, I wouldn't actually recommend Python. Instead, look into <a href=\"http://www.autohotkey.com/\" rel=\"nofollow noreferrer\">Autohotkey</a>. Trust me, I love Python, but in this circumstance a macro program is the ideal tool for the job. Autohotkey's scripting is only decent (in my opinion), but the ease of simulating input will save you countless hours. Autohotkey scripts can be \"compiled\" as well so you don't need the interpreter to run the script.</p>\n\n<p>Also, if this is for something on the Web, I recommend <a href=\"https://addons.mozilla.org/en-US/firefox/addon/3863\" rel=\"nofollow noreferrer\">iMacros</a>. It's a firefox plugin and therefore has a much better integration with websites. For example, you can say \"write 1000 'a's in this form\" instead of \"simulate a mouseclick at (319,400) and then press 'a' 1000 times\".</p>\n\n<p>For Linux, I unfortunately have not been able to find a good way to easily create keyboard/mouse macros.</p>\n"
},
{
"answer_id": 1282600,
"author": "wearetherock",
"author_id": 103583,
"author_profile": "https://Stackoverflow.com/users/103583",
"pm_score": 2,
"selected": false,
"text": "<p>Alternative way to set prefer window into foreground before send key press event.</p>\n\n<pre><code>hwnd = win32gui.FindWindowEx(0,0,0, \"App title\")\nwin32gui.SetForegroundWindow(hwnd)\n</code></pre>\n"
},
{
"answer_id": 33249229,
"author": "Malachi Bazar",
"author_id": 5231348,
"author_profile": "https://Stackoverflow.com/users/5231348",
"pm_score": 6,
"selected": false,
"text": "<p>You could also use PyAutoGui to send a virtual key presses.</p>\n\n<p>Here's the documentation: <a href=\"https://pyautogui.readthedocs.org/en/latest/\" rel=\"noreferrer\">https://pyautogui.readthedocs.org/en/latest/</a></p>\n\n<pre><code>import pyautogui\n\n\npyautogui.press('Any key combination')\n</code></pre>\n\n<p>You can also send keys like the shift key or enter key with:</p>\n\n<pre><code>import pyautogui\n\npyautogui.press('shift')\n</code></pre>\n\n<p>Pyautogui can also send straight text like so:</p>\n\n<pre><code>import pyautogui\n\npyautogui.typewrite('any text you want to type')\n</code></pre>\n\n<p>As for pressing the \"A\" key 1000 times, it would look something like this:</p>\n\n<pre><code>import pyautogui\n\nfor i in range(999):\n pyautogui.press(\"a\")\n</code></pre>\n\n<p>alt-tab or other tasks that require more than one key to be pressed at the same time:</p>\n\n<pre><code>import pyautogui\n\n# Holds down the alt key\npyautogui.keyDown(\"alt\")\n\n# Presses the tab key once\npyautogui.press(\"tab\")\n\n# Lets go of the alt key\npyautogui.keyUp(\"alt\")\n</code></pre>\n"
},
{
"answer_id": 44757414,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Check This module <a href=\"https://pypi.python.org/pypi/keyboard\" rel=\"noreferrer\"><strong>keyboard</strong></a> with many features.Install it, perhaps with this command: </p>\n\n<pre><code>pip3 install keyboard\n</code></pre>\n\n<p>Then Use this Code: </p>\n\n<pre><code>import keyboard\nkeyboard.write('A',delay=0)\n</code></pre>\n\n<p>If you Want to write 'A' multiple times, Then simply use a loop.<br>\n<strong><em>Note</em>:</strong><br>\n The key 'A' will be pressed for the whole windows.Means the script is running and you went to browser, the script will start writing there.</p>\n"
},
{
"answer_id": 60276594,
"author": "jeppoo1",
"author_id": 11786575,
"author_profile": "https://Stackoverflow.com/users/11786575",
"pm_score": 2,
"selected": false,
"text": "<p>PyAutoGui also lets you press a button multiple times:</p>\n\n<pre><code>pyautogui.press('tab', presses=5) # press TAB five times in a row\n\npyautogui.press('A', presses=1000) # press A a thousand times in a row\n</code></pre>\n"
},
{
"answer_id": 65262817,
"author": "jack chyna",
"author_id": 14739439,
"author_profile": "https://Stackoverflow.com/users/14739439",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import keyboard\n\nkeyboard.press_and_release('anykey')\n</code></pre>\n"
},
{
"answer_id": 66243541,
"author": "user15105779",
"author_id": 15105779,
"author_profile": "https://Stackoverflow.com/users/15105779",
"pm_score": 1,
"selected": false,
"text": "<p>There's a solution:</p>\n<pre><code>import pyautogui\nfor i in range(1000):\n pyautogui.typewrite("a")\n</code></pre>\n"
},
{
"answer_id": 66835510,
"author": "Piyush Pratap",
"author_id": 15496233,
"author_profile": "https://Stackoverflow.com/users/15496233",
"pm_score": 0,
"selected": false,
"text": "<p>You can use pyautogui module which can be used for automatically moving the mouse and for pressing a key. It can also be used for some GUI(very basic).\nYou can do the following :-\nimport pyautogui\npyautogui.press('A') # presses the 'A' key</p>\n<p>If you want to do it 1000 times, then you can use a while loop</p>\n<p>Hope this is helpful :)</p>\n"
},
{
"answer_id": 68592343,
"author": "TheCodeExpert",
"author_id": 16108971,
"author_profile": "https://Stackoverflow.com/users/16108971",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this code that I wrote which will press “a” key 1000 times</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pyautogui \nloop = 1\nwhile loop <= 1000: \n pyautogui.press("a")\n loop += 1\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
| Is it possible to make it appear to a system that a key was pressed, for example I need to make `A` key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.
A better way to put it, I need to emulate a key press, I.E. not capture a key press.
More Info (as requested):
I am running windows XP and need to send the keys to another application. | Install the [pywin32](https://github.com/mhammond/pywin32) extensions. Then you can do the following:
```
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
```
Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start [here](http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_pkoy.mspx?mfr=true), perhaps.
**EDIT:** Sending F11
```
import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")
``` |
136,752 | <p>I have a C++ tool that walks the call stack at one point. In the code, it first gets a copy of the live CPU registers (via RtlCaptureContext()), then uses a few "<code>#ifdef ...</code>" blocks to save the CPU-specific register names into <code>stackframe.AddrPC.Offset</code>, ...<code>AddrStack</code>..., and ...<code>AddrFrame</code>...; also, for each of the 3 <code>Addr</code>... members above, it sets <code>stackframe.Addr</code>...<code>.Mode = AddrModeFlat</code>. (This was borrowed from some example code I came across a while back.)</p>
<p>With an x86 binary, this works great. With an x64 binary, though, StackWalk64() passes back bogus addresses. <i>(The first time the API is called, the only blatantly bogus address value appears in <code>AddrReturn</code> ( == <code>0xFFFFFFFF'FFFFFFFE</code> -- aka StackWalk64()'s 3rd arg, the pseudo-handle returned by GetCurrentThread()). If the API is called a second time, however, all <code>Addr</code>... variables receive bogus addresses.)</i> This happens regardless of how <code>AddrFrame</code> is set:</p>
<ul>
<li>using either of the recommended x64 "base/frame pointer" CPU registers: <code>rbp</code> (= <code>0xf</code>), or <code>rdi</code> (= <code>0x0</code>)</li>
<li>using <code>rsp</code> <i>(didn't expect it to work, but tried it anyway)</i></li>
<li>setting <code>AddrPC</code> and <code>AddrStack</code> normally, but leaving <code>AddrFrame</code> zeroed out <i>(seen in other example code)</i></li>
<li>zeroing out all <code>Addr</code>... values, to let StackWalk64() fill them in from the passed-in CPU-register context <i>(seen in other example code)</i></li>
</ul>
<p>FWIW, the physical stack buffer's contents are also different on x64 vs. x86 (after accounting for different pointer widths & stack buffer locations, of course). Regardless of the reason, StackWalk64() should still be able to walk the call stack correctly -- heck, the debugger is still able to walk the call stack, and it appears to use StackWalk64() itself behind the scenes. The oddity there is that the (correct) call stack reported by the debugger contains base-address & return-address pointer values whose constituent bytes don't actually exist in the stack buffer (below or above the current stack pointer).</p>
<p><i>(FWIW #2: Given the stack-buffer strangeness above, I did try disabling ASLR (<code>/dynamicbase:no</code>) to see if it made a difference, but the binary still exhibited the same behavior.)</i></p>
<p>So. Any ideas why this would work fine on x86, but have problems on x64? Any suggestions on how to fix it?</p>
| [
{
"answer_id": 136942,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 2,
"selected": false,
"text": "<p>Given that fs.sf is a STACKFRAME64 structure, you need to initialize it like this before passing it to StackWalk64: (c is a CONTEXT structure)</p>\n\n<pre><code> DWORD machine = IMAGE_FILE_MACHINE_AMD64;\n RtlCaptureContext (&c);\n fs.sf.AddrPC.Offset = c.Rip;\n fs.sf.AddrFrame.Offset = c.Rsp;\n fs.sf.AddrStack.Offset = c.Rsp;\n fs.sf.AddrPC.Mode = AddrModeFlat;\n fs.sf.AddrFrame.Mode = AddrModeFlat;\n fs.sf.AddrStack.Mode = AddrModeFlat;\n</code></pre>\n\n<p>This code is taken from ACE (Adaptive Communications Environment), adapted from the StackWalker project on CodeProject.</p>\n"
},
{
"answer_id": 159851,
"author": "Quasidart",
"author_id": 19505,
"author_profile": "https://Stackoverflow.com/users/19505",
"pm_score": 1,
"selected": false,
"text": "<p>FWIW, I've switched to using <code>CaptureStackBackTrace()</code>, and now it works just fine.</p>\n"
},
{
"answer_id": 63977654,
"author": "catalin",
"author_id": 3636621,
"author_profile": "https://Stackoverflow.com/users/3636621",
"pm_score": 2,
"selected": false,
"text": "<p><code>SymInitialize(process, nullptr, TRUE)</code> must be called (once) before <code>StackWalk64()</code>.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19505/"
]
| I have a C++ tool that walks the call stack at one point. In the code, it first gets a copy of the live CPU registers (via RtlCaptureContext()), then uses a few "`#ifdef ...`" blocks to save the CPU-specific register names into `stackframe.AddrPC.Offset`, ...`AddrStack`..., and ...`AddrFrame`...; also, for each of the 3 `Addr`... members above, it sets `stackframe.Addr`...`.Mode = AddrModeFlat`. (This was borrowed from some example code I came across a while back.)
With an x86 binary, this works great. With an x64 binary, though, StackWalk64() passes back bogus addresses. *(The first time the API is called, the only blatantly bogus address value appears in `AddrReturn` ( == `0xFFFFFFFF'FFFFFFFE` -- aka StackWalk64()'s 3rd arg, the pseudo-handle returned by GetCurrentThread()). If the API is called a second time, however, all `Addr`... variables receive bogus addresses.)* This happens regardless of how `AddrFrame` is set:
* using either of the recommended x64 "base/frame pointer" CPU registers: `rbp` (= `0xf`), or `rdi` (= `0x0`)
* using `rsp` *(didn't expect it to work, but tried it anyway)*
* setting `AddrPC` and `AddrStack` normally, but leaving `AddrFrame` zeroed out *(seen in other example code)*
* zeroing out all `Addr`... values, to let StackWalk64() fill them in from the passed-in CPU-register context *(seen in other example code)*
FWIW, the physical stack buffer's contents are also different on x64 vs. x86 (after accounting for different pointer widths & stack buffer locations, of course). Regardless of the reason, StackWalk64() should still be able to walk the call stack correctly -- heck, the debugger is still able to walk the call stack, and it appears to use StackWalk64() itself behind the scenes. The oddity there is that the (correct) call stack reported by the debugger contains base-address & return-address pointer values whose constituent bytes don't actually exist in the stack buffer (below or above the current stack pointer).
*(FWIW #2: Given the stack-buffer strangeness above, I did try disabling ASLR (`/dynamicbase:no`) to see if it made a difference, but the binary still exhibited the same behavior.)*
So. Any ideas why this would work fine on x86, but have problems on x64? Any suggestions on how to fix it? | Given that fs.sf is a STACKFRAME64 structure, you need to initialize it like this before passing it to StackWalk64: (c is a CONTEXT structure)
```
DWORD machine = IMAGE_FILE_MACHINE_AMD64;
RtlCaptureContext (&c);
fs.sf.AddrPC.Offset = c.Rip;
fs.sf.AddrFrame.Offset = c.Rsp;
fs.sf.AddrStack.Offset = c.Rsp;
fs.sf.AddrPC.Mode = AddrModeFlat;
fs.sf.AddrFrame.Mode = AddrModeFlat;
fs.sf.AddrStack.Mode = AddrModeFlat;
```
This code is taken from ACE (Adaptive Communications Environment), adapted from the StackWalker project on CodeProject. |
136,771 | <p>How can I drop sql server agent jobs, if (and only if) it exists?</p>
<p>This is a well functioning script for <em>stored procedures</em>. How can I do the same to sql server agent jobs?</p>
<pre><code>if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[storedproc]
GO
CREATE PROCEDURE [dbo].[storedproc] ...
</code></pre>
| [
{
"answer_id": 137159,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 8,
"selected": true,
"text": "<p>Try something like this:</p>\n\n<pre><code>DECLARE @jobId binary(16)\n\nSELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')\nIF (@jobId IS NOT NULL)\nBEGIN\n EXEC msdb.dbo.sp_delete_job @jobId\nEND\n\nDECLARE @ReturnCode int\nEXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job'\n</code></pre>\n\n<p>Best to read the docs on all the parameters required for <a href=\"http://msdn.microsoft.com/en-us/library/ms182079.aspx\" rel=\"noreferrer\">'sp_add_job'</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms188376.aspx\" rel=\"noreferrer\">'sp_delete_job'</a></p>\n"
},
{
"answer_id": 138613,
"author": "Andy Jones",
"author_id": 5096,
"author_profile": "https://Stackoverflow.com/users/5096",
"pm_score": 2,
"selected": false,
"text": "<p>If you generate the SQL script for a job (tested with enterprise manager), it automatically builds the check for existance and drop statements for you. Example below: - </p>\n\n<pre><code>DECLARE @JobID BINARY(16) \nDECLARE @ReturnCode INT \nSELECT @ReturnCode = 0 \n-- Delete the job with the same name (if it exists) \nSELECT @JobID = job_id \nFROM msdb.dbo.sysjobs \nWHERE (name = N'My test job') \nIF (@JobID IS NOT NULL) \nBEGIN \n-- Check if the job is a multi-server job \nIF (EXISTS (SELECT * \nFROM msdb.dbo.sysjobservers \nWHERE (job_id = @JobID) AND (server_id <> 0))) \nBEGIN \n-- There is, so abort the script \nRAISERROR (N'Unable to import job ''My test job'' since there is already a multi-server job with this name.', 16, 1) \nEND \nELSE \n-- Delete the [local] job \nEXECUTE msdb.dbo.sp_delete_job @job_name = N'My test job' \nSELECT @JobID = NULL \nEND \n</code></pre>\n"
},
{
"answer_id": 10598289,
"author": "Seshu",
"author_id": 1395830,
"author_profile": "https://Stackoverflow.com/users/1395830",
"pm_score": 5,
"selected": false,
"text": "<pre><code>IF EXISTS (SELECT job_id \n FROM msdb.dbo.sysjobs_view \n WHERE name = N'Your Job Name')\nEXEC msdb.dbo.sp_delete_job @job_name=N'Your Job Name'\n , @delete_unused_schedule=1\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954/"
]
| How can I drop sql server agent jobs, if (and only if) it exists?
This is a well functioning script for *stored procedures*. How can I do the same to sql server agent jobs?
```
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[storedproc]
GO
CREATE PROCEDURE [dbo].[storedproc] ...
``` | Try something like this:
```
DECLARE @jobId binary(16)
SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')
IF (@jobId IS NOT NULL)
BEGIN
EXEC msdb.dbo.sp_delete_job @jobId
END
DECLARE @ReturnCode int
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job'
```
Best to read the docs on all the parameters required for ['sp\_add\_job'](http://msdn.microsoft.com/en-us/library/ms182079.aspx) and ['sp\_delete\_job'](http://msdn.microsoft.com/en-us/library/ms188376.aspx) |
136,782 | <p>I have a <code>datetime</code> column in MySQL. </p>
<p>How can I convert it to the display as <strong>mm/dd/yy H:M (AM/PM)</strong> using PHP?</p>
| [
{
"answer_id": 136796,
"author": "flash",
"author_id": 11539,
"author_profile": "https://Stackoverflow.com/users/11539",
"pm_score": 4,
"selected": false,
"text": "<p>An easier way would be to format the date directly in the MySQL query, instead of PHP. See the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format\" rel=\"noreferrer\">MySQL manual entry for DATE_FORMAT</a>.</p>\n\n<p>If you'd rather do it in PHP, then you need the <a href=\"http://uk.php.net/date\" rel=\"noreferrer\">date</a> function, but you'll have to convert your database value into a timestamp first.</p>\n"
},
{
"answer_id": 136802,
"author": "Gustavo Carreno",
"author_id": 8167,
"author_profile": "https://Stackoverflow.com/users/8167",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <a href=\"http://www.php.net/date\" rel=\"noreferrer\">date</a> function:</p>\n\n<pre><code><?php\n echo date(\"m/d/y g:i (A)\", $DB_Date_Field);\n?>\n</code></pre>\n"
},
{
"answer_id": 136872,
"author": "Tim Boland",
"author_id": 70,
"author_profile": "https://Stackoverflow.com/users/70",
"pm_score": 8,
"selected": false,
"text": "<p>To convert a date retrieved from MySQL into the format requested (<code>mm/dd/yy H:M (AM/PM)</code>):</p>\n\n<pre><code>// $datetime is something like: 2014-01-31 13:05:59\n$time = strtotime($datetimeFromMysql);\n$myFormatForView = date(\"m/d/y g:i A\", $time);\n// $myFormatForView is something like: 01/31/14 1:05 PM\n</code></pre>\n\n<p>Refer to the <a href=\"http://php.net/manual/en/function.date.php#refsect1-function.date-parameters\" rel=\"noreferrer\">PHP date formatting options</a> to adjust the format.</p>\n"
},
{
"answer_id": 136989,
"author": "phatduckk",
"author_id": 3896,
"author_profile": "https://Stackoverflow.com/users/3896",
"pm_score": 2,
"selected": false,
"text": "<p>You can also have your query return the time as a Unix timestamp. That would get rid of the need to call <code>strtotime()</code> and make things a bit less intensive on the PHP side...</p>\n\n<pre><code>select UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;\n</code></pre>\n\n<p>Then in PHP just use the <code>date()</code> function to format it whichever way you'd like.</p>\n\n<pre><code><?php\n echo date('l jS \\of F Y h:i:s A', $row->unixtime);\n?>\n</code></pre>\n\n<p>or </p>\n\n<pre><code><?php\n echo date('F j, Y, g:i a', $row->unixtime);\n?>\n</code></pre>\n\n<p>I like this approach as opposed to using <a href=\"http://en.wikipedia.org/wiki/MySQL\" rel=\"nofollow noreferrer\">MySQL</a>'s <code>DATE_FORMAT</code> function, because it allows you to reuse the same query to grab the data and allows you to alter the formatting in PHP.</p>\n\n<p>It's annoying to have two different queries just to change the way the date looks in the UI.</p>\n"
},
{
"answer_id": 137780,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 7,
"selected": false,
"text": "<p>If you are using PHP 5, you can also try</p>\n\n<pre><code>$oDate = new DateTime($row->createdate);\n$sDate = $oDate->format(\"Y-m-d H:i:s\");\n</code></pre>\n"
},
{
"answer_id": 1776427,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Using PHP version 4.4.9 & MySQL 5.0, this worked for me:</p>\n\n<pre><code>$oDate = strtotime($row['PubDate']);\n$sDate = date(\"m/d/y\",$oDate);\necho $sDate\n</code></pre>\n\n<p><code>PubDate</code> is the column in <a href=\"http://en.wikipedia.org/wiki/MySQL\" rel=\"nofollow noreferrer\">MySQL</a>.</p>\n"
},
{
"answer_id": 2695713,
"author": "matt.j.crawford",
"author_id": 2384400,
"author_profile": "https://Stackoverflow.com/users/2384400",
"pm_score": 1,
"selected": false,
"text": "<p>You can have trouble with dates not returned in Unix Timestamp, so this works for me...</p>\n\n<pre><code>return date(\"F j, Y g:i a\", strtotime(substr($datestring, 0, 15)))\n</code></pre>\n"
},
{
"answer_id": 5367048,
"author": "kta",
"author_id": 539023,
"author_profile": "https://Stackoverflow.com/users/539023",
"pm_score": 10,
"selected": true,
"text": "<p>If you're looking for a way to normalize a date into MySQL format, use the following</p>\n\n<pre><code>$phpdate = strtotime( $mysqldate );\n$mysqldate = date( 'Y-m-d H:i:s', $phpdate );\n</code></pre>\n\n<p>The line <code>$phpdate = strtotime( $mysqldate )</code> accepts a string and performs a series of heuristics to turn that string into a unix timestamp.</p>\n\n<p>The line <code>$mysqldate = date( 'Y-m-d H:i:s', $phpdate )</code> uses that timestamp and PHP's <a href=\"http://php.net\" rel=\"noreferrer\"><code>date</code></a> function to turn that timestamp back into MySQL's standard date format.</p>\n\n<p>(<strong>Editor Note</strong>: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)</p>\n"
},
{
"answer_id": 8056448,
"author": "riz",
"author_id": 1036374,
"author_profile": "https://Stackoverflow.com/users/1036374",
"pm_score": 3,
"selected": false,
"text": "<p>This should format a field in an SQL query:</p>\n\n<pre><code>SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename\n</code></pre>\n"
},
{
"answer_id": 12421182,
"author": "nixis",
"author_id": 876093,
"author_profile": "https://Stackoverflow.com/users/876093",
"pm_score": 3,
"selected": false,
"text": "<p>Forget all. Just use:</p>\n\n<pre><code>$date = date(\"Y-m-d H:i:s\",strtotime(str_replace('/','-',$date)))\n</code></pre>\n"
},
{
"answer_id": 15158450,
"author": "Tony Stark",
"author_id": 718224,
"author_profile": "https://Stackoverflow.com/users/718224",
"pm_score": 6,
"selected": false,
"text": "<pre><code>$valid_date = date( 'm/d/y g:i A', strtotime($date));\n</code></pre>\n\n<p><strong>Reference:</strong> <a href=\"http://php.net/manual/en/function.date.php\" rel=\"noreferrer\">http://php.net/manual/en/function.date.php</a></p>\n"
},
{
"answer_id": 16862942,
"author": "Greg",
"author_id": 431780,
"author_profile": "https://Stackoverflow.com/users/431780",
"pm_score": 3,
"selected": false,
"text": "<p>To correctly format a <code>DateTime</code> object in PHP for storing in MySQL use the standardised format that MySQL uses, which is <a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO 8601</a>.</p>\n\n<p>PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.</p>\n\n<pre><code>$dtNow = new DateTime();\n$mysqlDateTime = $dtNow->format(DateTime::ISO8601);\n</code></pre>\n\n<p>This, and a list of other PHP DateTime constants are available at <a href=\"http://php.net/manual/en/class.datetime.php#datetime.constants.types\" rel=\"noreferrer\">http://php.net/manual/en/class.datetime.php#datetime.constants.types</a></p>\n"
},
{
"answer_id": 20328996,
"author": "SagarPPanchal",
"author_id": 2351167,
"author_profile": "https://Stackoverflow.com/users/2351167",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$date = \"'\".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date']))).\"'\";\n</code></pre>\n"
},
{
"answer_id": 21317972,
"author": "tfont",
"author_id": 1804013,
"author_profile": "https://Stackoverflow.com/users/1804013",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on your MySQL datetime configuration. Typically: <strong><em>2011-12-31 07:55:13</em></strong> format. This very simple function should do the magic:</p>\n\n<pre><code>function datetime()\n{\n return date( 'Y-m-d H:i:s', time());\n}\n\necho datetime(); // display example: 2011-12-31 07:55:13\n</code></pre>\n\n<p>Or a bit more advance to match the question.</p>\n\n<pre><code>function datetime($date_string = false)\n{\n if (!$date_string)\n {\n $date_string = time();\n }\n return date(\"Y-m-d H:i:s\", strtotime($date_string));\n}\n</code></pre>\n"
},
{
"answer_id": 22343357,
"author": "Mihir Vadalia",
"author_id": 2702490,
"author_profile": "https://Stackoverflow.com/users/2702490",
"pm_score": 1,
"selected": false,
"text": "<p>This will work...</p>\n\n<pre><code>echo date('m/d/y H:i (A)',strtotime($data_from_mysql));\n</code></pre>\n"
},
{
"answer_id": 27713112,
"author": "Hasenpriester",
"author_id": 1021272,
"author_profile": "https://Stackoverflow.com/users/1021272",
"pm_score": 5,
"selected": false,
"text": "<p>Finally the right solution for PHP 5.3 and above:\n<em>(added optional Timezone to the Example like mentioned in the comments)</em></p>\n<p>without time zone:</p>\n<pre><code>$date = \\DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);\necho $date->format('m/d/y h:i a');\n</code></pre>\n<p>with time zone:</p>\n<pre><code>$date = \\DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \\DateTimeZone('UTC'));\n$date->setTimezone(new \\DateTimeZone('Europe/Berlin'));\necho $date->format('m/d/y h:i a');\n</code></pre>\n"
},
{
"answer_id": 31325161,
"author": "Rangel",
"author_id": 4773293,
"author_profile": "https://Stackoverflow.com/users/4773293",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT \n DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,\n DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil\nFROM demo\n</code></pre>\n\n<p>If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.</p>\n\n<p>It is important to name the rows with the <strong>as</strong> operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.</p>\n\n<p>The output of this example will be </p>\n\n<p>[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]</p>\n\n<p>Example: 5.August.2015</p>\n\n<p>Change the dots with the separator of choice and check the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format\" rel=\"noreferrer\">DATE_FORMAT(date,format)</a> function for more date formats.</p>\n"
},
{
"answer_id": 61841551,
"author": "Vadim Samokhin",
"author_id": 618020,
"author_profile": "https://Stackoverflow.com/users/618020",
"pm_score": 0,
"selected": false,
"text": "<p>The approach I suggest works like the following. First, you create a basic datetime object from a mysql-formatted string; and then you format it the way you like. Luckily, mysql datetime is ISO8601-compliant, so the code itself could look quite simple and elegant. Keep in mind though that <code>datetime</code> column doesn't have a timezone information, so <a href=\"https://stackoverflow.com/questions/2505681/timezone-conversion-in-php/61840217#61840217\">you need to convert it appropriately</a>.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>(new ISO8601Formatted(\n new FromISO8601('2038-01-19 11:14:07'),\n 'm/d/Y h:iA'\n))\n ->value();\n</code></pre>\n\n<p>It outputs <code>01/19/2038 11:14AM</code> -- hopefully what you expect.</p>\n\n<p>This example uses meringue library. You can <a href=\"https://meringue.readthedocs.io/en/latest/quick_start.html\" rel=\"nofollow noreferrer\">check out some more of it</a> if you fancy.</p>\n"
},
{
"answer_id": 72448983,
"author": "Alf Müller",
"author_id": 14693464,
"author_profile": "https://Stackoverflow.com/users/14693464",
"pm_score": 0,
"selected": false,
"text": "<p>Direct output e.g. in German format:</p>\n<pre><code> echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70/"
]
| I have a `datetime` column in MySQL.
How can I convert it to the display as **mm/dd/yy H:M (AM/PM)** using PHP? | If you're looking for a way to normalize a date into MySQL format, use the following
```
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
```
The line `$phpdate = strtotime( $mysqldate )` accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line `$mysqldate = date( 'Y-m-d H:i:s', $phpdate )` uses that timestamp and PHP's [`date`](http://php.net) function to turn that timestamp back into MySQL's standard date format.
(**Editor Note**: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists) |
136,789 | <p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow noreferrer">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p>
<p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
| [
{
"answer_id": 136870,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 2,
"selected": false,
"text": "<p>Use bind variables instead of literal values in the sql statements and create a cursor for \neach unique sql statement so that the statement does not need to be reparsed the next time it is used. From the python db api doc:</p>\n\n<blockquote>\n <p>Prepare and execute a database\n operation (query or command). \n Parameters may be provided as sequence\n or mapping and will be bound to\n variables in the operation. Variables\n are specified in a database-specific\n notation (see the module's paramstyle\n attribute for details). [5]</p>\n \n <p>A reference to the operation will be\n retained by the cursor. If the same\n operation object is passed in again,\n then the cursor can optimize its\n behavior. This is most effective for\n algorithms where the same operation is\n used, but different parameters are\n bound to it (many times).</p>\n</blockquote>\n\n<p>ALWAYS ALWAYS ALWAYS use bind variables.</p>\n"
},
{
"answer_id": 137002,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 2,
"selected": false,
"text": "<p>In the for loop, you're inserting into the 'chats' table repeatedly, so you only need a single sql statement with bind variables, to be executed with different values. So you could put this before the for loop:</p>\n\n<pre><code>insert_statement=\"\"\"\n INSERT INTO chats(person_id, message_type, created_at, channel)\n VALUES(:person_id,:message_type,:created_at,:channel)\n\"\"\"\n</code></pre>\n\n<p>Then in place of each sql statement you execute put this in place:</p>\n\n<pre><code>cursor.execute(insert_statement, person_id='person',message_type='msg',created_at=some_date, channel=3)\n</code></pre>\n\n<p>This will make things run faster because:</p>\n\n<ol>\n<li>The cursor object won't have to reparse the statement each time</li>\n<li>The db server won't have to generate a new execution plan as it can use the one it create previously.</li>\n<li>You won't have to call santitize() as special characters in the bind variables won't part of the sql statement that gets executed.</li>\n</ol>\n\n<p>Note: The bind variable syntax I used is Oracle specific. You'll have to check the psycopg2 library's documentation for the exact syntax.</p>\n\n<p>Other optimizations:</p>\n\n<ol>\n<li>You're incrementing with the \"UPDATE people SET chatscount\" after each loop iteration. Keep a dictionary mapping user to chat_count and then execute the statement of the total number you've seen. This will be faster then hitting the db after every record.</li>\n<li>Use bind variables on ALL your queries. Not just the insert statement, I choose that as an example.</li>\n<li>Change all the find_*() functions that do db look ups to cache their results so they don't have to hit the db every time.</li>\n<li>psycho optimizes python programs that perform a large number of numberic operation. The script is IO expensive and not CPU expensive so I wouldn't expect to give you much if any optimization.</li>\n</ol>\n"
},
{
"answer_id": 137076,
"author": "Barry Brown",
"author_id": 17312,
"author_profile": "https://Stackoverflow.com/users/17312",
"pm_score": 2,
"selected": false,
"text": "<p>As Mark suggested, use binding variables. The database only has to prepare each statement once, then \"fill in the blanks\" for each execution. As a nice side effect, it will automatically take care of string-quoting issues (which your program isn't handling).</p>\n\n<p>Turn transactions on (if they aren't already) and do a single commit at the end of the program. The database won't have to write anything to disk until all the data needs to be committed. And if your program encounters an error, none of the rows will be committed, allowing you to simply re-run the program once the problem has been corrected.</p>\n\n<p>Your log_hostname, log_person, and log_date functions are doing needless SELECTs on the tables. Make the appropriate table attributes PRIMARY KEY or UNIQUE. Then, instead of checking for the presence of the key before you INSERT, just do the INSERT. If the person/date/hostname already exists, the INSERT will fail from the constraint violation. (This won't work if you use a transaction with a single commit, as suggested above.)</p>\n\n<p>Alternatively, if you know you're the only one INSERTing into the tables while your program is running, then create parallel data structures in memory and maintain them in memory while you do your INSERTs. For example, read in all the hostnames from the table into an associative array at the start of the program. When want to know whether to do an INSERT, just do an array lookup. If no entry found, do the INSERT and update the array appropriately. (This suggestion is compatible with transactions and a single commit, but requires more programming. It'll be wickedly faster, though.)</p>\n"
},
{
"answer_id": 137096,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 1,
"selected": false,
"text": "<p>Additionally to the many fine suggestions @Mark Roddy has given, do the following:</p>\n\n<ul>\n<li>don't use <code>readlines</code>, you can iterate over file objects</li>\n<li>try to use <code>executemany</code> rather than <code>execute</code>: try to do batch inserts rather single inserts, this tends to be faster because there's less overhead. It also reduces the number of commits</li>\n<li><code>str.rstrip</code> will work just fine instead of stripping of the newline with a regex</li>\n</ul>\n\n<p>Batching the inserts will use more memory temporarily, but that should be fine when you don't read the whole file into memory.</p>\n"
},
{
"answer_id": 137320,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": true,
"text": "<p>Don't waste time profiling. The time is always in the database operations. Do as few as possible. Just the minimum number of inserts.</p>\n\n<p>Three Things.</p>\n\n<p>One. Don't SELECT over and over again to conform the Date, Hostname and Person dimensions. Fetch all the data ONCE into a Python dictionary and use it in memory. Don't do repeated singleton selects. Use Python.</p>\n\n<p>Two. Don't Update.</p>\n\n<p>Specifically, Do not do this. It's bad code for two reasons.</p>\n\n<pre><code>cursor.execute(\"UPDATE people SET chats_count = chats_count + 1 WHERE id = '%s'\" % person_id)\n</code></pre>\n\n<p>It be replaced with a simple SELECT COUNT(*) FROM ... . Never update to increment a count. Just count the rows that are there with a SELECT statement. [If you can't do this with a simple SELECT COUNT or SELECT COUNT(DISTINCT), you're missing some data -- your data model should always provide correct complete counts. Never update.]</p>\n\n<p>And. Never build SQL using string substitution. Completely dumb.</p>\n\n<p>If, for some reason the <code>SELECT COUNT(*)</code> isn't fast enough (benchmark first, before doing anything lame) you can cache the result of the count in another table. AFTER all of the loads. Do a <code>SELECT COUNT(*) FROM whatever GROUP BY whatever</code> and insert this into a table of counts. Don't Update. Ever.</p>\n\n<p>Three. Use Bind Variables. Always.</p>\n\n<pre><code>cursor.execute( \"INSERT INTO ... VALUES( %(x)s, %(y)s, %(z)s )\", {'x':person_id, 'y':time_to_string(time), 'z':channel,} )\n</code></pre>\n\n<p>The SQL never changes. The values bound in change, but the SQL never changes. This is MUCH faster. Never build SQL statements dynamically. Never. </p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15245/"
]
| Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <http://gist.github.com/12978>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)
Is it possible for this to go faster or is that a limitation on the language/database? | Don't waste time profiling. The time is always in the database operations. Do as few as possible. Just the minimum number of inserts.
Three Things.
One. Don't SELECT over and over again to conform the Date, Hostname and Person dimensions. Fetch all the data ONCE into a Python dictionary and use it in memory. Don't do repeated singleton selects. Use Python.
Two. Don't Update.
Specifically, Do not do this. It's bad code for two reasons.
```
cursor.execute("UPDATE people SET chats_count = chats_count + 1 WHERE id = '%s'" % person_id)
```
It be replaced with a simple SELECT COUNT(\*) FROM ... . Never update to increment a count. Just count the rows that are there with a SELECT statement. [If you can't do this with a simple SELECT COUNT or SELECT COUNT(DISTINCT), you're missing some data -- your data model should always provide correct complete counts. Never update.]
And. Never build SQL using string substitution. Completely dumb.
If, for some reason the `SELECT COUNT(*)` isn't fast enough (benchmark first, before doing anything lame) you can cache the result of the count in another table. AFTER all of the loads. Do a `SELECT COUNT(*) FROM whatever GROUP BY whatever` and insert this into a table of counts. Don't Update. Ever.
Three. Use Bind Variables. Always.
```
cursor.execute( "INSERT INTO ... VALUES( %(x)s, %(y)s, %(z)s )", {'x':person_id, 'y':time_to_string(time), 'z':channel,} )
```
The SQL never changes. The values bound in change, but the SQL never changes. This is MUCH faster. Never build SQL statements dynamically. Never. |
136,793 | <p>I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):</p>
<pre><code>people = []
info = 'a' # must fill variable with something, otherwise loop won't execute
while not info.empty?
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end
</code></pre>
<p>This code would look much nicer in a do ... while loop:</p>
<pre><code>people = []
do
info = gets.chomp
people += [Person.new(info)] if not info.empty?
while not info.empty?
</code></pre>
<p>In this code I don't have to assign info to some random string.</p>
<p>Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?</p>
| [
{
"answer_id": 136815,
"author": "hubbardr",
"author_id": 22457,
"author_profile": "https://Stackoverflow.com/users/22457",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n<p>I found the following snippet while reading the source for <code>Tempfile#initialize</code> in the Ruby core library:</p>\n<pre><code>begin\n tmpname = File.join(tmpdir, make_tmpname(basename, n))\n lock = tmpname + '.lock'\n n += 1\nend while @@cleanlist.include?(tmpname) or\n File.exist?(lock) or File.exist?(tmpname)\n</code></pre>\n<p>At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:</p>\n<pre><code>>> begin\n?> puts "do {} while ()" \n>> end while false\ndo {} while ()\n=> nil\n</code></pre>\n<p>As you would expect, the loop will continue to execute while the modifier is true.</p>\n<pre><code>>> n = 3\n=> 3\n>> begin\n?> puts n\n>> n -= 1\n>> end while n > 0\n3\n2\n1\n=> nil\n</code></pre>\n<p>While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:</p>\n<pre><code>def expensive\n @expensive ||= 2 + 2\nend\n</code></pre>\n<p>Here is an ugly, but quick way to memoize something more complex:</p>\n<pre><code>def expensive\n @expensive ||=\n begin\n n = 99\n buf = "" \n begin\n buf << "#{n} bottles of beer on the wall\\n" \n # ...\n n -= 1\n end while n > 0\n buf << "no more bottles of beer" \n end\nend\n</code></pre>\n</blockquote>\n<p><em>Originally written by <a href=\"https://twitter.com/jvoorhis\" rel=\"noreferrer\">Jeremy Voorhis</a>. The content has been copied here because it seems to have been taken down from the originating site. Copies can also be found in the <a href=\"http://web.archive.org/web/20080206125158/http://archive.jvoorhis.com/articles/2007/06/13/ruby-hidden-do-while-loop\" rel=\"noreferrer\">Web Archive</a> and at <a href=\"http://www.artima.com/forums/flat.jsp?forum=123&thread=208036\" rel=\"noreferrer\">Ruby Buzz Forum</a>. -Bill the Lizard</em></p>\n"
},
{
"answer_id": 136825,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 7,
"selected": false,
"text": "<p>Like this:</p>\n\n<pre><code>people = []\n\nbegin\n info = gets.chomp\n people += [Person.new(info)] if not info.empty?\nend while not info.empty?\n</code></pre>\n\n<p>Reference: <a href=\"http://web.archive.org/web/20080206125158/http://archive.jvoorhis.com/articles/2007/06/13/ruby-hidden-do-while-loop\" rel=\"noreferrer\">Ruby's Hidden do {} while () Loop</a></p>\n"
},
{
"answer_id": 136846,
"author": "AndrewR",
"author_id": 2994,
"author_profile": "https://Stackoverflow.com/users/2994",
"pm_score": 5,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>people = []\n\nuntil (info = gets.chomp).empty?\n people += [Person.new(info)]\nend\n</code></pre>\n"
},
{
"answer_id": 2044069,
"author": "is_that_okay",
"author_id": 248294,
"author_profile": "https://Stackoverflow.com/users/248294",
"pm_score": -1,
"selected": false,
"text": "<pre><code>ppl = []\nwhile (input=gets.chomp)\n if !input.empty?\n ppl << input\n else\n p ppl; puts \"Goodbye\"; break\n end\nend\n</code></pre>\n"
},
{
"answer_id": 3310563,
"author": "jvoorhis",
"author_id": 331685,
"author_profile": "https://Stackoverflow.com/users/331685",
"pm_score": 4,
"selected": false,
"text": "<p>Here's the full text article from hubbardr's dead link to my blog.</p>\n\n<p>I found the following snippet while reading the source for <code>Tempfile#initialize</code> in the Ruby core library:</p>\n\n<pre><code>begin\n tmpname = File.join(tmpdir, make_tmpname(basename, n))\n lock = tmpname + '.lock'\n n += 1\nend while @@cleanlist.include?(tmpname) or\n File.exist?(lock) or File.exist?(tmpname)\n</code></pre>\n\n<p>At first glance, I assumed the <code>while</code> modifier would be evaluated before the contents of <code>begin...end</code>, but that is not the case. Observe:</p>\n\n<pre><code>>> begin\n?> puts \"do {} while ()\" \n>> end while false\ndo {} while ()\n=> nil\n</code></pre>\n\n<p>As you would expect, the loop will continue to execute while the modifier is true.</p>\n\n<pre><code>>> n = 3\n=> 3\n>> begin\n?> puts n\n>> n -= 1\n>> end while n > 0\n3\n2\n1\n=> nil\n</code></pre>\n\n<p>While I would be happy to never see this idiom again, <code>begin...end</code> is quite powerful. The following is a common idiom to memoize a one-liner method with no params:</p>\n\n<pre><code>def expensive\n @expensive ||= 2 + 2\nend\n</code></pre>\n\n<p>Here is an ugly, but quick way to memoize something more complex:</p>\n\n<pre><code>def expensive\n @expensive ||=\n begin\n n = 99\n buf = \"\" \n begin\n buf << \"#{n} bottles of beer on the wall\\n\" \n # ...\n n -= 1\n end while n > 0\n buf << \"no more bottles of beer\" \n end\nend\n</code></pre>\n"
},
{
"answer_id": 3410762,
"author": "Paul Gillard",
"author_id": 411392,
"author_profile": "https://Stackoverflow.com/users/411392",
"pm_score": 2,
"selected": false,
"text": "<pre><code>a = 1\nwhile true\n puts a\n a += 1\n break if a > 10\nend\n</code></pre>\n"
},
{
"answer_id": 8079629,
"author": "Moray",
"author_id": 1039759,
"author_profile": "https://Stackoverflow.com/users/1039759",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another one:</p>\n\n<pre><code>people = []\n1.times do\n info = gets.chomp\n unless info.empty? \n people += [Person.new(info)]\n redo\n end\nend\n</code></pre>\n"
},
{
"answer_id": 10713963,
"author": "Siwei",
"author_id": 445908,
"author_profile": "https://Stackoverflow.com/users/445908",
"pm_score": 10,
"selected": true,
"text": "<p><strong>CAUTION</strong>:</p>\n\n<p>The <code>begin <code> end while <condition></code> is rejected by Ruby's author Matz. Instead he suggests using <code>Kernel#loop</code>, e.g.</p>\n\n<pre><code>loop do \n # some code here\n break if <condition>\nend \n</code></pre>\n\n<p>Here's <a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745\" rel=\"noreferrer\">an email exchange</a> in 23 Nov 2005 where Matz states:</p>\n\n<pre><code>|> Don't use it please. I'm regretting this feature, and I'd like to\n|> remove it in the future if it's possible.\n|\n|I'm surprised. What do you regret about it?\n\nBecause it's hard for users to tell\n\n begin <code> end while <cond>\n\nworks differently from\n\n <code> while <cond>\n</code></pre>\n\n<p><a href=\"http://rosettacode.org/wiki/Loops/Do-while#Ruby\" rel=\"noreferrer\">RosettaCode wiki</a> has a similar story:</p>\n\n<blockquote>\n <p>During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.</p>\n</blockquote>\n"
},
{
"answer_id": 14918579,
"author": "Steely Wing",
"author_id": 1877620,
"author_profile": "https://Stackoverflow.com/users/1877620",
"pm_score": 4,
"selected": false,
"text": "<p>This works correctly now:</p>\n\n<pre><code>begin\n # statment\nend until <condition>\n</code></pre>\n\n<p>But, it may be remove in the future, because the <code>begin</code> statement is counterintuitive. See: <a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745\" rel=\"nofollow noreferrer\">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745</a></p>\n\n<p>Matz (Ruby’s Creator) recommended doing it this way:</p>\n\n<pre><code>loop do\n # ...\n break if <condition>\nend\n</code></pre>\n"
},
{
"answer_id": 18495469,
"author": "jds",
"author_id": 2726610,
"author_profile": "https://Stackoverflow.com/users/2726610",
"pm_score": 3,
"selected": false,
"text": "<p>From what I gather, Matz does not like the construct</p>\n\n<pre><code>begin\n <multiple_lines_of_code>\nend while <cond>\n</code></pre>\n\n<p>because, it's semantics is different than</p>\n\n<pre><code><single_line_of_code> while <cond>\n</code></pre>\n\n<p>in that the first construct executes the code first before checking the condition,\nand the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.</p>\n\n<p>I never liked the second construct even for if statements. In all other cases, the computer\nexecutes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right\ntop-to-bottom.</p>\n\n<p>I suggest the following constructs instead:</p>\n\n<pre><code>if <cond> then <one_line_code> # matches case-when-then statement\n\nwhile <cond> then <one_line_code>\n\n<one_line_code> while <cond>\n\nbegin <multiple_line_code> end while <cond> # or something similar but left-to-right\n</code></pre>\n\n<p>I don't know if those suggestions will parse with the rest of the language. But in any case\nI prefere keeping left-to-right execution as well as language consistency.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
]
| I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):
```
people = []
info = 'a' # must fill variable with something, otherwise loop won't execute
while not info.empty?
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end
```
This code would look much nicer in a do ... while loop:
```
people = []
do
info = gets.chomp
people += [Person.new(info)] if not info.empty?
while not info.empty?
```
In this code I don't have to assign info to some random string.
Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this? | **CAUTION**:
The `begin <code> end while <condition>` is rejected by Ruby's author Matz. Instead he suggests using `Kernel#loop`, e.g.
```
loop do
# some code here
break if <condition>
end
```
Here's [an email exchange](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745) in 23 Nov 2005 where Matz states:
```
|> Don't use it please. I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised. What do you regret about it?
Because it's hard for users to tell
begin <code> end while <cond>
works differently from
<code> while <cond>
```
[RosettaCode wiki](http://rosettacode.org/wiki/Loops/Do-while#Ruby) has a similar story:
>
> During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
>
>
> |
136,823 | <p>I am trying to integrate the SSRS report to my web page.
The code is as follows:</p>
<pre><code>ReportViewer1.ProcessingMode = rocessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/reportserver");
ReportViewer1.ServerReport.ReportPath = "/Report Project1/Reconciliation";
List<ReportParameter> paramList = new List<ReportParameter>();
paramList.Add(new ReportParameter("StartDate", startdate.ToString(), false));
paramList.Add(new ReportParameter("EndDate", enddate.ToString(), false));
this.ReportViewer1.ServerReport.SetParameters(paramList);
ReportViewer1.Visible = true;
</code></pre>
<p>I get this error when I try to run this report:</p>
<pre><code>The permissions granted to user 'COMPUTERNAME\\ASPNET' are insufficient for performing this operation. (rsAccessDenied)"}
System.Exception {Microsoft.Reporting.WebForms.ReportServerException}
</code></pre>
<p>Can anyone tell me what I am doing wrong?</p>
| [
{
"answer_id": 136853,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is that your ASP.NET worker process does not have the permissions to do what you want.</p>\n\n<p>Edit this user on the server (MACHINENAME\\ASPNET), and give it more permissions (It may need write permissions etc).</p>\n\n<p>You also will need to add MACHINENAME\\ASPNET as a user to the SQL database SSRS is working with.</p>\n"
},
{
"answer_id": 137079,
"author": "Erikk Ross",
"author_id": 18772,
"author_profile": "https://Stackoverflow.com/users/18772",
"pm_score": 2,
"selected": false,
"text": "<p>You need to give your web app access to your reports. Go to your report manager (<a href=\"http://servername/reports/\" rel=\"nofollow noreferrer\">http://servername/reports/</a>). I usually just give the whole web server \"Browser\" rights to the reports. </p>\n\n<p>The account name of your server is usually Domain\\servername$. So if you server name is \"webserver01\" and your domain is Acme, you would give the account Acme\\servername$ Browser rights. </p>\n\n<p>I think you could also fix it by disabling anonymous access (in IIS) on the web application you are running the report from, that way reporting services would authenticate using the users credentials instead of the ASPNET account. But that may not be a viable solution for you. </p>\n"
},
{
"answer_id": 519661,
"author": "Keith K",
"author_id": 63245,
"author_profile": "https://Stackoverflow.com/users/63245",
"pm_score": 3,
"selected": false,
"text": "<p>To clarify Erikk's answer a little bit. </p>\n\n<p>The particular set of security permissions you want to set to fix this error (there are at least another two types of security settings in Reports Manager) are available in the \"security\" menu option of the \"Properties\" tab of the reports folder you are looking at.</p>\n\n<p>Obiously it goes without saying you should not give full permission to the \"Everyone\" group for the Home folder as this is inherited to all other items and subfolders and open a huge security hole.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
]
| I am trying to integrate the SSRS report to my web page.
The code is as follows:
```
ReportViewer1.ProcessingMode = rocessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/reportserver");
ReportViewer1.ServerReport.ReportPath = "/Report Project1/Reconciliation";
List<ReportParameter> paramList = new List<ReportParameter>();
paramList.Add(new ReportParameter("StartDate", startdate.ToString(), false));
paramList.Add(new ReportParameter("EndDate", enddate.ToString(), false));
this.ReportViewer1.ServerReport.SetParameters(paramList);
ReportViewer1.Visible = true;
```
I get this error when I try to run this report:
```
The permissions granted to user 'COMPUTERNAME\\ASPNET' are insufficient for performing this operation. (rsAccessDenied)"}
System.Exception {Microsoft.Reporting.WebForms.ReportServerException}
```
Can anyone tell me what I am doing wrong? | To clarify Erikk's answer a little bit.
The particular set of security permissions you want to set to fix this error (there are at least another two types of security settings in Reports Manager) are available in the "security" menu option of the "Properties" tab of the reports folder you are looking at.
Obiously it goes without saying you should not give full permission to the "Everyone" group for the Home folder as this is inherited to all other items and subfolders and open a huge security hole. |
136,829 | <p>In VB.NET (or C#) how can I determine programmatically if a public variable in class helper.vb is used anywhere within a project?</p>
| [
{
"answer_id": 136847,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to use reflection and it would be complicated.</p>\n\n<p>Why are you doing this programmaticly? You know that Visual Studio has a \"Find all References\" feature that can do this for you.</p>\n"
},
{
"answer_id": 136857,
"author": "Zee JollyRoger",
"author_id": 11118,
"author_profile": "https://Stackoverflow.com/users/11118",
"pm_score": 2,
"selected": false,
"text": "<p>Find all References is your friend.</p>\n"
},
{
"answer_id": 136866,
"author": "CheeZe5",
"author_id": 22431,
"author_profile": "https://Stackoverflow.com/users/22431",
"pm_score": 0,
"selected": false,
"text": "<p>Reflector has the Analyze feature. Or, is this some sort of run time functionality you are after?</p>\n"
},
{
"answer_id": 137094,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Are you talking about doing this before the code is compiled? Doing this against a compiled assembly would probably not be trivial, though tools like <a href=\"http://www.mono-project.com/Cecil\" rel=\"nofollow noreferrer\">Mono.Cecil</a> could help. You would have to actually walk each method and inspect the IL instructions for calls to the get and set methods of the property in question. It might not actually be that bad though, especially if you used Cecil instead of System.Reflection. Cecil is also much faster, as it treats assemblies as files rather than actually loading them into the application domain.</p>\n\n<p>If you're wanting to run this on the actual source code of a project things are a lot different. I don't know much about Visual Studio Add-Ins, but you might be able to invoke the \"Find all references\" command programmatically and use the results.</p>\n\n<p>There might also be something in System.CodeDom that could help. It looks like you could use a <code>CodeParser</code> to parse the code into a <code>CodeCompileUnit</code>, and then from there walk all of the statements in all of the methods and check for related <code>CodePropertyReferenceExpression</code>s.</p>\n"
},
{
"answer_id": 141954,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 3,
"selected": true,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/aa300858(VS.71).aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n\n<p>The Find object allows you to search for and replace text in places of the environment that support such operations, such as the Code editor. </p>\n\n<p>It is intended primarily for macro recording purposes. The editor's macro recording mechanism uses Find rather than TextSelection.FindPattern so that you can discover the global find functionality, and because it generally is more useful than using the TextSelection Object for such operations as Find-in-files.</p>\n\n<p>If the search operation is asynchronous, such as Find All, then the <strong>FindDone</strong> Event occurs when the operation completes.</p>\n\n<pre><code>Sub ActionExample()\n Dim objFind As Find = objTextDoc.DTE.Find\n\n ' Set the find options.\n objFind.Action = vsFindAction.vsFindActionFindAll\n objFind.Backwards = False\n objFind.FilesOfType = \"*.vb\"\n objFind.FindWhat = \"<Variable>\"\n objFind.KeepModifiedDocumentsOpen = False\n objFind.MatchCase = True\n objFind.MatchInHiddenText = True\n objFind.MatchWholeWord = True\n objFind.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral\n objFind.ResultsLocation = vsFindResultsLocation.vsFindResultsNone\n objFind.SearchPath = \"c:\\<Your>\\<Project>\\<Path>\"\n objFind.SearchSubfolders = False\n objFind.Target = vsFindTarget.vsFindTargetCurrentDocument\n ' Perform the Find operation.\n objFind.Execute()\nEnd Sub\n\n\n\n<System.ContextStaticAttribute()> _\nPublic WithEvents FindEvents As EnvDTE.FindEvents\n\nPublic Sub FindEvents_FindDone(ByVal Result As EnvDTE.vsFindResult, _\n ByVal Cancelled As Boolean) _\n Handles FindEvents.FindDone\n Select Case Result \n case vsFindResultFound\n 'Found!\n case else\n 'Not Found\n Ens select\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22301/"
]
| In VB.NET (or C#) how can I determine programmatically if a public variable in class helper.vb is used anywhere within a project? | From [MSDN](http://msdn.microsoft.com/en-us/library/aa300858(VS.71).aspx)
The Find object allows you to search for and replace text in places of the environment that support such operations, such as the Code editor.
It is intended primarily for macro recording purposes. The editor's macro recording mechanism uses Find rather than TextSelection.FindPattern so that you can discover the global find functionality, and because it generally is more useful than using the TextSelection Object for such operations as Find-in-files.
If the search operation is asynchronous, such as Find All, then the **FindDone** Event occurs when the operation completes.
```
Sub ActionExample()
Dim objFind As Find = objTextDoc.DTE.Find
' Set the find options.
objFind.Action = vsFindAction.vsFindActionFindAll
objFind.Backwards = False
objFind.FilesOfType = "*.vb"
objFind.FindWhat = "<Variable>"
objFind.KeepModifiedDocumentsOpen = False
objFind.MatchCase = True
objFind.MatchInHiddenText = True
objFind.MatchWholeWord = True
objFind.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral
objFind.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
objFind.SearchPath = "c:\<Your>\<Project>\<Path>"
objFind.SearchSubfolders = False
objFind.Target = vsFindTarget.vsFindTargetCurrentDocument
' Perform the Find operation.
objFind.Execute()
End Sub
<System.ContextStaticAttribute()> _
Public WithEvents FindEvents As EnvDTE.FindEvents
Public Sub FindEvents_FindDone(ByVal Result As EnvDTE.vsFindResult, _
ByVal Cancelled As Boolean) _
Handles FindEvents.FindDone
Select Case Result
case vsFindResultFound
'Found!
case else
'Not Found
Ens select
End Sub
``` |
136,836 | <p>What is the slickest way to initialize an array of dynamic size in C# that you know of?</p>
<p>This is the best I could come up with</p>
<pre><code>private bool[] GetPageNumbersToLink(IPagedResult result)
{
if (result.TotalPages <= 9)
return new bool[result.TotalPages + 1].Select(b => true).ToArray();
...
</code></pre>
| [
{
"answer_id": 136890,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Untested, but could you just do this?</p>\n\n<pre><code>return result.Select(p => true).ToArray();\n</code></pre>\n\n<p>Skipping the \"new bool[]\" part?</p>\n"
},
{
"answer_id": 137126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I would actually suggest this:</p>\n\n<pre><code>return Enumerable.Range(0, count).Select(x => true).ToArray();\n</code></pre>\n\n<p>This way you only allocate one array. This is essentially a more concise way to express:</p>\n\n<pre><code>var array = new bool[count];\n\nfor(var i = 0; i < count; i++) {\n array[i] = true;\n}\n\nreturn array;\n</code></pre>\n"
},
{
"answer_id": 137160,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 4,
"selected": false,
"text": "<p><em>EDIT: as a commenter pointed out, my original implementation didn't work. This version works but is rather un-slick being based around a for loop.</em></p>\n\n<p>If you're willing to create an extension method, you could try this</p>\n\n<pre><code>public static T[] SetAllValues<T>(this T[] array, T value) where T : struct\n{\n for (int i = 0; i < array.Length; i++)\n array[i] = value;\n\n return array;\n}\n</code></pre>\n\n<p>and then invoke it like this</p>\n\n<pre><code>bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true);\n</code></pre>\n\n<p>As an alternative, if you're happy with having a class hanging around, you could try something like this</p>\n\n<pre><code>public static class ArrayOf<T>\n{\n public static T[] Create(int size, T initialValue)\n {\n T[] array = (T[])Array.CreateInstance(typeof(T), size);\n for (int i = 0; i < array.Length; i++)\n array[i] = initialValue;\n return array;\n }\n}\n</code></pre>\n\n<p>which you can invoke like</p>\n\n<pre><code>bool[] tenTrueBoolsInAnArray = ArrayOf<bool>.Create(10, true);\n</code></pre>\n\n<p>Not sure which I prefer, although I do lurv extension methods lots and lots in general.</p>\n"
},
{
"answer_id": 137183,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "<p>use <a href=\"http://msdn.microsoft.com/en-us/library/bb348899%28v=vs.110%29.aspx\" rel=\"noreferrer\">Enumerable.Repeat</a></p>\n\n<pre><code>Enumerable.Repeat(true, result.TotalPages + 1).ToArray()\n</code></pre>\n"
},
{
"answer_id": 1051227,
"author": "Nigel Touch",
"author_id": 97846,
"author_profile": "https://Stackoverflow.com/users/97846",
"pm_score": 6,
"selected": false,
"text": "<p>If by 'slickest' you mean fastest, I'm afraid that <strong>Enumerable.Repeat</strong> may be 20x slower than a <strong>for</strong> loop.\nSee <a href=\"http://dotnetperls.com/initialize-array\" rel=\"noreferrer\">http://dotnetperls.com/initialize-array</a>:</p>\n\n<pre><code>Initialize with for loop: 85 ms [much faster]\nInitialize with Enumerable.Repeat: 1645 ms \n</code></pre>\n\n<p>So use Dotnetguy's SetAllValues() method.</p>\n"
},
{
"answer_id": 26277437,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 1,
"selected": false,
"text": "<p>Many times you'd want to initialize different cells with different values:</p>\n\n<pre><code>public static void Init<T>(this T[] arr, Func<int, T> factory)\n{\n for (int i = 0; i < arr.Length; i++)\n {\n arr[i] = factory(i);\n }\n}\n</code></pre>\n\n<p>Or in the factory flavor:</p>\n\n<pre><code>public static T[] GenerateInitializedArray<T>(int size, Func<int, T> factory)\n{\n var arr = new T[size];\n for (int i = 0; i < arr.Length; i++)\n {\n arr[i] = factory(i);\n }\n return arr;\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595/"
]
| What is the slickest way to initialize an array of dynamic size in C# that you know of?
This is the best I could come up with
```
private bool[] GetPageNumbersToLink(IPagedResult result)
{
if (result.TotalPages <= 9)
return new bool[result.TotalPages + 1].Select(b => true).ToArray();
...
``` | use [Enumerable.Repeat](http://msdn.microsoft.com/en-us/library/bb348899%28v=vs.110%29.aspx)
```
Enumerable.Repeat(true, result.TotalPages + 1).ToArray()
``` |
136,837 | <p>A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials.</p>
<p>One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP.</p>
<p>The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent.</p>
<p>Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps?</p>
| [
{
"answer_id": 136862,
"author": "Taptronic",
"author_id": 14728,
"author_profile": "https://Stackoverflow.com/users/14728",
"pm_score": 1,
"selected": false,
"text": "<p>In a highly secure application, you may be required to do such. What you can do is keep a login count incrementing that for the user that logs in and the IP address. The count should never be 2. If it is then you log the other IP out and whomever it is logged into that IP gets thrown out. That wont prevent user-1 from giving his credentials to user-2, it will just make it frustrating for user-1 to do his work if user-2 logs in somewhere else at the same time. </p>\n"
},
{
"answer_id": 136863,
"author": "Enrico Murru",
"author_id": 68336,
"author_profile": "https://Stackoverflow.com/users/68336",
"pm_score": 1,
"selected": false,
"text": "<p>I've never found a standard solution to this problem. In one of my apps I used a combination of Javascript + Java to ensure that a user could be logged only once from a specified IP (actually it was a session ID), but in the worst case of functioning, for a timeout (set to 2 minutes) the account was not available.\nI don't why there is not a common way to do it.</p>\n"
},
{
"answer_id": 136874,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "<p>I've implemented this by maintaining a hashtable of currently logged in users, the key was the username, the value was their last activity time.</p>\n\n<p>When logging in, you just check this hashtable for the key, and if it exists, reject the login.</p>\n\n<p>When the user does anything, you update the hashtable with the time (This is easy if you make it part of the core page framework).</p>\n\n<p>If the time in the hashtable is greater than 20 minutes of inactivity, you remove them. You can do this every time the hashtable is checked, so even if you only had one user, and the tried to login several hours later, during that initial check, it would remove them from the hashtable for being idle.</p>\n\n<p>Some examples in C# (Untested):</p>\n\n<pre><code>public Dictionary<String,DateTime> UserDictionary\n{\n get\n {\n if (HttpContext.Current.Cache[\"UserDictionary\"] != null)\n {\n return HttpContext.Current.Cache[\"UserDictionary\"] as Dictionary<String,DateTime>;\n }\n return new Dictionary<String,DateTime>();\n }\n set\n {\n HttpContext.Current.Cache[\"UserDictionary\"] = value;\n }\n}\n\npublic bool IsUserAlreadyLoggedIn(string userName)\n{\n removeIdleUsers();\n return UserDictionary.ContainsKey(userName);\n}\n\npublic void UpdateUser(string userName)\n{\n UserDictionary[userName] = DateTime.Now;\n\n removeIdleUsers();\n}\n\nprivate void removeIdleUsers()\n{\n for (int i = 0; i < UserDictionary.Length; i++)\n {\n if (user[i].Value < DateTime.Now.AddMinutes(-20))\n user.RemoveAt(i);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 137033,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at just IP can be unreliable. IIRC there are some styles of proxy that farm outgoing requests randomly over multiple IP addresses. Depending on the scope of your application, this may or may not affect you. Other proxies will show heaps of traffic from a single IP.</p>\n\n<p>Last login time can also be an issue. Consider cookie based authentication where the authenticate cookies isn't persistent (a good thing). If the browser crashes or is closed, the user must log back in, but can't until the timeout expires. If the app is for trading stocks, 20 minutes of not working costs money and is probably unacceptable.</p>\n\n<p>Usually smart firewalls / routers can be purchased that do a better job than either you or I can do as a one-off. They also help prevent replay attacks, cookie stealing, etc, and can be configured to run alongside standard mechanisms in your web platform of choice.</p>\n"
},
{
"answer_id": 137286,
"author": "Pete Karl II",
"author_id": 22491,
"author_profile": "https://Stackoverflow.com/users/22491",
"pm_score": 1,
"selected": false,
"text": "<p>I just had this problem.</p>\n\n<p>We were building a Drupal site that contained a Flex app (built by the client), and he wanted the following:</p>\n\n<ol>\n<li>transparent login from Drupal<->Flex (bleh!)</li>\n<li>no concurrent logins!!</li>\n</ol>\n\n<p>He tested the crap out of every solution, and in the end, this is what we did:</p>\n\n<ul>\n<li>We passed along the Session ID through every URL.</li>\n<li>When the user logged-in, we established an timestamp-IP-SessionID-Username footprint</li>\n<li>Every page, the DB was pinged, and if the same user was found at the same IP w/a different SessionID, they older user was booted</li>\n</ul>\n\n<p>This solutions satisfied our client's rigorous testing (2 computers in his house..he kept us up for hours finding little nooks and crannies in the code before we came to this solution)</p>\n"
},
{
"answer_id": 138622,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<p>I would turn the problem around, and allow the last login at the expense of any earlier login, so whenever a user logs on, terminate any other login sessions he may have. </p>\n\n<p>This is much eaiser it implement, and you end up knowing where you are. </p>\n"
},
{
"answer_id": 139042,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 2,
"selected": false,
"text": "<p>Having worked on a 'feature' like this be warned - this is an elephant-trap of edge cases where you end up thinking you have it nailed and then you or someone else says \"but what if someone did X?\" and you realise that you have to add another layer of complexity. </p>\n\n<p>For example:</p>\n\n<ul>\n<li>what if a user opens a new tab with a copy of the session?</li>\n<li>what if the user opens a new browser window?</li>\n<li>what if the user logs in and their browser crashes?</li>\n</ul>\n\n<p>and so on...</p>\n\n<p>Basically there are a range of more or less hacky solutions none of which are foolproof and all of which are going to be hard to maintain. Usually the real aim of the client is some other legitimate security goal such as 'stop users sharing accounts'.</p>\n\n<p>The best idea is to find out what the underlying goal is and find a way of meeting that. And I'm afraid that involves negotiotion diplomacy and other such 'soft skills' rather than embarking on a technical wild goose chase..,</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
| A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials.
One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP.
The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent.
Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps? | I've implemented this by maintaining a hashtable of currently logged in users, the key was the username, the value was their last activity time.
When logging in, you just check this hashtable for the key, and if it exists, reject the login.
When the user does anything, you update the hashtable with the time (This is easy if you make it part of the core page framework).
If the time in the hashtable is greater than 20 minutes of inactivity, you remove them. You can do this every time the hashtable is checked, so even if you only had one user, and the tried to login several hours later, during that initial check, it would remove them from the hashtable for being idle.
Some examples in C# (Untested):
```
public Dictionary<String,DateTime> UserDictionary
{
get
{
if (HttpContext.Current.Cache["UserDictionary"] != null)
{
return HttpContext.Current.Cache["UserDictionary"] as Dictionary<String,DateTime>;
}
return new Dictionary<String,DateTime>();
}
set
{
HttpContext.Current.Cache["UserDictionary"] = value;
}
}
public bool IsUserAlreadyLoggedIn(string userName)
{
removeIdleUsers();
return UserDictionary.ContainsKey(userName);
}
public void UpdateUser(string userName)
{
UserDictionary[userName] = DateTime.Now;
removeIdleUsers();
}
private void removeIdleUsers()
{
for (int i = 0; i < UserDictionary.Length; i++)
{
if (user[i].Value < DateTime.Now.AddMinutes(-20))
user.RemoveAt(i);
}
}
``` |
136,880 | <p>So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions:</p>
<ol>
<li><p>It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change <em>another</em> function somewhere else. Is this something that just gets easier with experience?</p></li>
<li><p>Are the benefits of using const <em>really</em> enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it?</p></li>
</ol>
<p>I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.</p>
| [
{
"answer_id": 136895,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a piece of code with a common error that const correctness can protect you against:</p>\n\n<pre><code>void foo(const int DEFCON)\n{\n if (DEFCON = 1) //< FLAGGED AS COMPILER ERROR! WORLD SAVED!\n {\n fire_missiles();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 136897,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 3,
"selected": false,
"text": "<p>There is a nice article <a href=\"http://duramecho.com/ComputerInformation/WhyHowCppConst.html\" rel=\"noreferrer\">here</a> about const in c++. Its a pretty straight forward opinion but hope it helps some.</p>\n"
},
{
"answer_id": 136900,
"author": "Antonio Haley",
"author_id": 390,
"author_profile": "https://Stackoverflow.com/users/390",
"pm_score": 5,
"selected": false,
"text": "<p>It's not for you when you are writing the code initially. It's for someone else (or you a few months later) who is looking at the method declaration inside the class or interface to see what it does. Not modifying an object is a significant piece of information to glean from that.</p>\n"
},
{
"answer_id": 136917,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 8,
"selected": true,
"text": "<p>This is the definitive article on \"const correctness\": <a href=\"https://isocpp.org/wiki/faq/const-correctness\" rel=\"noreferrer\">https://isocpp.org/wiki/faq/const-correctness</a>.</p>\n\n<p>In a nutshell, using const is good practice because...</p>\n\n<ol>\n<li>It protects you from accidentally changing variables that aren't intended be changed, </li>\n<li>It protects you from making accidental variable assignments, and </li>\n<li><p>The compiler can optimize it. For instance, you are protected from</p>\n\n<pre><code>if( x = y ) // whoops, meant if( x == y )\n</code></pre></li>\n</ol>\n\n<p>At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good.</p>\n\n<p>You are correct in that it can be difficult to use const-correctness consistently, but the end code is more concise and safer to program with. When you do a lot of C++ development, the benefits of this quickly manifest.</p>\n"
},
{
"answer_id": 136938,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p><code>const</code> helps you isolate code that \"change things\" behind your back. So, in a class, you'd mark all methods that don't change the state of the object as <code>const</code>. This means that <code>const</code> instances of that class will no longer be able to call any non-<code>const</code> methods. This way, you're prevented from accidentally calling functionality that can change your object.</p>\n\n<p>Also, <code>const</code> is part of the overload mechanism, so you can have two methods with identical signatures, but one with <code>const</code> and one without. The one with <code>const</code> is called for <code>const</code> references, and the other one is called for non-<code>const</code> references.</p>\n\n<p>Example:</p>\n\n<pre><code>#include <iostream>\n\nclass HelloWorld {\n bool hw_called;\n\npublic:\n HelloWorld() : hw_called(false) {}\n\n void hw() const {\n std::cout << \"Hello, world! (const)\\n\";\n // hw_called = true; <-- not allowed\n }\n\n void hw() {\n std::cout << \"Hello, world! (non-const)\\n\";\n hw_called = true;\n }\n};\n\nint\nmain()\n{\n HelloWorld hw;\n HelloWorld* phw1(&hw);\n HelloWorld const* phw2(&hw);\n\n hw.hw(); // calls non-const version\n phw1->hw(); // calls non-const version\n phw2->hw(); // calls const version\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 137008,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>I like const correctness ... in theory. By every time I have tried to apply it rigourously in practice it has broken down eventually and const_cast starts to creep in making the code ugly.</p>\n\n<p>Maybe it is just the design patterns I use, but const always ends up being too broad a brush.</p>\n\n<p>For example, imagine a simple database engine ... it has schema objects, tables, fields etc. A user may have a 'const Table' pointer meaning that they are not allowed to modify the table schema itself ... but what about manipulating the data associated with the table? If the Insert() method is marked const then internally it has to cast the const-ness away to actually manipulate the database. If it isn't marked const then it doesn't protect against calling the AddField method.</p>\n\n<p>Maybe the answer is to split the class up based on the const-ness requirements, but that tends to complicate the design more than I would like for the benefit it brings.</p>\n"
},
{
"answer_id": 137026,
"author": "Wesley Tarle",
"author_id": 17057,
"author_profile": "https://Stackoverflow.com/users/17057",
"pm_score": 2,
"selected": false,
"text": "<p>When you use the \"const\" keyword, you're specifying another interface to your classes. There is an interface that includes all methods, and an interface that includes only the const methods. Obviously this lets you restrict access to some things that you don't want changed.</p>\n\n<p>Yes, it does get easier with time.</p>\n"
},
{
"answer_id": 137071,
"author": "Chris Mayer",
"author_id": 4121,
"author_profile": "https://Stackoverflow.com/users/4121",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>It seems like every time I mark\n something as const, I get an error and\n have to change some other function\n somewhere to be const too. Then this\n causes me to have to change another\n function somewhere else. Is this\n something that just gets easier with\n experience?</p>\n</blockquote>\n\n<p>From experience, this is a total myth. It happens when non const-correct sits with const-correct code, sure. If you design const-correct from the start, this should NEVER be an issue. If you make something const, and then something else doesn't complile, the compiler is telling you something extremely important, and you should take the time to fix it <strong>properly</strong>.</p>\n"
},
{
"answer_id": 137179,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 5,
"selected": false,
"text": "<p>My philosophy is that if you're going to use a nit-picky language with compile time checks than make the best use of it you can. <code>const</code> is a compiler enforced way of communicating what you <strong><em>mean</em></strong>... it's better than comments or doxygen will ever be. You're paying the price, why not derive the value?</p>\n"
},
{
"answer_id": 137396,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 5,
"selected": false,
"text": "<p>const is a promise your are making as a developer, and enlisting the compiler's help in enforcing.</p>\n\n<p>My reasons for being const-correct:</p>\n\n<ul>\n<li>It communicates to clients of your function that your will not change the variable or object</li>\n<li>Accepting arguments by const reference gives you the efficiency of passing by reference with the safety of passing by value.</li>\n<li>Writing your interfaces as const correct will enable clients to use them. If you write your interface to take in non-const references, clients who are using const will need to cast constness away in order to work with you. This is especially annoying if your interface accepts non-const char*'s, and your clients are using std::strings, since you can only get a const char* from them.</li>\n<li>Using const will enlist the compiler in keeping you honest so you don't mistakenly change something that shouldn't change.</li>\n</ul>\n"
},
{
"answer_id": 137599,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": false,
"text": "<p>For embedded programming, using <code>const</code> judiciously when declaring global data structures can save a lot of RAM by causing the constant data to be located in ROM or flash without copying to RAM at boot time.</p>\n\n<p>In everyday programming, using <code>const</code> carefully helps you avoid writing programs that crash or behave unpredictably because they attempt to modify string literals and other constant global data.</p>\n\n<p>When working with other programmers on large projects, using <code>const</code> properly helps prevent the other programmers from throttling you.</p>\n"
},
{
"answer_id": 137654,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": false,
"text": "<p>Say you have a variable in Python. You know you aren't <em>supposed</em> to modify it. What if you accidentally do?</p>\n\n<p>C++ gives you a way to protect yourself from accidentally doing something you weren't supposed to be able to do in the first place. Technically you can get around it anyways, but you have to put in extra work to shoot yourself.</p>\n"
},
{
"answer_id": 137710,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 1,
"selected": false,
"text": "<p>You can give the compiler hints with const as well....as per the following code</p>\n\n<pre><code>#include <string>\n\nvoid f(const std::string& s)\n{\n\n}\nvoid x( std::string& x)\n{\n}\nvoid main()\n{\n f(\"blah\");\n x(\"blah\"); // won't compile...\n}\n</code></pre>\n"
},
{
"answer_id": 138221,
"author": "andreas buykx",
"author_id": 19863,
"author_profile": "https://Stackoverflow.com/users/19863",
"pm_score": 5,
"selected": false,
"text": "<p>Programming C++ without const is like driving without the safety belt on. </p>\n\n<p>It's a pain to put the safety belt on each time you step in the car, and 364 out of 365 days you'll arrive safely. </p>\n\n<p>The only difference is that when you get in trouble with your car you'll feel it immediately, whereas with programming without const you may have to search for two weeks what caused that crash only to find out that you inadvertently messed up a function argument that you passed by non-const reference for efficiency.</p>\n"
},
{
"answer_id": 142551,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 5,
"selected": false,
"text": "<p>If you use const rigorously, you'd be surprised how few real variables there are in most functions. Often no more than a loop counter. If your code is reaching that point, you get a warm feeling inside...validation by compilation...the realm of functional programming is nearby...you can almost touch it now...</p>\n"
},
{
"answer_id": 1871286,
"author": "Peter Kovacs",
"author_id": 81214,
"author_profile": "https://Stackoverflow.com/users/81214",
"pm_score": 4,
"selected": false,
"text": "<p>const correctness is one of those things that really needs to be in place from the beginning. As you've found, its a big pain to add it on later, especially when there is a lot of dependency between the new functions you are adding and old non-const-correct functions that already exist.</p>\n\n<p>In a lot of the code that I write, its really been worth the effort because we tend to use composition a lot:</p>\n\n<pre><code>class A { ... }\nclass B { A m_a; const A& getA() const { return m_a; } };\n</code></pre>\n\n<p>If we did not have const-correctness, then you would have to resort to returning complex objects by value in order to assure yourself that nobody was manipulating class B's internal state behind your back.</p>\n\n<p>In short, const-correctness is a defensive programming mechanism to save yourself from pain down the road.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
| So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions:
1. It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change *another* function somewhere else. Is this something that just gets easier with experience?
2. Are the benefits of using const *really* enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it?
I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications. | This is the definitive article on "const correctness": <https://isocpp.org/wiki/faq/const-correctness>.
In a nutshell, using const is good practice because...
1. It protects you from accidentally changing variables that aren't intended be changed,
2. It protects you from making accidental variable assignments, and
3. The compiler can optimize it. For instance, you are protected from
```
if( x = y ) // whoops, meant if( x == y )
```
At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good.
You are correct in that it can be difficult to use const-correctness consistently, but the end code is more concise and safer to program with. When you do a lot of C++ development, the benefits of this quickly manifest. |
136,884 | <p>Is it possible to have a <code><div></code> simultaneously (1) not take up all available width and (2) collapse margins with its neighbors?</p>
<p>I learned recently that setting a <code>div</code> to <code>display:table</code> will stop it from expanding to take up the whole width of the parent container -- but now I realize that this introduces a new problem: it stops collapsing margins with its neighbors.</p>
<p>In the example below, the red div fails to collapse, and the blue div is too wide.</p>
<pre><code><p style="margin:100px">This is a paragraph with 100px margin all around.</p>
<div style="margin: 100px; border: solid red 2px; display: table;">
This is a div with 100px margin all around and display:table.
<br/>
The problem is that it doesn't collapse margins with its neighbors.
</div>
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
<div style="margin: 100px; border: solid blue 2px; display: block;">
This is a div with 100px margin all around and display:block.
<br/>
The problem is that it expands to take up all available width.
</div>
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
</code></pre>
<p>Is there a way to meet both criteria simultaneously?</p>
| [
{
"answer_id": 136921,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": true,
"text": "<p>You could wrap the <code>display: table</code> <code>div</code> with another <code>div</code> and put the margin on the wrapper <code>div</code> instead. Nasty, but it works.</p>\n\n<pre><code><p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n\n<div style=\"margin: 100px\"><div style=\"border: solid red 2px; display: table;\">\n This is a div which had 100px margin all around and display:table, but the margin was moved to a wrapper div.\n <br/>\n The problem was that it didn't collapse margins with its neighbors.\n</div></div>\n\n<p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n\n<div style=\"margin: 100px; border: solid blue 2px; display: block;\">\n This is a div with 100px margin all around and display:block.\n <br/>\n The problem is that it expands to take up all available width.\n</div>\n\n<p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n</code></pre>\n"
},
{
"answer_id": 137397,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably just float the div (so that it doesn't take up available width) and then clear the float subsequently if necessary. </p>\n\n<pre><code><p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n\n<div style=\"border: solid red 2px; float: left;\">\n This should work.\n</div>\n\n<p style=\"margin:100px;clear:both;\">This is a paragraph with 100px margin all around.</p>\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| Is it possible to have a `<div>` simultaneously (1) not take up all available width and (2) collapse margins with its neighbors?
I learned recently that setting a `div` to `display:table` will stop it from expanding to take up the whole width of the parent container -- but now I realize that this introduces a new problem: it stops collapsing margins with its neighbors.
In the example below, the red div fails to collapse, and the blue div is too wide.
```
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
<div style="margin: 100px; border: solid red 2px; display: table;">
This is a div with 100px margin all around and display:table.
<br/>
The problem is that it doesn't collapse margins with its neighbors.
</div>
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
<div style="margin: 100px; border: solid blue 2px; display: block;">
This is a div with 100px margin all around and display:block.
<br/>
The problem is that it expands to take up all available width.
</div>
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
```
Is there a way to meet both criteria simultaneously? | You could wrap the `display: table` `div` with another `div` and put the margin on the wrapper `div` instead. Nasty, but it works.
```
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
<div style="margin: 100px"><div style="border: solid red 2px; display: table;">
This is a div which had 100px margin all around and display:table, but the margin was moved to a wrapper div.
<br/>
The problem was that it didn't collapse margins with its neighbors.
</div></div>
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
<div style="margin: 100px; border: solid blue 2px; display: block;">
This is a div with 100px margin all around and display:block.
<br/>
The problem is that it expands to take up all available width.
</div>
<p style="margin:100px">This is a paragraph with 100px margin all around.</p>
``` |
136,899 | <p>In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?</p>
<p>If so, in what circumstances would you use this?</p>
<p>Code examples are welcome.</p>
<p>Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use</p>
<pre><code>@fopen($file);
</code></pre>
<p>and then check afterwards... but you can get rid of the @ by doing</p>
<pre><code>if (file_exists($file))
{
fopen($file);
}
else
{
die('File not found');
}
</code></pre>
<p>or similar. </p>
<p>I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?</p>
| [
{
"answer_id": 136912,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 5,
"selected": false,
"text": "<p>Yes suppression makes sense.</p>\n\n<p>For example, the <code>fopen()</code> command returns <code>FALSE</code> if the file cannot be opened. That's fine, but it <em>also</em> produces a PHP warning message. Often you don't want the warning -- you'll check for <code>FALSE</code> yourself.</p>\n\n<p>In fact the <a href=\"http://us3.php.net/function.fopen\" rel=\"noreferrer\">PHP manual</a> specifically suggests using @ in this case!</p>\n"
},
{
"answer_id": 136941,
"author": "Enrico Murru",
"author_id": 68336,
"author_profile": "https://Stackoverflow.com/users/68336",
"pm_score": 2,
"selected": false,
"text": "<p>is there not a way to suppress from the php.ini warnings and errors? in that case you can debug only changing a flag and not trying to discovering which @ is hiding the problem.</p>\n"
},
{
"answer_id": 136955,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 1,
"selected": false,
"text": "<p>You do not want to suppress everything, since it slows down your script.</p>\n\n<p>And yes there is a way both in php.ini and within your script to remove errors (but only do this when you are in a live environment and log your errors from php)</p>\n\n<pre><code><?php\n error_reporting(0);\n?>\n</code></pre>\n\n<p>And you can read <a href=\"http://is2.php.net/manual/en/errorfunc.configuration.php#ini.display-errors\" rel=\"nofollow noreferrer\">this</a> for the php.ini version of turning it off.</p>\n"
},
{
"answer_id": 136968,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<p>Error suppression should be avoided unless you <em>know</em> you can handle all the conditions. </p>\n\n<p>This may be much harder than it looks at first. </p>\n\n<p>What you really should do is rely on php's \"error_log\" to be your reporting method, as you cannot rely on users viewing pages to report errors. ( And you should also disable php from displaying these errors ) </p>\n\n<p>Then at least you'll have a comprehensive report of all things going wrong in the system. </p>\n\n<p>If you really must handle the errors, you can create a custom error handler </p>\n\n<p><a href=\"http://php.net/set-error-handler\" rel=\"noreferrer\">http://php.net/set-error-handler</a></p>\n\n<p>Then you could possibly send exceptions ( which can be handled ) and do anything needed to report weird errors to administration. </p>\n"
},
{
"answer_id": 136973,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": -1,
"selected": false,
"text": "<p>I use it when trying to load an HTML file for processing as a DOMDocument object. If there are any problems in the HTML... and what website doesn't have <em>at least one</em>... DOMDocument->loadHTMLFile() will throw an error if you don't suppress it with @. This is the only way (perhaps there are better ones) I've ever been successful in creating HTML scrapers in PHP.</p>\n"
},
{
"answer_id": 137013,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": 2,
"selected": false,
"text": "<p>Using @ is sometimes counter productive. In my experience, you should always turn error reporting off in the php.ini or call</p>\n\n<pre><code>error_reporting(0);\n</code></pre>\n\n<p>on a production site. This way when you are in development you can just comment out the line and keep errors visible for debugging. </p>\n"
},
{
"answer_id": 137244,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 2,
"selected": false,
"text": "<p>One place I use it is in socket code, for example, if you have a timeout set you'll get a warning on this if you don't include @, even though it's valid to not get a packet.</p>\n\n<pre><code>$data_len = @socket_recvfrom( $sock, $buffer, 512, 0, $remote_host, $remote_port )\n</code></pre>\n"
},
{
"answer_id": 137728,
"author": "dirtside",
"author_id": 20903,
"author_profile": "https://Stackoverflow.com/users/20903",
"pm_score": 4,
"selected": false,
"text": "<p>If you don't want a warning thrown when using functions like fopen(), you can suppress the error but use exceptions:</p>\n\n<pre><code>try {\n if (($fp = @fopen($filename, \"r\")) == false) {\n throw new Exception;\n } else {\n do_file_stuff();\n }\n} catch (Exception $e) {\n handle_exception();\n}\n</code></pre>\n"
},
{
"answer_id": 138110,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 6,
"selected": true,
"text": "<p>I would suppress the error <strong>and handle it</strong>. Otherwise you may have a <strong>TOCTOU</strong> issue (Time-of-check, time-of-use. For example a file may get deleted after file_exists returns true, but before fopen).</p>\n\n<p>But I wouldn't just suppress errors to make them go away. These better be visible.</p>\n"
},
{
"answer_id": 960288,
"author": "Gerry",
"author_id": 109561,
"author_profile": "https://Stackoverflow.com/users/109561",
"pm_score": 7,
"selected": false,
"text": "<p>Note: Firstly, I realise 99% of PHP developers use the error suppression operator (I used to be one of them), so I'm expecting any PHP dev who sees this to disagree.</p>\n\n<blockquote>\n <p>In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?</p>\n</blockquote>\n\n<p><strong>Short answer:</strong><br>\nNo!</p>\n\n<p><strong>Longer more correct answer:</strong><br>\nI don't know as I don't know everything, but so far I haven't come across a situation where it was a good solution.</p>\n\n<p><strong>Why it's bad:</strong><br>\nIn what I think is about 7 years using PHP now I've seen endless debugging agony caused by the error suppression operator and have never come across a situation where it was unavoidable.</p>\n\n<p>The problem is that the piece of code you are suppressing errors for, may currently only cause the error you are seeing; however when you change the code which the suppressed line relies on, or the environment in which it runs, then there is every chance that the line will attempt to output a completely different error from the one you were trying to ignore. Then how do you track down an error that isn't outputting? Welcome to debugging hell!</p>\n\n<p>It took me many years to realise how much time I was wasting every couple of months because of suppressed errors. Most often (but not exclusively) this was after installing a third party script/app/library which was error free in the developers environment, but not mine because of a php or server configuration difference or missing dependency which would have normally output an error immediately alerting to what the issue was, but not when the dev adds the magic @.</p>\n\n<p><strong>The alternatives (depending on situation and desired result):</strong><br>\nHandle the actual error that you are aware of, so that if a piece of code is going to cause a certain error then it isn't run in that particular situation. But I think you get this part and you were just worried about end users seeing errors, which is what I will now address.</p>\n\n<p>For regular errors you can set up an error handler so that they are output in the way you wish when it's you viewing the page, but hidden from end users and logged so that you know what errors your users are triggering.</p>\n\n<p>For fatal errors set <code>display_errors</code> to off (your error handler still gets triggered) in your php.ini and enable error logging. If you have a development server as well as a live server (which I recommend) then this step isn't necessary on your development server, so you can still debug these fatal errors without having to resort to looking at the error log file. There's even a <a href=\"http://www.php.net/manual/en/function.set-error-handler.php#88401\" rel=\"noreferrer\">trick using the shutdown function</a> to send a great deal of fatal errors to your error handler.</p>\n\n<p><strong>In summary:</strong><br>\nPlease avoid it. There may be a good reason for it, but I'm yet to see one, so until that day it's my opinion that the (@) Error suppression operator is evil.</p>\n\n<p>You can read <a href=\"http://php.net/operators.errorcontrol#90987\" rel=\"noreferrer\">my comment on the Error Control Operators page</a> in the PHP manual if you want more info.</p>\n"
},
{
"answer_id": 1133973,
"author": "ashnazg",
"author_id": 108146,
"author_profile": "https://Stackoverflow.com/users/108146",
"pm_score": 3,
"selected": false,
"text": "<p>I NEVER allow myself to use '@'... period.</p>\n\n<p>When I discover usage of '@' in code, I add comments to make it glaringly apparent, both at the point of usage, and in the docblock around the function where it is used. I too have been bitten by \"chasing a ghost\" debugging due to this kind of error suppression, and I hope to make it easier on the next person by highlighting its usage when I find it.</p>\n\n<p>In cases where I'm wanting my own code to throw an Exception if a native PHP function encounters an error, and '@' seems to be the easy way to go, I instead choose to do something else that gets the same result but is (again) glaringly apparent in the code:</p>\n\n<pre><code>$orig = error_reporting(); // capture original error level\nerror_reporting(0); // suppress all errors\n$result = native_func(); // native_func() is expected to return FALSE when it errors\nerror_reporting($orig); // restore error reporting to its original level\nif (false === $result) { throw new Exception('native_func() failed'); }\n</code></pre>\n\n<p>That's a lot more code that just writing:</p>\n\n<pre><code>$result = @native_func();\n</code></pre>\n\n<p>but I prefer to make my suppression need VERY OBVIOUS, for the sake of the poor debugging soul that follows me.</p>\n"
},
{
"answer_id": 1156660,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 2,
"selected": false,
"text": "<p>The only place where I really needed to use it is the eval function. The problem with eval is that, when string cannot be parsed due to syntax error, eval does not return false, but rather throws an error, just like having a parse error in the regular script. In order to check whether the script stored in the string is parseable you can use something like:</p>\n\n<pre><code>$script_ok = @eval('return true; '.$script);\n</code></pre>\n\n<p>AFAIK, this is the most elegant way to do this.</p>\n"
},
{
"answer_id": 2272401,
"author": "Sumesh",
"author_id": 274301,
"author_profile": "https://Stackoverflow.com/users/274301",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a custom error handling function and wanna suppress an error (probably a known error), use this method. The use of '@' is not a good idea in this context as it will not suppress error if error handler is set.</p>\n\n<p>Write 3 functions and call like this. </p>\n\n<pre><code># supress error for this statement\nsupress_error_start(); \n$mail_sent = mail($EmailTo, $Subject, $message,$headers);\nsupress_error_end(); #Don't forgot to call this to restore error. \n\nfunction supress_error_start(){\n set_error_handler('nothing');\n error_reporting(0);\n}\n\nfunction supress_error_end(){\n set_error_handler('my_err_handler');\n error_reporting('Set this to a value of your choice');\n}\n\nfunction nothing(){ #Empty function\n}\n\nfunction my_err_handler('arguments will come here'){\n //Your own error handling routines will come here\n}\n</code></pre>\n"
},
{
"answer_id": 3870560,
"author": "Your Common Sense",
"author_id": 285587,
"author_profile": "https://Stackoverflow.com/users/285587",
"pm_score": 3,
"selected": false,
"text": "<p>Most people do not understand the meaning of error message.<br>\nNo kidding. Most of them.</p>\n\n<p>They think that error messages are all the same, says \"Something goes wrong!\"<br>\nThey don't bother to read it.<br>\nWhile it's most important part of error message - not just the fact it has been raised, but it's meaning. It can tell you <em>what</em> is going wrong. Error messages are for help, not for bothering you with \"how to hide it?\" problem. That's one of the biggest misunderstandings in the newbie web-programming world. </p>\n\n<p>Thus, instead of gagging error message, one should <em>read</em> what it says. It has not only one \"file not found\" value. There can be thousands different errors: <code>permission denied</code>, <code>save mode restriction</code>, <code>open_basedir restriction</code> etc.etc. Each one require appropriate action. <strong>But if you gag it you'll never know what happened!</strong></p>\n\n<p>The OP is messing up error <strong>reporting</strong> with error <strong>handling</strong>, while it's very big difference!<br>\nError handling is for user. \"something happened\" is enough here.<br>\nWhile error reporting is for programmer, who desperately need to know what certainly happened. </p>\n\n<p>Thus, never gag errors messages. Both <strong>log it</strong> for the programmer, and <strong>handle it</strong> for the user.</p>\n"
},
{
"answer_id": 54663855,
"author": "Herbert Peters",
"author_id": 3367214,
"author_profile": "https://Stackoverflow.com/users/3367214",
"pm_score": 2,
"selected": false,
"text": "<p>Today I encountered an issue that was a good example on when one might want to use at least temporarily the @ operator.</p>\n\n<p>Long story made short, I found logon info (username and password in plain text) written into the error log trace.</p>\n\n<p>Here a bit more info about this issue.</p>\n\n<p>The logon logic is in a class of it's own, because the system is supposed to offer different logon mechanisms. Due to server migration issues there was an error occurring. That error dumped the entire trace into the error log, including password info! One method expected the username and password as parameters, hence trace wrote everything faithfully into the error log.</p>\n\n<p>The long term fix here is to refactor said class, instead of using username and password as 2 parameters, for example using a single array parameter containing those 2 values (trace will write out Array for the paramater in such cases). There are also other ways of tackling this issue, but that is an entire different issue. </p>\n\n<p>Anyways. Trace messages are helpful, but in this case were outright harmful.</p>\n\n<p>The lesson I learned, as soon as I noticed that trace output: Sometimes suppressing an error message for the time being is an useful stop gap measure to avoid further harm.</p>\n\n<p>In my opinion I didn't think it is a case of bad class design. The error itself was triggered by an PDOException ( timestamp issue moving from MySQL 5.6 to 5.7 ) that just dumped by PHP default everything into the error log.</p>\n\n<p>In general I do not use the @ operator for all the reasons explained in other comments, but in this case the error log convinced me to do something quick until the problem was properly fixed.</p>\n"
},
{
"answer_id": 60886618,
"author": "Daan",
"author_id": 987864,
"author_profile": "https://Stackoverflow.com/users/987864",
"pm_score": 2,
"selected": false,
"text": "<p>Some functions in PHP will issue an <code>E_NOTICE</code> (the <a href=\"https://www.php.net/manual/en/function.unserialize\" rel=\"nofollow noreferrer\">unserialize</a> function for example).</p>\n\n<p>A possible way to catch that error (for <a href=\"https://www.php.net/manual/en/language.errors.php7.php\" rel=\"nofollow noreferrer\">PHP versions 7+</a>) is <strong>to convert all issued errors into exceptions</strong> and not let it issue an <code>E_NOTICE</code>. We could change the exception error handler as follow:</p>\n\n<pre><code>function exception_error_handler($severity, $message, $file, $line) { \n throw new ErrorException($message, 0, $severity, $file, $line); \n} \n\nset_error_handler('exception_error_handler'); \n\ntry { \n unserialize('foo');\n} catch(\\Exception $e) {\n // ... will throw the exception here\n} \n</code></pre>\n"
},
{
"answer_id": 67541028,
"author": "Christopher Schultz",
"author_id": 276232,
"author_profile": "https://Stackoverflow.com/users/276232",
"pm_score": 1,
"selected": false,
"text": "<p>I have what I think is a valid use-case for error suppression using @.</p>\n<p>I have two systems, one running PHP 5.6.something and another running PHP 7.3.something. I want a script which will run properly on both of them, but some stuff didn't exist back in PHP 5.6, so I'm using polyfills like <a href=\"https://github.com/paragonie/random_compat\" rel=\"nofollow noreferrer\">random_compat</a>.</p>\n<p>It's always best to use the built-in functions, so I have code that looks like this:</p>\n<pre><code>if(function_exists("random_bytes")) {\n $bytes = random_bytes(32);\n} else {\n @include "random_compat/random.php"; // Suppress warnings+errors\n if(function_exists("random_bytes")) {\n $bytes = random_bytes(32);\n } else if(function_exists('openssl_random_pseudo_bytes')) {\n $bytes = openssl_random_pseudo_bytes(4);\n } else {\n // Boooo! We have to generate crappy randomness\n $bytes = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',64)),0,32);\n }\n}\n</code></pre>\n<p>The fallback to the polyfill should never generate any errors or warnings. I'm checking to see that the function exists after attempting to load the polyfill which is all that is necessary. There is even a fallback to the fallback. And a fallback to the fallback to the fallback.</p>\n<p>There is no way to avoid a potential error with <code>include</code> (e.g. using <code>file_exists</code>) so the only way to do it is to suppress warnings and check to see if it worked. At least, in this case.</p>\n"
},
{
"answer_id": 68262822,
"author": "Emanuel A.",
"author_id": 2033076,
"author_profile": "https://Stackoverflow.com/users/2033076",
"pm_score": 1,
"selected": false,
"text": "<p>I can think of one case of use, for auto-increment a non existing array key.</p>\n<pre><code>$totalCars = [];\n\n$totalCars['toyota']++; // PHP Notice: Undefined index: toyota\n\n@$totalCars['toyota']++;\n// [\n// "toyota" => 2,\n// ]\n</code></pre>\n"
},
{
"answer_id": 70197339,
"author": "Stanley Aloh",
"author_id": 9182496,
"author_profile": "https://Stackoverflow.com/users/9182496",
"pm_score": 0,
"selected": false,
"text": "<p>In my experience I would say generally speaking, error suppress is just another bad practice for future developers and should be avoided as much as possible as it hides complication of error and prevent error logging unlike Exception which can help developers with error snapshot. But answering the original question which say "<strong>If so, in what circumstances would you use this?</strong>".</p>\n<p>I would say one should use it against some legacy codes or library that don't throw exception errors but instead handles bad errors by keep the error variables with it's object(speaking of OOP) or using a global variable for logging error or just printing error all together.</p>\n<p>Take for example the mysqli object</p>\n<pre><code>new mysqli($this->host, $this->username, $this->password, $this->db);\n</code></pre>\n<p>This code above barely or never throw an exception on failed connection, it only store error in <code>mysqli::errno</code> and <code>mysli::error</code></p>\n<p>For modern day coding the one solution I found was to suppress the ugly error messages (which helps no one especially when on production server where debug mode is off) and instead devs should throw their own exception. Which is consider modern practice and help coders track errors more quickly.</p>\n<pre><code> $this->connection = @new mysqli($this->host, $this->username, $this->password, $this->db);\n if($this->connection->connect_errno)\n throw new mysqli_sql_exception($this->connection->error);\n</code></pre>\n<p>You can notice the use of suppression <code>@</code> symbol to prevent the ugly error display should incase error display was turned on development server.</p>\n<p>Also I had to throw my own exception. This way I was able to use <code>@</code> symbol and same time I didn't hide error nor did I just make my own guess of what the error could be.</p>\n<p>I will say if used rightly, then it is justifiable.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20010/"
]
| In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?
If so, in what circumstances would you use this?
Code examples are welcome.
Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use
```
@fopen($file);
```
and then check afterwards... but you can get rid of the @ by doing
```
if (file_exists($file))
{
fopen($file);
}
else
{
die('File not found');
}
```
or similar.
I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner? | I would suppress the error **and handle it**. Otherwise you may have a **TOCTOU** issue (Time-of-check, time-of-use. For example a file may get deleted after file\_exists returns true, but before fopen).
But I wouldn't just suppress errors to make them go away. These better be visible. |
136,937 | <p>Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.</p>
| [
{
"answer_id": 136957,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 1,
"selected": false,
"text": "<p><code>onLocationChange</code> may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.</p>\n"
},
{
"answer_id": 136965,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 6,
"selected": true,
"text": "<p>Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers.onhashchange\" rel=\"noreferrer\"><code>hashchange</code></a> event:</p>\n\n<pre><code>window.addEventListener(\"hashchange\", function(e) {\n // ...\n})\n</code></pre>\n\n<p>If you need to support older browsers, check out the <a href=\"https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#hashchange-event\" rel=\"noreferrer\"><code>hashChange</code> Event section</a> in Modernizr's HTML5 Cross Browser Polyfills wiki page.</p>\n"
},
{
"answer_id": 136972,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 1,
"selected": false,
"text": "<p>Did you took a look at this? <a href=\"http://developer.yahoo.com/yui/history/\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/history/</a></p>\n"
},
{
"answer_id": 9406145,
"author": "Tom Penzer",
"author_id": 1227266,
"author_profile": "https://Stackoverflow.com/users/1227266",
"pm_score": 3,
"selected": false,
"text": "<p>I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question. </p>\n\n<p>What I ended up doing was creating an object as such: </p>\n\n<pre><code>var pageload = {\n ignorehashchange: false,\n loadUrl: function(){\n if (pageload.ignorehashchange == false){\n //code to parse window.location.hash and load content\n };\n }\n};\n</code></pre>\n\n<p>Then, I added a line to my site script to run the <code>pageload.loadUrl</code> function upon the <a href=\"https://developer.mozilla.org/en/DOM/window.onhashchange\" rel=\"noreferrer\" title=\"hashchange\">hashchange</a> event, as such:</p>\n\n<pre><code>window.addEventListener(\"hashchange\", pageload.loadUrl, false);\n</code></pre>\n\n<p>Then, any time I want to modify the <code>window.location.hash</code> without triggering this page loading routine, I simply add the following line before each <code>window.location.hash =</code> line:</p>\n\n<pre><code>pageload.ignorehashchange = true;\n</code></pre>\n\n<p>and then the following line after each hash modification line:</p>\n\n<pre><code>setTimeout(function(){pageload.ignorehashchange = false;}, 100);\n</code></pre>\n\n<p>So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.</p>\n"
},
{
"answer_id": 11529588,
"author": "JulianW",
"author_id": 577178,
"author_profile": "https://Stackoverflow.com/users/577178",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"https://github.com/balupton/History.js/\" rel=\"nofollow\">history.js</a>. There is a html 5 statechange event and you can listen to it.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393/"
]
| Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page. | Use the [`hashchange`](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers.onhashchange) event:
```
window.addEventListener("hashchange", function(e) {
// ...
})
```
If you need to support older browsers, check out the [`hashChange` Event section](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#hashchange-event) in Modernizr's HTML5 Cross Browser Polyfills wiki page. |
136,946 | <p>What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?</p>
<p>For example, when should one use</p>
<pre><code>enum {BUFFER = 1234};
</code></pre>
<p>over</p>
<pre><code>#define BUFFER 1234
</code></pre>
| [
{
"answer_id": 136954,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 7,
"selected": true,
"text": "<p><code>enum</code> defines a syntactical element.</p>\n\n<p><code>#define</code> is a pre-preprocessor directive, executed <em>before</em> the compiler sees the code, and therefore is not a language element of C itself.</p>\n\n<p>Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a <code>#define</code> made by another. This can be hard to track down.</p>\n"
},
{
"answer_id": 136974,
"author": "akiva",
"author_id": 65724,
"author_profile": "https://Stackoverflow.com/users/65724",
"pm_score": 3,
"selected": false,
"text": "<p>Define is a preprocessor command, it's just like doing \"replace all\" in your editor, it can replace a string with another and then compile the result.</p>\n\n<p>Enum is a special case of type, for example, if you write:</p>\n\n<pre><code>enum ERROR_TYPES\n{\n REGULAR_ERR =1,\n OK =0\n}\n</code></pre>\n\n<p>there exists a new type called ERROR_TYPES.\nIt is true that REGULAR_ERR yields to 1 but casting from this type to int should produce a casting warning (if you configure your compiler to high verbosity).</p>\n\n<p>Summary:\nthey are both alike, but when using enum you profit the type checking and by using defines you simply replace code strings.</p>\n"
},
{
"answer_id": 136978,
"author": "Smashery",
"author_id": 14902,
"author_profile": "https://Stackoverflow.com/users/14902",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a group of constants (like \"Days of the Week\") enums would be preferable, because it shows that they are grouped; and, as Jason said, they are type-safe. If it's a global constant (like version number), that's more what you'd use a <code>#define</code> for; although this is the subject of a lot of debate.</p>\n"
},
{
"answer_id": 136992,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p><code>#define</code> statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).</p>\n\n<p>Enumerations are part of the C language itself and have the following advantages.</p>\n\n<p>1/ They may have type and the compiler can type-check them.</p>\n\n<p>2/ Since they are available to the compiler, symbol information on them can be passed through to the debugger, making debugging easier.</p>\n"
},
{
"answer_id": 137099,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 3,
"selected": false,
"text": "<p>Enums are generally prefered over #define wherever it makes sense to use an enum:</p>\n\n<ul>\n<li>Debuggers can show you the symbolic name of an <code>enum</code>s value (\"<code>openType: OpenExisting</code>\", rather than \"<code>openType: 2</code>\"</li>\n<li>You get a bit more protection from name clashes, but this isn't as bad as it was (most compilers warn about re<code>#define</code>ition.</li>\n</ul>\n\n<p>The biggest difference is that you can use enums as types:</p>\n\n<pre><code>// Yeah, dumb example\nenum OpenType {\n OpenExisting,\n OpenOrCreate,\n Truncate\n};\n\nvoid OpenFile(const char* filename, OpenType openType, int bufferSize);\n</code></pre>\n\n<p>This gives you type-checking of parameters (you can't mix up openType and bufferSize as easily), and makes it easy to find what values are valid, making your interfaces much easier to use. Some IDEs can even give you <strike>intellisense</strike> code completion!</p>\n"
},
{
"answer_id": 138662,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the good points listed above, you can limit the scope of enums to a class, struct or namespace. Personally, I like to have the minimum number of relevent symbols in scope at any one time which is another reason for using enums rather than #defines.</p>\n"
},
{
"answer_id": 147203,
"author": "Russell Bryant",
"author_id": 23224,
"author_profile": "https://Stackoverflow.com/users/23224",
"pm_score": 1,
"selected": false,
"text": "<p>Another advantage of an enum over a list of defines is that compilers (gcc at least) can generate a warning when not all values are checked in a switch statement. For example:</p>\n\n<pre><code>enum {\n STATE_ONE,\n STATE_TWO,\n STATE_THREE\n};\n\n...\n\nswitch (state) {\ncase STATE_ONE:\n handle_state_one();\n break;\ncase STATE_TWO:\n handle_state_two();\n break;\n};\n</code></pre>\n\n<p>In the previous code, the compiler is able to generate a warning that not all values of the enum are handled in the switch. If the states were done as #define's, this would not be the case.</p>\n"
},
{
"answer_id": 3035591,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>It's always better to use an enum if possible. Using an enum gives the compiler more information about your source code, a preprocessor define is never seen by the compiler and thus carries less information.</p>\n\n<p>For implementing e.g. a bunch of modes, using an enum makes it possible for the compiler to catch missing <code>case</code>-statements in a switch, for instance.</p>\n"
},
{
"answer_id": 3035598,
"author": "PeterK",
"author_id": 350605,
"author_profile": "https://Stackoverflow.com/users/350605",
"pm_score": 1,
"selected": false,
"text": "<p>enums are more used for enumerating some kind of set, like days in a week. If you need just one constant number, <code>const int</code> (or double etc.) would be definetly better than enum. I personally do not like <code>#define</code> (at least not for the definition of some constants) because it does not give me type safety, but you can of course use it if it suits you better.</p>\n"
},
{
"answer_id": 3035604,
"author": "Henno Brandsma",
"author_id": 342544,
"author_profile": "https://Stackoverflow.com/users/342544",
"pm_score": 2,
"selected": false,
"text": "<p>If you only want this single constant (say for buffersize) then I would not use an enum, but a define. I would use enums for stuff like return values (that mean different error conditions) and wherever we need to distinguish different \"types\" or \"cases\". In that case we can use an enum to create a new type we can use in function prototypes etc., and then the compiler can sanity check that code better.</p>\n"
},
{
"answer_id": 3035620,
"author": "Andy",
"author_id": 339702,
"author_profile": "https://Stackoverflow.com/users/339702",
"pm_score": 2,
"selected": false,
"text": "<p>enum can group multiple elements in one category:</p>\n\n<pre><code>enum fruits{ apple=1234, orange=12345};\n</code></pre>\n\n<p>while #define can only create unrelated constants:</p>\n\n<pre><code>#define apple 1234\n#define orange 12345\n</code></pre>\n"
},
{
"answer_id": 3035640,
"author": "kriss",
"author_id": 168465,
"author_profile": "https://Stackoverflow.com/users/168465",
"pm_score": 2,
"selected": false,
"text": "<p><strong>#define is a preprocessor command, enum is in the C or C++ language.</strong></p>\n\n<p>It is always better to use enums over #define for this kind of cases. One thing is type safety. Another one is that when you have a sequence of values you only have to give the beginning of the sequence in the enum, the other values get consecutive values.</p>\n\n<pre><code>enum {\n ONE = 1,\n TWO,\n THREE,\n FOUR\n};\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>#define ONE 1\n#define TWO 2\n#define THREE 3\n#define FOUR 4\n</code></pre>\n\n<p>As a side-note, there is still some cases where you may have to use #define (typically for some kind of macros, if you need to be able to construct an identifier that contains the constant), but that's kind of macro black magic, and very very rare to be the way to go. If you go to these extremities you probably should use a C++ template (but if you're stuck with C...).</p>\n"
},
{
"answer_id": 3035672,
"author": "ShinTakezou",
"author_id": 354803,
"author_profile": "https://Stackoverflow.com/users/354803",
"pm_score": 2,
"selected": false,
"text": "<p>Besides all the thing already written, one said but not shown and is instead interesting. E.g.</p>\n\n<pre><code>enum action { DO_JUMP, DO_TURNL, DO_TURNR, DO_STOP };\n//...\nvoid do_action( enum action anAction, info_t x );\n</code></pre>\n\n<p>Considering action as a type makes thing clearer. Using define, you would have written</p>\n\n<pre><code>void do_action(int anAction, info_t x);\n</code></pre>\n"
},
{
"answer_id": 3035720,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>For integral constant values I've come to prefer <code>enum</code> over <code>#define</code>. There seem to be no disadvantages to using <code>enum</code> (discounting the miniscule disadvantage of a bit more typing), but you have the advantage that <code>enum</code> can be scoped, while <code>#define</code> identifiers have global scope that tromps everything.</p>\n\n<p>Using <code>#define</code> isn't usually a problem, but since there are no drawbacks to <code>enum</code>, I go with that.</p>\n\n<p>In C++ I also generally prefer <code>enum</code> to <code>const int</code> even though in C++ a <code>const int</code> can be used in place of a literal integer value (unlike in C) because <code>enum</code> is portable to C (which I still work in a lot) .</p>\n"
},
{
"answer_id": 3035798,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 1,
"selected": false,
"text": "<p>Creating an enum creates not only literals but also the type that groups these literals: This adds semantic to your code that the compiler is able to check.</p>\n\n<p>Moreover, when using a debugger, you have access to the values of enum literals. This is not always the case with #define.</p>\n"
},
{
"answer_id": 24367439,
"author": "prashantitis",
"author_id": 2058355,
"author_profile": "https://Stackoverflow.com/users/2058355",
"pm_score": 0,
"selected": false,
"text": "<p>There is little difference. The C Standard says that enumerations have integral type and that enumeration constants are of type int, so both may be freely intermixed with other integral types, without errors. (If, on the other hand, such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.)</p>\n\n<p>Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables. </p>\n"
},
{
"answer_id": 38479432,
"author": "Nikos",
"author_id": 703641,
"author_profile": "https://Stackoverflow.com/users/703641",
"pm_score": 1,
"selected": false,
"text": "<p>While several answers above recommend to use enum for various reasons, I'd like to point out that using defines has an actual advantage when developing interfaces. You can introduce new options and you can let software use them conditionally.</p>\n\n<p>For example:</p>\n\n<pre>\n\n #define OPT_X1 1 /* introduced in version 1 */\n #define OPT_X2 2 /* introduced in version 2 */\n\n</pre>\n\n<p>Then software which can be compiled with either version it can do</p>\n\n<pre>\n\n #ifdef OPT_X2\n int flags = OPT_X2;\n #else\n int flags = 0;\n #endif\n\n</pre>\n\n<p>While on an enumeration this isn't possible without a run-time feature detection mechanism.</p>\n"
},
{
"answer_id": 45641382,
"author": "user8194964",
"author_id": 8194964,
"author_profile": "https://Stackoverflow.com/users/8194964",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Enum:</strong><br><br>\n<strong>1.</strong> Generally used for multiple values<br><br>\n<strong>2.</strong> In enum there are two thing one is name and another is value of name name must be distinguished but value can be same.If we not define value then first value of enum name is 0 second value is 1,and so on, unless explicitly value are specified.<br><br>\n<strong>3.</strong> They may have type and compiler can type check them<br><br>\n<strong>4.</strong> Make debugging easy<br><br>\n<strong>5.</strong> We can limit scope of it up to a class.<br><br></p>\n\n<p><strong>Define:</strong><br><br>\n<strong>1.</strong> When we have to define only one value <br><br>\n<strong>2.</strong> It generally replace one string to another string.<br><br>\n<strong>3.</strong> It scope is global we cannot limit its scope <br><br></p>\n\n<p>Overall we have to use enum </p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21539/"
]
| What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?
For example, when should one use
```
enum {BUFFER = 1234};
```
over
```
#define BUFFER 1234
``` | `enum` defines a syntactical element.
`#define` is a pre-preprocessor directive, executed *before* the compiler sees the code, and therefore is not a language element of C itself.
Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a `#define` made by another. This can be hard to track down. |
136,948 | <p>I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7.</p>
<p>The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is</p>
<pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\
EIPortal_DEV_2_0_5_4[1].expd"
</code></pre>
<p>This unfortunately does not resolve to the physical file when calling <code>FileExists()</code> or when attempting to create a <code>TFileStream</code> object.</p>
<p>The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of <code>"Content.IE5\ALBKHO3Q"</code> whose absolute path would be expressed as</p>
<pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\
Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd"
</code></pre>
<p>Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing.</p>
<p>Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of <code>"application/x-expeditors"</code>. The registration of the <code>".expd"</code> / <code>"application/x-expeditors"</code> mime-type looks like this.</p>
<pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd]
@="ExpeditorsInstaller"
"Content Type"="application/x-expeditors"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller]
"EditFlags"=hex:00,00,01,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open]
@=""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command]
@="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors]
"Extension"=".expd"
</code></pre>
<p>I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix <code>"[n]"</code> may be the unique key.</p>
<p>I have tried wininet method <code>GetUrlCacheEntryInfo</code> but that requires the URL, not the virtual path handed over by IE.</p>
<p>My hope is that there is a Shell function that given a virtual path will hand back the physical path.</p>
| [
{
"answer_id": 136954,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 7,
"selected": true,
"text": "<p><code>enum</code> defines a syntactical element.</p>\n\n<p><code>#define</code> is a pre-preprocessor directive, executed <em>before</em> the compiler sees the code, and therefore is not a language element of C itself.</p>\n\n<p>Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a <code>#define</code> made by another. This can be hard to track down.</p>\n"
},
{
"answer_id": 136974,
"author": "akiva",
"author_id": 65724,
"author_profile": "https://Stackoverflow.com/users/65724",
"pm_score": 3,
"selected": false,
"text": "<p>Define is a preprocessor command, it's just like doing \"replace all\" in your editor, it can replace a string with another and then compile the result.</p>\n\n<p>Enum is a special case of type, for example, if you write:</p>\n\n<pre><code>enum ERROR_TYPES\n{\n REGULAR_ERR =1,\n OK =0\n}\n</code></pre>\n\n<p>there exists a new type called ERROR_TYPES.\nIt is true that REGULAR_ERR yields to 1 but casting from this type to int should produce a casting warning (if you configure your compiler to high verbosity).</p>\n\n<p>Summary:\nthey are both alike, but when using enum you profit the type checking and by using defines you simply replace code strings.</p>\n"
},
{
"answer_id": 136978,
"author": "Smashery",
"author_id": 14902,
"author_profile": "https://Stackoverflow.com/users/14902",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a group of constants (like \"Days of the Week\") enums would be preferable, because it shows that they are grouped; and, as Jason said, they are type-safe. If it's a global constant (like version number), that's more what you'd use a <code>#define</code> for; although this is the subject of a lot of debate.</p>\n"
},
{
"answer_id": 136992,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p><code>#define</code> statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).</p>\n\n<p>Enumerations are part of the C language itself and have the following advantages.</p>\n\n<p>1/ They may have type and the compiler can type-check them.</p>\n\n<p>2/ Since they are available to the compiler, symbol information on them can be passed through to the debugger, making debugging easier.</p>\n"
},
{
"answer_id": 137099,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 3,
"selected": false,
"text": "<p>Enums are generally prefered over #define wherever it makes sense to use an enum:</p>\n\n<ul>\n<li>Debuggers can show you the symbolic name of an <code>enum</code>s value (\"<code>openType: OpenExisting</code>\", rather than \"<code>openType: 2</code>\"</li>\n<li>You get a bit more protection from name clashes, but this isn't as bad as it was (most compilers warn about re<code>#define</code>ition.</li>\n</ul>\n\n<p>The biggest difference is that you can use enums as types:</p>\n\n<pre><code>// Yeah, dumb example\nenum OpenType {\n OpenExisting,\n OpenOrCreate,\n Truncate\n};\n\nvoid OpenFile(const char* filename, OpenType openType, int bufferSize);\n</code></pre>\n\n<p>This gives you type-checking of parameters (you can't mix up openType and bufferSize as easily), and makes it easy to find what values are valid, making your interfaces much easier to use. Some IDEs can even give you <strike>intellisense</strike> code completion!</p>\n"
},
{
"answer_id": 138662,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the good points listed above, you can limit the scope of enums to a class, struct or namespace. Personally, I like to have the minimum number of relevent symbols in scope at any one time which is another reason for using enums rather than #defines.</p>\n"
},
{
"answer_id": 147203,
"author": "Russell Bryant",
"author_id": 23224,
"author_profile": "https://Stackoverflow.com/users/23224",
"pm_score": 1,
"selected": false,
"text": "<p>Another advantage of an enum over a list of defines is that compilers (gcc at least) can generate a warning when not all values are checked in a switch statement. For example:</p>\n\n<pre><code>enum {\n STATE_ONE,\n STATE_TWO,\n STATE_THREE\n};\n\n...\n\nswitch (state) {\ncase STATE_ONE:\n handle_state_one();\n break;\ncase STATE_TWO:\n handle_state_two();\n break;\n};\n</code></pre>\n\n<p>In the previous code, the compiler is able to generate a warning that not all values of the enum are handled in the switch. If the states were done as #define's, this would not be the case.</p>\n"
},
{
"answer_id": 3035591,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>It's always better to use an enum if possible. Using an enum gives the compiler more information about your source code, a preprocessor define is never seen by the compiler and thus carries less information.</p>\n\n<p>For implementing e.g. a bunch of modes, using an enum makes it possible for the compiler to catch missing <code>case</code>-statements in a switch, for instance.</p>\n"
},
{
"answer_id": 3035598,
"author": "PeterK",
"author_id": 350605,
"author_profile": "https://Stackoverflow.com/users/350605",
"pm_score": 1,
"selected": false,
"text": "<p>enums are more used for enumerating some kind of set, like days in a week. If you need just one constant number, <code>const int</code> (or double etc.) would be definetly better than enum. I personally do not like <code>#define</code> (at least not for the definition of some constants) because it does not give me type safety, but you can of course use it if it suits you better.</p>\n"
},
{
"answer_id": 3035604,
"author": "Henno Brandsma",
"author_id": 342544,
"author_profile": "https://Stackoverflow.com/users/342544",
"pm_score": 2,
"selected": false,
"text": "<p>If you only want this single constant (say for buffersize) then I would not use an enum, but a define. I would use enums for stuff like return values (that mean different error conditions) and wherever we need to distinguish different \"types\" or \"cases\". In that case we can use an enum to create a new type we can use in function prototypes etc., and then the compiler can sanity check that code better.</p>\n"
},
{
"answer_id": 3035620,
"author": "Andy",
"author_id": 339702,
"author_profile": "https://Stackoverflow.com/users/339702",
"pm_score": 2,
"selected": false,
"text": "<p>enum can group multiple elements in one category:</p>\n\n<pre><code>enum fruits{ apple=1234, orange=12345};\n</code></pre>\n\n<p>while #define can only create unrelated constants:</p>\n\n<pre><code>#define apple 1234\n#define orange 12345\n</code></pre>\n"
},
{
"answer_id": 3035640,
"author": "kriss",
"author_id": 168465,
"author_profile": "https://Stackoverflow.com/users/168465",
"pm_score": 2,
"selected": false,
"text": "<p><strong>#define is a preprocessor command, enum is in the C or C++ language.</strong></p>\n\n<p>It is always better to use enums over #define for this kind of cases. One thing is type safety. Another one is that when you have a sequence of values you only have to give the beginning of the sequence in the enum, the other values get consecutive values.</p>\n\n<pre><code>enum {\n ONE = 1,\n TWO,\n THREE,\n FOUR\n};\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>#define ONE 1\n#define TWO 2\n#define THREE 3\n#define FOUR 4\n</code></pre>\n\n<p>As a side-note, there is still some cases where you may have to use #define (typically for some kind of macros, if you need to be able to construct an identifier that contains the constant), but that's kind of macro black magic, and very very rare to be the way to go. If you go to these extremities you probably should use a C++ template (but if you're stuck with C...).</p>\n"
},
{
"answer_id": 3035672,
"author": "ShinTakezou",
"author_id": 354803,
"author_profile": "https://Stackoverflow.com/users/354803",
"pm_score": 2,
"selected": false,
"text": "<p>Besides all the thing already written, one said but not shown and is instead interesting. E.g.</p>\n\n<pre><code>enum action { DO_JUMP, DO_TURNL, DO_TURNR, DO_STOP };\n//...\nvoid do_action( enum action anAction, info_t x );\n</code></pre>\n\n<p>Considering action as a type makes thing clearer. Using define, you would have written</p>\n\n<pre><code>void do_action(int anAction, info_t x);\n</code></pre>\n"
},
{
"answer_id": 3035720,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>For integral constant values I've come to prefer <code>enum</code> over <code>#define</code>. There seem to be no disadvantages to using <code>enum</code> (discounting the miniscule disadvantage of a bit more typing), but you have the advantage that <code>enum</code> can be scoped, while <code>#define</code> identifiers have global scope that tromps everything.</p>\n\n<p>Using <code>#define</code> isn't usually a problem, but since there are no drawbacks to <code>enum</code>, I go with that.</p>\n\n<p>In C++ I also generally prefer <code>enum</code> to <code>const int</code> even though in C++ a <code>const int</code> can be used in place of a literal integer value (unlike in C) because <code>enum</code> is portable to C (which I still work in a lot) .</p>\n"
},
{
"answer_id": 3035798,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 1,
"selected": false,
"text": "<p>Creating an enum creates not only literals but also the type that groups these literals: This adds semantic to your code that the compiler is able to check.</p>\n\n<p>Moreover, when using a debugger, you have access to the values of enum literals. This is not always the case with #define.</p>\n"
},
{
"answer_id": 24367439,
"author": "prashantitis",
"author_id": 2058355,
"author_profile": "https://Stackoverflow.com/users/2058355",
"pm_score": 0,
"selected": false,
"text": "<p>There is little difference. The C Standard says that enumerations have integral type and that enumeration constants are of type int, so both may be freely intermixed with other integral types, without errors. (If, on the other hand, such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.)</p>\n\n<p>Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables. </p>\n"
},
{
"answer_id": 38479432,
"author": "Nikos",
"author_id": 703641,
"author_profile": "https://Stackoverflow.com/users/703641",
"pm_score": 1,
"selected": false,
"text": "<p>While several answers above recommend to use enum for various reasons, I'd like to point out that using defines has an actual advantage when developing interfaces. You can introduce new options and you can let software use them conditionally.</p>\n\n<p>For example:</p>\n\n<pre>\n\n #define OPT_X1 1 /* introduced in version 1 */\n #define OPT_X2 2 /* introduced in version 2 */\n\n</pre>\n\n<p>Then software which can be compiled with either version it can do</p>\n\n<pre>\n\n #ifdef OPT_X2\n int flags = OPT_X2;\n #else\n int flags = 0;\n #endif\n\n</pre>\n\n<p>While on an enumeration this isn't possible without a run-time feature detection mechanism.</p>\n"
},
{
"answer_id": 45641382,
"author": "user8194964",
"author_id": 8194964,
"author_profile": "https://Stackoverflow.com/users/8194964",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Enum:</strong><br><br>\n<strong>1.</strong> Generally used for multiple values<br><br>\n<strong>2.</strong> In enum there are two thing one is name and another is value of name name must be distinguished but value can be same.If we not define value then first value of enum name is 0 second value is 1,and so on, unless explicitly value are specified.<br><br>\n<strong>3.</strong> They may have type and compiler can type check them<br><br>\n<strong>4.</strong> Make debugging easy<br><br>\n<strong>5.</strong> We can limit scope of it up to a class.<br><br></p>\n\n<p><strong>Define:</strong><br><br>\n<strong>1.</strong> When we have to define only one value <br><br>\n<strong>2.</strong> It generally replace one string to another string.<br><br>\n<strong>3.</strong> It scope is global we cannot limit its scope <br><br></p>\n\n<p>Overall we have to use enum </p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13183/"
]
| I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7.
The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is
```
"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\
EIPortal_DEV_2_0_5_4[1].expd"
```
This unfortunately does not resolve to the physical file when calling `FileExists()` or when attempting to create a `TFileStream` object.
The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of `"Content.IE5\ALBKHO3Q"` whose absolute path would be expressed as
```
"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\
Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd"
```
Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing.
Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of `"application/x-expeditors"`. The registration of the `".expd"` / `"application/x-expeditors"` mime-type looks like this.
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd]
@="ExpeditorsInstaller"
"Content Type"="application/x-expeditors"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller]
"EditFlags"=hex:00,00,01,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open]
@=""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command]
@="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors]
"Extension"=".expd"
```
I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix `"[n]"` may be the unique key.
I have tried wininet method `GetUrlCacheEntryInfo` but that requires the URL, not the virtual path handed over by IE.
My hope is that there is a Shell function that given a virtual path will hand back the physical path. | `enum` defines a syntactical element.
`#define` is a pre-preprocessor directive, executed *before* the compiler sees the code, and therefore is not a language element of C itself.
Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a `#define` made by another. This can be hard to track down. |
136,961 | <p>I'm using the jQuery Form plugin to upload an image. I've assigned a fade animation to happen the <code>beforeSubmit</code> callback, but as I'm running locally, it doesn't have time to finish before the <code>success</code> function is called. </p>
<p>I am using a callback function in my <code>fade();</code> call to make sure that one fade completes, before the next one begins, but that does not seem to guarantee that the function that's calling it is finished.</p>
<p>Am I doing something wrong? Shouldn't <code>beforeSubmit</code> complete before the ajax call is submitted?</p>
<p>Here's are the two callbacks:</p>
<p>beforeSubmit:</p>
<pre><code>function prepImageArea() {
if (userImage) {
userImage.fadeOut(1500, function() {
ajaxSpinner.fadeIn(1500);
});
}
}
</code></pre>
<p>success:</p>
<pre><code>function imageUploaded(data) {
var data = evalJson(data);
userImage.attr('src', data.large_thumb);
ajaxSpinner.fadeOut(1500, function() {
userImage.fadeIn(1500);
});
}
</code></pre>
| [
{
"answer_id": 137035,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 3,
"selected": true,
"text": "<p>I think you may be getting too fancy with those fade animations :)... In the beforeSubmit the fadeOut is setup but the function returns immediately causing the submit to happen. I guess the upload is happening under 3 seconds causing the new image to appear before your animations are complete.</p>\n\n<p>So if you really really want this effect, then you will need to do the image fadeout, spinner fadein, and once that is complete triggering the upload. Something like this:</p>\n\n<pre><code>if (userImage) {\n userImage.fadeOut(1500, function() {\n ajaxSpinner.fadeIn(1500, function(){\n //now trigger the upload and you don't need the before submit anymore\n });\n });\n}\nelse {\n // trigger the upload right away\n}\n</code></pre>\n"
},
{
"answer_id": 137046,
"author": "Ahmad",
"author_id": 22449,
"author_profile": "https://Stackoverflow.com/users/22449",
"pm_score": 1,
"selected": false,
"text": "<p>Even though the beforeSubmit callback is called before submitting the form, the userImage.fadeOut function is synchronous (i.e. it spawns a separate thread of execution to execute the fade animation then it continues execution) and it returns immediately. The fade animation takes 1.5 seconds to complete and as you are running on localhost the ajax response is returned faster than 1.5 seconds and thus you won't see the animation, in real world applications it mostly unlikely that ajax requests would take less than 1.5 seconds, so you are good :)</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4636/"
]
| I'm using the jQuery Form plugin to upload an image. I've assigned a fade animation to happen the `beforeSubmit` callback, but as I'm running locally, it doesn't have time to finish before the `success` function is called.
I am using a callback function in my `fade();` call to make sure that one fade completes, before the next one begins, but that does not seem to guarantee that the function that's calling it is finished.
Am I doing something wrong? Shouldn't `beforeSubmit` complete before the ajax call is submitted?
Here's are the two callbacks:
beforeSubmit:
```
function prepImageArea() {
if (userImage) {
userImage.fadeOut(1500, function() {
ajaxSpinner.fadeIn(1500);
});
}
}
```
success:
```
function imageUploaded(data) {
var data = evalJson(data);
userImage.attr('src', data.large_thumb);
ajaxSpinner.fadeOut(1500, function() {
userImage.fadeIn(1500);
});
}
``` | I think you may be getting too fancy with those fade animations :)... In the beforeSubmit the fadeOut is setup but the function returns immediately causing the submit to happen. I guess the upload is happening under 3 seconds causing the new image to appear before your animations are complete.
So if you really really want this effect, then you will need to do the image fadeout, spinner fadein, and once that is complete triggering the upload. Something like this:
```
if (userImage) {
userImage.fadeOut(1500, function() {
ajaxSpinner.fadeIn(1500, function(){
//now trigger the upload and you don't need the before submit anymore
});
});
}
else {
// trigger the upload right away
}
``` |
136,975 | <p>Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler.</p>
<p>In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.</p>
<p>It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.</p>
<p>Is that possible?</p>
<p>EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough. </p>
| [
{
"answer_id": 136994,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 4,
"selected": false,
"text": "<p>If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.</p>\n\n<p>I think you can safely call -= on the event with your handler even if it's not added (if not, you could catch it) -- to make sure it isn't in there before adding. </p>\n"
},
{
"answer_id": 136997,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 2,
"selected": false,
"text": "<pre><code>EventHandler.GetInvocationList().Length > 0\n</code></pre>\n"
},
{
"answer_id": 136998,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "<p>From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a <code>+=</code> or a <code>-=</code>. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is <code>null</code> - if so, then no event handler has been added. If not, then maybe and you can loop through the values in \n<a href=\"http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx\" rel=\"noreferrer\">Delegate.GetInvocationList</a>. If one is equal to the delegate that you want to add as event handler, then you know it's there.</p>\n\n<pre><code>public bool IsEventHandlerRegistered(Delegate prospectiveHandler)\n{ \n if ( this.EventHandler != null )\n {\n foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )\n {\n if ( existingHandler == prospectiveHandler )\n {\n return true;\n }\n }\n }\n return false;\n}\n</code></pre>\n\n<p>And this could easily be modified to become \"add the handler if it's not there\". If you don't have access to the innards of the class that's exposing the event, you may need to explore <code>-=</code> and <code>+=</code>, as suggested by @Lou Franco. </p>\n\n<p>However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.</p>\n"
},
{
"answer_id": 137112,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "<p>This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.</p>\n\n<pre><code>public class MyClass\n{\n event Action MyEvent;\n}\n\n...\n\nMyClass myClass = new MyClass();\nmyClass.MyEvent += SomeFunction;\n\n...\n\nAction[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example\n\nConsole.WriteLine(handlers[0].Method.Name);//prints the name of the method\n</code></pre>\n\n<p>You can examine various properties on the Method property of the delegate to see if a specific function has been added.</p>\n\n<p>If you are looking to see if there is just one attached, you can just test for null.</p>\n"
},
{
"answer_id": 140874,
"author": "CodeChef",
"author_id": 21786,
"author_profile": "https://Stackoverflow.com/users/21786",
"pm_score": 3,
"selected": false,
"text": "<p>If I understand your problem correctly you may have bigger issues. You said that other objects may subscribe to these events. When the object is serialized and deserialized the other objects (the ones that you don't have control of) will lose their event handlers. </p>\n\n<p>If you're not worried about that then keeping a reference to your event handler should be good enough. If you are worried about the side-effects of other objects losing their event handlers, then you may want to rethink your caching strategy.</p>\n"
},
{
"answer_id": 7065771,
"author": "alf",
"author_id": 512507,
"author_profile": "https://Stackoverflow.com/users/512507",
"pm_score": 8,
"selected": false,
"text": "<p>I recently came to a similar situation where I needed to register a handler for an event only once. I found that you can safely unregister first, and then register again, even if the handler is not registered at all:</p>\n\n<pre><code>myClass.MyEvent -= MyHandler;\nmyClass.MyEvent += MyHandler;\n</code></pre>\n\n<p>Note that doing this every time you register your handler will ensure that your handler is registered only once.\nSounds like a pretty good practice to me :)</p>\n"
},
{
"answer_id": 36175516,
"author": "Software_developer",
"author_id": 5093204,
"author_profile": "https://Stackoverflow.com/users/5093204",
"pm_score": 2,
"selected": false,
"text": "<p>i agree with alf's answer,but little modification to it is,,\nto use,</p>\n\n<pre><code> try\n {\n control_name.Click -= event_Click;\n main_browser.Document.Click += Document_Click;\n }\n catch(Exception exce)\n {\n main_browser.Document.Click += Document_Click;\n }\n</code></pre>\n"
},
{
"answer_id": 56279899,
"author": "Xtian11",
"author_id": 1108617,
"author_profile": "https://Stackoverflow.com/users/1108617",
"pm_score": 3,
"selected": false,
"text": "<p>The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.</p>\n\n<pre><code>bool alreadyAdded = false;\n</code></pre>\n\n<p>This variable can be global.</p>\n\n<pre><code>if(!alreadyAdded)\n{\n myClass.MyEvent += MyHandler;\n alreadyAdded = true;\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17145/"
]
| Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler.
In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.
It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.
Is that possible?
EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough. | From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a `+=` or a `-=`. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is `null` - if so, then no event handler has been added. If not, then maybe and you can loop through the values in
[Delegate.GetInvocationList](http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx). If one is equal to the delegate that you want to add as event handler, then you know it's there.
```
public bool IsEventHandlerRegistered(Delegate prospectiveHandler)
{
if ( this.EventHandler != null )
{
foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
if ( existingHandler == prospectiveHandler )
{
return true;
}
}
}
return false;
}
```
And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore `-=` and `+=`, as suggested by @Lou Franco.
However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself. |
136,986 | <p>2 tables: </p>
<pre><code>Employees
- EmployeeID
- LeadCount
Leads
- leadID
- employeeID
</code></pre>
<p>I want to update the <code>Employees.LeadCount</code> column by counting the # of leads in the <code>Leads</code> table that have the same <code>EmployeeID</code>.</p>
<p>Note: There may be more than 1 lead with the same employeeID, so I have to do a <code>DISTINCT(SUM(employeeID))</code>.</p>
| [
{
"answer_id": 137001,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 1,
"selected": false,
"text": "<pre><code>UPDATE Employees SET LeadCount = (\n SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Employees.employeeId\n)\n</code></pre>\n"
},
{
"answer_id": 137009,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "<pre><code>UPDATE\n Employees E\nSET\n E.LeadCount = (\n SELECT COUNT(L.EmployeeID)\n FROM Leads L\n WHERE L.EmployeeID = E.EmployeeID\n )\n</code></pre>\n"
},
{
"answer_id": 137032,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>Steeling from above and removing the dependent subquery.</p>\n\n<pre><code>// create tmp -> TBL (EmpID, count)\n\ninsert into TBL \n SELECT employeeID COUNT(employeeID) Di\n FROM Leads WHERE Leads.employeeId = Employees.employeeId GROUP BY EmployeeId\nUPDATE Employees SET LeadCount = (\n SELECT count FROM TBL WHERE TBL.EmpID = Employees.employeeId\n)\n\n// drop TBL\n</code></pre>\n\n<p><strong>EDIT</strong> It's \"group By\" not \"distinct\" :b (thanks Mark Brackett)</p>\n"
},
{
"answer_id": 137087,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>Joins work the same for updates (and deletes) just like they do for selects (edit: in some popular RDBMS', at least*):</p>\n\n<pre><code>UPDATE Employees SET\n LeadCount = Leads.LeadCount\nFROM Employee\nJOIN (\n SELECT EmployeeId, COUNT(*) as LeadCount \n FROM Leads \n GROUP BY EmployeeId\n) as Leads ON\n Employee.EmployeeId = Leads.EmployeeId \n</code></pre>\n\n<p>The SUM(DISTINCT EmployeeId) makes no sense - you just need a COUNT(*).</p>\n\n<ul>\n<li>MS SQL Server supports <a href=\"http://msdn.microsoft.com/en-us/library/ms177523.aspx\" rel=\"nofollow noreferrer\">UPDATE...FROM</a>, and <a href=\"http://msdn.microsoft.com/en-us/library/ms189835.aspx\" rel=\"nofollow noreferrer\">DELETE...FROM</a> syntax, as does <a href=\"http://dev.mysql.com/doc/refman/5.0/en/update.html\" rel=\"nofollow noreferrer\">MySql</a>, but the SQL-92 standard does not. SQL-92 would have you use a row expression. I know that <a href=\"http://publib.boulder.ibm.com/infocenter/db2v7luw/index.jsp?topic=/com.ibm.db2v7.doc/db2s0/sqls0645.htm\" rel=\"nofollow noreferrer\">DB2</a> supports this syntax, but not sure of any others. Frankly, I find the SQL-92 version confusing - but standards and theory wonks will argue that the FROM syntax violates relational theory and can lead to unpredictable results with imprecise JOIN clauses or when switching RDBMS vendors.</li>\n</ul>\n"
},
{
"answer_id": 137097,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "<p>You're setting yourself up for a data synchronization problem. As rows in the Leads table are inserted, updated, or deleted, you need to update the Employees.LeadCount column constantly. </p>\n\n<p>The best solution would be not to store the LeadCount column at all, but recalculate the count of leads with a SQL aggregate query as you need the value. That way it'll always be correct.</p>\n\n<pre><code>SELECT employeeID, COUNT(leadId) AS LeadCount\nFROM Leads\nGROUP BY employeeID;\n</code></pre>\n\n<p>The other solution is to create triggers on the Leads table for INSERT, UPDATE, and DELETE, so that you keep the Employees.LeadCount column current all the time. For example, using MySQL trigger syntax:</p>\n\n<pre><code>CREATE TRIGGER leadIns AFTER INSERT ON Leads\nFOR EACH ROW BEGIN\n UPDATE Employees SET LeadCount = LeadCount + 1 WHERE employeeID = NEW.employeeID;\nEND\n\nCREATE TRIGGER leadIns AFTER UPDATE ON Leads\nFOR EACH ROW BEGIN\n UPDATE Employees SET LeadCount = LeadCount - 1 WHERE employeeID = OLD.employeeID;\n UPDATE Employees SET LeadCount = LeadCount + 1 WHERE employeeID = NEW.employeeID;\nEND\n\nCREATE TRIGGER leadIns AFTER DELETE ON Leads\nFOR EACH ROW BEGIN\n UPDATE Employees SET LeadCount = LeadCount - 1 WHERE employeeID = OLD.employeeID;\nEND\n</code></pre>\n\n<p>Another option, if you are using MySQL, is to use multi-table UPDATE syntax. This is a MySQL extension to SQL, it's not portable to other brands of RDBMS. First, reset the LeadCount in all rows to zero, then do a join to the Leads table and increment the LeadCount in each row produced by the join.</p>\n\n<pre><code>UPDATE Employees SET LeadCount = 0;\nUPDATE Employees AS e JOIN Leads AS l USING (employeeID)\n SET e.LeadCount = e.LeadCount+1;\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/136986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
| 2 tables:
```
Employees
- EmployeeID
- LeadCount
Leads
- leadID
- employeeID
```
I want to update the `Employees.LeadCount` column by counting the # of leads in the `Leads` table that have the same `EmployeeID`.
Note: There may be more than 1 lead with the same employeeID, so I have to do a `DISTINCT(SUM(employeeID))`. | ```
UPDATE
Employees E
SET
E.LeadCount = (
SELECT COUNT(L.EmployeeID)
FROM Leads L
WHERE L.EmployeeID = E.EmployeeID
)
``` |
137,006 | <p>Is there any way to redefine a class or some of its methods without using typical inheritance? For example:</p>
<pre><code>class third_party_library {
function buggy_function() {
return 'bad result';
}
function other_functions(){
return 'blah';
}
}
</code></pre>
<p>What can I do to replace <code>buggy_function()</code>? Obviously this is what I would like to do</p>
<pre><code>class third_party_library redefines third_party_library{
function buggy_function() {
return 'good result';
}
function other_functions(){
return 'blah';
}
}
</code></pre>
<p>This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.</p>
<p>I've found this <a href="http://pecl.php.net/package/classkit" rel="noreferrer">library</a> that says it can do it, but I'm wary as it's 4 years old.</p>
<p>EDIT:</p>
<p>I should have clarified that I cannot rename the class from <code>third_party_library</code> to <code>magical_third_party_library</code> or anything else because of framework limitations.</p>
<p>For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a "partial class."</p>
| [
{
"answer_id": 137017,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 1,
"selected": false,
"text": "<p>Zend Studio and PDT (eclipse based ide) have some built in refractoring tools. But there are no built in methods to do this.</p>\n\n<p>Also you wouldn't want to have bad code in your system at all. Since it could be called upon by mistake.</p>\n"
},
{
"answer_id": 137028,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 6,
"selected": true,
"text": "<p>It's called <a href=\"http://en.wikipedia.org/wiki/Monkey_patch\" rel=\"noreferrer\">monkey patching</a>. But, PHP doesn't have native support for it.</p>\n\n<p>Though, as others have also pointed out, the <a href=\"http://docs.php.net/runkit\" rel=\"noreferrer\">runkit library</a> is available for adding support to the language and is the successor to <a href=\"http://docs.php.net/manual/en/book.classkit.php\" rel=\"noreferrer\">classkit</a>. And, though it seemed to have been <a href=\"http://pecl.php.net/package/runkit\" rel=\"noreferrer\">abandoned</a> by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a <a href=\"https://github.com/zenovich/runkit\" rel=\"noreferrer\">new home and maintainer</a>.</p>\n\n<p>I still <a href=\"https://stackoverflow.com/revisions/137028/3\">can't say I'm a fan</a> of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug.</p>\n\n<p>Still, <a href=\"http://us2.php.net/manual/en/function.runkit-method-redefine.php\" rel=\"noreferrer\"><code>runkit_method_redefine</code></a> appears to be what you're looking for, and an example of its use can be found in <a href=\"https://github.com/zenovich/runkit/blob/master/tests/runkit_method_redefine.phpt\" rel=\"noreferrer\"><code>/tests/runkit_method_redefine.phpt</code></a> in the repository:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>runkit_method_redefine('third_party_library', 'buggy_function', '',\n 'return \\'good result\\''\n);\n</code></pre>\n"
},
{
"answer_id": 137030,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, it's called <code>extend</code>:</p>\n\n<pre><code><?php\nclass sd_third_party_library extends third_party_library\n{\n function buggy_function() {\n return 'good result';\n }\n function other_functions(){\n return 'blah';\n }\n}\n</code></pre>\n\n<p>I prefixed with \"sd\". ;-)</p>\n\n<p>Keep in mind that when you extend a class to override methods, the method's signature has to match the original. So for example if the original said <code>buggy_function($foo, $bar)</code>, it has to match the parameters in the class extending it.</p>\n\n<p>PHP is pretty verbose about it.</p>\n"
},
{
"answer_id": 137034,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": -1,
"selected": false,
"text": "<p>There's alway extending the class with a new, proper, method and calling that class instead of the buggy one.</p>\n\n<pre><code>class my_better_class Extends some_buggy_class {\n function non_buggy_function() {\n return 'good result';\n }\n}\n</code></pre>\n\n<p>(Sorry for the crappy formatting)</p>\n"
},
{
"answer_id": 137057,
"author": "MOdMac",
"author_id": 18451,
"author_profile": "https://Stackoverflow.com/users/18451",
"pm_score": 0,
"selected": false,
"text": "<p>If the library is explicitly creating the bad class and not using a locater or dependency system you are out of luck. There is no way to override a method on another class unless you subclass.\nThe solution might be to create a patch file that fixes the library, so you can upgrade the library and re-apply the patch to fix that specific method.</p>\n"
},
{
"answer_id": 139391,
"author": "Toxygene",
"author_id": 8428,
"author_profile": "https://Stackoverflow.com/users/8428",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to do this with runkit. <a href=\"http://php.net/runkit\" rel=\"nofollow noreferrer\">http://php.net/runkit</a></p>\n"
},
{
"answer_id": 347522,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 4,
"selected": false,
"text": "<p>For the sake of completeness - monkey patching is available in PHP through <a href=\"http://docs.php.net/runkit\" rel=\"noreferrer\">runkit</a>. For details, see <code>runkit_method_redefine()</code>.</p>\n"
},
{
"answer_id": 4385190,
"author": "Newbie",
"author_id": 534686,
"author_profile": "https://Stackoverflow.com/users/534686",
"pm_score": 3,
"selected": false,
"text": "<p>How about wrapping it in another class like</p>\n\n<pre><code>class Wrapper {\n private $third_party_library;\n function __construct() { $this->third_party_library = new Third_party_library(); }\n function __call($method, $args) {\n return call_user_func_array(array($this->third_party_library, $method), $args);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6312192,
"author": "JPhilly",
"author_id": 759382,
"author_profile": "https://Stackoverflow.com/users/759382",
"pm_score": 4,
"selected": false,
"text": "<p>runkit seems like a good solution but its not enabled by default and parts of it are still experimental. So I hacked together a small class which replaces function definitions in a class file. Example usage:</p>\n\n<pre><code>class Patch {\n\nprivate $_code;\n\npublic function __construct($include_file = null) {\n if ( $include_file ) {\n $this->includeCode($include_file);\n }\n}\n\npublic function setCode($code) {\n $this->_code = $code;\n}\n\npublic function includeCode($path) {\n\n $fp = fopen($path,'r');\n $contents = fread($fp, filesize($path));\n $contents = str_replace('<?php','',$contents);\n $contents = str_replace('?>','',$contents);\n fclose($fp); \n\n $this->setCode($contents);\n}\n\nfunction redefineFunction($new_function) {\n\n preg_match('/function (.+)\\(/', $new_function, $aryMatches);\n $func_name = trim($aryMatches[1]);\n\n if ( preg_match('/((private|protected|public) function '.$func_name.'[\\w\\W\\n]+?)(private|protected|public)/s', $this->_code, $aryMatches) ) {\n\n $search_code = $aryMatches[1];\n\n $new_code = str_replace($search_code, $new_function.\"\\n\\n\", $this->_code);\n\n $this->setCode($new_code);\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n}\n\nfunction getCode() {\n return $this->_code;\n}\n}\n</code></pre>\n\n<p>Then include the class to be modified and redefine its methods:</p>\n\n<pre><code>$objPatch = new Patch('path_to_class_file.php');\n$objPatch->redefineFunction(\"\n protected function foo(\\$arg1, \\$arg2)\n { \n return \\$arg1+\\$arg2;\n }\");\n</code></pre>\n\n<p>Then eval the new code:</p>\n\n<pre><code>eval($objPatch->getCode());\n</code></pre>\n\n<p>A little crude but it works!</p>\n"
},
{
"answer_id": 44169113,
"author": "Ben Creasy",
"author_id": 4200039,
"author_profile": "https://Stackoverflow.com/users/4200039",
"pm_score": 0,
"selected": false,
"text": "<p>You can make a copy of the library class, with everything the same except the class name. Then override that renamed class.</p>\n\n<p>It's not perfect, but it does improve the visibility of the extending class's changes. If you fetch the library with something like Composer, you'll have to commit the copy to source control and update it when you update the library.</p>\n\n<p>In my case it was an old version of <a href=\"https://github.com/bshaffer/oauth2-server-php\" rel=\"nofollow noreferrer\">https://github.com/bshaffer/oauth2-server-php</a>. I modified the library's autoloader to fetch my class file instead. My class file took on the original name and extended a copied version of one of the files.</p>\n"
},
{
"answer_id": 45260210,
"author": "Ludo - Off the record",
"author_id": 1362815,
"author_profile": "https://Stackoverflow.com/users/1362815",
"pm_score": 4,
"selected": false,
"text": "<p>For people that are still looking for this answer.</p>\n\n<p>You should use <a href=\"http://php.net/manual/en/reflection.extending.php\" rel=\"noreferrer\">extends</a> in combination with <a href=\"http://php.net/manual/en/language.namespaces.php\" rel=\"noreferrer\">namespaces</a>.</p>\n\n<p>like this:</p>\n\n<pre><code>namespace MyCustomName;\n\nclass third_party_library extends \\third_party_library {\n function buggy_function() {\n return 'good result';\n }\n function other_functions(){\n return 'blah';\n }\n}\n</code></pre>\n\n<p>Then to use it do like this:</p>\n\n<pre><code>use MyCustomName\\third_party_library;\n\n$test = new third_party_library();\n$test->buggy_function();\n//or static.\nthird_party_library::other_functions();\n</code></pre>\n"
},
{
"answer_id": 46818982,
"author": "That Realty Programmer Guy",
"author_id": 578023,
"author_profile": "https://Stackoverflow.com/users/578023",
"pm_score": 0,
"selected": false,
"text": "<p>Since you always have access to the base code in PHP, redefine the main class functions you want to override as follows, this should leave your interfaces intact:</p>\n\n<pre><code>class third_party_library {\n public static $buggy_function;\n public static $ranOnce=false;\n\n public function __construct(){\n if(!self::$ranOnce){\n self::$buggy_function = function(){ return 'bad result'; };\n self::$ranOnce=true;\n }\n .\n .\n .\n }\n function buggy_function() {\n return self::$buggy_function();\n } \n}\n</code></pre>\n\n<p>You may for some reason use a private variable but then you will only be able to access the function by extending the class or logic inside the class. Similarly it's possible you'd want to have different objects of the same class have different functions. If so, do't use static, but usually you want it to be static so you don't duplicate the memory use for each object made. The 'ranOnce' code just makes sure you only need to initialize it once for the class, not for every <code>$myObject = new third_party_library()</code></p>\n\n<p>Now, later on in your code or another class - whenever the logic hits a point where you need to override the function - simply do as follows:</p>\n\n<pre><code>$backup['buggy_function'] = third_party_library::$buggy_function;\nthird_party_library::$buggy_function = function(){\n //do stuff\n return $great_calculation;\n}\n.\n.\n. //do other stuff that needs the override\n. //when finished, restore the original function\n.\nthird_party_library::$buggy_function=$backup['buggy_function'];\n</code></pre>\n\n<p>As a side note, if you do all your class functions this way and use a string-based key/value store like <code>public static $functions['function_name'] = function(...){...};</code> this can be useful for reflection. Not as much in PHP as other languages though because you can already grab the class and function names, but you can save some processing and future users of your class can use overrides in PHP. It is however, one extra level of indirection, so I would avoid using it on primitive classes wherever possible.</p>\n"
},
{
"answer_id": 61447042,
"author": "Arik",
"author_id": 1655245,
"author_profile": "https://Stackoverflow.com/users/1655245",
"pm_score": 1,
"selected": false,
"text": "<p>I've modified the code from the answer by @JPhilly and made it possible to rename a the patched class to avoid errors.</p>\n\n<p>Also, I've changed the regex that identifies the about-to-be-replaced function to fit cases where the replaced function doesn't have any class access modifiers in front of its name</p>\n\n<p>Hope it helps.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Patch {\n\n private $_code;\n\n public function __construct($include_file = null) {\n if ( $include_file ) {\n $this->includeCode($include_file);\n }\n }\n\n public function setCode($code) {\n $this->_code = $code;\n }\n\n public function includeCode($path) {\n\n $fp = fopen($path,'r');\n $contents = fread($fp, filesize($path));\n $contents = str_replace('<?php','',$contents);\n $contents = str_replace('?>','',$contents);\n fclose($fp); \n\n $this->setCode($contents);\n }\n\n function redefineFunction($new_function) {\n\n preg_match('/function ([^\\(]*)\\(/', $new_function, $aryMatches);\n $func_name = trim($aryMatches[1]);\n\n // capture the function with its body and replace it with the new function\n if ( preg_match('/((private|protected|public)?\\s?function ' . $func_name .'[\\w\\W\\n]+?)(private|protected|public|function|class)/s', $this->_code, $aryMatches) ) {\n\n $search_code = $aryMatches[1];\n\n $new_code = str_replace($search_code, $new_function.\"\\n\\n\", $this->_code);\n\n $this->setCode($new_code);\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n }\n function renameClass($old_name, $new_name) {\n\n $new_code = str_replace(\"class $old_name \", \"class $new_name \", $this->_code);\n\n $this->setCode($new_code);\n\n }\n\n function getCode() {\n return $this->_code;\n }\n}\n</code></pre>\n\n<p>This is how I've used it to patch a Wordpress plugin:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$objPatch = new Patch(ABSPATH . 'wp-content/plugins/a-plugin/code.php');\n$objPatch->renameClass(\"Patched_AClass\", \"Patched_Patched_AClass\"); // just to avoid class redefinition\n$objPatch->redefineFunction(\"\n function default_initialize() {\n echo 'my patched function';\n }\");\neval($objPatch->getCode());\n$result = new Patched_AClass();\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
]
| Is there any way to redefine a class or some of its methods without using typical inheritance? For example:
```
class third_party_library {
function buggy_function() {
return 'bad result';
}
function other_functions(){
return 'blah';
}
}
```
What can I do to replace `buggy_function()`? Obviously this is what I would like to do
```
class third_party_library redefines third_party_library{
function buggy_function() {
return 'good result';
}
function other_functions(){
return 'blah';
}
}
```
This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.
I've found this [library](http://pecl.php.net/package/classkit) that says it can do it, but I'm wary as it's 4 years old.
EDIT:
I should have clarified that I cannot rename the class from `third_party_library` to `magical_third_party_library` or anything else because of framework limitations.
For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a "partial class." | It's called [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch). But, PHP doesn't have native support for it.
Though, as others have also pointed out, the [runkit library](http://docs.php.net/runkit) is available for adding support to the language and is the successor to [classkit](http://docs.php.net/manual/en/book.classkit.php). And, though it seemed to have been [abandoned](http://pecl.php.net/package/runkit) by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a [new home and maintainer](https://github.com/zenovich/runkit).
I still [can't say I'm a fan](https://stackoverflow.com/revisions/137028/3) of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug.
Still, [`runkit_method_redefine`](http://us2.php.net/manual/en/function.runkit-method-redefine.php) appears to be what you're looking for, and an example of its use can be found in [`/tests/runkit_method_redefine.phpt`](https://github.com/zenovich/runkit/blob/master/tests/runkit_method_redefine.phpt) in the repository:
```php
runkit_method_redefine('third_party_library', 'buggy_function', '',
'return \'good result\''
);
``` |
137,038 | <p>How does one do this?</p>
<p>If I want to analyze how something is getting compiled, how would I get the emitted assembly code?</p>
| [
{
"answer_id": 137044,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 5,
"selected": false,
"text": "<p>Use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> switch:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -S main.cpp\n</code></pre>\n<p>Or also with <code>gcc</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -S main.c\n</code></pre>\n<p>Also see <a href=\"http://www.delorie.com/djgpp/v2faq/faq8_20.html\" rel=\"nofollow noreferrer\">this</a>.</p>\n"
},
{
"answer_id": 137047,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> option:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -S program.c\n</code></pre>\n"
},
{
"answer_id": 137056,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 4,
"selected": false,
"text": "<p>If what you want to see depends on the linking of the output, then <a href=\"https://linux.die.net/man/1/objdump\" rel=\"nofollow noreferrer\">objdump</a> on the output object file/executable may also be useful in addition to <a href=\"https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc/137044#137044\">the aforementioned</a> <code>gcc -S</code>. Here's a very useful script by Loren Merritt that converts the default objdump syntax into the more readable <a href=\"https://en.wikipedia.org/wiki/Netwide_Assembler\" rel=\"nofollow noreferrer\">NASM</a> syntax:</p>\n<pre><code>#!/usr/bin/perl -w\n$ptr='(BYTE|WORD|DWORD|QWORD|XMMWORD) PTR ';\n$reg='(?:[er]?(?:[abcd]x|[sd]i|[sb]p)|[abcd][hl]|r1?[0-589][dwb]?|mm[0-7]|xmm1?[0-9])';\nopen FH, '-|', '/usr/bin/objdump', '-w', '-M', 'intel', @ARGV or die;\n$prev = "";\nwhile(<FH>){\n if(/$ptr/o) {\n s/$ptr(\\[[^\\[\\]]+\\],$reg)/$2/o or\n s/($reg,)$ptr(\\[[^\\[\\]]+\\])/$1$3/o or\n s/$ptr/lc $1/oe;\n }\n if($prev =~ /\\t(repz )?ret / and\n $_ =~ /\\tnop |\\txchg *ax,ax$/) {\n # drop this line\n } else {\n print $prev;\n $prev = $_;\n }\n}\nprint $prev;\nclose FH;\n</code></pre>\n<p>I suspect this can also be used on the output of <code>gcc -S</code>.</p>\n"
},
{
"answer_id": 137074,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 10,
"selected": true,
"text": "<p>Use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"noreferrer\">-S</a> option to <code>gcc</code> (or <code>g++</code>), optionally with <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm\" rel=\"noreferrer\">-fverbose-asm</a> which works well at the default <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0\" rel=\"noreferrer\">-O0</a> to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at.</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -S helloworld.c\n</code></pre>\n<p>This will run the preprocessor (cpp) over <em>helloworld.c</em>, perform the initial compilation and then stop before the assembler is run. For useful compiler options to use in that case, see <em><a href=\"https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output\">How to remove "noise" from GCC/clang assembly output?</a></em> (or just <strong>look at your code on <a href=\"https://godbolt.org/\" rel=\"noreferrer\">Matt Godbolt's online Compiler Explorer</a></strong> which filters out directives and stuff, and has highlighting to match up source lines with asm using debug information.)</p>\n<p>By default, this will output the file <code>helloworld.s</code>. The output file can be still be set by using the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-o\" rel=\"noreferrer\">-o</a> option, including <code>-o -</code> to write to <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29\" rel=\"noreferrer\">standard output</a> for pipe into <a href=\"https://en.wikipedia.org/wiki/Less_(Unix)\" rel=\"noreferrer\">less</a>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -S -o my_asm_output.s helloworld.c\n</code></pre>\n<p>Of course, this only works if you have the original source.\nAn alternative if you only have the resultant object file is to use <a href=\"https://linux.die.net/man/1/objdump\" rel=\"noreferrer\">objdump</a>, by setting the <code>--disassemble</code> option (or <code>-d</code> for the abbreviated form).</p>\n<pre class=\"lang-none prettyprint-override\"><code>objdump -S --disassemble helloworld > helloworld.dump\n</code></pre>\n<p><code>-S</code> interleaves source lines with normal disassembly output, so this option works best if debugging option is enabled for the object file (<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g\" rel=\"noreferrer\">-g</a> at compilation time) and the file hasn't been stripped.</p>\n<p>Running <code>file helloworld</code> will give you some indication as to the level of detail that you will get by using <em>objdump</em>.</p>\n<p>Other useful <code>objdump</code> options include <code>-rwC</code> (to show symbol relocations, disable line-wrapping of long machine code, and demangle C++ names). And if you don't like AT&T syntax for x86, <code>-Mintel</code>. See <a href=\"https://man7.org/linux/man-pages/man1/objdump.1.html\" rel=\"noreferrer\">the man page</a>.</p>\n<p>So for example, <code>objdump -drwC -Mintel -S foo.o | less</code>.\n<code>-r</code> is very important with a <code>.o</code> that only has <code>00 00 00 00</code> placeholders for symbol references, as opposed to a linked executable.</p>\n"
},
{
"answer_id": 137354,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>As everyone has pointed out, use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\"><code>-S</code></a> option to GCC. I would also like to add that the results may vary (wildly!) depending on whether or not you add optimization options (<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0\" rel=\"nofollow noreferrer\"><code>-O0</code></a> for none, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O2\" rel=\"nofollow noreferrer\"><code>-O2</code></a> for aggressive optimization).</p>\n<p>On RISC architectures in particular, the compiler will often transform the code almost beyond recognition in doing optimization. It's impressive and fascinating to look at the results!</p>\n"
},
{
"answer_id": 137479,
"author": "PhirePhly",
"author_id": 20082,
"author_profile": "https://Stackoverflow.com/users/20082",
"pm_score": 8,
"selected": false,
"text": "<p>This will generate assembly code with the C code + line numbers interwoven, to more easily see which lines generate what code (<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm\" rel=\"nofollow noreferrer\">-fverbose-asm</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g\" rel=\"nofollow noreferrer\">-g</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O2\" rel=\"nofollow noreferrer\">-O2</a>):</p>\n<pre class=\"lang-bash prettyprint-override\"><code># Create assembler code:\ng++ -S -fverbose-asm -g -O2 test.cc -o test.s\n\n# Create asm interlaced with source lines:\nas -alhnd test.s > test.lst\n</code></pre>\n<p>It was found in <a href=\"http://www.jjj.de/fxt/fxtbook.pdf\" rel=\"nofollow noreferrer\">Algorithms for programmers</a>, page 3 (which is the overall 15th page of the PDF).</p>\n"
},
{
"answer_id": 194284,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned before, look at the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> flag.</p>\n<p>It's also worth looking at the '-fdump-tree' family of flags, in particular <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Developer-Options.html#index-fdump-tree-all\" rel=\"nofollow noreferrer\">-fdump-tree-all</a>, which lets you see some of GCC's intermediate forms. These can often be more readable than assembler (at least to me), and let you see how optimisation passes perform.</p>\n"
},
{
"answer_id": 4456913,
"author": "Pizearke",
"author_id": 521420,
"author_profile": "https://Stackoverflow.com/users/521420",
"pm_score": 2,
"selected": false,
"text": "<p>Use \"-S\" as an option. It displays the assembly output in the terminal.</p>\n"
},
{
"answer_id": 4593358,
"author": "Anonymous",
"author_id": 562509,
"author_profile": "https://Stackoverflow.com/users/562509",
"pm_score": 3,
"selected": false,
"text": "<p>From the FAQ <em><a href=\"http://www.delorie.com/djgpp/v2faq/faq8_20.html\" rel=\"nofollow noreferrer\">How to get GCC to generate assembly code</a></em>:</p>\n<p><em>gcc <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-c\" rel=\"nofollow noreferrer\">-c</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g\" rel=\"nofollow noreferrer\">-g</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Assembler-Options.html#index-Wa\" rel=\"nofollow noreferrer\">-Wa,-a,-ad</a> [other GCC options] foo.c > foo.lst</em></p>\n<p>as an alternative to <a href=\"https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc/137479#137479\">PhirePhly's answer</a>.</p>\n<p>Or just use <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> as everyone said.</p>\n"
},
{
"answer_id": 7871911,
"author": "mcandre",
"author_id": 350106,
"author_profile": "https://Stackoverflow.com/users/350106",
"pm_score": 3,
"selected": false,
"text": "<p>If you're looking for LLVM assembly:</p>\n\n<pre><code>llvm-gcc -emit-llvm -S hello.c\n</code></pre>\n"
},
{
"answer_id": 17083009,
"author": "METADATA",
"author_id": 2478689,
"author_profile": "https://Stackoverflow.com/users/2478689",
"pm_score": 4,
"selected": false,
"text": "<p>Well, as everyone said, use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> option.</p>\n<p>If you use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Developer-Options.html#index-save-temps\" rel=\"nofollow noreferrer\">-save-temps</a> option, you can also get the preprocessed file (<em>.i), assembly file (</em>.s) and object file (*.o) (get each of them by using <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-E\" rel=\"nofollow noreferrer\">-E</a>, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a>, and <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-c\" rel=\"nofollow noreferrer\">-c</a>, respectively).</p>\n"
},
{
"answer_id": 19083877,
"author": "Cr McDonough",
"author_id": 2829396,
"author_profile": "https://Stackoverflow.com/users/2829396",
"pm_score": 6,
"selected": false,
"text": "<p>The following command line is from <a href=\"http://christiangarbin.blogspot.com/2013/05/c-generating-assembly-code-with-gccg.html\" rel=\"nofollow noreferrer\">Christian Garbin's blog</a>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -g -O -Wa,-aslh horton_ex2_05.cpp >list.txt\n</code></pre>\n<p>I ran G++ from a DOS window on Windows XP, against a routine that contains an implicit cast</p>\n<pre class=\"lang-none prettyprint-override\"><code>cd C:\\gpp_code\ng++ -g -O -Wa,-aslh horton_ex2_05.cpp > list.txt\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>horton_ex2_05.cpp: In function `int main()':\nhorton_ex2_05.cpp:92: warning: assignment to `int' from `double'\n</code></pre>\n<p>The output is assembled generated code, interspersed with the original C++ code (the C++ code is shown as comments in the generated assembly language stream)</p>\n<pre class=\"lang-none prettyprint-override\"><code> 16:horton_ex2_05.cpp **** using std::setw;\n 17:horton_ex2_05.cpp ****\n 18:horton_ex2_05.cpp **** void disp_Time_Line (void);\n 19:horton_ex2_05.cpp ****\n 20:horton_ex2_05.cpp **** int main(void)\n 21:horton_ex2_05.cpp **** {\n 164 %ebp\n 165 subl $128,%esp\n?GAS LISTING C:\\DOCUME~1\\CRAIGM~1\\LOCALS~1\\Temp\\ccx52rCc.s\n166 0128 55 call ___main\n167 0129 89E5 .stabn 68,0,21,LM2-_main\n168 012b 81EC8000 LM2:\n168 0000\n169 0131 E8000000 LBB2:\n169 00\n170 .stabn 68,0,25,LM3-_main\n171 LM3:\n172 movl $0,-16(%ebp)\n</code></pre>\n"
},
{
"answer_id": 48426040,
"author": "Antonin GAVREL",
"author_id": 3161139,
"author_profile": "https://Stackoverflow.com/users/3161139",
"pm_score": 3,
"selected": false,
"text": "<p>I don't see this possibility among answers, probably because the question is from 2008, but in 2018 you can use Matt Goldbolt's online website <a href=\"https://godbolt.org\" rel=\"noreferrer\">https://godbolt.org</a></p>\n\n<p>You can also locally git clone and run his project <a href=\"https://github.com/mattgodbolt/compiler-explorer\" rel=\"noreferrer\">https://github.com/mattgodbolt/compiler-explorer</a></p>\n"
},
{
"answer_id": 48969827,
"author": "Ashutosh K Singh",
"author_id": 7394522,
"author_profile": "https://Stackoverflow.com/users/7394522",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/KOXCa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KOXCa.png\" alt=\"Output of these commands\" /></a></p>\n<p>Here are the steps to see/print the assembly code of any C program on your Windows:</p>\n<p>In a console/terminal command prompt:</p>\n<ol>\n<li><p>Write a C program in a C code editor like <a href=\"https://en.wikipedia.org/wiki/Code::Blocks\" rel=\"nofollow noreferrer\">Code::Blocks</a> and save it with filename extension .c</p>\n</li>\n<li><p>Compile and run it.</p>\n</li>\n<li><p>Once run successfully, go to the folder where you have installed your GCC compiler and enter the following command to get a ' .s ' file of the ' .c' file</p>\n<pre class=\"lang-none prettyprint-override\"><code>cd C:\\gcc\ngcc -S complete path of the C file ENTER\n</code></pre>\n<p>An example command (as in my case)</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -S D:\\Aa_C_Certified\\alternate_letters.c\n</code></pre>\n<p>This outputs a '.s' file of the original '.c' file.</p>\n</li>\n<li><p>After this, type the following command</p>\n<pre class=\"lang-none prettyprint-override\"><code>cpp filename.s ENTER\n</code></pre>\n<p>Example command (as in my case)</p>\n<pre class=\"lang-none prettyprint-override\"><code>cpp alternate_letters.s <enter>\n</code></pre>\n</li>\n</ol>\n<p>This will print/output the entire assembly language code of your C program.</p>\n"
},
{
"answer_id": 53513204,
"author": "Abhishek D K",
"author_id": 7303415,
"author_profile": "https://Stackoverflow.com/users/7303415",
"pm_score": 2,
"selected": false,
"text": "<p>Recently I wanted to know the assembly of each functions in a. This is how I did it:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc main.c // 'main.c' source file\ngdb a.exe // 'gdb a.out' in Linux\n</code></pre>\n<p>In GDB:</p>\n<pre class=\"lang-none prettyprint-override\"><code>disass main // Note here 'main' is a function\n // Similarly, it can be done for other functions.\n</code></pre>\n"
},
{
"answer_id": 53927419,
"author": "Himanshu Pal",
"author_id": 10697722,
"author_profile": "https://Stackoverflow.com/users/10697722",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a solution for C using GCC:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -S program.c && gcc program.c -o output\n</code></pre>\n<ol>\n<li><p>Here the first part stores the assembly output of the program in the same file name as the <em>program</em>, but with a changed <strong>.s</strong> extension, you can open it as any normal text file.</p>\n</li>\n<li><p>The second part here compiles your program for actual usage and generates an executable for your Program with a specified file name.</p>\n</li>\n</ol>\n<p>The <em>program.c</em> used above is the name of your program and <em>output</em> is the name of the executable you want to generate.</p>\n"
},
{
"answer_id": 56801917,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 5,
"selected": false,
"text": "<p><strong><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Developer-Options.html#index-save-temps\" rel=\"nofollow noreferrer\">-save-temps</a></strong></p>\n<p>This was mentioned in <a href=\"https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc/17083009#17083009\">METADATA's answer</a>, but let me further exemplify it.</p>\n<p>The big advantage of this option over <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> is that it is very easy to add it to any build script, without interfering much in the build itself.</p>\n<p>When you do:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -save-temps -c -o main.o main.c\n</code></pre>\n<h3>File <em>main.c</em></h3>\n<pre><code>#define INC 1\n\nint myfunc(int i) {\n return i + INC;\n}\n</code></pre>\n<p>and now, besides the normal output <code>main.o</code>, the current working directory also contains the following files:</p>\n<ul>\n<li><p><code>main.i</code> is a bonus and contains the preprocessed file:</p>\n<pre class=\"lang-none prettyprint-override\"><code># 1 "main.c"\n# 1 "<built-in>"\n# 1 "<command-line>"\n# 31 "<command-line>"\n# 1 "/usr/include/stdc-predef.h" 1 3 4\n# 32 "<command-line>" 2\n# 1 "main.c"\n\n\nint myfunc(int i) {\n return i + 1;\n}\n</code></pre>\n</li>\n<li><p><code>main.s</code> contains the desired generated assembly:</p>\n<pre class=\"lang-none prettyprint-override\"><code> .file "main.c"\n .text\n .globl myfunc\n .type myfunc, @function\nmyfunc:\n.LFB0:\n .cfi_startproc\n pushq %rbp\n .cfi_def_cfa_offset 16\n .cfi_offset 6, -16\n movq %rsp, %rbp\n .cfi_def_cfa_register 6\n movl %edi, -4(%rbp)\n movl -4(%rbp), %eax\n addl $1, %eax\n popq %rbp\n .cfi_def_cfa 7, 8\n ret\n .cfi_endproc\n.LFE0:\n .size myfunc, .-myfunc\n .ident "GCC: (Ubuntu 8.3.0-6ubuntu1) 8.3.0"\n .section .note.GNU-stack,"",@progbits\n</code></pre>\n</li>\n</ul>\n<p>If you want to do it for a large number of files, consider using instead:</p>\n<pre class=\"lang-none prettyprint-override\"><code>-save-temps=obj\n</code></pre>\n<p>which saves the intermediate files to the same directory as the <code>-o</code> object output instead of the current working directory, thus avoiding potential basename conflicts.</p>\n<p>Another cool thing about this option is if you add <code>-v</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -save-temps -c -o main.o -v main.c\n</code></pre>\n<p>it actually shows the explicit files being used instead of ugly temporaries under <code>/tmp</code>, so it is easy to know exactly what is going on, which includes the preprocessing / compilation / assembly steps:</p>\n<pre class=\"lang-none prettyprint-override\"><code>/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -E -quiet -v -imultiarch x86_64-linux-gnu main.c -mtune=generic -march=x86-64 -fpch-preprocess -fstack-protector-strong -Wformat -Wformat-security -o main.i\n/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -fpreprocessed main.i -quiet -dumpbase main.c -mtune=generic -march=x86-64 -auxbase-strip main.o -version -fstack-protector-strong -Wformat -Wformat-security -o main.s\nas -v --64 -o main.o main.s\n</code></pre>\n<p>It was tested in <a href=\"https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_19.04_(Disco_Dingo)\" rel=\"nofollow noreferrer\">Ubuntu 19.04</a> (Disco Dingo) amd64, GCC 8.3.0.</p>\n<p><strong>CMake predefined targets</strong></p>\n<p>CMake automatically provides a targets for the preprocessed file:</p>\n<pre class=\"lang-none prettyprint-override\"><code>make help\n</code></pre>\n<p>shows us that we can do:</p>\n<pre class=\"lang-none prettyprint-override\"><code>make main.s\n</code></pre>\n<p>and that target runs:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Compiling C source to assembly CMakeFiles/main.dir/main.c.s\n/usr/bin/cc -S /home/ciro/hello/main.c -o CMakeFiles/main.dir/main.c.s\n</code></pre>\n<p>so the file can be seen at <code>CMakeFiles/main.dir/main.c.s</code>.</p>\n<p>It was tested on CMake 3.16.1.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
]
| How does one do this?
If I want to analyze how something is getting compiled, how would I get the emitted assembly code? | Use the [-S](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S) option to `gcc` (or `g++`), optionally with [-fverbose-asm](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm) which works well at the default [-O0](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0) to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at.
```none
gcc -S helloworld.c
```
This will run the preprocessor (cpp) over *helloworld.c*, perform the initial compilation and then stop before the assembler is run. For useful compiler options to use in that case, see *[How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output)* (or just **look at your code on [Matt Godbolt's online Compiler Explorer](https://godbolt.org/)** which filters out directives and stuff, and has highlighting to match up source lines with asm using debug information.)
By default, this will output the file `helloworld.s`. The output file can be still be set by using the [-o](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-o) option, including `-o -` to write to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) for pipe into [less](https://en.wikipedia.org/wiki/Less_(Unix)).
```none
gcc -S -o my_asm_output.s helloworld.c
```
Of course, this only works if you have the original source.
An alternative if you only have the resultant object file is to use [objdump](https://linux.die.net/man/1/objdump), by setting the `--disassemble` option (or `-d` for the abbreviated form).
```none
objdump -S --disassemble helloworld > helloworld.dump
```
`-S` interleaves source lines with normal disassembly output, so this option works best if debugging option is enabled for the object file ([-g](https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g) at compilation time) and the file hasn't been stripped.
Running `file helloworld` will give you some indication as to the level of detail that you will get by using *objdump*.
Other useful `objdump` options include `-rwC` (to show symbol relocations, disable line-wrapping of long machine code, and demangle C++ names). And if you don't like AT&T syntax for x86, `-Mintel`. See [the man page](https://man7.org/linux/man-pages/man1/objdump.1.html).
So for example, `objdump -drwC -Mintel -S foo.o | less`.
`-r` is very important with a `.o` that only has `00 00 00 00` placeholders for symbol references, as opposed to a linked executable. |
137,043 | <p>When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this:</p>
<pre><code> <table>
<tr>
<td>blah</td></tr></table>
</code></pre>
<p>...into this:</p>
<pre><code><table>
<tr>
<td>
blah
</td>
</tr>
</table>
</code></pre>
| [
{
"answer_id": 137139,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.delorie.com/gnu/docs/emacs/emacs_277.html\" rel=\"noreferrer\">http://www.delorie.com/gnu/docs/emacs/emacs_277.html</a></p>\n\n<p>After selecting the region you want to fix. (To select the whole buffer use C-x h)</p>\n\n<blockquote>\n <p><em>C-M-q</em></p>\n \n <p>Reindent all the lines within one parenthetical grouping(indent-sexp).</p>\n \n <p><em>C-M-\\</em></p>\n \n <p>Reindent all lines in the region (indent-region). </p>\n</blockquote>\n"
},
{
"answer_id": 137697,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://tidy.sourceforge.net/\" rel=\"noreferrer\">Tidy</a> can do what you want, but only for whole buffer it seems (and the result is XHTML) </p>\n\n<pre><code>M-x tidy-buffer\n</code></pre>\n"
},
{
"answer_id": 144938,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 6,
"selected": true,
"text": "<p>By default, when you visit a <code>.html</code> file in Emacs (22 or 23), it will put you in <code>html-mode</code>. That is probably not what you want. You probably want <code>nxml-mode</code>, which is seriously fancy. <code>nxml-mode</code> seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the <a href=\"http://www.thaiopensource.com/nxml-mode/\" rel=\"noreferrer\">nXML web site</a>. There is also a Debian and Ubuntu package named <code>nxml-mode</code>. You can enter <code>nxml-mode</code> with:</p>\n\n<pre><code>M-x nxml-mode\n</code></pre>\n\n<p>You can view nxml mode documentation with:</p>\n\n<pre><code>C-h i g (nxml-mode) RET\n</code></pre>\n\n<p>All that being said, you will probably have to use something like <a href=\"http://tidy.sourceforge.net/\" rel=\"noreferrer\">Tidy</a> to re-format your xhtml example. <code>nxml-mode</code> will get you from</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n<body>\n<table>\n <tr>\n<td>blah</td></tr></table>\n</body>\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n <body>\n <table>\n <tr>\n <td>blah</td></tr></table>\n</body>\n</html>\n</code></pre>\n\n<p>but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that <code>C-j</code> will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a <code>defun</code> that will do your tables.</p>\n"
},
{
"answer_id": 4146331,
"author": "nevcx",
"author_id": 503449,
"author_profile": "https://Stackoverflow.com/users/503449",
"pm_score": 3,
"selected": false,
"text": "<p>You can do a replace regexp</p>\n\n<pre><code> M-x replace-regexp\n\n \\(</[^>]+>\\)\n\n \\1C-q-j\n</code></pre>\n\n<p>Indent the whole buffer</p>\n\n<pre><code> C-x h\n M-x indent-region\n</code></pre>\n"
},
{
"answer_id": 6247579,
"author": "vava",
"author_id": 6258,
"author_profile": "https://Stackoverflow.com/users/6258",
"pm_score": 7,
"selected": false,
"text": "<p>You can do <code>sgml-pretty-print</code> and then <code>indent-for-tab</code> on the same region/buffer, provided you are in html-mode or nxml-mode.</p>\n\n<p><code>sgml-pretty-print</code> adds new lines to proper places and <code>indent-for-tab</code> adds nice indentation. Together they lead to properly formatted html/xml.</p>\n"
},
{
"answer_id": 6255409,
"author": "jtahlborn",
"author_id": 552759,
"author_profile": "https://Stackoverflow.com/users/552759",
"pm_score": 3,
"selected": false,
"text": "<p>i wrote a function myself to do this for xml, which works well in nxml-mode. should work pretty well for html as well:</p>\n\n<pre><code>(defun jta-reformat-xml ()\n \"Reformats xml to make it readable (respects current selection).\"\n (interactive)\n (save-excursion\n (let ((beg (point-min))\n (end (point-max)))\n (if (and mark-active transient-mark-mode)\n (progn\n (setq beg (min (point) (mark)))\n (setq end (max (point) (mark))))\n (widen))\n (setq end (copy-marker end t))\n (goto-char beg)\n (while (re-search-forward \">\\\\s-*<\" end t)\n (replace-match \">\\n<\" t t))\n (goto-char beg)\n (indent-region beg end nil))))\n</code></pre>\n"
},
{
"answer_id": 7436381,
"author": "Geoff",
"author_id": 446564,
"author_profile": "https://Stackoverflow.com/users/446564",
"pm_score": 2,
"selected": false,
"text": "<p>You can pipe a region to xmllint (if you have it) using:</p>\n\n<pre><code>M-|\nShell command on region: xmllint --format -\n</code></pre>\n\n<p>The result will end up in a new buffer.</p>\n\n<p>I do this with XML, and it works, though I believe xmllint needs certain other options to work with HTML or other not-perfect XML. nxml-mode will tell you if you have a well-formed document.</p>\n"
},
{
"answer_id": 11020114,
"author": "user1454331",
"author_id": 1454331,
"author_profile": "https://Stackoverflow.com/users/1454331",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way to do it is via command line.</p>\n\n<ul>\n<li>Make sure you have tidy installed</li>\n<li>type <code>tidy -i -m <<file_name>></code></li>\n</ul>\n\n<p>Note that <code>-m</code> option replaces the newly tidied file with the old one. If you don't want that, you can type <code>tidy -i -o <<tidied_file_name>> <<untidied_file_name>></code></p>\n\n<p>The <code>-i</code> is for indentation. Alternatively, you can create a <code>.tidyrc</code> file that has settings such as </p>\n\n<pre><code>indent: auto\nindent-spaces: 2\nwrap: 72\nmarkup: yes\noutput-xml: no\ninput-xml: no\nshow-warnings: yes\nnumeric-entities: yes\nquote-marks: yes\nquote-nbsp: yes\nquote-ampersand: no\nbreak-before-br: no\nuppercase-tags: no\nuppercase-attributes: no\n</code></pre>\n\n<p>This way all you have to do is type <code>tidy -o <<tidied_file_name>> <<untidied_file_name>></code>.</p>\n\n<p>For more just type <code>man tidy</code> on the command line. </p>\n"
},
{
"answer_id": 27183016,
"author": "abhillman",
"author_id": 3622198,
"author_profile": "https://Stackoverflow.com/users/3622198",
"pm_score": 3,
"selected": false,
"text": "<p>This question is quite old, but I wasn't really happy with the various answers. A simple way to re-indent an HTML file, given that you are running a relatively newer version of emacs (I am running 24.4.1) is to:</p>\n\n<ul>\n<li>open the file in emacs</li>\n<li>mark the entire file with <code>C-x h</code> (note: if you would like to see what is being marked, add <code>(setq transient-mark-mode t)</code> to your <code>.emacs</code> file)</li>\n<li>execute <code>M-x indent-region</code></li>\n</ul>\n\n<p>What's nice about this method is that it does not require any plugins (Conway's suggestion), it does not require a replace regexp (nevcx's suggestion), nor does it require switching modes (jfm3's suggestion). Jay's suggestion is in the right direction — in general, executing <code>C-M-q</code> will indent according to a mode's rules — for example, <code>C-M-q</code> works, in my experience, in <code>js-mode</code> and in several other modes. But neither <code>html-mode</code> nor <code>nxml-mode</code> do not seem to implement <code>C-M-q</code>. </p>\n"
},
{
"answer_id": 39440788,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 3,
"selected": false,
"text": "<p>In emacs 25, which I'm currently building from source, assuming you are in HTML mode, use<br>\n <kbd>Ctrl</kbd>-<kbd>x</kbd><br>\n<kbd>h</kbd> </p>\n\n<p>to select all, and then press <kbd>Tab</kbd>.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this:
```
<table>
<tr>
<td>blah</td></tr></table>
```
...into this:
```
<table>
<tr>
<td>
blah
</td>
</tr>
</table>
``` | By default, when you visit a `.html` file in Emacs (22 or 23), it will put you in `html-mode`. That is probably not what you want. You probably want `nxml-mode`, which is seriously fancy. `nxml-mode` seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the [nXML web site](http://www.thaiopensource.com/nxml-mode/). There is also a Debian and Ubuntu package named `nxml-mode`. You can enter `nxml-mode` with:
```
M-x nxml-mode
```
You can view nxml mode documentation with:
```
C-h i g (nxml-mode) RET
```
All that being said, you will probably have to use something like [Tidy](http://tidy.sourceforge.net/) to re-format your xhtml example. `nxml-mode` will get you from
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr>
<td>blah</td></tr></table>
</body>
```
to
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr>
<td>blah</td></tr></table>
</body>
</html>
```
but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that `C-j` will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a `defun` that will do your tables. |
137,054 | <p>How can I validate that my ASPNET AJAX installation is correct.</p>
<p>I have Visual Studio 2008 and had never previously installed any AJAX version.</p>
<p>My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior.</p>
<p>I tried installing AJAX from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en" rel="nofollow noreferrer">MSDN</a> followed by an IISRESET yet still it is still not working properly.</p>
<p>What can I check to diagnose the problem?</p>
<p><strong>Update:</strong> When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler:</p>
<pre><code>http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&t=633564733834698722
http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&t=ffffffff867086f6
http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&t=ffffffff867086f6
</code></pre>
<p>but when I run within IIS i only get this single request :</p>
<pre><code>http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&t=ffffffff867086f6
</code></pre>
<p>Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests.</p>
| [
{
"answer_id": 137139,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.delorie.com/gnu/docs/emacs/emacs_277.html\" rel=\"noreferrer\">http://www.delorie.com/gnu/docs/emacs/emacs_277.html</a></p>\n\n<p>After selecting the region you want to fix. (To select the whole buffer use C-x h)</p>\n\n<blockquote>\n <p><em>C-M-q</em></p>\n \n <p>Reindent all the lines within one parenthetical grouping(indent-sexp).</p>\n \n <p><em>C-M-\\</em></p>\n \n <p>Reindent all lines in the region (indent-region). </p>\n</blockquote>\n"
},
{
"answer_id": 137697,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://tidy.sourceforge.net/\" rel=\"noreferrer\">Tidy</a> can do what you want, but only for whole buffer it seems (and the result is XHTML) </p>\n\n<pre><code>M-x tidy-buffer\n</code></pre>\n"
},
{
"answer_id": 144938,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 6,
"selected": true,
"text": "<p>By default, when you visit a <code>.html</code> file in Emacs (22 or 23), it will put you in <code>html-mode</code>. That is probably not what you want. You probably want <code>nxml-mode</code>, which is seriously fancy. <code>nxml-mode</code> seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the <a href=\"http://www.thaiopensource.com/nxml-mode/\" rel=\"noreferrer\">nXML web site</a>. There is also a Debian and Ubuntu package named <code>nxml-mode</code>. You can enter <code>nxml-mode</code> with:</p>\n\n<pre><code>M-x nxml-mode\n</code></pre>\n\n<p>You can view nxml mode documentation with:</p>\n\n<pre><code>C-h i g (nxml-mode) RET\n</code></pre>\n\n<p>All that being said, you will probably have to use something like <a href=\"http://tidy.sourceforge.net/\" rel=\"noreferrer\">Tidy</a> to re-format your xhtml example. <code>nxml-mode</code> will get you from</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n<body>\n<table>\n <tr>\n<td>blah</td></tr></table>\n</body>\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n <body>\n <table>\n <tr>\n <td>blah</td></tr></table>\n</body>\n</html>\n</code></pre>\n\n<p>but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that <code>C-j</code> will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a <code>defun</code> that will do your tables.</p>\n"
},
{
"answer_id": 4146331,
"author": "nevcx",
"author_id": 503449,
"author_profile": "https://Stackoverflow.com/users/503449",
"pm_score": 3,
"selected": false,
"text": "<p>You can do a replace regexp</p>\n\n<pre><code> M-x replace-regexp\n\n \\(</[^>]+>\\)\n\n \\1C-q-j\n</code></pre>\n\n<p>Indent the whole buffer</p>\n\n<pre><code> C-x h\n M-x indent-region\n</code></pre>\n"
},
{
"answer_id": 6247579,
"author": "vava",
"author_id": 6258,
"author_profile": "https://Stackoverflow.com/users/6258",
"pm_score": 7,
"selected": false,
"text": "<p>You can do <code>sgml-pretty-print</code> and then <code>indent-for-tab</code> on the same region/buffer, provided you are in html-mode or nxml-mode.</p>\n\n<p><code>sgml-pretty-print</code> adds new lines to proper places and <code>indent-for-tab</code> adds nice indentation. Together they lead to properly formatted html/xml.</p>\n"
},
{
"answer_id": 6255409,
"author": "jtahlborn",
"author_id": 552759,
"author_profile": "https://Stackoverflow.com/users/552759",
"pm_score": 3,
"selected": false,
"text": "<p>i wrote a function myself to do this for xml, which works well in nxml-mode. should work pretty well for html as well:</p>\n\n<pre><code>(defun jta-reformat-xml ()\n \"Reformats xml to make it readable (respects current selection).\"\n (interactive)\n (save-excursion\n (let ((beg (point-min))\n (end (point-max)))\n (if (and mark-active transient-mark-mode)\n (progn\n (setq beg (min (point) (mark)))\n (setq end (max (point) (mark))))\n (widen))\n (setq end (copy-marker end t))\n (goto-char beg)\n (while (re-search-forward \">\\\\s-*<\" end t)\n (replace-match \">\\n<\" t t))\n (goto-char beg)\n (indent-region beg end nil))))\n</code></pre>\n"
},
{
"answer_id": 7436381,
"author": "Geoff",
"author_id": 446564,
"author_profile": "https://Stackoverflow.com/users/446564",
"pm_score": 2,
"selected": false,
"text": "<p>You can pipe a region to xmllint (if you have it) using:</p>\n\n<pre><code>M-|\nShell command on region: xmllint --format -\n</code></pre>\n\n<p>The result will end up in a new buffer.</p>\n\n<p>I do this with XML, and it works, though I believe xmllint needs certain other options to work with HTML or other not-perfect XML. nxml-mode will tell you if you have a well-formed document.</p>\n"
},
{
"answer_id": 11020114,
"author": "user1454331",
"author_id": 1454331,
"author_profile": "https://Stackoverflow.com/users/1454331",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way to do it is via command line.</p>\n\n<ul>\n<li>Make sure you have tidy installed</li>\n<li>type <code>tidy -i -m <<file_name>></code></li>\n</ul>\n\n<p>Note that <code>-m</code> option replaces the newly tidied file with the old one. If you don't want that, you can type <code>tidy -i -o <<tidied_file_name>> <<untidied_file_name>></code></p>\n\n<p>The <code>-i</code> is for indentation. Alternatively, you can create a <code>.tidyrc</code> file that has settings such as </p>\n\n<pre><code>indent: auto\nindent-spaces: 2\nwrap: 72\nmarkup: yes\noutput-xml: no\ninput-xml: no\nshow-warnings: yes\nnumeric-entities: yes\nquote-marks: yes\nquote-nbsp: yes\nquote-ampersand: no\nbreak-before-br: no\nuppercase-tags: no\nuppercase-attributes: no\n</code></pre>\n\n<p>This way all you have to do is type <code>tidy -o <<tidied_file_name>> <<untidied_file_name>></code>.</p>\n\n<p>For more just type <code>man tidy</code> on the command line. </p>\n"
},
{
"answer_id": 27183016,
"author": "abhillman",
"author_id": 3622198,
"author_profile": "https://Stackoverflow.com/users/3622198",
"pm_score": 3,
"selected": false,
"text": "<p>This question is quite old, but I wasn't really happy with the various answers. A simple way to re-indent an HTML file, given that you are running a relatively newer version of emacs (I am running 24.4.1) is to:</p>\n\n<ul>\n<li>open the file in emacs</li>\n<li>mark the entire file with <code>C-x h</code> (note: if you would like to see what is being marked, add <code>(setq transient-mark-mode t)</code> to your <code>.emacs</code> file)</li>\n<li>execute <code>M-x indent-region</code></li>\n</ul>\n\n<p>What's nice about this method is that it does not require any plugins (Conway's suggestion), it does not require a replace regexp (nevcx's suggestion), nor does it require switching modes (jfm3's suggestion). Jay's suggestion is in the right direction — in general, executing <code>C-M-q</code> will indent according to a mode's rules — for example, <code>C-M-q</code> works, in my experience, in <code>js-mode</code> and in several other modes. But neither <code>html-mode</code> nor <code>nxml-mode</code> do not seem to implement <code>C-M-q</code>. </p>\n"
},
{
"answer_id": 39440788,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 3,
"selected": false,
"text": "<p>In emacs 25, which I'm currently building from source, assuming you are in HTML mode, use<br>\n <kbd>Ctrl</kbd>-<kbd>x</kbd><br>\n<kbd>h</kbd> </p>\n\n<p>to select all, and then press <kbd>Tab</kbd>.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
]
| How can I validate that my ASPNET AJAX installation is correct.
I have Visual Studio 2008 and had never previously installed any AJAX version.
My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior.
I tried installing AJAX from [MSDN](http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en) followed by an IISRESET yet still it is still not working properly.
What can I check to diagnose the problem?
**Update:** When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler:
```
http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&t=633564733834698722
http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&t=ffffffff867086f6
http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&t=ffffffff867086f6
```
but when I run within IIS i only get this single request :
```
http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&t=ffffffff867086f6
```
Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests. | By default, when you visit a `.html` file in Emacs (22 or 23), it will put you in `html-mode`. That is probably not what you want. You probably want `nxml-mode`, which is seriously fancy. `nxml-mode` seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the [nXML web site](http://www.thaiopensource.com/nxml-mode/). There is also a Debian and Ubuntu package named `nxml-mode`. You can enter `nxml-mode` with:
```
M-x nxml-mode
```
You can view nxml mode documentation with:
```
C-h i g (nxml-mode) RET
```
All that being said, you will probably have to use something like [Tidy](http://tidy.sourceforge.net/) to re-format your xhtml example. `nxml-mode` will get you from
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr>
<td>blah</td></tr></table>
</body>
```
to
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr>
<td>blah</td></tr></table>
</body>
</html>
```
but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that `C-j` will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a `defun` that will do your tables. |
137,089 | <p>I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:</p>
<pre><code>#include <boost/signal.hpp>
typedef boost::signal<void (void)> Event;
int main(int argc, char* argv[])
{
Event e;
return 0;
}
</code></pre>
<p>Thanks!</p>
<p>Edit: This was Boost 1.36.0 compiled with Visual Studio 2008 w/ SP1. Boost::filesystem, like boost::signal also has a library that must be linked in, and it seems to work fine. All the other boost libraries I use are headers-only, I believe.</p>
| [
{
"answer_id": 137175,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": true,
"text": "<p>I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the compiler that your Boost.Signals library is built on. Try to download the Boost source, and compile Boost.Signals using the same compiler as you use for building your code.</p>\n\n<p>Just for my info, what compiler (and version) are you using?</p>\n"
},
{
"answer_id": 138430,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p>This kind of problem often occurs when compiling with a different heap implementation. In VS, it is possible to ask for the CRT to be linked in (as a static library), or left as a dynamic library.</p>\n\n<p>If the library you use allocates memory on its linked-in heap, and your program tries to deallocate it, using another heap, you get in trouble: the object to be freed is not on the list of objects that were allocated.</p>\n"
},
{
"answer_id": 149647,
"author": "Brian Stewart",
"author_id": 3114,
"author_profile": "https://Stackoverflow.com/users/3114",
"pm_score": 3,
"selected": false,
"text": "<p>I have confirmed this as a problem - Stephan T Lavavej (STL!) at Microsoft <a href=\"http://blogs.msdn.com/vcblog/archive/2007/02/26/stl-destructor-of-bugs.aspx\" rel=\"noreferrer\">blogged about this</a>.</p>\n<p>Specifically, he said:</p>\n<blockquote>\n<p>The general problem is that the linker does not diagnose all One Definition Rule (ODR) violations. Although not impossible, this is a difficult problem to solve, which is why the Standard specifically permits certain ODR violations to go undiagnosed.</p>\n<p>I would certainly love for the compiler and linker to have a special mode that would catch all ODR violations at build time, but I recognize that that would be difficult to achieve (and would consume resources that could perhaps be put to even better use, like more conformance). In any event, ODR violations can be avoided without extreme effort by properly structuring your code, so we as programmers can cope with this lack of linker checking.</p>\n<p>However, macros that change the functionality of code by being switched on and off are flirting dangerously with the ODR, and the specific problem is that _SECURE_SCL and _HAS_ITERATOR_DEBUGGING both do exactly this. At first glance, this might not seem so bad, since you should already have control over which macros are defined project-wide in your build system. However, separately compiled libraries complicate things - if you've built (for example) Boost with _SECURE_SCL on, which is the default, your project must not turn _SECURE_SCL off. If you're intent on turning _SECURE_SCL off in your project, now you have to re-build Boost accordingly. And depending on the separately compiled library in question, that might be difficult (with Boost, according to my understanding, it can be done, I've just never figured out how).</p>\n</blockquote>\n<p>He lists some possible workarounds later on in a comment, but none looked appropriate to this situation. Someone else reported being able to turn off these flags when compiling boost by inserting some defines in <strong>boost/config/compiler/visualc.hpp</strong>, but this did <strong>NOT</strong> work for me. However inserting the following line <strong>VERBATIM</strong> in <strong>tools/build/v2/user-config.jam</strong> did the trick. Note that the whitespace is important to boost jam.</p>\n<pre>\nusing msvc : 9.0 : : <cxxflags>-D _SECURE_SCL=0 <cxxflags>-D _HAS_ITERATOR_DEBUGGING=0 ;\n</pre>\n"
},
{
"answer_id": 3803104,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>Brian, I've just experienced exactly the same problem as you. Thanks to your answer about the blog post, I tracked it down to our disabling of <code>_HAS_ITERATOR_DEBUGGING</code> and <code>_SECURE_SCL</code>.</p>\n\n<p>To fix this problem, I built the boost libraries manually. I didn't need to mess around with config files. Here are the two command lines I used:</p>\n\n<blockquote>\n <p><strong>x86</strong><br>\n bjam debug release link=static\n threading=multi runtime-link=shared\n define=_SECURE_SCL=0\n define=_HAS_ITERATOR_DEBUGGING=0\n --with-signals stage</p>\n \n <p><strong>x64</strong><br>\n bjam debug release link=static\n threading=multi runtime-link=shared\n define=_SECURE_SCL=0\n define=_HAS_ITERATOR_DEBUGGING=0\n address-model=64 --with-signals stage</p>\n</blockquote>\n\n<p>This builds the following files:<br>\nlibboost_signals-vc90-mt-1_43.lib<br>\nlibboost_signals-vc90-mt-gd-1_43.lib </p>\n\n<p>Hope that helps.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
]
| I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:
```
#include <boost/signal.hpp>
typedef boost::signal<void (void)> Event;
int main(int argc, char* argv[])
{
Event e;
return 0;
}
```
Thanks!
Edit: This was Boost 1.36.0 compiled with Visual Studio 2008 w/ SP1. Boost::filesystem, like boost::signal also has a library that must be linked in, and it seems to work fine. All the other boost libraries I use are headers-only, I believe. | I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the compiler that your Boost.Signals library is built on. Try to download the Boost source, and compile Boost.Signals using the same compiler as you use for building your code.
Just for my info, what compiler (and version) are you using? |
137,091 | <p>At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion:</p>
<pre><code>function daysToTimestamp(days) {
return Math.round(+days * 86400);
}
</code></pre>
<p>By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why?</p>
| [
{
"answer_id": 137119,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 2,
"selected": false,
"text": "<p>It is because it is neither a linear representation of time nor a true representation of UTC (though it is frequently mistaken for both) as the times it represents are UTC but it has no way of representing UTC leap seconds</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Unix_time</a></p>\n"
},
{
"answer_id": 137122,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>1199059200 represents December 31 2007 in UTC. Sample Python session:</p>\n\n<pre><code>>>> import time\n>>> time.gmtime(1199059200)\n(2007, 12, 31, 0, 0, 0, 0, 365, 0)\n</code></pre>\n\n<p>Remember that all <code>time_t</code> values are against UTC. :-) You have to adjust accordingly to your timezone.</p>\n\n<p>Edit: Since you and I are both in New Zealand, here's how you might have got the 1199098800 value:</p>\n\n<pre><code>>>> time.localtime(1199098800)\n(2008, 1, 1, 0, 0, 0, 1, 1, 1)\n</code></pre>\n\n<p>This is so because in New Year (summer in New Zealand), the timezone here is +1300. Do the maths and see. :-)</p>\n\n<p>For January 1 2008 in UTC, add 86400 to 1199059200, and get 1199145600.</p>\n\n<pre><code>>>> time.gmtime(1199145600)\n(2008, 1, 1, 0, 0, 0, 1, 1, 0)\n</code></pre>\n"
},
{
"answer_id": 137131,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>Unix times (time_t) are represented in seconds since Jan 1, 1970 not milliseconds.</p>\n\n<p>I imagine what you are seeing is a difference in timezone. The delta you have is 11 hours, how are you getting the expected value?</p>\n"
},
{
"answer_id": 137143,
"author": "Ahmad",
"author_id": 22449,
"author_profile": "https://Stackoverflow.com/users/22449",
"pm_score": -1,
"selected": false,
"text": "<p>You should multiply by 86400000</p>\n\n<p>1 day = 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 86400000</p>\n"
},
{
"answer_id": 3997133,
"author": "Dave",
"author_id": 484241,
"author_profile": "https://Stackoverflow.com/users/484241",
"pm_score": 1,
"selected": false,
"text": "<p>Because 1199098800/86400 = 13878.4583333333333 (with the 3 repeating forever), not 13878.0. It gets rounded to 13878.0 since it's being stored as an integer. If you want to see the difference it makes, try this: .4583333333333*86400 = 39599.99999999712. Even that makes it slightly incorrect, but this is where the discrepancy comes from, as 1199098800-1199059200=35600.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
]
| At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion:
```
function daysToTimestamp(days) {
return Math.round(+days * 86400);
}
```
By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why? | It is because it is neither a linear representation of time nor a true representation of UTC (though it is frequently mistaken for both) as the times it represents are UTC but it has no way of representing UTC leap seconds
<http://en.wikipedia.org/wiki/Unix_time> |
137,092 | <p>I will soon be working on AJAX driven web pages that have a lot of content generated from a Web Service (WCF).</p>
<p>I've tested this sort of thing in the past (and found it easy) but not with this level of dynamic content.</p>
<p>I'm developing in .NET 3.5 using Visual Studio 2008. I envisage this testing in:</p>
<ol>
<li>TestDriven.NET</li>
<li>MBUnit (this is not <strong>Unit</strong> testing though)</li>
<li>Some sort of automation tool to
control browsers (Maybe Selenium,
though it might be SWEA or Watin.
I'm thinking IE,Firefox, and likely
Opera and Safari.)</li>
</ol>
<p>In the past I've used delays when testing the browser. I don't particularly like doing that and it wastes time.</p>
<p><strong>What experience and practice is there for doing things better</strong>, than using waits. Maybe introducing callbacks and a functional style of programming to run the tests in?</p>
<hr>
<p><strong>Notes 1. More detail after reviewing first 3 replies.</strong></p>
<p>1) Thanks Alan, Eran and marxidad, your replies have set me on the track to getting my answer, hopefully without too much time spent.</p>
<p>2) Another detail, I'm using <strong>jQuery</strong> to run the Ajax, so this is not built in Asp.NET AJAX.</p>
<p>3) I found an article which <strong>illustrates the situation</strong> nicely. It's from <a href="http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/" rel="nofollow noreferrer" title="WatiN, Watir, Selenium review">http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/</a></p>
<p>3.1) <strong>Selenium</strong> Sample (This and the next, WatiN, code sample do not show up in the original web page (on either IE or Firefox) so I've extracted them and listed them here.)</p>
<pre><code>public void MinAndMaxPriceRestoredWhenOpenedAfterUsingBackButton(){
OpenBrowserTo("welcome/index.rails");
bot.Click("priceDT");
WaitForText("Price Range");
WaitForText("515 N. County Road");
bot.Select("MaxDropDownList", "$5,000,000");
WaitForText("Prewar 8 Off Fifth Avenue");
bot.Select("MinDropDownList", "$2,000,000");
WaitForText("of 86");
bot.Click("link=Prewar 8 Off Fifth Avenue");
WaitForText("Rarely available triple mint restoration");
bot.GoBack();
Thread.Sleep(20000);
bot.Click("priceDT");
WaitForText("Price Range");
Assert.AreEqual("$5,000,000", bot.GetSelectedLabel("MaxDropDownList"));
Assert.AreEqual("$2,000,000", bot.GetSelectedLabel("MinDropDownList"));}
</code></pre>
<p>3.2) <strong>WatiN</strong> sample</p>
<pre><code>public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){
OpenBrowserTo("welcome/index.rails");
ClickLink("Price");
SelectMaxPrice("$5,000,000");
SelectMinPrice("$2,000,000");
ClickLink("Prewar 8 Off Fifth Avenue");
GoBack();
ClickLink("Price");
Assert.AreEqual("$5,000,000", SelectedMaxPrice());
Assert.AreEqual("$2,000,000", SelectedMinPrice());}
</code></pre>
<p>3.3) If you look at these, apparently equivalent, samples you can see that the WatiN sample has <strong>abstracted away the waits</strong>.</p>
<p>3.4) However it may be that WatiN needs <strong>additional support</strong> for values changed by Ajax calls as noted in <a href="http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html" rel="nofollow noreferrer" title="Using WatiN with Ajax">http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html</a>. In that article the page is given an additional field which can be used to synthesize a changed event, like so:</p>
<pre><code>// Wait until the value of the watintoken attribute is changed
ie.SelectList("countries").WaitUntil(!Find.By("watintoken",watintoken));
</code></pre>
<p>4) Now what I'm after is a way to do something <strong>like what we see in the WatiN code without that synthesized event</strong>. It could be a way to directly hook into events, like changed events. I wouldn't have problems with callbacks either though that could change the way tests are coded. I also think we'll see alternate ways of writing tests as the implications of new features in C# 3, VB 9 and F# start to sink in (and wouldn't mind exploring that).</p>
<p>5) marxidad, my source didn't have a sample from WebAii so I haven't got any comments on this, interesting looking, tool.</p>
<hr>
<p><strong>Notes 2. 2008-09-29. After some feedback independent of this page.</strong></p>
<p>5) I attempted to get more complete source for the WatiN sample code above. Unfortunately it's no longer available, the link is dead. When doing that I noticed talk of a DSL, presumably a model that maps between the web page and the automation tool. I found no details on that.</p>
<p>6) For the WebAii it was suggested code like this (it's not tested) would be used:</p>
<pre><code>public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){
ActiveBrowser.NavigateTo("welcome/index.rails");
Find.ByContent<HtmlAnchor>("Price").Click();
HtmlSelect maxPrice = Find.ById<HtmlSelect>("MaxDropDownList");
HtmlSelect minPrice = Find.ById<HtmlSelect>("MinDropDownList");
maxPrice.SelectByText("$5,000,000");
minPrice.SelectByText("$2,000,000");
Find.ByContent<HtmlAnchor>("Prewar 8 Off Fifth Avenue").Click();
ActiveBrowser.GoBack();
Find.ByContent<HtmlAnchor>("Price").Click();
maxPrice.AssertSelect().SelectedText("$5,000,000");
minPrice.AssertSelect().SelectedText("$2,000,000");}
</code></pre>
<p>6) From the code I can clearly avoid waits and delays, with some of the frameworks, but I will need to spend more time to see whether WatiN is right for me. </p>
| [
{
"answer_id": 137546,
"author": "Alan",
"author_id": 9916,
"author_profile": "https://Stackoverflow.com/users/9916",
"pm_score": 2,
"selected": false,
"text": "<p>Most automation frameworks have some synchronizationfunctions built in. Selenium is no exception, and includes functionality like waitForText, waitForElementPresent,etc.</p>\n\n<p>I just realized that you mentioned \"waits\" above, which I interpreted as Sleeps (which aren't good in automation). Let me know if I misinterpreted, and I can talk more about wait* functions or alternatives.</p>\n"
},
{
"answer_id": 137579,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.artoftest.com/Resources/WebAii/Documentation/topicsindex.aspx?topic=ajaxsupport\" rel=\"nofollow noreferrer\">WebAii</a> has a <strong>WaitForElement(s)</strong> method that lets you specify the parameters of the elements to wait for.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21930/"
]
| I will soon be working on AJAX driven web pages that have a lot of content generated from a Web Service (WCF).
I've tested this sort of thing in the past (and found it easy) but not with this level of dynamic content.
I'm developing in .NET 3.5 using Visual Studio 2008. I envisage this testing in:
1. TestDriven.NET
2. MBUnit (this is not **Unit** testing though)
3. Some sort of automation tool to
control browsers (Maybe Selenium,
though it might be SWEA or Watin.
I'm thinking IE,Firefox, and likely
Opera and Safari.)
In the past I've used delays when testing the browser. I don't particularly like doing that and it wastes time.
**What experience and practice is there for doing things better**, than using waits. Maybe introducing callbacks and a functional style of programming to run the tests in?
---
**Notes 1. More detail after reviewing first 3 replies.**
1) Thanks Alan, Eran and marxidad, your replies have set me on the track to getting my answer, hopefully without too much time spent.
2) Another detail, I'm using **jQuery** to run the Ajax, so this is not built in Asp.NET AJAX.
3) I found an article which **illustrates the situation** nicely. It's from [http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/](http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/ "WatiN, Watir, Selenium review")
3.1) **Selenium** Sample (This and the next, WatiN, code sample do not show up in the original web page (on either IE or Firefox) so I've extracted them and listed them here.)
```
public void MinAndMaxPriceRestoredWhenOpenedAfterUsingBackButton(){
OpenBrowserTo("welcome/index.rails");
bot.Click("priceDT");
WaitForText("Price Range");
WaitForText("515 N. County Road");
bot.Select("MaxDropDownList", "$5,000,000");
WaitForText("Prewar 8 Off Fifth Avenue");
bot.Select("MinDropDownList", "$2,000,000");
WaitForText("of 86");
bot.Click("link=Prewar 8 Off Fifth Avenue");
WaitForText("Rarely available triple mint restoration");
bot.GoBack();
Thread.Sleep(20000);
bot.Click("priceDT");
WaitForText("Price Range");
Assert.AreEqual("$5,000,000", bot.GetSelectedLabel("MaxDropDownList"));
Assert.AreEqual("$2,000,000", bot.GetSelectedLabel("MinDropDownList"));}
```
3.2) **WatiN** sample
```
public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){
OpenBrowserTo("welcome/index.rails");
ClickLink("Price");
SelectMaxPrice("$5,000,000");
SelectMinPrice("$2,000,000");
ClickLink("Prewar 8 Off Fifth Avenue");
GoBack();
ClickLink("Price");
Assert.AreEqual("$5,000,000", SelectedMaxPrice());
Assert.AreEqual("$2,000,000", SelectedMinPrice());}
```
3.3) If you look at these, apparently equivalent, samples you can see that the WatiN sample has **abstracted away the waits**.
3.4) However it may be that WatiN needs **additional support** for values changed by Ajax calls as noted in [http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html](http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html "Using WatiN with Ajax"). In that article the page is given an additional field which can be used to synthesize a changed event, like so:
```
// Wait until the value of the watintoken attribute is changed
ie.SelectList("countries").WaitUntil(!Find.By("watintoken",watintoken));
```
4) Now what I'm after is a way to do something **like what we see in the WatiN code without that synthesized event**. It could be a way to directly hook into events, like changed events. I wouldn't have problems with callbacks either though that could change the way tests are coded. I also think we'll see alternate ways of writing tests as the implications of new features in C# 3, VB 9 and F# start to sink in (and wouldn't mind exploring that).
5) marxidad, my source didn't have a sample from WebAii so I haven't got any comments on this, interesting looking, tool.
---
**Notes 2. 2008-09-29. After some feedback independent of this page.**
5) I attempted to get more complete source for the WatiN sample code above. Unfortunately it's no longer available, the link is dead. When doing that I noticed talk of a DSL, presumably a model that maps between the web page and the automation tool. I found no details on that.
6) For the WebAii it was suggested code like this (it's not tested) would be used:
```
public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){
ActiveBrowser.NavigateTo("welcome/index.rails");
Find.ByContent<HtmlAnchor>("Price").Click();
HtmlSelect maxPrice = Find.ById<HtmlSelect>("MaxDropDownList");
HtmlSelect minPrice = Find.ById<HtmlSelect>("MinDropDownList");
maxPrice.SelectByText("$5,000,000");
minPrice.SelectByText("$2,000,000");
Find.ByContent<HtmlAnchor>("Prewar 8 Off Fifth Avenue").Click();
ActiveBrowser.GoBack();
Find.ByContent<HtmlAnchor>("Price").Click();
maxPrice.AssertSelect().SelectedText("$5,000,000");
minPrice.AssertSelect().SelectedText("$2,000,000");}
```
6) From the code I can clearly avoid waits and delays, with some of the frameworks, but I will need to spend more time to see whether WatiN is right for me. | Most automation frameworks have some synchronizationfunctions built in. Selenium is no exception, and includes functionality like waitForText, waitForElementPresent,etc.
I just realized that you mentioned "waits" above, which I interpreted as Sleeps (which aren't good in automation). Let me know if I misinterpreted, and I can talk more about wait\* functions or alternatives. |
137,114 | <p>Whats the best way to round in VBA Access?</p>
<p>My current method utilizes the Excel method</p>
<pre><code>Excel.WorksheetFunction.Round(...
</code></pre>
<p>But I am looking for a means that does not rely on Excel.</p>
| [
{
"answer_id": 137136,
"author": "inglesp",
"author_id": 10439,
"author_profile": "https://Stackoverflow.com/users/10439",
"pm_score": 2,
"selected": false,
"text": "<p>Int and Fix are both useful rounding functions, which give you the integer part of a number.</p>\n\n<p>Int always rounds down - Int(3.5) = 3, Int(-3.5) = -4</p>\n\n<p>Fix always rounds towards zero - Fix(3.5) = 3, Fix(-3.5) = -3</p>\n\n<p>There's also the coercion functions, in particular CInt and CLng, which try to coerce a number to an integer type or a long type (integers are between -32,768 and 32,767, longs are between-2,147,483,648 and 2,147,483,647). These will both round towards the nearest whole number, rounding away from zero from .5 - CInt(3.5) = 4, Cint(3.49) = 3, CInt(-3.5) = -4, etc.</p>\n"
},
{
"answer_id": 137164,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 0,
"selected": false,
"text": "<pre><code>VBA.Round(1.23342, 2) // will return 1.23\n</code></pre>\n"
},
{
"answer_id": 137177,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 6,
"selected": true,
"text": "<p>Be careful, the VBA Round function uses Banker's rounding, where it rounds .5 to an even number, like so: </p>\n\n<pre><code>Round (12.55, 1) would return 12.6 (rounds up) \nRound (12.65, 1) would return 12.6 (rounds down) \nRound (12.75, 1) would return 12.8 (rounds up) \n</code></pre>\n\n<p>Whereas the Excel Worksheet Function Round, always rounds .5 up.</p>\n\n<p>I've done some tests and it looks like .5 up rounding (symmetric rounding) is also used by cell formatting, and also for Column Width rounding (when using the General Number format). The 'Precision as displayed' flag doesn't appear to do any rounding itself, it just uses the rounded result of the cell format.</p>\n\n<p>I tried to implement the SymArith function from Microsoft in VBA for my rounding, but found that Fix has an error when you try to give it a number like 58.55; the function giving a result of 58.5 instead of 58.6. I then finally discovered that you can use the Excel Worksheet Round function, like so:</p>\n\n<blockquote>\n <p><strong>Application.Round(58.55, 1)</strong></p>\n</blockquote>\n\n<p>This will allow you to do normal rounding in VBA, though it may not be as quick as some custom function. I realize that this has come full circle from the question, but wanted to include it for completeness.</p>\n"
},
{
"answer_id": 137217,
"author": "RET",
"author_id": 14750,
"author_profile": "https://Stackoverflow.com/users/14750",
"pm_score": 1,
"selected": false,
"text": "<p>If you're talking about rounding to an integer value (and not rounding to <em>n</em> decimal places), there's always the old school way:</p>\n\n<pre><code>return int(var + 0.5)\n</code></pre>\n\n<p>(You can make this work for <em>n</em> decimal places too, but it starts to get a bit messy)</p>\n"
},
{
"answer_id": 155710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>1 place = INT(number x 10 + .5)/10\n3 places = INT(number x 1000 + .5)/1000\n</code></pre>\n\n<p>and so on.You'll often find that apparently kludgy solutions like this are much faster than using Excel functions, because VBA seems to operate in a different memory space.</p>\n\n<p>eg <code>If A > B Then MaxAB = A Else MaxAB = B</code> is about 40 x faster than using ExcelWorksheetFunction.Max</p>\n"
},
{
"answer_id": 166302,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 2,
"selected": false,
"text": "<p>In Switzerland and in particulat in the insurance industry, we have to use several rounding rules, depending if it chash out, a benefit etc.</p>\n\n<p>I currently use the function</p>\n\n<pre><code>Function roundit(value As Double, precision As Double) As Double\n roundit = Int(value / precision + 0.5) * precision\nEnd Function\n</code></pre>\n\n<p>which seems to work fine</p>\n"
},
{
"answer_id": 266745,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": false,
"text": "<p>To expand a little on the accepted answer:</p>\n\n<p>\"The Round function performs round to even, which is different from round to larger.\"<br>--Microsoft</p>\n\n<p>Format always rounds up.</p>\n\n<pre><code> Debug.Print Round(19.955, 2)\n 'Answer: 19.95\n\n Debug.Print Format(19.955, \"#.00\")\n 'Answer: 19.96\n</code></pre>\n\n<p>ACC2000: Rounding Errors When You Use Floating-Point Numbers: <a href=\"http://support.microsoft.com/kb/210423\" rel=\"noreferrer\">http://support.microsoft.com/kb/210423</a></p>\n\n<p>ACC2000: How to Round a Number Up or Down by a Desired Increment: <a href=\"http://support.microsoft.com/kb/209996\" rel=\"noreferrer\">http://support.microsoft.com/kb/209996</a></p>\n\n<p>Round Function: <a href=\"http://msdn2.microsoft.com/en-us/library/se6f2zfx.aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/en-us/library/se6f2zfx.aspx</a></p>\n\n<p>How To Implement Custom Rounding Procedures: <a href=\"http://support.microsoft.com/kb/196652\" rel=\"noreferrer\">http://support.microsoft.com/kb/196652</a></p>\n"
},
{
"answer_id": 586816,
"author": "Will Rickards",
"author_id": 290835,
"author_profile": "https://Stackoverflow.com/users/290835",
"pm_score": 1,
"selected": false,
"text": "<p>Lance already mentioned the inherit rounding <code>bug</code> in VBA's implementation.\nSo I need a real rounding function in a VB6 app.\nHere is one that I'm using. It is based on one I found on the web as is indicated in the comments.</p>\n\n<pre><code>' -----------------------------------------------------------------------------\n' RoundPenny\n'\n' Description:\n' rounds currency amount to nearest penny\n'\n' Arguments:\n' strCurrency - string representation of currency value\n'\n' Dependencies:\n'\n' Notes:\n' based on RoundNear found here:\n' http://advisor.com/doc/08884\n'\n' History:\n' 04/14/2005 - WSR : created\n'\nFunction RoundPenny(ByVal strCurrency As String) As Currency\n\n Dim mnyDollars As Variant\n Dim decCents As Variant\n Dim decRight As Variant\n Dim lngDecPos As Long\n\n1 On Error GoTo RoundPenny_Error\n\n ' find decimal point\n2 lngDecPos = InStr(1, strCurrency, \".\")\n\n ' if there is a decimal point\n3 If lngDecPos > 0 Then\n\n ' take everything before decimal as dollars\n4 mnyDollars = CCur(Mid(strCurrency, 1, lngDecPos - 1))\n\n ' get amount after decimal point and multiply by 100 so cents is before decimal point\n5 decRight = CDec(CDec(Mid(strCurrency, lngDecPos)) / 0.01)\n\n ' get cents by getting integer portion\n6 decCents = Int(decRight)\n\n ' get leftover\n7 decRight = CDec(decRight - decCents)\n\n ' if leftover is equal to or above round threshold\n8 If decRight >= 0.5 Then\n\n9 RoundPenny = mnyDollars + ((decCents + 1) * 0.01)\n\n ' if leftover is less than round threshold\n10 Else\n\n11 RoundPenny = mnyDollars + (decCents * 0.01)\n\n12 End If\n\n ' if there is no decimal point\n13 Else\n\n ' return it\n14 RoundPenny = CCur(strCurrency)\n\n15 End If\n\n16 Exit Function\n\nRoundPenny_Error:\n\n17 Select Case Err.Number\n\n Case 6\n\n18 Err.Raise vbObjectError + 334, c_strComponent & \".RoundPenny\", \"Number '\" & strCurrency & \"' is too big to represent as a currency value.\"\n\n19 Case Else\n\n20 DisplayError c_strComponent, \"RoundPenny\"\n\n21 End Select\n\nEnd Function\n' ----------------------------------------------------------------------------- \n</code></pre>\n"
},
{
"answer_id": 1981091,
"author": "John OQuin",
"author_id": 241019,
"author_profile": "https://Stackoverflow.com/users/241019",
"pm_score": 0,
"selected": false,
"text": "<p>Here is easy way to always round up to next whole number in Access 2003:</p>\n\n<pre><code>BillWt = IIf([Weight]-Int([Weight])=0,[Weight],Int([Weight])+1)\n</code></pre>\n\n<p>For example: </p>\n\n<ul>\n<li>[Weight] = 5.33 ; Int([Weight]) = 5 ; so 5.33-5 = 0.33 (<>0), so answer is BillWt = 5+1 = 6. </li>\n<li>[Weight] = 6.000, Int([Weight]) = 6 , so 6.000-6 = 0, so answer is BillWt = 6.</li>\n</ul>\n"
},
{
"answer_id": 22692373,
"author": "user3469318",
"author_id": 3469318,
"author_profile": "https://Stackoverflow.com/users/3469318",
"pm_score": 0,
"selected": false,
"text": "<p>To solve the problem of penny splits not adding up to the amount that they were originally split from, I created a user defined function.</p>\n\n<pre><code>Function PennySplitR(amount As Double, Optional splitRange As Variant, Optional index As Integer = 0, Optional n As Integer = 0, Optional flip As Boolean = False) As Double\n' This Excel function takes either a range or an index to calculate how to \"evenly\" split up dollar amounts\n' when each split amount must be in pennies. The amounts might vary by a penny but the total of all the\n' splits will add up to the input amount.\n\n' Splits a dollar amount up either over a range or by index\n' Example for passing a range: set range $I$18:$K$21 to =PennySplitR($E$15,$I$18:$K$21) where $E$15 is the amount and $I$18:$K$21 is the range\n' it is intended that the element calling this function will be in the range\n' or to use an index and total items instead of a range: =PennySplitR($E$15,,index,N)\n' The flip argument is to swap rows and columns in calculating the index for the element in the range.\n\n' Thanks to: http://stackoverflow.com/questions/5559279/excel-cell-from-which-a-function-is-called for the application.caller.row hint.\nDim evenSplit As Double, spCols As Integer, spRows As Integer\nIf (index = 0 Or n = 0) Then\n spRows = splitRange.Rows.count\n spCols = splitRange.Columns.count\n n = spCols * spRows\n If (flip = False) Then\n index = (Application.Caller.Row - splitRange.Cells.Row) * spCols + Application.Caller.Column - splitRange.Cells.Column + 1\n Else\n index = (Application.Caller.Column - splitRange.Cells.Column) * spRows + Application.Caller.Row - splitRange.Cells.Row + 1\n End If\n End If\n If (n < 1) Then\n PennySplitR = 0\n Return\n Else\n evenSplit = amount / n\n If (index = 1) Then\n PennySplitR = Round(evenSplit, 2)\n Else\n PennySplitR = Round(evenSplit * index, 2) - Round(evenSplit * (index - 1), 2)\n End If\nEnd If\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 23521993,
"author": "Sidupac",
"author_id": 2199867,
"author_profile": "https://Stackoverflow.com/users/2199867",
"pm_score": 0,
"selected": false,
"text": "<p>I used the following <strong>simple</strong> function to round my <strong>currencies</strong> as in our company we <strong>always</strong> round up.</p>\n\n<pre><code>Function RoundUp(Number As Variant)\n RoundUp = Int(-100 * Number) / -100\n If Round(Number, 2) = Number Then RoundUp = Number\nEnd Function\n</code></pre>\n\n<p>but this will ALWAYS round up to 2 decimals and may also error.</p>\n\n<p>even if it is negative it will round up (-1.011 will be -1.01 and 1.011 will be 1.02)</p>\n\n<p>so to provide more options for <em>rounding up</em> (or down for negative) you <strong>could</strong> use this function:</p>\n\n<pre><code>Function RoundUp(Number As Variant, Optional RoundDownIfNegative As Boolean = False)\nOn Error GoTo err\nIf Number = 0 Then\nerr:\n RoundUp = 0\nElseIf RoundDownIfNegative And Number < 0 Then\n RoundUp = -1 * Int(-100 * (-1 * Number)) / -100\nElse\n RoundUp = Int(-100 * Number) / -100\nEnd If\nIf Round(Number, 2) = Number Then RoundUp = Number\nEnd Function\n</code></pre>\n\n<p>(used in a module, if it isn't obvious)</p>\n"
},
{
"answer_id": 36966140,
"author": "Gustav",
"author_id": 3527297,
"author_profile": "https://Stackoverflow.com/users/3527297",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, the native functions of VBA that can perform rounding are either missing, limited, inaccurate, or buggy, and each addresses only a single rounding method. The upside is that they are fast, and that may in some situations be important.</p>\n\n<p>However, often precision is mandatory, and with the speed of computers today, a little slower processing will hardly be noticed, indeed not for processing of single values. All the functions at the links below run at about 1 µs.</p>\n\n<p>The complete set of functions - for all common rounding methods, all data types of VBA, for any value, and not returning unexpected values - can be found here:</p>\n\n<p><a href=\"https://rdsrc.us/Mw1Iiy\" rel=\"nofollow\">Rounding values up, down, by 4/5, or to significant figures (EE)</a></p>\n\n<p>or here:</p>\n\n<p><a href=\"http://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur\" rel=\"nofollow\">Rounding values up, down, by 4/5, or to significant figures (CodePlex)</a></p>\n\n<p>Code only at GitHub:</p>\n\n<p><a href=\"https://github.com/GustavBrock/VBA.Round.git\" rel=\"nofollow\">VBA.Round</a></p>\n\n<p>They cover the normal rounding methods:</p>\n\n<ul>\n<li><p>Round down, with the option to round negative values towards zero</p></li>\n<li><p>Round up, with the option to round negative values away from zero</p></li>\n<li><p>Round by 4/5, either away from zero or to even (Banker's Rounding)</p></li>\n<li><p>Round to a count of significant figures</p></li>\n</ul>\n\n<p>The first three functions accept all the numeric data types, while the last exists in three varieties - for Currency, Decimal, and Double respectively.</p>\n\n<p>They all accept a specified count of decimals - including a negative count which will round to tens, hundreds, etc. Those with Variant as return type will return Null for incomprehensible input</p>\n\n<p>A test module for test and validating is included as well.</p>\n\n<p>An example is here - for the common 4/5 rounding. Please study the in-line comments for the subtle details and the way <em>CDec</em> is used to avoid bit errors.</p>\n\n<pre><code>' Common constants.\n'\nPublic Const Base10 As Double = 10\n\n' Rounds Value by 4/5 with count of decimals as specified with parameter NumDigitsAfterDecimals.\n'\n' Rounds to integer if NumDigitsAfterDecimals is zero.\n'\n' Rounds correctly Value until max/min value limited by a Scaling of 10\n' raised to the power of (the number of decimals).\n'\n' Uses CDec() for correcting bit errors of reals.\n'\n' Execution time is about 1µs.\n'\nPublic Function RoundMid( _\n ByVal Value As Variant, _\n Optional ByVal NumDigitsAfterDecimals As Long, _\n Optional ByVal MidwayRoundingToEven As Boolean) _\n As Variant\n\n Dim Scaling As Variant\n Dim Half As Variant\n Dim ScaledValue As Variant\n Dim ReturnValue As Variant\n\n ' Only round if Value is numeric and ReturnValue can be different from zero.\n If Not IsNumeric(Value) Then\n ' Nothing to do.\n ReturnValue = Null\n ElseIf Value = 0 Then\n ' Nothing to round.\n ' Return Value as is.\n ReturnValue = Value\n Else\n Scaling = CDec(Base10 ^ NumDigitsAfterDecimals)\n\n If Scaling = 0 Then\n ' A very large value for Digits has minimized scaling.\n ' Return Value as is.\n ReturnValue = Value\n ElseIf MidwayRoundingToEven Then\n ' Banker's rounding.\n If Scaling = 1 Then\n ReturnValue = Round(Value)\n Else\n ' First try with conversion to Decimal to avoid bit errors for some reals like 32.675.\n ' Very large values for NumDigitsAfterDecimals can cause an out-of-range error \n ' when dividing.\n On Error Resume Next\n ScaledValue = Round(CDec(Value) * Scaling)\n ReturnValue = ScaledValue / Scaling\n If Err.Number <> 0 Then\n ' Decimal overflow.\n ' Round Value without conversion to Decimal.\n ReturnValue = Round(Value * Scaling) / Scaling\n End If\n End If\n Else\n ' Standard 4/5 rounding.\n ' Very large values for NumDigitsAfterDecimals can cause an out-of-range error \n ' when dividing.\n On Error Resume Next\n Half = CDec(0.5)\n If Value > 0 Then\n ScaledValue = Int(CDec(Value) * Scaling + Half)\n Else\n ScaledValue = -Int(-CDec(Value) * Scaling + Half)\n End If\n ReturnValue = ScaledValue / Scaling\n If Err.Number <> 0 Then\n ' Decimal overflow.\n ' Round Value without conversion to Decimal.\n Half = CDbl(0.5)\n If Value > 0 Then\n ScaledValue = Int(Value * Scaling + Half)\n Else\n ScaledValue = -Int(-Value * Scaling + Half)\n End If\n ReturnValue = ScaledValue / Scaling\n End If\n End If\n If Err.Number <> 0 Then\n ' Rounding failed because values are near one of the boundaries of type Double.\n ' Return value as is.\n ReturnValue = Value\n End If\n End If\n\n RoundMid = ReturnValue\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 69890635,
"author": "trs11",
"author_id": 15078702,
"author_profile": "https://Stackoverflow.com/users/15078702",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Public Function RoundUpDown(value, decimals, updown)\nIf IsNumeric(value) Then\n rValue = Round(value, decimals)\n rDec = 10 ^ (-(decimals))\n rDif = rValue - value\n If updown = "down" Then 'rounding for "down" explicitly.\n If rDif > 0 Then ' if the difference is more than 0, it rounded up.\n RoundUpDown = rValue - rDec\n ElseIf rDif < 0 Then ' if the difference is less than 0, it rounded down.\n RoundUpDown = rValue\n Else\n RoundUpDown = rValue\n End If\n Else 'rounding for anything thats not "down"\n If rDif > 0 Then ' if the difference is more than 0, it rounded up.\n RoundUpDown = rValue\n ElseIf rDif < 0 Then ' if the difference is less than 0, it rounded down.\n RoundUpDown = rValue + rDec\n Else\n RoundUpDown = rValue\n End If\n End If\n\nEnd If\n'RoundUpDown(value, decimals, updown) 'where updown is "down" if down. else rounds up. put this in your program.\nEnd Function\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3155/"
]
| Whats the best way to round in VBA Access?
My current method utilizes the Excel method
```
Excel.WorksheetFunction.Round(...
```
But I am looking for a means that does not rely on Excel. | Be careful, the VBA Round function uses Banker's rounding, where it rounds .5 to an even number, like so:
```
Round (12.55, 1) would return 12.6 (rounds up)
Round (12.65, 1) would return 12.6 (rounds down)
Round (12.75, 1) would return 12.8 (rounds up)
```
Whereas the Excel Worksheet Function Round, always rounds .5 up.
I've done some tests and it looks like .5 up rounding (symmetric rounding) is also used by cell formatting, and also for Column Width rounding (when using the General Number format). The 'Precision as displayed' flag doesn't appear to do any rounding itself, it just uses the rounded result of the cell format.
I tried to implement the SymArith function from Microsoft in VBA for my rounding, but found that Fix has an error when you try to give it a number like 58.55; the function giving a result of 58.5 instead of 58.6. I then finally discovered that you can use the Excel Worksheet Round function, like so:
>
> **Application.Round(58.55, 1)**
>
>
>
This will allow you to do normal rounding in VBA, though it may not be as quick as some custom function. I realize that this has come full circle from the question, but wanted to include it for completeness. |
137,147 | <p>For example</p>
<pre><code>int f(int a) {
...
return a > 10;
}
</code></pre>
<p>is that considered acceptable (not legal, I mean is it ``good code''), or should it always be in a conditional, like this</p>
<pre><code>int f(int a) {
...
if (a > 10)
return 1;
else
return 0;
}
</code></pre>
| [
{
"answer_id": 137152,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "<p>This is absolutely acceptable! In fact, Joel mentioned this on the latest stackoverflow podcast. He said it was the one thing he's had to show almost every programmer that starts at Fog Creek.</p>\n"
},
{
"answer_id": 137155,
"author": "Svet",
"author_id": 8934,
"author_profile": "https://Stackoverflow.com/users/8934",
"pm_score": 2,
"selected": false,
"text": "<p>I don't see anything wrong with it. If anything it's more concise and I think most developers with moderate experience would prefer it.</p>\n"
},
{
"answer_id": 137157,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 2,
"selected": false,
"text": "<p>The first is much preferable to me, since it is more concise. (And it avoids multiple returns:)</p>\n"
},
{
"answer_id": 137163,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>I'll typically do the former over the latter.</p>\n"
},
{
"answer_id": 137172,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 1,
"selected": false,
"text": "<p>I think its perfectly acceptable, provided that you ensure that you make an extra effort to maintain readability. Like I would make sure that the method name is very unambiguous and you use good variable names. </p>\n\n<p>The second alternative that you provided I think is almost worse because it involves a branch statement and multiple return statements and these things increase the complexity of the method while themselves reducing its readability. </p>\n"
},
{
"answer_id": 137184,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": false,
"text": "<p>It would be acceptable - if your return type was <a href=\"http://en.wikipedia.org/wiki/Boolean_datatype#C99\" rel=\"nofollow noreferrer\">bool</a>.</p>\n"
},
{
"answer_id": 137185,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 2,
"selected": false,
"text": "<p>I'd rather write <code>bool f(int);</code> and the first form as bool is the <code>boolean</code> type in C++. If I really need to return an <code>int</code>, I'd write something like</p>\n\n<pre><code>int f(int) {\n ...\n const int res = (i>42) ? 1 : 0;\n return res;\n}\n</code></pre>\n\n<p>I'd never understood why people write </p>\n\n<pre><code>if (expr == true)\n mybool = true ; \nelse \n mybool = false;\n</code></pre>\n\n<p>instead of the plain</p>\n\n<pre><code>mybool = expr;\n</code></pre>\n\n<p>Boolean algebra is a tool that any developer should be able to handle instinctively</p>\n\n<p><em>Moreover, I'd rather define a named temporary as some debuggers don't handle function return values very well.</em></p>\n"
},
{
"answer_id": 137198,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 3,
"selected": false,
"text": "<p>The first case is perfectly good, far better than the second, IMHO. As a matter of readability, I personally would do</p>\n\n<pre><code> return (a > 10);\n</code></pre>\n\n<p>but that is a minor nit, and not one everyone would agree on.</p>\n"
},
{
"answer_id": 137222,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 4,
"selected": false,
"text": "<pre><code>return a > 10 ? 1 : 0;\n</code></pre>\n\n<p>... makes more sense because you're returning an int, not a bool.</p>\n"
},
{
"answer_id": 140404,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 1,
"selected": false,
"text": "<p>Not only is that syntax 100% acceptable, you should also feel free to use boolean expressions outside of if statements, i.e. <code>int x = i && ( j || k );</code> (or returning values like that). </p>\n"
},
{
"answer_id": 141561,
"author": "brijwhiz",
"author_id": 19615,
"author_profile": "https://Stackoverflow.com/users/19615",
"pm_score": 1,
"selected": false,
"text": "<p>I think part of it has to do with the style and culture of the language. The first example you have written is what would be expected from an experienced C programmer. They would much rather strangle themselves than put in an unnecessary block of statements.</p>\n\n<p>I think it is perfectly acceptable when the language allows it and the usage is part of the paradigm of that language</p>\n"
},
{
"answer_id": 3359554,
"author": "Roland Illig",
"author_id": 225757,
"author_profile": "https://Stackoverflow.com/users/225757",
"pm_score": 1,
"selected": false,
"text": "<p>I just tried three different variants with GCC:</p>\n\n<pre><code>int one(int x) { return (x > 42) ? 1 : 0; }\nint two(int x) { return x > 42; }\nint thr(int x) { if (x > 42) return 1; else return 0; }\n</code></pre>\n\n<p>As soon as you enable some optimization, the generated code for all of them is the same. So you should use the variant that is easiest to read.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| For example
```
int f(int a) {
...
return a > 10;
}
```
is that considered acceptable (not legal, I mean is it ``good code''), or should it always be in a conditional, like this
```
int f(int a) {
...
if (a > 10)
return 1;
else
return 0;
}
``` | This is absolutely acceptable! In fact, Joel mentioned this on the latest stackoverflow podcast. He said it was the one thing he's had to show almost every programmer that starts at Fog Creek. |
137,181 | <p>I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used?</p>
| [
{
"answer_id": 137200,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 4,
"selected": true,
"text": "<p>Try -V which \"Print the version and build parameters of httpd, and then exit.\"</p>\n\n<pre><code>httpd -V\n</code></pre>\n\n<p>Also, you can see the options for httpd via:</p>\n\n<pre><code>httpd -h\n</code></pre>\n"
},
{
"answer_id": 14920292,
"author": "babyromeo",
"author_id": 544611,
"author_profile": "https://Stackoverflow.com/users/544611",
"pm_score": 0,
"selected": false,
"text": "<p>I re-compiled apache 2.4.3 recently and change the MPM from worker to prefork, what you have to do if you still keep your original compiled directory without ran \"make distclean\" (if you ran \"make clean\" it still OK). You can use the SAME configure option to re-configure by exec ./config.status or you can find and copy './configure' from ./config.status (yes, all the original options that you used to run configure still there).</p>\n\n<p>Here is part of my config.status...</p>\n\n<pre><code>if $ac_cs_silent; then\n exec 6>/dev/null\n ac_configure_extra_args=\"$ac_configure_extra_args --silent\"\nfi\n\nif $ac_cs_recheck; then\n set X /bin/sh **'./configure' '--enable-file-cache' '--enable-cache' '--enable-disk-cache' '--enable-mem-cache' '--enable-deflate' '--enable-expires' '--enable-headers' '--enable-usertrack' '--enable-cgi' '--enable-vhost-alias' '--enable-rewrite' '--enable-so' '--with-apr=/usr/local/apache/' '--with-apr-util=/usr/local/apache/' '--prefix=/usr/local/apache' '--with-mpm=worker' '--with-mysql=/var/lib/mysql' '--with-mysql-sock=/var/run/mysqld/mysqld.sock' '--enable-mods-shared=most' '--enable-ssl' 'CFLAGS=-Wall -O3 -ffast-math -frename-registers -mtune=corei7-avx' '--enable-modules=all' '--enable-proxy' '--enable-proxy-fcgi'** $ac_configure_extra_args --no-create --no-recursion\n shift\n $as_echo \"running CONFIG_SHELL=/bin/sh $*\" >&6\n CONFIG_SHELL='/bin/sh'\n export CONFIG_SHELL\n exec \"$@\"\nfi\n</code></pre>\n"
},
{
"answer_id": 23370616,
"author": "kyle",
"author_id": 1874154,
"author_profile": "https://Stackoverflow.com/users/1874154",
"pm_score": 3,
"selected": false,
"text": "<p>I found previous configure options in the build directory of apache root. </p>\n\n<p>I'm a Centos 5/6 user. </p>\n\n<p>Apache ver. is 2.2.27.</p>\n\n<p>apachedir/build/config.nice</p>\n\n<pre><code>#! /bin/sh\n#\n# Created by configure\n\n\"./configure\" \\\n\"--prefix=/usr/local/apache2\" \\\n\"--enable-so\" \\\n\"--enable-mods-shared=most\" \\\n\"--enable-ssl\" \\\n\"--with-mpm=worker\" \\\n\"--enable-cgi\" \\\n\"$@\"\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
]
| I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used? | Try -V which "Print the version and build parameters of httpd, and then exit."
```
httpd -V
```
Also, you can see the options for httpd via:
```
httpd -h
``` |
137,212 | <p>If you want a cryptographically strong random numbers in Java, you use <code>SecureRandom</code>. Unfortunately, <code>SecureRandom</code> can be very slow. If it uses <code>/dev/random</code> on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty?</p>
<p>Has anyone used <a href="https://uncommons-maths.dev.java.net/" rel="noreferrer">Uncommon Maths</a> as a solution to this problem?</p>
<p>Can anybody confirm that this performance problem has been solved in JDK 6?</p>
| [
{
"answer_id": 137223,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": "<p>I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a seed, then dies. The method which you call for randoms will join to that thread if it is alive so the first call only blocks if it occurs very early in program execution.</p>\n"
},
{
"answer_id": 137252,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 3,
"selected": false,
"text": "<p>The problem you referenced about <code>/dev/random</code> is not with the <code>SecureRandom</code> algorithm, but with the source of randomness that it uses. The two are orthogonal. You should figure out which one of the two is slowing you down.</p>\n\n<p>Uncommon Maths page that you linked explicitly mentions that they are not addressing the source of randomness.</p>\n\n<p>You can try different JCE providers, such as BouncyCastle, to see if their implementation of <code>SecureRandom</code> is faster.</p>\n\n<p>A brief <a href=\"http://www.google.com/search?q=fortuna+/dev/random\" rel=\"nofollow noreferrer\">search</a> also reveals Linux patches that replace the default implementation with Fortuna. I don't know much more about this, but you're welcome to investigate.</p>\n\n<p>I should also mention that while it's very dangerous to use a badly implemented <code>SecureRandom</code> algorithm and/or randomness source, you can roll your own JCE Provider with a custom implementation of <code>SecureRandomSpi</code>. You will need to go through a process with Sun to get your provider signed, but it's actually pretty straightforward; they just need you to fax them a form stating that you're aware of the US export restrictions on crypto libraries.</p>\n"
},
{
"answer_id": 137288,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 8,
"selected": true,
"text": "<p>If you want true random data, then unfortunately you have to wait for it. This includes the seed for a <code>SecureRandom</code> PRNG. Uncommon Maths can't gather true random data any faster than <code>SecureRandom</code>, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than <code>/dev/random</code> where that's available.</p>\n\n<p>If you want a PRNG, do something like this:</p>\n\n<pre><code>SecureRandom.getInstance(\"SHA1PRNG\");\n</code></pre>\n\n<p>What strings are supported depends on the <code>SecureRandom</code> SPI provider, but you can enumerate them using <code>Security.getProviders()</code> and <code>Provider.getService()</code>.</p>\n\n<p>Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.</p>\n\n<p>The exception is that if you don't call <code>setSeed()</code> before getting data, then the PRNG will seed itself once the first time you call <code>next()</code> or <code>nextBytes()</code>. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of \"hash the current time together with the PID, add 27, and hope for the best\". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.</p>\n"
},
{
"answer_id": 137626,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>My experience has been only with slow initialization of the PRNG, not with generation of random data after that. Try a more eager initialization strategy. Since they're expensive to create, treat it like a singleton and reuse the same instance. If there's too much thread contention for one instance, pool them or make them thread-local.</p>\n\n<p>Don't compromise on random number generation. A weakness there compromises all of your security.</p>\n\n<p>I don't see a lot of COTS atomic-decay–based generators, but there are several plans out there for them, if you really need a lot of random data. One site that always has interesting things to look at, including HotBits, is <a href=\"http://www.fourmilab.ch/\" rel=\"nofollow noreferrer\">John Walker's Fourmilab.</a></p>\n"
},
{
"answer_id": 138745,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 5,
"selected": false,
"text": "<p>On Linux, the default implementation for <code>SecureRandom</code> is <code>NativePRNG</code> (source code <a href=\"http://www.java2s.com/Open-Source/Java/6.0-JDK-Platform/solaris/sun/security/provider/NativePRNG.java.htm\" rel=\"noreferrer\">here</a>), which tends to be very slow. On Windows, the default is <code>SHA1PRNG</code>, which as others pointed out you can also use on Linux if you specify it explicitly.</p>\n\n<p><code>NativePRNG</code> differs from <code>SHA1PRNG</code> and Uncommons Maths' <a href=\"http://maths.uncommons.org/api/org/uncommons/maths/random/AESCounterRNG.html\" rel=\"noreferrer\">AESCounterRNG</a> in that it continuously receives entropy from the operating system (by reading from <code>/dev/urandom</code>). The other PRNGs do not acquire any additional entropy after seeding.</p>\n\n<p>AESCounterRNG is about 10x faster than <code>SHA1PRNG</code>, which IIRC is itself two or three times faster than <code>NativePRNG</code>.</p>\n\n<p>If you need a faster PRNG that acquires entropy after initialization, see if you can find a Java implementation of <a href=\"http://en.wikipedia.org/wiki/Fortuna_(PRNG)\" rel=\"noreferrer\">Fortuna</a>. The core PRNG of a Fortuna implementation is identical to that used by AESCounterRNG, but there is also a sophisticated system of entropy pooling and automatic reseeding.</p>\n"
},
{
"answer_id": 139165,
"author": "Lorenzo Boccaccia",
"author_id": 2273540,
"author_profile": "https://Stackoverflow.com/users/2273540",
"pm_score": 2,
"selected": false,
"text": "<p>Use the secure random as initialization source for a recurrent algorithm; you could use then a Mersenne twister for the bulk work instead of the one in UncommonMath, which has been around for a while and proven better than other prng</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Mersenne_twister\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Mersenne_twister</a></p>\n\n<p>Make sure to refresh now and then the secure random used for the initialization, for example you could have one secure random generated per client, using one mersenne twister pseudo random generator per client, obtaining a high enough degree of randomization</p>\n"
},
{
"answer_id": 140921,
"author": "Chris Kite",
"author_id": 9573,
"author_profile": "https://Stackoverflow.com/users/9573",
"pm_score": 4,
"selected": false,
"text": "<p>If you want truly \"cryptographically strong\" randomness, then you need a strong entropy source. <code>/dev/random</code> is slow because it has to wait for system events to gather entropy (disk reads, network packets, mouse movement, key presses, etc.).</p>\n\n<p>A faster solution is a hardware random number generator. You may already have one built-in to your motherboard; check out the <a href=\"http://www.mjmwired.net/kernel/Documentation/hw_random.txt\" rel=\"noreferrer\">hw_random documentation</a> for instructions on figuring out if you have it, and how to use it. The rng-tools package includes a daemon which will feed hardware generated entropy into <code>/dev/random</code>.</p>\n\n<p>If a HRNG is not available on your system, and you are willing to sacrifice entropy strength for performance, you will want to seed a good PRNG with data from <code>/dev/random</code>, and let the PRNG do the bulk of the work. There are several NIST-approved PRNG's listed in <a href=\"http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf\" rel=\"noreferrer\">SP800-90</a> which are straightforward to implement.</p>\n"
},
{
"answer_id": 169338,
"author": "Diastrophism",
"author_id": 18093,
"author_profile": "https://Stackoverflow.com/users/18093",
"pm_score": 1,
"selected": false,
"text": "<p>Something else to look at is the property securerandom.source in file lib/security/java.security\n<P>There may be a performance benefit to using /dev/urandom rather than /dev/random. Remember that if the quality of the random numbers is important, don't make a compromise which breaks security.</p>\n"
},
{
"answer_id": 388984,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.</p>\n\n<p>If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with <a href=\"https://stackoverflow.com/questions/137212/how-to-solve-performance-problem-with-java-securerandom#138745\">Dan Dyer's response</a> about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.</p>\n\n<p>I would <em>think</em> that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's <a href=\"http://www.ecrypt.eu.org/stream/\" rel=\"nofollow noreferrer\">eStream</a> project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.</p>\n\n<p>Edit: here's some <a href=\"http://www.tml.tkk.fi/Opinnot/T-110.470/2004/20041101.pdf\" rel=\"nofollow noreferrer\">cryptographic course notes on RNG</a> I found on the 'net that look very relevant to this topic.</p>\n"
},
{
"answer_id": 2325109,
"author": "Thomas Leonard",
"author_id": 50926,
"author_profile": "https://Stackoverflow.com/users/50926",
"pm_score": 8,
"selected": false,
"text": "<p>You should be able to select the faster-but-slightly-less-secure /dev/urandom on Linux using:</p>\n\n<pre><code>-Djava.security.egd=file:/dev/urandom\n</code></pre>\n\n<p>However, this doesn't work with Java 5 and later (<a href=\"https://bugs.openjdk.java.net/browse/JDK-6202721\" rel=\"noreferrer\">Java Bug 6202721</a>). The suggested work-around is to use:</p>\n\n<pre><code>-Djava.security.egd=file:/dev/./urandom\n</code></pre>\n\n<p>(note the extra <code>/./</code>)</p>\n"
},
{
"answer_id": 12159344,
"author": "David K",
"author_id": 1324595,
"author_profile": "https://Stackoverflow.com/users/1324595",
"pm_score": 3,
"selected": false,
"text": "<p>There is a tool (on Ubuntu at least) that will feed artificial randomness into your system. The command is simply:</p>\n\n<pre><code>rngd -r /dev/urandom\n</code></pre>\n\n<p>and you may need a sudo at the front. If you don't have rng-tools package, you will need to install it. I tried this, and it definitely helped me!</p>\n\n<p>Source: <a href=\"http://www.mattvsworld.com/blog/2010/02/speed-up-key-generation-with-artificial-entropy/\" rel=\"noreferrer\">matt vs world</a></p>\n"
},
{
"answer_id": 18816044,
"author": "user2781824",
"author_id": 2781824,
"author_profile": "https://Stackoverflow.com/users/2781824",
"pm_score": 2,
"selected": false,
"text": "<p>If your hardware supports it try <a href=\"https://github.com/hpadmanabhan/rdrand-util\" rel=\"nofollow noreferrer\">using Java RdRand Utility</a> of which I'm the author.</p>\n\n<p>Its based on Intel's <code>RDRAND</code> instruction and is about 10 times faster than <code>SecureRandom</code> and no bandwidth issues for large volume implementation.</p>\n\n<hr>\n\n<p>Note that this implementation only works on those CPU's that provide the instruction (i.e. when the <code>rdrand</code> processor flag is set). You need to explicitly instantiate it through the <code>RdRandRandom()</code> constructor; no specific <code>Provider</code> has been implemented.</p>\n"
},
{
"answer_id": 30358935,
"author": "thunder",
"author_id": 3438692,
"author_profile": "https://Stackoverflow.com/users/3438692",
"pm_score": 4,
"selected": false,
"text": "<p>I had a similar problem with calls to <code>SecureRandom</code> blocking for about 25 seconds at a time on a headless Debian server. I installed the <code>haveged</code> daemon to ensure <code>/dev/random</code> is kept topped up, on headless servers you need something like this to generate the required entropy. \nMy calls to <code>SecureRandom</code> now perhaps take milliseconds. </p>\n"
},
{
"answer_id": 40647569,
"author": "so-random-dude",
"author_id": 6785908,
"author_profile": "https://Stackoverflow.com/users/6785908",
"pm_score": 3,
"selected": false,
"text": "<p>I faced same <a href=\"https://stackoverflow.com/questions/40383430/tomcat-takes-too-much-time-to-start-java-securerandom\">issue</a>. After some Googling with the right search terms, I came across this nice article on <a href=\"https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged\" rel=\"nofollow noreferrer\">DigitalOcean</a>. </p>\n\n<h2>haveged is a potential solution without compromising on security.</h2>\n\n<p>I am merely quoting the relevant part from the article here.</p>\n\n<blockquote>\n <p>Based on the HAVEGE principle, and previously based on its associated\n library, haveged allows generating randomness based on variations in\n code execution time on a processor. Since it's nearly impossible for\n one piece of code to take the same exact time to execute, even in the\n same environment on the same hardware, the timing of running a single\n or multiple programs should be suitable to seed a random source. The\n haveged implementation seeds your system's random source (usually\n /dev/random) using differences in your processor's time stamp counter\n (TSC) after executing a loop repeatedly</p>\n</blockquote>\n\n<h2>How to install haveged</h2>\n\n<p>Follow the steps in this article. <a href=\"https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged\" rel=\"nofollow noreferrer\">https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged</a></p>\n\n<p>I have posted it <a href=\"https://stackoverflow.com/a/40603084/6785908\">here</a></p>\n"
},
{
"answer_id": 40885767,
"author": "Lachlan",
"author_id": 94152,
"author_profile": "https://Stackoverflow.com/users/94152",
"pm_score": 3,
"selected": false,
"text": "<p>Using Java 8, I found that on Linux calling <code>SecureRandom.getInstanceStrong()</code> would give me the <code>NativePRNGBlocking</code> algorithm. This would often block for many seconds to generate a few bytes of salt.</p>\n\n<p>I switched to explicitly asking for <code>NativePRNGNonBlocking</code> instead, and as expected from the name, it no longer blocked. I have no idea what the security implications of this are. Presumably the non-blocking version can't guarantee the amount of entropy being used.</p>\n\n<p><strong>Update</strong>: Ok, I found <a href=\"https://tersesystems.com/2015/12/17/the-right-way-to-use-securerandom/\" rel=\"noreferrer\">this excellent explanation</a>.</p>\n\n<p>In a nutshell, to avoid blocking, use <code>new SecureRandom()</code>. This uses <code>/dev/urandom</code>, which doesn't block and is basically as secure as <code>/dev/random</code>. From the post: \"The only time you would want to call /dev/random is when the machine is first booting, and entropy has not yet accumulated\".</p>\n\n<p><code>SecureRandom.getInstanceStrong()</code> gives you the absolute strongest RNG, but it's only safe to use in situations where a bunch of blocking won't effect you.</p>\n"
},
{
"answer_id": 47097219,
"author": "rustyx",
"author_id": 485343,
"author_profile": "https://Stackoverflow.com/users/485343",
"pm_score": 5,
"selected": false,
"text": "<p>Many Linux distros (mostly Debian-based) configure OpenJDK to use <code>/dev/random</code> for entropy.</p>\n\n<p><code>/dev/random</code> is by definition slow (and can even block).</p>\n\n<p>From here you have two options on how to unblock it:</p>\n\n<ol>\n<li>Improve entropy, or</li>\n<li>Reduce randomness requirements.</li>\n</ol>\n\n<p><strong>Option 1, Improve entropy</strong></p>\n\n<p>To get more entropy into <code>/dev/random</code>, try the <a href=\"https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged\" rel=\"noreferrer\"><strong>haveged</strong></a> daemon. It's a daemon that continuously collects HAVEGE entropy, and works also in a virtualized environment because it doesn't require any special hardware, only the CPU itself and a clock.</p>\n\n<p>On Ubuntu/Debian:</p>\n\n<pre><code>apt-get install haveged\nupdate-rc.d haveged defaults\nservice haveged start\n</code></pre>\n\n<p>On RHEL/CentOS:</p>\n\n<pre><code>yum install haveged\nsystemctl enable haveged\nsystemctl start haveged\n</code></pre>\n\n<p><strong>Option 2. Reduce randomness requirements</strong></p>\n\n<p>If for some reason the solution above doesn't help or you don't care about cryptographically strong randomness, you can switch to <code>/dev/urandom</code> instead, which is guaranteed not to block.</p>\n\n<p>To do it globally, edit the file <code>jre/lib/security/java.security</code> in your default Java installation to use <code>/dev/urandom</code> (due to another <a href=\"https://bugs.openjdk.java.net/browse/JDK-6202721\" rel=\"noreferrer\">bug</a> it needs to be specified as <code>/dev/./urandom</code>).</p>\n\n<p>Like this:</p>\n\n<pre><code>#securerandom.source=file:/dev/random\nsecurerandom.source=file:/dev/./urandom\n</code></pre>\n\n<p>Then you won't ever have to specify it on the command line.</p>\n\n<hr>\n\n<p>Note: If you do cryptography, you <em>need</em> good entropy. Case in point - <a href=\"https://bitcoin.org/en/alert/2013-08-11-android\" rel=\"noreferrer\">android PRNG issue</a> reduced the security of Bitcoin wallets.</p>\n"
},
{
"answer_id": 58182522,
"author": "SQB",
"author_id": 2936460,
"author_profile": "https://Stackoverflow.com/users/2936460",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#GUID-9DC4ADD5-6D01-4B2E-9E85-B88E3BEE7453\" rel=\"nofollow noreferrer\" title=\"JDK Providers Documentation – Table 4-3 Default SecureRandom Implementations\">the documentation</a>, the different algorithms used by SecureRandom are, in order of preference:</p>\n<ul>\n<li>On most *NIX systems (including macOS)\n<ol>\n<li>PKCS11 (only on Solaris)</li>\n<li>NativePRNG</li>\n<li>SHA1PRNG</li>\n<li>NativePRNGBlocking</li>\n<li>NativePRNGNonBlocking</li>\n</ol>\n</li>\n<li>On Windows systems\n<ol>\n<li>DRBG</li>\n<li>SHA1PRNG</li>\n<li>Windows-PRNG</li>\n</ol>\n</li>\n</ul>\n<p>Since you asked about Linux, I will ignore the Windows implementation, as well as PKCS11 which is only really available on Solaris, unless you installed it yourself — and if you did, you probably wouldn't be asking this question.</p>\n<p>According to that same documentation, <a href=\"https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#d53600e823\" rel=\"nofollow noreferrer\" title=\"JDK Providers Documentation – Table 4-4 Algorithms in SUN provider\">what these algorithms use</a> are</p>\n<h5>SHA1PRNG</h5>\n<p>Initial seeding is currently done via a combination of system attributes and the java.security entropy gathering device.</p>\n<h5>NativePRNG</h5>\n<p><code>nextBytes()</code> uses <code>/dev/urandom</code><br />\n<code>generateSeed()</code> uses <code>/dev/random</code></p>\n<h5>NativePRNGBlocking</h5>\n<p><code>nextBytes()</code> and <code>generateSeed()</code> use <code>/dev/random</code></p>\n<h5>NativePRNGNonBlocking</h5>\n<p><code>nextBytes()</code> and <code>generateSeed()</code> use <code>/dev/urandom</code></p>\n<hr />\n<p>That means if you use <code>SecureRandom random = new SecureRandom()</code>, it goes down that list until it finds one that works, which will typically be NativePRNG. And that means that it seeds itself from <code>/dev/random</code> (or uses that if you explicitly generate a seed), then uses <code>/dev/urandom</code> for getting the next bytes, ints, double, booleans, what-have-yous.</p>\n<p>Since <code>/dev/random</code> is blocking (it blocks until it has enough entropy in the entropy pool), that may impede performance.</p>\n<p>One solution to that is using something like haveged to generate enough entropy, another solution is using <code>/dev/urandom</code> instead. While you could set that for the entire jvm, a better solution is doing it for this specific instance of <code>SecureRandom</code>, by using <code>SecureRandom random = SecureRandom.getInstance("NativePRNGNonBlocking")</code>. Note that that method can throw a NoSuchAlgorithmException if NativePRNGNonBlocking is unavailable, so be prepared to fall back to the default.</p>\n<pre><code>SecureRandom random;\ntry {\n random = SecureRandom.getInstance("NativePRNGNonBlocking");\n} catch (NoSuchAlgorithmException nsae) {\n random = new SecureRandom();\n}\n</code></pre>\n<p>Also note that on other *nix systems, <a href=\"https://en.wikipedia.org/wiki//dev/random#FreeBSD\" rel=\"nofollow noreferrer\" title=\"/dev/random on Wikipedia, section FreeBSD\"><code>/dev/urandom</code> may behave differently</a>.</p>\n<hr />\n<h3>Is <code>/dev/urandom</code> random enough?</h3>\n<p>Conventional wisdom has it that only <code>/dev/random</code> is random enough. However, some voices differ. In <a href=\"https://tersesystems.com/blog/2015/12/17/the-right-way-to-use-securerandom/\" rel=\"nofollow noreferrer\" title=\"Terse System: 'The Right Way to Use SecureRandom'\">"The Right Way to Use SecureRandom"</a> and <a href=\"https://www.2uo.de/myths-about-urandom/\" rel=\"nofollow noreferrer\" title=\"Myths about /dev/urandom by Thomas Hühn\">"Myths about /dev/urandom"</a>, it is argued that <code>/dev/urandom/</code> is just as good.</p>\n<p>The users over on the Information Security stack <a href=\"https://security.stackexchange.com/a/3939/34215\" title=\"Is a rand from /dev/urandom secure for a login key?\">agree with that</a>. Basically, if you have to ask, <code>/dev/urandom</code> is fine for your purpose.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150/"
]
| If you want a cryptographically strong random numbers in Java, you use `SecureRandom`. Unfortunately, `SecureRandom` can be very slow. If it uses `/dev/random` on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty?
Has anyone used [Uncommon Maths](https://uncommons-maths.dev.java.net/) as a solution to this problem?
Can anybody confirm that this performance problem has been solved in JDK 6? | If you want true random data, then unfortunately you have to wait for it. This includes the seed for a `SecureRandom` PRNG. Uncommon Maths can't gather true random data any faster than `SecureRandom`, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than `/dev/random` where that's available.
If you want a PRNG, do something like this:
```
SecureRandom.getInstance("SHA1PRNG");
```
What strings are supported depends on the `SecureRandom` SPI provider, but you can enumerate them using `Security.getProviders()` and `Provider.getService()`.
Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.
The exception is that if you don't call `setSeed()` before getting data, then the PRNG will seed itself once the first time you call `next()` or `nextBytes()`. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful. |
137,219 | <p>I am looking for the way to mount NTFS hard disk on FreeBSD 6.2 in read/write mode.</p>
<p>searching google, I found that NTFS-3G can be a help.</p>
<p>Using NTFS-3G, there is no problem when I try to mount/unmount NTFS manually:</p>
<p>mount: ntfs-3g /dev/ad1s1 /home/admin/data -o uid=1002,</p>
<p>or</p>
<p>umount: umount /home/admin/data</p>
<p>But I have a problem when try to mount ntfs hard disk automatically at boot time.</p>
<p>I have tried: </p>
<ul>
<li>adding fstab: /dev/ad1s1 /home/admin/data ntfs-3g uid=1002 0 0</li>
<li>make a script, that automatically mount ntfs partition at start up, on /usr/local/etc/rc.d/ directory.</li>
</ul>
<p>But it is still failed.
The script works well when it is executed manually.</p>
<p>Does anyone know an alternative method/ solution to have read/write access NTFS on FreeBSD 6.2?</p>
<p>Thanks.</p>
| [
{
"answer_id": 137223,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": "<p>I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a seed, then dies. The method which you call for randoms will join to that thread if it is alive so the first call only blocks if it occurs very early in program execution.</p>\n"
},
{
"answer_id": 137252,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 3,
"selected": false,
"text": "<p>The problem you referenced about <code>/dev/random</code> is not with the <code>SecureRandom</code> algorithm, but with the source of randomness that it uses. The two are orthogonal. You should figure out which one of the two is slowing you down.</p>\n\n<p>Uncommon Maths page that you linked explicitly mentions that they are not addressing the source of randomness.</p>\n\n<p>You can try different JCE providers, such as BouncyCastle, to see if their implementation of <code>SecureRandom</code> is faster.</p>\n\n<p>A brief <a href=\"http://www.google.com/search?q=fortuna+/dev/random\" rel=\"nofollow noreferrer\">search</a> also reveals Linux patches that replace the default implementation with Fortuna. I don't know much more about this, but you're welcome to investigate.</p>\n\n<p>I should also mention that while it's very dangerous to use a badly implemented <code>SecureRandom</code> algorithm and/or randomness source, you can roll your own JCE Provider with a custom implementation of <code>SecureRandomSpi</code>. You will need to go through a process with Sun to get your provider signed, but it's actually pretty straightforward; they just need you to fax them a form stating that you're aware of the US export restrictions on crypto libraries.</p>\n"
},
{
"answer_id": 137288,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 8,
"selected": true,
"text": "<p>If you want true random data, then unfortunately you have to wait for it. This includes the seed for a <code>SecureRandom</code> PRNG. Uncommon Maths can't gather true random data any faster than <code>SecureRandom</code>, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than <code>/dev/random</code> where that's available.</p>\n\n<p>If you want a PRNG, do something like this:</p>\n\n<pre><code>SecureRandom.getInstance(\"SHA1PRNG\");\n</code></pre>\n\n<p>What strings are supported depends on the <code>SecureRandom</code> SPI provider, but you can enumerate them using <code>Security.getProviders()</code> and <code>Provider.getService()</code>.</p>\n\n<p>Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.</p>\n\n<p>The exception is that if you don't call <code>setSeed()</code> before getting data, then the PRNG will seed itself once the first time you call <code>next()</code> or <code>nextBytes()</code>. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of \"hash the current time together with the PID, add 27, and hope for the best\". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.</p>\n"
},
{
"answer_id": 137626,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>My experience has been only with slow initialization of the PRNG, not with generation of random data after that. Try a more eager initialization strategy. Since they're expensive to create, treat it like a singleton and reuse the same instance. If there's too much thread contention for one instance, pool them or make them thread-local.</p>\n\n<p>Don't compromise on random number generation. A weakness there compromises all of your security.</p>\n\n<p>I don't see a lot of COTS atomic-decay–based generators, but there are several plans out there for them, if you really need a lot of random data. One site that always has interesting things to look at, including HotBits, is <a href=\"http://www.fourmilab.ch/\" rel=\"nofollow noreferrer\">John Walker's Fourmilab.</a></p>\n"
},
{
"answer_id": 138745,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 5,
"selected": false,
"text": "<p>On Linux, the default implementation for <code>SecureRandom</code> is <code>NativePRNG</code> (source code <a href=\"http://www.java2s.com/Open-Source/Java/6.0-JDK-Platform/solaris/sun/security/provider/NativePRNG.java.htm\" rel=\"noreferrer\">here</a>), which tends to be very slow. On Windows, the default is <code>SHA1PRNG</code>, which as others pointed out you can also use on Linux if you specify it explicitly.</p>\n\n<p><code>NativePRNG</code> differs from <code>SHA1PRNG</code> and Uncommons Maths' <a href=\"http://maths.uncommons.org/api/org/uncommons/maths/random/AESCounterRNG.html\" rel=\"noreferrer\">AESCounterRNG</a> in that it continuously receives entropy from the operating system (by reading from <code>/dev/urandom</code>). The other PRNGs do not acquire any additional entropy after seeding.</p>\n\n<p>AESCounterRNG is about 10x faster than <code>SHA1PRNG</code>, which IIRC is itself two or three times faster than <code>NativePRNG</code>.</p>\n\n<p>If you need a faster PRNG that acquires entropy after initialization, see if you can find a Java implementation of <a href=\"http://en.wikipedia.org/wiki/Fortuna_(PRNG)\" rel=\"noreferrer\">Fortuna</a>. The core PRNG of a Fortuna implementation is identical to that used by AESCounterRNG, but there is also a sophisticated system of entropy pooling and automatic reseeding.</p>\n"
},
{
"answer_id": 139165,
"author": "Lorenzo Boccaccia",
"author_id": 2273540,
"author_profile": "https://Stackoverflow.com/users/2273540",
"pm_score": 2,
"selected": false,
"text": "<p>Use the secure random as initialization source for a recurrent algorithm; you could use then a Mersenne twister for the bulk work instead of the one in UncommonMath, which has been around for a while and proven better than other prng</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Mersenne_twister\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Mersenne_twister</a></p>\n\n<p>Make sure to refresh now and then the secure random used for the initialization, for example you could have one secure random generated per client, using one mersenne twister pseudo random generator per client, obtaining a high enough degree of randomization</p>\n"
},
{
"answer_id": 140921,
"author": "Chris Kite",
"author_id": 9573,
"author_profile": "https://Stackoverflow.com/users/9573",
"pm_score": 4,
"selected": false,
"text": "<p>If you want truly \"cryptographically strong\" randomness, then you need a strong entropy source. <code>/dev/random</code> is slow because it has to wait for system events to gather entropy (disk reads, network packets, mouse movement, key presses, etc.).</p>\n\n<p>A faster solution is a hardware random number generator. You may already have one built-in to your motherboard; check out the <a href=\"http://www.mjmwired.net/kernel/Documentation/hw_random.txt\" rel=\"noreferrer\">hw_random documentation</a> for instructions on figuring out if you have it, and how to use it. The rng-tools package includes a daemon which will feed hardware generated entropy into <code>/dev/random</code>.</p>\n\n<p>If a HRNG is not available on your system, and you are willing to sacrifice entropy strength for performance, you will want to seed a good PRNG with data from <code>/dev/random</code>, and let the PRNG do the bulk of the work. There are several NIST-approved PRNG's listed in <a href=\"http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf\" rel=\"noreferrer\">SP800-90</a> which are straightforward to implement.</p>\n"
},
{
"answer_id": 169338,
"author": "Diastrophism",
"author_id": 18093,
"author_profile": "https://Stackoverflow.com/users/18093",
"pm_score": 1,
"selected": false,
"text": "<p>Something else to look at is the property securerandom.source in file lib/security/java.security\n<P>There may be a performance benefit to using /dev/urandom rather than /dev/random. Remember that if the quality of the random numbers is important, don't make a compromise which breaks security.</p>\n"
},
{
"answer_id": 388984,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.</p>\n\n<p>If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with <a href=\"https://stackoverflow.com/questions/137212/how-to-solve-performance-problem-with-java-securerandom#138745\">Dan Dyer's response</a> about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.</p>\n\n<p>I would <em>think</em> that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's <a href=\"http://www.ecrypt.eu.org/stream/\" rel=\"nofollow noreferrer\">eStream</a> project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.</p>\n\n<p>Edit: here's some <a href=\"http://www.tml.tkk.fi/Opinnot/T-110.470/2004/20041101.pdf\" rel=\"nofollow noreferrer\">cryptographic course notes on RNG</a> I found on the 'net that look very relevant to this topic.</p>\n"
},
{
"answer_id": 2325109,
"author": "Thomas Leonard",
"author_id": 50926,
"author_profile": "https://Stackoverflow.com/users/50926",
"pm_score": 8,
"selected": false,
"text": "<p>You should be able to select the faster-but-slightly-less-secure /dev/urandom on Linux using:</p>\n\n<pre><code>-Djava.security.egd=file:/dev/urandom\n</code></pre>\n\n<p>However, this doesn't work with Java 5 and later (<a href=\"https://bugs.openjdk.java.net/browse/JDK-6202721\" rel=\"noreferrer\">Java Bug 6202721</a>). The suggested work-around is to use:</p>\n\n<pre><code>-Djava.security.egd=file:/dev/./urandom\n</code></pre>\n\n<p>(note the extra <code>/./</code>)</p>\n"
},
{
"answer_id": 12159344,
"author": "David K",
"author_id": 1324595,
"author_profile": "https://Stackoverflow.com/users/1324595",
"pm_score": 3,
"selected": false,
"text": "<p>There is a tool (on Ubuntu at least) that will feed artificial randomness into your system. The command is simply:</p>\n\n<pre><code>rngd -r /dev/urandom\n</code></pre>\n\n<p>and you may need a sudo at the front. If you don't have rng-tools package, you will need to install it. I tried this, and it definitely helped me!</p>\n\n<p>Source: <a href=\"http://www.mattvsworld.com/blog/2010/02/speed-up-key-generation-with-artificial-entropy/\" rel=\"noreferrer\">matt vs world</a></p>\n"
},
{
"answer_id": 18816044,
"author": "user2781824",
"author_id": 2781824,
"author_profile": "https://Stackoverflow.com/users/2781824",
"pm_score": 2,
"selected": false,
"text": "<p>If your hardware supports it try <a href=\"https://github.com/hpadmanabhan/rdrand-util\" rel=\"nofollow noreferrer\">using Java RdRand Utility</a> of which I'm the author.</p>\n\n<p>Its based on Intel's <code>RDRAND</code> instruction and is about 10 times faster than <code>SecureRandom</code> and no bandwidth issues for large volume implementation.</p>\n\n<hr>\n\n<p>Note that this implementation only works on those CPU's that provide the instruction (i.e. when the <code>rdrand</code> processor flag is set). You need to explicitly instantiate it through the <code>RdRandRandom()</code> constructor; no specific <code>Provider</code> has been implemented.</p>\n"
},
{
"answer_id": 30358935,
"author": "thunder",
"author_id": 3438692,
"author_profile": "https://Stackoverflow.com/users/3438692",
"pm_score": 4,
"selected": false,
"text": "<p>I had a similar problem with calls to <code>SecureRandom</code> blocking for about 25 seconds at a time on a headless Debian server. I installed the <code>haveged</code> daemon to ensure <code>/dev/random</code> is kept topped up, on headless servers you need something like this to generate the required entropy. \nMy calls to <code>SecureRandom</code> now perhaps take milliseconds. </p>\n"
},
{
"answer_id": 40647569,
"author": "so-random-dude",
"author_id": 6785908,
"author_profile": "https://Stackoverflow.com/users/6785908",
"pm_score": 3,
"selected": false,
"text": "<p>I faced same <a href=\"https://stackoverflow.com/questions/40383430/tomcat-takes-too-much-time-to-start-java-securerandom\">issue</a>. After some Googling with the right search terms, I came across this nice article on <a href=\"https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged\" rel=\"nofollow noreferrer\">DigitalOcean</a>. </p>\n\n<h2>haveged is a potential solution without compromising on security.</h2>\n\n<p>I am merely quoting the relevant part from the article here.</p>\n\n<blockquote>\n <p>Based on the HAVEGE principle, and previously based on its associated\n library, haveged allows generating randomness based on variations in\n code execution time on a processor. Since it's nearly impossible for\n one piece of code to take the same exact time to execute, even in the\n same environment on the same hardware, the timing of running a single\n or multiple programs should be suitable to seed a random source. The\n haveged implementation seeds your system's random source (usually\n /dev/random) using differences in your processor's time stamp counter\n (TSC) after executing a loop repeatedly</p>\n</blockquote>\n\n<h2>How to install haveged</h2>\n\n<p>Follow the steps in this article. <a href=\"https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged\" rel=\"nofollow noreferrer\">https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged</a></p>\n\n<p>I have posted it <a href=\"https://stackoverflow.com/a/40603084/6785908\">here</a></p>\n"
},
{
"answer_id": 40885767,
"author": "Lachlan",
"author_id": 94152,
"author_profile": "https://Stackoverflow.com/users/94152",
"pm_score": 3,
"selected": false,
"text": "<p>Using Java 8, I found that on Linux calling <code>SecureRandom.getInstanceStrong()</code> would give me the <code>NativePRNGBlocking</code> algorithm. This would often block for many seconds to generate a few bytes of salt.</p>\n\n<p>I switched to explicitly asking for <code>NativePRNGNonBlocking</code> instead, and as expected from the name, it no longer blocked. I have no idea what the security implications of this are. Presumably the non-blocking version can't guarantee the amount of entropy being used.</p>\n\n<p><strong>Update</strong>: Ok, I found <a href=\"https://tersesystems.com/2015/12/17/the-right-way-to-use-securerandom/\" rel=\"noreferrer\">this excellent explanation</a>.</p>\n\n<p>In a nutshell, to avoid blocking, use <code>new SecureRandom()</code>. This uses <code>/dev/urandom</code>, which doesn't block and is basically as secure as <code>/dev/random</code>. From the post: \"The only time you would want to call /dev/random is when the machine is first booting, and entropy has not yet accumulated\".</p>\n\n<p><code>SecureRandom.getInstanceStrong()</code> gives you the absolute strongest RNG, but it's only safe to use in situations where a bunch of blocking won't effect you.</p>\n"
},
{
"answer_id": 47097219,
"author": "rustyx",
"author_id": 485343,
"author_profile": "https://Stackoverflow.com/users/485343",
"pm_score": 5,
"selected": false,
"text": "<p>Many Linux distros (mostly Debian-based) configure OpenJDK to use <code>/dev/random</code> for entropy.</p>\n\n<p><code>/dev/random</code> is by definition slow (and can even block).</p>\n\n<p>From here you have two options on how to unblock it:</p>\n\n<ol>\n<li>Improve entropy, or</li>\n<li>Reduce randomness requirements.</li>\n</ol>\n\n<p><strong>Option 1, Improve entropy</strong></p>\n\n<p>To get more entropy into <code>/dev/random</code>, try the <a href=\"https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged\" rel=\"noreferrer\"><strong>haveged</strong></a> daemon. It's a daemon that continuously collects HAVEGE entropy, and works also in a virtualized environment because it doesn't require any special hardware, only the CPU itself and a clock.</p>\n\n<p>On Ubuntu/Debian:</p>\n\n<pre><code>apt-get install haveged\nupdate-rc.d haveged defaults\nservice haveged start\n</code></pre>\n\n<p>On RHEL/CentOS:</p>\n\n<pre><code>yum install haveged\nsystemctl enable haveged\nsystemctl start haveged\n</code></pre>\n\n<p><strong>Option 2. Reduce randomness requirements</strong></p>\n\n<p>If for some reason the solution above doesn't help or you don't care about cryptographically strong randomness, you can switch to <code>/dev/urandom</code> instead, which is guaranteed not to block.</p>\n\n<p>To do it globally, edit the file <code>jre/lib/security/java.security</code> in your default Java installation to use <code>/dev/urandom</code> (due to another <a href=\"https://bugs.openjdk.java.net/browse/JDK-6202721\" rel=\"noreferrer\">bug</a> it needs to be specified as <code>/dev/./urandom</code>).</p>\n\n<p>Like this:</p>\n\n<pre><code>#securerandom.source=file:/dev/random\nsecurerandom.source=file:/dev/./urandom\n</code></pre>\n\n<p>Then you won't ever have to specify it on the command line.</p>\n\n<hr>\n\n<p>Note: If you do cryptography, you <em>need</em> good entropy. Case in point - <a href=\"https://bitcoin.org/en/alert/2013-08-11-android\" rel=\"noreferrer\">android PRNG issue</a> reduced the security of Bitcoin wallets.</p>\n"
},
{
"answer_id": 58182522,
"author": "SQB",
"author_id": 2936460,
"author_profile": "https://Stackoverflow.com/users/2936460",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#GUID-9DC4ADD5-6D01-4B2E-9E85-B88E3BEE7453\" rel=\"nofollow noreferrer\" title=\"JDK Providers Documentation – Table 4-3 Default SecureRandom Implementations\">the documentation</a>, the different algorithms used by SecureRandom are, in order of preference:</p>\n<ul>\n<li>On most *NIX systems (including macOS)\n<ol>\n<li>PKCS11 (only on Solaris)</li>\n<li>NativePRNG</li>\n<li>SHA1PRNG</li>\n<li>NativePRNGBlocking</li>\n<li>NativePRNGNonBlocking</li>\n</ol>\n</li>\n<li>On Windows systems\n<ol>\n<li>DRBG</li>\n<li>SHA1PRNG</li>\n<li>Windows-PRNG</li>\n</ol>\n</li>\n</ul>\n<p>Since you asked about Linux, I will ignore the Windows implementation, as well as PKCS11 which is only really available on Solaris, unless you installed it yourself — and if you did, you probably wouldn't be asking this question.</p>\n<p>According to that same documentation, <a href=\"https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#d53600e823\" rel=\"nofollow noreferrer\" title=\"JDK Providers Documentation – Table 4-4 Algorithms in SUN provider\">what these algorithms use</a> are</p>\n<h5>SHA1PRNG</h5>\n<p>Initial seeding is currently done via a combination of system attributes and the java.security entropy gathering device.</p>\n<h5>NativePRNG</h5>\n<p><code>nextBytes()</code> uses <code>/dev/urandom</code><br />\n<code>generateSeed()</code> uses <code>/dev/random</code></p>\n<h5>NativePRNGBlocking</h5>\n<p><code>nextBytes()</code> and <code>generateSeed()</code> use <code>/dev/random</code></p>\n<h5>NativePRNGNonBlocking</h5>\n<p><code>nextBytes()</code> and <code>generateSeed()</code> use <code>/dev/urandom</code></p>\n<hr />\n<p>That means if you use <code>SecureRandom random = new SecureRandom()</code>, it goes down that list until it finds one that works, which will typically be NativePRNG. And that means that it seeds itself from <code>/dev/random</code> (or uses that if you explicitly generate a seed), then uses <code>/dev/urandom</code> for getting the next bytes, ints, double, booleans, what-have-yous.</p>\n<p>Since <code>/dev/random</code> is blocking (it blocks until it has enough entropy in the entropy pool), that may impede performance.</p>\n<p>One solution to that is using something like haveged to generate enough entropy, another solution is using <code>/dev/urandom</code> instead. While you could set that for the entire jvm, a better solution is doing it for this specific instance of <code>SecureRandom</code>, by using <code>SecureRandom random = SecureRandom.getInstance("NativePRNGNonBlocking")</code>. Note that that method can throw a NoSuchAlgorithmException if NativePRNGNonBlocking is unavailable, so be prepared to fall back to the default.</p>\n<pre><code>SecureRandom random;\ntry {\n random = SecureRandom.getInstance("NativePRNGNonBlocking");\n} catch (NoSuchAlgorithmException nsae) {\n random = new SecureRandom();\n}\n</code></pre>\n<p>Also note that on other *nix systems, <a href=\"https://en.wikipedia.org/wiki//dev/random#FreeBSD\" rel=\"nofollow noreferrer\" title=\"/dev/random on Wikipedia, section FreeBSD\"><code>/dev/urandom</code> may behave differently</a>.</p>\n<hr />\n<h3>Is <code>/dev/urandom</code> random enough?</h3>\n<p>Conventional wisdom has it that only <code>/dev/random</code> is random enough. However, some voices differ. In <a href=\"https://tersesystems.com/blog/2015/12/17/the-right-way-to-use-securerandom/\" rel=\"nofollow noreferrer\" title=\"Terse System: 'The Right Way to Use SecureRandom'\">"The Right Way to Use SecureRandom"</a> and <a href=\"https://www.2uo.de/myths-about-urandom/\" rel=\"nofollow noreferrer\" title=\"Myths about /dev/urandom by Thomas Hühn\">"Myths about /dev/urandom"</a>, it is argued that <code>/dev/urandom/</code> is just as good.</p>\n<p>The users over on the Information Security stack <a href=\"https://security.stackexchange.com/a/3939/34215\" title=\"Is a rand from /dev/urandom secure for a login key?\">agree with that</a>. Basically, if you have to ask, <code>/dev/urandom</code> is fine for your purpose.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am looking for the way to mount NTFS hard disk on FreeBSD 6.2 in read/write mode.
searching google, I found that NTFS-3G can be a help.
Using NTFS-3G, there is no problem when I try to mount/unmount NTFS manually:
mount: ntfs-3g /dev/ad1s1 /home/admin/data -o uid=1002,
or
umount: umount /home/admin/data
But I have a problem when try to mount ntfs hard disk automatically at boot time.
I have tried:
* adding fstab: /dev/ad1s1 /home/admin/data ntfs-3g uid=1002 0 0
* make a script, that automatically mount ntfs partition at start up, on /usr/local/etc/rc.d/ directory.
But it is still failed.
The script works well when it is executed manually.
Does anyone know an alternative method/ solution to have read/write access NTFS on FreeBSD 6.2?
Thanks. | If you want true random data, then unfortunately you have to wait for it. This includes the seed for a `SecureRandom` PRNG. Uncommon Maths can't gather true random data any faster than `SecureRandom`, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than `/dev/random` where that's available.
If you want a PRNG, do something like this:
```
SecureRandom.getInstance("SHA1PRNG");
```
What strings are supported depends on the `SecureRandom` SPI provider, but you can enumerate them using `Security.getProviders()` and `Provider.getService()`.
Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.
The exception is that if you don't call `setSeed()` before getting data, then the PRNG will seed itself once the first time you call `next()` or `nextBytes()`. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful. |
137,221 | <p>I've searched around for a while today, but I haven't been able to come up with an AutoComplete TextBox code sample for Silverlight 2 Beta 2. The most promising reference was found on <a href="http://www.nikhilk.net/Silverlight-AutoComplete.aspx/" rel="nofollow noreferrer">nikhilk.net</a> but the online demo doesn't currently render and after downloading a getting the code to compile with Beta 2, I couldn't get the Silverlight plugin it to render either. I think it is fair to say it is a compatibility issue, but I'm not sure. Does anyone have any alternate sample code or implementation suggestions?</p>
| [
{
"answer_id": 137231,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at the combobox(very close to a autocomplete text box) at worksight's blog <a href=\"http://worksightblog.com/?p=72\" rel=\"nofollow noreferrer\">Silverlight ComboBox</a></p>\n"
},
{
"answer_id": 140167,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 3,
"selected": true,
"text": "<p>You may want to take a look at my blog: <a href=\"http://weblogs.manas.com.ar/ary/2008/09/26/autocomplete-in-silverlight/\" rel=\"nofollow noreferrer\">http://weblogs.manas.com.ar/ary/2008/09/26/autocomplete-in-silverlight/</a></p>\n\n<p>You simply write in your XAML:</p>\n\n<pre><code>manas:Autocomplete.Suggest=\"DoSuggest\"\n</code></pre>\n\n<p>and then in the class file, you need to implement that method, which report suggestions to a delegate. The options can be hardcoded, requested to a web service, or whaterver.</p>\n"
},
{
"answer_id": 1698888,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>There is also another good example here:</p>\n\n<p><a href=\"http://silvermail.com.au\" rel=\"nofollow noreferrer\">http://silvermail.com.au</a></p>\n\n<p>This is a Silverlight based mail client that looks a little like Outlook. When I go to send mail and start typing in the \"To\" text box, an auto-complete pops up and populates the control for me based on values in a list... I think it automatically stores the addresses in isolated storage, but that's just a guess.</p>\n\n<p>This is a really handy tool for checking mail while away from my home PC... at work for example... and it is loaded with impressive Silverlight functionality.</p>\n\n<p>S.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115/"
]
| I've searched around for a while today, but I haven't been able to come up with an AutoComplete TextBox code sample for Silverlight 2 Beta 2. The most promising reference was found on [nikhilk.net](http://www.nikhilk.net/Silverlight-AutoComplete.aspx/) but the online demo doesn't currently render and after downloading a getting the code to compile with Beta 2, I couldn't get the Silverlight plugin it to render either. I think it is fair to say it is a compatibility issue, but I'm not sure. Does anyone have any alternate sample code or implementation suggestions? | You may want to take a look at my blog: <http://weblogs.manas.com.ar/ary/2008/09/26/autocomplete-in-silverlight/>
You simply write in your XAML:
```
manas:Autocomplete.Suggest="DoSuggest"
```
and then in the class file, you need to implement that method, which report suggestions to a delegate. The options can be hardcoded, requested to a web service, or whaterver. |
137,227 | <p>How can I list all the types that are declared by a module in Ruby?</p>
| [
{
"answer_id": 137311,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 6,
"selected": true,
"text": "<p>Use the <em>constants</em> method defined in the <em>Module</em> module. From the Ruby documentation:</p>\n\n<blockquote>\n <p>Module.constants => array</p>\n \n <p>Returns an array of the names of all\n constants defined in the system. This\n list includes the names of all modules\n and classes.</p>\n \n <p>p Module.constants.sort[1..5]</p>\n \n <p>produces:</p>\n \n <p>[\"ARGV\", \"ArgumentError\", \"Array\",\n \"Bignum\", \"Binding\"]</p>\n</blockquote>\n\n<p>You can call <em>constants</em> on any module or class you would like.</p>\n\n<pre><code>p Class.constants\n</code></pre>\n"
},
{
"answer_id": 137334,
"author": "zackola",
"author_id": 321427,
"author_profile": "https://Stackoverflow.com/users/321427",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure if this is what you mean, but you can grab an array of the names of all constants and classes defined in a module by doing</p>\n\n<blockquote>\n <blockquote>\n <blockquote>\n <p>ModuleName.constants</p>\n </blockquote>\n </blockquote>\n</blockquote>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
| How can I list all the types that are declared by a module in Ruby? | Use the *constants* method defined in the *Module* module. From the Ruby documentation:
>
> Module.constants => array
>
>
> Returns an array of the names of all
> constants defined in the system. This
> list includes the names of all modules
> and classes.
>
>
> p Module.constants.sort[1..5]
>
>
> produces:
>
>
> ["ARGV", "ArgumentError", "Array",
> "Bignum", "Binding"]
>
>
>
You can call *constants* on any module or class you would like.
```
p Class.constants
``` |
137,255 | <p>How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?</p>
| [
{
"answer_id": 137294,
"author": "Kepboy",
"author_id": 21429,
"author_profile": "https://Stackoverflow.com/users/21429",
"pm_score": 2,
"selected": false,
"text": "<p>Are you talking about mapping a network share to a logical drive on you computer?</p>\n\n<p>If so you can use DriveInfo.</p>\n\n<pre>\n DriveInfo info = new DriveInfo(\"X:\");\n\n info.AvailableFreeSpace;\n</pre>\n\n<p>DriveInfo only works with logical drives so if you are just using the full share (UNC) name I don't think the above code will work.</p>\n"
},
{
"answer_id": 137347,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 4,
"selected": true,
"text": "<p>There are two possible solutions. </p>\n\n<ol>\n<li><p>Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program:</p>\n\n<pre><code>internal static class Win32\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);\n\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n long freeBytesForUser;\n long totalBytes;\n long freeBytes;\n\n if (Win32.GetDiskFreeSpaceEx(@\"\\\\prime\\cargohold\", out freeBytesForUser, out totalBytes, out freeBytes)) {\n Console.WriteLine(freeBytesForUser);\n Console.WriteLine(totalBytes);\n Console.WriteLine(freeBytes);\n }\n }\n}\n</code></pre></li>\n<li><p>Use the system management interface. There is another answer in this post which describes this. This method is really designed for use in scripting languages such as PowerShell. It performs a lot of fluff just to get the right object. Ultimately, I suspect, this method boils down to calling GetDiskFreeSpaceEx.</p></li>\n</ol>\n\n<p>Anybody doing any serious Windows development in C# will probably end up calling many Win32 functions. The .NET framework just doesn't cover 100% of the Win32 API. Any large program will quickly uncover gaps in the .NET libraries that are only available through the Win32 API. I would get hold of one of the Win32 wrappers for .NET and include this in your project. This will give you instant access to just about every Win32 API.</p>\n"
},
{
"answer_id": 137348,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if GetDiskFreeSpaceEx works on UNC shares, but if it does use that, otherwise here is how to mount a UNC share to a logal drive:</p>\n\n<p><strong>EDIT</strong> GetDiskFreeSpaceEx does work on UNC shares, use that...however, this code was too much effort to just delete, and is handy if you ever want to mount a UNC share as a local drive in your code.</p>\n\n<pre><code>public class DriveWrapper\n{ \n [StructLayout(LayoutKind.Sequential)]\n public struct NETRESOURCEA\n {\n public int dwScope;\n public int dwType;\n public int dwDisplayType;\n public int dwUsage;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpLocalName;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpRemoteName;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpComment;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpProvider;\n public override String ToString()\n {\n String str = \"LocalName: \" + lpLocalName + \" RemoteName: \" + lpRemoteName\n + \" Comment: \" + lpComment + \" lpProvider: \" + lpProvider;\n return (str);\n }\n }\n\n [DllImport(\"mpr.dll\")]\n public static extern int WNetAddConnection2A(\n [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,\n [MarshalAs(UnmanagedType.LPStr)] string lpPassword,\n [MarshalAs(UnmanagedType.LPStr)] string UserName,\n int dwFlags); \n [DllImport(\"mpr.dll\", CharSet = System.Runtime.InteropServices.CharSet.Auto)]\n private static extern int WNetCancelConnection2A(\n [MarshalAs(UnmanagedType.LPStr)]\n string lpName,\n int dwFlags,\n int fForce\n );\n\n public int GetDriveSpace(string shareName, string userName, string password)\n {\n NETRESOURCEA[] n = new NETRESOURCEA[1];\n n[0] = new NETRESOURCEA();\n\n n[0].dwScope = 0;\n n[0].dwType = 0;\n n[0].dwDisplayType = 0;\n n[0].dwUsage = 0;\n\n n[0].dwType = 1;\n\n n[0].lpLocalName = \"x:\";\n n[0].lpRemoteName = shareName;\n n[0].lpProvider = null;\n\n int res = WNetAddConnection2A(n, userName, password, 1);\n\n DriveInfo info = new DriveInfo(\"x:\");\n int space = info.AvailableFreeSpace;\n\n int err = 0;\n err = WNetCancelConnection2A(\"x:\", 0, 1);\n\n return space;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 137357,
"author": "s d",
"author_id": 20911,
"author_profile": "https://Stackoverflow.com/users/20911",
"pm_score": 3,
"selected": false,
"text": "<p>Use WMI</p>\n\n<pre><code>using System.Management;\n\n// Get all the network drives (drivetype=4)\nSelectQuery query = new SelectQuery(\"select Name, VolumeName, FreeSpace from win32_logicaldisk where drivetype=4\");\nManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\nforeach (ManagementObject drive in searcher.Get())\n{\n string Name = (string)drive[\"Name\"];\n string VolumeName = (string)drive[\"VolumeName\"];\n UInt64 freeSpace = (UInt64)drive[\"FreeSpace\"];\n}\n</code></pre>\n\n<p>based on (stolen from) <a href=\"http://www.dreamincode.net/code/snippet1576.htm\" rel=\"noreferrer\">http://www.dreamincode.net/code/snippet1576.htm</a></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
]
| How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net? | There are two possible solutions.
1. Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program:
```
internal static class Win32
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
}
class Program
{
static void Main(string[] args)
{
long freeBytesForUser;
long totalBytes;
long freeBytes;
if (Win32.GetDiskFreeSpaceEx(@"\\prime\cargohold", out freeBytesForUser, out totalBytes, out freeBytes)) {
Console.WriteLine(freeBytesForUser);
Console.WriteLine(totalBytes);
Console.WriteLine(freeBytes);
}
}
}
```
2. Use the system management interface. There is another answer in this post which describes this. This method is really designed for use in scripting languages such as PowerShell. It performs a lot of fluff just to get the right object. Ultimately, I suspect, this method boils down to calling GetDiskFreeSpaceEx.
Anybody doing any serious Windows development in C# will probably end up calling many Win32 functions. The .NET framework just doesn't cover 100% of the Win32 API. Any large program will quickly uncover gaps in the .NET libraries that are only available through the Win32 API. I would get hold of one of the Win32 wrappers for .NET and include this in your project. This will give you instant access to just about every Win32 API. |
137,258 | <p>Here's a common code pattern I have to work with:</p>
<pre><code>class foo {
public:
void InitMap();
void InvokeMethodsInMap();
static void abcMethod();
static void defMethod();
private:
typedef std::map<const char*, pMethod> TMyMap;
TMyMap m_MyMap;
}
void
foo::InitMap()
{
m_MyMap["abc"] = &foo::abcMethod;
m_MyMap["def"] = &foo::defMethod;
}
void
foo::InvokeMethodsInMap()
{
for (TMyMap::const_iterator it = m_MyMap.begin();
it != m_MyMap.end(); it++)
{
(*it->second)(it->first);
}
}
</code></pre>
<p>However, I have found that the <em>order</em> that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order.</p>
<p>I thought that by using <code>begin()</code> in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed.</p>
<p>This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build).</p>
<p>Can anyone explain this strange behaviour?</p>
| [
{
"answer_id": 137264,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>Don't use <code>const char*</code> as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a <code>std::string</code> as the key type, instead.</p>\n\n<p><code>std::map</code> is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some criteria (by default, <code><</code> comparison between keys).</p>\n"
},
{
"answer_id": 137477,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": "<p>The definition of map is:<br>\n<b>map<Key, Data, Compare, Alloc></b></p>\n\n<p>Where the last two template parameters default too:<br>\nCompare: less<Key><br>\nAlloc: allocator<value_type><br></p>\n\n<p>When inserting new values into a map. The new value (valueToInsert) is compared against the old values in order (<b>N.B.</b> This is not sequential search, the standard guarantees a max insert complexity of O(log(N)) ) until Compare(value,ValueToInsert) returns true. Because you are using <b><i>'const char*'</i></b> as the key. The Compare Object is using <b><i>less<const char*></i></b> this class just does a < on the two values. So in effect you are comparing the pointer values (not the string) therefore the order is random (as you don't know where the compiler will put strings.</p>\n\n<p>There are two possible solutions:</p>\n\n<ul>\n<li>Change the type of the key so that it compares the string values.</li>\n<li>Define another Compare Type that does what you need.</li>\n</ul>\n\n<p>Personally I (like Chris) would just use a std::string because < operator used on strings returns a comparison based on the string content. But for arguments sake we can just define a Compare type.</p>\n\n<pre><code>struct StringLess\n{\n bool operator()(const char* const& left,const char* const& right) const\n {\n return strcmp(left,right) < 0;\n }\n};\n\n///\n\ntypedef std::map<const char*, int,StringLess> TMyMap;\n</code></pre>\n"
},
{
"answer_id": 137502,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use const char * as the key for your map, also set a key comparison function that uses strcmp (or similar) to compare the keys. That way your map will be ordered by the string's contents, rather than the string's pointer value (i.e. location in memory).</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22489/"
]
| Here's a common code pattern I have to work with:
```
class foo {
public:
void InitMap();
void InvokeMethodsInMap();
static void abcMethod();
static void defMethod();
private:
typedef std::map<const char*, pMethod> TMyMap;
TMyMap m_MyMap;
}
void
foo::InitMap()
{
m_MyMap["abc"] = &foo::abcMethod;
m_MyMap["def"] = &foo::defMethod;
}
void
foo::InvokeMethodsInMap()
{
for (TMyMap::const_iterator it = m_MyMap.begin();
it != m_MyMap.end(); it++)
{
(*it->second)(it->first);
}
}
```
However, I have found that the *order* that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order.
I thought that by using `begin()` in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed.
This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build).
Can anyone explain this strange behaviour? | Don't use `const char*` as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a `std::string` as the key type, instead.
`std::map` is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some criteria (by default, `<` comparison between keys). |
137,260 | <p>I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.</p>
<p>I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?</p>
| [
{
"answer_id": 137274,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>If you have users that override your virtual methods you can't seal them again without breaking code.</li>\n<li>Any virtual methods you call from the constructor may fall down to derived implementations and if they don't call the base method and the constructor depends on it, the object may be in an invalid state</li>\n</ul>\n"
},
{
"answer_id": 137281,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>Ayende has a nice treatment of how virtual methods work:</p>\n\n<p><a href=\"http://ayende.com/Blog/archive/2007/01/05/HowVirtualMethodsWork.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2007/01/05/HowVirtualMethodsWork.aspx</a></p>\n"
},
{
"answer_id": 137324,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:</p>\n\n<pre><code>class Base {\n public Base() {\n InitializeComponent();\n }\n protected virtual void InitializeComponent() {\n ...\n }\n}\n\nclass Derived : Base {\n private Button button1;\n public Derived() : base() {\n button1 = new Button();\n }\n protected override void InitializeComponent() {\n button1.Text = \"I'm gonna throw a null reference exception\"\n }\n}\n</code></pre>\n\n<p>The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
| I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.
I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for? | Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:
```
class Base {
public Base() {
InitializeComponent();
}
protected virtual void InitializeComponent() {
...
}
}
class Derived : Base {
private Button button1;
public Derived() : base() {
button1 = new Button();
}
protected override void InitializeComponent() {
button1.Text = "I'm gonna throw a null reference exception"
}
}
```
The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run. |
137,282 | <p><a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="noreferrer">http://en.wikipedia.org/wiki/Diamond_problem</a></p>
<p>I know what it means, but what steps can I take to avoid it?</p>
| [
{
"answer_id": 137289,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 4,
"selected": false,
"text": "<p>virtual inheritance. That's what it's there for.</p>\n"
},
{
"answer_id": 137317,
"author": "Bob Somers",
"author_id": 1384,
"author_profile": "https://Stackoverflow.com/users/1384",
"pm_score": 4,
"selected": false,
"text": "<p>I'd stick to using multiple inheritance of interfaces only. While multiple inheritance of classes is attractive sometimes, it can also be confusing and painful if you rely on it regularly.</p>\n"
},
{
"answer_id": 137344,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 2,
"selected": false,
"text": "<p>Well, the great thing about the Dreaded Diamond is that it's an error when it occurs. The best way to avoid is to figure out your inheritance structure beforehand. For instance, one project I work on has Viewers and Editors. Editors are logical subclasses of Viewers, but since all Viewers are subclasses - TextViewer, ImageViewer, etc., Editor does not derive from Viewer, thus allowing the final TextEditor, ImageEditor classes to avoid the diamond.</p>\n\n<p>In cases where the diamond is not avoidable, using virtual inheritance. The biggest caveat, however, with virtual bases, is that the constructor for the virtual base <em>must</em> be called by the most derived class, meaning that a class that derives virtually has no control over the constructor parameters. Also, the presence of a virtual base tends to incur a performance/space penalty on casting through the chain, though I don't believe there is much of a penalty for more beyond the first.</p>\n\n<p>Plus, you can always use the diamond if you are explicit about which base you want to use. Sometimes it's the only way.</p>\n"
},
{
"answer_id": 139257,
"author": "user17720",
"author_id": 17720,
"author_profile": "https://Stackoverflow.com/users/17720",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest a better class design. I'm sure there are some problems that are solved best through multiple inheritance, but check to see if there is another way first.</p>\n\n<p>If not, use virtual functions/interfaces.</p>\n"
},
{
"answer_id": 139329,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 7,
"selected": true,
"text": "<p>A practical example:</p>\n\n<pre><code>class A {};\nclass B : public A {};\nclass C : public A {};\nclass D : public B, public C {};\n</code></pre>\n\n<p>Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.</p>\n\n<p>To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:</p>\n\n<pre><code>class A {};\nclass B : virtual public A {};\nclass C : virtual public A {};\nclass D : public B, public C {};\n</code></pre>\n"
},
{
"answer_id": 143104,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Inheritance is a strong, strong weapon. Use it only when you really need it. In the past, diamond inheritance was a sign that I was going to far with classification, saying that a user is an \"employee\" but they are also a \"widget listener\", but also a ...</p>\n\n<p>In these cases, it's easy to hit multiple inheritance issues.</p>\n\n<p>I solved them by using composition and pointers back to the owner:</p>\n\n<p>Before:</p>\n\n<pre><code>class Employee : public WidgetListener, public LectureAttendee\n{\npublic:\n Employee(int x, int y)\n WidgetListener(x), LectureAttendee(y)\n {}\n};\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>class Employee\n{\npublic:\n Employee(int x, int y)\n : listener(this, x), attendee(this, y)\n {}\n\n WidgetListener listener;\n LectureAttendee attendee;\n};\n</code></pre>\n\n<p>Yes, access rights are different, but if you can get away with such an approach, without duplicating code, it's better because it's less powerful. (You can save the power for when you have no alternative.)</p>\n"
},
{
"answer_id": 4975075,
"author": "Lee Louviere",
"author_id": 491837,
"author_profile": "https://Stackoverflow.com/users/491837",
"pm_score": 0,
"selected": false,
"text": "<p>Use inheritance by delegation. Then both classes will point to a base A, but have to implement methods that redirect to A. It has the side effect of turning protected members of A into \"private\" members in B,C, and D, but now you don't need virtual, and you don't have a diamond.</p>\n"
},
{
"answer_id": 11494762,
"author": "NItish",
"author_id": 1527338,
"author_profile": "https://Stackoverflow.com/users/1527338",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class A {}; \nclass B : public A {}; \nclass C : public A {}; \nclass D : public B, public C {};\n</code></pre>\n\n<p>In this the attributes of Class A repeated twice in Class D which makes more memory usage... So to save memory we make a virtual attribute for all inherited attributes of class A which are stored in a Vtable.</p>\n"
},
{
"answer_id": 72211282,
"author": "mada",
"author_id": 16972547,
"author_profile": "https://Stackoverflow.com/users/16972547",
"pm_score": 0,
"selected": false,
"text": "<p>This is all I have in my notes about this topic. I think this would help you.</p>\n<p>The diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a member in A that B and C, and D does not override it, then which member does D inherit: that of B, or that of C?</p>\n<pre><code>struct A { int a; };\nstruct B : A { int b; };\nstruct C : A { int c; };\nstruct D : B, C {};\n\nD d;\nd.a = 10; //error: ambiguous request for 'a'\n</code></pre>\n<p>In the above example, both B & C inherit A, and they both have a single copy of A. However D inherits both B & C, therefore D has two copies of A, one from B and another from C. If we need to access the data member an of A through the object of D, we must specify the path from which the member will be accessed: whether it is from B or C because most compilers can’t differentiate between two copies of A in D.</p>\n<p>There are 4 ways to avoid this ambiguity:</p>\n<p>1- Using the scope resolution operator we can manually specify the path from which a data member will be accessed, but note that, still there are two copies (two separate subjects) of A in D, so there is still a problem.</p>\n<pre><code>d.B::a = 10; // OK\nd.C::a = 100; // OK\nd.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a\n</code></pre>\n<p>2- Using static_cast we can specify which path the compiler can take to reach to data member, but note that, still there are two copies (two separate suobjects) of A in D, so there is still a problem.</p>\n<pre><code>static_cast<B&>(static_cast<D&>(d)).a = 10;\nstatic_cast<C&>(static_cast<D&>(d)).a = 100;\nd.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a\n</code></pre>\n<p>3- Using overridden, the ambiguous class can overriden the member, but note that, still there are two copies (two separate suobjects) of A in D, so there is still a problem.</p>\n<pre><code>struct A { int a; };\nstruct B : A { int b; };\nstruct C : A { int c; };\nstruct D : B, C { int a; };\n \nD d;\nd.a = 10; // OK: D::a = 10\nd.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a\n</code></pre>\n<p>3- Using virtual inheritance, the problem is completely solved: If the inheritance from A to B and the inheritance from A to C are both marked "virtual", C++ takes special care to create only one A subobject,</p>\n<pre><code>struct A { int a; };\nstruct B : virtual A { int b; };\nstruct C : virtual A { int c; };\nstruct D : B, C {};\n \nD d;\nd.a = 10; // OK: D has only one copy of A - D::a = 10\nd.A::a = 20; // OK: D::a = 20\n</code></pre>\n<p>Note that "<em>both</em>" B and C have to be virtual, otherwise if one of them is non-virtual, D would have a virtual A subobject and another non-virtual A subobject, and ambiguity will be still taken place even if class D itself is virtual. For example, class D is ambiguous in all of the following:</p>\n<pre><code>struct A { int a; };\nstruct B : A { int b; };\nstruct C : virtual A { int c; };\nstruct D : B, C {};\n\nOr\n\nstruct A { int a; };\nstruct B : virtual A { int b; };\nstruct C : A { int c; };\nstruct D : B, C {};\n\nOr\n\nstruct A { int a; };\nstruct B : A { int b; };\nstruct C : virtual A { int c; };\nstruct D : virtual B, C {};\n\nOr\n\nstruct A { int a; };\nstruct B : virtual A { int b; };\nstruct C : A { int c; };\nstruct D : virtual B, C {};\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
]
| <http://en.wikipedia.org/wiki/Diamond_problem>
I know what it means, but what steps can I take to avoid it? | A practical example:
```
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
```
Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.
To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:
```
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
``` |
137,285 | <p>What is the best way to read an HTTP response from GetResponseStream ?</p>
<p>Currently I'm using the following approach.</p>
<pre><code>Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream)
SourceCode = SReader.ReadToEnd()
End Using
</code></pre>
<p>I'm not quite sure if this is the most efficient way to read an http response.</p>
<p>I need the output as string, I've seen an <a href="http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=583" rel="noreferrer">article</a> with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites.</p>
<p>How do you read web responses?</p>
| [
{
"answer_id": 137300,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 4,
"selected": false,
"text": "<p>I use something like this to download a file from a URL:</p>\n\n<pre><code>if (!Directory.Exists(localFolder))\n{\n Directory.CreateDirectory(localFolder); \n}\n\n\ntry\n{\n HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));\n httpRequest.Method = \"GET\";\n\n // if the URI doesn't exist, an exception will be thrown here...\n using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())\n {\n using (Stream responseStream = httpResponse.GetResponseStream())\n {\n using (FileStream localFileStream = \n new FileStream(Path.Combine(localFolder, filename), FileMode.Create))\n {\n var buffer = new byte[4096];\n long totalBytesRead = 0;\n int bytesRead;\n\n while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)\n {\n totalBytesRead += bytesRead;\n localFileStream.Write(buffer, 0, bytesRead);\n }\n }\n }\n }\n}\ncatch (Exception ex)\n{\n // You might want to handle some specific errors : Just pass on up for now...\n // Remove this catch if you don't want to handle errors here.\n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 161621,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You forgot to define \"buffer\" and \"totalBytesRead\":</p>\n\n<pre><code>using ( FileStream localFileStream = .... \n{ \n byte[] buffer = new byte[ 255 ]; \n int bytesRead; \n double totalBytesRead = 0; \n\n while ((bytesRead = .... \n</code></pre>\n"
},
{
"answer_id": 846188,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe you could look into the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx\" rel=\"noreferrer\">WebClient</a> class. Here is an example : </p>\n\n<pre><code>using System.Net;\n\nnamespace WebClientExample\n{\n class Program\n {\n static void Main(string[] args)\n {\n var remoteUri = \"http://www.contoso.com/library/homepage/images/\";\n var fileName = \"ms-banner.gif\";\n WebClient myWebClient = new WebClient();\n myWebClient.DownloadFile(remoteUri + fileName, fileName);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2945166,
"author": "Robert MacLean",
"author_id": 53236,
"author_profile": "https://Stackoverflow.com/users/53236",
"pm_score": 4,
"selected": false,
"text": "<p>My simple way of doing it to a string. Note the <code>true</code> second parameter on the <code>StreamReader</code> constructor. This tells it to detect the encoding from the byte order marks and may help with the encoding issue you are getting as well.</p>\n\n<pre><code>string target = string.Empty;\nHttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(\"http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=583\");\n\nHttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();\ntry\n{\n StreamReader streamReader = new StreamReader(response.GetResponseStream(),true); \n try\n {\n target = streamReader.ReadToEnd();\n }\n finally\n {\n streamReader.Close();\n }\n}\nfinally\n{\n response.Close();\n}\n</code></pre>\n"
},
{
"answer_id": 10528832,
"author": "Stew-au",
"author_id": 182260,
"author_profile": "https://Stackoverflow.com/users/182260",
"pm_score": 3,
"selected": false,
"text": "<p>In powershell, I have this function:</p>\n\n<pre><code>function GetWebPage\n{param ($Url, $Outfile)\n $request = [System.Net.HttpWebRequest]::Create($SearchBoxBuilderURL)\n $request.AuthenticationLevel = \"None\"\n $request.TimeOut = 600000 #10 mins \n $response = $request.GetResponse() #Appending \"|Out-Host\" anulls the variable\n Write-Host \"Response Status Code: \"$response.StatusCode\n Write-Host \"Response Status Description: \"$response.StatusDescription\n $requestStream = $response.GetResponseStream()\n $readStream = new-object System.IO.StreamReader $requestStream\n new-variable db | Out-Host\n $db = $readStream.ReadToEnd()\n $readStream.Close()\n $response.Close()\n #Create a new file and write the web output to a file\n $sw = new-object system.IO.StreamWriter($Outfile)\n $sw.writeline($db) | Out-Host\n $sw.close() | Out-Host\n}\n</code></pre>\n\n<p>And I call it like this:</p>\n\n<pre><code>$SearchBoxBuilderURL = $SiteUrl + \"nin_searchbox/DailySearchBoxBuilder.asp\"\n$SearchBoxBuilderOutput=\"D:\\ecom\\tmp\\ss2.txt\"\nGetWebPage $SearchBoxBuilderURL $SearchBoxBuilderOutput\n</code></pre>\n"
},
{
"answer_id": 43981770,
"author": "João Paulo Melo",
"author_id": 2791237,
"author_profile": "https://Stackoverflow.com/users/2791237",
"pm_score": 1,
"selected": false,
"text": "<p>I faced a similar situation:</p>\n\n<p>I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.</p>\n\n<p>However, when reading the response using <code>GetResponseStream()</code>, got the error:</p>\n\n<blockquote>\n <p>Stream not readable</p>\n</blockquote>\n\n<p>So, this code worked for me:</p>\n\n<pre><code>try\n{\n response = basicHTTPBindingClient.CallOperation(request);\n}\ncatch (ProtocolException exception)\n{\n var webException = exception.InnerException as WebException;\n\n var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;\n using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))\n using (var reader = new StreamReader(brandNewStream))\n rawResponse = reader.ReadToEnd();\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What is the best way to read an HTTP response from GetResponseStream ?
Currently I'm using the following approach.
```
Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream)
SourceCode = SReader.ReadToEnd()
End Using
```
I'm not quite sure if this is the most efficient way to read an http response.
I need the output as string, I've seen an [article](http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=583) with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites.
How do you read web responses? | I use something like this to download a file from a URL:
```
if (!Directory.Exists(localFolder))
{
Directory.CreateDirectory(localFolder);
}
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));
httpRequest.Method = "GET";
// if the URI doesn't exist, an exception will be thrown here...
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream responseStream = httpResponse.GetResponseStream())
{
using (FileStream localFileStream =
new FileStream(Path.Combine(localFolder, filename), FileMode.Create))
{
var buffer = new byte[4096];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bytesRead;
localFileStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
catch (Exception ex)
{
// You might want to handle some specific errors : Just pass on up for now...
// Remove this catch if you don't want to handle errors here.
throw;
}
``` |
137,313 | <p>I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns.</p>
<p>I wrote a small Perl script to do this:</p>
<pre><code>#!/usr/bin/perl
die("need max length\n") unless $#ARGV == 0;
while (<STDIN>)
{
$_ = substr($_, 0, $ARGV[0]);
chomp($_);
print "$_\n";
}
</code></pre>
<p>But I have a feeling that this functionality is probably built into some other tools (sed?) That I just don't know enough about to use for this task.</p>
<p>So my question sort of a reverse question: how do I truncate a line of stdin Without writing a program to do it?</p>
| [
{
"answer_id": 137323,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": 5,
"selected": true,
"text": "<p>Pipe output to:</p>\n\n<pre><code>cut -b 1-LIMIT\n</code></pre>\n\n<p>Where LIMIT is the desired line width.</p>\n"
},
{
"answer_id": 137329,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": 4,
"selected": false,
"text": "<p>Another tactic I use for viewing log files with very long lines is to pipe the file to \"less -S\". The -S option for less will print lines without wrapping, and you can view the hidden part of long lines by pressing the right-arrow key.</p>\n"
},
{
"answer_id": 137642,
"author": "Yanick",
"author_id": 10356,
"author_profile": "https://Stackoverflow.com/users/10356",
"pm_score": 2,
"selected": false,
"text": "<p>Not exactly answering the question, but if you want to stick with Perl and use a one-liner, a possibility is:</p>\n\n<pre><code>$ perl -pe's/(?<=.{25}).*//' filename\n</code></pre>\n\n<p>where 25 is the desired line length.</p>\n"
},
{
"answer_id": 138192,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>The usual way to do this would be</p>\n\n<pre><code>perl -wlne'print substr($_,0,80)'\n</code></pre>\n\n<p>Golfed (for 5.10):</p>\n\n<pre><code>perl -nE'say/(.{0,80})/'\n</code></pre>\n\n<p>(Don't think of it as programming, think of it as using a command line tool with a huge number of options.) (Yes, the <a href=\"http://www.serve.com/bonzai/monty/classics/TheKnightsWhoSayNi\" rel=\"nofollow noreferrer\">python</a> reference is intentional.)</p>\n"
},
{
"answer_id": 141112,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 0,
"selected": false,
"text": "<p>A Korn shell solution (truncating to 70 chars - easy to parameterize though):</p>\n\n<pre><code>typeset -L70 line\nwhile read line\ndo\n print $line\ndone\n</code></pre>\n"
},
{
"answer_id": 142098,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a tied variable that clips its contents to a fixed length:</p>\n\n<pre><code>#! /usr/bin/perl -w\n\nuse strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 142217,
"author": "Sam Martin",
"author_id": 19088,
"author_profile": "https://Stackoverflow.com/users/19088",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't exactly what you're asking for, but <a href=\"http://www.gnu.org/software/screen/\" rel=\"nofollow noreferrer\">GNU Screen</a> (included with OS X, if I recall correctly, and common on other *nix systems) lets you turn line wrapping on/off (C-a r and C-a C-r). That way, you can simply resize your terminal instead of piping stuff through a script.</p>\n\n<p>Screen basically gives you \"virtual\" terminals within one toplevel terminal application.</p>\n"
},
{
"answer_id": 848356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>use strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 12899735,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 0,
"selected": false,
"text": "<p>Unless I'm missing the point, the UNIX \"fold\" command was designed to do exactly that:</p>\n\n<pre><code>$ cat file\nthe quick brown fox jumped over the lazy dog's back\n\n$ fold -w20 file\nthe quick brown fox\njumped over the lazy\n dog's back\n\n$ fold -w10 file\nthe quick\nbrown fox\njumped ove\nr the lazy\n dog's bac\nk\n\n$ fold -s -w10 file\nthe quick\nbrown fox\njumped\nover the\nlazy\ndog's back\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
| I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns.
I wrote a small Perl script to do this:
```
#!/usr/bin/perl
die("need max length\n") unless $#ARGV == 0;
while (<STDIN>)
{
$_ = substr($_, 0, $ARGV[0]);
chomp($_);
print "$_\n";
}
```
But I have a feeling that this functionality is probably built into some other tools (sed?) That I just don't know enough about to use for this task.
So my question sort of a reverse question: how do I truncate a line of stdin Without writing a program to do it? | Pipe output to:
```
cut -b 1-LIMIT
```
Where LIMIT is the desired line width. |
137,314 | <p>I've got a CAkePHP 1.2 site. I've got three related Models/tables:
A Comment has exactly one Touch, a Touch has exactly one Touchtype.</p>
<p>In each model, I have a belongs to, so I have
Comments belongs to Touch, Touch belongs to Touchtype.</p>
<p>I'm trying to get a list of comments that includes information about the touch stored in the touchtype table. </p>
<pre><code>$this->Comment->find(...)
</code></pre>
<p>I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help.</p>
| [
{
"answer_id": 137323,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": 5,
"selected": true,
"text": "<p>Pipe output to:</p>\n\n<pre><code>cut -b 1-LIMIT\n</code></pre>\n\n<p>Where LIMIT is the desired line width.</p>\n"
},
{
"answer_id": 137329,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": 4,
"selected": false,
"text": "<p>Another tactic I use for viewing log files with very long lines is to pipe the file to \"less -S\". The -S option for less will print lines without wrapping, and you can view the hidden part of long lines by pressing the right-arrow key.</p>\n"
},
{
"answer_id": 137642,
"author": "Yanick",
"author_id": 10356,
"author_profile": "https://Stackoverflow.com/users/10356",
"pm_score": 2,
"selected": false,
"text": "<p>Not exactly answering the question, but if you want to stick with Perl and use a one-liner, a possibility is:</p>\n\n<pre><code>$ perl -pe's/(?<=.{25}).*//' filename\n</code></pre>\n\n<p>where 25 is the desired line length.</p>\n"
},
{
"answer_id": 138192,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>The usual way to do this would be</p>\n\n<pre><code>perl -wlne'print substr($_,0,80)'\n</code></pre>\n\n<p>Golfed (for 5.10):</p>\n\n<pre><code>perl -nE'say/(.{0,80})/'\n</code></pre>\n\n<p>(Don't think of it as programming, think of it as using a command line tool with a huge number of options.) (Yes, the <a href=\"http://www.serve.com/bonzai/monty/classics/TheKnightsWhoSayNi\" rel=\"nofollow noreferrer\">python</a> reference is intentional.)</p>\n"
},
{
"answer_id": 141112,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 0,
"selected": false,
"text": "<p>A Korn shell solution (truncating to 70 chars - easy to parameterize though):</p>\n\n<pre><code>typeset -L70 line\nwhile read line\ndo\n print $line\ndone\n</code></pre>\n"
},
{
"answer_id": 142098,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a tied variable that clips its contents to a fixed length:</p>\n\n<pre><code>#! /usr/bin/perl -w\n\nuse strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 142217,
"author": "Sam Martin",
"author_id": 19088,
"author_profile": "https://Stackoverflow.com/users/19088",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't exactly what you're asking for, but <a href=\"http://www.gnu.org/software/screen/\" rel=\"nofollow noreferrer\">GNU Screen</a> (included with OS X, if I recall correctly, and common on other *nix systems) lets you turn line wrapping on/off (C-a r and C-a C-r). That way, you can simply resize your terminal instead of piping stuff through a script.</p>\n\n<p>Screen basically gives you \"virtual\" terminals within one toplevel terminal application.</p>\n"
},
{
"answer_id": 848356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>use strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 12899735,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 0,
"selected": false,
"text": "<p>Unless I'm missing the point, the UNIX \"fold\" command was designed to do exactly that:</p>\n\n<pre><code>$ cat file\nthe quick brown fox jumped over the lazy dog's back\n\n$ fold -w20 file\nthe quick brown fox\njumped over the lazy\n dog's back\n\n$ fold -w10 file\nthe quick\nbrown fox\njumped ove\nr the lazy\n dog's bac\nk\n\n$ fold -s -w10 file\nthe quick\nbrown fox\njumped\nover the\nlazy\ndog's back\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
]
| I've got a CAkePHP 1.2 site. I've got three related Models/tables:
A Comment has exactly one Touch, a Touch has exactly one Touchtype.
In each model, I have a belongs to, so I have
Comments belongs to Touch, Touch belongs to Touchtype.
I'm trying to get a list of comments that includes information about the touch stored in the touchtype table.
```
$this->Comment->find(...)
```
I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help. | Pipe output to:
```
cut -b 1-LIMIT
```
Where LIMIT is the desired line width. |
137,326 | <p>How do you embed a SWF file in an HTML page?</p>
| [
{
"answer_id": 137332,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 7,
"selected": false,
"text": "<pre><code><object width=\"100\" height=\"100\">\n <param name=\"movie\" value=\"file.swf\">\n <embed src=\"file.swf\" width=\"100\" height=\"100\">\n </embed>\n</object>\n</code></pre>\n"
},
{
"answer_id": 137349,
"author": "Ronnie Liew",
"author_id": 1987,
"author_profile": "https://Stackoverflow.com/users/1987",
"pm_score": 8,
"selected": true,
"text": "<p>The best approach to embed a SWF into an HTML page is to use <a href=\"https://github.com/swfobject/swfobject/\" rel=\"noreferrer\">SWFObject</a>.</p>\n\n<p>It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content.</p>\n\n<p>It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page.</p>\n\n<p>An example from the documentation:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n <head>\n <title>SWFObject dynamic embed - step 3</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n <script type=\"text/javascript\" src=\"swfobject.js\"></script>\n\n <script type=\"text/javascript\">\n swfobject.embedSWF(\"myContent.swf\", \"myContent\", \"300\", \"120\", \"9.0.0\");\n </script>\n\n </head>\n <body>\n <div id=\"myContent\">\n <p>Alternative content</p>\n </div>\n </body>\n</html>\n</code></pre>\n\n<p>A good tool to use along with this is the SWFObject HTML and JavaScript <a href=\"https://github.com/swfobject/swfobject/wiki/SWFObject-Generator\" rel=\"noreferrer\">generator</a>. It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters.</p>\n\n<p>It Is highly recommended and very simple to use.</p>\n"
},
{
"answer_id": 137362,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://wiltgen.net/objecty/\" rel=\"nofollow noreferrer\">http://wiltgen.net/objecty/</a>, it helps to embed media content and avoid the IE \"click to activate\" problem.</p>\n"
},
{
"answer_id": 137923,
"author": "phatduckk",
"author_id": 3896,
"author_profile": "https://Stackoverflow.com/users/3896",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned SWF Object is great. <a href=\"http://osflash.org/doku.php?id=ufo\" rel=\"nofollow noreferrer\">UFO</a> is worth a look as well</p>\n"
},
{
"answer_id": 142304,
"author": "Brian Kim",
"author_id": 5704,
"author_profile": "https://Stackoverflow.com/users/5704",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using one of those js libraries to insert Flash, I suggest adding plain object embed tag inside of <code><noscript/></code>.</p>\n"
},
{
"answer_id": 12847276,
"author": "Spooky",
"author_id": 1739270,
"author_profile": "https://Stackoverflow.com/users/1739270",
"pm_score": 3,
"selected": false,
"text": "<pre><code><object type=\"application/x-shockwave-flash\" data=\"http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01\" \nstyle=\"width:640px;height:480px;margin:10px 36px;\">\n\n<param name=\"movie\" value=\"http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01\" />\n<param name=\"allowfullscreen\" value=\"true\" />\n<param name=\"allowscriptaccess\" value=\"always\" />\n<param name=\"wmode\" value=\"opaque\" />\n<param name=\"quality\" value=\"high\" />\n<param name=\"menu\" value=\"false\" />\n\n</object>\n</code></pre>\n"
},
{
"answer_id": 12847491,
"author": "Spooky",
"author_id": 1739270,
"author_profile": "https://Stackoverflow.com/users/1739270",
"pm_score": 4,
"selected": false,
"text": "<p>This is suitable for application from root environment. </p>\n\n<pre><code><object type=\"application/x-shockwave-flash\" data=\"/dir/application.swf\" \nid=\"applicationID\" style=\"margin:0 10px;width:auto;height:auto;\">\n\n<param name=\"movie\" value=\"/dir/application.swf\" />\n<param name=\"wmode\" value=\"transparent\" /> <!-- Or opaque, etc. -->\n\n<!-- ↓ Required paramter or not, depends on application -->\n<param name=\"FlashVars\" value=\"\" />\n\n<param name=\"quality\" value=\"high\" />\n<param name=\"menu\" value=\"false\" />\n\n</object>\n</code></pre>\n\n<p>Additional parameters should be/can be added which depends on .swf it self. <strong>No embed</strong>, just <strong>object</strong> and parameters within, so, it remains valid, working and usable everywhere, it doesn't matter which !DOCTYPE is all about. :)</p>\n"
},
{
"answer_id": 20752959,
"author": "Syed",
"author_id": 2228691,
"author_profile": "https://Stackoverflow.com/users/2228691",
"pm_score": 1,
"selected": false,
"text": "<p>What is the 'best' way? Words like 'most efficient,' 'fastest rendering,' etc. are more specific. Anyway, I am offering an alternative answer that helps me most of the time (whether or not is 'best' is irrelevant).</p>\n\n<p>Alternate answer: Use an iframe.</p>\n\n<p>That is, host the SWF file on the server. If you put the SWF file in the root or public_html folder then the SWF file will be located at <code>www.YourDomain.com/YourFlashFile.swf</code>.</p>\n\n<p>Then, on your index.html or wherever, link the above location to your iframe and it will be displayed around your content wherever you put your iframe. If you can put an iframe there, you can put an SWF file there. Make the iframe dimensions the same as your SWF file. In the example below, the SWF file is 500 by 500.</p>\n\n<p>Pseudo code:</p>\n\n<pre><code><iframe src=\"//www.YourDomain.com/YourFlashFile.swf\" width=\"500\" height=\"500\"></iframe>\n</code></pre>\n\n<p>The line of HTML code above will embed your SWF file. No other mess needed.\nPros: W3C compliant, page design friendly, no speed issue, minimalist approach. <br/>\nCons: White space around your SWF file when launched in a browser.</p>\n\n<p>That is an alternate answer. Whether it is the 'best' answer depends on your project.</p>\n"
},
{
"answer_id": 21070366,
"author": "Allan",
"author_id": 2289327,
"author_profile": "https://Stackoverflow.com/users/2289327",
"pm_score": -1,
"selected": false,
"text": "<p>You can use JavaScript if you're familiar with, like that:</p>\n\n<pre><code>swfobject.embedSWF(\"filename.swf\", \"Title\", \"width\", \"height\", \"9.0.0\");\n</code></pre>\n\n<p>--the 9.0.0 is the flash version.</p>\n\n<p>Or you can use the <code><object></code> tag of HTML5.</p>\n"
},
{
"answer_id": 25805669,
"author": "gtb",
"author_id": 3009025,
"author_profile": "https://Stackoverflow.com/users/3009025",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code> <a target=\"_blank\" href=\"{{ entity.link }}\">\n <object type=\"application/x-shockwave-flash\" data=\"{{ entity.file.path }}?clickTAG={{ entity.link }}\" width=\"120\" height=\"600\" style=\"visibility: visible;\">\n <param name=\"quality\" value=\"high\">\n <param name=\"play\" value=\"true\">\n <param name=\"LOOP\" value=\"false\">\n <param name=\"wmode\" value=\"transparent\">\n <param name=\"allowScriptAccess\" value=\"true\">\n </object>\n </a>\n</code></pre>\n"
},
{
"answer_id": 30406612,
"author": "Jan Desta",
"author_id": 2942035,
"author_profile": "https://Stackoverflow.com/users/2942035",
"pm_score": 4,
"selected": false,
"text": "<p>How about simple HTML5 tag embed?</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n<body>\n\n<embed src=\"anim.swf\">\n\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 31627369,
"author": "Stefan Đorđević",
"author_id": 4722777,
"author_profile": "https://Stackoverflow.com/users/4722777",
"pm_score": 2,
"selected": false,
"text": "<p>This one will work, I am sure!</p>\n\n<pre><code><embed src=\"application.swf\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getfashplayer\" type=\"application/x-shockwave-flash\" width=\"690\" height=\"430\">\n</code></pre>\n"
},
{
"answer_id": 48910563,
"author": "Isuru Dilshan",
"author_id": 7877099,
"author_profile": "https://Stackoverflow.com/users/7877099",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old question. But this answer will be good for the present.</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <title>histo2</title>\n <style type=\"text/css\" media=\"screen\">\n html, body { height:100%; background-color: #ffff99;}\n body { margin:0; padding:0; overflow:hidden; }\n #flashContent { width:100%; height:100%; }\n </style>\n </head>\n <body>\n <div id=\"flashContent\">\n <object type=\"application/x-shockwave-flash\" data=\"histo2.swf\" width=\"822\" height=\"550\" id=\"histo2\" style=\"float: none; vertical-align:middle\">\n <param name=\"movie\" value=\"histo2.swf\" />\n <param name=\"quality\" value=\"high\" />\n <param name=\"bgcolor\" value=\"#ffff99\" />\n <param name=\"play\" value=\"true\" />\n <param name=\"loop\" value=\"true\" />\n <param name=\"wmode\" value=\"window\" />\n <param name=\"scale\" value=\"showall\" />\n <param name=\"menu\" value=\"true\" />\n <param name=\"devicefont\" value=\"false\" />\n <param name=\"salign\" value=\"\" />\n <param name=\"allowScriptAccess\" value=\"sameDomain\" />\n <a href=\"http://www.adobe.com/go/getflash\">\n <img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" />\n </a>\n </object>\n </div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 54138706,
"author": "xxnull",
"author_id": 6273068,
"author_profile": "https://Stackoverflow.com/users/6273068",
"pm_score": 1,
"selected": false,
"text": "<p>Thi works on IE, Edge, Firefox, Safari and Chrome.</p>\n<pre><code><object type="application/x-shockwave-flash" data="movie.swf" width="720" height="480">\n <param name="movie" value="movie.swf" />\n <param name="quality" value="high" />\n <param name="bgcolor" value="#000000" />\n <param name="play" value="true" />\n <param name="loop" value="true" />\n <param name="wmode" value="window" />\n <param name="scale" value="showall" />\n <param name="menu" value="true" />\n <param name="devicefont" value="false" />\n <param name="salign" value="" />\n <param name="allowScriptAccess" value="sameDomain" />\n <a href="http://www.adobe.com/go/getflash">\n <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />\n </a>\n</object>\n</code></pre>\n"
},
{
"answer_id": 61020637,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <code><embed></code> element:</p>\n\n<pre><code><embed src=\"file.swf\" width=\"854\" height=\"480\"></embed>\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/137326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18309/"
]
| How do you embed a SWF file in an HTML page? | The best approach to embed a SWF into an HTML page is to use [SWFObject](https://github.com/swfobject/swfobject/).
It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content.
It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page.
An example from the documentation:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 3</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0");
</script>
</head>
<body>
<div id="myContent">
<p>Alternative content</p>
</div>
</body>
</html>
```
A good tool to use along with this is the SWFObject HTML and JavaScript [generator](https://github.com/swfobject/swfobject/wiki/SWFObject-Generator). It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters.
It Is highly recommended and very simple to use. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.