qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
34,128 | <p>We are trying to create a web-service that we plan to pass a variable amount of variables to it.</p>
<p>Can this be done?</p>
<p>Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.</p>
<p>Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<WebMethod xmlns="http://tempuri.org/">
<domains>
<function1>
<title>Some Title</title>
<type>25</type>
</function1>
<function2 />
<function3>
<param>13</param>
</function3>
</domains>
</WebMethod>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>Will this work or should we do a different way?</p>
| [
{
"answer_id": 34132,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply pass a variable-length array as a parameter.</p>\n"
},
{
"answer_id": 34138,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>If you dont like the idea of an Array (this is not slating Konrad's answer - you may have differing param types) you can pass complex objects (i.e. objects that you made yourself).. The downside is that you cannot then test using the ASMX page, but would need to do it all in code (which isn't really a bad thing, especially if you are used to it).</p>\n"
},
{
"answer_id": 34150,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>I would pass in an xml document instead of doing concreate functions for this. </p>\n\n<p>The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally. </p>\n\n<p>XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice. </p>\n\n<p>Take a look at these</p>\n\n<p><a href=\"http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html\" rel=\"nofollow noreferrer\">IBM Developer</a>\n<a href=\"http://forums.asp.net/p/1253455/2323689.aspx#2323689\" rel=\"nofollow noreferrer\">ASP.NET Forum</a></p>\n\n<p>I would also recommend using this for testing webservices and its free\n<a href=\"http://www.codeplex.com/wsstudioexpress\" rel=\"nofollow noreferrer\">WSStudio</a></p>\n"
},
{
"answer_id": 34229,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with littlegeek. Do not make your web service is hard method. Make it a receiving end point to receive <em>messages</em>. Particularly, a Command Message.</p>\n\n<p><a href=\"http://www.eaipatterns.com/CommandMessage.html\" rel=\"nofollow noreferrer\">http://www.eaipatterns.com/CommandMessage.html</a></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3582/"
] | We are trying to create a web-service that we plan to pass a variable amount of variables to it.
Can this be done?
Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.
Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.
```
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<WebMethod xmlns="http://tempuri.org/">
<domains>
<function1>
<title>Some Title</title>
<type>25</type>
</function1>
<function2 />
<function3>
<param>13</param>
</function3>
</domains>
</WebMethod>
</soap:Body>
</soap:Envelope>
```
Will this work or should we do a different way? | I would pass in an xml document instead of doing concreate functions for this.
The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally.
XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice.
Take a look at these
[IBM Developer](http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html)
[ASP.NET Forum](http://forums.asp.net/p/1253455/2323689.aspx#2323689)
I would also recommend using this for testing webservices and its free
[WSStudio](http://www.codeplex.com/wsstudioexpress) |
34,144 | <p>I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.</p>
<p>To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.</p>
| [
{
"answer_id": 34156,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 6,
"selected": false,
"text": "<p>Using the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/\" rel=\"noreferrer\">Maven Dependency Plugin</a>:</p>\n\n<pre><code>mvn dependency:tree\n</code></pre>\n"
},
{
"answer_id": 34162,
"author": "Valters Vingolds",
"author_id": 885,
"author_profile": "https://Stackoverflow.com/users/885",
"pm_score": 2,
"selected": false,
"text": "<p>If you run maven with \"-x\" switch, it will print out plenty of diagnostics, I guess the relevant dependency path can be picked up from there.</p>\n"
},
{
"answer_id": 34167,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 8,
"selected": true,
"text": "<p>To add to @David Crow, here's <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html\" rel=\"noreferrer\">a dependency:tree example</a> from the Maven site:</p>\n\n<pre><code>mvn dependency:tree -Dincludes=velocity:velocity\n</code></pre>\n\n<p>might output</p>\n\n<pre><code>[INFO] [dependency:tree]\n[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT\n[INFO] \\- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile\n[INFO] \\- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile\n[INFO] \\- velocity:velocity:jar:1.4:compile\n</code></pre>\n"
},
{
"answer_id": 219325,
"author": "Filip Korling",
"author_id": 25098,
"author_profile": "https://Stackoverflow.com/users/25098",
"pm_score": 1,
"selected": false,
"text": "<p>The dependency information is also included in the Project Information/Dependencies report if you have maven generate a site for the project, using mvn site.</p>\n"
},
{
"answer_id": 274901,
"author": "Brian Fox",
"author_id": 77489,
"author_profile": "https://Stackoverflow.com/users/77489",
"pm_score": 3,
"selected": false,
"text": "<p>If you use eclipse and the <a href=\"https://www.eclipse.org/m2e/\" rel=\"nofollow noreferrer\">m2eclipse plugin</a> then there is a graphical version of dependency tree where you can filter by scope etc.</p>\n"
},
{
"answer_id": 4233244,
"author": "Bang",
"author_id": 514515,
"author_profile": "https://Stackoverflow.com/users/514515",
"pm_score": 2,
"selected": false,
"text": "<p>You can have many reports by </p>\n\n<blockquote>\n <p>mvn site</p>\n</blockquote>\n\n<p>One of them is the dependency report.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] | I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.
To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that. | To add to @David Crow, here's [a dependency:tree example](http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html) from the Maven site:
```
mvn dependency:tree -Dincludes=velocity:velocity
```
might output
```
[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- velocity:velocity:jar:1.4:compile
``` |
34,155 | <p>I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the <a href="http://en.wikipedia.org/wiki/Continuation" rel="noreferrer">Wikipedia article</a>:</p>
<pre><code>(define the-continuation #f)
(define (test)
(let ((i 0))
; call/cc calls its first function argument, passing
; a continuation variable representing this point in
; the program as the argument to that function.
;
; In this case, the function argument assigns that
; continuation to the variable the-continuation.
;
(call/cc (lambda (k) (set! the-continuation k)))
;
; The next time the-continuation is called, we start here.
(set! i (+ i 1))
i))
</code></pre>
<p>I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate. </p>
<p>So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.</p>
<p>Cheers!</p>
| [
{
"answer_id": 34173,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 2,
"selected": false,
"text": "<p>Continuations can be used in \"real-life\" examples whenever the program flow is not linear, or not even pre-determined. A familiar situation is <a href=\"http://www.ibm.com/developerworks/library/j-contin.html\" rel=\"nofollow noreferrer\">web applications</a>.</p>\n"
},
{
"answer_id": 34175,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "<p>Continuations are used by some web servers and web frameworks to store session information. A continuation object is created for each session and then used by each request within the session.</p>\n\n<p><a href=\"http://www.ibm.com/developerworks/library/os-lightweight9/index.html\" rel=\"noreferrer\">There's an article about this approach here.</a></p>\n"
},
{
"answer_id": 34273,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 3,
"selected": false,
"text": "<p>Seaside: </p>\n\n<ul>\n<li><a href=\"http://www.seaside.st/\" rel=\"nofollow noreferrer\">homepage</a> </li>\n<li><a href=\"http://en.wikipedia.org/wiki/Seaside_%28software%29\" rel=\"nofollow noreferrer\">wikipedia page</a></li>\n</ul>\n"
},
{
"answer_id": 34327,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 3,
"selected": false,
"text": "<p>@Pat</p>\n\n<blockquote>\n <p>Seaside</p>\n</blockquote>\n\n<p>Yes, <a href=\"http://www.seaside.st\" rel=\"nofollow noreferrer\">Seaside</a> is a great example. I browsed its code quickly and found this message illustrating passing control between components in a seemingly statefull way accross the Web.</p>\n\n<pre><code>WAComponent >> call: aComponent\n \"Pass control from the receiver to aComponent. The receiver will be\n temporarily replaced with aComponent. Code can return from here later\n on by sending #answer: to aComponent.\"\n\n ^ AnswerContinuation currentDo: [ :cc |\n self show: aComponent onAnswer: cc.\n WARenderNotification raiseSignal ]\n</code></pre>\n\n<p>So nice!</p>\n"
},
{
"answer_id": 34387,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 5,
"selected": true,
"text": "<p>In Algo & Data II we used these all the times to \"exit\" or \"return\" from a (long) function</p>\n\n<p>for example the BFS algorthm to traverse trees with was implemented like this:</p>\n\n<pre><code>(define (BFS graph root-discovered node-discovered edge-discovered edge-bumped . nodes)\n (define visited (make-vector (graph.order graph) #f))\n (define q (queue.new))\n (define exit ())\n (define (BFS-tree node)\n (if (node-discovered node)\n (exit node))\n (graph.map-edges\n graph\n node\n (lambda (node2)\n (cond ((not (vector-ref visited node2))\n (when (edge-discovered node node2)\n (vector-set! visited node2 #t)\n (queue.enqueue! q node2)))\n (else\n (edge-bumped node node2)))))\n (if (not (queue.empty? q))\n (BFS-tree (queue.serve! q))))\n\n (call-with-current-continuation\n (lambda (my-future)\n (set! exit my-future)\n (cond ((null? nodes)\n (graph.map-nodes\n graph\n (lambda (node)\n (when (not (vector-ref visited node))\n (vector-set! visited node #t)\n (root-discovered node)\n (BFS-tree node)))))\n (else\n (let loop-nodes\n ((node-list (car nodes)))\n (vector-set! visited (car node-list) #t)\n (root-discovered (car node-list))\n (BFS-tree (car node-list))\n (if (not (null? (cdr node-list)))\n (loop-nodes (cdr node-list)))))))))\n</code></pre>\n\n<p>As you can see the algorithm will exit when the node-discovered function returns true:</p>\n\n<pre><code> (if (node-discovered node)\n (exit node))\n</code></pre>\n\n<p>the function will also give a \"return value\": 'node'</p>\n\n<p>why the function exits, is because of this statement:</p>\n\n<pre><code>(call-with-current-continuation\n (lambda (my-future)\n (set! exit my-future)\n</code></pre>\n\n<p>when we use exit, it will go back to the state before the execution, emptying the call-stack and return the value you gave it.</p>\n\n<p>So basically, call-cc is used (here) to jump out of a recursive function, instead of waiting for the entire recursion to end by itself (which can be quite expensive when doing lots of computational work)</p>\n\n<p>another smaller example doing the same with call-cc:</p>\n\n<pre><code>(define (connected? g node1 node2)\n (define visited (make-vector (graph.order g) #f))\n (define return ())\n (define (connected-rec x y)\n (if (eq? x y)\n (return #t))\n (vector-set! visited x #t)\n (graph.map-edges g\n x\n (lambda (t)\n (if (not (vector-ref visited t))\n (connected-rec t y)))))\n (call-with-current-continuation\n (lambda (future)\n (set! return future)\n (connected-rec node1 node2)\n (return #f))))\n</code></pre>\n"
},
{
"answer_id": 53674,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 3,
"selected": false,
"text": "<p>I came accross an implementation of the <code>amb</code> operator in <a href=\"http://www.randomhacks.net/articles/2005/10/11/amb-operator\" rel=\"noreferrer\">this post</a> from <a href=\"http://www.randomhacks.net\" rel=\"noreferrer\">http://www.randomhacks.net</a>, using continuations.</p>\n\n<p>Here's what the <code>amb</code> opeerator does:</p>\n\n<pre><code># amb will (appear to) choose values\n# for x and y that prevent future\n# trouble.\nx = amb 1, 2, 3\ny = amb 4, 5, 6\n\n# Ooops! If x*y isn't 8, amb would\n# get angry. You wouldn't like\n# amb when it's angry.\namb if x*y != 8\n\n# Sure enough, x is 2 and y is 4.\nputs x, y \n</code></pre>\n\n<p>And here's the post's implementation:</p>\n\n<pre><code># A list of places we can \"rewind\" to\n# if we encounter amb with no\n# arguments.\n$backtrack_points = []\n\n# Rewind to our most recent backtrack\n# point.\ndef backtrack\n if $backtrack_points.empty?\n raise \"Can't backtrack\"\n else\n $backtrack_points.pop.call\n end\nend\n\n# Recursive implementation of the\n# amb operator.\ndef amb *choices\n # Fail if we have no arguments.\n backtrack if choices.empty?\n callcc {|cc|\n # cc contains the \"current\n # continuation\". When called,\n # it will make the program\n # rewind to the end of this block.\n $backtrack_points.push cc\n\n # Return our first argument.\n return choices[0]\n }\n\n # We only get here if we backtrack\n # using the stored value of cc,\n # above. We call amb recursively\n # with the arguments we didn't use.\n amb *choices[1...choices.length]\nend\n\n# Backtracking beyond a call to cut\n# is strictly forbidden.\ndef cut\n $backtrack_points = []\nend\n</code></pre>\n\n<p>I like <code>amb</code>!</p>\n"
},
{
"answer_id": 69874,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 3,
"selected": false,
"text": "<p>I built my own unit testing software. Before executing the test, I store the continuation before executing the test, and then on failure, I (optionally) tell the scheme interpreter to drop into debug mode, and re-invoke the continuation. This way I can step through the problematic code really easily.</p>\n\n<p>If your continuations are serializable, you can also store then on application failure, and then re-invoke them to get detailed information about variable values, stack traces, etc.</p>\n"
},
{
"answer_id": 69906,
"author": "Greg",
"author_id": 4123,
"author_profile": "https://Stackoverflow.com/users/4123",
"pm_score": 2,
"selected": false,
"text": "<p>Continuations are a good alternative to thread-per-request in server programming (including web application frontends.</p>\n\n<p>In this model, instead of launching a new (heavy) thread every time a request comes in, you just start some work in a function. Then, when you are ready to block on I/O (i.e. reading from the database), you pass a continuation into the networking response handler. When the response comes back, you execute the continuation. With this scheme, you can process lots of requests with just a few threads.</p>\n\n<p>This makes the control flow more complex than using blocking threads, but under heavy load, it is more efficient (at least on today's hardware).</p>\n"
},
{
"answer_id": 499490,
"author": "Tom Dunham",
"author_id": 6402,
"author_profile": "https://Stackoverflow.com/users/6402",
"pm_score": 1,
"selected": false,
"text": "<p>How about the <a href=\"http://code.google.com/apis/maps/documentation/mapplets/guide.html\" rel=\"nofollow noreferrer\">Google Mapplets API</a>? There are a bunch of functions (all ending in <code>Async</code>) to which you pass a callback. The API function does an async request, gets it's result, then passes that result to your callback (as the \"next thing to do\"). Sounds a lot like <a href=\"http://en.wikipedia.org/wiki/Continuation-passing_style\" rel=\"nofollow noreferrer\">continuation passing style</a> to me.</p>\n\n<p>This <a href=\"http://code.google.com/apis/maps/documentation/mapplets/guide.html#Asynchronous\" rel=\"nofollow noreferrer\">example</a> shows a very simple case.</p>\n\n<pre><code>map.getZoomAsync(function(zoom) {\n alert(\"Current zoom level is \" + zoom); // this is the continuation\n}); \nalert(\"This might happen before or after you see the zoom level message\");\n</code></pre>\n\n<p>As this is Javascript there's no <a href=\"http://en.wikipedia.org/wiki/Tail_call_optimization\" rel=\"nofollow noreferrer\">tail call optimization</a>, so the stack will grow with every call into a continuation, and you'll eventually return the thread of control to the browser. All the same, I think it's a nice abstraction. </p>\n"
},
{
"answer_id": 615158,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>Continuations can be used to implement exceptions, a debugger.</p>\n"
},
{
"answer_id": 2769791,
"author": "Justin Smith",
"author_id": 252401,
"author_profile": "https://Stackoverflow.com/users/252401",
"pm_score": 1,
"selected": false,
"text": "<p>If you have to invoke an asynchronous action, and suspend execution until you get the result, you would normally either poll for the result or put the rest of your code in a callback to be executed by the asynchronous action upon completion. With continuations you don't need to do the inefficient option of polling, and you don't need to wrap up all your code to be run after the asynch event in a callback - you just pass the current state of the code as your callback - and the code is effectively \"woken up\" as soon as the asynch action completes.</p>\n"
},
{
"answer_id": 2855037,
"author": "Zorf",
"author_id": 2281094,
"author_profile": "https://Stackoverflow.com/users/2281094",
"pm_score": 2,
"selected": false,
"text": "<p>The amb operator is a good example that allows prolog-like declarative programming.</p>\n\n<p>As we speak I'm coding a piece of music composition software in Scheme (I'm a musician with next to no knowledge of the theory behind music and I'm just analysing my own pieces to see how the maths behind it works.)</p>\n\n<p>Using the amb operator I can just fill in constraints which a melody must satisfy and let Scheme figure out the result.</p>\n\n<p>Continuations are probably put into Scheme because of the language philosophy, Scheme is a framework enabling you to realize about any programming paradigm found in other language by defining libraries in Scheme itself. Continuations are for making up your own abstract control structures like 'return', 'break' or to enable declarative programming. Scheme is more 'generalizing' and begs that such constructs should be able to be specified by the programmer too.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] | I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the [Wikipedia article](http://en.wikipedia.org/wiki/Continuation):
```
(define the-continuation #f)
(define (test)
(let ((i 0))
; call/cc calls its first function argument, passing
; a continuation variable representing this point in
; the program as the argument to that function.
;
; In this case, the function argument assigns that
; continuation to the variable the-continuation.
;
(call/cc (lambda (k) (set! the-continuation k)))
;
; The next time the-continuation is called, we start here.
(set! i (+ i 1))
i))
```
I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate.
So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.
Cheers! | In Algo & Data II we used these all the times to "exit" or "return" from a (long) function
for example the BFS algorthm to traverse trees with was implemented like this:
```
(define (BFS graph root-discovered node-discovered edge-discovered edge-bumped . nodes)
(define visited (make-vector (graph.order graph) #f))
(define q (queue.new))
(define exit ())
(define (BFS-tree node)
(if (node-discovered node)
(exit node))
(graph.map-edges
graph
node
(lambda (node2)
(cond ((not (vector-ref visited node2))
(when (edge-discovered node node2)
(vector-set! visited node2 #t)
(queue.enqueue! q node2)))
(else
(edge-bumped node node2)))))
(if (not (queue.empty? q))
(BFS-tree (queue.serve! q))))
(call-with-current-continuation
(lambda (my-future)
(set! exit my-future)
(cond ((null? nodes)
(graph.map-nodes
graph
(lambda (node)
(when (not (vector-ref visited node))
(vector-set! visited node #t)
(root-discovered node)
(BFS-tree node)))))
(else
(let loop-nodes
((node-list (car nodes)))
(vector-set! visited (car node-list) #t)
(root-discovered (car node-list))
(BFS-tree (car node-list))
(if (not (null? (cdr node-list)))
(loop-nodes (cdr node-list)))))))))
```
As you can see the algorithm will exit when the node-discovered function returns true:
```
(if (node-discovered node)
(exit node))
```
the function will also give a "return value": 'node'
why the function exits, is because of this statement:
```
(call-with-current-continuation
(lambda (my-future)
(set! exit my-future)
```
when we use exit, it will go back to the state before the execution, emptying the call-stack and return the value you gave it.
So basically, call-cc is used (here) to jump out of a recursive function, instead of waiting for the entire recursion to end by itself (which can be quite expensive when doing lots of computational work)
another smaller example doing the same with call-cc:
```
(define (connected? g node1 node2)
(define visited (make-vector (graph.order g) #f))
(define return ())
(define (connected-rec x y)
(if (eq? x y)
(return #t))
(vector-set! visited x #t)
(graph.map-edges g
x
(lambda (t)
(if (not (vector-ref visited t))
(connected-rec t y)))))
(call-with-current-continuation
(lambda (future)
(set! return future)
(connected-rec node1 node2)
(return #f))))
``` |
34,161 | <p>I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form).</p>
| [
{
"answer_id": 34172,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": true,
"text": "<p>If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be triggered by simply clicking inside a field, or other simple actions you wouldn't normally consider 'editing'.</p>\n\n<p>This is usually avoided in Access by using the RunCommand method to undo any edits before deleting the record:</p>\n\n<pre><code>DoCmd.RunCommand acCmdUndo\n</code></pre>\n"
},
{
"answer_id": 34178,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 0,
"selected": false,
"text": "<p>Also check the \"row locking mechanism\" that you have. I haven't used Access in a while but I remember that you could use set that in the table properties. You can access those properties clicking in the famous \"dot\" in the upper left corner of the table to bring up its properties. Well if you're using Access, you know what I'm talking about.</p>\n"
},
{
"answer_id": 67662,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 1,
"selected": false,
"text": "<p>samjudson suggested:</p>\n\n<blockquote>\n <p>DoCmd.RunCommand acCmdUndo</p>\n</blockquote>\n\n<p>You can also use Me.Undo, to undo the last edit to the form in which the code runs.</p>\n\n<p>Or, Me!MySubForm.Form.Undo to undo the last unsaved edit in the subform whose subform control is named \"MySubForm\".</p>\n\n<p>You can also use Me!MyControl.Undo to cancel the last edit to a particular control.</p>\n\n<p>\"DoCmd.RunCommand acCmdUndo\" will apply the Undo operation to the currently selected object, but you won't know for sure whether it will apply at the control or form level. Using the commands I suggested completely disambiguates what gets undone.</p>\n\n<p>Keep in mind, though, that Undo will not undo edits to a control after the control's AfterUpdate event has fired, or to a form after its AfterUpdate event has fired (i.e., the data has been saved to the underlying data table).</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717/"
] | I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form). | If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be triggered by simply clicking inside a field, or other simple actions you wouldn't normally consider 'editing'.
This is usually avoided in Access by using the RunCommand method to undo any edits before deleting the record:
```
DoCmd.RunCommand acCmdUndo
``` |
34,183 | <p>I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:</p>
<pre><code>SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
</code></pre>
<p>If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).</p>
<p>The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?</p>
<p><strong>EDIT:</strong> See my answer below for the contents of the batch file.</p>
<ul>
<li>The output.txt never gets created.</li>
</ul>
<p>I added these lines: </p>
<pre><code>psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
</code></pre>
<p>and stepped through them in debug mode. The code hangs on the <code>ReadLine()</code>. I'm stumped!</p>
| [
{
"answer_id": 34187,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>My guess would be that the build.cmd is waiting for some sort of user-interaction/reply. If you log the output of the command with the \"<strong>> logfile.txt</strong>\" operator at the end, it might help you find the problem.</p>\n"
},
{
"answer_id": 34191,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 2,
"selected": false,
"text": "<p>Without seeing the build.cmd it's hard to tell what is going on, however, you should build the path using Path.Combine(arg1, arg2); It's the correct way to build a path. </p>\n\n<pre><code>Path.Combine( Environment.SystemDirectory, \"cmd.exe\" );\n</code></pre>\n\n<p>I don't remember now but don't you have to set UseShellExecute = true ?</p>\n"
},
{
"answer_id": 34193,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 1,
"selected": false,
"text": "<p>Another possibility to \"debug\" it is to use standardoutput and then read from it:</p>\n\n<pre><code>psi.RedirectStandardOutput = True;\nProcess proc = Process.Start(psi);\nString whatever = proc.StandardOutput.ReadLine();\n</code></pre>\n"
},
{
"answer_id": 34197,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the contents of build.cmd:</p>\n\n<pre><code>@echo off\nset path=C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;%path%\n\nmsbuild myproject.csproj /t:Build > output.txt\nIF NOT ERRORLEVEL 1 goto :end\n\n:error\nbmail -s k2smtpout.secureserver.net -f [email protected] -t [email protected] -a \"Build failed.\" -m output.txt -h\n\n:end\ndel output.txt\n</code></pre>\n\n<p>As you can see, I'm careful not to output anything. It all goes to a file that gets emailed to me if the build happens to fail. I've actually been running this file as a scheduled task nightly for quite a while now. I'm trying to build a web app that allows me to run it on demand.</p>\n\n<p>Thanks for everyone's help so far! The Path.Combine tip was particularly useful.</p>\n"
},
{
"answer_id": 34205,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 1,
"selected": false,
"text": "<p>In order to \"see\" what's going on, I'd suggest you transform the process into something more interactive (turn off Echo off) and put some \"prints\" to see if anything is actually happening. What is in the output.txt file after you run this?</p>\n\n<p>Does the bmail actually executes?</p>\n\n<p>Put some prints after/before to see what's going on. </p>\n\n<p>Also add \"@\" to the arguments, just in case: </p>\n\n<pre><code>psi.Arguments = @\"/q /c build.cmd\";\n</code></pre>\n\n<p>It has to be something very simple :)</p>\n"
},
{
"answer_id": 34801,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 0,
"selected": false,
"text": "<p>I think cmd.exe hangs if the parameters are incorrect.</p>\n\n<p>If the batch executes correctly then I would just shell execute it like this instead.</p>\n\n<pre><code>ProcessStartInfo psi = new ProcessStartInfo();\nProcess p = new Process();\npsi.WindowStyle = ProcessWindowStyle.Hidden;\npsi.WorkingDirectory = @\"c:\\build\";\npsi.FileName = @\"C:\\build\\build.cmd\";\npsi.UseShellExecute = true;\npsi.UserName = \"builder\";\npsi.Password = password;\np.StartInfo = psi;\np.Start();\n</code></pre>\n\n<p>Also it could be that cmd.exe just can't find build.cmd so why not give the full path to the file?</p>\n"
},
{
"answer_id": 38072,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 0,
"selected": false,
"text": "<p>What are the endlines of you batch? If the code hangs on ReadLine, then the problem might be that it's unable to read the batch file…</p>\n"
},
{
"answer_id": 38164,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 2,
"selected": false,
"text": "<p>Why not just do all the work in C# instead of using batch files?</p>\n\n<p>I was bored so i wrote this real quick, it's just an outline of how I would do it since I don't know what the command line switches do or the file paths.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Text;\nusing System.Security;\nusing System.Diagnostics;\n\nnamespace asdf\n{\n class StackoverflowQuestion\n {\n private const string MSBUILD = @\"path\\to\\msbuild.exe\";\n private const string BMAIL = @\"path\\to\\bmail.exe\";\n private const string WORKING_DIR = @\"path\\to\\working_directory\";\n\n private string stdout;\n private Process p;\n\n public void DoWork()\n {\n // build project\n StartProcess(MSBUILD, \"myproject.csproj /t:Build\", true);\n }\n\n public void StartProcess(string file, string args, bool redirectStdout)\n {\n SecureString password = new SecureString();\n foreach (char c in \"mypassword\".ToCharArray())\n password.AppendChar(c);\n\n ProcessStartInfo psi = new ProcessStartInfo();\n p = new Process();\n psi.WindowStyle = ProcessWindowStyle.Hidden;\n psi.WorkingDirectory = WORKING_DIR;\n psi.FileName = file;\n psi.UseShellExecute = false;\n psi.RedirectStandardOutput = redirectStdout;\n psi.UserName = \"builder\";\n psi.Password = password;\n p.StartInfo = psi;\n p.EnableRaisingEvents = true;\n p.Exited += new EventHandler(p_Exited);\n p.Start();\n\n if (redirectStdout)\n {\n stdout = p.StandardOutput.ReadToEnd();\n }\n }\n\n void p_Exited(object sender, EventArgs e)\n {\n if (p.ExitCode != 0)\n {\n // failed\n StringBuilder args = new StringBuilder();\n args.Append(\"-s k2smtpout.secureserver.net \");\n args.Append(\"-f [email protected] \");\n args.Append(\"-t [email protected] \");\n args.Append(\"-a \\\"Build failed.\\\" \");\n args.AppendFormat(\"-m {0} -h\", stdout);\n\n // send email\n StartProcess(BMAIL, args.ToString(), false);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38331,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 4,
"selected": true,
"text": "<p>I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:</p>\n\n<p><a href=\"http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx\" rel=\"noreferrer\">http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx</a></p>\n\n<p>That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] | I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:
```
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
```
If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).
The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?
**EDIT:** See my answer below for the contents of the batch file.
* The output.txt never gets created.
I added these lines:
```
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
```
and stepped through them in debug mode. The code hangs on the `ReadLine()`. I'm stumped! | I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:
<http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx>
That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files. |
34,194 | <p>Where can I find some good pointers on best practices for running ASP.NET MVC on IIS6?</p>
<p>I haven't seen any realistic options for web-hosts who provide IIS7-hosting yet. Mostly because I don't live in the U.S.</p>
<p>So I was wondering on how you best build applications in ASP.NET MVC and make it easily available to deploy on both IIS6 and IIS7. Keep in mind that this is for standard web-hosts, so there is no access to ISAPI-filters or special settings inside IIS6.</p>
<p>Are there anything else one should think about when developing ASP.NET MVC-applications to target IIS6? Any functions that doesn't work?</p>
<p>UPDATE: One of the bigger issues is the thing with routes. The pattern {controller}/{action} will work on IIS7, but not IIS6 which needs {controller}.mvc/{action}. So how do I make this transparent? Again, <strong>no ISAPI</strong> and <strong>no IIS-settings</strong>, please.</p>
| [
{
"answer_id": 34206,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>With IIS6 you can do one of two things:</p>\n\n<ol>\n<li>Setup an ISAPI filter to map MVC URLs to ASP.NET</li>\n<li><a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true\" rel=\"nofollow noreferrer\">Include an extension in the URL</a>. For example: htp://localhost/Home.mvc</li>\n</ol>\n\n<p>Since option 1 is not available on most web-hosts, you have to go for number 2.</p>\n"
},
{
"answer_id": 34738,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>You don't have to live with that extension if you can install an ISAPI filter on the server.</p>\n\n<p>Basically you route matched urls to the {controller}.mvc variety, then in ASP.NET you rewrite this url to remove .mvc -- doing this you don't have to define any extra routes or expose .mvc to your users.</p>\n\n<p>I've written about this here:\n<a href=\"http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx\" rel=\"nofollow noreferrer\">http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx</a></p>\n\n<p>and Steve Sanderson has a good post here as well: <a href=\"http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/\" rel=\"nofollow noreferrer\">http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/</a></p>\n"
},
{
"answer_id": 35932,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 3,
"selected": false,
"text": "<p>Since you can't modify IIS settings to map .mvc to ASP.Net, you can use a different extension that's already mapped to ASP.Net. For example, you could use {controller}.ashx/{action} and it should work out of the box on IIS 6.</p>\n"
},
{
"answer_id": 40510,
"author": "Jim Geurts",
"author_id": 3085,
"author_profile": "https://Stackoverflow.com/users/3085",
"pm_score": -1,
"selected": false,
"text": "<p>I have a detailed step by step guide, but it requires that you use isapi_rewrite. View it at: <a href=\"http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/\" rel=\"nofollow noreferrer\">http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/</a></p>\n"
},
{
"answer_id": 316015,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>It took me a bit, but I figured out how to make the extensions work with IIS 6. First, you need to rework the base routing to include .aspx so that they will be routed through the ASP.NET ISAPI filter.</p>\n\n<pre><code>routes.MapRoute(\n \"Default\", // Route name\n \"{controller}.aspx/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n);\n</code></pre>\n\n<p>If you navigate to Home.aspx, for example, your site should be working fine. But Default.aspx and the default page address of <a href=\"http://[website]/\" rel=\"nofollow noreferrer\">http://[website]/</a> stop working correctly. So how is that fixed?</p>\n\n<p>Well, you need to define a second route. Unfortunately, using Default.aspx as the route does not work properly:</p>\n\n<pre><code>routes.MapRoute(\n \"Default2\", // Route name\n \"Default.aspx\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n);\n</code></pre>\n\n<p>So how do you get this to work? Well, this is where you need the original routing code:</p>\n\n<pre><code>routes.MapRoute(\n \"Default2\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n);\n</code></pre>\n\n<p>When you do this, Default.aspx and <a href=\"http://[website]/\" rel=\"nofollow noreferrer\">http://[website]/</a> both start working again, I think because they become successfully mapped back to the Home controller. So the complete solution is:</p>\n\n<pre><code>public class MvcApplication : System.Web.HttpApplication\n{\n public static void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n routes.MapRoute(\n \"Default\", // Route name\n \"{controller}.aspx/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n );\n\n routes.MapRoute(\n \"Default2\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n );\n }\n\n protected void Application_Start()\n {\n RegisterRoutes(RouteTable.Routes);\n }\n}\n</code></pre>\n\n<p>And your site should start working just fine under IIS 6. (At least it does on my PC.)</p>\n\n<p>And as a bonus, if you are using Html.ActionLink() in your pages, you should not have to change any other line of code throughout the entire site. This method takes care of properly tagging on the .aspx extension to the controller.</p>\n"
},
{
"answer_id": 1023346,
"author": "PropellerHead",
"author_id": 103365,
"author_profile": "https://Stackoverflow.com/users/103365",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned in this <a href=\"http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx\" rel=\"nofollow noreferrer\">blog post</a> by Phil Hack, it is possible to setup extension-less URLs for ASP.NET MVC in IIS 6 using <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true\" rel=\"nofollow noreferrer\">wildcard application mappings</a>:</p>\n\n<ol>\n<li>In IIS 6, go to the Application Configuration Properties for your ASP.NET MVC web application.</li>\n<li>Click \"Insert...\" in the Wildcard application maps section.</li>\n<li>Set the Executable to the path of the aspnet_isapi.dll (on my machine this is c:\\windows\\microsoft.net\\framework\\v2.0.50727\\aspnet_isapi.dll).</li>\n<li>Make sure NOT to check the \"Verify that file exists\" and click \"OK\".</li>\n</ol>\n\n<p>However as also mentioned by Hack, there are some performance implications of doing this.</p>\n"
},
{
"answer_id": 1788200,
"author": "Alex Ilyin",
"author_id": 114103,
"author_profile": "https://Stackoverflow.com/users/114103",
"pm_score": 1,
"selected": false,
"text": "<p>Url rewriting can help you to solve the problem. I've implemented solution allowing to deploy MVC application at any IIS version even when virtual hosting is used.\n<a href=\"http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx</a></p>\n"
},
{
"answer_id": 2687318,
"author": "anov",
"author_id": 181295,
"author_profile": "https://Stackoverflow.com/users/181295",
"pm_score": 0,
"selected": false,
"text": "<p>I have a sample application on IIS6.</p>\n\n<p>I found quick-and-dirty solution. (Dirty, because it contains default view name with extension) It does not require additional route, or anything special. (Except, your default route must {controller}.aspx/{action}... format)</p>\n\n<p>Here the default.aspx</p>\n\n<pre><code><%@ Page Language=\"C#\"%>\n<script runat=\"server\">\nprotected void Page_Load(object sender, EventArgs e)\n{\n HttpContext.Current.RewritePath(\"~/Home.aspx/index\");\n IHttpHandler httpHandler = new MvcHttpHandler();\n httpHandler.ProcessRequest(HttpContext.Current);\n}\n</script>\n</code></pre>\n\n<p>My sample applications default action was index, in Home directory.</p>\n\n<p>Note : I saw this code at Phil Haack's blog. Thanks to Brian Lowe.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] | Where can I find some good pointers on best practices for running ASP.NET MVC on IIS6?
I haven't seen any realistic options for web-hosts who provide IIS7-hosting yet. Mostly because I don't live in the U.S.
So I was wondering on how you best build applications in ASP.NET MVC and make it easily available to deploy on both IIS6 and IIS7. Keep in mind that this is for standard web-hosts, so there is no access to ISAPI-filters or special settings inside IIS6.
Are there anything else one should think about when developing ASP.NET MVC-applications to target IIS6? Any functions that doesn't work?
UPDATE: One of the bigger issues is the thing with routes. The pattern {controller}/{action} will work on IIS7, but not IIS6 which needs {controller}.mvc/{action}. So how do I make this transparent? Again, **no ISAPI** and **no IIS-settings**, please. | It took me a bit, but I figured out how to make the extensions work with IIS 6. First, you need to rework the base routing to include .aspx so that they will be routed through the ASP.NET ISAPI filter.
```
routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
If you navigate to Home.aspx, for example, your site should be working fine. But Default.aspx and the default page address of <http://[website]/> stop working correctly. So how is that fixed?
Well, you need to define a second route. Unfortunately, using Default.aspx as the route does not work properly:
```
routes.MapRoute(
"Default2", // Route name
"Default.aspx", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
So how do you get this to work? Well, this is where you need the original routing code:
```
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
When you do this, Default.aspx and <http://[website]/> both start working again, I think because they become successfully mapped back to the Home controller. So the complete solution is:
```
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
```
And your site should start working just fine under IIS 6. (At least it does on my PC.)
And as a bonus, if you are using Html.ActionLink() in your pages, you should not have to change any other line of code throughout the entire site. This method takes care of properly tagging on the .aspx extension to the controller. |
34,204 | <p>How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.</p>
<p><code>tf get</code> only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work.</p>
| [
{
"answer_id": 35169,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 1,
"selected": false,
"text": "<p>Well... It looks like you have three options.</p>\n\n<ol>\n<li><p>In your batch file, issue a tf get at each directory branch you want.</p></li>\n<li><p>reorganize your solution so that all of the dependencies are under the same root path.</p></li>\n<li><p>Use the visual way of right clicking on the loaded project and issuing the get command.</p></li>\n</ol>\n\n<p>The only time it's actually solution aware is when the project is loaded in the IDE; or when it's loaded by the build servers.</p>\n"
},
{
"answer_id": 52525,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>I know you mentioned batch files, but let me throw something else out for you.</p>\n\n<p>I'm going to guess that you are using the 2005 version of TFS. 2008 has all of the scheduling stuff built in. </p>\n\n<p>However, you could also use <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET\" rel=\"nofollow noreferrer\">CruiseControl.net</a> to do scheduled builds for you. I've used both TFS 2008 and CruiseControl and they both seem to work just fine.</p>\n"
},
{
"answer_id": 185256,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 3,
"selected": true,
"text": "<p>TFS has a <a href=\"http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx\" rel=\"nofollow noreferrer\">.Net SDK</a> that allows you to create your own custom programs that interact with a TFS Server. You could write a small program that performs the task you need:</p>\n\n<pre><code>TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(\"MyServer\");\nVersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));\n\nWorkSpace[] myWorkSpaces = vcs.QueryWorkSpaces(\"MyWorkSpaceName\", \"MyLoginName\", \"MyComputer\");\n\nmyWorkSpaces[0].Get(VersionSpec.Latest, GetOptions.GetAll);\n</code></pre>\n"
},
{
"answer_id": 1560520,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>One more possible solution is to use powershell. The following link is to a code project sample which shows how to get a solution from TFS and build it locally. Powershell is a much better solution than regular batch files.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/install/ExtractAndBuild.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/install/ExtractAndBuild.aspx</a></p>\n"
},
{
"answer_id": 1564465,
"author": "Richard Berg",
"author_id": 74439,
"author_profile": "https://Stackoverflow.com/users/74439",
"pm_score": 0,
"selected": false,
"text": "<p>Don't do this. VS is not nearly as smart as you think. (As evidenced by the mysterious & futile checkouts that everyone has experienced for 3+ product cycles, you & I included. This is not the mark of a reliable system!) </p>\n\n<p>What you describe only works for project-to-project references. Running source control operations from Solution Explorer will \"by design\" omit:</p>\n\n<ul>\n<li>project-to-assembly references</li>\n<li>video, sound, PDFs, any other type of media that VS doesn't support but may play an integral role in the product</li>\n<li>MSBuild *.targets files that are referenced in your projects</li>\n<li>any files of any kind that are referenced from custom targets</li>\n<li>any 3rd party executables required by the build process</li>\n<li>etc</li>\n</ul>\n\n<p>Just say <strong>no</strong> to incomplete synchronization. Down that path, only headaches lie. </p>\n\n<p>Run 'tf get' with no path scope from the command line, or rightclick -> Get from the root $/ node in Source Control Explorer.</p>\n"
},
{
"answer_id": 3320993,
"author": "Mike Diehl",
"author_id": 400539,
"author_profile": "https://Stackoverflow.com/users/400539",
"pm_score": 2,
"selected": false,
"text": "<p>I agree that Solution Explorer will \"by design\" omit all those objects, but only if you do not include them as Solution items, which I believe you <em>should</em> include in your solutions, so that a newbie can open the solution, do a Get Latest, and know they have all the dependencies needed for that solution, and not have to learn how to do it via a command line tool, or use Source Control Explorer if they don't want to. </p>\n\n<p>Including all the non-code dependencies as solution items (we organize the solution folders using the same folder structure as their source control folders) reduces \"voodoo\" knowledge required to open and compile the solution for new developers on a project. </p>\n\n<p>It would be good if you could link entire folder trees to a solution folder in the VS solution.</p>\n"
},
{
"answer_id": 10179887,
"author": "TheKnucklehead",
"author_id": 1276038,
"author_profile": "https://Stackoverflow.com/users/1276038",
"pm_score": 2,
"selected": false,
"text": "<p>If you have dependent projects under a different folder. Use this to loop through all of the sub directories to grab the latest for each project:</p>\n\n<p>Start in the main directory <code>C:\\Project\\SupportingProjects</code></p>\n\n<pre><code>FOR /D %%G IN (\"*\") DO ECHO ..from....%%G && tf get C:\\Projects\\SupportingProjects\\%%G \n\n::Get the latest for the Main project\ntf get C:\\Projects\\MainProject /recursive \n</code></pre>\n\n<p>In my case the MainProject folder contains the solution file and the project file.</p>\n\n<p>I found this easy and simple. </p>\n\n<p>More on the FOR command: <a href=\"http://ss64.com/nt/for_d.html\" rel=\"nofollow\">http://ss64.com/nt/for_d.html</a></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] | How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.
`tf get` only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work. | TFS has a [.Net SDK](http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx) that allows you to create your own custom programs that interact with a TFS Server. You could write a small program that performs the task you need:
```
TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer("MyServer");
VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
WorkSpace[] myWorkSpaces = vcs.QueryWorkSpaces("MyWorkSpaceName", "MyLoginName", "MyComputer");
myWorkSpaces[0].Get(VersionSpec.Latest, GetOptions.GetAll);
``` |
34,209 | <p>In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.</p>
<p>I get the following error:</p>
<pre><code>TypeError: __init__() got an unexpected keyword argument 'core'
</code></pre>
<p>[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?</p>
| [
{
"answer_id": 34391,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 2,
"selected": false,
"text": "<p>This is simple. I started getting this problems a few revisions ago. Basically, just remove the \"core=True\" parameter in the ImageField in the models, and then follow the instructions <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects\" rel=\"nofollow noreferrer\">here</a> to convert to what the newforms admin uses.</p>\n"
},
{
"answer_id": 35089,
"author": "Dan",
"author_id": 444,
"author_profile": "https://Stackoverflow.com/users/444",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>core</code> attribute isn't used anymore.</p>\n\n<p>From <a href=\"http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/\" rel=\"nofollow noreferrer\">Brian Rosner's Blog</a>:</p>\n\n<blockquote>\n <p>You can safely just remove any and all <code>core</code> arguments. They are no longer used. <em>newforms-admin</em> now provides a nice delete checkbox for exisiting instances in inlines.</p>\n</blockquote>\n"
},
{
"answer_id": 35633,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 4,
"selected": true,
"text": "<p>To get rid of \"This field is required,\" you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField).</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.
I get the following error:
```
TypeError: __init__() got an unexpected keyword argument 'core'
```
[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin? | To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField). |
34,249 | <p>What's the best (halting) algorithm for determining if a linked list has a cycle in it?</p>
<p>[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.</p>
<p>[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".</p>
| [
{
"answer_id": 34253,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 0,
"selected": false,
"text": "<p>What about using a hash table to store the already seen nodes (you look at them in order from the start of the list)? In practise, you could achieve something close to O(N).</p>\n\n<p>Otherwise, using a sorted heap instead of a hash table would achieve O(N log(N)).</p>\n"
},
{
"answer_id": 34255,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 7,
"selected": true,
"text": "<p>Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:</p>\n\n<pre><code>node* tortoise(begin), * hare(begin);\nwhile(hare = hare->next)\n{\n if(hare == tortoise) { throw std::logic_error(\"There's a cycle\"); }\n hare = hare->next;\n if(hare == tortoise) { throw std::logic_error(\"There's a cycle\"); }\n tortoise = tortoise->next;\n}\n</code></pre>\n\n<p>O(n), which is as good as you can get.</p>\n"
},
{
"answer_id": 34258,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "<p>I wonder if there's any other way than just going iteratively - populate an array as you step forwards, and check if the current node is already present in the array...</p>\n"
},
{
"answer_id": 34277,
"author": "Liedman",
"author_id": 890,
"author_profile": "https://Stackoverflow.com/users/890",
"pm_score": 0,
"selected": false,
"text": "<p>Konrad Rudolph's algorithm won't work if the cycle isn't pointing to the beginning. The following list will make it an infinite loop: 1->2->3->2.</p>\n\n<p>DrPizza's algorithm is definitely the way to go.</p>\n"
},
{
"answer_id": 34285,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>In this case OysterD's code will be the fastest solution (vertex coloring)</p>\n</blockquote>\n\n<p>That would really surprise me. My solution makes at most two passes through the list (if the last node is linked to the penultimate lode), and in the common case (no loop) will make only one pass. With no hashing, no memory allocation, etc.</p>\n"
},
{
"answer_id": 34296,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<blockquote>\n<p>In this case OysterD's code will be the fastest solution (vertex coloring)</p>\n</blockquote>\n<p>That would really surprise me. My solution makes at most two passes through the list (if the last node is linked to the penultimate lode), and in the common case (no loop) will make only one pass. With no hashing, no memory allocation, etc.</p>\n</blockquote>\n<p>Yes. I've noticed that the formulation wasn't perfect and have rephrased it. I still believe that a clever hashing might perform faster – by a hair. I believe your algorithm <em>is</em> the best solution, though.</p>\n<p>Just to underline my point: the vertec coloring is used to detect cycles in dependencies by modern garbage collectors so there is a very real use case for it. They mostly use bit flags to perform the coloring.</p>\n"
},
{
"answer_id": 140080,
"author": "Guillermo Phillips",
"author_id": 441661,
"author_profile": "https://Stackoverflow.com/users/441661",
"pm_score": 0,
"selected": false,
"text": "<p>You will have to visit every node to determine this. This can be done recursively. To stop you visiting already visited nodes, you need a flag to say 'already visited'. This of course doesn't give you loops. So instead of a bit flag, use a number. Start at 1. Check connected nodes and then mark these as 2 and recurse until the network is covered. If when checking nodes you encounter a node which is more than one less than the current node, then you have a cycle. The cycle length is given by the difference.</p>\n"
},
{
"answer_id": 6024103,
"author": "kbsant",
"author_id": 500236,
"author_profile": "https://Stackoverflow.com/users/500236",
"pm_score": 2,
"selected": false,
"text": "<p>Precondition: Keep track of the list size (update the size whenenver a node is added or deleted).</p>\n\n<p>Loop detection:</p>\n\n<ol>\n<li><p>Keep a counter when traversing the list size.</p></li>\n<li><p>If the counter exceeds the list size, there is a possible cycle.</p></li>\n</ol>\n\n<p>Complexity: O(n)</p>\n\n<p>Note: the comparison between the counter and the list size, as well as the update operation of the list size, must be made thread-safe.</p>\n"
},
{
"answer_id": 14070358,
"author": "Harry He",
"author_id": 1092195,
"author_profile": "https://Stackoverflow.com/users/1092195",
"pm_score": 0,
"selected": false,
"text": "<p>Two pointers are initialized at the head of list. One pointer forwards once at each step, and the other forwards twice at each step. If the faster pointer meets the slower one again, there is a loop in the list. Otherwise there is no loop if the faster one reaches the end of list.</p>\n\n<p>The sample code below is implemented according to this solution. The faster pointer is pFast, and the slower one is pSlow.</p>\n\n<pre><code>bool HasLoop(ListNode* pHead)\n{\n if(pHead == NULL)\n return false;\n\n\n ListNode* pSlow = pHead->m_pNext;\n if(pSlow == NULL)\n return false;\n\n\n ListNode* pFast = pSlow->m_pNext;\n while(pFast != NULL && pSlow != NULL)\n {\n if(pFast == pSlow)\n return true;\n\n\n pSlow = pSlow->m_pNext;\n\n\n pFast = pFast->m_pNext;\n if(pFast != NULL)\n pFast = pFast->m_pNext;\n }\n\n\n return false;\n}\n</code></pre>\n\n<p>This solution is available on <a href=\"http://codercareer.blogspot.com/2012/01/no-29-loop-in-list.html\" rel=\"nofollow\">my blog</a>. There is a more problem discussed in the blog: What is the entry node when there is cycle/loop in a list?</p>\n"
},
{
"answer_id": 19701109,
"author": "Ayrat",
"author_id": 801203,
"author_profile": "https://Stackoverflow.com/users/801203",
"pm_score": 0,
"selected": false,
"text": "<p>\"Hack\" solution (should work in C/C++):</p>\n\n<ul>\n<li>Traverse the list, and set the last bit of <code>next</code> pointer to 1. </li>\n<li>If find an element with flagged pointer -- return true and the first element of the cycle. </li>\n<li>Before returning, reset pointers back, though i believe dereferencing will work even with flagged pointers.</li>\n</ul>\n\n<p>Time complexity is 2n. Looks like it doesn't use any temporal variables.</p>\n"
},
{
"answer_id": 31607956,
"author": "mac jc",
"author_id": 4692908,
"author_profile": "https://Stackoverflow.com/users/4692908",
"pm_score": 1,
"selected": false,
"text": "<p>Take 2 pointer *p and *q , start traversing the linked list \"LL\" using both pointers :</p>\n\n<p>1) pointer p will delete previous node each time and pointing to next node.</p>\n\n<p>2) pointer q will go each time in forward direction direction only.</p>\n\n<p>conditions:</p>\n\n<p>1) pointer p is pointing to null and q is pointing to some node : Loop is present</p>\n\n<p>2) both pointer pointing to null: no loop is there </p>\n"
},
{
"answer_id": 38452940,
"author": "FlyingAura",
"author_id": 3426358,
"author_profile": "https://Stackoverflow.com/users/3426358",
"pm_score": 0,
"selected": false,
"text": "<p>This is a solution using a Hash table ( just a list actually) to save the pointer address. </p>\n\n<pre><code>def hash_cycle(node):\n hashl=[]\n while(node):\n if node in hashl:\n return True\n else:\n hashl.append(node)\n node=node.next\n return False\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | What's the best (halting) algorithm for determining if a linked list has a cycle in it?
[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.
[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph". | Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:
```
node* tortoise(begin), * hare(begin);
while(hare = hare->next)
{
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
hare = hare->next;
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
tortoise = tortoise->next;
}
```
O(n), which is as good as you can get. |
34,312 | <p>I was wondering if anyone that has experience in both this stuff can shed some light on the <em>significant</em> difference between the two if any?</p>
<p>Any specific strength of each that makes it suitable for any specific case?</p>
| [
{
"answer_id": 34338,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 3,
"selected": false,
"text": "<p>I found SimpleTest was even easier than PHPUnit to set up. Just extract it and you are good to go. A benefit of this is if you are working at more than one machine, since you can store the whole testing framework the same way as your source code, and thereby know that you are using the same framework code. Especially if you modify it in any way.</p>\n\n<p>So, I would say that a strength of SimpleTest is that it is very light weight and portable.</p>\n\n<p>SimpleTest also ships with a very simple HTML GUI, which is quite easy to extend if you want to. As far as I know, PHPUnit does not include a HTML GUI, but there are GUI:s available to download, such as <a href=\"http://cool.sourceforge.net/\" rel=\"noreferrer\">Cool</a>.</p>\n"
},
{
"answer_id": 34343,
"author": "FrankS",
"author_id": 3134,
"author_profile": "https://Stackoverflow.com/users/3134",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't checked Simple Test for a while, last time it had an eclipse plugin, which is a major factor for me, but it hasn't been updated for a long time.\nSebastian Bergmann is still very actively working on PHPUnit, but it still lacks a good plugin for eclipse - but it is included for the new Zend Studio.</p>\n"
},
{
"answer_id": 34474,
"author": "Eric Scrivner",
"author_id": 2594,
"author_profile": "https://Stackoverflow.com/users/2594",
"pm_score": 5,
"selected": false,
"text": "<p>I prefer PHPUnit now, but when I started out I used SimpleTest as I didn't always have access to the command line. SimpleTest is nice, but the only thing it really has over PHPUnit, in my opinion, is the web runner.</p>\n\n<p>The reasons I like PHPUnit are that it integrates with other PHP developer tools such as <a href=\"http://phing.info\" rel=\"noreferrer\" title=\"Phing\">phing</a> (as does SimpleTest), <a href=\"http://www.phpundercontrol.org/about.html\" rel=\"noreferrer\" title=\"phpUnderControl\">phpUnderControl</a>, and <a href=\"http://code.google.com/p/xinc/\" rel=\"noreferrer\" title=\"Xinc\">Xinc</a>. As of version 3.0 it <a href=\"http://www.phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects\" rel=\"noreferrer\" title=\"PHPUnit Mock Objects\">has mocking</a> support, is being actively developed, and the documentation is excellent.</p>\n\n<p>Really the only way to answer this question for yourself is to try both out for a time, and see which fits your style better.</p>\n\n<p>EDIT: Phing now integrates with SimpleTest as well.</p>\n"
},
{
"answer_id": 814882,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 4,
"selected": false,
"text": "<p>Baphled has a nice article on <a href=\"http://baphled.wordpress.com/2009/01/28/simpletest-vs-phpunit/\" rel=\"noreferrer\">SimpleTest vs PHPUnit3</a>.</p>\n"
},
{
"answer_id": 1004351,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Well I made a phpUnit web based UI test case runner and made it available on sourceforge. Uses ajax and has quite cool interface as well if you want to give it a shot check it at sourceforge. The project name is phpunitwebui and the website is <a href=\"http://phpunitwebui.sourceforge.net/\" rel=\"noreferrer\">http://phpunitwebui.sourceforge.net/</a></p>\n"
},
{
"answer_id": 1753464,
"author": "stfan",
"author_id": 213453,
"author_profile": "https://Stackoverflow.com/users/213453",
"pm_score": 4,
"selected": false,
"text": "<ul>\n<li>I could NOT understand how to download and install PHPUnit.</li>\n<li><p>I could, however, easily understand how to install SimpleTest. </p>\n\n<p>(As far as i can remember the instructions for <strong>PHPUnit</strong> said something along the lines of \"install it via PEAR and we won't give any instructions on how to do it any other way\") \nsee:</p></li>\n<li><a href=\"http://www.phpunit.de/manual/current/en/installation.html\" rel=\"noreferrer\">http://www.phpunit.de/manual/current/en/installation.html</a></li>\n</ul>\n\n<p>For <strong>SimpleTest</strong>, just download it and point to it from your code.</p>\n\n<p>So Simpletest won for me.</p>\n"
},
{
"answer_id": 4534779,
"author": "T0xicCode",
"author_id": 142020,
"author_profile": "https://Stackoverflow.com/users/142020",
"pm_score": 2,
"selected": false,
"text": "<p>As it has been pointed, it's mostly a preference choice, as both will run the tests you write for it and report back the results.</p>\n\n<p>The Simpletest web UI is very useful, but it can also sometimes get cumbersome. In my current project, I would have had to put more work into a system to make my application (an API) work with the web interface (set up apache correctly, copy files to the public_html root, etc.) than it would have been to simply run phpunit from the eclipse workspace. Therefore I choose PHPUnit. Also, the use of PEAR was a big plus since you don't need to manually track updates. Simply run <code>pear upgrade</code> once in a while and PHPUnit will be kept up-to-date.</p>\n"
},
{
"answer_id": 8715966,
"author": "edorian",
"author_id": 285578,
"author_profile": "https://Stackoverflow.com/users/285578",
"pm_score": 8,
"selected": true,
"text": "<p>This question is quite dated but as it is still getting traffic and answers I though I state my point here again even so I already did it on some other (newer) questions.</p>\n<p>I'm <em><strong>really really</strong></em> baffled that SimpleTest <strong>still</strong> is considered an alternative to phpunit. Maybe i'm just misinformed but as far as I've seen:</p>\n<ul>\n<li>PHPUnit is the standard; most frameworks use it (like Zend Framework (1&2), Cake, Agavi, even Symfony is dropping their own Framework in Symfony 2 for phpunit).</li>\n<li>PHPUnit is integrated in every PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm) and works nicely.</li>\n<li>Simpletest has an eclipse extension for PHP 5.1 (a.k.a. old) and nothing else.</li>\n<li>PHPUnit works fine with every continuous integration server since it outputs all standard log files for code coverage and test reports.</li>\n<li>Simpletest does not. While this is not a big problem to start with it will bite you big time once you stop "just testing" and start developing software (Yes that statement is provocative :) Don't take it too seriously).</li>\n<li>PHPUnit is actively maintained, stable and works great for every codebase, every scenario and every way you want to write your tests.</li>\n<li>(Subjective) <a href=\"http://www.phpunit.de/manual/3.6/en/code-coverage-analysis.html\" rel=\"noreferrer\">PHPUnit provides much nicer</a> code coverage reports <a href=\"http://www.simpletest.org/en/reporter_documentation.html\" rel=\"noreferrer\">than Simpletest</a></li>\n<li>With PHPUnit you also get these reports inside your IDE (<a href=\"http://netbeans.org/kb/docs/php/phpunit.htm%60\" rel=\"noreferrer\">Netbeans</a>, Eclipse, ...)</li>\n<li>Also there are a couple of suggestings for a <a href=\"https://stackoverflow.com/questions/2424457/web-interface-to-phpunit-tests\"><strong><code>web interface to phpunit tests</code></strong></a>.</li>\n</ul>\n<p>I've yet to see any argument in favor of SimpleTest. It's not even simpler to install since PHPUnit is available via pear:</p>\n<pre><code>pear channel-discover pear.phpunit.de\npear install phpunit/PHPUnit\n</code></pre>\n<p>and the "first test" looks pretty much the same.</p>\n<p>As of <code>PHPUnit 3.7</code> it's <strong>even easier to install</strong> it by just using the <a href=\"http://www.phpunit.de/manual/current/en/installation.html#installation.phar\" rel=\"noreferrer\"><strong><code>PHAR Archive</code></strong></a></p>\n<pre><code>wget http://pear.phpunit.de/get/phpunit.phar\nchmod +x phpunit-3.7.6.phar\n</code></pre>\n<p>or for windows just <a href=\"http://pear.phpunit.de/get/phpunit.phar\" rel=\"noreferrer\">downloading</a> the phar and running:</p>\n<pre><code>php phpunit-.phar\n</code></pre>\n<p>or when using the <a href=\"http://www.phpunit.de/manual/current/en/installation.html#installation.composer\" rel=\"noreferrer\">supported composer install</a> ways like</p>\n<pre><code>"require-dev": {\n "phpunit/phpunit": "3.7.*"\n}\n</code></pre>\n<p>to your composer.json.</p>\n<hr />\n<p>For everything you want to test PHPUnit will have a solution and you will be able to find help pretty much anywhere (SO, #phpunit irc channel on freenode, pretty much every php developer ;) )</p>\n<p>Please correct me if I've stated something wrong or forgot something :)</p>\n<h1>Overview of PHP Testing tools</h1>\n<p>Video: <a href=\"http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/\" rel=\"noreferrer\">http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/</a></p>\n<p>Slides: <a href=\"http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011\" rel=\"noreferrer\">http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011</a></p>\n<p>It mentions stuff like <a href=\"https://github.com/mageekguy/atoum\" rel=\"noreferrer\">Atoum</a> which calls its self: "A simple, modern and intuitive unit testing framework for PHP!"</p>\n<hr />\n<h3>Full disclosure</h3>\n<p>I've originally written this answer Jan. 2011 where I had no affiliation with any PHP Testing project. Since then I became a contributor to PHPUnit.</p>\n"
},
{
"answer_id": 12900425,
"author": "mr1031011",
"author_id": 821517,
"author_profile": "https://Stackoverflow.com/users/821517",
"pm_score": 1,
"selected": false,
"text": "<p>This question is old, but I want to add my experience: PHPUnit seems to be the standard now, but if you work with a legacy system that uses lots and lots of global variables, you may get stuck from the get go. It seems like there is no good way to do tests with global vars in PHPUnit, you seem to have to set your variables via $GLOBALS which is NO GOOD if you have tons of files setting global variables everywhere. OK some may say that the problem is in the legacy system but that doesn't mean we cannot do tests on such system. With SimpleTest such thing is simple. I suppose if PHPUnit allows us to include a file globally, not within any class/function scope then it wouldn't be too much of an issue as well.</p>\n\n<p>Another promising solution is <a href=\"http://www.enhance-php.com\" rel=\"nofollow\">http://www.enhance-php.com</a>, looks nice :)</p>\n"
},
{
"answer_id": 22735130,
"author": "Jens A. Koch",
"author_id": 1163786,
"author_profile": "https://Stackoverflow.com/users/1163786",
"pm_score": 4,
"selected": false,
"text": "<p>Half of the mentioned points in the accepted answer are simply not true:</p>\n\n<p><a href=\"https://github.com/simpletest/simpletest\" rel=\"nofollow noreferrer\">SimpleTest</a> has </p>\n\n<ul>\n<li>the easier setup (extract to folder, include and run)</li>\n<li>simply check the folder into version control (try to do that with phpunit nowadays :))</li>\n<li>less dependencies and lots of extensions (webtester, formtester, auth)</li>\n<li>a good code coverage reporter, which is easy to extend (dots, function names, colors)</li>\n<li>a code coverage summary (finally landed in PHPUnit 4.x)</li>\n<li>a decent web runner and an ajax web runner, with groups and single file executions</li>\n<li>still better diff tool (with no whitespace or newline problems)</li>\n<li>an adapter/wrapper to run SimpleTests by phpUnit and vice versa</li>\n<li>compatibility PHP5.4+</li>\n</ul>\n\n<p>The downside:</p>\n\n<ul>\n<li>not industry standard (PHPUnit)</li>\n<li>not actively maintained</li>\n</ul>\n"
},
{
"answer_id": 33172760,
"author": "user5454174",
"author_id": 5454174,
"author_profile": "https://Stackoverflow.com/users/5454174",
"pm_score": -1,
"selected": false,
"text": "<p>when there are thousands functions to test at one go, phpunit is way to go, simple test is falling short as it web based. </p>\n\n<p>I am still using simple web to for small scale test . </p>\n\n<p>But both are good</p>\n"
},
{
"answer_id": 39249666,
"author": "tru7",
"author_id": 430531,
"author_profile": "https://Stackoverflow.com/users/430531",
"pm_score": 2,
"selected": false,
"text": "<p>This is from the point of view of a very casual PHP developer:</p>\n\n<p>It took me two days to grasp PHPUnit, mostly trying to debug under Eclipse that I finally gave up.</p>\n\n<p>It took me two hours to setup Simpletest including debug under Eclipse.</p>\n\n<p>Maybe I will find the shortfalls of Simpletest in the future but so far it does well what I need: TestClasses, Mock objects, test-code debugging, and web interface for a quick snapshot of the situation.</p>\n\n<p>Again: <strong>This from the point of view of a very casual PHP user</strong> (not even developer :-)</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
] | I was wondering if anyone that has experience in both this stuff can shed some light on the *significant* difference between the two if any?
Any specific strength of each that makes it suitable for any specific case? | This question is quite dated but as it is still getting traffic and answers I though I state my point here again even so I already did it on some other (newer) questions.
I'm ***really really*** baffled that SimpleTest **still** is considered an alternative to phpunit. Maybe i'm just misinformed but as far as I've seen:
* PHPUnit is the standard; most frameworks use it (like Zend Framework (1&2), Cake, Agavi, even Symfony is dropping their own Framework in Symfony 2 for phpunit).
* PHPUnit is integrated in every PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm) and works nicely.
* Simpletest has an eclipse extension for PHP 5.1 (a.k.a. old) and nothing else.
* PHPUnit works fine with every continuous integration server since it outputs all standard log files for code coverage and test reports.
* Simpletest does not. While this is not a big problem to start with it will bite you big time once you stop "just testing" and start developing software (Yes that statement is provocative :) Don't take it too seriously).
* PHPUnit is actively maintained, stable and works great for every codebase, every scenario and every way you want to write your tests.
* (Subjective) [PHPUnit provides much nicer](http://www.phpunit.de/manual/3.6/en/code-coverage-analysis.html) code coverage reports [than Simpletest](http://www.simpletest.org/en/reporter_documentation.html)
* With PHPUnit you also get these reports inside your IDE ([Netbeans](http://netbeans.org/kb/docs/php/phpunit.htm%60), Eclipse, ...)
* Also there are a couple of suggestings for a [**`web interface to phpunit tests`**](https://stackoverflow.com/questions/2424457/web-interface-to-phpunit-tests).
I've yet to see any argument in favor of SimpleTest. It's not even simpler to install since PHPUnit is available via pear:
```
pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit
```
and the "first test" looks pretty much the same.
As of `PHPUnit 3.7` it's **even easier to install** it by just using the [**`PHAR Archive`**](http://www.phpunit.de/manual/current/en/installation.html#installation.phar)
```
wget http://pear.phpunit.de/get/phpunit.phar
chmod +x phpunit-3.7.6.phar
```
or for windows just [downloading](http://pear.phpunit.de/get/phpunit.phar) the phar and running:
```
php phpunit-.phar
```
or when using the [supported composer install](http://www.phpunit.de/manual/current/en/installation.html#installation.composer) ways like
```
"require-dev": {
"phpunit/phpunit": "3.7.*"
}
```
to your composer.json.
---
For everything you want to test PHPUnit will have a solution and you will be able to find help pretty much anywhere (SO, #phpunit irc channel on freenode, pretty much every php developer ;) )
Please correct me if I've stated something wrong or forgot something :)
Overview of PHP Testing tools
=============================
Video: <http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/>
Slides: <http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011>
It mentions stuff like [Atoum](https://github.com/mageekguy/atoum) which calls its self: "A simple, modern and intuitive unit testing framework for PHP!"
---
### Full disclosure
I've originally written this answer Jan. 2011 where I had no affiliation with any PHP Testing project. Since then I became a contributor to PHPUnit. |
34,365 | <p>Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to <code>HttpContext.Current.Request.QueryString</code>. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module?</p>
| [
{
"answer_id": 34375,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring. </p>\n\n<p>Using an <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx\" rel=\"noreferrer\">IHttpModule</a>, it might look something like:</p>\n\n<pre><code>context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!);\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 36809,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 0,
"selected": false,
"text": "<p>Ditto Espo's answer and I would like to add that usually in medium trust (specific to many shared hostings) you will not have access to reflection so ... RewritePath will remain your probably only choice.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1735/"
] | Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to `HttpContext.Current.Request.QueryString`. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module? | Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring.
Using an [IHttpModule](http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx), it might look something like:
```
context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!);
```
Hope this helps! |
34,390 | <p>Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?</p>
<p>Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?</p>
| [
{
"answer_id": 34432,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>If you are creating composite UserControl, then you can set the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass.aspx\" rel=\"nofollow noreferrer\">CSSClass</a> property on the child controls..</p>\n\n<p>If not, then you need to expose properties that are either of the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass.aspx\" rel=\"nofollow noreferrer\">Style</a> type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a <em>style</em> attribute to the HTML tags when rendering).</p>\n"
},
{
"answer_id": 34502,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 7,
"selected": true,
"text": "<p>Here's what I did:</p>\n\n<pre><code><link rel=\"Stylesheet\" type=\"text/css\" href=\"Stylesheet.css\" id=\"style\" runat=\"server\" visible=\"false\" />\n</code></pre>\n\n<p>It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.</p>\n\n<hr>\n\n<p>Here's an even more concise way to do this with multiple references;</p>\n\n<pre><code><% if (false) { %>\n <link rel=\"Stylesheet\" type=\"text/css\" href=\"Stylesheet.css\" />\n <script type=\"text/javascript\" src=\"js/jquery-1.2.6.js\" />\n<% } %>\n</code></pre>\n\n<p>As seen in <a href=\"http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx\" rel=\"noreferrer\">this blog post</a> from Phil Haack.</p>\n"
},
{
"answer_id": 9953418,
"author": "Kirtish Srivastava",
"author_id": 1304634,
"author_profile": "https://Stackoverflow.com/users/1304634",
"pm_score": -1,
"selected": false,
"text": "<p>You Can use <code>CSS</code> direct in <code>userControl</code>.</p>\n\n<p>Use this in <code>UserControl</code>:</p>\n\n<pre><code> <head>\n <title></title> \n <style type=\"text/css\">\n .wrapper {\n margin: 0 auto -142px; \n /* the bottom margin is the negative value of the footer's height */ \n }\n </style>\n </head>\n</code></pre>\n\n<p>This will work.</p>\n"
},
{
"answer_id": 14774992,
"author": "Abdul Saboor",
"author_id": 1176903,
"author_profile": "https://Stackoverflow.com/users/1176903",
"pm_score": 2,
"selected": false,
"text": "<p>Add the style on your usercontrol and import css in it.</p>\n\n<pre><code> <%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"WCReportCalendar.ascx.vb\"\nInherits=\"Intra.WCReportCalender\" %>\n <style type='text/css'> \n @import url(\"path of file.css\");\n // This is how i used jqueryui css\n @import url(\"http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css\"); \n\n </style>\n\n your html \n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?
Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView? | Here's what I did:
```
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" />
```
It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.
---
Here's an even more concise way to do this with multiple references;
```
<% if (false) { %>
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" />
<script type="text/javascript" src="js/jquery-1.2.6.js" />
<% } %>
```
As seen in [this blog post](http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx) from Phil Haack. |
34,394 | <p>How would you programmacially abbreviate <code>XHTML</code> to an arbitrary number of words without leaving unclosed or corrupted tags?</p>
<p>i.e.</p>
<pre><code><p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
hendrerit, <em>justo</em>.
</p>
</code></pre>
<p>Abbreviated to 25 words would be:</p>
<pre><code><p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue...</span>
</p>
</code></pre>
| [
{
"answer_id": 34432,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>If you are creating composite UserControl, then you can set the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass.aspx\" rel=\"nofollow noreferrer\">CSSClass</a> property on the child controls..</p>\n\n<p>If not, then you need to expose properties that are either of the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass.aspx\" rel=\"nofollow noreferrer\">Style</a> type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a <em>style</em> attribute to the HTML tags when rendering).</p>\n"
},
{
"answer_id": 34502,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 7,
"selected": true,
"text": "<p>Here's what I did:</p>\n\n<pre><code><link rel=\"Stylesheet\" type=\"text/css\" href=\"Stylesheet.css\" id=\"style\" runat=\"server\" visible=\"false\" />\n</code></pre>\n\n<p>It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.</p>\n\n<hr>\n\n<p>Here's an even more concise way to do this with multiple references;</p>\n\n<pre><code><% if (false) { %>\n <link rel=\"Stylesheet\" type=\"text/css\" href=\"Stylesheet.css\" />\n <script type=\"text/javascript\" src=\"js/jquery-1.2.6.js\" />\n<% } %>\n</code></pre>\n\n<p>As seen in <a href=\"http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx\" rel=\"noreferrer\">this blog post</a> from Phil Haack.</p>\n"
},
{
"answer_id": 9953418,
"author": "Kirtish Srivastava",
"author_id": 1304634,
"author_profile": "https://Stackoverflow.com/users/1304634",
"pm_score": -1,
"selected": false,
"text": "<p>You Can use <code>CSS</code> direct in <code>userControl</code>.</p>\n\n<p>Use this in <code>UserControl</code>:</p>\n\n<pre><code> <head>\n <title></title> \n <style type=\"text/css\">\n .wrapper {\n margin: 0 auto -142px; \n /* the bottom margin is the negative value of the footer's height */ \n }\n </style>\n </head>\n</code></pre>\n\n<p>This will work.</p>\n"
},
{
"answer_id": 14774992,
"author": "Abdul Saboor",
"author_id": 1176903,
"author_profile": "https://Stackoverflow.com/users/1176903",
"pm_score": 2,
"selected": false,
"text": "<p>Add the style on your usercontrol and import css in it.</p>\n\n<pre><code> <%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"WCReportCalendar.ascx.vb\"\nInherits=\"Intra.WCReportCalender\" %>\n <style type='text/css'> \n @import url(\"path of file.css\");\n // This is how i used jqueryui css\n @import url(\"http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css\"); \n\n </style>\n\n your html \n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3187/"
] | How would you programmacially abbreviate `XHTML` to an arbitrary number of words without leaving unclosed or corrupted tags?
i.e.
```
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
hendrerit, <em>justo</em>.
</p>
```
Abbreviated to 25 words would be:
```
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue...</span>
</p>
``` | Here's what I did:
```
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" />
```
It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.
---
Here's an even more concise way to do this with multiple references;
```
<% if (false) { %>
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" />
<script type="text/javascript" src="js/jquery-1.2.6.js" />
<% } %>
```
As seen in [this blog post](http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx) from Phil Haack. |
34,395 | <p>I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit?</p>
| [
{
"answer_id": 34431,
"author": "otsdr",
"author_id": 321238,
"author_profile": "https://Stackoverflow.com/users/321238",
"pm_score": 4,
"selected": true,
"text": "<p>In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:</p>\n\n<pre><code>static string Truncate(string s, int maxLength) {\n if (Encoding.UTF8.GetByteCount(s) <= maxLength)\n return s;\n var cs = s.ToCharArray();\n int length = 0;\n int i = 0;\n while (i < cs.Length){\n int charSize = 1;\n if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))\n charSize = 2;\n int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);\n if ((byteSize + length) <= maxLength){\n i = i + charSize;\n length += byteSize;\n }\n else\n break;\n }\n return s.Substring(0, i);\n}\n</code></pre>\n\n<p>The returned string can then be safely transferred to a byte array of length maxLength.</p>\n"
},
{
"answer_id": 34442,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You should be using the Encoding class to do your conversion to byte array correct? All Encoding objects have an overridden method GetMaxCharCount, which will give you \"The maximum number of characters produced by decoding the specified number of bytes.\" You should be able to use this value to trim your string and properly encode it.</p>\n"
},
{
"answer_id": 34448,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 1,
"selected": false,
"text": "<p>Efficient way would be finding how much (pessimistically) bytes you will need per character with</p>\n\n<pre><code>Encoding.GetMaxByteCount(1);\n</code></pre>\n\n<p>then dividing your string size by the result, then converting that much characters with</p>\n\n<pre><code>public virtual int Encoding.GetBytes (\n string s,\n int charIndex,\n int charCount,\n byte[] bytes,\n int byteIndex\n)\n</code></pre>\n\n<p>If you want to use less memory use</p>\n\n<pre><code>Encoding.GetByteCount(string);\n</code></pre>\n\n<p>but that is a much slower method.</p>\n"
},
{
"answer_id": 34450,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 1,
"selected": false,
"text": "<p>The Encoding class in .NET has a method called <code>GetByteCount</code> which can take in a string or char[]. If you pass in 1 character, it will tell you how many bytes are needed for that 1 character in whichever encoding you are using.</p>\n\n<p>The method <code>GetMaxByteCount</code> is faster, but it does a worst case calculation which could return a higher number than is actually needed.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2348/"
] | I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit? | In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:
```
static string Truncate(string s, int maxLength) {
if (Encoding.UTF8.GetByteCount(s) <= maxLength)
return s;
var cs = s.ToCharArray();
int length = 0;
int i = 0;
while (i < cs.Length){
int charSize = 1;
if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
charSize = 2;
int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
if ((byteSize + length) <= maxLength){
i = i + charSize;
length += byteSize;
}
else
break;
}
return s.Substring(0, i);
}
```
The returned string can then be safely transferred to a byte array of length maxLength. |
34,398 | <p>I have a new database table I need to create...<br>
It logically contains an <code>ID</code>, a <code>name</code>, and a <code>"value"</code>.<br>
That value field could be either numeric or a character string in nature. </p>
<p>I don't think I want to just make the field a <code>varchar</code>, because I also want to be able to query with filters like <code>WHERE value > 0.5</code> and such.</p>
<p>What's the best way to model this concept in SQL Server 2005?</p>
<p><strong>EDIT:</strong>
I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea.<br>
I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. </p>
<p>Any opinions on that?</p>
<p>What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view.<br>
I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance.<br>
That querying performance is my main concern.</p>
| [
{
"answer_id": 34402,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to store numeric and string values in the same column, I am not sure you can avoid doing a lot of casts and converts when using that column as a query filter. </p>\n"
},
{
"answer_id": 34405,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 2,
"selected": false,
"text": "<p>A good way to get the query support you want is to have two columns: numvalue that stores a number and textvalue that stores characters. They should be nullable or at least have some default that represents no value. Your application can then decide which column to store its value and which to leave with no value.</p>\n"
},
{
"answer_id": 34406,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "<p>two columns. </p>\n\n<pre><code>Table: (ValueLable as char(x), Value as numerica(p,s))\n</code></pre>\n"
},
{
"answer_id": 34407,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think it's possible to have a column with both varchar and int type. You could save your value as a varchar and cast it to int during your query. But this way you could get an exception if your value does contain any character. What are you trying to achieve?</p>\n"
},
{
"answer_id": 34408,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 0,
"selected": false,
"text": "<p>If you want it to be able to hold a character string, I think you have to make the column varchar, or similar.</p>\n\n<p>An alternative could be to have 2 or 3 columns instead of the one value column. Maybe have the three columns, value_type (enum between \"number\" and \"string\"), number_value, string_value. Then you could reconstruct that query to be</p>\n\n<pre><code>WHERE value_type = 'number' AND number_value > 0.5\n</code></pre>\n"
},
{
"answer_id": 34420,
"author": "Mark Struzinski",
"author_id": 1284,
"author_profile": "https://Stackoverflow.com/users/1284",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think you're going to be able to get around using VARCHAR or NVARCHAR as your data type. With mixed data like you're describing, you'll have to test the value when you pull the field out of the db and perform the appropriate CAST or CONVERT based on the data type. </p>\n"
},
{
"answer_id": 34480,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": true,
"text": "<p>Your issue with mixing data may be how Sql 2005 sorts text data. It's not a 'natural' sort.</p>\n\n<p>If you have a varchar field and you do:</p>\n\n<pre><code>where value > '20.5'\n</code></pre>\n\n<p>Values like \"5\" will be in your result (as in a character based sort \"5\" comes after \"20.5\")</p>\n\n<p>You're going to be better off with separate columns for storage.</p>\n\n<p>Use Coalesce to merge them into one column if you need them merged in your results:</p>\n\n<pre><code>select [ID], [Name], Coalesce( [value_str], [value_num] )\nfrom [tablename]\n</code></pre>\n"
},
{
"answer_id": 34567,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. Any opinions on that?</p>\n</blockquote>\n\n<p>It depends on the source of the data. If you are getting the data from users (or some other system) in some free-form manner and don't really care what type of data it is, then the best way to store it is the most generic manner (varchar, etc). If the incoming data is more structured and you care about that structure, then it makes more sense to keep that structure in the database by using separate fields.</p>\n\n<p>From the viewpoint of a SELECT it doesn't really matter; you can store it either way and read it as the same schema. Once you get into filters (as you mention) things get a bit more hairy, but still easily doable. However, you don't mention if you need to be able to update this data and if so, if you need to enforce any validation on the data.</p>\n\n<p>From the sounds of it, you need to do different types of searches based on the \"type\" of value being stored. As such, it may make sense to add a Type field so that any filters can be quickly limited to the type of values that you care about. Note, by Type I mean a more logical, application scope, Type; not the actual datatype being stored.</p>\n\n<p>My recommendation would be to use a single field with a Type column if you need to easily support UPDATEs or use multiple fields (or tables, if these are totally different data sets) if SELECTing and filtering is all that is needed.</p>\n"
},
{
"answer_id": 34626,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You might consider using two columns, one \"string\" and one \"numeric\" (whatever variants of those are appropriate) with the \"string\" column NOT NULL and the \"numeric\" column allowing NULL values. When inserting a value, always populate the \"string\" column indpendent of the type, however if the value is numeric, ALSO store it in the \"numeric\" column. Now you have a built in indicator as to the type (if the \"numeric\" column is populated it is numeric, if not it is a string), can always just pull the value for display from the \"string\" column, and can use the \"numeric\" value in calculations or for proper numeric sorting / comparison as needed. You could always add a third column indicating the value type, but this approach eliminates the need for that. Note that you might consider maintaining the numeric and string values using a set of INSERT and UPDATE triggers.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I have a new database table I need to create...
It logically contains an `ID`, a `name`, and a `"value"`.
That value field could be either numeric or a character string in nature.
I don't think I want to just make the field a `varchar`, because I also want to be able to query with filters like `WHERE value > 0.5` and such.
What's the best way to model this concept in SQL Server 2005?
**EDIT:**
I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea.
I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column.
Any opinions on that?
What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view.
I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance.
That querying performance is my main concern. | Your issue with mixing data may be how Sql 2005 sorts text data. It's not a 'natural' sort.
If you have a varchar field and you do:
```
where value > '20.5'
```
Values like "5" will be in your result (as in a character based sort "5" comes after "20.5")
You're going to be better off with separate columns for storage.
Use Coalesce to merge them into one column if you need them merged in your results:
```
select [ID], [Name], Coalesce( [value_str], [value_num] )
from [tablename]
``` |
34,401 | <p>Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?</p>
<pre><code><?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" />
</connectionStrings>
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" >
</errorLog>
<errorMail from="[email protected]"
to="[email protected]"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="***"
userName="***"
password="***">
</errorMail>
</elmah>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx">
<error statusCode="403" redirect="NotAuthorized.aspx" />
<!--<error statusCode="404" redirect="FileNotFound.htm" />-->
</customErrors>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
</system.web>
</configuration>
</code></pre>
| [
{
"answer_id": 34434,
"author": "Rob Bazinet",
"author_id": 2305,
"author_profile": "https://Stackoverflow.com/users/2305",
"pm_score": 3,
"selected": false,
"text": "<p>I have used Elmah myself in this configuration and I had to setup the server with SMTP locally. It is a straight-forward install on you local IIS server. This should do the trick.</p>\n\n<p>Good point above, you need the errorMail module BUT if you are not using a remote SMTP server you need SMTP locally, just to clarify.</p>\n"
},
{
"answer_id": 34435,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 7,
"selected": true,
"text": "<p>You need the ErrorMail httpModule.</p>\n\n<p>add this line inside the <httpModules> section</p>\n\n<pre><code><add name=\"ErrorMail\" type=\"Elmah.ErrorMailModule, Elmah\" />\n</code></pre>\n\n<p>If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server.</p>\n"
},
{
"answer_id": 7254040,
"author": "Anand Patel",
"author_id": 840003,
"author_profile": "https://Stackoverflow.com/users/840003",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, if you are not using remote SMTP server you must have SMTP Server configured locally. You can also configure email for elmah in web.config as follows:</p>\n\n<pre><code><configSections>\n <sectionGroup name=\"elmah\">\n <section name=\"errorMail\" requirePermission=\"false\" type=\"Elmah.ErrorMailSectionHandler, Elmah\"> \n </sectionGroup>\n</configSections> \n\n<elmah> \n <errorMail from=\"from Mail Address\" to=\"to mail address\" \n async=\"true\" smtpPort=\"0\" useSsl=\"true\" /> \n</elmah>\n\n<system.net> \n <mailSettings> \n <smtp deliveryMethod =\"Network\"> \n <network host=\"smtp.gmail.com\" port=\"587\" userName=\"yourgmailEmailAddress\" password=\"yourGmailEmailPassword\" /> \n </smtp> \n </mailSettings> \n</system.net>\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] | Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by \* \* \*. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?
```
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" />
</connectionStrings>
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" >
</errorLog>
<errorMail from="[email protected]"
to="[email protected]"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="***"
userName="***"
password="***">
</errorMail>
</elmah>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx">
<error statusCode="403" redirect="NotAuthorized.aspx" />
<!--<error statusCode="404" redirect="FileNotFound.htm" />-->
</customErrors>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
</system.web>
</configuration>
``` | You need the ErrorMail httpModule.
add this line inside the <httpModules> section
```
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
```
If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server. |
34,411 | <p>I always tend to forget these built-in <strong>Symfony</strong> functions for making links.</p>
| [
{
"answer_id": 34426,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 1,
"selected": false,
"text": "<p>This advice is for symfony 1.0. It probably will work for later versions.</p>\n\n<p><strong>Within your sfAction class</strong>:</p>\n\n<p>string genUrl($parameters = array(), $absolute = false)</p>\n\n<p>eg. \n$this->getController()->genUrl('yourmodule/youraction?key=value&key2=value', true);</p>\n\n<p><strong>In a template</strong>:</p>\n\n<p>This will generate a normal link.</p>\n\n<p>string link_to($name, $internal_uri, $options = array());</p>\n\n<p>eg. \nlink_to('My link name', 'yourmodule/youraction?key=value&key2=value');</p>\n"
},
{
"answer_id": 36026,
"author": "jamz",
"author_id": 3734,
"author_profile": "https://Stackoverflow.com/users/3734",
"pm_score": 4,
"selected": true,
"text": "<p>If your goal is to have user-friendly URLs throughout your application, use the following approach:</p>\n\n<p>1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager):</p>\n\n<pre><code>recent_questions:\n url: questions/recent/:page\n param: { module: questions, action: recent, page: 1 }\n</code></pre>\n\n<p>2) Once the routing rule is set, use the <code>url_for()</code> helper in your template to format outgoing URLs.</p>\n\n<pre><code><a href=\"<?php echo url_for('questions/recent?page=1') ?>\">Recent Questions</a>\n</code></pre>\n\n<p>In this example, the following URL will be constructed: <code>http://myapp/questions/recent/1.html</code>.</p>\n\n<p>3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the <code>:/page</code> portion of the URL) will become request parameters.</p>\n\n<p>You can also use the <code>link_to()</code> helper to output a URL without using the HTML <code><a></code> tag.</p>\n"
},
{
"answer_id": 372205,
"author": "thrashr888",
"author_id": 46443,
"author_profile": "https://Stackoverflow.com/users/46443",
"pm_score": 0,
"selected": false,
"text": "<p>In addition, if you actually want a query string with that url, you use this: </p>\n\n<pre><code>link_to('My link name', 'yourmodule/youraction?key=value&key2=value',array('query_string'=>'page=2'));\n</code></pre>\n\n<p>Otherwise, it's going to try to route it as part of the url and likely break your action.</p>\n"
},
{
"answer_id": 8052024,
"author": "priyabagus",
"author_id": 1035374,
"author_profile": "https://Stackoverflow.com/users/1035374",
"pm_score": 0,
"selected": false,
"text": "<p>You can generate URL directly without define the rule first.</p>\n\n<p>If you want to generate URL in the actions, you can use <strong>generateUrl()</strong> helper:</p>\n\n<pre><code>$this->generateUrl('default', array('module'=>'[ModuleName]','action'=>'[ActionName]'))\n</code></pre>\n\n<p>If you want to generate URL in the templates, you can use <strong>url_for()</strong> helper:</p>\n\n<pre><code>url_for('[ModuleName]/[ActionName]', $absolute)\n</code></pre>\n\n<p>set $absolute as true/false, dont forget to use echo if you want to display it.</p>\n\n<p>But if you want to make a <strong>link</strong> (something like <code><a href=\"\"></a></code>), <strong>link_to()</strong> helper will do.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108/"
] | I always tend to forget these built-in **Symfony** functions for making links. | If your goal is to have user-friendly URLs throughout your application, use the following approach:
1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager):
```
recent_questions:
url: questions/recent/:page
param: { module: questions, action: recent, page: 1 }
```
2) Once the routing rule is set, use the `url_for()` helper in your template to format outgoing URLs.
```
<a href="<?php echo url_for('questions/recent?page=1') ?>">Recent Questions</a>
```
In this example, the following URL will be constructed: `http://myapp/questions/recent/1.html`.
3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the `:/page` portion of the URL) will become request parameters.
You can also use the `link_to()` helper to output a URL without using the HTML `<a>` tag. |
34,439 | <p>Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?</p>
<p>Or,</p>
<p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
| [
{
"answer_id": 34452,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 10,
"selected": true,
"text": "<p><strong>For many objects</strong>, you can use this code, replacing 'object' with the object you're interested in:</p>\n<pre class=\"lang-py prettyprint-override\"><code>object_methods = [method_name for method_name in dir(object)\n if callable(getattr(object, method_name))]\n</code></pre>\n<p>I discovered it at <a href=\"https://web.archive.org/web/20180901124519/http://www.diveintopython.net/power_of_introspection/index.html\" rel=\"noreferrer\">diveintopython.net</a> (now archived), that should provide some further details!</p>\n<p><strong>If you get an <code>AttributeError</code>, you can use this instead</strong>:</p>\n<p><code>getattr()</code> is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\ndf = pd.DataFrame([[10, 20, 30], [100, 200, 300]],\n columns=['foo', 'bar', 'baz'])\ndef get_methods(object, spacing=20):\n methodList = []\n for method_name in dir(object):\n try:\n if callable(getattr(object, method_name)):\n methodList.append(str(method_name))\n except Exception:\n methodList.append(str(method_name))\n processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)\n for method in methodList:\n try:\n print(str(method.ljust(spacing)) + ' ' +\n processFunc(str(getattr(object, method).__doc__)[0:90]))\n except Exception:\n print(method.ljust(spacing) + ' ' + ' getattr() failed')\n\nget_methods(df['foo'])\n</code></pre>\n"
},
{
"answer_id": 34467,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 8,
"selected": false,
"text": "<p>You can use the built in <code>dir()</code> function to get a list of all the attributes a module has. Try this at the command line to see how it works.</p>\n<pre><code>>>> import moduleName\n>>> dir(moduleName)\n</code></pre>\n<p>Also, you can use the <code>hasattr(module_name, "attr_name")</code> function to find out if a module has a specific attribute.</p>\n<p>See the <a href=\"https://zetcode.com/python/introspection/\" rel=\"noreferrer\">Python introspection</a> for more information.</p>\n"
},
{
"answer_id": 34472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>To check if it has a particular method:</p>\n\n<pre><code>hasattr(object,\"method\")\n</code></pre>\n"
},
{
"answer_id": 34481,
"author": "jmanning2k",
"author_id": 1480,
"author_profile": "https://Stackoverflow.com/users/1480",
"pm_score": 5,
"selected": false,
"text": "<p>On top of the more direct answers, I'd be remiss if I didn't mention <a href=\"http://ipython.scipy.org/\" rel=\"nofollow noreferrer\">IPython</a>.</p>\n<p>Hit <kbd>Tab</kbd> to see the available methods, with autocompletion.</p>\n<p>And once you've found a method, try:</p>\n<pre><code>help(object.method)\n</code></pre>\n<p>to see the pydocs, method signature, etc.</p>\n<p>Ahh... <a href=\"http://en.wikipedia.org/wiki/REPL\" rel=\"nofollow noreferrer\">REPL</a>.</p>\n"
},
{
"answer_id": 15640132,
"author": "Bruno Bronosky",
"author_id": 117471,
"author_profile": "https://Stackoverflow.com/users/117471",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>...is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called</p>\n</blockquote>\n<p>While "<a href=\"http://docs.python.org/2/glossary.html#term-eafp\" rel=\"nofollow noreferrer\">Easier to ask for forgiveness than permission</a>" is certainly the Pythonic way, you may be looking for:</p>\n<pre><code>d={'foo':'bar', 'spam':'eggs'}\nif 'get' in dir(d):\n d.get('foo')\n# OUT: 'bar'\n</code></pre>\n"
},
{
"answer_id": 20100900,
"author": "Pawan Kumar",
"author_id": 1668274,
"author_profile": "https://Stackoverflow.com/users/1668274",
"pm_score": 7,
"selected": false,
"text": "<p>The simplest method is to use <code>dir(objectname)</code>. It will display all the methods available for that object.</p>\n"
},
{
"answer_id": 27380776,
"author": "Cld",
"author_id": 3973130,
"author_profile": "https://Stackoverflow.com/users/3973130",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with all methods indicated here is that you <em>can't</em> be sure that a method doesn't exist.</p>\n<p>In Python you can intercept the dot calling through <code>__getattr__</code> and <code>__getattribute__</code>, making it possible to create method "at runtime"</p>\n<p>Example:</p>\n<pre><code>class MoreMethod(object):\n def some_method(self, x):\n return x\n def __getattr__(self, *args):\n return lambda x: x*2\n</code></pre>\n<p>If you execute it, you can call non-existing methods in the object dictionary...</p>\n<pre><code>>>> o = MoreMethod()\n>>> o.some_method(5)\n5\n>>> dir(o)\n['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']\n>>> o.i_dont_care_of_the_name(5)\n10\n</code></pre>\n<p>And it's why you use the <a href=\"https://docs.python.org/2/glossary.html#term-eafp\" rel=\"nofollow noreferrer\">Easier to ask for forgiveness than permission</a> paradigms in Python.</p>\n"
},
{
"answer_id": 28220562,
"author": "paulmelnikow",
"author_id": 893113,
"author_profile": "https://Stackoverflow.com/users/893113",
"pm_score": 4,
"selected": false,
"text": "<p>If you specifically want <strong>methods</strong>, you should use <a href=\"https://docs.python.org/2/library/inspect.html#inspect.ismethod\" rel=\"noreferrer\">inspect.ismethod</a>.</p>\n\n<p>For method names:</p>\n\n<pre><code>import inspect\nmethod_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]\n</code></pre>\n\n<p>For the methods themselves:</p>\n\n<pre><code>import inspect\nmethods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]\n</code></pre>\n\n<p>Sometimes <a href=\"https://docs.python.org/3/library/inspect.html#inspect.isroutine\" rel=\"noreferrer\"><code>inspect.isroutine</code></a> can be useful too (for built-ins, C extensions, Cython without the \"binding\" compiler directive).</p>\n"
},
{
"answer_id": 29851741,
"author": "james_womack",
"author_id": 230571,
"author_profile": "https://Stackoverflow.com/users/230571",
"pm_score": 1,
"selected": false,
"text": "<p>One can create a <code>getAttrs</code> function that will return an object's callable property names</p>\n\n<pre><code>def getAttrs(object):\n return filter(lambda m: callable(getattr(object, m)), dir(object))\n\nprint getAttrs('Foo bar'.split(' '))\n</code></pre>\n\n<p>That'd return</p>\n\n<pre><code>['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',\n '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', \n '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', \n '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', \n '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', \n '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', \n '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', \n 'remove', 'reverse', 'sort']\n</code></pre>\n"
},
{
"answer_id": 32608298,
"author": "aver",
"author_id": 3165751,
"author_profile": "https://Stackoverflow.com/users/3165751",
"pm_score": 2,
"selected": false,
"text": "<p>There is no reliable way to list all object's methods. <code>dir(object)</code> is usually useful, but in some cases it may not list all methods. According to <a href=\"https://docs.python.org/2/library/functions.html#dir\" rel=\"nofollow\"><code>dir()</code> documentation</a>: <em>\"With an argument, <strong>attempt</strong> to return a list of valid attributes for that object.\"</em></p>\n\n<p>Checking that method exists can be done by <code>callable(getattr(object, method))</code> as already mentioned there.</p>\n"
},
{
"answer_id": 37464502,
"author": "ivanleoncz",
"author_id": 5780109,
"author_profile": "https://Stackoverflow.com/users/5780109",
"pm_score": 5,
"selected": false,
"text": "<p>I believe that you want something like this:</p>\n<blockquote>\n<p>a list of attributes from an object</p>\n</blockquote>\n<p>The built-in function <code>dir()</code> can do this job.</p>\n<p>Taken from <code>help(dir)</code> output on your Python shell:</p>\n<blockquote>\n<p>dir(...)</p>\n<pre><code>dir([object]) -> list of strings\n</code></pre>\n<p>If called without an argument, return the names in the current scope.</p>\n<p>Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it.</p>\n<p>If the object supplies a method named <code>__dir__</code>, it will be used; otherwise\nthe default dir() logic is used and returns:</p>\n<ul>\n<li>for a module object: the module's attributes.</li>\n<li>for a class object: its attributes, and recursively the attributes of its bases.</li>\n<li>for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.</li>\n</ul>\n</blockquote>\n<p><strong>For example:</strong></p>\n<pre><code>$ python\nPython 2.7.6 (default, Jun 22 2015, 17:58:13)\n[GCC 4.8.2] on linux2\nType "help", "copyright", "credits" or "license" for more information.\n\n>>> a = "I am a string"\n>>>\n>>> type(a)\n<class 'str'>\n>>>\n>>> dir(a)\n['__add__', '__class__', '__contains__', '__delattr__', '__doc__',\n'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',\n'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',\n'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',\n'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',\n'__setattr__', '__sizeof__', '__str__', '__subclasshook__',\n'_formatter_field_name_split', '_formatter_parser', 'capitalize',\n'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',\n'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',\n'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',\n'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',\n'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',\n'translate', 'upper', 'zfill']\n</code></pre>\n"
},
{
"answer_id": 47317075,
"author": "Valery Ramusik",
"author_id": 5992385,
"author_profile": "https://Stackoverflow.com/users/5992385",
"pm_score": 4,
"selected": false,
"text": "<p>Open a Bash shell (<kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>T</kbd> on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press <kbd>Tab</kbd> twice and you'll see something like this:</p>\n<pre><code>user@note:~$ python3\nPython 3.4.3 (default, Nov 17 2016, 01:08:31)\n[GCC 4.8.4] on linux\nType "help", "copyright", "credits" or "license" for more information.\n>>> import readline\n>>> readline.parse_and_bind("tab: complete")\n>>> s = "Any object. Now it's a string"\n>>> s. # here tab should be pressed twice\ns.__add__( s.__rmod__( s.istitle(\ns.__class__( s.__rmul__( s.isupper(\ns.__contains__( s.__setattr__( s.join(\ns.__delattr__( s.__sizeof__( s.ljust(\ns.__dir__( s.__str__( s.lower(\ns.__doc__ s.__subclasshook__( s.lstrip(\ns.__eq__( s.capitalize( s.maketrans(\ns.__format__( s.casefold( s.partition(\ns.__ge__( s.center( s.replace(\ns.__getattribute__( s.count( s.rfind(\ns.__getitem__( s.encode( s.rindex(\ns.__getnewargs__( s.endswith( s.rjust(\ns.__gt__( s.expandtabs( s.rpartition(\ns.__hash__( s.find( s.rsplit(\ns.__init__( s.format( s.rstrip(\ns.__iter__( s.format_map( s.split(\ns.__le__( s.index( s.splitlines(\ns.__len__( s.isalnum( s.startswith(\ns.__lt__( s.isalpha( s.strip(\ns.__mod__( s.isdecimal( s.swapcase(\ns.__mul__( s.isdigit( s.title(\ns.__ne__( s.isidentifier( s.translate(\ns.__new__( s.islower( s.upper(\ns.__reduce__( s.isnumeric( s.zfill(\ns.__reduce_ex__( s.isprintable(\ns.__repr__( s.isspace(\n</code></pre>\n"
},
{
"answer_id": 48284803,
"author": "Mahdi Ghelichi",
"author_id": 8291566,
"author_profile": "https://Stackoverflow.com/users/8291566",
"pm_score": 1,
"selected": false,
"text": "<p>Take a list as an object</p>\n\n<pre><code>obj = []\n</code></pre>\n\n<p><code>list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))</code></p>\n\n<p>You get:</p>\n\n<pre><code>['__add__',\n '__class__',\n '__contains__',\n '__delattr__',\n '__delitem__',\n '__dir__',\n '__eq__',\n '__format__',\n '__ge__',\n '__getattribute__',\n '__getitem__',\n '__gt__',\n '__iadd__',\n '__imul__',\n '__init__',\n '__init_subclass__',\n '__iter__',\n '__le__',\n '__len__',\n '__lt__',\n '__mul__',\n '__ne__',\n '__new__',\n '__reduce__',\n '__reduce_ex__',\n '__repr__',\n '__reversed__',\n '__rmul__',\n '__setattr__',\n '__setitem__',\n '__sizeof__',\n '__str__',\n '__subclasshook__',\n 'append',\n 'clear',\n 'copy',\n 'count',\n 'extend',\n 'index',\n 'insert',\n 'pop',\n 'remove',\n 'reverse',\n 'sort']\n</code></pre>\n"
},
{
"answer_id": 49194581,
"author": "Simon PII",
"author_id": 9467669,
"author_profile": "https://Stackoverflow.com/users/9467669",
"pm_score": 0,
"selected": false,
"text": "<p>In order to search for a specific method in a whole module</p>\n\n<pre><code>for method in dir(module) :\n if \"keyword_of_methode\" in method :\n print(method, end=\"\\n\")\n</code></pre>\n"
},
{
"answer_id": 50050651,
"author": "Paritosh Vyas",
"author_id": 6852381,
"author_profile": "https://Stackoverflow.com/users/6852381",
"pm_score": 5,
"selected": false,
"text": "<p>The simplest way to get a list of methods of any object is to use the <code>help()</code> command.</p>\n<pre><code>help(object)\n</code></pre>\n<p>It will list out all the available/important methods associated with that object.</p>\n<p>For example:</p>\n<pre><code>help(str)\n</code></pre>\n"
},
{
"answer_id": 58987382,
"author": "The Mob",
"author_id": 8812904,
"author_profile": "https://Stackoverflow.com/users/8812904",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-py prettyprint-override\"><code>import moduleName\nfor x in dir(moduleName):\n print(x)\n</code></pre>\n<p>This should work :)</p>\n"
},
{
"answer_id": 61189861,
"author": "Nick Cuevas",
"author_id": 5784892,
"author_profile": "https://Stackoverflow.com/users/5784892",
"pm_score": 0,
"selected": false,
"text": "<p>If you are, for instance, using shell plus you can use this instead:</p>\n\n<pre><code>>> MyObject??\n</code></pre>\n\n<p>that way, with the '??' just after your object, it'll show you all the attributes/methods the class has.</p>\n"
},
{
"answer_id": 63481052,
"author": "Sanmitha Sadhishkumar",
"author_id": 13827419,
"author_profile": "https://Stackoverflow.com/users/13827419",
"pm_score": -1,
"selected": false,
"text": "<p>You can make use of dir() which is pre-defined in Python.</p>\n<pre><code>import module_name\ndir(module_name)\n</code></pre>\n<p>You can also pass an object to dir() as</p>\n<pre><code>dir(object_name)\n</code></pre>\n<p>If the object is an object of a pre-defined class such as int, str, etc. it displays the methods in it (you may know those methods as built in functions). If that object is created for a user-defined class, it displays all the methods given in that class.</p>\n"
},
{
"answer_id": 63620684,
"author": "revliscano",
"author_id": 7303434,
"author_profile": "https://Stackoverflow.com/users/7303434",
"pm_score": 2,
"selected": false,
"text": "<p>I have done the following function (<code>get_object_functions</code>), which receives an object (<code>object_</code>) as its argument, and <strong>returns a list (<code>functions</code>) containing all of the methods (including static and class methods) defined in the object's class</strong>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_object_functions(object_):\n functions = [attr_name\n for attr_name in dir(object_)\n if str(type(getattr(object_,\n attr_name))) in ("<class 'function'>",\n "<class 'method'>")]\n return functions\n</code></pre>\n<p>Well, it just checks if the string representation of the type of a class' attribute equals <code>"<class 'function'>"</code> or <code>"<class 'method'>"</code> and then includes that attribute in the <code>functions</code> list if that's <code>True</code>.</p>\n<hr />\n<h3>Demo</h3>\n<pre class=\"lang-py prettyprint-override\"><code>class Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def introduce(self):\n print(f'My name is {self.name}')\n\n @staticmethod\n def say_hi():\n print('hi')\n\n @classmethod\n def reproduce(cls, name):\n return cls(name, 0)\n\n\nperson = Person('Rafael', 27)\nprint(get_object_functions(person))\n\n</code></pre>\n<h3>Output</h3>\n<pre class=\"lang-py prettyprint-override\"><code>['__init__', 'introduce', 'reproduce', 'say_hi']\n</code></pre>\n<p><em>For a cleaner version of the code:</em> <a href=\"https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py\" rel=\"nofollow noreferrer\">https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py</a></p>\n"
},
{
"answer_id": 65186594,
"author": "Sergey Bushmanov",
"author_id": 4317058,
"author_profile": "https://Stackoverflow.com/users/4317058",
"pm_score": 4,
"selected": false,
"text": "<p>Suppose we have a Python <code>obj</code>. Then to see all the methods it has, including those surrounded by <code>__</code> (<a href=\"https://stackoverflow.com/a/8690287/4317058\">magic methods</a>):</p>\n<pre><code>print(dir(obj))\n</code></pre>\n<p>To exclude magic builtins one would do:</p>\n<pre><code>[m for m in dir(obj) if not m.startswith('__')]\n</code></pre>\n"
},
{
"answer_id": 67662964,
"author": "Zack Plauché",
"author_id": 10415970,
"author_profile": "https://Stackoverflow.com/users/10415970",
"pm_score": -1,
"selected": false,
"text": "<p>Here's a nice one liner (but will get attributes as well):</p>\n<pre><code>print(*dir(obj), sep='\\n')\n</code></pre>\n"
},
{
"answer_id": 68474764,
"author": "Dharma",
"author_id": 2103732,
"author_profile": "https://Stackoverflow.com/users/2103732",
"pm_score": 0,
"selected": false,
"text": "<p>Most of the time, I want to see the user-defined methods and I don't want to see the built-in attributes that start with '__', if you want that you can use the following code:</p>\n<pre><code>object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name] \n</code></pre>\n<p>For example, for this class:</p>\n<pre><code>class Person: \n def __init__(self, name): \n self.name = name \n def print_name(self):\n print(self.name)\n</code></pre>\n<p>Above code will print: ['print_name']</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3587/"
] | Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | **For many objects**, you can use this code, replacing 'object' with the object you're interested in:
```py
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
```
I discovered it at [diveintopython.net](https://web.archive.org/web/20180901124519/http://www.diveintopython.net/power_of_introspection/index.html) (now archived), that should provide some further details!
**If you get an `AttributeError`, you can use this instead**:
`getattr()` is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.
```py
import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
methodList = []
for method_name in dir(object):
try:
if callable(getattr(object, method_name)):
methodList.append(str(method_name))
except Exception:
methodList.append(str(method_name))
processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
for method in methodList:
try:
print(str(method.ljust(spacing)) + ' ' +
processFunc(str(getattr(object, method).__doc__)[0:90]))
except Exception:
print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo'])
``` |
34,486 | <p>I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?</p>
<pre><code>function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
</code></pre>
| [
{
"answer_id": 34538,
"author": "MattGrommes",
"author_id": 3098,
"author_profile": "https://Stackoverflow.com/users/3098",
"pm_score": 5,
"selected": true,
"text": "<p>I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.</p>\n\n<p>Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax.</p>\n"
},
{
"answer_id": 34539,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": false,
"text": "<p>I would remove this line.</p>\n\n<pre><code>alert(\"Your browser does not support AJAX!\")\n</code></pre>\n\n<p>Shouting at the user in a language he probably doesn't understand is worse than failure. :-)</p>\n"
},
{
"answer_id": 34625,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 1,
"selected": false,
"text": "<p>jQuery is probably one of the lightest popular libraries out there.</p>\n"
},
{
"answer_id": 34714,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 2,
"selected": false,
"text": "<p>I've never been a fan of nested try/catch blocks, so I'd do it something like:</p>\n\n<pre><code>var xmlHttp;\nif (window.XMLHttpRequest) {\n // Firefox, Opera 8.0+, Safari\n xmlHttp=new XMLHttpRequest();\n} else if (window.ActiveXObject) {\n try {\n xmlHttp=new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n xmlHttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n}\n\nif (xmlHttp) {\n // No errors, do whatever you need.\n}\n</code></pre>\n\n<p>I think that'll work. But as has been mentioned before - why reinvent the wheel, use a library. Even better - find out how they do it.</p>\n"
},
{
"answer_id": 39376,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 1,
"selected": false,
"text": "<p>The same thing in prototype:</p>\n\n<pre><code>function loadPage(pagePath, displayElement) {\n new Ajax.Updater(displayElement, pagePath);\n}\n</code></pre>\n\n<p><a href=\"http://prototypejs.org/api/ajax/updater\" rel=\"nofollow noreferrer\">Ajax.Updater in Prototype API</a></p>\n"
},
{
"answer_id": 6761093,
"author": "Sean McMillan",
"author_id": 117587,
"author_profile": "https://Stackoverflow.com/users/117587",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want to see what you are missing, read the jQuery or Prototype source code for their ajax routines. If there are bug numbers in the comments, look those up as well.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
```
function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
``` | I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.
Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax. |
34,488 | <p>Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?</p>
<p>for example</p>
<pre><code> select * from people where name = "Re0sless" limit 1
</code></pre>
<p>if there is only one record with that name? and what about if <code>name</code> was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?</p>
| [
{
"answer_id": 34499,
"author": "Owen Fraser-Green",
"author_id": 3382,
"author_profile": "https://Stackoverflow.com/users/3382",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the LIMIT is something done after the data set is found and the result set is being built up so I wouldn't expect it to make any difference at all. Making name the primary key will have a significant positive effect though as it will result in an index being made for the column.</p>\n"
},
{
"answer_id": 34500,
"author": "John Douthat",
"author_id": 2774,
"author_profile": "https://Stackoverflow.com/users/2774",
"pm_score": 6,
"selected": true,
"text": "<p>If the column has </p>\n\n<p><strong>a unique index: no,</strong> it's no faster</p>\n\n<p><strong>a non-unique index: maybe,</strong> because it will prevent sending any additional rows beyond the first matched, if any exist</p>\n\n<p><strong>no index: sometimes</strong></p>\n\n<ul>\n<li>if 1 or more rows match the query, <strong>yes</strong>, because the full table scan will be halted after the first row is matched.</li>\n<li>if no rows match the query, <strong>no</strong>, because it will need to complete a full table scan</li>\n</ul>\n"
},
{
"answer_id": 34501,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>If \"name\" is unique in the table, then there may still be a (very very minimal) gain in performance by putting the limit constraint on your query. If name is the primary key, there will likely be none.</p>\n"
},
{
"answer_id": 34508,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 2,
"selected": false,
"text": "<p>To answer your questions in order:\n 1) yes, if there is no index on name. The query will end as soon as it finds the first record. take off the limit and it has to do a full table scan every time.\n 2) no. primary/unique keys are guaranteed to be unique. The query should stop running as soon as it finds the row.</p>\n"
},
{
"answer_id": 695083,
"author": "jle",
"author_id": 41713,
"author_profile": "https://Stackoverflow.com/users/41713",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you will notice a performance difference when dealing with the data. One record takes up less space than multiple records. Unless you are dealing with many rows, this would not be much of a difference, but once you run the query, the data has to be displayed back to you, which is costly, or dealt with programmatically. Either way, one record is easier than multiple.</p>\n"
},
{
"answer_id": 695102,
"author": "Andomar",
"author_id": 50552,
"author_profile": "https://Stackoverflow.com/users/50552",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a slightly more complicated query, with one or more joins, the LIMIT clause gives the optimizer extra information. If it expects to match two tables and return all rows, a <a href=\"http://en.wikipedia.org/wiki/Hash_join\" rel=\"nofollow noreferrer\" title=\"hash join\">hash join</a> is typically optimal. A hash join is a type of join optimized for large amounts of matching.</p>\n\n<p>Now if the optimizer knows you've passed LIMIT 1, it knows that it won't be processing large amounts of data. It can revert to a <a href=\"http://en.wikipedia.org/wiki/Nested_loop_join\" rel=\"nofollow noreferrer\" title=\"loop join\">loop join</a>.</p>\n\n<p>Based on the database (and even database version) this can have a huge impact on performance.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] | Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?
for example
```
select * from people where name = "Re0sless" limit 1
```
if there is only one record with that name? and what about if `name` was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal? | If the column has
**a unique index: no,** it's no faster
**a non-unique index: maybe,** because it will prevent sending any additional rows beyond the first matched, if any exist
**no index: sometimes**
* if 1 or more rows match the query, **yes**, because the full table scan will be halted after the first row is matched.
* if no rows match the query, **no**, because it will need to complete a full table scan |
34,490 | <p><a href="http://en.wikipedia.org/wiki/SHA-1" rel="noreferrer">SHA Hash functions</a></p>
| [
{
"answer_id": 34514,
"author": "devstopfix",
"author_id": 3366,
"author_profile": "https://Stackoverflow.com/users/3366",
"pm_score": 10,
"selected": true,
"text": "<pre><code>require 'digest/sha1'\nDigest::SHA1.hexdigest 'foo'\n</code></pre>\n"
},
{
"answer_id": 5269105,
"author": "r4ccoon",
"author_id": 79770,
"author_profile": "https://Stackoverflow.com/users/79770",
"pm_score": -1,
"selected": false,
"text": "<p>Where 'serialize' is some user function defined elsewhere.</p>\n\n<pre><code> def generateKey(data)\n return Digest::SHA1.hexdigest (\"#{serialize(data)}\")\n end\n</code></pre>\n"
},
{
"answer_id": 5968830,
"author": "Thiago Ganzarolli",
"author_id": 287604,
"author_profile": "https://Stackoverflow.com/users/287604",
"pm_score": 3,
"selected": false,
"text": "<p>For a Base64 encoded hash, to validated an Oauth signature, I used</p>\n\n<pre><code>require 'base64'\nrequire 'hmac-sha1'\n\nBase64.encode64((HMAC::SHA1.new('key') << 'base').digest).strip\n</code></pre>\n"
},
{
"answer_id": 19819184,
"author": "Gregory Ostermayr",
"author_id": 833555,
"author_profile": "https://Stackoverflow.com/users/833555",
"pm_score": 3,
"selected": false,
"text": "<p>I created a helper <a href=\"https://rubygems.org/gems/rickshaw\" rel=\"noreferrer\">gem</a> which is a simple wrapper around some sha1 code</p>\n\n<pre><code>require 'rickshaw'\n> Rickshaw::SHA1.hash('LICENSE.txt')\n\n => \"4659d94e7082a65ca39e7b6725094f08a413250a\" \n\n> \"hello world\".to_sha1\n\n => \"2aae6c35c94fcfb415dbe95f408b9ce91ee846ed\" \n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | [SHA Hash functions](http://en.wikipedia.org/wiki/SHA-1) | ```
require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
``` |
34,493 | <p>We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values.</p>
<p>Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook.</p>
<p>(The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.)</p>
<p><strong>Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?</strong></p>
<p>I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable.</p>
<p>Be aware that the .Precedent, .Dependent, etc methods only track direct formulas.</p>
<p>(Also, rewriting the spreadsheets in <em>whatever</em> is not an option for us).</p>
<p>Thanks!</p>
| [
{
"answer_id": 34719,
"author": "sdfx",
"author_id": 3445,
"author_profile": "https://Stackoverflow.com/users/3445",
"pm_score": 4,
"selected": true,
"text": "<p>You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ):</p>\n\n<pre><code>Sub iterateOverWorkbook()\nFor Each i In ThisWorkbook.Worksheets\n Set rRng = i.UsedRange\n For Each j In rRng\n If (Not IsEmpty(j)) Then\n If (j.HasFormula) Then\n If InStr(oCell.Formula, \"INDIRECT\") Then\n j.Value = Replace(j.Formula, \"INDIRECT(D4)\", \"INDIRECT(C4)\")\n End If\n End If\n End If\n Next j\nNext i\nEnd Sub\n</code></pre>\n\n<p>This example substitues every occurrence of \"indirect(D4)\" with \"indirect(C4)\". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks.</p>\n"
},
{
"answer_id": 34750,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 0,
"selected": false,
"text": "<p>You can use something like this in VBA:</p>\n\n<pre><code>Sub ListIndirectRef()\n\nDim rRng As Range\nDim oSh As Worksheet\nDim oCell As Range\n\nFor Each oSh In ThisWorkbook.Worksheets\n Set rRng = oSh.UsedRange\n For Each oCell In rRng\n If InStr(oCell.Formula, \"INDIRECT\") Then\n Debug.Print oCell.Address, oCell.Formula\n End If\n Next\nNext\n\nEnd Sub\n</code></pre>\n\n<p>Instead of Debug.Print you can add code to suit your taste</p>\n"
},
{
"answer_id": 35042,
"author": "sdfx",
"author_id": 3445,
"author_profile": "https://Stackoverflow.com/users/3445",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Unfortunately, the arguments of\n INDIRECT are usually more complex than\n that. Here's an actual formula from\n one of the sheets, not the most\n complex formula we have:</p>\n \n <p><code>=IF(INDIRECT(\"'\"&$B$5&\"'!\"&$O5&\"1\")=\"\",\"\",INDIRECT(\"'\"&$B$5&\"'!\"&$O5&\"1\"))</code></p>\n</blockquote>\n\n<p>hm, you could write a simple parser by ignoring most of the characters and just looking for the relevant parts (in this example: \"A..Z\", \"0..9\" and \"!:\" etc.) but you will run into troubles if the arguments in \"indirect\" are functions.</p>\n\n<p>maybe the safer approach would be to print every occurence of \"indirect\" in a third sheet. you could then add the desired output and write a small search and replace program to write your changes back.</p>\n\n<blockquote>\n <p>If you \"get\" every cell in a huge\n spreadsheet you might end up needing\n monstrous amounts of memory. I am\n still willing to try and take that\n risk.</p>\n</blockquote>\n\n<p>PabloG's method of selecting the used range is the way to go (added it into my original code). The speed is pretty good, especially if you check whether the current cell contains a formula. Obviously, this all depends on the size of your workbook.</p>\n"
},
{
"answer_id": 67261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Q: \"Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?\"</p>\n\n<p>As I read it, you want to look inside the arguments of INDIRECT for references to areas of interest.\nOTTOMH I'd write VBA to use a regular expression parser, or even a simple INSTR to find INDIRECT( read forward to the matching ), then EVALUATE() the string inside to convert it to the actual address, repeat as required for multiple INDIRECT(...) calls and dump the formula and its translation to two columns in a sheet.</p>\n"
},
{
"answer_id": 1429203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what the etiquette of SO is concerning mention of products with which the writer is connected, but OAK, the Operis Analysis Kit, an Excel add-in, can replace the INDIRECT functions by the cell references they resolve to. You can then use Excel's audit tools to determine what dependents each range has. </p>\n\n<p>You would, of course, do this to a temporary copy of the workbook.</p>\n\n<p>More at</p>\n\n<ul>\n<li>http://www.operisanalysiskit.com/oakpruning.htm</li>\n<li>http://www.operisanalysiskit.com/help/2007/index.html?oakconceptpruning.htm</li>\n</ul>\n\n<p>Given the age of this question you may well have found an alternative solution or workaround.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2230/"
] | We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values.
Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook.
(The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.)
**Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?**
I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable.
Be aware that the .Precedent, .Dependent, etc methods only track direct formulas.
(Also, rewriting the spreadsheets in *whatever* is not an option for us).
Thanks! | You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ):
```
Sub iterateOverWorkbook()
For Each i In ThisWorkbook.Worksheets
Set rRng = i.UsedRange
For Each j In rRng
If (Not IsEmpty(j)) Then
If (j.HasFormula) Then
If InStr(oCell.Formula, "INDIRECT") Then
j.Value = Replace(j.Formula, "INDIRECT(D4)", "INDIRECT(C4)")
End If
End If
End If
Next j
Next i
End Sub
```
This example substitues every occurrence of "indirect(D4)" with "indirect(C4)". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks. |
34,505 | <p>The MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx" rel="noreferrer">Object.GetHashCode()</a> describes 3 contradicting rules for how the method should work. </p>
<ol>
<li>If two objects of the same type represent the same value, the hash function must return the same constant value for either object.</li>
<li>For the best performance, a hash function must generate a random distribution for all input.</li>
<li>The hash function must return exactly the same value regardless of any changes that are made to the object.</li>
</ol>
<p>Rules 1 & 3 are contradictory to me.</p>
<p>Does Object.GetHashCode() return a unique number based on the <strong>value</strong> of an object, or the <strong>reference</strong> to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.</p>
| [
{
"answer_id": 34511,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>By default it does it based on the reference to the object, but that means that it's the exact same object, so both would return the same hash. But a hash should be based on the value, like in the case of the string class. \"a\" and \"b\" would have a different hash, but \"a\" and \"a\" would return the same hash.</p>\n"
},
{
"answer_id": 34541,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>Rules 1 & 3 are contradictory to me.</p>\n</blockquote>\n\n<p>To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.</p>\n\n<p>To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.</p>\n\n<p>Consider the following example:</p>\n\n<pre><code>struct Person {\n public readonly string FirstName;\n public readonly string Name;\n public readonly DateTime Birthday;\n\n public int ShoeSize;\n}\n</code></pre>\n\n<p>People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:</p>\n\n<pre><code>public int GetHashCode() {\n return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();\n}\n</code></pre>\n"
},
{
"answer_id": 34566,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure what MSDN documentation you are referring to. Looking at the current documentation on Object.GetHashCode (<a href=\"http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx</a>) provides the following \"rules\":</p>\n\n<ul>\n<li><p>If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values. </p></li>\n<li><p>The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again. </p></li>\n<li><p>For the best performance, a hash function must generate a random distribution for all input. </p></li>\n</ul>\n\n<p>If you are referring to the second bullet point, the key phrases here are \"as long as there is no modification to the object state\" and \"true only for the current execution of an application\". </p>\n\n<p>Also from the documentation, </p>\n\n<blockquote>\n <p>A hash function is used to quickly generate a number (hash code) that corresponds to the <strong>value</strong> of an object. Hash functions are usually specific to each Type and must use at least one of the <strong>instance</strong> fields as input. [<em>Emphasis added is mine.</em>]</p>\n</blockquote>\n\n<p>As for the actual implementation, it clearly states that derived classes can defer to the Object.GetHashCode implementation <strong>if and only if</strong> that derived class defines value equality to be reference equality and the type is not a value type. In other words, the default implementation of Object.GetHashCode is going to be based on reference equality since there are no real instance fields to use and, therefore, does not guarantee unique return values for different objects. Otherwise, your implementation should be specific to your type and should use at least one of your instance fields. As an example, the implementation of String.GetHashCode returns identical hash codes for identical string values, so two String objects return the same hash code if they represent the same string value, and uses all the characters in the string to generate that hash value.</p>\n"
},
{
"answer_id": 34573,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>Rules 1 & 3 aren't really a contradiction.</p>\n\n<p>For a reference type the hash code is derived from a reference to the object - change an object's property and the reference is the same.</p>\n\n<p>For value types the hash code is derived from the value, change a property of a value type and you get a completely new instance of the value type.</p>\n"
},
{
"answer_id": 337351,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 0,
"selected": false,
"text": "<p>I can't know for sure how Object.GetHashCode is implemented in <em>real</em> .NET Framework, but in Rotor it uses SyncBlock index for the object as hashcode. There are some blog posts about it on the web, however most of them are from 2005. </p>\n"
},
{
"answer_id": 32736203,
"author": "thewhiteambit",
"author_id": 2042691,
"author_profile": "https://Stackoverflow.com/users/2042691",
"pm_score": 1,
"selected": false,
"text": "<p>A very good explanation on how to handle <code>GetHashCode</code> (beyond Microsoft rules) is given in Eric Lipperts (co. Designer of C#) Blog with the article \"<a href=\"http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/\" rel=\"nofollow\">Guidelines and rules for GetHashCode</a>\". It is not good practice to add hyperlinks here (since they can get invalid) but this one is worth it, and provided the information above one will probably still find it in case the hyperlink is lost.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | The MSDN documentation on [Object.GetHashCode()](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) describes 3 contradicting rules for how the method should work.
1. If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
2. For the best performance, a hash function must generate a random distribution for all input.
3. The hash function must return exactly the same value regardless of any changes that are made to the object.
Rules 1 & 3 are contradictory to me.
Does Object.GetHashCode() return a unique number based on the **value** of an object, or the **reference** to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows. | >
> Rules 1 & 3 are contradictory to me.
>
>
>
To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.
To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.
Consider the following example:
```
struct Person {
public readonly string FirstName;
public readonly string Name;
public readonly DateTime Birthday;
public int ShoeSize;
}
```
People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:
```
public int GetHashCode() {
return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();
}
``` |
34,506 | <p>Is there anyway to have a sort of virtual static member in C++?</p>
<p>For example:</p>
<pre><code>class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
</code></pre>
<p>I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?</p>
<pre><code>class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
</code></pre>
<p>This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes.</p>
<p>Any idea?</p>
| [
{
"answer_id": 34591,
"author": "Hershi",
"author_id": 1596,
"author_profile": "https://Stackoverflow.com/users/1596",
"pm_score": 2,
"selected": false,
"text": "<p>It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class.</p>\n\n<p>If you insist on having the \"shared\" members implemented as static members of the derived class, you might be able to auto-generate the code of the derived classes. XSLT is a great tool for auto-generating simple classes.</p>\n\n<p>In general, the example doesn't show a need for \"virtual static\" members, because for purposes like these you don't actually need inheritance - instead you should use the base class and have it accept the appropriate values in the constructor - maybe creating a single instance of the arguments for each \"sub-type\" and passing a pointer to it to avoid duplication of the shared data. Another similar approach is to use templates and pass as the template argument a class that provides all the relevant values (this is commonly referred to as the \"Policy\" pattern).</p>\n\n<p>To conclude - for the purpose of the original example, there is no need for such \"virtual static\" members. If you still think they are needed for the code you are writing, please try to elaborate and add more context.</p>\n\n<p>Example of what I described above:</p>\n\n<pre><code>class BaseClass {\n public:\n BaseClass(const Descriptor& desc) : _desc(desc) {}\n string GetName() const { return _desc.name; }\n int GetId() const { return _desc.Id; }\n X GetX() connst { return _desc.X; }\n virtual void UseClass() = 0;\n private:\n const Descriptor _desc;\n};\n\n\nclass DerivedClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(Descriptor(\"abc\", 1,...)) {}\n virtual void UseClass() { /* do something */ }\n};\n\nclass DerDerClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(\"Wowzer\", 843,...) {}\n virtual void UseClass() { /* do something */ }\n};\n</code></pre>\n\n<p>I'd like to elaborate on this solution, and maybe give a solution to the de-initialization problem:</p>\n\n<p>With a small change, you can implement the design described above without necessarily create a new instance of the \"descriptor\" for each instance of a derived class.</p>\n\n<p>You can create a singleton object, DescriptorMap, that will hold the single instance of each descriptor, and use it when constructing the derived objects like so:</p>\n\n<pre><code>enum InstanceType {\n Yellow,\n Big,\n BananaHammoc\n}\n\nclass DescriptorsMap{\n public:\n static Descriptor* GetDescriptor(InstanceType type) {\n if ( _instance.Get() == null) {\n _instance.reset(new DescriptorsMap());\n }\n return _instance.Get()-> _descriptors[type];\n }\n private:\n DescriptorsMap() {\n descriptors[Yellow] = new Descriptor(\"Yellow\", 42, ...);\n descriptors[Big] = new Descriptor(\"InJapan\", 17, ...)\n ...\n }\n\n ~DescriptorsMap() {\n /*Delete all the descriptors from the map*/\n }\n\n static autoptr<DescriptorsMap> _instance;\n map<InstanceType, Descriptor*> _descriptors;\n}\n</code></pre>\n\n<p>Now we can do this:</p>\n\n<pre><code>class DerivedClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}\n virtual void UseClass() { /* do something */ }\n};\n\nclass DerDerClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}\n virtual void UseClass() { /* do something */ }\n};\n</code></pre>\n\n<p>At the end of execution, when the C runtime performs uninitializations, it also calls the destructor of static objects, including our autoptr, which in deletes our instance of the DescriptorsMap.</p>\n\n<p>So now we have a single instance of each descriptor that is also being deleted at the end of execution.</p>\n\n<p>Note that if the only purpose of the derived class is to supply the relevant \"descriptor\" data (i.e. as opposed to implementing virtual functions) then you should make do with making the base class non-abstract, and just creating an instance with the appropriate descriptor each time.</p>\n"
},
{
"answer_id": 34701,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 1,
"selected": false,
"text": "<p>@Hershi: the problem with that approach is that each instance of each derived class has a copy of the data, which may be expensive in some way.</p>\n<p>Perhaps you could try something like this (I'm spit-balling without a compiling example, but the idea should be clear).</p>\n<pre><code>\n#include <iostream>\n#include <string>\nusing namespace std;\n\nstruct DerivedData\n{\n DerivedData(const string & word, const int number) :\n my_word(word), my_number(number) {}\n const string my_word;\n const int my_number;\n};\n\nclass Base {\npublic:\n Base() : m_data(0) {}\n string getWord() const { return m_data->my_word; }\n int getNumber() const { return m_data->my_number; }\nprotected:\n DerivedData * m_data;\n};\n\n\nclass Derived : public Base {\npublic:\n Derived() : Base() {\n if(Derived::s_data == 0) {\n Derived::s_data = new DerivedData(\"abc\", 1);\n }\n m_data = s_data;\n }\nprivate:\n static DerivedData * s_data;\n};\n\n\nDerivedData * Derived::s_data = 0; \n\nint main()\n{\n Base * p_b = new Derived();\n cout getWord() << endl;\n}\n\n</code></pre>\n<p>Regarding the follow-up question on deleting the static object: the only solution that comes to mind is to use a smart pointer, something like the <a href=\"https://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">Boost shared pointer</a>.</p>\n"
},
{
"answer_id": 34857,
"author": "Misha M",
"author_id": 3467,
"author_profile": "https://Stackoverflow.com/users/3467",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Hershi's suggestion to use a template as the \"base class\". From what you're describing, it sounds more like a use for templates rather then subclassing.</p>\n\n<p>You could create a template as follows ( have not tried to compile this ):</p>\n\n<pre>\n<code>\ntemplate <typename T>\nclass Object\n{\npublic:\n\n Object( const T& newObject ) : yourObject(newObject) {} ;\n T GetObject() const { return yourObject } ;\n void SetObject( const T& newObject ) { yourObject = newObject } ;\n\nprotected:\n\n const T yourObject ;\n} ;\n\nclass SomeClassOne\n{\npublic:\n\n SomeClassOne( const std::vector& someData )\n {\n yourData.SetObject( someData ) ;\n }\n\nprivate:\n\n Object<std::vector<int>> yourData ;\n} ;\n</code>\n</pre>\n\n<p>This will let you use the template class methods to modify the data as needed from within your custom classes that use the data and share the various aspects of the template class.</p>\n\n<p>If you're intent on using inheritance, then you might have to resort to the \"joys\" of using a void* pointer in your BaseClass and dealing with casting, etc.</p>\n\n<p>However, based on your explanation, it seems like you need templates and not inheritance.</p>\n"
},
{
"answer_id": 35201,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 4,
"selected": true,
"text": "<p>Here is one solution: </p>\n\n<pre><code>struct BaseData\n{\n const string my_word;\n const int my_number;\n};\n\nclass Base\n{\npublic:\n Base(const BaseData* apBaseData)\n {\n mpBaseData = apBaseData;\n }\n const string getMyWord()\n {\n return mpBaseData->my_word;\n }\n int getMyNumber()\n {\n return mpBaseData->my_number;\n }\nprivate:\n const BaseData* mpBaseData;\n};\n\nclass Derived : public Base\n{\npublic:\n Derived() : Base(&sBaseData)\n {\n }\nprivate:\n static BaseData sBaseData;\n}\n\nBaseData Derived::BaseData = { \"Foo\", 42 };\n</code></pre>\n"
},
{
"answer_id": 895651,
"author": "no-op",
"author_id": 110250,
"author_profile": "https://Stackoverflow.com/users/110250",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds as if you're trying to avoid having to duplicate the code at the leaf classes, so why not just derive an intermediate base class from the base class. this intermediate class can hold the static data, and have all your leaf classes derive from the intermediate base class. This presupposes that one static piece of data held over all the derived classes is desired, which seems so from your example.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3373/"
] | Is there anyway to have a sort of virtual static member in C++?
For example:
```
class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
```
I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?
```
class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
```
This solution does not satify me because I need reimplement the member \_name and its accessor GetName() in every class. In my case I have several members that follows \_name behavior and tenths of derived classes.
Any idea? | Here is one solution:
```
struct BaseData
{
const string my_word;
const int my_number;
};
class Base
{
public:
Base(const BaseData* apBaseData)
{
mpBaseData = apBaseData;
}
const string getMyWord()
{
return mpBaseData->my_word;
}
int getMyNumber()
{
return mpBaseData->my_number;
}
private:
const BaseData* mpBaseData;
};
class Derived : public Base
{
public:
Derived() : Base(&sBaseData)
{
}
private:
static BaseData sBaseData;
}
BaseData Derived::BaseData = { "Foo", 42 };
``` |
34,509 | <p>We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.</p>
<p>Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.</p>
<p>While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.</p>
<p>For instance, sorting by a string record id gives something like:</p>
<pre><code>rec1
rec10
rec14
rec2
rec20
rec3
rec4
</code></pre>
<p>...and so on.</p>
<p>I want this to take account of the number, so:</p>
<pre><code>rec1
rec2
rec3
rec4
rec10
rec14
rec20
</code></pre>
<p>I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".</p>
<p>I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.</p>
<p>Does anyone know a way to quickly apply a natural sort in Sql server?</p>
<hr>
<p>We're using:</p>
<pre><code>ROW_NUMBER() over (order by {field name} asc)
</code></pre>
<p>And then we're paging by that.</p>
<p>We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.</p>
<hr>
<p>We have valid user input that follows different formats for different clients.</p>
<p>One might go rec1, rec2, rec3, ... rec100, rec101</p>
<p>While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301</p>
<p>When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.</p>
<p>These formats vary a lot, but are often mixtures of letters and numbers.</p>
<p>Sorting these in C# is easy - just break it up into <code>{ "grp", 20, "rec", 301 }</code> and then compare sequence values in turn.</p>
<p>However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.</p>
<p>SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.</p>
<p>@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.</p>
| [
{
"answer_id": 35382,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": -1,
"selected": false,
"text": "<p>I still don't understand (probably because of my poor English).</p>\n\n<p>You could try:</p>\n\n<pre><code>ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC)\n</code></pre>\n\n<p>But it won't work for millions of records.</p>\n\n<p>That why I suggested to use trigger which <em>fills</em> <em>separate</em> column with <em>human value</em>.</p>\n\n<p>Moreover:</p>\n\n<ul>\n<li>built-in T-SQL functions are really\nslow and Microsoft suggest to use\n.NET functions instead.</li>\n<li><em>human value</em> is constant so there is no point calculating it each time\nwhen query runs.</li>\n</ul>\n"
},
{
"answer_id": 77373,
"author": "Chris Wuestefeld",
"author_id": 10082,
"author_profile": "https://Stackoverflow.com/users/10082",
"pm_score": 1,
"selected": false,
"text": "<p>If you're having trouble loading the data from the DB to sort in C#, then I'm sure you'll be disappointed with any approach at doing it programmatically in the DB. When the server is going to sort, it's got to calculate the \"perceived\" order just as you would have -- every time. </p>\n\n<p>I'd suggest that you add an additional column to store the preprocessed sortable string, using some C# method, when the data is first inserted. You might try to convert the numerics into fixed-width ranges, for example, so \"xyz1\" would turn into \"xyz00000001\". Then you could use normal SQL Server sorting.</p>\n\n<p>At the risk of tooting my own horn, I wrote a CodeProject article implementing the problem as posed in the CodingHorror article. Feel free to <a href=\"http://www.codeproject.com/KB/dotnet/SortingStringsForHumans.aspx\" rel=\"nofollow noreferrer\">steal from my code</a>.</p>\n"
},
{
"answer_id": 523012,
"author": "JazzHands",
"author_id": 63173,
"author_profile": "https://Stackoverflow.com/users/63173",
"pm_score": 3,
"selected": false,
"text": "<p>I know this is a bit old at this point, but in my search for a better solution, I came across this question. I'm currently using a function to order by. It works fine for my purpose of sorting records which are named with mixed alpha numeric ('item 1', 'item 10', 'item 2', etc) </p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnMixSort]\n(\n @ColValue NVARCHAR(255)\n)\nRETURNS NVARCHAR(1000)\nAS\n\nBEGIN\n DECLARE @p1 NVARCHAR(255),\n @p2 NVARCHAR(255),\n @p3 NVARCHAR(255),\n @p4 NVARCHAR(255),\n @Index TINYINT\n\n IF @ColValue LIKE '[a-z]%'\n SELECT @Index = PATINDEX('%[0-9]%', @ColValue),\n @p1 = LEFT(CASE WHEN @Index = 0 THEN @ColValue ELSE LEFT(@ColValue, @Index - 1) END + REPLICATE(' ', 255), 255),\n @ColValue = CASE WHEN @Index = 0 THEN '' ELSE SUBSTRING(@ColValue, @Index, 255) END\n ELSE\n SELECT @p1 = REPLICATE(' ', 255)\n\n SELECT @Index = PATINDEX('%[^0-9]%', @ColValue)\n\n IF @Index = 0\n SELECT @p2 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255),\n @ColValue = ''\n ELSE\n SELECT @p2 = RIGHT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),\n @ColValue = SUBSTRING(@ColValue, @Index, 255)\n\n SELECT @Index = PATINDEX('%[0-9,a-z]%', @ColValue)\n\n IF @Index = 0\n SELECT @p3 = REPLICATE(' ', 255)\n ELSE\n SELECT @p3 = LEFT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),\n @ColValue = SUBSTRING(@ColValue, @Index, 255)\n\n IF PATINDEX('%[^0-9]%', @ColValue) = 0\n SELECT @p4 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255)\n ELSE\n SELECT @p4 = LEFT(@ColValue + REPLICATE(' ', 255), 255)\n\n RETURN @p1 + @p2 + @p3 + @p4\n\nEND\n</code></pre>\n\n<p>Then call</p>\n\n<pre><code>select item_name from my_table order by fnMixSort(item_name)\n</code></pre>\n\n<p>It easily triples the processing time for a simple data read, so it may not be the perfect solution.</p>\n"
},
{
"answer_id": 579005,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>order by LEN(value), value\n</code></pre>\n\n<p>Not perfect, but works well in a lot of cases.</p>\n"
},
{
"answer_id": 750888,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following code to resolve the problem:</p>\n\n<pre><code>Select *, \n substring(Cote,1,len(Cote) - Len(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1)))alpha,\n CAST(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1) AS INT)intv \nFROM Documents \n left outer join Sites ON Sites.IDSite = Documents.IDSite \nOrder BY alpha, intv\n</code></pre>\n\n<p>regards,\[email protected]</p>\n"
},
{
"answer_id": 751040,
"author": "M.Turrini",
"author_id": 83623,
"author_profile": "https://Stackoverflow.com/users/83623",
"pm_score": 0,
"selected": false,
"text": "<p>I've just read a article somewhere about such a topic. The key point is: you only need the integer value to sort data, while the 'rec' string belongs to the UI. You could split the information in two fields, say alpha and num, sort by alpha and num (separately) and then showing a string composed by alpha + num. You could use a computed column to compose the string, or a view.\nHope it helps</p>\n"
},
{
"answer_id": 2060952,
"author": "D'Arcy Rittich",
"author_id": 39430,
"author_profile": "https://Stackoverflow.com/users/39430",
"pm_score": 6,
"selected": true,
"text": "<p>Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was <em>way</em> too slow.</p>\n\n<p>Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:</p>\n\n<ul>\n<li>will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)</li>\n<li>properly sorts decimals, so 123.333 comes before 123.45</li>\n<li>because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code</li>\n<li>supports sorting a string with an arbitrary number of numbers within it</li>\n<li>will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)</li>\n</ul>\n\n<p>The code is here:</p>\n\n<pre><code>using System;\nusing System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n\npublic class UDF\n{\n [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]\n public static SqlString Naturalize(string val)\n {\n if (String.IsNullOrEmpty(val))\n return val;\n\n while(val.Contains(\" \"))\n val = val.Replace(\" \", \" \");\n\n const int maxLength = 1000;\n const int padLength = 25;\n\n bool inNumber = false;\n bool isDecimal = false;\n int numStart = 0;\n int numLength = 0;\n int length = val.Length < maxLength ? val.Length : maxLength;\n\n //TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength\n var sb = new StringBuilder();\n for (var i = 0; i < length; i++)\n {\n int charCode = (int)val[i];\n if (charCode >= 48 && charCode <= 57)\n {\n if (!inNumber)\n {\n numStart = i;\n numLength = 1;\n inNumber = true;\n continue;\n }\n numLength++;\n continue;\n }\n if (inNumber)\n {\n sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));\n inNumber = false;\n }\n isDecimal = (charCode == 46);\n sb.Append(val[i]);\n }\n if (inNumber)\n sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));\n\n var ret = sb.ToString();\n if (ret.Length > maxLength)\n return ret.Substring(0, maxLength);\n\n return ret;\n }\n\n static string PadNumber(string num, bool isDecimal, int padLength)\n {\n return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');\n }\n}\n</code></pre>\n\n<p>To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:</p>\n\n<pre><code>CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here\ngo\nCREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) \nEXTERNAL NAME SqlServerClr.UDF.Naturalize\ngo\n</code></pre>\n\n<p>Then, you can use it like so:</p>\n\n<pre><code>select *\nfrom MyTable\norder by dbo.Naturalize(MyTextField)\n</code></pre>\n\n<p><strong>Note</strong>: If you get an error in SQL Server along the lines of <em>Execution of user code in the .NET Framework is disabled. Enable \"clr enabled\" configuration option.</em>, follow the instructions <a href=\"http://www.novicksoftware.com/TipsAndTricks/tip-sql-server-2005-enable-clr-programming.htm\" rel=\"nofollow noreferrer\">here</a> to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.</p>\n\n<p><strong>Note2</strong>: This code does not properly support internationalization (e.g., assumes the decimal marker is \".\", is not optimized for speed, etc. Suggestions on improving it are welcome!</p>\n\n<p><strong>Edit:</strong> Renamed the function to <em>Naturalize</em> instead of <em>NaturalSort</em>, since it does not do any actual sorting.</p>\n"
},
{
"answer_id": 3887921,
"author": "Seph",
"author_id": 288747,
"author_profile": "https://Stackoverflow.com/users/288747",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is an old question but I just came across it and since it's not got an accepted answer.</p>\n\n<p>I have always used ways similar to this:</p>\n\n<pre><code>SELECT [Column] FROM [Table]\nORDER BY RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))), 1000)\n</code></pre>\n\n<p>The only common times that this has issues is if your column won't cast to a VARCHAR(MAX), or if LEN([Column]) > 1000 (but you can change that 1000 to something else if you want), but you can use this rough idea for what you need.</p>\n\n<p>Also this is much worse performance than normal ORDER BY [Column], but it does give you the result asked for in the OP.</p>\n\n<p>Edit: Just to further clarify, this the above will not work if you have decimal values such as having <code>1</code>, <code>1.15</code> and <code>1.5</code>, (they will sort as <code>{1, 1.5, 1.15}</code>) as that is not what is asked for in the OP, but that can easily be done by:</p>\n\n<pre><code>SELECT [Column] FROM [Table]\nORDER BY REPLACE(RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))) + REPLICATE('0', 100 - CHARINDEX('.', REVERSE(LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX))))), 1)), 1000), '.', '0')\n</code></pre>\n\n<p>Result: <code>{1, 1.15, 1.5}</code></p>\n\n<p>And still all entirely within SQL. This will not sort IP addresses because you're now getting into very specific number combinations as opposed to simple text + number.</p>\n"
},
{
"answer_id": 5587314,
"author": "plalx",
"author_id": 1211528,
"author_profile": "https://Stackoverflow.com/users/1211528",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a solution written for SQL 2000. It can probably be improved for newer SQL versions.</p>\n\n<pre><code>/**\n * Returns a string formatted for natural sorting. This function is very useful when having to sort alpha-numeric strings.\n *\n * @author Alexandre Potvin Latreille (plalx)\n * @param {nvarchar(4000)} string The formatted string.\n * @param {int} numberLength The length each number should have (including padding). This should be the length of the longest number. Defaults to 10.\n * @param {char(50)} sameOrderChars A list of characters that should have the same order. Ex: '.-/'. Defaults to empty string.\n *\n * @return {nvarchar(4000)} A string for natural sorting.\n * Example of use: \n * \n * SELECT Name FROM TableA ORDER BY Name\n * TableA (unordered) TableA (ordered)\n * ------------ ------------\n * ID Name ID Name\n * 1. A1. 1. A1-1. \n * 2. A1-1. 2. A1.\n * 3. R1 --> 3. R1\n * 4. R11 4. R11\n * 5. R2 5. R2\n *\n * \n * As we can see, humans would expect A1., A1-1., R1, R2, R11 but that's not how SQL is sorting it.\n * We can use this function to fix this.\n *\n * SELECT Name FROM TableA ORDER BY dbo.udf_NaturalSortFormat(Name, default, '.-')\n * TableA (unordered) TableA (ordered)\n * ------------ ------------\n * ID Name ID Name\n * 1. A1. 1. A1. \n * 2. A1-1. 2. A1-1.\n * 3. R1 --> 3. R1\n * 4. R11 4. R2\n * 5. R2 5. R11\n */\nALTER FUNCTION [dbo].[udf_NaturalSortFormat](\n @string nvarchar(4000),\n @numberLength int = 10,\n @sameOrderChars char(50) = ''\n)\nRETURNS varchar(4000)\nAS\nBEGIN\n DECLARE @sortString varchar(4000),\n @numStartIndex int,\n @numEndIndex int,\n @padLength int,\n @totalPadLength int,\n @i int,\n @sameOrderCharsLen int;\n\n SELECT \n @totalPadLength = 0,\n @string = RTRIM(LTRIM(@string)),\n @sortString = @string,\n @numStartIndex = PATINDEX('%[0-9]%', @string),\n @numEndIndex = 0,\n @i = 1,\n @sameOrderCharsLen = LEN(@sameOrderChars);\n\n -- Replace all char that have the same order by a space.\n WHILE (@i <= @sameOrderCharsLen)\n BEGIN\n SET @sortString = REPLACE(@sortString, SUBSTRING(@sameOrderChars, @i, 1), ' ');\n SET @i = @i + 1;\n END\n\n -- Pad numbers with zeros.\n WHILE (@numStartIndex <> 0)\n BEGIN\n SET @numStartIndex = @numStartIndex + @numEndIndex;\n SET @numEndIndex = @numStartIndex;\n\n WHILE(PATINDEX('[0-9]', SUBSTRING(@string, @numEndIndex, 1)) = 1)\n BEGIN\n SET @numEndIndex = @numEndIndex + 1;\n END\n\n SET @numEndIndex = @numEndIndex - 1;\n\n SET @padLength = @numberLength - (@numEndIndex + 1 - @numStartIndex);\n\n IF @padLength < 0\n BEGIN\n SET @padLength = 0;\n END\n\n SET @sortString = STUFF(\n @sortString,\n @numStartIndex + @totalPadLength,\n 0,\n REPLICATE('0', @padLength)\n );\n\n SET @totalPadLength = @totalPadLength + @padLength;\n SET @numStartIndex = PATINDEX('%[0-9]%', RIGHT(@string, LEN(@string) - @numEndIndex));\n END\n\n RETURN @sortString;\nEND\n</code></pre>\n"
},
{
"answer_id": 5682368,
"author": "jack.mike.info",
"author_id": 707910,
"author_profile": "https://Stackoverflow.com/users/707910",
"pm_score": 1,
"selected": false,
"text": "<p>Simply you sort by</p>\n\n<pre><code>ORDER BY \ncast (substring(name,(PATINDEX('%[0-9]%',name)),len(name))as int)\n\n ##\n</code></pre>\n"
},
{
"answer_id": 7410173,
"author": "Gut Feeling",
"author_id": 816701,
"author_profile": "https://Stackoverflow.com/users/816701",
"pm_score": 2,
"selected": false,
"text": "<p>For the following <code>varchar</code> data:</p>\n\n<pre><code>BR1\nBR2\nExternal Location\nIR1\nIR2\nIR3\nIR4\nIR5\nIR6\nIR7\nIR8\nIR9\nIR10\nIR11\nIR12\nIR13\nIR14\nIR16\nIR17\nIR15\nVCR\n</code></pre>\n\n<p>This worked best for me:</p>\n\n<pre><code>ORDER BY substring(fieldName, 1, 1), LEN(fieldName)\n</code></pre>\n"
},
{
"answer_id": 13375351,
"author": "Simon",
"author_id": 888392,
"author_profile": "https://Stackoverflow.com/users/888392",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an other solution that I like:\n<a href=\"http://www.dreamchain.com/sql-and-alpha-numeric-sort-order/\" rel=\"nofollow noreferrer\">http://www.dreamchain.com/sql-and-alpha-numeric-sort-order/</a></p>\n<p>It's not Microsoft SQL, but since I ended up here when I was searching for a solution for Postgres, I thought adding this here would help others.</p>\n<p><strong>EDIT: Here is the code, in case the link goes away.</strong></p>\n<pre><code>CREATE or REPLACE FUNCTION pad_numbers(text) RETURNS text AS $$\n SELECT regexp_replace(regexp_replace(regexp_replace(regexp_replace(($1 collate "C"),\n E'(^|\\\\D)(\\\\d{1,3}($|\\\\D))', E'\\\\1000\\\\2', 'g'),\n E'(^|\\\\D)(\\\\d{4,6}($|\\\\D))', E'\\\\1000\\\\2', 'g'),\n E'(^|\\\\D)(\\\\d{7}($|\\\\D))', E'\\\\100\\\\2', 'g'),\n E'(^|\\\\D)(\\\\d{8}($|\\\\D))', E'\\\\10\\\\2', 'g');\n$$ LANGUAGE SQL;\n</code></pre>\n<p>"C" is the default collation in postgresql; you may specify any collation you desire, or remove the collation statement if you can be certain your table columns will never have a nondeterministic collation assigned.</p>\n<p>usage:</p>\n<pre><code>SELECT * FROM wtf w \n WHERE TRUE\n ORDER BY pad_numbers(w.my_alphanumeric_field)\n</code></pre>\n"
},
{
"answer_id": 19471828,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/2060952/33080\">RedFilter's answer</a> is great for reasonably sized datasets where indexing is not critical, however if you want an index, several tweaks are required.</p>\n\n<p>First, mark the function as not doing any data access and being deterministic and precise:</p>\n\n<pre><code>[SqlFunction(DataAccess = DataAccessKind.None,\n SystemDataAccess = SystemDataAccessKind.None,\n IsDeterministic = true, IsPrecise = true)]\n</code></pre>\n\n<p>Next, MSSQL has a 900 byte limit on the index key size, so if the naturalized value is the only value in the index, it must be at most 450 characters long. If the index includes multiple columns, the return value must be even smaller. Two changes:</p>\n\n<pre><code>CREATE FUNCTION Naturalize(@str AS nvarchar(max)) RETURNS nvarchar(450)\n EXTERNAL NAME ClrExtensions.Util.Naturalize\n</code></pre>\n\n<p>and in the C# code:</p>\n\n<pre><code>const int maxLength = 450;\n</code></pre>\n\n<p>Finally, you will need to add a computed column to your table, and it must be persisted (because MSSQL cannot prove that <code>Naturalize</code> is deterministic and precise), which means the naturalized value is actually stored in the table but is still maintained automatically:</p>\n\n<pre><code>ALTER TABLE YourTable ADD nameNaturalized AS dbo.Naturalize(name) PERSISTED\n</code></pre>\n\n<p>You can now create the index!</p>\n\n<pre><code>CREATE INDEX idx_YourTable_n ON YourTable (nameNaturalized)\n</code></pre>\n\n<p>I've also made a couple of changes to RedFilter's code: using chars for clarity, incorporating duplicate space removal into the main loop, exiting once the result is longer than the limit, setting maximum length without substring etc. Here's the result:</p>\n\n<pre><code>using System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n\npublic static class Util\n{\n [SqlFunction(DataAccess = DataAccessKind.None, SystemDataAccess = SystemDataAccessKind.None, IsDeterministic = true, IsPrecise = true)]\n public static SqlString Naturalize(string str)\n {\n if (string.IsNullOrEmpty(str))\n return str;\n\n const int maxLength = 450;\n const int padLength = 15;\n\n bool isDecimal = false;\n bool wasSpace = false;\n int numStart = 0;\n int numLength = 0;\n\n var sb = new StringBuilder();\n for (var i = 0; i < str.Length; i++)\n {\n char c = str[i];\n if (c >= '0' && c <= '9')\n {\n if (numLength == 0)\n numStart = i;\n numLength++;\n }\n else\n {\n if (numLength > 0)\n {\n sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));\n numLength = 0;\n }\n if (c != ' ' || !wasSpace)\n sb.Append(c);\n isDecimal = c == '.';\n if (sb.Length > maxLength)\n break;\n }\n wasSpace = c == ' ';\n }\n if (numLength > 0)\n sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));\n\n if (sb.Length > maxLength)\n sb.Length = maxLength;\n return sb.ToString();\n }\n\n private static string pad(string num, bool isDecimal, int padLength)\n {\n return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71357605,
"author": "ShrapNull",
"author_id": 1652234,
"author_profile": "https://Stackoverflow.com/users/1652234",
"pm_score": 0,
"selected": false,
"text": "<p>I'm fashionably late to the party as usual. Nevertheless, here is my attempt at an answer that seems to work well (I would say that). It assumes text with digits at the end, like in the original example data.</p>\n<p>First a function that won't end up winning a "pretty SQL" competition anytime soon.</p>\n<pre><code>CREATE FUNCTION udfAlphaNumericSortHelper (\n@string varchar(max)\n)\nRETURNS @results TABLE (\n txt varchar(max),\n num float\n)\nAS\nBEGIN\n\n DECLARE @txt varchar(max) = @string\n DECLARE @numStr varchar(max) = ''\n DECLARE @num float = 0\n DECLARE @lastChar varchar(1) = ''\n\n set @lastChar = RIGHT(@txt, 1)\n WHILE @lastChar <> '' and @lastChar is not null\n BEGIN \n IF ISNUMERIC(@lastChar) = 1\n BEGIN \n set @numStr = @lastChar + @numStr\n set @txt = Substring(@txt, 0, len(@txt))\n set @lastChar = RIGHT(@txt, 1)\n END\n ELSE\n BEGIN \n set @lastChar = null\n END\n END\n SET @num = CAST(@numStr as float)\n\n INSERT INTO @results select @txt, @num\n RETURN;\nEND\n</code></pre>\n<p>Then call it like below:</p>\n<pre><code>declare @str nvarchar(250) = 'sox,fox,jen1,Jen0,jen15,jen02,jen0004,fox00,rec1,rec10,jen3,rec14,rec2,rec20,rec3,rec4,zip1,zip1.32,zip1.33,zip1.3,TT0001,TT01,TT002'\n\n\nSELECT tbl.value --, sorter.txt, sorter.num\nFROM STRING_SPLIT(@str, ',') as tbl\nCROSS APPLY dbo.udfAlphaNumericSortHelper(value) as sorter\nORDER BY sorter.txt, sorter.num, len(tbl.value)\n</code></pre>\n<p>With results:\nfox\nfox00\nJen0\njen1\njen02\njen3\njen0004\njen15\nrec1\nrec2\nrec3\nrec4\nrec10\nrec14\nrec20\nsox\nTT01\nTT0001\nTT002\nzip1\nzip1.3\nzip1.32\nzip1.33</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.
Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.
While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.
For instance, sorting by a string record id gives something like:
```
rec1
rec10
rec14
rec2
rec20
rec3
rec4
```
...and so on.
I want this to take account of the number, so:
```
rec1
rec2
rec3
rec4
rec10
rec14
rec20
```
I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".
I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.
Does anyone know a way to quickly apply a natural sort in Sql server?
---
We're using:
```
ROW_NUMBER() over (order by {field name} asc)
```
And then we're paging by that.
We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.
---
We have valid user input that follows different formats for different clients.
One might go rec1, rec2, rec3, ... rec100, rec101
While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301
When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.
These formats vary a lot, but are often mixtures of letters and numbers.
Sorting these in C# is easy - just break it up into `{ "grp", 20, "rec", 301 }` and then compare sequence values in turn.
However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.
SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.
@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values. | Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was *way* too slow.
Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:
* will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)
* properly sorts decimals, so 123.333 comes before 123.45
* because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code
* supports sorting a string with an arbitrary number of numbers within it
* will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)
The code is here:
```
using System;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
public class UDF
{
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]
public static SqlString Naturalize(string val)
{
if (String.IsNullOrEmpty(val))
return val;
while(val.Contains(" "))
val = val.Replace(" ", " ");
const int maxLength = 1000;
const int padLength = 25;
bool inNumber = false;
bool isDecimal = false;
int numStart = 0;
int numLength = 0;
int length = val.Length < maxLength ? val.Length : maxLength;
//TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength
var sb = new StringBuilder();
for (var i = 0; i < length; i++)
{
int charCode = (int)val[i];
if (charCode >= 48 && charCode <= 57)
{
if (!inNumber)
{
numStart = i;
numLength = 1;
inNumber = true;
continue;
}
numLength++;
continue;
}
if (inNumber)
{
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
inNumber = false;
}
isDecimal = (charCode == 46);
sb.Append(val[i]);
}
if (inNumber)
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
var ret = sb.ToString();
if (ret.Length > maxLength)
return ret.Substring(0, maxLength);
return ret;
}
static string PadNumber(string num, bool isDecimal, int padLength)
{
return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');
}
}
```
To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:
```
CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here
go
CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000)
EXTERNAL NAME SqlServerClr.UDF.Naturalize
go
```
Then, you can use it like so:
```
select *
from MyTable
order by dbo.Naturalize(MyTextField)
```
**Note**: If you get an error in SQL Server along the lines of *Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.*, follow the instructions [here](http://www.novicksoftware.com/TipsAndTricks/tip-sql-server-2005-enable-clr-programming.htm) to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.
**Note2**: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome!
**Edit:** Renamed the function to *Naturalize* instead of *NaturalSort*, since it does not do any actual sorting. |
34,510 | <p>When writing multithreaded applications, one of the most common problems experienced is race conditions.</p>
<p>My questions to the community are:</p>
<ul>
<li>What is the race condition?</li>
<li>How do you detect them?</li>
<li>How do you handle them?</li>
<li>Finally, how do you prevent them from occurring?</li>
</ul>
| [
{
"answer_id": 34537,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 5,
"selected": false,
"text": "<p>A race condition is a kind of bug, that happens only with certain temporal conditions.</p>\n\n<p>Example:\nImagine you have two threads, A and B.</p>\n\n<p>In Thread A:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if( object.a != 0 )\n object.avg = total / object.a\n</code></pre>\n\n<p>In Thread B:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>object.a = 0\n</code></pre>\n\n<p>If thread A is preempted just after having check that object.a is not null, B will do <code>a = 0</code>, and when thread A will gain the processor, it will do a \"divide by zero\". </p>\n\n<p>This bug only happen when thread A is preempted just after the if statement, it's very rare, but it can happen.</p>\n"
},
{
"answer_id": 34550,
"author": "Lehane",
"author_id": 142,
"author_profile": "https://Stackoverflow.com/users/142",
"pm_score": 12,
"selected": true,
"text": "<p>A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are \"racing\" to access/change the data. </p>\n\n<p>Problems often occur when one thread does a \"check-then-act\" (e.g. \"check\" if the value is X, then \"act\" to do something that depends on the value being X) and another thread does something to the value in between the \"check\" and the \"act\". E.g:</p>\n\n<pre><code>if (x == 5) // The \"Check\"\n{\n y = x * 2; // The \"Act\"\n\n // If another thread changed x in between \"if (x == 5)\" and \"y = x * 2\" above,\n // y will not be equal to 10.\n}\n</code></pre>\n\n<p>The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.</p>\n\n<p>In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:</p>\n\n<pre><code>// Obtain lock for x\nif (x == 5)\n{\n y = x * 2; // Now, nothing can change x until the lock is released. \n // Therefore y = 10\n}\n// release lock for x\n</code></pre>\n"
},
{
"answer_id": 34562,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 5,
"selected": false,
"text": "<p>A race condition is a situation on concurrent programming where two concurrent threads or processes compete for a resource and the resulting final state depends on who gets the resource first.</p>\n"
},
{
"answer_id": 34578,
"author": "tsellon",
"author_id": 3575,
"author_profile": "https://Stackoverflow.com/users/3575",
"pm_score": 4,
"selected": false,
"text": "<p>Race conditions occur in multi-threaded applications or multi-process systems. A race condition, at its most basic, is anything that makes the assumption that two things not in the same thread or process will happen in a particular order, without taking steps to ensure that they do. This happens commonly when two threads are passing messages by setting and checking member variables of a class both can access. There's almost always a race condition when one thread calls sleep to give another thread time to finish a task (unless that sleep is in a loop, with some checking mechanism).</p>\n\n<p>Tools for preventing race conditions are dependent on the language and OS, but some comon ones are mutexes, critical sections, and signals. Mutexes are good when you want to make sure you're the only one doing something. Signals are good when you want to make sure someone else has finished doing something. Minimizing shared resources can also help prevent unexpected behaviors</p>\n\n<p>Detecting race conditions can be difficult, but there are a couple signs. Code which relies heavily on sleeps is prone to race conditions, so first check for calls to sleep in the affected code. Adding particularly long sleeps can also be used for debugging to try and force a particular order of events. This can be useful for reproducing the behavior, seeing if you can make it disappear by changing the timing of things, and for testing solutions put in place. The sleeps should be removed after debugging.</p>\n\n<p>The signature sign that one has a race condition though, is if there's an issue that only occurs intermittently on some machines. Common bugs would be crashes and deadlocks. With logging, you should be able to find the affected area and work back from there.</p>\n"
},
{
"answer_id": 34621,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": false,
"text": "<p>A sort-of-canonical definition is \"<em>when two threads access the same location in memory at the same time, and at least one of the accesses is a write</em>.\" In the situation the \"reader\" thread may get the old value or the new value, depending on which thread \"wins the race.\" This is not always a bug—in fact, some really hairy low-level algorithms do this on purpose—but it should generally be avoided. @Steve Gury give's a good example of when it might be a problem.</p>\n"
},
{
"answer_id": 34745,
"author": "privatehuff",
"author_id": 2570347,
"author_profile": "https://Stackoverflow.com/users/2570347",
"pm_score": 8,
"selected": false,
"text": "<p>A \"race condition\" exists when multithreaded (or otherwise parallel) code that would access a shared resource could do so in such a way as to cause unexpected results.</p>\n\n<p>Take this example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>for ( int i = 0; i < 10000000; i++ )\n{\n x = x + 1; \n}\n</code></pre>\n\n<p>If you had 5 threads executing this code at once, the value of x WOULD NOT end up being 50,000,000. It would in fact vary with each run.</p>\n\n<p>This is because, in order for each thread to increment the value of x, they have to do the following: (simplified, obviously)</p>\n\n<pre>\nRetrieve the value of x\nAdd 1 to this value\nStore this value to x\n</pre>\n\n<p>Any thread can be at any step in this process at any time, and they can step on each other when a shared resource is involved. The state of x can be changed by another thread during the time between x is being read and when it is written back.</p>\n\n<p>Let's say a thread retrieves the value of x, but hasn't stored it yet. Another thread can also retrieve the <b>same</b> value of x (because no thread has changed it yet) and then they would both be storing the <b>same</b> value (x+1) back in x!</p>\n\n<p>Example:</p>\n\n<pre>\nThread 1: reads x, value is 7\nThread 1: add 1 to x, value is now 8\nThread 2: reads x, <b>value is 7</b>\nThread 1: stores 8 in x\nThread 2: adds 1 to x, value is now 8\nThread 2: <b>stores 8 in x</b>\n</pre>\n\n<p>Race conditions can be avoided by employing some sort of <b>locking</b> mechanism before the code that accesses the shared resource:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>for ( int i = 0; i < 10000000; i++ )\n{\n //lock x\n x = x + 1; \n //unlock x\n}\n</code></pre>\n\n<p>Here, the answer comes out as 50,000,000 every time.</p>\n\n<p>For more on locking, search for: mutex, semaphore, critical section, shared resource.</p>\n"
},
{
"answer_id": 8222450,
"author": "realPK",
"author_id": 853001,
"author_profile": "https://Stackoverflow.com/users/853001",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class BankAccount {\n\n/**\n * @param args\n */\nint accountNumber;\ndouble accountBalance;\n\npublic synchronized boolean Deposit(double amount){\n double newAccountBalance=0;\n if(amount<=0){\n return false;\n }\n else {\n newAccountBalance = accountBalance+amount;\n accountBalance=newAccountBalance;\n return true;\n }\n\n}\npublic synchronized boolean Withdraw(double amount){\n double newAccountBalance=0;\n if(amount>accountBalance){\n return false;\n }\n else{\n newAccountBalance = accountBalance-amount;\n accountBalance=newAccountBalance;\n return true;\n }\n}\n\npublic static void main(String[] args) {\n // TODO Auto-generated method stub\n BankAccount b = new BankAccount();\n b.accountBalance=2000;\n System.out.println(b.Withdraw(3000));\n\n}\n</code></pre>\n"
},
{
"answer_id": 12420366,
"author": "Konstantin Dinev",
"author_id": 1348324,
"author_profile": "https://Stackoverflow.com/users/1348324",
"pm_score": 4,
"selected": false,
"text": "<p>Microsoft actually have published a really detailed <a href=\"http://support.microsoft.com/kb/317723\" rel=\"noreferrer\">article</a> on this matter of race conditions and deadlocks. The most summarized abstract from it would be the title paragraph:</p>\n\n<blockquote>\n <p>A race condition occurs when two threads access a shared variable at\n the same time. The first thread reads the variable, and the second\n thread reads the same value from the variable. Then the first thread\n and second thread perform their operations on the value, and they race\n to see which thread can write the value last to the shared variable.\n The value of the thread that writes its value last is preserved,\n because the thread is writing over the value that the previous thread\n wrote.</p>\n</blockquote>\n"
},
{
"answer_id": 16861236,
"author": "Morsu",
"author_id": 2440915,
"author_profile": "https://Stackoverflow.com/users/2440915",
"pm_score": 0,
"selected": false,
"text": "<p>Try this basic example for better understanding of race condition:</p>\n\n<pre><code> public class ThreadRaceCondition {\n\n /**\n * @param args\n * @throws InterruptedException\n */\n public static void main(String[] args) throws InterruptedException {\n Account myAccount = new Account(22222222);\n\n // Expected deposit: 250\n for (int i = 0; i < 50; i++) {\n Transaction t = new Transaction(myAccount,\n Transaction.TransactionType.DEPOSIT, 5.00);\n t.start();\n }\n\n // Expected withdrawal: 50\n for (int i = 0; i < 50; i++) {\n Transaction t = new Transaction(myAccount,\n Transaction.TransactionType.WITHDRAW, 1.00);\n t.start();\n\n }\n\n // Temporary sleep to ensure all threads are completed. Don't use in\n // realworld :-)\n Thread.sleep(1000);\n // Expected account balance is 200\n System.out.println(\"Final Account Balance: \"\n + myAccount.getAccountBalance());\n\n }\n\n}\n\nclass Transaction extends Thread {\n\n public static enum TransactionType {\n DEPOSIT(1), WITHDRAW(2);\n\n private int value;\n\n private TransactionType(int value) {\n this.value = value;\n }\n\n public int getValue() {\n return value;\n }\n };\n\n private TransactionType transactionType;\n private Account account;\n private double amount;\n\n /*\n * If transactionType == 1, deposit else if transactionType == 2 withdraw\n */\n public Transaction(Account account, TransactionType transactionType,\n double amount) {\n this.transactionType = transactionType;\n this.account = account;\n this.amount = amount;\n }\n\n public void run() {\n switch (this.transactionType) {\n case DEPOSIT:\n deposit();\n printBalance();\n break;\n case WITHDRAW:\n withdraw();\n printBalance();\n break;\n default:\n System.out.println(\"NOT A VALID TRANSACTION\");\n }\n ;\n }\n\n public void deposit() {\n this.account.deposit(this.amount);\n }\n\n public void withdraw() {\n this.account.withdraw(amount);\n }\n\n public void printBalance() {\n System.out.println(Thread.currentThread().getName()\n + \" : TransactionType: \" + this.transactionType + \", Amount: \"\n + this.amount);\n System.out.println(\"Account Balance: \"\n + this.account.getAccountBalance());\n }\n}\n\nclass Account {\n private int accountNumber;\n private double accountBalance;\n\n public int getAccountNumber() {\n return accountNumber;\n }\n\n public double getAccountBalance() {\n return accountBalance;\n }\n\n public Account(int accountNumber) {\n this.accountNumber = accountNumber;\n }\n\n // If this method is not synchronized, you will see race condition on\n // Remove syncronized keyword to see race condition\n public synchronized boolean deposit(double amount) {\n if (amount < 0) {\n return false;\n } else {\n accountBalance = accountBalance + amount;\n return true;\n }\n }\n\n // If this method is not synchronized, you will see race condition on\n // Remove syncronized keyword to see race condition\n public synchronized boolean withdraw(double amount) {\n if (amount > accountBalance) {\n return false;\n } else {\n accountBalance = accountBalance - amount;\n return true;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18506177,
"author": "Baris Kasikci",
"author_id": 1631712,
"author_profile": "https://Stackoverflow.com/users/1631712",
"pm_score": 6,
"selected": false,
"text": "<p>There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not. </p>\n\n<p>A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no <em>happens before ordering</em> among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order. </p>\n\n<p>A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program <em>behavior</em>. </p>\n\n<p>Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. <a href=\"http://blog.regehr.org/archives/490\" rel=\"noreferrer\">This</a> blog post also explains the difference very well, with a simple bank transaction example. Here is another simple <a href=\"https://stackoverflow.com/questions/11276259/are-data-races-and-race-condition-actually-the-same-thing-in-context-of-conc/18049303#18049303\">example</a> that explains the difference.</p>\n\n<p>Now that we nailed down the terminology, let us try to answer the original question.</p>\n\n<p>Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.</p>\n\n<p>On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is <a href=\"https://code.google.com/p/data-race-test/wiki/ThreadSanitizer\" rel=\"noreferrer\">ThreadSanitizer</a> which works very well in practice.</p>\n\n<p>Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.</p>\n"
},
{
"answer_id": 19190984,
"author": "Vishal Shukla",
"author_id": 2734949,
"author_profile": "https://Stackoverflow.com/users/2734949",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n <p>What is a Race Condition?</p>\n</blockquote>\n\n<p>You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I'm sure you can guess what happens: it's a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That's a race condition - specifically a \"check-then-act\" scenario of race conditions.</p>\n\n<blockquote>\n <p>How do you detect them?</p>\n</blockquote>\n\n<p>Religious code review, multi-threaded unit tests. There is no shortcut. There are few Eclipse plugin emerging on this, but nothing stable yet.</p>\n\n<blockquote>\n <p>How do you handle and prevent them?</p>\n</blockquote>\n\n<p>The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronization, and actor based concurrency will help.</p>\n\n<p>The best resource for concurrency is JCIP. You can also get some more <a href=\"http://brevitaz.com/race-condition-java-concurrency-2/\">details on above explanation here</a>.</p>\n"
},
{
"answer_id": 25708683,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 0,
"selected": false,
"text": "<p>You don't always want to discard a race condition. If you have a flag which can be read and written by multiple threads, and this flag is set to 'done' by one thread so that other thread stop processing when flag is set to 'done', you don't want that \"race condition\" to be eliminated. In fact, this one can be referred to as a benign race condition. </p>\n\n<p>However, using a tool for detection of race condition, it will be spotted as a harmful race condition.</p>\n\n<p>More details on race condition here, <a href=\"http://msdn.microsoft.com/en-us/magazine/cc546569.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/magazine/cc546569.aspx</a>. </p>\n"
},
{
"answer_id": 26931373,
"author": "Adnan Qureshi",
"author_id": 1137271,
"author_profile": "https://Stackoverflow.com/users/1137271",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>What is a race condition?</p>\n</blockquote>\n\n<p>The situation when the process is critically dependent on the sequence or timing of other events.</p>\n\n<p>For example,\nProcessor A and processor B <strong>both needs</strong> identical resource for their execution.</p>\n\n<blockquote>\n <p>How do you detect them? </p>\n</blockquote>\n\n<p>There are tools to detect race condition automatically:</p>\n\n<ul>\n<li><a href=\"http://www.hpcaconf.org/hpca13/papers/014-zhou.pdf\" rel=\"noreferrer\">Lockset-Based Race Checker</a></li>\n<li><a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.39.9581&rep=rep1&type=pdf\" rel=\"noreferrer\">Happens-Before Race Detection</a></li>\n<li><a href=\"http://web.cs.msu.edu/~cse914/Readings/hybridDynamicRaceDetection-ppopp03.pdf\" rel=\"noreferrer\">Hybrid Race Detection</a></li>\n</ul>\n\n<blockquote>\n <p>How do you handle them? </p>\n</blockquote>\n\n<p>Race condition can be handled by <strong>Mutex</strong> or <strong>Semaphores</strong>. They act as a lock allows a process to acquire a resource based on certain requirements to prevent race condition.</p>\n\n<blockquote>\n <p>How do you prevent them from occurring?</p>\n</blockquote>\n\n<p>There are various ways to prevent race condition, such as <strong>Critical Section Avoidance</strong>.</p>\n\n<ol>\n<li>No two processes simultaneously inside their critical regions. (<strong>Mutual Exclusion)</strong></li>\n<li>No assumptions are made about speeds or the number of CPUs.</li>\n<li>No process running outside its critical region which blocks other processes.</li>\n<li>No process has to wait forever to enter its critical region. (A waits for B resources, B waits for C resources, C waits for A resources)</li>\n</ol>\n"
},
{
"answer_id": 31424696,
"author": "bharanitharan",
"author_id": 358099,
"author_profile": "https://Stackoverflow.com/users/358099",
"pm_score": 0,
"selected": false,
"text": "<p>Consider an operation which has to display the count as soon as the count gets incremented. ie., as soon as <strong>CounterThread</strong> increments the value <strong>DisplayThread</strong> needs to display the recently updated value.</p>\n\n<pre><code>int i = 0;\n</code></pre>\n\n<p>Output </p>\n\n<pre><code>CounterThread -> i = 1 \nDisplayThread -> i = 1 \nCounterThread -> i = 2 \nCounterThread -> i = 3 \nCounterThread -> i = 4 \nDisplayThread -> i = 4\n</code></pre>\n\n<p>Here <strong>CounterThread</strong> gets the lock frequently and updates the value before <strong>DisplayThread</strong> displays it. Here exists a Race condition. Race Condition can be solved by using Synchronzation</p>\n"
},
{
"answer_id": 45498041,
"author": "nybon",
"author_id": 84540,
"author_profile": "https://Stackoverflow.com/users/84540",
"pm_score": 5,
"selected": false,
"text": "<p>Many answers in this discussion explains what a race condition is. I try to provide an explaination why this term is called <code>race condition</code> in software industry.</p>\n<h1>Why is it called <code>race condition</code>?</h1>\n<p>Race condition is not only related with software but also related with hardware too. Actually the term was initially coined by the hardware industry.</p>\n<p>According to <a href=\"https://en.wikipedia.org/wiki/Race_condition\" rel=\"nofollow noreferrer\">wikipedia</a>:</p>\n<blockquote>\n<p>The term originates with the idea of <strong>two signals racing each other</strong> to\n<strong>influence the output first</strong>.</p>\n<p>Race condition in a logic circuit:</p>\n<p><a href=\"https://i.stack.imgur.com/iUgaj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iUgaj.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p>Software industry took this term without modification, which makes it a little bit difficult to understand.</p>\n<p>You need to do some replacement to map it to the software world:</p>\n<ul>\n<li>"two signals" ==> "two threads"/"two processes"</li>\n<li>"influence the output" ==> "influence some shared state"</li>\n</ul>\n<p>So race condition in software industry means "two threads"/"two processes" racing each other to "influence some shared state", and the final result of the shared state will depend on some subtle timing difference, which could be caused by some specific thread/process launching order, thread/process scheduling, etc.</p>\n"
},
{
"answer_id": 45651528,
"author": "Aleksei Moshkov",
"author_id": 5031817,
"author_profile": "https://Stackoverflow.com/users/5031817",
"pm_score": 2,
"selected": false,
"text": "<p>You can <em>prevent race condition</em>, if you use \"Atomic\" classes. The reason is just the thread don't separate operation get and set, example is below:</p>\n\n<pre><code>AtomicInteger ai = new AtomicInteger(2);\nai.getAndAdd(5);\n</code></pre>\n\n<p>As a result, you will have 7 in link \"ai\". \nAlthough you did two actions, but the both operation confirm the same thread and no one other thread will interfere to this, that means no race conditions! </p>\n"
},
{
"answer_id": 53626771,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": 0,
"selected": false,
"text": "<p>A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.</p>\n"
},
{
"answer_id": 72158679,
"author": "zacksiri",
"author_id": 1584262,
"author_profile": "https://Stackoverflow.com/users/1584262",
"pm_score": 2,
"selected": false,
"text": "<p>I made a video that explains this.</p>\n<p>Essentially it is when you have a state with is shared across multiple threads and before the first execution on a given state is completed, another execution starts and the new thread’s initial state for a given operation is wrong because the previous execution has not completed.</p>\n<p>Because the initial state of the second execution is wrong, the resulting computation is also wrong. Because eventually the second execution will update the final state with the wrong result.</p>\n<p><a href=\"https://i.stack.imgur.com/rONSe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rONSe.png\" alt=\"reading a shared state\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/a9TgU.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/a9TgU.jpg\" alt=\"final computation is incorrect\" /></a></p>\n<p>You can view it here.\n<a href=\"https://youtu.be/RWRicNoWKOY\" rel=\"nofollow noreferrer\">https://youtu.be/RWRicNoWKOY</a></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | When writing multithreaded applications, one of the most common problems experienced is race conditions.
My questions to the community are:
* What is the race condition?
* How do you detect them?
* How do you handle them?
* Finally, how do you prevent them from occurring? | A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:
```
if (x == 5) // The "Check"
{
y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
// y will not be equal to 10.
}
```
The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.
In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:
```
// Obtain lock for x
if (x == 5)
{
y = x * 2; // Now, nothing can change x until the lock is released.
// Therefore y = 10
}
// release lock for x
``` |
34,516 | <p>Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?</p>
| [
{
"answer_id": 34530,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/// <summary>\n///\n/// </summary>\n/// <param name=\"strFilePath\"></param>\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc302121.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc302121.aspx</a></p>\n"
},
{
"answer_id": 34532,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>C# has built in <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/codedoc\" rel=\"nofollow noreferrer\">documentation commands</a>\nHave fun!</p>\n"
},
{
"answer_id": 34533,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 6,
"selected": true,
"text": "<p>You can use XML style comments, and use tools to pull those comments out into API documentation.</p>\n\n<p>Here is an example of the comment style:</p>\n\n<pre><code>/// <summary>\n/// Authenticates a user based on a username and password.\n/// </summary>\n/// <param name=\"username\">The username.</param>\n/// <param name=\"password\">The password.</param>\n/// <returns>\n/// True, if authentication is successful, otherwise False.\n/// </returns>\n/// <remarks>\n/// For use with local systems\n/// </remarks>\npublic override bool Authenticate(string username, string password)\n</code></pre>\n\n<p>Some items to facilitate this are:</p>\n\n<p><a href=\"http://www.roland-weigelt.de/ghostdoc/\" rel=\"noreferrer\">GhostDoc</a>, which give a single shortcut key to automatically generate comments for a class or method.\n<a href=\"http://blogs.msdn.com/sandcastle/about.aspx\" rel=\"noreferrer\">Sandcastle</a>, which generates MSDN style documentation from XML comments.</p>\n"
},
{
"answer_id": 34543,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "<p>Microsoft uses \"<a href=\"http://msdn.microsoft.com/en-us/library/b2s063f7.aspx\" rel=\"nofollow noreferrer\">XML Documentation Comments</a>\" which will give IDE intellisense descriptions and also allow you to auto-generate MSDN-style documentation using a tool such as Sandcastle if you turn on the generation of the XML file output.</p>\n\n<p>To turn on the generation of the XML file for documentation, right click on a project in visual studio, click \"Properties\" and go to the \"Build\" tab. Towards the bottom you can specify a location for your XML comments output file.</p>\n"
},
{
"answer_id": 34677,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 1,
"selected": false,
"text": "<p>The previous answers point out the XML syntax perfectly. I just wanted to throw in my recommendation for the <a href=\"http://ndoc.sourceforge.net/\" rel=\"nofollow noreferrer\">free (and open-source) nDoc help library generator</a> that parses all comments in a project. </p>\n"
},
{
"answer_id": 699654,
"author": "GameFreak",
"author_id": 26659,
"author_profile": "https://Stackoverflow.com/users/26659",
"pm_score": 0,
"selected": false,
"text": "<p>I was always told to use block comments opened with 2 or more asterisks do delimit documentation comments.</p>\n\n<pre><code>/**\nDocumentation goes here.\n(flowerboxes optional) \n*/\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code? | You can use XML style comments, and use tools to pull those comments out into API documentation.
Here is an example of the comment style:
```
/// <summary>
/// Authenticates a user based on a username and password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>
/// True, if authentication is successful, otherwise False.
/// </returns>
/// <remarks>
/// For use with local systems
/// </remarks>
public override bool Authenticate(string username, string password)
```
Some items to facilitate this are:
[GhostDoc](http://www.roland-weigelt.de/ghostdoc/), which give a single shortcut key to automatically generate comments for a class or method.
[Sandcastle](http://blogs.msdn.com/sandcastle/about.aspx), which generates MSDN style documentation from XML comments. |
34,518 | <p>How do you sort an array of strings <a href="http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="nofollow noreferrer">naturally</a> in different programming languages? Post your implementation and what language it is in in the answer.</p>
| [
{
"answer_id": 34528,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": "<p><strong>JavaScript</strong></p>\n\n<pre><code>Array.prototype.alphanumSort = function(caseInsensitive) {\n for (var z = 0, t; t = this[z]; z++) {\n this[z] = [], x = 0, y = -1, n = 0, i, j;\n\n while (i = (j = t.charAt(x++)).charCodeAt(0)) {\n var m = (i == 46 || (i >=48 && i <= 57));\n if (m !== n) {\n this[z][++y] = \"\";\n n = m;\n }\n this[z][y] += j;\n }\n }\n\n this.sort(function(a, b) {\n for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {\n if (caseInsensitive) {\n aa = aa.toLowerCase();\n bb = bb.toLowerCase();\n }\n if (aa !== bb) {\n var c = Number(aa), d = Number(bb);\n if (c == aa && d == bb) {\n return c - d;\n } else return (aa > bb) ? 1 : -1;\n }\n }\n return a.length - b.length;\n });\n\n for (var z = 0; z < this.length; z++)\n this[z] = this[z].join(\"\");\n}\n</code></pre>\n\n<p><a href=\"http://my.opera.com/GreyWyvern/blog/show.dml/1671288\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 34542,
"author": "Rytis",
"author_id": 979,
"author_profile": "https://Stackoverflow.com/users/979",
"pm_score": 3,
"selected": false,
"text": "<p>For MySQL, I personally use code from a Drupal module, which is available at hhttp://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/natsort.install.mysql</p>\n\n<p>Basically, you execute the posted SQL script to create functions, and then use <code>ORDER BY natsort_canon(field_name, 'natural')</code></p>\n\n<p>Here's a readme about the function:\n<a href=\"http://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/README.txt\" rel=\"nofollow noreferrer\">http://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/README.txt</a></p>\n"
},
{
"answer_id": 34780,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "<p>If the OP is asking about idomatic sorting expressions, then not all languages have a <em>natural</em> expression built in. For c I'd go to <code><stdlib.h></code> and use <code>qsort</code>. Something on the lines of :</p>\n\n<pre><code>/* non-functional mess deleted */\n</code></pre>\n\n<p>to sort the arguments into lexical order. Unfortunately this idiom is rather hard to parse for those not used the ways of c.</p>\n\n<hr>\n\n<p><em>Suitably chastened by the downvote, I actually read the linked article. Mea culpa.</em></p>\n\n<p>In anycase the original code did not work, except in the single case I tested. Damn. Plain vanilla c does not have this function, nor is it in any of the usual libraries. </p>\n\n<p>The code below sorts the command line arguments in the <strong>natural</strong> way as linked. <em>Caveat emptor</em> as it is only lightly tested.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\nint naturalstrcmp(const char **s1, const char **s2);\n\nint main(int argc, char **argv){\n /* Sort the command line arguments in place */\n qsort(&argv[1],argc-1,sizeof(char*),\n (int(*)(const void *, const void *))naturalstrcmp);\n\n while(--argc){\n printf(\"%s\\n\",(++argv)[0]);\n };\n}\n\nint naturalstrcmp(const char **s1p, const char **s2p){\n if ((NULL == s1p) || (NULL == *s1p)) {\n if ((NULL == s2p) || (NULL == *s2p)) return 0;\n return 1;\n };\n if ((NULL == s2p) || (NULL == *s2p)) return -1;\n\n const char *s1=*s1p;\n const char *s2=*s2p;\n\n do {\n if (isdigit(s1[0]) && isdigit(s2[0])){ \n /* Compare numbers as numbers */\n int c1 = strspn(s1,\"0123456789\"); /* Could be more efficient here... */\n int c2 = strspn(s2,\"0123456789\");\n if (c1 > c2) {\n return 1;\n } else if (c1 < c2) {\n return -1;\n };\n /* the digit strings have equal length, so compare digit by digit */\n while (c1--) {\n if (s1[0] > s2[0]){\n return 1;\n } else if (s1[0] < s2[0]){\n return -1;\n }; \n s1++;\n s2++;\n };\n } else if (s1[0] > s2[0]){\n return 1;\n } else if (s1[0] < s2[0]){\n return -1;\n }; \n s1++;\n s2++;\n } while ( (s1!='\\0') || (s2!='\\0') );\n return 0;\n}\n</code></pre>\n\n<p>This approach is pretty brute force, but it is simple and can probably be duplicated in any imperative language.</p>\n"
},
{
"answer_id": 35969,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 2,
"selected": false,
"text": "<p>In C++ I use this <a href=\"http://web.archive.org/web/20071217040157/http://www.boostcookbook.com/Recipe:/1235053\" rel=\"nofollow noreferrer\">example code</a> to do natural sorting. The code requires the boost library.</p>\n"
},
{
"answer_id": 341599,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "<p>I just use <a href=\"http://msdn.microsoft.com/en-us/library/bb759947.aspx\" rel=\"nofollow noreferrer\">StrCmpLogicalW</a>. It does exactly what Jeff is wanting, since it's the same API that explorer uses. Admittedly, it's not portable.</p>\n\n<p>In C++:</p>\n\n<pre><code>bool NaturalLess(const wstring &lhs, const wstring &rhs)\n{\n return StrCmpLogicalW(lhs.c_str(), rhs.c_str()) < 0;\n}\n\nvector<wstring> strings;\n// ... load the strings\nsort(strings.begin(), strings.end(), &NaturalLess);\n</code></pre>\n"
},
{
"answer_id": 341730,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a cleanup of <a href=\"http://nedbatchelder.com/blog/200712.html#e20071211T054956\" rel=\"nofollow noreferrer\">the code</a> in <a href=\"https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/\" rel=\"nofollow noreferrer\">the article</a> the question linked to:</p>\n\n<pre><code>def sorted_nicely(strings): \n \"Sort strings the way humans are said to expect.\"\n return sorted(strings, key=natural_sort_key)\n\ndef natural_sort_key(key):\n import re\n return [int(t) if t.isdigit() else t for t in re.split(r'(\\d+)', key)]\n</code></pre>\n\n<p>But actually I haven't had occasion to sort anything this way.</p>\n"
},
{
"answer_id": 341745,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<p>Here's how you can get explorer-like behaviour in Python:</p>\n\n\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\"\"\"\n>>> items = u'a1 a003 b2 a2 a10 1 10 20 2 c100'.split()\n>>> items.sort(explorer_cmp)\n>>> for s in items:\n... print s,\n1 2 10 20 a1 a2 a003 a10 b2 c100\n>>> items.sort(key=natural_key, reverse=True)\n>>> for s in items:\n... print s,\nc100 b2 a10 a003 a2 a1 20 10 2 1\n\"\"\"\nimport re\n\ndef natural_key(astr):\n \"\"\"See http://www.codinghorror.com/blog/archives/001018.html\"\"\"\n return [int(s) if s.isdigit() else s for s in re.split(r'(\\d+)', astr)]\n\ndef natural_cmp(a, b):\n return cmp(natural_key(a), natural_key(b))\n\ntry: # use explorer's comparison function if available\n import ctypes\n explorer_cmp = ctypes.windll.shlwapi.StrCmpLogicalW\nexcept (ImportError, AttributeError):\n # not on Windows or old python version\n explorer_cmp = natural_cmp \n\nif __name__ == '__main__':\n import doctest; doctest.testmod()\n</code></pre>\n\n<p>To support Unicode strings, <code>.isdecimal()</code> should be used instead of <code>.isdigit()</code>.</p>\n\n<p><code>.isdigit()</code> may also fail (return value that is not accepted by <code>int()</code>) for a bytestring on Python 2 in some locales e.g., <a href=\"https://stackoverflow.com/a/19440958/4279\">'\\xb2' ('²') in cp1252 locale on Windows</a>.</p>\n"
},
{
"answer_id": 348036,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 2,
"selected": false,
"text": "<p>Just a link to some nice work in Common Lisp by Eric Normand:</p>\n\n<p><a href=\"http://www.lispcast.com/wordpress/2007/12/human-order-sorting/\" rel=\"nofollow noreferrer\">http://www.lispcast.com/wordpress/2007/12/human-order-sorting/</a></p>\n"
},
{
"answer_id": 753548,
"author": "RHSeeger",
"author_id": 26816,
"author_profile": "https://Stackoverflow.com/users/26816",
"pm_score": 0,
"selected": false,
"text": "<p>For Tcl, the -dict (dictionary) option to lsort:</p>\n\n<pre><code>% lsort -dict {a b 1 c 2 d 13}\n1 2 13 a b c d\n</code></pre>\n"
},
{
"answer_id": 753739,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 1,
"selected": false,
"text": "<p>Note that for most such questions, you can just consult the <a href=\"http://www.rosettacode.org/wiki/Main_Page\" rel=\"nofollow noreferrer\">Rosetta Code Wiki</a>. I adapted my answer from the entry for sorting integers.</p>\n\n<p>In a system's programming language doing something like this is generally going to be uglier than with a specialzed string-handling language. Fortunately for Ada, the most recent version has a library routine for just this kind of task.</p>\n\n<p>For Ada 2005 I believe you could do something along the following lines (warning, not compiled!):</p>\n\n<pre><code>type String_Array is array(Natural range <>) of Ada.Strings.Unbounded.Unbounded_String;\nfunction \"<\" (L, R : Ada.Strings.Unbounded.Unbounded_String) return boolean is\nbegin\n --// Natural ordering predicate here. Sorry to cheat in this part, but\n --// I don't exactly grok the requirement for \"natural\" ordering. Fill in \n --// your proper code here.\nend \"<\";\nprocedure Sort is new Ada.Containers.Generic_Array_Sort \n (Index_Type => Natural;\n Element_Type => Ada.Strings.Unbounded.Unbounded_String,\n Array_Type => String_Array\n );\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code> using Ada.Strings.Unbounded;\n\n Example : String_Array := (To_Unbounded_String (\"Joe\"),\n To_Unbounded_String (\"Jim\"),\n To_Unbounded_String (\"Jane\"),\n To_Unbounded_String (\"Fred\"),\n To_Unbounded_String (\"Bertha\"),\n To_Unbounded_String (\"Joesphus\"),\n To_Unbounded_String (\"Jonesey\"));\nbegin\n Sort (Example);\n ...\nend;\n</code></pre>\n"
},
{
"answer_id": 1344071,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 2,
"selected": false,
"text": "<p>In C, this solution correctly handles numbers with leading zeroes:</p>\n\n<pre><code>#include <stdlib.h>\n#include <ctype.h>\n\n/* like strcmp but compare sequences of digits numerically */\nint strcmpbynum(const char *s1, const char *s2) {\n for (;;) {\n if (*s2 == '\\0')\n return *s1 != '\\0';\n else if (*s1 == '\\0')\n return 1;\n else if (!(isdigit(*s1) && isdigit(*s2))) {\n if (*s1 != *s2)\n return (int)*s1 - (int)*s2;\n else\n (++s1, ++s2);\n } else {\n char *lim1, *lim2;\n unsigned long n1 = strtoul(s1, &lim1, 10);\n unsigned long n2 = strtoul(s2, &lim2, 10);\n if (n1 > n2)\n return 1;\n else if (n1 < n2)\n return -1;\n s1 = lim1;\n s2 = lim2;\n }\n }\n}\n</code></pre>\n\n<p>If you want to use it with <code>qsort</code>, use this auxiliary function:</p>\n\n<pre><code>static int compare(const void *p1, const void *p2) {\n const char * const *ps1 = p1;\n const char * const *ps2 = p2;\n return strcmpbynum(*ps1, *ps2);\n}\n</code></pre>\n\n<p>And you can do something on the order of</p>\n\n<pre><code>char *lines = ...;\nqsort(lines, next, sizeof(lines[0]), compare);\n</code></pre>\n"
},
{
"answer_id": 4001057,
"author": "adw",
"author_id": 484688,
"author_profile": "https://Stackoverflow.com/users/484688",
"pm_score": 1,
"selected": false,
"text": "<p>Python, using itertools:</p>\n\n<pre><code>def natural_key(s):\n return tuple(\n int(''.join(chars)) if isdigit else ''.join(chars)\n for isdigit, chars in itertools.groupby(s, str.isdigit)\n )\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>>>> natural_key('abc-123foo456.xyz')\n('abc-', 123, 'foo', 456, '.xyz')\n</code></pre>\n\n<p>Sorting:</p>\n\n<pre><code>>>> sorted(['1.1.1', '1.10.4', '1.5.0', '42.1.0', '9', 'banana'], key=natural_key)\n['1.1.1', '1.5.0', '1.10.4', '9', '42.1.0', 'banana']\n</code></pre>\n"
},
{
"answer_id": 6924517,
"author": "Thang Mai",
"author_id": 807672,
"author_profile": "https://Stackoverflow.com/users/807672",
"pm_score": 1,
"selected": false,
"text": "<p>My implementation on Clojure 1.1:</p>\n\n<pre><code>(ns alphanumeric-sort\n (:import [java.util.regex Pattern]))\n\n(defn comp-alpha-numerical\n \"Compare two strings alphanumerically.\"\n [a b]\n (let [regex (Pattern/compile \"[\\\\d]+|[a-zA-Z]+\")\n sa (re-seq regex a)\n sb (re-seq regex b)]\n (loop [seqa sa seqb sb]\n (let [counta (count seqa)\n countb (count seqb)]\n (if-not (not-any? zero? [counta countb]) (- counta countb)\n (let [c (first seqa)\n d (first seqb)\n c1 (read-string c)\n d1 (read-string d)]\n (if (every? integer? [c1 d1]) \n (def result (compare c1 d1)) (def result (compare c d)))\n (if-not (= 0 result) result (recur (rest seqa) (rest seqb)))))))))\n\n(sort comp-alpha-numerical [\"a1\" \"a003\" \"b2\" \"a10\" \"a2\" \"1\" \"10\" \"20\" \"2\" \"c100\"])\n</code></pre>\n\n<p>Result:</p>\n\n<p>(\"1\" \"2\" \"10\" \"20\" \"a1\" \"a2\" \"a003\" \"a10\" \"b2\" \"c100\")</p>\n"
},
{
"answer_id": 26478632,
"author": "grant sun",
"author_id": 3509287,
"author_profile": "https://Stackoverflow.com/users/3509287",
"pm_score": 0,
"selected": false,
"text": "<p>php has a easy function \"natsort\" to do that,and I implements it by myself:</p>\n\n<pre><code><?php\n$temp_files = array('+====','-==',\"temp15-txt\",\"temp10.txt\",\n\"temp1.txt\",\"tempe22.txt\",\"temp2.txt\");\n$my_arr = $temp_files;\n\n\nnatsort($temp_files);\necho \"Natural order: \";\nprint_r($temp_files);\n\n\necho \"My Natural order: \";\nusort($my_arr,'my_nat_func');\nprint_r($my_arr);\n\n\nfunction is_alpha($a){\n return $a>='0'&&$a<='9' ;\n}\n\nfunction my_nat_func($a,$b){\n if(preg_match('/[0-9]/',$a)){\n if(preg_match('/[0-9]/',$b)){\n $i=0;\n while(!is_alpha($a[$i])) ++$i;\n $m = intval(substr($a,$i)); \n $i=0;\n while(!is_alpha($b[$i])) ++$i;\n $n = intval(substr($b,$i));\n return $m>$n?1:($m==$n?0:-1);\n }\n return 1;\n }else{\n if(preg_match('/[0-9]/',$b)){\n return -1;\n }\n return $a>$b?1:($a==$b?0:-1);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71668742,
"author": "vsk.rahul",
"author_id": 3116461,
"author_profile": "https://Stackoverflow.com/users/3116461",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Java solution:-</strong></p>\n<p>This can be achieved by implementing new <code>Comparator<String></code> and pass it to <code>Collections.sort(list, comparator)</code> method.</p>\n<pre><code>@Override\npublic int compare(String s1, String s2) {\n int len1 = s1.length();\n int len2 = s2.length();\n int lim = Math.min(len1, len2);\n char v1[] = s1.toCharArray();\n char v2[] = s2.toCharArray();\n\n int k = 0;\n while (k < lim) {\n char c1 = v1[k];\n char c2 = v2[k];\n if (c1 != c2) {\n if(this.isInteger(c1) && this.isInteger(c2)) {\n int i1 = grabContinousInteger(v1, k);\n int i2 = grabContinousInteger(v2, k);\n return i1 - i2;\n }\n return c1 - c2;\n }\n k++;\n }\n return len1 - len2;\n}\n\nprivate boolean isInteger(char c) {\n return c >= 48 && c <= 57; // ascii value 0-9\n}\n\nprivate int grabContinousInteger(char[] arr, int k) {\n \n int i = k;\n while(i < arr.length && this.isInteger(arr[i])) {\n i++;\n }\n return Integer.parseInt(new String(arr, k, i - k));\n}\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] | How do you sort an array of strings [naturally](http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/) in different programming languages? Post your implementation and what language it is in in the answer. | **JavaScript**
```
Array.prototype.alphanumSort = function(caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z] = [], x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});
for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}
```
[Source](http://my.opera.com/GreyWyvern/blog/show.dml/1671288) |
34,519 | <p>A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community: </p>
<p>What is a semaphore and how do you use it?</p>
| [
{
"answer_id": 34529,
"author": "Craig H",
"author_id": 2328,
"author_profile": "https://Stackoverflow.com/users/2328",
"pm_score": -1,
"selected": false,
"text": "<p>A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.</p>\n"
},
{
"answer_id": 34560,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 4,
"selected": false,
"text": "<p>@Craig:</p>\n\n<blockquote>\n <p>A semaphore is a way to lock a\n resource so that it is guaranteed that\n while a piece of code is executed,\n only this piece of code has access to\n that resource. This keeps two threads\n from concurrently accesing a resource,\n which can cause problems.</p>\n</blockquote>\n\n<p>This is not restricted to only one thread. A semaphore can be configured to allow a fixed number of threads to access a resource.</p>\n"
},
{
"answer_id": 40238,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 8,
"selected": false,
"text": "<p>The article <a href=\"https://barrgroup.com/embedded-systems/how-to/rtos-mutex-semaphore\" rel=\"noreferrer\">Mutexes and Semaphores Demystified</a> by Michael Barr is a great short introduction into what makes mutexes and semaphores different, and when they should and should not be used. I've excerpted several key paragraphs here.</p>\n<p>The key point is that mutexes should be used to protect shared resources, while semaphores should be used for signaling. You should generally not use semaphores to protect shared resources, nor mutexes for signaling. There are issues, for instance, with the bouncer analogy in terms of using semaphores to protect shared resources - you can use them that way, but it may cause hard to diagnose bugs.</p>\n<blockquote>\n<p>While mutexes and semaphores have some similarities in their implementation, they should always be used differently.</p>\n<p>The most common (but nonetheless incorrect) answer to the question posed at the top is that mutexes and semaphores are very similar, with the only significant difference being that semaphores can count higher than one. Nearly all engineers seem to properly understand that a mutex is a binary flag used to protect a shared resource by ensuring mutual exclusion inside critical sections of code. But when asked to expand on how to use a "counting semaphore," most engineers—varying only in their degree of confidence—express some flavor of the textbook opinion that these are used to protect several equivalent resources.</p>\n</blockquote>\n<p>...</p>\n<p>At this point an interesting analogy is made using the idea of bathroom keys as protecting shared resources - the bathroom. If a shop has a single bathroom, then a single key will be sufficient to protect that resource and prevent multiple people from using it simultaneously.</p>\n<p>If there are multiple bathrooms, one might be tempted to key them alike and make multiple keys - this is similar to a semaphore being mis-used. Once you have a key you don't actually know which bathroom is available, and if you go down this path you're probably going to end up using mutexes to provide that information and make sure you don't take a bathroom that's already occupied.</p>\n<p>A semaphore is the wrong tool to protect several of the essentially same resource, but this is how many people think of it and use it. The bouncer analogy is distinctly different - there aren't several of the same type of resource, instead there is one resource which can accept multiple simultaneous users. I suppose a semaphore can be used in such situations, but rarely are there real-world situations where the analogy actually holds - it's more often that there are several of the same type, but still individual resources, like the bathrooms, which cannot be used this way.</p>\n<p>...</p>\n<blockquote>\n<p>The correct use of a semaphore is for signaling from one task to another. A mutex is meant to be taken and released, always in that order, by each task that uses the shared resource it protects. By contrast, tasks that use semaphores either signal or wait—not both. For example, Task 1 may contain code to post (i.e., signal or increment) a particular semaphore when the "power" button is pressed and Task 2, which wakes the display, pends on that same semaphore. In this scenario, one task is the producer of the event signal; the other the consumer.</p>\n</blockquote>\n<p>...</p>\n<p>Here an important point is made that mutexes interfere with real time operating systems in a bad way, causing priority inversion where a less important task may be executed before a more important task because of resource sharing. In short, this happens when a lower priority task uses a mutex to grab a resource, A, then tries to grab B, but is paused because B is unavailable. While it's waiting, a higher priority task comes along and needs A, but it's already tied up, and by a process that isn't even running because it's waiting for B. There are many ways to resolve this, but it most often is fixed by altering the mutex and task manager. The mutex is much more complex in these cases than a binary semaphore, and using a semaphore in such an instance will cause priority inversions because the task manager is unaware of the priority inversion and cannot act to correct it.</p>\n<p>...</p>\n<blockquote>\n<p>The cause of the widespread modern confusion between mutexes and semaphores is historical, as it dates all the way back to the 1974 invention of the Semaphore (capital "S", in this article) by Djikstra. Prior to that date, none of the interrupt-safe task synchronization and signaling mechanisms known to computer scientists was efficiently scalable for use by more than two tasks. Dijkstra's revolutionary, safe-and-scalable Semaphore was applied in both critical section protection and signaling. And thus the confusion began.</p>\n<p>However, it later became obvious to operating system developers, after the appearance of the priority-based preemptive RTOS (e.g., VRTX, ca. 1980), publication of academic papers establishing RMA and the problems caused by priority inversion, and a paper on priority inheritance protocols in 1990, 3 it became apparent that mutexes must be more than just semaphores with a binary counter.</p>\n</blockquote>\n<p>Mutex: resource sharing</p>\n<p>Semaphore: signaling</p>\n<p>Don't use one for the other without careful consideration of the side effects.</p>\n"
},
{
"answer_id": 40282,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 6,
"selected": false,
"text": "<p>Mutex: exclusive-member access to a resource</p>\n\n<p>Semaphore: n-member access to a resource</p>\n\n<p>That is, a mutex can be used to syncronize access to a counter, file, database, etc.</p>\n\n<p>A sempahore can do the same thing but supports a fixed number of simultaneous callers. For example, I can wrap my database calls in a semaphore(3) so that my multithreaded app will hit the database with at most 3 simultaneous connections. All attempts will block until one of the three slots opens up. They make things like doing naive throttling really, really easy.</p>\n"
},
{
"answer_id": 40410,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": false,
"text": "<p>A semaphore is an object containing a natural number (i.e. a integer greater or equal to zero) on which two modifying operations are defined. One operation, <code>V</code>, adds 1 to the natural. The other operation, <code>P</code>, decreases the natural number by 1. Both activities are atomic (i.e. no other operation can be executed at the same time as a <code>V</code> or a <code>P</code>).</p>\n\n<p>Because the natural number 0 cannot be decreased, calling <code>P</code> on a semaphore containing a 0 will block the execution of the calling process(/thread) until some moment at which the number is no longer 0 and <code>P</code> can be successfully (and atomically) executed.</p>\n\n<p>As mentioned in other answers, semaphores can be used to restrict access to a certain resource to a maximum (but variable) number of processes.</p>\n"
},
{
"answer_id": 40473,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 9,
"selected": false,
"text": "<p>Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.</p>\n\n<p>It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.</p>\n\n<p>Here is a very pedagogic example in C# :-)</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\n\nnamespace TheNightclub\n{\n public class Program\n {\n public static Semaphore Bouncer { get; set; }\n\n public static void Main(string[] args)\n {\n // Create the semaphore with 3 slots, where 3 are available.\n Bouncer = new Semaphore(3, 3);\n\n // Open the nightclub.\n OpenNightclub();\n }\n\n public static void OpenNightclub()\n {\n for (int i = 1; i <= 50; i++)\n {\n // Let each guest enter on an own thread.\n Thread thread = new Thread(new ParameterizedThreadStart(Guest));\n thread.Start(i);\n }\n }\n\n public static void Guest(object args)\n {\n // Wait to enter the nightclub (a semaphore to be released).\n Console.WriteLine(\"Guest {0} is waiting to entering nightclub.\", args);\n Bouncer.WaitOne(); \n\n // Do some dancing.\n Console.WriteLine(\"Guest {0} is doing some dancing.\", args);\n Thread.Sleep(500);\n\n // Let one guest out (release one semaphore).\n Console.WriteLine(\"Guest {0} is leaving the nightclub.\", args);\n Bouncer.Release(1);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73387,
"author": "shodanex",
"author_id": 11589,
"author_profile": "https://Stackoverflow.com/users/11589",
"pm_score": 4,
"selected": false,
"text": "<p>Semaphore can also be used as a ... semaphore.\nFor example if you have multiple process enqueuing data to a queue, and only one task consuming data from the queue. If you don't want your consuming task to constantly poll the queue for available data, you can use semaphore.</p>\n\n<p>Here the semaphore is not used as an exclusion mechanism, but as a signaling mechanism.\nThe consuming task is waiting on the semaphore\nThe producing task are posting on the semaphore.</p>\n\n<p>This way the consuming task is running when and only when there is data to be dequeued</p>\n"
},
{
"answer_id": 5975456,
"author": "MABUTOBRIGHTON",
"author_id": 750219,
"author_profile": "https://Stackoverflow.com/users/750219",
"pm_score": 2,
"selected": false,
"text": "<p>A hardware or software flag. In multi tasking systems , a semaphore is as variable with a value that indicates the status of a common resource.A process needing the resource checks the semaphore to determine the resources status and then decides how to proceed.</p>\n"
},
{
"answer_id": 9103974,
"author": "bestsss",
"author_id": 554431,
"author_profile": "https://Stackoverflow.com/users/554431",
"pm_score": 0,
"selected": false,
"text": "<p>This is an old question but one of the most interesting uses of semaphore is a read/write lock and it has not been explicitly mentioned.</p>\n\n<p>The r/w locks works in simple fashion: consume one permit for a reader and all permits for writers.\nIndeed, a trivial implementation of a r/w lock but requires metadata modification on read (actually twice) that can become a bottle neck, still significantly better than a mutex or lock.</p>\n\n<p>Another downside is that writers can be started rather easily as well unless the semaphore is a fair one or the writes acquire permits in multiple requests, in such case they need an explicit mutex between themselves.</p>\n\n<p>Further <a href=\"http://doc.qt.nokia.com/qq/qq11-mutex.html\" rel=\"nofollow\">read</a>:</p>\n"
},
{
"answer_id": 21761646,
"author": "Columbia Student in Jae Class",
"author_id": 3307208,
"author_profile": "https://Stackoverflow.com/users/3307208",
"pm_score": 2,
"selected": false,
"text": "<p>So imagine everyone is trying to go to the bathroom and there's only a certain number of keys to the bathroom. Now if there's not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.</p>\n\n<p>Now imagine two processes trying to go to the bathroom at the same time. That's not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).</p>\n\n<p>There are also differences between binary/mutex & counting semaphores. </p>\n\n<p>Check out the lecture notes at <a href=\"http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html\" rel=\"nofollow\">http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html</a>.</p>\n"
},
{
"answer_id": 23545993,
"author": "aspen100",
"author_id": 2112500,
"author_profile": "https://Stackoverflow.com/users/2112500",
"pm_score": 4,
"selected": false,
"text": "<p>There are two essential concepts to building concurrent programs - synchronization and mutual exclusion. We will see how these two types of locks (semaphores are more generally a kind of locking mechanism) help us achieve synchronization and mutual exclusion.</p>\n\n<p>A semaphore is a programming construct that helps us achieve concurrency, by implementing both synchronization and mutual exclusion. Semaphores are of two types, Binary and Counting.</p>\n\n<p>A semaphore has two parts : a counter, and a list of tasks waiting to access a particular resource. A semaphore performs two operations : wait (P) [this is like acquiring a lock], and release (V)[ similar to releasing a lock] - these are the only two operations that one can perform on a semaphore. In a binary semaphore, the counter logically goes between 0 and 1. You can think of it as being similar to a lock with two values : open/closed. A counting semaphore has multiple values for count.</p>\n\n<p>What is important to understand is that the semaphore counter keeps track of the number of tasks that do not have to block, i.e., they can make progress. Tasks block, and add themselves to the semaphore's list only when the counter is zero. Therefore, a task gets added to the list in the P() routine if it cannot progress, and \"freed\" using the V() routine.</p>\n\n<p>Now, it is fairly obvious to see how binary semaphores can be used to solve synchronization and mutual exclusion - they are essentially locks.</p>\n\n<p>ex. Synchronization:</p>\n\n<pre><code>thread A{\nsemaphore &s; //locks/semaphores are passed by reference! think about why this is so.\nA(semaphore &s): s(s){} //constructor\nfoo(){\n...\ns.P();\n;// some block of code B2\n...\n}\n\n//thread B{\nsemaphore &s;\nB(semaphore &s): s(s){} //constructor\nfoo(){\n...\n...\n// some block of code B1\ns.V();\n..\n}\n\nmain(){\nsemaphore s(0); // we start the semaphore at 0 (closed)\nA a(s);\nB b(s);\n}\n</code></pre>\n\n<p>In the above example, B2 can only execute after B1 has finished execution. Let's say thread A comes executes first - gets to sem.P(), and waits, since the counter is 0 (closed). Thread B comes along, finishes B1, and then frees thread A - which then completes B2. So we achieve synchronization.</p>\n\n<p>Now let's look at mutual exclusion with a binary semaphore:</p>\n\n<pre><code>thread mutual_ex{\nsemaphore &s;\nmutual_ex(semaphore &s): s(s){} //constructor\nfoo(){\n...\ns.P();\n//critical section\ns.V();\n...\n...\ns.P();\n//critical section\ns.V();\n...\n\n}\n\nmain(){\nsemaphore s(1);\nmutual_ex m1(s);\nmutual_ex m2(s);\n}\n</code></pre>\n\n<p>The mutual exclusion is quite simple as well - m1 and m2 cannot enter the critical section at the same time. So each thread is using the same semaphore to provide mutual exclusion for its two critical sections. Now, is it possible to have greater concurrency? Depends on the critical sections. (Think about how else one could use semaphores to achieve mutual exclusion.. hint hint : do i necessarily only need to use one semaphore?)</p>\n\n<p>Counting semaphore: A semaphore with more than one value. Let's look at what this is implying - a lock with more than one value?? So open, closed, and ...hmm. Of what use is a multi-stage-lock in mutual exclusion or synchronization?</p>\n\n<p>Let's take the easier of the two:</p>\n\n<p>Synchronization using a counting semaphore: Let's say you have 3 tasks - #1 and 2 you want executed after 3. How would you design your synchronization?</p>\n\n<pre><code>thread t1{\n...\ns.P();\n//block of code B1\n\nthread t2{\n...\ns.P();\n//block of code B2\n\nthread t3{\n...\n//block of code B3\ns.V();\ns.V();\n}\n</code></pre>\n\n<p>So if your semaphore starts off closed, you ensure that t1 and t2 block, get added to the semaphore's list. Then along comes all important t3, finishes its business and frees t1 and t2. What order are they freed in? Depends on the implementation of the semaphore's list. Could be FIFO, could be based some particular priority,etc. (Note : think about how you would arrange your P's and V;s if you wanted t1 and t2 to be executed in some particular order, and if you weren't aware of the implementation of the semaphore)</p>\n\n<p>(Find out : What happens if the number of V's is greater than the number of P's?)</p>\n\n<p>Mutual Exclusion Using counting semaphores: I'd like you to construct your own pseudocode for this (makes you understand things better!) - but the fundamental concept is this : a counting semaphore of counter = N allows N tasks to enter the critical section freely. What this means is you have N tasks (or threads, if you like) enter the critical section, but the N+1th task gets blocked (goes on our favorite blocked-task list), and only is let through when somebody V's the semaphore at least once. So the semaphore counter, instead of swinging between 0 and 1, now goes between 0 and N, allowing N tasks to freely enter and exit, blocking nobody!</p>\n\n<p>Now gosh, why would you need such a stupid thing? Isn't the whole point of mutual exclusion to not let more than one guy access a resource?? (Hint Hint...You don't always only have one drive in your computer, do you...?)</p>\n\n<p><em>To think about</em> : Is mutual exclusion achieved by having a counting semaphore alone? What if you have 10 instances of a resource, and 10 threads come in (through the counting semaphore) and try to use the first instance?</p>\n"
},
{
"answer_id": 44971803,
"author": "NKumar",
"author_id": 5532090,
"author_profile": "https://Stackoverflow.com/users/5532090",
"pm_score": 5,
"selected": false,
"text": "<p>Consider, a taxi that can accommodate a total of 3(<em>rear</em>)+2(<em>front</em>) persons including the driver. So, a <strong><code>semaphore</code></strong> allows only 5 persons inside a car at a time.\nAnd a <strong><code>mutex</code></strong> allows only 1 person on a single seat of the car.</p>\n\n<p>Therefore, <strong><code>Mutex</code></strong> is to allow exclusive access for a resource (<em>like an OS thread</em>) while a <strong><code>Semaphore</code></strong> is to allow access for <strong>n</strong> number of resources at a time.</p>\n"
},
{
"answer_id": 52093990,
"author": "Volodymyr",
"author_id": 1245166,
"author_profile": "https://Stackoverflow.com/users/1245166",
"pm_score": 3,
"selected": false,
"text": "<p>I've created the visualization which should help to understand the idea. Semaphore controls access to a common resource in a multithreading environment.\n<a href=\"https://i.stack.imgur.com/cDXIV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/cDXIV.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>ExecutorService executor = Executors.newFixedThreadPool(7);\n\nSemaphore semaphore = new Semaphore(4);\n\nRunnable longRunningTask = () -> {\n boolean permit = false;\n try {\n permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);\n if (permit) {\n System.out.println(\"Semaphore acquired\");\n Thread.sleep(5);\n } else {\n System.out.println(\"Could not acquire semaphore\");\n }\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n } finally {\n if (permit) {\n semaphore.release();\n }\n }\n};\n\n// execute tasks\nfor (int j = 0; j < 10; j++) {\n executor.submit(longRunningTask);\n}\nexecutor.shutdown();\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>Semaphore acquired\nSemaphore acquired\nSemaphore acquired\nSemaphore acquired\nCould not acquire semaphore\nCould not acquire semaphore\nCould not acquire semaphore\n</code></pre>\n\n<p>Sample code from the <a href=\"https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/#semaphores\" rel=\"noreferrer\">article</a></p>\n"
},
{
"answer_id": 57520626,
"author": "sumit",
"author_id": 10828672,
"author_profile": "https://Stackoverflow.com/users/10828672",
"pm_score": 2,
"selected": false,
"text": "<p>Semaphores are act like thread limiters. </p>\n\n<p><strong>Example:</strong> If you have a pool of 100 threads and you want to perform some DB operation. If 100 threads access the DB at a given time, then there may be locking issue in DB so we can use semaphore which allow only limited thread at a time.Below Example allow only one thread at a time. When a thread call the <code>acquire()</code> method, it will then get the access and after calling the <code>release()</code> method, it will release the acccess so that next thread will get the access.</p>\n\n<pre><code> package practice;\n import java.util.concurrent.Semaphore;\n\n public class SemaphoreExample {\n public static void main(String[] args) {\n Semaphore s = new Semaphore(1);\n semaphoreTask s1 = new semaphoreTask(s);\n semaphoreTask s2 = new semaphoreTask(s);\n semaphoreTask s3 = new semaphoreTask(s);\n semaphoreTask s4 = new semaphoreTask(s);\n semaphoreTask s5 = new semaphoreTask(s);\n s1.start();\n s2.start();\n s3.start();\n s4.start();\n s5.start();\n }\n }\n\n class semaphoreTask extends Thread {\n Semaphore s;\n public semaphoreTask(Semaphore s) {\n this.s = s;\n }\n @Override\n public void run() {\n try {\n s.acquire();\n Thread.sleep(1000);\n System.out.println(Thread.currentThread().getName()+\" Going to perform some operation\");\n s.release();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n } \n }\n</code></pre>\n"
},
{
"answer_id": 71113133,
"author": "Pithikos",
"author_id": 474563,
"author_profile": "https://Stackoverflow.com/users/474563",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Mutex is just a boolean while semaphore is a counter</strong>.</p>\n<p>Both are used to lock part of code so it's not accessed by too many threads.</p>\n<p>Example</p>\n<pre><code>lock.set()\na += 1\nlock.unset()\n</code></pre>\n<p>Now if <code>lock</code> was a mutex, it means that it will always be locked or unlocked (a boolean under the surface) regardless how many threads try access the protected snippet of code. While locked, any other thread would just wait until it's unlocked/unset by the previous thread.</p>\n<p>Now imagine if instead <code>lock</code> was under the hood a counter with a predefined MAX value (say 2 for our example). Then if 2 threads try to access the resource, then lock would get its value increased to 2. If a 3rd thread then tried to access it, it would simply wait for the counter to go below 2 and so on.</p>\n<p><strong>If lock as a semaphore had a max of 1, then it would be acting exactly as a mutex.</strong></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community:
What is a semaphore and how do you use it? | Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.
It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.
Here is a very pedagogic example in C# :-)
```cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TheNightclub
{
public class Program
{
public static Semaphore Bouncer { get; set; }
public static void Main(string[] args)
{
// Create the semaphore with 3 slots, where 3 are available.
Bouncer = new Semaphore(3, 3);
// Open the nightclub.
OpenNightclub();
}
public static void OpenNightclub()
{
for (int i = 1; i <= 50; i++)
{
// Let each guest enter on an own thread.
Thread thread = new Thread(new ParameterizedThreadStart(Guest));
thread.Start(i);
}
}
public static void Guest(object args)
{
// Wait to enter the nightclub (a semaphore to be released).
Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
Bouncer.WaitOne();
// Do some dancing.
Console.WriteLine("Guest {0} is doing some dancing.", args);
Thread.Sleep(500);
// Let one guest out (release one semaphore).
Console.WriteLine("Guest {0} is leaving the nightclub.", args);
Bouncer.Release(1);
}
}
}
``` |
34,536 | <p>This most be the second most simple rollover effect, still I don't find any simple solution.</p>
<p><strong>Wanted:</strong> I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.</p>
<p>The following code works, but <em>is awful</em>. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.</p>
<pre><code><script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
</code></pre>
| [
{
"answer_id": 34564,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>The only thing that's wrong with this code (at least to me) is that you're not using a loop to process all elements. Other than that, why not to it like that?</p>\n\n<p>And with loop, I mean grabbing the container element via a JQuery and iterating over all child elements – basically a one-liner.</p>\n"
},
{
"answer_id": 34617,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the jQuery version:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js\"></script>\n<script type=\"text/javascript\">\n$(function () {\n $(\"#switches li\").mouseover(function () {\n var $this = $(this);\n $(\"#slides div\").hide();\n $(\"#slide\" + $this.attr(\"id\").replace(/switch/, \"\")).show();\n $(\"#switches li\").css(\"font-weight\", \"normal\");\n $this.css(\"font-weight\", \"bold\");\n });\n});\n</script>\n\n<ul id=\"switches\">\n <li id=\"switch1\" style=\"font-weight:bold;\">First slide</li>\n <li id=\"switch2\">Second slide</li>\n <li id=\"switch3\">Third slide</li>\n <li id=\"switch4\">Fourth slide</li>\n</ul>\n<div id=\"slides\">\n <div id=\"slide1\">Well well.</div>\n <div id=\"slide2\" style=\"display:none;\">Oh no!</div>\n <div id=\"slide3\" style=\"display:none;\">You again?</div>\n <div id=\"slide4\" style=\"display:none;\">I'm gone!</div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 34646,
"author": "Dmitry Mukhin",
"author_id": 3448,
"author_profile": "https://Stackoverflow.com/users/3448",
"pm_score": 2,
"selected": false,
"text": "<pre><code><html>\n<head>\n<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\">\n\n$(document).ready(\n function(){\n $( '#switches li' ).mouseover(\n function(){\n $( \"#slides div\" ).hide();\n $( '#switches li' ).css( 'font-weight', 'normal' );\n $( this ).css( 'font-weight', 'bold' );\n $( '#slide' + $( this ).attr( 'id' ).replace( 'switch', '' ) ).show();\n }\n );\n }\n);\n\n</script>\n</head>\n<body>\n<ul id=\"switches\">\n <li id=\"switch1\" style=\"font-weight:bold;\">First slide</li>\n <li id=\"switch2\">Second slide</li>\n <li id=\"switch3\">Third slide</li>\n <li id=\"switch4\">Fourth slide</li>\n</ul>\n<div id=\"slides\">\n <div id=\"slide1\">Well well.</div>\n <div id=\"slide2\" style=\"display:none;\">Oh no!</div>\n <div id=\"slide3\" style=\"display:none;\">You again?</div>\n <div id=\"slide4\" style=\"display:none;\">I'm gone!</div>\n</div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 34710,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 5,
"selected": true,
"text": "<p>Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the \"active\" class pre-set on the proper switch/slide.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).ready(function() {\r\n switches = $('#switches > li');\r\n slides = $('#slides > div');\r\n switches.each(function(idx) {\r\n $(this).data('slide', slides.eq(idx));\r\n }).hover(\r\n function() {\r\n switches.removeClass('active');\r\n slides.removeClass('active');\r\n $(this).addClass('active');\r\n $(this).data('slide').addClass('active');\r\n });\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#switches .active {\r\n font-weight: bold;\r\n}\r\n#slides div {\r\n display: none;\r\n}\r\n#slides div.active {\r\n display: block;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><html>\r\n\r\n<head>\r\n\r\n <title>test</title>\r\n\r\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n <script type=\"text/javascript\" src=\"switch.js\"></script>\r\n\r\n</head>\r\n\r\n<body>\r\n\r\n <ul id=\"switches\">\r\n <li class=\"active\">First slide</li>\r\n <li>Second slide</li>\r\n <li>Third slide</li>\r\n <li>Fourth slide</li>\r\n </ul>\r\n <div id=\"slides\">\r\n <div class=\"active\">Well well.</div>\r\n <div>Oh no!</div>\r\n <div>You again?</div>\r\n <div>I'm gone!</div>\r\n </div>\r\n\r\n</body>\r\n\r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 34718,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my light-markup jQuery version:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\">\nfunction switchTo(i) {\n $('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold');\n $('#slides div').css('display','none').eq(i).css('display','block');\n}\n$(document).ready(function(){\n $('#switches li').mouseover(function(event){\n switchTo($('#switches li').index(event.target));\n });\n switchTo(0);\n});\n</script>\n<ul id=\"switches\">\n <li>First slide</li>\n <li>Second slide</li>\n <li>Third slide</li>\n <li>Fourth slide</li>\n</ul>\n<div id=\"slides\">\n <div>Well well.</div>\n <div>Oh no!</div>\n <div>You again?</div>\n <div>I'm gone!</div>\n</div>\n</code></pre>\n\n<p>This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable. The <code>switchTo</code> function takes an index number of which <code><li></code> / <code><div></code> pair to activate, resets all the relevant elements to their default styles (non-bold for list items, <code>display:none</code> for the DIVs) and the sets the desired <code>list-item</code> and <code>div</code> to <code>bold</code> and <code>display</code>. As long as the client has javascript enabled, the functionality will be exactly the same as your original example.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
] | This most be the second most simple rollover effect, still I don't find any simple solution.
**Wanted:** I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.
The following code works, but *is awful*. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.
```
<script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
``` | Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide.
```js
$(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
});
```
```css
#switches .active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
}
```
```html
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="switch.js"></script>
</head>
<body>
<ul id="switches">
<li class="active">First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div class="active">Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
</body>
</html>
``` |
34,565 | <p>Additionally, how can I format it as a string padded with zeros?</p>
| [
{
"answer_id": 34582,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 7,
"selected": false,
"text": "<p>To generate the number call rand with the result of the expression \"10 to the power of 10\"</p>\n\n<pre><code>rand(10 ** 10)\n</code></pre>\n\n<p>To pad the number with zeros you can use the string format operator</p>\n\n<pre><code>'%010d' % rand(10 ** 10)\n</code></pre>\n\n<p>or the <code>rjust</code> method of string</p>\n\n<pre><code>rand(10 ** 10).to_s.rjust(10,'0') \n</code></pre>\n"
},
{
"answer_id": 175678,
"author": "Grant Hutchins",
"author_id": 6304,
"author_profile": "https://Stackoverflow.com/users/6304",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an expression that will use one fewer method call than quackingduck's example.</p>\n\n<pre><code>'%011d' % rand(1e10)\n</code></pre>\n\n<p>One caveat, <code>1e10</code> is a <code>Float</code>, and <code>Kernel#rand</code> ends up calling <code>to_i</code> on it, so for some higher values you might have some inconsistencies. To be more precise with a literal, you could also do:</p>\n\n<pre><code>'%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals\n</code></pre>\n"
},
{
"answer_id": 11442975,
"author": "Poseidon_Geek",
"author_id": 1269764,
"author_profile": "https://Stackoverflow.com/users/1269764",
"pm_score": 2,
"selected": false,
"text": "<p>I just want to modify first answer. <code>rand (10**10)</code> may generate 9 digit random no if 0 is in first place. For ensuring 10 exact digit just modify </p>\n\n<pre><code>code = rand(10**10)\nwhile code.to_s.length != 10\ncode = rand(11**11)\n</code></pre>\n\n<p>end</p>\n"
},
{
"answer_id": 14501221,
"author": "Paulo Fidalgo",
"author_id": 1006863,
"author_profile": "https://Stackoverflow.com/users/1006863",
"pm_score": 0,
"selected": false,
"text": "<p>This will work even on ruby 1.8.7:</p>\n\n<blockquote>\n <p>rand(9999999999).to_s.center(10, rand(9).to_s).to_i</p>\n</blockquote>\n"
},
{
"answer_id": 18161300,
"author": "Kreeki",
"author_id": 559316,
"author_profile": "https://Stackoverflow.com/users/559316",
"pm_score": 6,
"selected": false,
"text": "<p>I would like to contribute probably a simplest solution I know, which is a quite a good trick. </p>\n\n<pre><code>rand.to_s[2..11] \n => \"5950281724\"\n</code></pre>\n"
},
{
"answer_id": 18789508,
"author": "Gabriel Osorio",
"author_id": 2192331,
"author_profile": "https://Stackoverflow.com/users/2192331",
"pm_score": 3,
"selected": false,
"text": "<p>Just because it wasn't mentioned, the <code>Kernel#sprintf</code> method (or it's alias <code>Kernel#format</code> in the <a href=\"https://github.com/bbatsov/powerpack\">Powerpack Library</a>) is generally preferred over the <code>String#%</code> method, as mentioned in the <a href=\"https://github.com/bbatsov/ruby-style-guide\">Ruby Community Style Guide</a>.</p>\n\n<p>Of course this is highly debatable, but to provide insight:</p>\n\n<p>The syntax of @quackingduck's answer would be</p>\n\n<pre><code># considered bad\n'%010d' % rand(10**10)\n\n# considered good\nsprintf('%010d', rand(10**10))\n</code></pre>\n\n<p>The nature of this preference is primarily due to the cryptic nature of <code>%</code>. It's not very semantic by itself and without any additional context it can be confused with the <code>%</code> modulo operator.</p>\n\n<p>Examples from the <a href=\"https://github.com/bbatsov/ruby-style-guide\">Style Guide</a>:</p>\n\n<pre><code># bad\n'%d %d' % [20, 10]\n# => '20 10'\n\n# good\nsprintf('%d %d', 20, 10)\n# => '20 10'\n\n# good\nsprintf('%{first} %{second}', first: 20, second: 10)\n# => '20 10'\n\nformat('%d %d', 20, 10)\n# => '20 10'\n\n# good\nformat('%{first} %{second}', first: 20, second: 10)\n# => '20 10'\n</code></pre>\n\n<p>To make justice for <code>String#%</code>, I personally really like using operator-like syntaxes instead of commands, the same way you would do <code>your_array << 'foo'</code> over <code>your_array.push('123')</code>.</p>\n\n<p>This just illustrates a tendency in the community, what's \"best\" is up to you.</p>\n\n<p>More info in <a href=\"http://batsov.com/articles/2013/06/27/the-elements-of-style-in-ruby-number-2-favor-sprintf-format-over-string-number-percent/\">this blogpost</a>.</p>\n"
},
{
"answer_id": 25682945,
"author": "Tan Nguyen",
"author_id": 2245697,
"author_profile": "https://Stackoverflow.com/users/2245697",
"pm_score": 1,
"selected": false,
"text": "<pre><code>rand(9999999999).to_s.center(10, rand(9).to_s).to_i\n</code></pre>\n\n<p>is faster than</p>\n\n<pre><code>rand.to_s[2..11].to_i\n</code></pre>\n\n<p>You can use:</p>\n\n<pre><code>puts Benchmark.measure{(1..1000000).map{rand(9999999999).to_s.center(10, rand(9).to_s).to_i}}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>puts Benchmark.measure{(1..1000000).map{rand.to_s[2..11].to_i}}\n</code></pre>\n\n<p>in Rails console to confirm that.</p>\n"
},
{
"answer_id": 30456635,
"author": "Kamil Lelonek",
"author_id": 1313175,
"author_profile": "https://Stackoverflow.com/users/1313175",
"pm_score": 4,
"selected": false,
"text": "<h2>DON'T USE <code>rand.to_s[2..11].to_i</code></h2>\n\n<p>Why? Because here's what you can get:</p>\n\n<pre><code>rand.to_s[2..9] #=> \"04890612\"\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>\"04890612\".to_i #=> 4890612\n</code></pre>\n\n<p>Note that:</p>\n\n<pre><code>4890612.to_s.length #=> 7\n</code></pre>\n\n<p>Which is not what you've expected!</p>\n\n<p>To check that error in your own code, instead of <code>.to_i</code> you may wrap it like this:</p>\n\n<pre><code>Integer(rand.to_s[2..9])\n</code></pre>\n\n<p>and very soon it will turn out that:</p>\n\n<pre><code>ArgumentError: invalid value for Integer(): \"02939053\"\n</code></pre>\n\n<p>So it's always better to stick to <code>.center</code>, but keep in mind that:</p>\n\n<pre><code>rand(9) \n</code></pre>\n\n<p>sometimes may give you <code>0</code>.</p>\n\n<p>To prevent that:</p>\n\n<pre><code>rand(1..9)\n</code></pre>\n\n<p>which will always return something withing <code>1..9</code> range.</p>\n\n<p>I'm glad that I had good tests and I hope you will avoid breaking your system.</p>\n"
},
{
"answer_id": 31021140,
"author": "Dharani Manne",
"author_id": 2893591,
"author_profile": "https://Stackoverflow.com/users/2893591",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the SecureRandom ruby library.</p>\n\n<p>It generates random numbers but the length is not specific.</p>\n\n<p>Go through this link for more information: <a href=\"http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html\" rel=\"nofollow\">http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html</a></p>\n"
},
{
"answer_id": 31043708,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 2,
"selected": false,
"text": "<p>This technique works for any \"alphabet\"</p>\n\n<pre><code>(1..10).map{\"0123456789\".chars.to_a.sample}.join\n=> \"6383411680\"\n</code></pre>\n"
},
{
"answer_id": 31043825,
"author": "art-solopov",
"author_id": 2733119,
"author_profile": "https://Stackoverflow.com/users/2733119",
"pm_score": 4,
"selected": false,
"text": "<p>The most straightforward answer would probably be</p>\n\n<p><code>rand(1e9...1e10).to_i</code></p>\n\n<p>The <code>to_i</code> part is needed because <code>1e9</code> and <code>1e10</code> are actually floats:</p>\n\n<pre><code>irb(main)> 1e9.class\n=> Float\n</code></pre>\n"
},
{
"answer_id": 35785079,
"author": "steenslag",
"author_id": 290394,
"author_profile": "https://Stackoverflow.com/users/290394",
"pm_score": 5,
"selected": false,
"text": "<p>This is a fast way to generate a 10-sized string of digits:</p>\n\n<pre><code>10.times.map{rand(10)}.join # => \"3401487670\"\n</code></pre>\n"
},
{
"answer_id": 39995528,
"author": "Rahul Patel",
"author_id": 2334864,
"author_profile": "https://Stackoverflow.com/users/2334864",
"pm_score": 2,
"selected": false,
"text": "<p>Simplest way to generate n digit random number - </p>\n\n<pre><code>Random.new.rand((10**(n - 1))..(10**n))\n</code></pre>\n\n<p>generate 10 digit number number -</p>\n\n<pre><code>Random.new.rand((10**(10 - 1))..(10**10))\n</code></pre>\n"
},
{
"answer_id": 43346807,
"author": "907th",
"author_id": 1247092,
"author_profile": "https://Stackoverflow.com/users/1247092",
"pm_score": 4,
"selected": false,
"text": "<h2>Random number generation</h2>\n\n<p>Use <a href=\"https://ruby-doc.org/core-2.2.3/Kernel.html#method-i-rand\" rel=\"noreferrer\">Kernel#rand</a> method:</p>\n\n<pre><code>rand(1_000_000_000..9_999_999_999) # => random 10-digits number\n</code></pre>\n\n<h2>Random string generation</h2>\n\n<p>Use <code>times</code> + <code>map</code> + <code>join</code> combination:</p>\n\n<pre><code>10.times.map { rand(0..9) }.join # => random 10-digit string (may start with 0!)\n</code></pre>\n\n<h2>Number to string conversion with padding</h2>\n\n<p>Use <a href=\"https://ruby-doc.org/core-2.2.0/String.html#method-i-25\" rel=\"noreferrer\">String#%</a> method:</p>\n\n<pre><code>\"%010d\" % 123348 # => \"0000123348\"\n</code></pre>\n\n<h2>Password generation</h2>\n\n<p>Use <a href=\"https://github.com/johnbintz/keepass-password-generator\" rel=\"noreferrer\">KeePass password generator</a> library, it supports different patterns for generating random password:</p>\n\n<pre><code>KeePass::Password.generate(\"d{10}\") # => random 10-digit string (may start with 0!)\n</code></pre>\n\n<p>A documentation for KeePass patterns can be found <a href=\"http://keepass.info/help/base/pwgenerator.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 45458745,
"author": "Tom Lord",
"author_id": 1954610,
"author_profile": "https://Stackoverflow.com/users/1954610",
"pm_score": 1,
"selected": false,
"text": "<p>An alternative answer, using the <a href=\"https://github.com/tom-lord/regexp-examples\" rel=\"nofollow noreferrer\"><code>regexp-examples</code></a> ruby gem:</p>\n\n<pre><code>require 'regexp-examples'\n\n/\\d{10}/.random_example # => \"0826423747\"\n</code></pre>\n\n<p>There's no need to \"pad with zeros\" with this approach, since you are immediately generating a <code>String</code>.</p>\n"
},
{
"answer_id": 50966721,
"author": "Anderson Marques",
"author_id": 6646873,
"author_profile": "https://Stackoverflow.com/users/6646873",
"pm_score": 0,
"selected": false,
"text": "<p>A better approach is use <code>Array.new()</code> instead of <code>.times.map</code>. Rubocop recommends it.</p>\n\n<p>Example:</p>\n\n<pre><code>string_size = 9\nArray.new(string_size) do\n rand(10).to_s\nend\n</code></pre>\n\n<p>Rubucop, TimesMap:</p>\n\n<p><a href=\"https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Performance/TimesMap\" rel=\"nofollow noreferrer\">https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Performance/TimesMap</a></p>\n"
},
{
"answer_id": 52075422,
"author": "Lalit Kumar Maurya",
"author_id": 1637683,
"author_profile": "https://Stackoverflow.com/users/1637683",
"pm_score": 2,
"selected": false,
"text": "<p>Just use straightforward below.</p>\n\n<pre><code>rand(10 ** 9...10 ** 10)\n</code></pre>\n\n<p>Just test it on IRB with below.</p>\n\n<pre><code>(1..1000).each { puts rand(10 ** 9...10 ** 10) }\n</code></pre>\n"
},
{
"answer_id": 53654592,
"author": "Mario Ruiz",
"author_id": 2546667,
"author_profile": "https://Stackoverflow.com/users/2546667",
"pm_score": -1,
"selected": false,
"text": "<p>Random 10 numbers:</p>\n\n<pre><code>require 'string_pattern'\nputs \"10:N\".gen\n</code></pre>\n"
},
{
"answer_id": 54283486,
"author": "kazuwombat",
"author_id": 5992952,
"author_profile": "https://Stackoverflow.com/users/5992952",
"pm_score": 0,
"selected": false,
"text": "<p>In my case number must be unique in my models, so I added checking block.</p>\n\n<pre><code> module StringUtil\n refine String.singleton_class do\n def generate_random_digits(size:)\n proc = lambda{ rand.to_s[2...(2 + size)] }\n if block_given?\n loop do\n generated = proc.call\n break generated if yield(generated) # check generated num meets condition\n end\n else\n proc.call\n end\n end\n end\n end\n using StringUtil\n String.generate_random_digits(3) => \"763\"\n String.generate_random_digits(3) do |num|\n User.find_by(code: num).nil?\n end => \"689\"(This is unique in Users code)\n</code></pre>\n"
},
{
"answer_id": 55379711,
"author": "Khalil Gharbaoui",
"author_id": 5641227,
"author_profile": "https://Stackoverflow.com/users/5641227",
"pm_score": 2,
"selected": false,
"text": "<p><code>('%010d' % rand(0..9999999999)).to_s</code></p>\n\n<p>or</p>\n\n<p><code>\"#{'%010d' % rand(0..9999999999)}\"</code></p>\n"
},
{
"answer_id": 56564214,
"author": "Eliot Sykes",
"author_id": 67834,
"author_profile": "https://Stackoverflow.com/users/67834",
"pm_score": 2,
"selected": false,
"text": "<p>To generate a random, 10-digit string:</p>\n\n<pre><code># This generates a 10-digit string, where the\n# minimum possible value is \"0000000000\", and the\n# maximum possible value is \"9999999999\"\nSecureRandom.random_number(10**10).to_s.rjust(10, '0')\n</code></pre>\n\n<hr>\n\n<p>Here's more detail of what's happening, shown by breaking the single line into multiple lines with explaining variables:</p>\n\n<pre><code> # Calculate the upper bound for the random number generator\n # upper_bound = 10,000,000,000\n upper_bound = 10**10\n\n # n will be an integer with a minimum possible value of 0,\n # and a maximum possible value of 9,999,999,999\n n = SecureRandom.random_number(upper_bound)\n\n # Convert the integer n to a string\n # unpadded_str will be \"0\" if n == 0\n # unpadded_str will be \"9999999999\" if n == 9_999_999_999\n unpadded_str = n.to_s\n\n # Pad the string with leading zeroes if it is less than\n # 10 digits long.\n # \"0\" would be padded to \"0000000000\"\n # \"123\" would be padded to \"0000000123\"\n # \"9999999999\" would not be padded, and remains unchanged as \"9999999999\"\n padded_str = unpadded_str.rjust(10, '0')\n</code></pre>\n"
},
{
"answer_id": 63454165,
"author": "Anton Semenichenko",
"author_id": 7809709,
"author_profile": "https://Stackoverflow.com/users/7809709",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up with using Ruby kernel <code>srand</code></p>\n<p><code>srand.to_s.last(10)</code></p>\n<p>Docs here: <a href=\"https://www.rubydoc.info/stdlib/core/Kernel:srand\" rel=\"noreferrer\">Kernel#srand</a></p>\n"
},
{
"answer_id": 67246974,
"author": "MD Tawab Alam Khan",
"author_id": 11111981,
"author_profile": "https://Stackoverflow.com/users/11111981",
"pm_score": 0,
"selected": false,
"text": "<p>I did something like this</p>\n<pre><code>x = 10 #Number of digit\n(rand(10 ** x) + 10**x).to_s[0..x-1]\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | Additionally, how can I format it as a string padded with zeros? | To generate the number call rand with the result of the expression "10 to the power of 10"
```
rand(10 ** 10)
```
To pad the number with zeros you can use the string format operator
```
'%010d' % rand(10 ** 10)
```
or the `rjust` method of string
```
rand(10 ** 10).to_s.rjust(10,'0')
``` |
34,571 | <p>How do I use JUnit to test a class that has internal private methods, fields or nested classes?</p>
<p>It seems bad to change the access modifier for a method just to be able to run a test.</p>
| [
{
"answer_id": 34586,
"author": "Sir Rippov the Maple",
"author_id": 2822,
"author_profile": "https://Stackoverflow.com/users/2822",
"pm_score": 10,
"selected": false,
"text": "<p>The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:</p>\n\n<ol>\n<li>The private method is dead code</li>\n<li>There is a design smell near the class that you are testing</li>\n<li>The method that you are trying to test should not be private</li>\n</ol>\n"
},
{
"answer_id": 34590,
"author": "John Channing",
"author_id": 3305,
"author_profile": "https://Stackoverflow.com/users/3305",
"pm_score": 7,
"selected": false,
"text": "<p>Generally a unit test is intended to exercise the public interface of a class or unit. Therefore, private methods are implementation detail that you would not expect to test explicitly.</p>\n"
},
{
"answer_id": 34594,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 6,
"selected": false,
"text": "<p>The private methods are called by a public method, so the inputs to your public methods should also test private methods that are called by those public methods. When a public method fails, then that could be a failure in the private method.</p>\n"
},
{
"answer_id": 34598,
"author": "Iker Jimenez",
"author_id": 2697,
"author_profile": "https://Stackoverflow.com/users/2697",
"pm_score": 8,
"selected": false,
"text": "<p>From this article: <a href=\"http://www.artima.com/suiterunner/private.html\" rel=\"noreferrer\">Testing Private Methods with JUnit and SuiteRunner</a> (Bill Venners), you basically have 4 options:</p>\n<blockquote>\n<ol>\n<li>Don't test private methods.</li>\n<li>Give the methods package access.</li>\n<li>Use a nested test class.</li>\n<li>Use reflection.</li>\n</ol>\n</blockquote>\n"
},
{
"answer_id": 34630,
"author": "bmurphy1976",
"author_id": 1931,
"author_profile": "https://Stackoverflow.com/users/1931",
"pm_score": 4,
"selected": false,
"text": "<p>I tend not to test private methods. There lies madness. Personally, I believe you should only test your publicly exposed interfaces (and that includes protected and internal methods). </p>\n"
},
{
"answer_id": 34644,
"author": "Josh Brown",
"author_id": 2030,
"author_profile": "https://Stackoverflow.com/users/2030",
"pm_score": 3,
"selected": false,
"text": "<p>For Java I'd use <a href=\"http://docs.oracle.com/javase/tutorial/reflect/index.html\" rel=\"nofollow noreferrer\">reflection</a>, since I don't like the idea of changing the access to a package on the declared method just for the sake of testing. However, I usually just test the public methods which should also ensure the private methods are working correctly.</p>\n\n<blockquote>\n <p>you can't use reflection to get private methods from outside the owner class, the private modifier affects reflection also</p>\n</blockquote>\n\n<p>This is not true. You most certainly can, as mentioned in <a href=\"https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#34658\">Cem Catikkas's answer</a>.</p>\n"
},
{
"answer_id": 34658,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 12,
"selected": true,
"text": "<p>If you have somewhat of a legacy <strong>Java</strong> application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use <a href=\"http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29\" rel=\"noreferrer\">reflection</a>.</p>\n<p>Internally we're using helpers to get/set <code>private</code> and <code>private static</code> variables as well as invoke <code>private</code> and <code>private static</code> methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change <code>private static final</code> variables through reflection.</p>\n<pre><code>Method method = TargetClass.getDeclaredMethod(methodName, argClasses);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, argObjects);\n</code></pre>\n<p>And for fields:</p>\n<pre><code>Field field = TargetClass.getDeclaredField(fieldName);\nfield.setAccessible(true);\nfield.set(object, value);\n</code></pre>\n<hr />\n<blockquote>\n<p><strong>Notes:</strong></p>\n<ol>\n<li><code>TargetClass.getDeclaredMethod(methodName, argClasses)</code> lets you look into <code>private</code> methods. The same thing applies for\n<code>getDeclaredField</code>.</li>\n<li>The <code>setAccessible(true)</code> is required to play around with privates.</li>\n</ol>\n</blockquote>\n"
},
{
"answer_id": 38425,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 5,
"selected": false,
"text": "<p>Having tried Cem Catikkas' <a href=\"https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#34658\">solution using reflection</a> for Java, I'd have to say his was a more elegant solution than I have described here. However, if you're looking for an alternative to using reflection, and have access to the source you're testing, this will still be an option.</p>\n\n<p>There is possible merit in testing private methods of a class, particularly with <a href=\"http://en.wikipedia.org/wiki/Test-driven_development\" rel=\"noreferrer\">test-driven development</a>, where you would like to design small tests before you write any code.</p>\n\n<p>Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Can test to a finer granularity</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>Test code must reside in the same\nfile as source code, which can be\nmore difficult to maintain</li>\n<li>Similarly with .class output files, they must remain within the same package as declared in source code</li>\n</ul>\n\n<p>However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.</p>\n\n<p>Here is a convoluted example of how this would work:</p>\n\n<pre><code>// Import statements and package declarations\n\npublic class ClassToTest\n{\n private int decrement(int toDecrement) {\n toDecrement--;\n return toDecrement;\n }\n\n // Constructor and the rest of the class\n\n public static class StaticInnerTest extends TestCase\n {\n public StaticInnerTest(){\n super();\n }\n\n public void testDecrement(){\n int number = 10;\n ClassToTest toTest= new ClassToTest();\n int decremented = toTest.decrement(number);\n assertEquals(9, decremented);\n }\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(StaticInnerTest.class);\n }\n }\n}\n</code></pre>\n\n<p>The inner class would be compiled to <code>ClassToTest$StaticInnerTest</code>.</p>\n\n<p>See also: <em><a href=\"http://www.javaworld.com/javaworld/javatips/jw-javatip106.html\" rel=\"noreferrer\">Java Tip 106: Static inner classes for fun and profit</a></em></p>\n"
},
{
"answer_id": 46255,
"author": "Don Kirkby",
"author_id": 4794,
"author_profile": "https://Stackoverflow.com/users/4794",
"pm_score": 5,
"selected": false,
"text": "<p>If you're trying to test existing code that you're reluctant or unable to change, reflection is a good choice.</p>\n\n<p>If the class's design is still flexible, and you've got a complicated private method that you'd like to test separately, I suggest you pull it out into a separate class and test that class separately. This doesn't have to change the public interface of the original class; it can internally create an instance of the helper class and call the helper method.</p>\n\n<p>If you want to test difficult error conditions coming from the helper method, you can go a step further. Extract an interface from the helper class, add a public getter and setter to the original class to inject the helper class (used through its interface), and then inject a mock version of the helper class into the original class to test how the original class responds to exceptions from the helper. This approach is also helpful if you want to test the original class without also testing the helper class.</p>\n"
},
{
"answer_id": 51192,
"author": "Will Sargent",
"author_id": 5266,
"author_profile": "https://Stackoverflow.com/users/5266",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to test private methods of a legacy application where you can't change the code, one option for Java is <a href=\"http://code.google.com/p/jmockit/\" rel=\"noreferrer\">jMockit</a>, which will allow you to create mocks to an object even when they're private to the class.</p>\n"
},
{
"answer_id": 52054,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 9,
"selected": false,
"text": "<p>When I have private methods in a class that are sufficiently complicated that I feel the need to test the private methods directly, that is a code smell: my class is too complicated. </p>\n\n<p>My usual approach to addressing such issues is to tease out a new class that contains the interesting bits. Often, this method and the fields it interacts with, and maybe another method or two can be extracted in to a new class. </p>\n\n<p>The new class exposes these methods as 'public', so they're accessible for unit testing. The new and old classes are now both simpler than the original class, which is great for me (I need to keep things simple, or I get lost!).</p>\n\n<p>Note that I'm not suggesting that people create classes without using their brain! The point here is to use the forces of unit testing to help you find good new classes. </p>\n"
},
{
"answer_id": 53571,
"author": "Darren Greaves",
"author_id": 151,
"author_profile": "https://Stackoverflow.com/users/151",
"pm_score": 4,
"selected": false,
"text": "<p>As many above have suggested, a good way is to test them via your public interfaces.</p>\n<p>If you do this, it's a good idea to use a <a href=\"https://en.wikipedia.org/wiki/Code_coverage\" rel=\"nofollow noreferrer\">code coverage</a> tool (like <a href=\"https://en.wikipedia.org/wiki/Java_code_coverage_tools#EMMA\" rel=\"nofollow noreferrer\">EMMA</a>) to see if your private methods are in fact being executed from your tests.</p>\n"
},
{
"answer_id": 57795,
"author": "Joe",
"author_id": 5313,
"author_profile": "https://Stackoverflow.com/users/5313",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using JUnit, have a look at <a href=\"http://junit-addons.sourceforge.net/\" rel=\"noreferrer\">junit-addons</a>. It has the ability to ignore the Java security model and access private methods and attributes.</p>\n"
},
{
"answer_id": 91206,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 4,
"selected": false,
"text": "<p>First, I'll throw this question out: Why do your private members need isolated testing? Are they that complex, providing such complicated behaviors as to require testing apart from the public surface? It's unit testing, not 'line-of-code' testing. Don't sweat the small stuff.</p>\n<p>If they are that big, big enough that these private members are each a 'unit' large in complexity—consider refactoring such private members out of this class.</p>\n<p>If refactoring is inappropriate or infeasible, can you use the <a href=\"https://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">strategy pattern</a> to replace access to these private member functions / member classes when under unit test? Under unit test, the strategy would provide added validation, but in release builds it would be simple passthrough.</p>\n"
},
{
"answer_id": 190338,
"author": "ema",
"author_id": 19520,
"author_profile": "https://Stackoverflow.com/users/19520",
"pm_score": 5,
"selected": false,
"text": "<p>Testing private methods breaks the encapsulation of your class because every time you change the internal implementation you break client code (in this case, the tests).</p>\n\n<p>So don't test private methods.</p>\n"
},
{
"answer_id": 549551,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 5,
"selected": false,
"text": "<p>As others have said... don't test private methods directly. Here are a few thoughts:</p>\n<ol>\n<li>Keep all methods small and focused (easy to test, easy to find what is wrong)</li>\n<li>Use code coverage tools. I like <a href=\"http://cobertura.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">Cobertura</a> (oh happy day, it looks like a new version is out!)</li>\n</ol>\n<p>Run the code coverage on the unit tests. If you see that methods are not fully tested add to the tests to get the coverage up. Aim for 100% code coverage, but realize that you probably won't get it.</p>\n"
},
{
"answer_id": 549558,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 3,
"selected": false,
"text": "<p>You can turn off Java access restrictions for reflection so that private means nothing.</p>\n\n<p>The <code>setAccessible(true)</code> call does that.</p>\n\n<p>The only restriction is that a ClassLoader may disallow you from doing that.</p>\n\n<p>See <em><a href=\"http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html\" rel=\"nofollow noreferrer\">Subverting Java Access Protection for Unit Testing</a></em> (Ross Burton) for a way to do this in Java.</p>\n"
},
{
"answer_id": 549592,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 2,
"selected": false,
"text": "<p>In C# you could have used <code>System.Reflection</code>, though in Java I don't know. If you "feel you need to unit test private methods", my guess is that there is something else which is wrong...</p>\n<p>I would seriously consider looking at my architecture again with fresh eyes...</p>\n"
},
{
"answer_id": 1038507,
"author": "Diego Amicabile",
"author_id": 126875,
"author_profile": "https://Stackoverflow.com/users/126875",
"pm_score": 2,
"selected": false,
"text": "<p>What if your test classes are in the same package as the class that should be tested?</p>\n\n<p>But in a different directory of course, <code>src</code> & <code>classes</code> for your source code, <code>test/src</code> and <code>test/classes</code> for your test classes. And let <code>classes</code> and <code>test/classes</code> be in your classpath.</p>\n"
},
{
"answer_id": 1043013,
"author": "Jon",
"author_id": 128285,
"author_profile": "https://Stackoverflow.com/users/128285",
"pm_score": 8,
"selected": false,
"text": "<p>I have used <a href=\"http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29\" rel=\"nofollow noreferrer\">reflection</a> to do this for Java in the past, and in my opinion it was a big mistake.</p>\n<p>Strictly speaking, you should <em>not</em> be writing unit tests that directly test private methods. What you <em>should</em> be testing is the public contract that the class has with other objects; you should never directly test an object's internals. If another developer wants to make a small internal change to the class, which doesn't affect the classes public contract, he/she then has to modify your reflection based test to ensure that it works. If you do this repeatedly throughout a project, unit tests then stop being a useful measurement of code health, and start to become a hindrance to development, and an annoyance to the development team.</p>\n<p>What I recommend doing instead is using a code coverage tool, such as <a href=\"https://en.wikipedia.org/wiki/Java_code_coverage_tools#Cobertura\" rel=\"nofollow noreferrer\">Cobertura</a>, to ensure that the unit tests you write provide decent coverage of the code in private methods. That way, you indirectly test what the private methods are doing, and maintain a higher level of agility.</p>\n"
},
{
"answer_id": 3177465,
"author": "Richard Le Mesurier",
"author_id": 383414,
"author_profile": "https://Stackoverflow.com/users/383414",
"pm_score": 6,
"selected": false,
"text": "<p>Just two examples of where I would want to test a private method:</p>\n<ol>\n<li><p><strong>Decryption routines</strong> - I would not\nwant to make them visible to anyone to see just for\nthe sake of testing, else anyone can\nuse them to decrypt. But they are\nintrinsic to the code, complicated,\nand need to always work (the obvious exception is reflection which can be used to view even private methods in most cases, when <code>SecurityManager</code> is not configured to prevent this).</p>\n</li>\n<li><p><strong>Creating an SDK</strong> for community\nconsumption. Here public takes on a\nwholly different meaning, since this\nis code that the whole world may see\n(not just internal to my application). I put\ncode into private methods if I don't\nwant the SDK users to see it - I\ndon't see this as code smell, merely\nas how SDK programming works. But of\ncourse I still need to test my\nprivate methods, and they are where\nthe functionality of my SDK actually\nlives.</p>\n</li>\n</ol>\n<p>I understand the idea of only testing the "contract". But I don't see one can advocate actually not testing code—your mileage may vary.</p>\n<p>So my trade-off involves complicating the JUnit tests with reflection, rather than compromising my security and SDK.</p>\n"
},
{
"answer_id": 4667692,
"author": "phareim",
"author_id": 373975,
"author_profile": "https://Stackoverflow.com/users/373975",
"pm_score": 5,
"selected": false,
"text": "<p>To test legacy code with large and quirky classes, it is often very helpful to be able to test the one private (or public) method I'm writing <em>right now</em>.</p>\n<p>I use the <strong>junitx.util.PrivateAccessor</strong>-package for Java. It has lots of helpful one-liners for accessing private methods and private fields.</p>\n<pre><code>import junitx.util.PrivateAccessor;\n\nPrivateAccessor.setField(myObjectReference, "myCrucialButHardToReachPrivateField", myNewValue);\nPrivateAccessor.invoke(myObjectReference, "privateMethodName", java.lang.Class[] parameterTypes, java.lang.Object[] args);\n</code></pre>\n"
},
{
"answer_id": 5083041,
"author": "simpatico",
"author_id": 300248,
"author_profile": "https://Stackoverflow.com/users/300248",
"pm_score": 4,
"selected": false,
"text": "<p>The answer from <a href=\"http://junit.org/faq.html#atests_11\" rel=\"nofollow noreferrer\">JUnit.org FAQ page</a>:</p>\n<blockquote>\n<p>But if you must...</p>\n<p>If you are using JDK 1.3 or higher, you can use reflection to subvert\nthe access control mechanism with the aid of the <a href=\"http://sourceforge.net/projects/privaccessor/\" rel=\"nofollow noreferrer\">PrivilegedAccessor</a>.\nFor details on how to use it, read <a href=\"http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html\" rel=\"nofollow noreferrer\">this article</a>.</p>\n<p>If you are using JDK 1.6 or higher and you annotate your tests with\n@Test, you can use <a href=\"http://dp4j.com\" rel=\"nofollow noreferrer\">Dp4j</a> to inject reflection in your test methods. For\ndetails on how to use it, see <a href=\"http://dp4j.com/testscript\" rel=\"nofollow noreferrer\">this test script</a>.</p>\n</blockquote>\n<p>P.S. I'm the main contributor to <a href=\"http://dp4j.com\" rel=\"nofollow noreferrer\">Dp4j</a>. Ask <a href=\"https://stackoverflow.com/users/300248\">me</a> if you need help. :)</p>\n"
},
{
"answer_id": 5820700,
"author": "Gimby",
"author_id": 424903,
"author_profile": "https://Stackoverflow.com/users/424903",
"pm_score": 0,
"selected": false,
"text": "<p>I only test the public interface, but I have been known to make specific private methods protected so I can either mock them out entirely, or add in additional steps specific for unit testing purposes. A general case is to hook in flags I can set from the unit test to make certain methods intentionally cause an exception to be able to test fault paths; the exception triggering code is only in the test path in an overridden implementation of the protected method.</p>\n\n<p>I minimize the need for this though and I always document the precise reasons to avoid confusion.</p>\n"
},
{
"answer_id": 8139572,
"author": "marc wellman",
"author_id": 946904,
"author_profile": "https://Stackoverflow.com/users/946904",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure whether this is a good technique, but I developed the following pattern to unit test private methods:</p>\n<p>I don't modify the visibility of the method that I want to test and add an additional method. Instead I am adding an additional public method for every private method I want to test. I call this additional method <code>Test-Port</code> and denote them with the prefix <code>t_</code>. This <code>Test-Port</code> method then simply accesses the according private method.</p>\n<p>Additionally, I add a Boolean flag to the <code>Test-Port</code> method to decide whether I grant access to the private method through the <code>Test-Port</code> method from outside. This flag is then set globally in a static class where I place e.g. other global settings for the application. So I can switch the access to the private methods on and off in one place, e.g., in the corresponding unit test.</p>\n"
},
{
"answer_id": 8704898,
"author": "sagehen03",
"author_id": 107852,
"author_profile": "https://Stackoverflow.com/users/107852",
"pm_score": 0,
"selected": false,
"text": "<p>Groovy has a <a href=\"http://jira.codehaus.org/browse/GROOVY-1875\" rel=\"nofollow\">bug/feature</a>, through which you can invoke private methods as if they were public. So if you're able to use Groovy in your project, it's an option you can use in lieu of reflection. Check out <a href=\"http://marciogarcia.com/?p=80\" rel=\"nofollow\">this page</a> for an example.</p>\n"
},
{
"answer_id": 15192546,
"author": "Steven Bluen",
"author_id": 419109,
"author_profile": "https://Stackoverflow.com/users/419109",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://en.wikipedia.org/wiki/Java_Modeling_Language\" rel=\"nofollow noreferrer\">JML</a> has a <em>spec_public</em> comment annotation syntax that allows you to specify a method as public during tests:</p>\n<pre><code>private /*@ spec_public @*/ int methodName(){\n...\n}\n</code></pre>\n<p>This syntax is discussed at <em><a href=\"http://www.eecs.ucf.edu/%7Eleavens/JML/jmlrefman/jmlrefman_2.html#SEC12\" rel=\"nofollow noreferrer\">2.4 Privacy Modifiers and Visibility</a></em>. There also exists a program that translates JML specifications into JUnit tests. I'm not sure how well that works or what its capabilities are, but it doesn't appear to be necessary since JML is a viable testing framework on its own.</p>\n"
},
{
"answer_id": 18859235,
"author": "Snicolas",
"author_id": 693752,
"author_profile": "https://Stackoverflow.com/users/693752",
"pm_score": 4,
"selected": false,
"text": "<p>Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.</p>\n<p>If you got some code with private methods or fields or constructors, you can use <a href=\"https://github.com/stephanenicolas/boundbox\" rel=\"nofollow noreferrer\"><strong>BoundBox</strong></a>. It does exactly what you are looking for.\nHere below is an example of a test that accesses two private fields of an Android activity to test it:</p>\n<pre><code>@UiThreadTest\npublic void testCompute() {\n\n // Given\n boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());\n\n // When\n boundBoxOfMainActivity.boundBox_getButtonMain().performClick();\n\n // Then\n assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());\n}\n</code></pre>\n<p><strong>BoundBox</strong> makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, <em><strong>but</strong></em> everything is checked at compile time.</p>\n<p>It is ideal for testing some legacy code. Use it carefully. ;)</p>\n"
},
{
"answer_id": 20337937,
"author": "Antony Booth",
"author_id": 312957,
"author_profile": "https://Stackoverflow.com/users/312957",
"pm_score": 5,
"selected": false,
"text": "<p>Private methods are consumed by public ones. Otherwise, they're dead code. That's why you test the public method, asserting the expected results of the public method and thereby, the private methods it consumes.</p>\n\n<p>Testing private methods should be tested by debugging before running your unit tests on public methods.</p>\n\n<p>They may also be debugged using test-driven development, debugging your unit tests until all your assertions are met.</p>\n\n<p>I personally believe it is better to create classes using TDD; creating the public method stubs, then generating unit tests with <strong>all</strong> the assertions defined in advance, so the expected outcome of the method is determined before you code it. This way, you don't go down the wrong path of making the unit test assertions fit the results. Your class is then robust and meets requirements when all your unit tests pass.</p>\n"
},
{
"answer_id": 20990300,
"author": "Yuli Reiri",
"author_id": 1789360,
"author_profile": "https://Stackoverflow.com/users/1789360",
"pm_score": 4,
"selected": false,
"text": "<p>Here is my generic function to test private fields:</p>\n\n<pre><code>protected <F> F getPrivateField(String fieldName, Object obj)\n throws NoSuchFieldException, IllegalAccessException {\n Field field =\n obj.getClass().getDeclaredField(fieldName);\n\n field.setAccessible(true);\n return (F)field.get(obj);\n}\n</code></pre>\n"
},
{
"answer_id": 23441118,
"author": "loknath",
"author_id": 2373304,
"author_profile": "https://Stackoverflow.com/users/2373304",
"pm_score": 4,
"selected": false,
"text": "<p>A private method is only to be accessed within the same class. So there is no way to test a “private” method of a target class from any test class. A way out is that you can perform unit testing manually or can change your method from “private” to “protected”.</p>\n\n<p>And then a protected method can only be accessed within the same package where the class is defined. So, testing a protected method of a target class means we need to define your test class in the same package as the target class.</p>\n\n<p>If all the above does not suits your requirement, use <a href=\"https://stackoverflow.com/questions/11483647/how-to-access-private-methods-and-private-data-members-via-reflection\"><strong>the reflection way</strong></a> to access the private method. </p>\n"
},
{
"answer_id": 26855013,
"author": "Steve Chambers",
"author_id": 1063716,
"author_profile": "https://Stackoverflow.com/users/1063716",
"pm_score": 5,
"selected": false,
"text": "<p>If using Spring, <a href=\"http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html\" rel=\"noreferrer\">ReflectionTestUtils</a> provides some handy tools that help out here with minimal effort. For example, to set up a mock on a private member without being forced to add an undesirable public setter:</p>\n\n<pre><code>ReflectionTestUtils.setField(theClass, \"theUnsettableField\", theMockObject);\n</code></pre>\n"
},
{
"answer_id": 30093076,
"author": "CoronA",
"author_id": 4497253,
"author_profile": "https://Stackoverflow.com/users/4497253",
"pm_score": 3,
"selected": false,
"text": "<p>I recently had this problem and wrote a little tool, called <a href=\"https://github.com/almondtools/picklock\" rel=\"noreferrer\">Picklock</a>, that avoids the problems of explicitly using the Java reflection API, two examples:</p>\n\n<p><strong>Calling methods, e.g. <code>private void method(String s)</code> - by Java reflection</strong></p>\n\n<pre><code>Method method = targetClass.getDeclaredMethod(\"method\", String.class);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, \"mystring\");\n</code></pre>\n\n<p><strong>Calling methods, e.g. <code>private void method(String s)</code> - by Picklock</strong></p>\n\n<pre><code>interface Accessible {\n void method(String s);\n}\n\n...\nAccessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);\na.method(\"mystring\");\n</code></pre>\n\n<p><strong>Setting fields, e.g. <code>private BigInteger amount;</code> - by Java reflection</strong></p>\n\n<pre><code>Field field = targetClass.getDeclaredField(\"amount\");\nfield.setAccessible(true);\nfield.set(object, BigInteger.valueOf(42));\n</code></pre>\n\n<p><strong>Setting fields, e.g. <code>private BigInteger amount;</code> - by Picklock</strong></p>\n\n<pre><code>interface Accessible {\n void setAmount(BigInteger amount);\n}\n\n...\nAccessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);\na.setAmount(BigInteger.valueOf(42));\n</code></pre>\n"
},
{
"answer_id": 31020978,
"author": "Mikhail",
"author_id": 1781357,
"author_profile": "https://Stackoverflow.com/users/1781357",
"pm_score": 6,
"selected": false,
"text": "<p>In the <a href=\"http://en.wikipedia.org/wiki/Spring_Framework\" rel=\"noreferrer\">Spring Framework</a> you can test private methods using this method:</p>\n\n<pre><code>ReflectionTestUtils.invokeMethod()\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>ReflectionTestUtils.invokeMethod(TestClazz, \"createTest\", \"input data\");\n</code></pre>\n"
},
{
"answer_id": 36115967,
"author": "supernova",
"author_id": 538160,
"author_profile": "https://Stackoverflow.com/users/538160",
"pm_score": 6,
"selected": false,
"text": "<p>Another approach I have used is to change a private method to package private or protected then complement it with the <strong>@VisibleForTesting</strong> annotation of the Google Guava library.</p>\n\n<p>This will tell anybody using this method to take caution and not access it directly even in a package. Also a test class need not be in same package <strong>physically</strong>, but in the same package under the <strong>test</strong> folder.</p>\n\n<p>For example, if a method to be tested is in <code>src/main/java/mypackage/MyClass.java</code> then your test call should be placed in <code>src/test/java/mypackage/MyClassTest.java</code>. That way, you got access to the test method in your test class.</p>\n"
},
{
"answer_id": 37591098,
"author": "Olcay Tarazan",
"author_id": 2335016,
"author_profile": "https://Stackoverflow.com/users/2335016",
"pm_score": 4,
"selected": false,
"text": "<p>Please see below for an example;</p>\n\n<p>The following import statement should be added:</p>\n\n<pre><code>import org.powermock.reflect.Whitebox;\n</code></pre>\n\n<p>Now you can directly pass the object which has the private method, method name to be called, and additional parameters as below.</p>\n\n<pre><code>Whitebox.invokeMethod(obj, \"privateMethod\", \"param1\");\n</code></pre>\n"
},
{
"answer_id": 37618628,
"author": "Legna",
"author_id": 2197088,
"author_profile": "https://Stackoverflow.com/users/2197088",
"pm_score": 2,
"selected": false,
"text": "<p>A quick addition to <a href=\"https://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes#34658\">Cem Catikka's answer</a>, when using ExpectedException:</p>\n<p>Keep in mind that your expected exception will be wrapped in an InvocationTargetException, so in order to get to your exception you will have to throw the cause of the InvocationTargetException you received. Something like (testing private method validateRequest() on BizService):</p>\n<pre><code>@Rule\npublic ExpectedException thrown = ExpectedException.none();\n\n@Autowired(required = true)\nprivate BizService svc;\n\n\n@Test\npublic void testValidateRequest() throws Exception {\n\n thrown.expect(BizException.class);\n thrown.expectMessage(expectMessage);\n\n BizRequest request = /* Mock it, read from source - file, etc. */;\n validateRequest(request);\n}\n\nprivate void validateRequest(BizRequest request) throws Exception {\n Method method = svc.getClass().getDeclaredMethod("validateRequest", BizRequest.class);\n method.setAccessible(true);\n try {\n method.invoke(svc, request);\n }\n catch (InvocationTargetException e) {\n throw ((BizException)e.getCause());\n }\n }\n</code></pre>\n"
},
{
"answer_id": 39215279,
"author": "GROX13",
"author_id": 3930424,
"author_profile": "https://Stackoverflow.com/users/3930424",
"pm_score": 4,
"selected": false,
"text": "<p>I would suggest you refactoring your code a little bit. When you have to start thinking about using reflection or other kind of stuff, for just testing your code, something is going wrong with your code.</p>\n<p>You mentioned different types of problems. Let's start with private fields. In case of private fields I would have added a new constructor and injected fields into that. Instead of this:</p>\n<pre><code>public class ClassToTest {\n\n private final String first = "first";\n private final List<String> second = new ArrayList<>();\n ...\n}\n</code></pre>\n<p>I'd have used this:</p>\n<pre><code>public class ClassToTest {\n\n private final String first;\n private final List<String> second;\n\n public ClassToTest() {\n this("first", new ArrayList<>());\n }\n\n public ClassToTest(final String first, final List<String> second) {\n this.first = first;\n this.second = second;\n }\n ...\n}\n</code></pre>\n<p>This won't be a problem even with some legacy code. Old code will be using an empty constructor, and if you ask me, refactored code will look cleaner, and you'll be able to inject necessary values in test without reflection.</p>\n<p>Now about private methods. In my personal experience when you have to stub a private method for testing, then that method has nothing to do in that class. A common pattern, in that case, would be to <em>wrap</em> it within an interface, like <code>Callable</code> and then you pass in that interface also in the constructor (with that multiple constructor trick):</p>\n<pre><code>public ClassToTest() {\n this(...);\n}\n\npublic ClassToTest(final Callable<T> privateMethodLogic) {\n this.privateMethodLogic = privateMethodLogic;\n}\n</code></pre>\n<p>Mostly all that I wrote looks like it's a <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> pattern. In my personal experience it's really useful while testing, and I think that this kind of code is cleaner and will be easier to maintain. I'd say the same about nested classes. If a nested class contains heavy logic it would be better if you'd moved it as a package private class and have injected it into a class needing it.</p>\n<p>There are also several other design patterns which I have used while refactoring and maintaining legacy code, but it all depends on cases of your code to test. Using reflection mostly is not a problem, but when you have an enterprise application which is heavily tested and tests are run before every deployment everything gets really slow (it's just annoying and I don't like that kind of stuff).</p>\n<p>There is also setter injection, but I wouldn't recommended using it. I'd better stick with a constructor and initialize everything when it's really necessary, leaving the possibility for injecting necessary dependencies.</p>\n"
},
{
"answer_id": 46121866,
"author": "Rahul",
"author_id": 7599315,
"author_profile": "https://Stackoverflow.com/users/7599315",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Mockito\" rel=\"nofollow noreferrer\">PowerMockito</a> to set return values for private fields and private methods that are called/used in the private method you want to test:</p>\n<p>For example, setting a return value for a private method:</p>\n<pre><code>MyClient classUnderTest = PowerMockito.spy(new MyClient());\n\n// Set the expected return value\nPowerMockito.doReturn(20).when(classUnderTest, "myPrivateMethod", anyString(), anyInt());\n// This is very important. Otherwise, it will not work\nclassUnderTest.myPrivateMethod();\n\n// Setting the private field value as someValue:\nWhitebox.setInternalState(classUnderTest, "privateField", someValue);\n</code></pre>\n<p>Then finally you can validate your private method under test is returning the correct value based on set values above by:</p>\n<pre><code>String msg = Whitebox.invokeMethod(obj, "privateMethodToBeTested", "param1");\nAssert.assertEquals(privateMsg, msg);\n</code></pre>\n<p>Or</p>\n<p>If the classUnderTest private method does not return a value, but it sets another private field then you can get that private field value to see if it was set correctly:</p>\n<pre><code>// To get the value of a private field\nMyClass obj = Whitebox.getInternalState(classUnderTest, "foo");\nassertThat(obj, is(notNull(MyClass.class))); // Or test value\n</code></pre>\n"
},
{
"answer_id": 47004093,
"author": "Miladinho",
"author_id": 4836141,
"author_profile": "https://Stackoverflow.com/users/4836141",
"pm_score": 2,
"selected": false,
"text": "<p>If you are worried by not testing private methods as many of the posts suggest, consider that a <strong>code coverage</strong> tool will determine exactly how much of your code is tested and where it leaks, so it is quantifiably acceptable to do this.</p>\n<p>Answers that direct the author of the question towards a 'workaround' are doing a massive disservice to the community. Testing is a major part of all engineering disciplines. You would not want to buy a car that is not properly tested, and tested in a meaningful way, so why would anyone want to buy or use software that is tested poorly? The reason people do this anyway is probably because the effects of badly tested software are felt way after the fact, and we don't usually associate them with bodily harm.</p>\n<p>This is a very dangerous perception which will be difficult to change, but it is our responsibility to deliver safe products regardless of what even management is bullying us to do. Think <a href=\"https://en.wikipedia.org/wiki/2017_Equifax_data_breach#Data_breach\" rel=\"nofollow noreferrer\">the Equifax hack</a>...</p>\n<p>We must strive to build an environment that encourages good software engineering practices. This does not mean ostracizing the weak/lazy among us who do not take their craft seriously, but rather, to create a status quo of accountability and self reflection that would encourage everyone to pursue growth, both mentally and skillfully.</p>\n<p>I am still learning, and may have wrong perceptions/opinions myself, but I do firmly believe that we need to hold ourselves accountable to good practices and shun irresponsible hacks or workarounds to problems.</p>\n"
},
{
"answer_id": 47454552,
"author": "Android is everything for me",
"author_id": 1550509,
"author_profile": "https://Stackoverflow.com/users/1550509",
"pm_score": 2,
"selected": false,
"text": "<p>The best and proper legal way to test a Java private method from a test framework is the <strong>@VisibleForTesting</strong> annotation over the method, so the same method will be visible for the test framework like a public method.</p>\n"
},
{
"answer_id": 48182688,
"author": "mohammad madani",
"author_id": 1125774,
"author_profile": "https://Stackoverflow.com/users/1125774",
"pm_score": 3,
"selected": false,
"text": "<p>In <a href=\"https://en.wikipedia.org/wiki/C%2B%2B\" rel=\"nofollow noreferrer\">C++</a>: before including the class header that has a private function that you want to test.</p>\n<p>Use this code:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#define private public\n#define protected public\n</code></pre>\n"
},
{
"answer_id": 48430793,
"author": "Victor Grazi",
"author_id": 522729,
"author_profile": "https://Stackoverflow.com/users/522729",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://meta.stackexchange.com/questions/184108/what-is-syntax-highlighting-and-how-does-it-wok/184109#184109\">PowerMockito</a> is made for this.</p>\n<p>Use a <a href=\"https://en.wikipedia.org/wiki/Apache_Maven\" rel=\"nofollow noreferrer\">Maven</a> dependency:</p>\n<pre class=\"lang-xml prettyprint-override\"><code> <dependency>\n <groupId>org.powermock</groupId>\n <artifactId>powermock-core</artifactId>\n <version>2.0.7</version>\n <scope>test</scope>\n </dependency>\n</code></pre>\n<p>Then you can do</p>\n<pre><code>import org.powermock.reflect.Whitebox;\n...\nMyClass sut = new MyClass();\nSomeType rval = Whitebox.invokeMethod(sut, "myPrivateMethod", params, moreParams);\n</code></pre>\n"
},
{
"answer_id": 51081607,
"author": "HilaB",
"author_id": 8356771,
"author_profile": "https://Stackoverflow.com/users/8356771",
"pm_score": 1,
"selected": false,
"text": "<p>My team and I are using Typemock, which has an API that allows you to <a href=\"https://www.typemock.com/docs/?book=Isolator&page=Documentation%2FHtmlDocs%2Fcontrollingnonpublicmethods.htm\" rel=\"nofollow noreferrer\">fake non-public methods</a>.</p>\n<p>Recently they added the ability to <a href=\"https://www.typemock.com/docs/?book=Isolator&page=Documentation%2FHtmlDocs%2Ffakingnonpublicobjects.htm\" rel=\"nofollow noreferrer\">fake non-visible types</a> and to use <a href=\"https://en.wikipedia.org/wiki/XUnit\" rel=\"nofollow noreferrer\">xUnit</a>.</p>\n"
},
{
"answer_id": 52455476,
"author": "AR1",
"author_id": 2300013,
"author_profile": "https://Stackoverflow.com/users/2300013",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a case where you really need to test a private method/class etc.. directly, you can use reflection as already mentioned in other answers. However if it comes to that, instead of dealing directly with reflection I'd rather use utility classes provided by your framework. For instance, for Java we have:</p>\n<ul>\n<li><p><a href=\"https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ReflectionUtils.html\" rel=\"nofollow noreferrer\">ReflectionUtils</a> in <a href=\"https://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring Framework</a></p>\n</li>\n<li><p><a href=\"https://junit.org/junit5/docs/5.0.3/api/org/junit/platform/commons/util/ReflectionUtils.html\" rel=\"nofollow noreferrer\">ReflectionUtils</a> in <a href=\"https://en.wikipedia.org/wiki/JUnit\" rel=\"nofollow noreferrer\">JUnit</a></p>\n</li>\n</ul>\n<p>As per how to use them, you can find plenty of articles online. Here one that I particularly liked:</p>\n<ul>\n<li><a href=\"https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.util.ReflectionUtils\" rel=\"nofollow noreferrer\">Java Code Examples for org.springframework.util.ReflectionUtils</a></li>\n</ul>\n"
},
{
"answer_id": 53768967,
"author": "Louis Saglio",
"author_id": 7629797,
"author_profile": "https://Stackoverflow.com/users/7629797",
"pm_score": 1,
"selected": false,
"text": "<p>You can create a special public method to proxy the private method to test.\nThe @TestOnly annotation is out of the box available when using IntelliJ.\nThe downside is is that if somebody want to to use the private method in a public context, he can do it. But he will be warned by the annotation and the method name. On IntelliJ a warning will appear when doing it.</p>\n\n<pre><code>import org.jetbrains.annotations.TestOnly\n\nclass MyClass {\n\n private void aPrivateMethod() {}\n\n @TestOnly\n public void aPrivateMethodForTest() {\n aPrivateMethod()\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55588184,
"author": "Ercan",
"author_id": 4308897,
"author_profile": "https://Stackoverflow.com/users/4308897",
"pm_score": 0,
"selected": false,
"text": "<p>There is another approach to test your private methods.\nIf you \"enable assertion\" in run configurations then you can unit test your method inside method itself. For example;</p>\n\n<pre><code>assert (\"Ercan\".equals(person1.name));\nassert (Person.count == 2);\n</code></pre>\n"
},
{
"answer_id": 56100192,
"author": "WesternGun",
"author_id": 4537090,
"author_profile": "https://Stackoverflow.com/users/4537090",
"pm_score": 2,
"selected": false,
"text": "<p><code>PowerMock.Whitebox</code> is the best option I have seen, but when I read its source code, it reads private fields with reflection, so I think I have my answer: </p>\n\n<ul>\n<li>test private internal states(fields) with PowerMock, or just reflection without the overhead of introducing another independency</li>\n<li>for private methods: actually, the upvote for this question itself, and the huge number of comments and answers, shows that it is a very concurrent and controversial topic <strong>where no definite answer could be given to suit every circumstance</strong>. I understand that only contract should be tested, but we also have coverage to consider. Actually, <strong>I doubt that only testing contracts will 100% make a class immune to errors</strong>. Private methods are those who process data in the class where it is defined and thus does not interest other classes, so we cannot simply expose to make it testable. I will <strong>try not to test them</strong>, but when you have to, <strong>just go for it and forget all the answers here</strong>. You know better your situation and restrictions than any other one in the Internet. When you have control over your code, use that. With consideration, but without over-thinking. </li>\n</ul>\n\n<hr>\n\n<p>After some time, when I reconsider it, I still believe this is true, but I saw better approaches.</p>\n\n<p>First of all, <code>Powermock.Whitebox</code> is still usable. </p>\n\n<p>And, Mockito <code>Whitebox</code> has been hidden after v2(the latest version I can find with <code>Whitebox</code> is <code>testImplementation 'org.mockito:mockito-core:1.10.19'</code>) and it has always been part of <code>org.mockito.internal</code> package, which is prone of breaking changes in the future(see <a href=\"https://stackoverflow.com/questions/40280918/what-do-i-use-instead-of-whitebox-in-mockito-2-2-to-set-fields\">this post</a>). So now I tend not to use it. </p>\n\n<p>In Gradle/Maven projects, if you define private methods or fields, there is no other ways then reflection to get access to them, so the first part stays true. But, if you change the visibility to \"package private\", <strong>the tests following the same structure in <code>test</code> package will have access to them.</strong> That is also another important reason why we are encouraged to create the same hierarchy in <code>main</code> and <code>test</code> package. So, when you have control over production code as well as tests, delete that <code>private</code> access modifier may be the best option for you because relatively it does not cause huge impact. And, that makes testing as well as <strong>private method spying</strong> possible.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Autowired\nprivate SomeService service; // with a package private method \"doSomething()\"\n\n@Test\nvoid shouldReturnTrueDoSomething() {\n assertThat(doSomething(input), is(true)); // package private method testing\n}\n\n@Test\nvoid shouldReturnTrueWhenServiceThrowsException() {\n SomeService spy = Mockito.spy(service); // spying real object\n doThrow(new AppException()).when(spy).doSomething(input); // spy package private method\n ...\n\n}\n</code></pre>\n\n<p>When it comes to internal fields, in Spring you have <code>ReflectionUtils.setField()</code>. </p>\n\n<p>At last, sometimes we can bypass the problem itself: if there is a coverage requirement to meet, maybe you can move these private methods into an inner static class and ignore this class in Jacoco. I just found some way to ignore inner class in Jacoco gradle tasks. <a href=\"https://stackoverflow.com/questions/58604955/how-to-ignore-inner-static-classes-in-jacoco-when-using-gradle\">another question</a></p>\n"
},
{
"answer_id": 57010282,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 2,
"selected": false,
"text": "<p>Android has <a href=\"https://developer.android.com/studio/write/annotations.html#visible\" rel=\"nofollow noreferrer\"><code>@VisibleForTesting</code></a> annotation from <code>android.support.annotation</code> package.</p>\n\n<blockquote>\n <p>The <code>@VisibleForTesting</code> annotation indicates that an annotated method is more visible than normally necessary to make the method testable. This annotation has an optional <code>otherwise</code> argument that lets you designate what the visibility of the method should have been if not for the need to make it visible for testing. Lint uses the <code>otherwise</code> argument to enforce the intended visibility.</p>\n</blockquote>\n\n<p>On the practice it means that you should make a method open for testing and the <code>@VisibleForTesting</code> annotation will show a warning.</p>\n\n<p>For example</p>\n\n<pre><code>package com.mypackage;\n\npublic class ClassA {\n\n @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)\n static void myMethod() {\n\n }\n}\n</code></pre>\n\n<p>And when you call ClassA.myMethod() within the same package(com.mypackage) you will see the warning.</p>\n\n<p><a href=\"https://i.stack.imgur.com/25FX3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/25FX3.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 57514468,
"author": "avtomaton",
"author_id": 2915032,
"author_profile": "https://Stackoverflow.com/users/2915032",
"pm_score": 0,
"selected": false,
"text": "<p>For C++ (since C++11) adding the test class as a friend works perfectly and does not break production encapsulation.</p>\n\n<p>Let's suppose that we have some class <code>Foo</code> with some private functions which really require testing, and some class <code>FooTest</code> that should have access to Foo's private members. Then we should write the following:</p>\n\n<pre><code>// prod.h: some production code header\n\n// forward declaration is enough\n// we should not include testing headers into production code\nclass FooTest;\n\nclass Foo\n{\n // that does not affect Foo's functionality\n // but now we have access to Foo's members from FooTest\n friend FooTest;\npublic:\n Foo();\nprivate:\n bool veryComplicatedPrivateFuncThatReallyRequiresTesting();\n}\n</code></pre>\n\n<pre><code>// test.cpp: some test\n#include <prod.h>\n\nclass FooTest\n{\npublic:\n void complicatedFisture() {\n Foo foo;\n ASSERT_TRUE(foo.veryComplicatedPrivateFuncThatReallyRequiresTesting());\n }\n}\n\nint main(int /*argc*/, char* argv[])\n{\n FooTest test;\n test.complicatedFixture(); // and it really works!\n}\n</code></pre>\n"
},
{
"answer_id": 58452308,
"author": "Mukundhan",
"author_id": 6769119,
"author_profile": "https://Stackoverflow.com/users/6769119",
"pm_score": 0,
"selected": false,
"text": "<p>The following <strong>Reflection TestUtil</strong> could be <strong><em>used generically</em></strong> to test the <strong><em>private methods for their atomicity</em></strong>.</p>\n\n<pre><code>import com.google.common.base.Preconditions;\n\nimport org.springframework.test.util.ReflectionTestUtils;\n\n/**\n * <p>\n * Invoker\n * </p>\n *\n * @author\n * @created Oct-10-2019\n */\npublic class Invoker {\n private Object target;\n private String methodName;\n private Object[] arguments;\n\n public <T> T invoke() {\n try {\n Preconditions.checkNotNull(target, \"Target cannot be empty\");\n Preconditions.checkNotNull(methodName, \"MethodName cannot be empty\");\n if (null == arguments) {\n return ReflectionTestUtils.invokeMethod(target, methodName);\n } else {\n return ReflectionTestUtils.invokeMethod(target, methodName, arguments);\n }\n } catch (Exception e) {\n throw e;\n }\n }\n\n public Invoker withTarget(Object target) {\n this.target = target;\n return this;\n }\n\n public Invoker withMethod(String methodName) {\n this.methodName = methodName;\n return this;\n }\n\n public Invoker withArguments(Object... args) {\n this.arguments = args;\n return this;\n }\n\n}\n\nObject privateMethodResponse = new Invoker()\n .withTarget(targetObject)\n .withMethod(PRIVATE_METHOD_NAME_TO_INVOKE)\n .withArguments(arg1, arg2, arg3)\n .invoke();\nAssert.assertNotNutll(privateMethodResponse)\n</code></pre>\n"
},
{
"answer_id": 59762243,
"author": "Vishwas",
"author_id": 4458900,
"author_profile": "https://Stackoverflow.com/users/4458900",
"pm_score": 1,
"selected": false,
"text": "<p>If you are only using <a href=\"https://en.wikipedia.org/wiki/Mockito\" rel=\"nofollow noreferrer\">Mockito</a>:</p>\n<p>You can consider the private method as a part of public method being tested. You can make sure you cover all the cases in private method when testing public method.</p>\n<p>Suppose you are a Mockito-only user (you are not allowed or don't want to use <a href=\"https://de.wikipedia.org/wiki/PowerMock\" rel=\"nofollow noreferrer\">PowerMock</a> or reflection or any such tools) and you don’t want to change the existing code or libraries being tested, this might be the best way.</p>\n<p>The only thing you need to handle if you choose this way is the variables (user-defined objects) declared locally within private methods. If the private method depends on locally declared variable objects and their methods, make sure you declare those user-defined objects globally as private object instead of locally declared objects. You can instantiate these objects locally.</p>\n<p>This allows you to <a href=\"https://en.wikipedia.org/wiki/Mock_object\" rel=\"nofollow noreferrer\">mock</a> these objects and inject them back to testing object. You can also mock (using when/then) their methods.</p>\n<p>This will allow you test private method without errors when testing the public method.</p>\n<p>Advantages</p>\n<ol>\n<li>Code coverage</li>\n<li>Able to test the complete private method.</li>\n</ol>\n<p>Disadvantages</p>\n<ol>\n<li>Scope of the object—if you don't want the object to be exposed to other methods within same class, this might not be your way.</li>\n<li>You might end up testing the private method multiple times when invoked at different public methods and/or in the same method multiple times.</li>\n</ol>\n"
},
{
"answer_id": 60675043,
"author": "Abhishek Sengupta",
"author_id": 9389293,
"author_profile": "https://Stackoverflow.com/users/9389293",
"pm_score": 2,
"selected": false,
"text": "<p>Hey use this utility class if you are on <strong>spring</strong>.</p>\n\n<pre><code>ReflectionTestUtils.invokeMethod(new ClassName(), \"privateMethodName\");\n</code></pre>\n"
},
{
"answer_id": 62632701,
"author": "Ahmed Hussein",
"author_id": 7280140,
"author_profile": "https://Stackoverflow.com/users/7280140",
"pm_score": -1,
"selected": false,
"text": "<p>In your class:</p>\n<pre><code>namespace my_namespace {\n #ifdef UNIT_TEST\n class test_class;\n #endif\n\n class my_class {\n public:\n #ifdef UNIT_TEST\n friend class test_class;\n #endif\n private:\n void fun() { cout << "I am private" << endl; }\n }\n}\n</code></pre>\n<p>In your unit test class:</p>\n<pre><code>#ifndef UNIT_TEST\n #define UNIT_TEST\n#endif\n\n#include "my_class.h"\n\nclass my_namespace::test_class {\n public:\n void fun() { my_obj.fun(); }\n private:\n my_class my_obj;\n}\n\nvoid my_unit_test() {\n test_class test_obj;\n test_obj.fun(); // here you accessed the private function ;)\n}\n</code></pre>\n"
},
{
"answer_id": 63069114,
"author": "m.nguyencntt",
"author_id": 3110488,
"author_profile": "https://Stackoverflow.com/users/3110488",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my <a href=\"https://projectlombok.org/features/\" rel=\"nofollow noreferrer\">Lombok</a> sample:</p>\n<pre><code>public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {\n Student student = new Student();\n\n Field privateFieldName = Student.class.getDeclaredField("name");\n privateFieldName.setAccessible(true);\n privateFieldName.set(student, "Naruto");\n\n Field privateFieldAge = Student.class.getDeclaredField("age");\n privateFieldAge.setAccessible(true);\n privateFieldAge.set(student, "28");\n\n System.out.println(student.toString());\n\n Method privateMethodGetInfo = Student.class.getDeclaredMethod("getInfo", String.class, String.class);\n privateMethodGetInfo.setAccessible(true);\n System.out.println(privateMethodGetInfo.invoke(student, "Sasuke", "29"));\n}\n\n\n@Setter\n@Getter\n@ToString\nclass Student {\n private String name;\n private String age;\n \n private String getInfo(String name, String age) {\n return name + "-" + age;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67065816,
"author": "Rinke",
"author_id": 12592592,
"author_profile": "https://Stackoverflow.com/users/12592592",
"pm_score": 2,
"selected": false,
"text": "<p>I think most answers are too crude. It depends on your code if you should test private methods or not.</p>\n<p>I used private method testing in the past, and I did this by reflection. It works for me. I realize the problems with it, but for me it was the best sollution.</p>\n<p>I have a heavy application that simulates human behaviour in a population of over a million persons. Every person is represented by an object. The main purpose of the application is to follow how something (disease, information, ideas) spreads through the population.</p>\n<p>For this I have methods that pass on the disease or information from one object to another. There is absolutely no reason to make these methods public, for the end user is not interested in one pass from person to person. The end user is only interested in the grand picture of how it spreads through the population. So those methods are private.</p>\n<p>But I want to know for sure if the single act of passing one bit of information from one person to another is doing what it should. Testing it via public user interfaces is also not possible, because it's just not public, and I think it's awkward to make it public just for the purpose of testing. The end output of the application is defined by hundreds of millions of such single steps being performed all the time. I cannot test the end output either, because that has complicated stochastability involved, which makes it too unpredictable to test.</p>\n<p>So the way for me to test the application is by testing a single step of passing information from one person to another person. These are all private methods. And so I use reflection to test that.</p>\n<p>I'm telling this story to show that it's not that plain black and white story. It depends on your application what is best. Under some circumstances, testing private methods via reflection might be your best option.</p>\n<p>If some people here know better solutions in my use case, I'd happily stand corrected of course....</p>\n"
},
{
"answer_id": 67122309,
"author": "Saša",
"author_id": 897373,
"author_profile": "https://Stackoverflow.com/users/897373",
"pm_score": 3,
"selected": false,
"text": "<p>I want to share a rule I have about testing which particularly is related to this topic:</p>\n<blockquote>\n<p>I think that you should never adapt production code in order to\nindulge easer writing of tests.</p>\n</blockquote>\n<p><em>There are a few suggestions in other posts saying you should adapt the original class in order to test a private method - please red this warning first.</em></p>\n<p>If we change the accessibility of a method/field to package private or protected, just in order to have it accessible to tests, then we defeat the purpose of existence of private access directive.</p>\n<p>Why should we have private fields/methods/classes at all when we want to have <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">test-driven development</a>? Should we declare everything as package private, or even public then, so we can test without any effort?—I don't think so.</p>\n<p>From another point of view: <em>Tests should not burden performance and execution of the production application.</em></p>\n<p>If we change production code just for the sake of easier testing, that may burden performance and the execution of the application in some way.</p>\n<p>If someone starts to change private access to package private, then a developer may eventually come up to other "ingenious ideas" about adding even more code to the original class. This would make additional noise to readability and can burden the performance of the application.</p>\n<p>With changing of a private access to some less restrictive, we are opening the possibility to a developer for misusing the new situation in the future development of the application. Instead of enforcing him/her to develop in the proper way, we are tempting him/her with new possibilities and giving him ability to make wrong choices in the future.</p>\n<p>Of course there might be a few exceptions to this rule, but with clear understanding, what is the rule and what is the exception? We need to be absolutely sure we know why that kind of exception is introduced.</p>\n"
},
{
"answer_id": 70938111,
"author": "d3rbastl3r",
"author_id": 2893873,
"author_profile": "https://Stackoverflow.com/users/2893873",
"pm_score": 1,
"selected": false,
"text": "<p>I feel exactly the same ... change the access modifier for a method just to be able to run a test looks for me as a bad idea. Also in our company we had a lot of discussions about it and in my opinion, really nice way to test a private method is to using Java reflection or another framework which making the method testable. I did so multiple times for complex private methods and this helped me to keep the test small, readable and maintainable.</p>\n<p>After I have read all the answers here, I just disagree with persons who say "if you need to test a private method, then there is a code smell" or even "don´t test private methods" ... so I have a little example for you:</p>\n<p>Imagine I have a class with one public method and a couple of private methods:</p>\n<pre><code>public class ConwaysGameOfLife {\n\n private boolean[][] generationData = new boolean[128][128];\n\n /**\n * Compute the next generation and return the new state\n * Also saving the new state in generationData\n */\n public boolean[][] computeNextGeneration() {\n boolean[][] tempData = new boolean[128][128];\n\n for (int yPos=0; yPos<=generationData.length; yPos++) {\n for (int xPos=0; xPos<=generationData[yPos].length; xPos++) {\n int neighbors = countNeighbors(yPos, xPos);\n tempData[yPos][xPos] = determineCellState(neighbors, yPos, xPos);\n }\n }\n\n generationData = tempData;\n return generationData;\n }\n\n /**\n * Counting the neighbors for a cell on given position considering all the edge cases\n *\n * @return the amount of found neighbors for a cell\n */\n private int countNeighbors(int yPos, int xPos) {}\n\n /**\n * Determine the cell state depending on the amount of neighbors of a cell and on a current state of the cell\n *\n * @return the new cell state\n */\n private boolean determineCellState(int neighborsAmount, int yPos, int xPos) {}\n}\n</code></pre>\n<p>So at least for the method "countNeighbors" I need to test eight edge cases and also some general cases (cells directly in the corners, cells directly on the edges of the matrix and cells somewhere in the middle). So if I am only trying to cover all the cases through the "computeNextGeneration" method and after refactoring, some tests are red, it is probably time consuming to identify the place where the bug is.</p>\n<p>If I am testing "determineCellState" and "countNeighbors" separately and after refactoring and optimization, tests of "computeNextGeneration" and "determineCellState" are red, I am pretty sure that the error will be in the "determineCellState" method.</p>\n<p>Also, if you write unit tests for those methods from the beginning, this tests will help you to develop the methods / the algorithms without a need to considering and wrapping other method calls and cases inside the public method. You can just write fast small tests covering your cases in the method ... for example if the test with the name "countNeighbors_should_return_right_amount_of_neighbors_for_the_right_top_corner_cell()" fails, then it is pretty clear where to look for the bug.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
] | How do I use JUnit to test a class that has internal private methods, fields or nested classes?
It seems bad to change the access modifier for a method just to be able to run a test. | If you have somewhat of a legacy **Java** application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use [reflection](http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29).
Internally we're using helpers to get/set `private` and `private static` variables as well as invoke `private` and `private static` methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change `private static final` variables through reflection.
```
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
```
And for fields:
```
Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
```
---
>
> **Notes:**
>
>
> 1. `TargetClass.getDeclaredMethod(methodName, argClasses)` lets you look into `private` methods. The same thing applies for
> `getDeclaredField`.
> 2. The `setAccessible(true)` is required to play around with privates.
>
>
> |
34,579 | <p>I've recently been working with a MySQL database, and using MySQL workbench to design the Database.</p>
<p>When I use the export to SQL function, so I can actually get the layout in to the Database, I get:</p>
<blockquote>
<p>"Error 1005: Cannot create table"</p>
</blockquote>
<p>This appears to be related to Foreign Keys in the create table statement.</p>
<p>Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later? That's a less than ideal solution given the size of the database.</p>
| [
{
"answer_id": 34642,
"author": "joev",
"author_id": 3449,
"author_profile": "https://Stackoverflow.com/users/3449",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into this situation recently when I attempted (in InnoDB tables) to make a foreign key reference to a column that had a different data type.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html\" rel=\"nofollow noreferrer\">MySQL 5.1 Documentation</a></p>\n"
},
{
"answer_id": 34713,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 3,
"selected": false,
"text": "<p>When you get this (and other errors out of the InnoDB engine) issue:</p>\n\n<pre><code>SHOW ENGINE INNODB STATUS;\n</code></pre>\n\n<p>It will give a more detailed reason why the operation couldn't be completed. Make sure to run that from something that'll allow you to scroll or copy the data, as the response is quite long.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655/"
] | I've recently been working with a MySQL database, and using MySQL workbench to design the Database.
When I use the export to SQL function, so I can actually get the layout in to the Database, I get:
>
> "Error 1005: Cannot create table"
>
>
>
This appears to be related to Foreign Keys in the create table statement.
Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later? That's a less than ideal solution given the size of the database. | When you get this (and other errors out of the InnoDB engine) issue:
```
SHOW ENGINE INNODB STATUS;
```
It will give a more detailed reason why the operation couldn't be completed. Make sure to run that from something that'll allow you to scroll or copy the data, as the response is quite long. |
34,581 | <p>I expected the two <code>span</code> tags in the following sample to display next to each other, instead they display one below the other. If I set the <code>width</code> of the class <code>span</code>.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible <code>padding/margin</code> which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
border: none;
}
div.header {
width: 100%;
height: 80px;
vertical-align: top;
}
span.left {
height: 80px;
width: 50%;
display: inline-block;
background-color: pink;
}
span.right {
vertical-align: top;
display: inline-block;
text-align: right;
height: 80px;
width: 50%;
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Test Page</title>
</head>
<body>
<div class='header'>
<span class='left'>Left Span 50% width</span>
<span class='right'>Right Span 50% width</span>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<hr />
<p>Thanks for the explanation. The <code>float:left</code> works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge</p>
| [
{
"answer_id": 34587,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 3,
"selected": true,
"text": "<pre><code>float: left;\n</code></pre>\n\n<p>Try adding that to span.left</p>\n\n<p>It will cause it to float to the left (as suggested by the syntax).</p>\n\n<hr>\n\n<p>I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it.</p>\n\n<p>If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these \"interesting results\" you can use \"clear: left/right/both\" which will cause the block with the clear styling to be under anything floated to the left/right/both. <a href=\"http://w3schools.com/css/pr_class_clear.asp\" rel=\"nofollow noreferrer\">W3Schools</a> have a page on this property too.</p>\n\n<p>And welcome to Stackoverflow.</p>\n"
},
{
"answer_id": 34853,
"author": "rams",
"author_id": 3635,
"author_profile": "https://Stackoverflow.com/users/3635",
"pm_score": 1,
"selected": false,
"text": "<p>I don't like this hack but it seems to do the job both in Firefox and IE6:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>span.right {\n vertical-align:top; \n display:inline-block;\n text-align:right;\n height:80px;\n width:50%;\n *width:100%;\n background-color:red;\n}\n</code></pre>\n\n<p>Note the <code>*width: 100%</code> which seems to satisfy IE6's requirement and is ignored by Firefox.</p>\n"
},
{
"answer_id": 16191163,
"author": "eba",
"author_id": 1237397,
"author_profile": "https://Stackoverflow.com/users/1237397",
"pm_score": 2,
"selected": false,
"text": "<p>This is because inline and inline-block include whitespace (in your case the line break) between the elements. In your case the combined width of the elements is 50%+50%+whitespace > 100%.</p>\n\n<p>You should either put the two elements on the same row in your HTML document (without space)</p>\n\n<pre><code><div class='header'>\n <span class='left'>Left Span 50% width</span><span class='right'>Right Span 50% width</span>\n</div>\n</code></pre>\n\n<p>Or use HTML comments</p>\n\n<pre><code><div class='header'>\n <span class='left'>Left Span 50% width</span><!--\n --><span class='right'>Right Span 50% width</span>\n</div>\n</code></pre>\n\n<p>I myself prefer the latter.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] | I expected the two `span` tags in the following sample to display next to each other, instead they display one below the other. If I set the `width` of the class `span`.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible `padding/margin` which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?
```css
* {
margin: 0;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
border: none;
}
div.header {
width: 100%;
height: 80px;
vertical-align: top;
}
span.left {
height: 80px;
width: 50%;
display: inline-block;
background-color: pink;
}
span.right {
vertical-align: top;
display: inline-block;
text-align: right;
height: 80px;
width: 50%;
background-color: red;
}
```
```html
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div class='header'>
<span class='left'>Left Span 50% width</span>
<span class='right'>Right Span 50% width</span>
</div>
</body>
</html>
```
---
Thanks for the explanation. The `float:left` works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge | ```
float: left;
```
Try adding that to span.left
It will cause it to float to the left (as suggested by the syntax).
---
I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it.
If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these "interesting results" you can use "clear: left/right/both" which will cause the block with the clear styling to be under anything floated to the left/right/both. [W3Schools](http://w3schools.com/css/pr_class_clear.asp) have a page on this property too.
And welcome to Stackoverflow. |
34,588 | <p>When running my application I sometimes get an error about <code>too many files open</code>.</p>
<p>Running <code>ulimit -a</code> reports that the limit is 1024. How do I increase the limit above 1024? </p>
<p><strong>Edit</strong>
<code>ulimit -n 2048</code> results in a permission error.</p>
| [
{
"answer_id": 34645,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 8,
"selected": true,
"text": "<p>You could always try doing a <code>ulimit -n 2048</code>. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit</p>\n\n<p>Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.</p>\n\n<pre><code>set rlim_fd_max = 166384\nset rlim_fd_cur = 8192\n</code></pre>\n\n<p>On OS X, this same data must be set in /etc/sysctl.conf.</p>\n\n<pre><code>kern.maxfilesperproc=166384\nkern.maxfiles=8192\n</code></pre>\n\n<p>Under Linux, these settings are often in /etc/security/limits.conf.</p>\n\n<p>There are two kinds of limits:</p>\n\n<ul>\n<li><strong>soft</strong> limits are simply the currently enforced limits</li>\n<li><strong>hard</strong> limits mark the maximum value which cannot be exceeded by setting a soft limit</li>\n</ul>\n\n<p>Soft limits could be set by any user while hard limits are changeable only by root.\nLimits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.</p>\n\n<p>There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. </p>\n"
},
{
"answer_id": 923369,
"author": "Jonathan Stanton",
"author_id": 5137,
"author_profile": "https://Stackoverflow.com/users/5137",
"pm_score": 7,
"selected": false,
"text": "<p>If you are using Linux and you got the permission error, you will need to raise the allowed limit in the <code>/etc/limits.conf</code> or <code>/etc/security/limits.conf</code> file (where the file is located depends on your specific Linux distribution). </p>\n\n<p>For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the <code>limits.conf</code> file. </p>\n\n<p><code>* hard nofile 10000</code></p>\n\n<p>Then logout and relogin to your system and you should be able to do:</p>\n\n<p><code>ulimit -n 10000</code> </p>\n\n<p>without a permission error. </p>\n"
},
{
"answer_id": 8285278,
"author": "Vikrant Telkar",
"author_id": 1067805,
"author_profile": "https://Stackoverflow.com/users/1067805",
"pm_score": 5,
"selected": false,
"text": "<p>1) Add the following line to <code>/etc/security/limits.conf</code></p>\n\n<pre><code>webuser hard nofile 64000\n</code></pre>\n\n<p>then login as webuser</p>\n\n<pre><code>su - webuser\n</code></pre>\n\n<p>2) Edit following two files for webuser</p>\n\n<p>append <strong>.bashrc and .bash_profile</strong> file by running</p>\n\n<pre><code>echo \"ulimit -n 64000\" >> .bashrc ; echo \"ulimit -n 64000\" >> .bash_profile\n</code></pre>\n\n<p>3) Log out, then log back in and verify that the changes have been made correctly:</p>\n\n<pre><code>$ ulimit -a | grep open\nopen files (-n) 64000\n</code></pre>\n\n<p>Thats it and them boom, boom boom.</p>\n"
},
{
"answer_id": 9521975,
"author": "Sysadmin",
"author_id": 1243439,
"author_profile": "https://Stackoverflow.com/users/1243439",
"pm_score": 3,
"selected": false,
"text": "<p>If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting</p>\n\n<blockquote>\n <p>[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread</p>\n</blockquote>\n\n<p>Try to put <code>ulimit -s unlimited</code> into <code>/etc/init.d/httpd</code>. This does not require a server reboot.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] | When running my application I sometimes get an error about `too many files open`.
Running `ulimit -a` reports that the limit is 1024. How do I increase the limit above 1024?
**Edit**
`ulimit -n 2048` results in a permission error. | You could always try doing a `ulimit -n 2048`. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit
Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.
```
set rlim_fd_max = 166384
set rlim_fd_cur = 8192
```
On OS X, this same data must be set in /etc/sysctl.conf.
```
kern.maxfilesperproc=166384
kern.maxfiles=8192
```
Under Linux, these settings are often in /etc/security/limits.conf.
There are two kinds of limits:
* **soft** limits are simply the currently enforced limits
* **hard** limits mark the maximum value which cannot be exceeded by setting a soft limit
Soft limits could be set by any user while hard limits are changeable only by root.
Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam\_limits.
There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. |
34,595 | <p>What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:</p>
<pre><code>function Hash(key)
return key mod PrimeNumber
end
</code></pre>
<p>(mod is the % operator in C and similar languages)</p>
<p>with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys?</p>
| [
{
"answer_id": 34606,
"author": "Einar",
"author_id": 2964,
"author_profile": "https://Stackoverflow.com/users/2964",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.</p>\n"
},
{
"answer_id": 34652,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<p>There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean.</p>\n\n<p>Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider <em>all</em> information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.</p>\n\n<p>Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste.</p>\n\n<p>This is actually one of the cases where I advise to read what Knuth has to say in <em>The Art of Computer Programming</em>, vol. 3. Another good read is Julienne Walker's <a href=\"http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx\" rel=\"noreferrer\">The Art of Hashing</a>.</p>\n"
},
{
"answer_id": 34681,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 1,
"selected": false,
"text": "<p>A good hash function has the following properties:</p>\n\n<ol>\n<li><p>Given a hash of a message it is computationally infeasible for an attacker to find another message such that their hashes are identical.</p></li>\n<li><p>Given a pair of message, m' and m, it is computationally infeasible to find two such that that h(m) = h(m')</p></li>\n</ol>\n\n<p>The two cases are <em>not</em> the same. In the first case, there is a pre-existing hash that you're trying to find a collision for. In the second case, you're trying to find <em>any</em> two messages that collide. The second task is significantly easier due to the birthday \"paradox.\"</p>\n\n<p>Where performance is not that great an issue, you should always use a secure hash function. There are very clever attacks that can be performed by forcing collisions in a hash. If you use something strong from the outset, you'll secure yourself against these.</p>\n\n<p>Don't use MD5 or SHA-1 in new designs. Most cryptographers, me included, would consider them broken. The principle source of weakness in both of these designs is that the second property, which I outlined above, does not hold for these constructions. If an attacker can generate two messages, m and m', that both hash to the same value they can use these messages against you. SHA-1 and MD5 also suffer from message extension attacks, which can fatally weaken your application if you're not careful.</p>\n\n<p>A more modern hash such as Whirpool is a better choice. It does not suffer from these message extension attacks and uses the same mathematics as AES uses to prove security against a variety of attacks. </p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 236471,
"author": "Myrddin Emrys",
"author_id": 9084,
"author_profile": "https://Stackoverflow.com/users/9084",
"pm_score": 3,
"selected": false,
"text": "<p>There are two major purposes of hashing functions:</p>\n\n<ul>\n<li>to disperse data points uniformly into n bits.</li>\n<li>to securely identify the input data.</li>\n</ul>\n\n<p>It's impossible to recommend a hash without knowing what you're using it for.</p>\n\n<p>If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a <a href=\"http://isthe.com/chongo/tech/comp/fnv/\" rel=\"noreferrer\">variation of FNV</a>. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.</p>\n\n<p>If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. <a href=\"http://www.larc.usp.br/~pbarreto/hflounge.html\" rel=\"noreferrer\">The Hash Function Lounge</a> is a good place to start.</p>\n"
},
{
"answer_id": 626599,
"author": "Nick Van Brunt",
"author_id": 30470,
"author_profile": "https://Stackoverflow.com/users/30470",
"pm_score": 3,
"selected": false,
"text": "<p>This is an example of a good one and also an example of why you would never want to write one.\nIt is a Fowler / Noll / Vo (FNV) Hash which is equal parts computer science genius and pure voodoo:</p>\n\n<pre><code>unsigned fnv_hash_1a_32 ( void *key, int len ) {\n unsigned char *p = key;\n unsigned h = 0x811c9dc5;\n int i;\n\n for ( i = 0; i < len; i++ )\n h = ( h ^ p[i] ) * 0x01000193;\n\n return h;\n}\n\nunsigned long long fnv_hash_1a_64 ( void *key, int len ) {\n unsigned char *p = key;\n unsigned long long h = 0xcbf29ce484222325ULL;\n int i;\n\n for ( i = 0; i < len; i++ )\n h = ( h ^ p[i] ) * 0x100000001b3ULL;\n\n return h;\n}\n</code></pre>\n\n<p>Edit: </p>\n\n<ul>\n<li>Landon Curt Noll recommends on <a href=\"http://www.isthe.com/chongo/tech/comp/fnv/\" rel=\"noreferrer\">his site</a> the FVN-1A algorithm over the original FVN-1 algorithm: The improved algorithm better disperses the last byte in the hash. I adjusted the algorithm accordingly.</li>\n</ul>\n"
},
{
"answer_id": 746727,
"author": "Chris Harris",
"author_id": 90577,
"author_profile": "https://Stackoverflow.com/users/90577",
"pm_score": 6,
"selected": true,
"text": "<p>For doing \"normal\" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.</p>\n\n<p><a href=\"http://www.azillionmonkeys.com/qed/hash.html\" rel=\"noreferrer\">http://www.azillionmonkeys.com/qed/hash.html</a></p>\n\n<p>If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for.</p>\n"
},
{
"answer_id": 16390594,
"author": "Gavriel Feria",
"author_id": 1928927,
"author_profile": "https://Stackoverflow.com/users/1928927",
"pm_score": 1,
"selected": false,
"text": "<p>What you're saying here is you want to have one that uses has collision resistance. Try using SHA-2. Or try using a (good) block cipher in a one way compression function (never tried that before), like AES in Miyaguchi-Preenel mode. The problem with that is that you need to:\n<br>\n<br>\n1) have an IV. Try using the first 256 bits of the fractional parts of Khinchin's constant or something like that.\n2) have a padding scheme. Easy. Barrow it from a hash like MD5 or SHA-3 (Keccak [pronounced 'ket-chak']).\nIf you don't care about the security (a few others said this), look at FNV or lookup2 by Bob Jenkins (actually I'm the first one who reccomends lookup2) Also try MurmurHash, it's fast (check this: .16 cpb).</p>\n"
},
{
"answer_id": 63927109,
"author": "Wolfgang Brehm",
"author_id": 2119377,
"author_profile": "https://Stackoverflow.com/users/2119377",
"pm_score": 1,
"selected": false,
"text": "<p>A good hash function should</p>\n<ol>\n<li>be bijective to not loose information, where possible, and have the least collisions</li>\n<li>cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.</li>\n<li>if used in a cryptographic context there should not exist an efficient way to invert it.</li>\n</ol>\n<p>A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).</p>\n<p>To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with <a href=\"https://www.pcg-random.org/pdf/hmc-cs-2014-0905.pdf\" rel=\"nofollow noreferrer\">PCG</a> for random number generation.</p>\n<p>Useful permutations, among others, are:</p>\n<ul>\n<li>multiplication with an uneven integer</li>\n<li>binary rotations</li>\n<li>xorshift</li>\n</ul>\n<p>Following this recipe we can create our own <a href=\"https://stackoverflow.com/a/57556517/2119377\">hash function</a> or we take <a href=\"https://stackoverflow.com/a/12996028/2119377\">splitmix</a> which is tested and well accepted.</p>\n<p>If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:</p>\n<p>First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or <code>k</code> many applications of <code>(n*(n+1)/2) mod 2^k</code> interspersed with an xorshift when <code>k</code> is the number of bits in the resulting hash.</p>\n"
},
{
"answer_id": 69964280,
"author": "otmar",
"author_id": 5439309,
"author_profile": "https://Stackoverflow.com/users/5439309",
"pm_score": 0,
"selected": false,
"text": "<p>I highly recommend the SMhasher GitHub project <a href=\"https://github.com/rurban/smhasher\" rel=\"nofollow noreferrer\">https://github.com/rurban/smhasher</a> which is a test suite for hash functions. The fastest state-of-the-art non-cryptographic hash functions without known quality problems are listed here: <a href=\"https://github.com/rurban/smhasher#summary\" rel=\"nofollow noreferrer\">https://github.com/rurban/smhasher#summary</a>.</p>\n"
},
{
"answer_id": 74025413,
"author": "cwtuan",
"author_id": 2822680,
"author_profile": "https://Stackoverflow.com/users/2822680",
"pm_score": 0,
"selected": false,
"text": "<p>Different application scenarios have different design requirements for hash algorithms, but a good hash function should have the following three points:</p>\n<ul>\n<li><strong>Collision Resistance</strong>: try to avoid conflicts. If it is difficult to find two inputs that are hashed to the same output, the hash function is anti-collision</li>\n<li><strong>Tamper Resistant</strong>: As long as one byte is changed, its hash value will be very different.</li>\n<li><strong>Computational Efficiency</strong>: Hash table is an algorithm that can make a trade-off between time consumption and space consumption.</li>\n</ul>\n<p>In 2022, we can choose the <a href=\"https://fe-tool.com/en-us/hash/sha256\" rel=\"nofollow noreferrer\">SHA-2</a> family to use in secure encryption, <a href=\"http://localhost:3000/en-us/hash/sha3\" rel=\"nofollow noreferrer\">SHA-3</a> it is safer but has greater performance loss. A safer approach is to add salt and mix encryption., we can choose the SHA-2 family to use in secure encryption, SHA-3 it is safer but has greater performance loss. A safer approach is to add salt and mix encryption.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
] | What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:
```
function Hash(key)
return key mod PrimeNumber
end
```
(mod is the % operator in C and similar languages)
with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys? | For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.
<http://www.azillionmonkeys.com/qed/hash.html>
If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for. |
34,623 | <p>Why would you do an automatic HTML post rather than a simple redirect?</p>
<p>Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known?</p>
<p>eg.</p>
<ol>
<li>User is not logged in and visits your login page.</li>
<li>You detect the user's openID from a cookie.</li>
<li>Form is generated that directly posts to remote OpenID server.</li>
<li>Remote server redirects user back to website.</li>
<li>Website logs in the user.</li>
</ol>
<p>If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out.</p>
<p>I can find very little information on how this spec should be best implemented.</p>
<p>See HTML FORM Redirection in the official specs:</p>
<p><a href="http://openid.net/specs/openid-authentication-2_0.html#indirect_comm" rel="noreferrer">http://openid.net/specs/openid-authentication-2_0.html#indirect_comm</a></p>
<p>I found this out from looking at the <a href="http://openidenabled.com/php-openid/" rel="noreferrer">PHP OpenID Library</a> (version 2.1.1).</p>
<pre><code>// Redirect the user to the OpenID server for authentication.
// Store the token for this authentication so we can verify the
// response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript
// form to send a POST request to the server.
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL(getTrustRoot(),
getReturnTo());
// If the redirect URL can't be built, display an error
// message.
if (Auth_OpenID::isFailure($redirect_url)) {
displayError("Could not redirect to server: " . $redirect_url->message);
} else {
// Send redirect.
header("Location: ".$redirect_url);
}
} else {
// Generate form markup and render it.
$form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated;
// otherwise, render the HTML.
if (Auth_OpenID::isFailure($form_html)) {
displayError("Could not redirect to server: " . $form_html->message);
} else {
print $form_html;
}
}
</code></pre>
| [
{
"answer_id": 35960,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<p>I can think of a couple of reasons:</p>\n\n<ul>\n<li>A modicum of security by obscurity - it's slightly more work to tamper with POST submissions than GET</li>\n<li>Caching and resubmit rules are more restrictive for POST than GET. I'm not entirely sure this would matter for the OpenID use case, though.</li>\n<li>Bots wouldn't follow the POST form, but would follow the redirect. This could impact server load. </li>\n<li>Different browsers have different max lengths for GET requests - but none of them are as large as POST.</li>\n<li>Some browsers will warn on redirect to another domain. They'll also warn if you're submitting POST to a non-HTTPS url.</li>\n<li>By turning JavaScript off, I can have a relatively secure experience, and not be silently redirected to another domain.</li>\n</ul>\n\n<p>I don't know that any of these are a slam-dunk reason to choose POST - unless the amount of data being sent exceeds the querystring length for some major browser.</p>\n"
},
{
"answer_id": 85788,
"author": "keturn",
"author_id": 9585,
"author_profile": "https://Stackoverflow.com/users/9585",
"pm_score": 4,
"selected": true,
"text": "<p>The primary motivation was, as Mark Brackett says, the limits on payload size imposed by using redirects and GET. Some implementations are smart enough to only use POST when the message goes over a certain size, as there are certainly disadvantages to the POST technique. (Chief among them being the fact that your Back button doesn't work.) Other implementations, like the example code you cited, go for simplicity and consistency and leave out that conditional.</p>\n"
},
{
"answer_id": 669298,
"author": "Laurent Fournié",
"author_id": 80861,
"author_profile": "https://Stackoverflow.com/users/80861",
"pm_score": 2,
"selected": false,
"text": "<p>The same approach is used for the SAML Web Browser SSO profile. The primary motivations of using HTML Post redirection are :</p>\n\n<ul>\n<li><p>Virtually unlimited length of the payload : in SAML the payload is a XML document signed with XMLDSig and base64 encoded. It is larger than the usual 1024 characters limitation of URL (a best practice to support not only any browsers but intermediary network devices like Firewall, Reverse Proxy, Load Balancer as well).</p></li>\n<li><p>W3C HTTP standard says that GET is idempotent (the same URL GET executed multiple times should always result in same response) and consequently can be cached along the way while POST is not and must reach the URL target. Response of an OpenID HTML Form POST or SAML HTML Form POST should not be cached. It must reach the target in order to initiate the authenticated session.</p></li>\n</ul>\n\n<p>You could argue that using a HTTP GET redirection would work as well since the URL query always change and you would be right is practice. However, this would be a workaround of the W3C standard, and therefore, should not be a standard but an alternate implementation whenever both end agree with it.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108/"
] | Why would you do an automatic HTML post rather than a simple redirect?
Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known?
eg.
1. User is not logged in and visits your login page.
2. You detect the user's openID from a cookie.
3. Form is generated that directly posts to remote OpenID server.
4. Remote server redirects user back to website.
5. Website logs in the user.
If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out.
I can find very little information on how this spec should be best implemented.
See HTML FORM Redirection in the official specs:
<http://openid.net/specs/openid-authentication-2_0.html#indirect_comm>
I found this out from looking at the [PHP OpenID Library](http://openidenabled.com/php-openid/) (version 2.1.1).
```
// Redirect the user to the OpenID server for authentication.
// Store the token for this authentication so we can verify the
// response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript
// form to send a POST request to the server.
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL(getTrustRoot(),
getReturnTo());
// If the redirect URL can't be built, display an error
// message.
if (Auth_OpenID::isFailure($redirect_url)) {
displayError("Could not redirect to server: " . $redirect_url->message);
} else {
// Send redirect.
header("Location: ".$redirect_url);
}
} else {
// Generate form markup and render it.
$form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated;
// otherwise, render the HTML.
if (Auth_OpenID::isFailure($form_html)) {
displayError("Could not redirect to server: " . $form_html->message);
} else {
print $form_html;
}
}
``` | The primary motivation was, as Mark Brackett says, the limits on payload size imposed by using redirects and GET. Some implementations are smart enough to only use POST when the message goes over a certain size, as there are certainly disadvantages to the POST technique. (Chief among them being the fact that your Back button doesn't work.) Other implementations, like the example code you cited, go for simplicity and consistency and leave out that conditional. |
34,655 | <p>I would like to have an <code>iframe</code> take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?</p>
<p>Are there any workarounds?</p>
| [
{
"answer_id": 34663,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>This CSS snippet should remove the vertical scrollbar:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body {\n overflow-x: hidden;\n overflow-y: hidden;\n} \n</code></pre>\n\n<p>I'm not sure yet about having it take up as much vertical space as it needs, but I'll see if I can't figure it out.</p>\n"
},
{
"answer_id": 34686,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 5,
"selected": true,
"text": "<p>This should set the <code>IFRAME</code> height to its content's height:</p>\n\n<pre><code><script type=\"text/javascript\">\nthe_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;\ndocument.getElementById('the_iframe').height = the_height;\n</script>\n</code></pre>\n\n<p>You may want to add <code>scrolling=\"no\"</code> to your <code>IFRAME</code> to turn off the scrollbars.</p>\n\n<p><em>edit:</em> Oops, forgot to declare <code>the_height</code>.</p>\n"
},
{
"answer_id": 288322,
"author": "Adam",
"author_id": 33503,
"author_profile": "https://Stackoverflow.com/users/33503",
"pm_score": 0,
"selected": false,
"text": "<p>Adding a <code>DOCTYPE</code> declaration to the <code>IFRAME</code> source document will help to calculate the correct value from the line</p>\n\n<pre><code>document.getElementById('the_iframe').contentWindow.document.body.scrollHeight\n</code></pre>\n\n<p>see <a href=\"http://www.w3.org/QA/2002/04/valid-dtd-list.html\" rel=\"nofollow noreferrer\">W3C DOCTYPE for examples</a></p>\n\n<p>I was having problems with both IE and FF as it was rendering the <code>iframe</code> document in 'quirks' mode, until I added the <code>DOCTYPE</code>.</p>\n\n<p>FF/IE/Chrome support: The .scrollHeight doesnt work with Chrome so I have come up with a javascript example using jQuery to set all <code>IFRAME</code> heights on a page based on the iframes content. NOTE: This is for reference pages within the your current domain.</p>\n\n<pre><code><script type=\"text/javascript\">\n $(document).ready(function(){\n $('iframe').each(function(){\n var context = $(this);\n context.load(function(event){ // attach the onload event to the iframe \n var body = $(this.contentWindow.document).find('body');\n if (body.length > 0 && $(body).find('*').length > 0) { // check if iframe has contents\n context.height($(body.get(0)).height() + 20);\n } else {\n context.hide(); // hide iframes with no contents\n }\n });\n });\n });\n</script>\n</code></pre>\n"
},
{
"answer_id": 288456,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<p>The workaround is not to use <code><iframe></code> and preprocess code on server-side.</p>\n"
},
{
"answer_id": 1156747,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Also check out this thread: <a href=\"https://stackoverflow.com/questions/754519/how-does-the-diggbar-dynamically-resize-its-iframes-height-based-on-content-not\">How does the DiggBar dynamically resize its iframe's height based on content not on their domain?</a>.</p>\n\n<p>It addresses the same question.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983/"
] | I would like to have an `iframe` take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?
Are there any workarounds? | This should set the `IFRAME` height to its content's height:
```
<script type="text/javascript">
the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
document.getElementById('the_iframe').height = the_height;
</script>
```
You may want to add `scrolling="no"` to your `IFRAME` to turn off the scrollbars.
*edit:* Oops, forgot to declare `the_height`. |
34,664 | <p>Has anyone found a useful solution to the DesignMode problem when developing controls?</p>
<p>The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.</p>
<p>The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.</p>
<p>The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.</p>
<p>A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!</p>
| [
{
"answer_id": 34696,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>I've never been caught by this myself, but couldn't you just walk back up the Parent chain from the control to see if DesignMode is set anywhere above you?</p>\n"
},
{
"answer_id": 34741,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>DesignMode is a private property (from what I can tell). The answer is to provide a public property that exposes the DesignMode prop. Then you can cascasde back up the chain of user controls until you run into a non-user control or a control that is in design mode. Something like this....</p>\n\n<pre><code> public bool RealDesignMode()\n {\n if (Parent is MyBaseUserControl)\n {\n return (DesignMode ? true : (MyBaseUserControl) Parent.RealDesignMode;\n }\n\n return DesignMode;\n }\n</code></pre>\n\n<p>Where all your UserControls inherit from MyBaseUserControl. Alternatively you could implement an interface that exposes the \"RealDeisgnMode\". </p>\n\n<p>Please note this code is not live code, just off the cuff musings. :)</p>\n"
},
{
"answer_id": 34842,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "<p>I hadn't realised that you can't call Parent.DesignMode (and I have learned something about 'protected' in C# too...)</p>\n\n<p>Here's a reflective version: (I suspect there might be a performance advantage to making designModeProperty a static field)</p>\n\n<pre><code>static bool IsDesignMode(Control control)\n{\n PropertyInfo designModeProperty = typeof(Component).\n GetProperty(\"DesignMode\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n while (designModeProperty != null && control != null)\n {\n if((bool)designModeProperty.GetValue(control, null))\n {\n return true;\n }\n control = control.Parent;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 346806,
"author": "hopla",
"author_id": 40972,
"author_profile": "https://Stackoverflow.com/users/40972",
"pm_score": 5,
"selected": false,
"text": "<p>Why don't you check LicenseManager.UsageMode.\nThis property can have the values LicenseUsageMode.Runtime or LicenseUsageMode.Designtime.</p>\n\n<p>Is you want code to only run in runtime, use the following code:</p>\n\n<pre><code>if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)\n{\n bla bla bla...\n}\n</code></pre>\n"
},
{
"answer_id": 708594,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 7,
"selected": true,
"text": "<p>Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows:</p>\n\n<pre><code>System.ComponentModel.DesignMode property\n\nSystem.ComponentModel.LicenseManager.UsageMode property\n\nprivate string ServiceString()\n{\n if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null) \n return \"Present\";\n else\n return \"Not present\";\n}\n\npublic bool IsDesignerHosted\n{\n get\n {\n Control ctrl = this;\n\n while(ctrl != null)\n {\n if((ctrl.Site != null) && ctrl.Site.DesignMode)\n return true;\n ctrl = ctrl.Parent;\n }\n return false;\n }\n}\npublic static bool IsInDesignMode()\n{\n return System.Reflection.Assembly.GetExecutingAssembly()\n .Location.Contains(\"VisualStudio\"))\n}\n</code></pre>\n\n<p>To try and get a hang on the three solutions proposed, I created a little test solution - with three projects: </p>\n\n<ul>\n<li>TestApp (winforms application), </li>\n<li>SubControl (dll) </li>\n<li>SubSubControl (dll)</li>\n</ul>\n\n<p>I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.</p>\n\n<p>This screenshot shows the result when running.\n<img src=\"https://i.stack.imgur.com/pylfS.png\" alt=\"Screenshot of running\"></p>\n\n<p>This screenshot shows the result with the form open in Visual Studio:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4cgxt.png\" alt=\"Screenshot of not running\"></p>\n\n<p>Conclusion: It would appear that <em>without reflection</em> the only one that is reliable <em>within</em> the constructor is LicenseUsage, and the only one which is reliable <em>outside</em> the constructor is 'IsDesignedHosted' (by <a href=\"https://stackoverflow.com/questions/34664/designmode-with-controls/2693338#2693338\">BlueRaja</a> below)</p>\n\n<p>PS: See ToolmakerSteve's comment below (which I haven't tested): \"Note that <a href=\"https://stackoverflow.com/a/2693338/199364\">IsDesignerHosted</a> answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is <a href=\"https://stackoverflow.com/a/2849244/199364\">test LicenseManager in constructor and cache the result</a>.\"</p>\n"
},
{
"answer_id": 2693338,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://decav.com/blogs/andre/archive/2007/04/18/1078.aspx\" rel=\"noreferrer\">this page</a>:</p>\n\n<p><em>(<strong>[Edit 2013]</strong> Edited to work in constructors, using the method provided by @hopla)</em></p>\n\n<pre><code>/// <summary>\n/// The DesignMode property does not correctly tell you if\n/// you are in design mode. IsDesignerHosted is a corrected\n/// version of that property.\n/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n/// and http://stackoverflow.com/a/2693338/238419 )\n/// </summary>\npublic bool IsDesignerHosted\n{\n get\n {\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n return true;\n\n Control ctrl = this;\n while (ctrl != null)\n {\n if ((ctrl.Site != null) && ctrl.Site.DesignMode)\n return true;\n ctrl = ctrl.Parent;\n }\n return false;\n }\n}\n</code></pre>\n\n<p>I've submitted <a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/553305/designmode-always-returns-false-winforms-designer#\" rel=\"noreferrer\">a bug-report</a> with Microsoft; I doubt it will go anywhere, but vote it up anyways, as this is obviously a bug (whether or not it's <em>\"by design\"</em>).</p>\n"
},
{
"answer_id": 2849244,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 3,
"selected": false,
"text": "<p>I use the LicenseManager method, but cache the value from the constructor for use throughout the lifetime of the instance.</p>\n\n<pre><code>public MyUserControl()\n{\n InitializeComponent();\n m_IsInDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);\n}\n\nprivate bool m_IsInDesignMode = true;\npublic bool IsInDesignMode { get { return m_IsInDesignMode; } }\n</code></pre>\n\n<hr>\n\n<p>VB version:</p>\n\n<pre><code>Sub New()\n InitializeComponent()\n\n m_IsInDesignMode = (LicenseManager.UsageMode = LicenseUsageMode.Designtime)\nEnd Sub\n\nPrivate ReadOnly m_IsInDesignMode As Boolean = True\nPublic ReadOnly Property IsInDesignMode As Boolean\n Get\n Return m_IsInDesignMode\n End Get\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 3822767,
"author": "husayt",
"author_id": 15461,
"author_profile": "https://Stackoverflow.com/users/15461",
"pm_score": 3,
"selected": false,
"text": "<p>This is the method I use inside forms:</p>\n\n<pre><code> /// <summary>\n /// Gets a value indicating whether this instance is in design mode.\n /// </summary>\n /// <value>\n /// <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.\n /// </value>\n protected bool IsDesignMode\n {\n get { return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime; }\n }\n</code></pre>\n\n<p>This way, the result will be correct, even if either of DesignMode or LicenseManager properties fail.</p>\n"
},
{
"answer_id": 7281838,
"author": "Boris B.",
"author_id": 382783,
"author_profile": "https://Stackoverflow.com/users/382783",
"pm_score": 2,
"selected": false,
"text": "<p>Since none of the methods are reliable (DesignMode, LicenseManager) or efficient (Process, recursive checks) I'm using a <code>public static bool Runtime { get; private set }</code> at program level and explicitly setting it inside the Main() method. </p>\n"
},
{
"answer_id": 12526432,
"author": "juFo",
"author_id": 187650,
"author_profile": "https://Stackoverflow.com/users/187650",
"pm_score": 2,
"selected": false,
"text": "<p>We use this code with success:</p>\n\n<pre><code>public static bool IsRealDesignerMode(this Control c)\n{\n if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)\n return true;\n else\n {\n Control ctrl = c;\n\n while (ctrl != null)\n {\n if (ctrl.Site != null && ctrl.Site.DesignMode)\n return true;\n ctrl = ctrl.Parent;\n }\n\n return System.Diagnostics.Process.GetCurrentProcess().ProcessName == \"devenv\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 35041620,
"author": "user2785562",
"author_id": 2785562,
"author_profile": "https://Stackoverflow.com/users/2785562",
"pm_score": 2,
"selected": false,
"text": "<p>My suggestion is an optimization of @blueraja-danny-pflughoeft <a href=\"https://stackoverflow.com/a/2693338/2785562\">reply</a>.\nThis solution doesn't calculate result every time but only at the first time (an object cannot change UsageMode from design to runtime) </p>\n\n<pre><code>private bool? m_IsDesignerHosted = null; //contains information about design mode state\n/// <summary>\n/// The DesignMode property does not correctly tell you if\n/// you are in design mode. IsDesignerHosted is a corrected\n/// version of that property.\n/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n/// and https://stackoverflow.com/a/2693338/238419 )\n/// </summary>\n[Browsable(false)]\npublic bool IsDesignerHosted\n{\n get\n {\n if (m_IsDesignerHosted.HasValue)\n return m_IsDesignerHosted.Value;\n else\n {\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n {\n m_IsDesignerHosted = true;\n return true;\n }\n Control ctrl = this;\n while (ctrl != null)\n {\n if ((ctrl.Site != null) && ctrl.Site.DesignMode)\n {\n m_IsDesignerHosted = true;\n return true;\n }\n ctrl = ctrl.Parent;\n }\n m_IsDesignerHosted = false;\n return false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 54243122,
"author": "RB Davidson",
"author_id": 113730,
"author_profile": "https://Stackoverflow.com/users/113730",
"pm_score": 0,
"selected": false,
"text": "<p>I had to fight this problem recently in Visual Studio 2017 when using nested UserControls. I combine several of the approaches mentioned above and elsewhere, then tweaked the code until I had a decent extension method which works acceptably so far. It performs a sequence of checks, storing the result in static boolean variables so so each check is only performed at most only once at run time. The process may be overkill, but it is keeping the code from executing in studio. Hope this helps someone.</p>\n\n<pre><code> public static class DesignTimeHelper\n {\n private static bool? _isAssemblyVisualStudio;\n private static bool? _isLicenseDesignTime;\n private static bool? _isProcessDevEnv;\n private static bool? _mIsDesignerHosted; \n\n /// <summary>\n /// Property <see cref=\"Form.DesignMode\"/> does not correctly report if a nested <see cref=\"UserControl\"/>\n /// is in design mode. InDesignMode is a corrected that property which .\n /// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n /// and https://stackoverflow.com/a/2693338/238419 )\n /// </summary>\n public static bool InDesignMode(\n this Control userControl,\n string source = null)\n => IsLicenseDesignTime\n || IsProcessDevEnv\n || IsExecutingAssemblyVisualStudio\n || IsDesignerHosted(userControl);\n\n private static bool IsExecutingAssemblyVisualStudio\n => _isAssemblyVisualStudio\n ?? (_isAssemblyVisualStudio = Assembly\n .GetExecutingAssembly()\n .Location.Contains(value: \"VisualStudio\"))\n .Value;\n\n private static bool IsLicenseDesignTime\n => _isLicenseDesignTime\n ?? (_isLicenseDesignTime = LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n .Value;\n\n private static bool IsDesignerHosted(\n Control control)\n {\n if (_mIsDesignerHosted.HasValue)\n return _mIsDesignerHosted.Value;\n\n while (control != null)\n {\n if (control.Site?.DesignMode == true)\n {\n _mIsDesignerHosted = true;\n return true;\n }\n\n control = control.Parent;\n }\n\n _mIsDesignerHosted = false;\n return false;\n }\n\n private static bool IsProcessDevEnv\n => _isProcessDevEnv\n ?? (_isProcessDevEnv = Process.GetCurrentProcess()\n .ProcessName == \"devenv\")\n .Value;\n }\n</code></pre>\n"
},
{
"answer_id": 70761163,
"author": "Mike L",
"author_id": 7292047,
"author_profile": "https://Stackoverflow.com/users/7292047",
"pm_score": 0,
"selected": false,
"text": "<p>I solved this in .NET 5 with the following:</p>\n<pre><code>public static bool InDesignMode()\n{ \n return Process.GetCurrentProcess().ProcessName.Contains("DesignToolsServer");\n}\n</code></pre>\n"
},
{
"answer_id": 74346003,
"author": "PhilH",
"author_id": 5714170,
"author_profile": "https://Stackoverflow.com/users/5714170",
"pm_score": 0,
"selected": false,
"text": "<p>In .Net 6, the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.isancestorsiteindesignmode?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Windows.Forms.Control.IsAncestorSiteInDesignMode)%3Bk(DevLang-csharp)%26rd%3Dtrue&view=windowsdesktop-6.0\" rel=\"nofollow noreferrer\"><code>Control.IsAncestorSiteInDesignMode</code></a> property is available.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
] | Has anyone found a useful solution to the DesignMode problem when developing controls?
The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.
The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.
The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.
A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better! | Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows:
```
System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString()
{
if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null)
return "Present";
else
return "Not present";
}
public bool IsDesignerHosted
{
get
{
Control ctrl = this;
while(ctrl != null)
{
if((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
public static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly()
.Location.Contains("VisualStudio"))
}
```
To try and get a hang on the three solutions proposed, I created a little test solution - with three projects:
* TestApp (winforms application),
* SubControl (dll)
* SubSubControl (dll)
I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.
This screenshot shows the result when running.

This screenshot shows the result with the form open in Visual Studio:

Conclusion: It would appear that *without reflection* the only one that is reliable *within* the constructor is LicenseUsage, and the only one which is reliable *outside* the constructor is 'IsDesignedHosted' (by [BlueRaja](https://stackoverflow.com/questions/34664/designmode-with-controls/2693338#2693338) below)
PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that [IsDesignerHosted](https://stackoverflow.com/a/2693338/199364) answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is [test LicenseManager in constructor and cache the result](https://stackoverflow.com/a/2849244/199364)." |
34,674 | <p>You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C.</p>
<pre><code>myObject.property = YES;
</code></pre>
<p>or</p>
<pre><code>[myObject setProperty:YES];
</code></pre>
<p>Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style?</p>
| [
{
"answer_id": 34688,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I've seen, there isn't a significant performance difference between the two. I'm reasonably certain that in most cases it will be 'compiled' down to the same code.</p>\n\n<p>If you're not sure, try writing a test application that does each method a million times or so, all the while timing how long it takes. That's the only way to be certain (although it may vary on different architecture.)</p>\n"
},
{
"answer_id": 34690,
"author": "Misha M",
"author_id": 3467,
"author_profile": "https://Stackoverflow.com/users/3467",
"pm_score": 3,
"selected": false,
"text": "<p>Check out <a href=\"http://www.cimgf.com/2008/07/08/a-case-against-dot-syntax/\" rel=\"noreferrer\">article from Cocoa is My Girlfriend</a>. The gist of it, is that there is no performance penalty of using one over the other.</p>\n\n<p>However, the notation does make it more difficult to see what is happening with your variables and what your variables are.</p>\n"
},
{
"answer_id": 35636,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 5,
"selected": true,
"text": "<p>Dot notation for property access in Objective-C <strong>is</strong> a message send, just as bracket notation. That is, given this:</p>\n\n<pre><code>@interface Foo : NSObject\n@property BOOL bar;\n@end\n\nFoo *foo = [[Foo alloc] init];\nfoo.bar = YES;\n[foo setBar:YES];\n</code></pre>\n\n<p>The last two lines will compile exactly the same. The only thing that changes this is if a property has a <code>getter</code> and/or <code>setter</code> attribute specified; however, all it does is change what message gets sent, not whether a message is sent:</p>\n\n<pre><code>@interface MyView : NSView\n@property(getter=isEmpty) BOOL empty;\n@end\n\nif ([someView isEmpty]) { /* ... */ }\nif (someView.empty) { /* ... */ }\n</code></pre>\n\n<p>Both of the last two lines will compile identically.</p>\n"
},
{
"answer_id": 61913,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 3,
"selected": false,
"text": "<p>The only time you'll see a performance difference is if you do not mark a property as "nonatomic". Then <code>@synthesize</code> will automatically add synchronization code around the setting of your property, keeping it thread safe - but slower to set and access.</p>\n<p>Thus mostly you probably want to define a property like:</p>\n<pre><code>@property (nonatomic, retain) NSString *myProp;\n</code></pre>\n<p>Personally I find the dot notation generally useful from the standpoint of you not having to think about writing correct setter methods, which is not completely trivial even for nonatomic setters because you must also remember to release the old value properly. Using template code helps but you can always make mistakes and it's generally repetitious code that clutters up classes.</p>\n<p>A pattern to be aware of: if you define the setter yourself (instead of letting <code>@synthesize</code> create it) and start having other side effects of setting a value you should probably make the setter a normal method instead of calling using the property notation.</p>\n<p>Semantically using properties appears to be direct access to the actual value to the caller and anything that varies from that should thus be done via sending a message, not accessing a property (even though they are really both sending messages).</p>\n"
},
{
"answer_id": 77874,
"author": "charles",
"author_id": 9900,
"author_profile": "https://Stackoverflow.com/users/9900",
"pm_score": 0,
"selected": false,
"text": "<p>Also read this blog post on Cocoa with Love:</p>\n\n<p><a href=\"http://cocoawithlove.com/2008/06/speed-test-nsmanagedobject-objc-20.html\" rel=\"nofollow noreferrer\">http://cocoawithlove.com/2008/06/speed-test-nsmanagedobject-objc-20.html</a></p>\n\n<p>There the author compares the speed of custom accessor and dot notations for NSManagedObject, and finds no difference. However, KVC access (setValue:forKey:) appears to be about twice as slow.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] | You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C.
```
myObject.property = YES;
```
or
```
[myObject setProperty:YES];
```
Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style? | Dot notation for property access in Objective-C **is** a message send, just as bracket notation. That is, given this:
```
@interface Foo : NSObject
@property BOOL bar;
@end
Foo *foo = [[Foo alloc] init];
foo.bar = YES;
[foo setBar:YES];
```
The last two lines will compile exactly the same. The only thing that changes this is if a property has a `getter` and/or `setter` attribute specified; however, all it does is change what message gets sent, not whether a message is sent:
```
@interface MyView : NSView
@property(getter=isEmpty) BOOL empty;
@end
if ([someView isEmpty]) { /* ... */ }
if (someView.empty) { /* ... */ }
```
Both of the last two lines will compile identically. |
34,687 | <p>When I try to do any svn command and supply the <code>--username</code> and/or <code>--password</code> options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by <code>--username</code>. Neither <code>--no-auth-cache</code> nor <code>--non-interactive</code> have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt.</p>
<p>For example, logged in as user1:</p>
<pre><code># $ svn update --username 'user2' --password 'password'
# [email protected]'s password:
</code></pre>
<p>Other options work correctly:</p>
<pre><code># $ svn --version --quiet
# 1.3.2
</code></pre>
<p>Why does it prompt me?<br>
And why is it asking for user1's password instead of user2's?<br>
I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords?<br>
Or is it something else entirely?</p>
<p>I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux).</p>
<hr>
<p>Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN:</p>
<pre><code># HOSTNAME=XXXXXX
# TERM=xterm
# SHELL=/bin/sh
# HISTSIZE=1000
# KDE_NO_IPV6=1
# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX
# QTDIR=/usr/lib/qt-3.3
# QTINC=/usr/lib/qt-3.3/include
# SSH_TTY=/dev/pts/2
# USER=XXXXXX
# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
# KDEDIR=/usr
# MAIL=/var/spool/mail/XXXXXX
# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
# INPUTRC=/etc/inputrc
# PWD=/home/users/XXXXXX/my_repository
# KDE_IS_PRELINKED=1
# LANG=en_US.UTF-8
# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
# SHLVL=1
# HOME=/home/users/XXXXXX
# LOGNAME=XXXXXX
# QTLIB=/usr/lib/qt-3.3/lib
# CVS_RSH=ssh
# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22
# LESSOPEN=|/usr/bin/lesspipe.sh %s
# G_BROKEN_FILENAMES=1
# _=/bin/env
# OLDPWD=/home/users/XXXXXX
</code></pre>
| [
{
"answer_id": 34755,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 0,
"selected": false,
"text": "<p>Best I can give you is a \"works for me\" on SVN 1.5. You may try adding <code>--no-auth-cache</code> to your <code>svn update</code> to see if that lets you override more easily.</p>\n\n<p>If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for domain.com (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update.</p>\n"
},
{
"answer_id": 34911,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 6,
"selected": false,
"text": "<p>Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need <code>--no-auth-cache</code> and <code>--non-interactive</code></p>\n\n<p>Here is what I use (no single quotes)</p>\n\n<pre>\n--non-interactive --no-auth-cache --username XXXX --password YYYY\n</pre>\n\n<p>See the <a href=\"http://svnbook.red-bean.com/en/1.4/svn.serverconfig.netmodel.html#svn.serverconfig.netmodel.credcache\" rel=\"noreferrer\"><b>Client Credentials Caching</b> documentation in the svnbook</a> for more information.</p>\n"
},
{
"answer_id": 38386,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 6,
"selected": true,
"text": "<p>The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.</p>\n\n<p>IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?</p>\n\n<p>If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password.</p>\n"
},
{
"answer_id": 44505,
"author": "Matt Kantor",
"author_id": 3625,
"author_profile": "https://Stackoverflow.com/users/3625",
"pm_score": 0,
"selected": false,
"text": "<p>The problem was that the working copy was checked out via svn+ssh (thanks, Thomas). Instead of setting up ssh keys as was suggested, I just checked out a new working copy using svn://domain.com/path/to/repo rather than svn+ssh://domain.com/path/to/repo. Because this working copy is on the same machine as the repository itself, I'm not really missing out on anything, and I can now use the --password and --username options gratuitously. Seems obvious now that I think about it.</p>\n"
},
{
"answer_id": 1002686,
"author": "tjstankus",
"author_id": 104513,
"author_profile": "https://Stackoverflow.com/users/104513",
"pm_score": 4,
"selected": false,
"text": "<p>I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:</p>\n\n<pre>\nHost server.hostname\n User username\n</pre>\n\n<p>I found this blog post helpful: <a href=\"http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html\" rel=\"noreferrer\">http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html</a></p>\n"
},
{
"answer_id": 19704577,
"author": "Znik",
"author_id": 2261349,
"author_profile": "https://Stackoverflow.com/users/2261349",
"pm_score": 0,
"selected": false,
"text": "<p>Look to your local svn repo and look into directory .svn .\nthere is file: entries look into them and you'll see lines begins with:\nsvn+ssh://</p>\n\n<p>this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'</p>\n\n<p>if you want to change this, te best way is completly refresh this repository.\nupdate/commit what you should for save work. then remove completly directory\nand last step is create this by\nsvn co/checkout 'URI-for-main-repo' [optionally local directory for store]</p>\n\n<p>you should select connection method to repo file:// svn+ssh:// http:// https:// or other\ndescribed in documentation.</p>\n\n<p>after that you use svn update/commit as usual.</p>\n\n<p>this topic looks like out of topic. better you go to superuser pages.</p>\n"
},
{
"answer_id": 36519216,
"author": "Andre Holzner",
"author_id": 288875,
"author_profile": "https://Stackoverflow.com/users/288875",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used <code>svn relocate</code> (as described in <a href=\"https://stackoverflow.com/a/13944343/288875\">in this answer</a>. In my case, I'm using svn 1.6.11 and did the following:</p>\n\n<pre><code>svn switch --relocate \\\n svn+ssh://olduser@svnserver/path/to/repo \\\n svn+ssh://newuser@svnserver/path/to/repo\n</code></pre>\n\n<p>where <code>svn+ssh://olduser@svnserver/path/to/repo</code> can be found in the <code>URL:</code> line output of <code>svn info</code> command. This command asked me for the password of <code>newuser</code>. </p>\n\n<p>Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after <code>svn update</code> etc.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625/"
] | When I try to do any svn command and supply the `--username` and/or `--password` options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by `--username`. Neither `--no-auth-cache` nor `--non-interactive` have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt.
For example, logged in as user1:
```
# $ svn update --username 'user2' --password 'password'
# [email protected]'s password:
```
Other options work correctly:
```
# $ svn --version --quiet
# 1.3.2
```
Why does it prompt me?
And why is it asking for user1's password instead of user2's?
I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords?
Or is it something else entirely?
I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux).
---
Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN:
```
# HOSTNAME=XXXXXX
# TERM=xterm
# SHELL=/bin/sh
# HISTSIZE=1000
# KDE_NO_IPV6=1
# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX
# QTDIR=/usr/lib/qt-3.3
# QTINC=/usr/lib/qt-3.3/include
# SSH_TTY=/dev/pts/2
# USER=XXXXXX
# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
# KDEDIR=/usr
# MAIL=/var/spool/mail/XXXXXX
# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
# INPUTRC=/etc/inputrc
# PWD=/home/users/XXXXXX/my_repository
# KDE_IS_PRELINKED=1
# LANG=en_US.UTF-8
# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
# SHLVL=1
# HOME=/home/users/XXXXXX
# LOGNAME=XXXXXX
# QTLIB=/usr/lib/qt-3.3/lib
# CVS_RSH=ssh
# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22
# LESSOPEN=|/usr/bin/lesspipe.sh %s
# G_BROKEN_FILENAMES=1
# _=/bin/env
# OLDPWD=/home/users/XXXXXX
``` | The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.
IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?
If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password. |
34,708 | <p>A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).</p>
<p>It ended up generating values that looked something like this:</p>
<pre><code>Af3nT5Xf2
</code></pre>
<p>Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.</p>
<p>Here's what we ended up doing:</p>
<p>We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.</p>
<p>The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.</p>
<p>I was never satisfied with this particular implementation. What would you guys have done?</p>
| [
{
"answer_id": 34722,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 2,
"selected": false,
"text": "<p>In C#, I have used the '<a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx\" rel=\"nofollow noreferrer\">System.IO.Path.GetRandomFileName() : String</a>' method... but I was generating salt for debug file names. This method returns stuff that looks like your first example, except with a random '.xyz' file extension too.</p>\n\n<p>If you're in .NET and just want a simpler (but not 'nicer' looking) solution, I would say this is it... you could remove the random file extension if you like.</p>\n"
},
{
"answer_id": 34727,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 3,
"selected": false,
"text": "<p>In .NET you can use the RNGCryptoServiceProvider method GetBytes() which will \"fill an array of bytes with a cryptographically strong sequence of random values\" (from ms documentation).</p>\n\n<pre><code>byte[] randomBytes = new byte[4];\nRNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\nrng.GetBytes(randomBytes);\n</code></pre>\n\n<p>You can increase the lengh of the byte array and pluck out the character values you want to allow.</p>\n"
},
{
"answer_id": 34736,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": false,
"text": "<p>Here's how I would do it.</p>\n\n<p>I'd obtain a list of common English words with usage frequency and some grammatical information (like is it a noun or a verb?). I think you can look around the intertubes for some copy. Firefox is open-source and it has a spellchecker... so it must be obtainable somehow.</p>\n\n<p>Then I'd run a filter on it so obscure words are removed and that words which are too long are excluded.</p>\n\n<p>Then my generation algorithm would pick 2 words from the list and concatenate them and add a random 3 digits number.</p>\n\n<p>I can also randomize word selection pattern between verb/nouns like</p>\n\n<blockquote>\n <p><strong>eatCake778<br>\n pickBasket524<br>\n rideFlyer113\n etc..</strong></p>\n</blockquote>\n\n<p>the case needn't be camel casing, you can randomize that as well. You can also randomize the placement of the number and the verb/noun.</p>\n\n<p>And since that's a lot of randomizing, Jeff's <a href=\"http://www.codinghorror.com/blog/archives/001015.html\" rel=\"noreferrer\">The Danger of Naïveté</a> is a must-read. Also make sure to study dictionary attacks well in advance.</p>\n\n<p>And after I'd implemented it, I'd run a test to make sure that my algorithms should never collide. If the collision rate was high, then I'd play with the parameters (amount of nouns used, amount of verbs used, length of random number, total number of words, different kinds of casings etc.)</p>\n"
},
{
"answer_id": 34757,
"author": "Joseph Kingry",
"author_id": 3046,
"author_profile": "https://Stackoverflow.com/users/3046",
"pm_score": 0,
"selected": false,
"text": "<p>If by user friendly, you mean that a user could type the answer in then I think you would want to look in a different direction. I've seen and done implementations for initial random passwords that pick random words and numbers as an easier and less error prone string. </p>\n\n<p>If though you're looking for a way to encode a random code in the URL string which is an issue I've dealt with for awhile then I what I have done is use 64-bit encoded GUIDs.</p>\n"
},
{
"answer_id": 34936,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>You could load your list of words as chakrit suggested into a data table or xml file with a unique sequential key. When getting your random word, use a random number generator to determine what words to fetch by their key. If you concatenate 2 of them, I don't think you need to include the numbers in the string unless \"true randomness\" is part of the goal.</p>\n"
},
{
"answer_id": 62920385,
"author": "Peter O.",
"author_id": 815724,
"author_profile": "https://Stackoverflow.com/users/815724",
"pm_score": 2,
"selected": false,
"text": "<p>At the time of this writing, this question's title is:</p>\n<blockquote>\n<p>How can I generate a unique, small, random, and user-friendly key?</p>\n</blockquote>\n<p>To that, I should note that it's not possible in general to create a <em>random</em> value that's also <em>unique</em>, at least if each random value is generated independently of any other. In addition, there are many things you should ask yourself if you want to generate unique identifiers (which come from my <a href=\"https://peteroupc.github.io/random.html#Unique_Random_Identifiers\" rel=\"nofollow noreferrer\">section on unique random identifiers</a>):</p>\n<ol>\n<li>Can the application easily check identifiers for uniqueness within the desired scope and range (e.g., check whether a file or database record with that identifier already exists)?</li>\n<li>Can the application tolerate the risk of generating the same identifier for different resources?</li>\n<li>Do identifiers have to be hard to guess, be simply "random-looking", or be neither?</li>\n<li>Do identifiers have to be typed in or otherwise relayed by end users?</li>\n<li>Is the resource an identifier identifies available to anyone who knows that identifier (even without being logged in or authorized in some way)?</li>\n<li>Do identifiers have to be memorable?</li>\n</ol>\n<p>In your case, you have several conflicting goals: You want identifiers that are—</p>\n<ul>\n<li>unique,</li>\n<li>easy to type by end users (including small), and</li>\n<li>hard to guess (including random).</li>\n</ul>\n<p>Important points you don't mention in the question include:</p>\n<ul>\n<li>How will the key be used?</li>\n<li>Are other users allowed to access the resource identified by the key, whenever they know the key? If not, then additional access control or a longer key length will be necessary.</li>\n<li>Can your application tolerate the risk of duplicate keys? If so, then the keys can be completely randomly generated (such as by a cryptographic RNG). If not, then your goal will be harder to achieve, especially for keys intended for security purposes.</li>\n</ul>\n<p>Note that I don't go into the issue of formatting a unique value into a "user-friendly key". There are many ways to do so, and they all come down to mapping unique values one-to-one with "user-friendly keys" — if the input value was unique, the "user-friendly key" will likewise be unique.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).
It ended up generating values that looked something like this:
```
Af3nT5Xf2
```
Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.
Here's what we ended up doing:
We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.
The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.
I was never satisfied with this particular implementation. What would you guys have done? | In .NET you can use the RNGCryptoServiceProvider method GetBytes() which will "fill an array of bytes with a cryptographically strong sequence of random values" (from ms documentation).
```
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
```
You can increase the lengh of the byte array and pluck out the character values you want to allow. |
34,712 | <p>I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.</p>
<p>Any ideas about how to detect which mode the user is in and re-format the forms on the fly?</p>
<hr>
<p>Post Answer Edit:</p>
<p>Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.</p>
<p>I'm doing the following:</p>
<p><strong>Function Declaration:</strong>
<pre><code> Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
</pre></code></p>
<p><strong><em>Code Body:</em></strong>
<pre><code>
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)</p>
<p>GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
</pre></code></p>
<p>The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.</p>
| [
{
"answer_id": 34724,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>There's the <a href=\"http://msdn.microsoft.com/en-us/library/bb759813%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">IsThemeActive</a> WinAPI function.</p>\n"
},
{
"answer_id": 34729,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": true,
"text": "<p>Try using a combination of <a href=\"http://www.pinvoke.net/default.aspx/uxtheme/GetCurrentThemeName.html\" rel=\"nofollow noreferrer\">GetCurrentThemeName</a> (<a href=\"http://msdn.microsoft.com/en-us/library/bb773365%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">MSDN Page</a>) and <a href=\"http://msdn.microsoft.com/en-us/library/aa969518%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">DwmIsCompositionEnabled</a></p>\n\n<p>I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment:</p>\n\n<pre><code>[DllImport(\"dwmapi.dll\", PreserveSig = false)]\npublic static extern bool DwmIsCompositionEnabled();\n</code></pre>\n\n<p>See what results you get out of those two functions; they should be enough to determine when you want to use a different theme!</p>\n"
},
{
"answer_id": 104081,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I use the following to see if the app is running under themed:</p>\n\n<pre><code>if (Application.RenderWithVisualStyles)\n{\n // you're themed\n}\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3648/"
] | I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.
Any ideas about how to detect which mode the user is in and re-format the forms on the fly?
---
Post Answer Edit:
Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.
I'm doing the following:
**Function Declaration:**
```
Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
```
***Code Body:***
```
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)
```
GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue. | Try using a combination of [GetCurrentThemeName](http://www.pinvoke.net/default.aspx/uxtheme/GetCurrentThemeName.html) ([MSDN Page](http://msdn.microsoft.com/en-us/library/bb773365%28VS.85%29.aspx)) and [DwmIsCompositionEnabled](http://msdn.microsoft.com/en-us/library/aa969518%28VS.85%29.aspx)
I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment:
```
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
```
See what results you get out of those two functions; they should be enough to determine when you want to use a different theme! |
34,732 | <p>How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).</p>
<p>I'm using gcc 4.0.2, if that makes a difference.</p>
| [
{
"answer_id": 34758,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the <code>nm -g</code> tool from the binutils toolchain. However, their source is not always readily available. and I'm not actually even sure that this information can always be retrieved. Perhaps <code>objcopy</code> reveals further information.</p>\n\n<p>/EDIT: The tool's name is of course <code>nm</code>. The flag <code>-g</code> is used to show only exported symbols.</p>\n"
},
{
"answer_id": 34796,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 10,
"selected": true,
"text": "<p>The standard tool for listing symbols is <code>nm</code>, you can use it simply like this:</p>\n\n<pre><code>nm -gD yourLib.so\n</code></pre>\n\n<p>If you want to see symbols of a C++ library, add the \"-C\" option which demangle the symbols (it's far more readable demangled).</p>\n\n<pre><code>nm -gDC yourLib.so\n</code></pre>\n\n<p>If your .so file is in elf format, you have two options:</p>\n\n<p>Either <code>objdump</code> (<code>-C</code> is also useful for demangling C++):</p>\n\n<pre><code>$ objdump -TC libz.so\n\nlibz.so: file format elf64-x86-64\n\nDYNAMIC SYMBOL TABLE:\n0000000000002010 l d .init 0000000000000000 .init\n0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free\n0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location\n0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable\n</code></pre>\n\n<p>Or use <code>readelf</code>:</p>\n\n<pre><code>$ readelf -Ws libz.so\nSymbol table '.dynsym' contains 112 entries:\n Num: Value Size Type Bind Vis Ndx Name\n 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND\n 1: 0000000000002010 0 SECTION LOCAL DEFAULT 10\n 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)\n 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)\n 4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable\n</code></pre>\n"
},
{
"answer_id": 35328,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 4,
"selected": false,
"text": "<p>Try adding -l to the nm flags in order to get the source of each symbol. If the library is compiled with debugging info (gcc -g) this should be the source file and line number. As Konrad said, the object file / static library is probably unknown at this point.</p>\n"
},
{
"answer_id": 1620583,
"author": "P Shved",
"author_id": 158676,
"author_profile": "https://Stackoverflow.com/users/158676",
"pm_score": 7,
"selected": false,
"text": "<p>If your <code>.so</code> file is in elf format, you can use readelf program to extract symbol information from the binary. This command will give you the symbol table:</p>\n\n<pre><code>readelf -Ws /usr/lib/libexample.so\n</code></pre>\n\n<p>You only should extract those that are defined in this <code>.so</code> file, not in the libraries referenced by it. Seventh column should contain a number in this case. You can extract it by using a simple regex:</p>\n\n<pre><code>readelf -Ws /usr/lib/libstdc++.so.6 | grep '^\\([[:space:]]\\+[^[:space:]]\\+\\)\\{6\\}[[:space:]]\\+[[:digit:]]\\+'\n</code></pre>\n\n<p>or, as proposed by <a href=\"https://stackoverflow.com/users/28817/caspin\">Caspin</a>,:</p>\n\n<pre><code>readelf -Ws /usr/lib/libstdc++.so.6 | awk '{print $8}';\n</code></pre>\n"
},
{
"answer_id": 2073825,
"author": "Pavel Lapin",
"author_id": 212229,
"author_profile": "https://Stackoverflow.com/users/212229",
"pm_score": 6,
"selected": false,
"text": "<pre><code>objdump -TC /usr/lib/libexample.so\n</code></pre>\n"
},
{
"answer_id": 3657200,
"author": "Peter Remmers",
"author_id": 255776,
"author_profile": "https://Stackoverflow.com/users/255776",
"pm_score": 5,
"selected": false,
"text": "<p>I kept wondering why <em>-fvisibility=hidden</em> and <em>#pragma GCC visibility</em> did not seem to have any influence, as all the symbols were always visible with <em>nm</em> - until I found this post that pointed me to <em>readelf</em> and <em>objdump</em>, which made me realize that there seem to actually be <strong>two</strong> symbol tables:</p>\n\n<ul>\n<li>The one you can list with <em>nm</em></li>\n<li>The one you can list with <em>readelf</em> and <em>objdump</em></li>\n</ul>\n\n<p>I think the former contains debugging symbols that can be stripped with <em>strip</em> or the -s switch that you can give to the linker or the <em>install</em> command. And even if nm does not list anything anymore, your exported symbols are still exported because they are in the ELF \"dynamic symbol table\", which is the latter.</p>\n"
},
{
"answer_id": 4152074,
"author": "zhaorufei",
"author_id": 64469,
"author_profile": "https://Stackoverflow.com/users/64469",
"pm_score": 3,
"selected": false,
"text": "<p>nm -g list the extern variable, which is not necessary exported symbol.\nAny non-static file scope variable(in C) are all extern variable.</p>\n\n<p>nm -D will list the symbol in the dynamic table, which you can find it's address by dlsym.</p>\n\n<p>nm --version </p>\n\n<p>GNU nm 2.17.50.0.6-12.el5 20061020</p>\n"
},
{
"answer_id": 14737593,
"author": "cavila",
"author_id": 936787,
"author_profile": "https://Stackoverflow.com/users/936787",
"pm_score": 5,
"selected": false,
"text": "<p>For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux</p>\n\n<pre><code>nm -D libNAME.so\n</code></pre>\n\n<p>and for static library as reported by others</p>\n\n<pre><code>nm -g libNAME.a\n</code></pre>\n"
},
{
"answer_id": 26739013,
"author": "Adi Shavit",
"author_id": 135862,
"author_profile": "https://Stackoverflow.com/users/135862",
"pm_score": 4,
"selected": false,
"text": "<p>For Android <code>.so</code> files, the NDK toolchain comes with the required tools mentioned in the other answers: <code>readelf</code>, <code>objdump</code> and <code>nm</code>.</p>\n"
},
{
"answer_id": 48122967,
"author": "user7610",
"author_id": 1047788,
"author_profile": "https://Stackoverflow.com/users/1047788",
"pm_score": 5,
"selected": false,
"text": "<p>For C++ <code>.so</code> files, the ultimate <code>nm</code> command is <code>nm --demangle --dynamic --defined-only --extern-only <my.so></code></p>\n\n<pre><code># nm --demangle --dynamic --defined-only --extern-only /usr/lib64/libqpid-proton-cpp.so | grep work | grep add\n0000000000049500 T proton::work_queue::add(proton::internal::v03::work)\n0000000000049580 T proton::work_queue::add(proton::void_function0&)\n000000000002e7b0 W proton::work_queue::impl::add_void(proton::internal::v03::work)\n000000000002b1f0 T proton::container::impl::add_work_queue()\n000000000002dc50 T proton::container::impl::container_work_queue::add(proton::internal::v03::work)\n000000000002db60 T proton::container::impl::connection_work_queue::add(proton::internal::v03::work)\n</code></pre>\n\n<p>source: <a href=\"https://stackoverflow.com/a/43257338\">https://stackoverflow.com/a/43257338</a></p>\n"
},
{
"answer_id": 54591492,
"author": "Craig Ringer",
"author_id": 398670,
"author_profile": "https://Stackoverflow.com/users/398670",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want to know if there are symbols <em>present</em> you can use</p>\n\n<pre><code>objdump -h /path/to/object\n</code></pre>\n\n<p>or to list the debug info</p>\n\n<pre><code>objdump -g /path/to/object\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] | How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).
I'm using gcc 4.0.2, if that makes a difference. | The standard tool for listing symbols is `nm`, you can use it simply like this:
```
nm -gD yourLib.so
```
If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled).
```
nm -gDC yourLib.so
```
If your .so file is in elf format, you have two options:
Either `objdump` (`-C` is also useful for demangling C++):
```
$ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE:
0000000000002010 l d .init 0000000000000000 .init
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location
0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable
```
Or use `readelf`:
```
$ readelf -Ws libz.so
Symbol table '.dynsym' contains 112 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000002010 0 SECTION LOCAL DEFAULT 10
2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)
4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
``` |
34,768 | <p>I have recently installed .net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set:</p>
<pre><code><form id="theForm" runat="server" action="post.aspx">
</code></pre>
<p>I received this error.<br>
Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'.<br>
If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this?</p>
| [
{
"answer_id": 34776,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know the specific solution, but HtmlForm.set_Action() is a function the compiler creates that acts as the setter for a property called Action.</p>\n\n<p>When you do:</p>\n\n<pre><code>public String Action { set { DoStuff(); } }\n</code></pre>\n\n<p>The <strong>set</strong> code actually becomes a function called <strong>set_Action</strong>.</p>\n\n<p>I know it's not the best answer, but I hope it helps you find the source of your problems!</p>\n"
},
{
"answer_id": 34810,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://johnsheehan.me/blog/less-code-is-fun-aspnet-35-sp1-removes-need-for-control-adapter-when-using-url-rewriting/\" rel=\"nofollow noreferrer\">.NET 3.5 SP1 tries to use the action=\"\" attribute</a> (.NET 3.5 RTM did not). So, when you deploy, your code is attempting to set the HtmlForm.Action property and failing, as the System.Web.dll on the deploy target is RTM and does not have a setter on the property.</p>\n"
},
{
"answer_id": 280868,
"author": "Lea Cohen",
"author_id": 278,
"author_profile": "https://Stackoverflow.com/users/278",
"pm_score": 0,
"selected": false,
"text": "<p>I just ran into the same problem.\nFrom what I understood it is indeed caused by the fact the my PC has .NET 3.5 SP1 on it, and the server to which I deployed the project doesn't.<br>\nFrom what I understand, one solution is that the server be updated with .NET 3.5 SP1. As I don't want to do that yet, I just removed the \"action\" attribute from all the forms in the project, and that solved the problem.<br>\n<a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361981&wa=wsignin1.0\" rel=\"nofollow noreferrer\">Read more</a></p>\n"
},
{
"answer_id": 1272718,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>All mentioned above is true...</p>\n\n<p>In fact, when one installs 3.5 SP1, it automatically updates 2.0 and 3.0 with their own SP2.\nSo, if you are using 2.0 for an application, you'll get the error.</p>\n\n<p>In addition, SP1 on .Net2.0 did not cause the problem.</p>\n"
},
{
"answer_id": 1320343,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>There is another solution to this.\nWrite a JavaScript that would set the action of the form to the expected URL at Page_Load and register the script at page load.</p>\n"
},
{
"answer_id": 1506252,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It is enough to install Framework 3.6 sp1 which does work fine.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2903/"
] | I have recently installed .net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set:
```
<form id="theForm" runat="server" action="post.aspx">
```
I received this error.
Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set\_Action(System.String)'.
If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this? | [.NET 3.5 SP1 tries to use the action="" attribute](http://johnsheehan.me/blog/less-code-is-fun-aspnet-35-sp1-removes-need-for-control-adapter-when-using-url-rewriting/) (.NET 3.5 RTM did not). So, when you deploy, your code is attempting to set the HtmlForm.Action property and failing, as the System.Web.dll on the deploy target is RTM and does not have a setter on the property. |
34,784 | <p>What is a good setup for .hgignore file when working with Visual Studio 2008?</p>
<p>I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.</p>
<p>I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?</p>
<p>Thanks!</p>
<p>p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.</p>
<pre><code># regexp syntax.
syntax: glob
*.pdb
syntax: regexp
/obj/
</code></pre>
| [
{
"answer_id": 34805,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 5,
"selected": false,
"text": "<p>This is specific to a C# project, but I ignore these files/directories:</p>\n\n<blockquote>\n <ul>\n <li><code>*.csproj.user</code></li>\n <li><code>/obj/*</code></li>\n <li><code>/bin/*</code></li>\n <li><code>*.ncb</code></li>\n <li><code>*.suo</code></li>\n </ul>\n</blockquote>\n\n<p>I have no problems running the code in the depot on other machines after I ignore all of these files. The easiest way to find out what you need to keep is to make a copy of the folder and start deleting things you think aren't necessary. Keep trying to build, and as long as you can build successfully keep on deleting. If you delete too much, copy it from the source folder.</p>\n\n<p>In the end you'll have a nice directory full of the only files that have to be committed.</p>\n"
},
{
"answer_id": 226447,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the content of my .hgignore for C# Visual Studio projects:</p>\n\n<pre><code>syntax: glob\n*.user\n*.ncb\n*.nlb\n*.suo\n*.aps\n*.clw\n*.pdb\n*\\Debug\\*\n*\\Release\\*\n</code></pre>\n\n<p>A few notes:</p>\n\n<ol>\n<li>If you have custom \"releases\"\nbesides \"Debug\" and \"Release\", you\nmay need to add them. </li>\n<li>Be careful when you manually edit your\n.hgignore. If you make a syntax\nerror, then hgtortoise will no\nlonger open the commit dialog.</li>\n</ol>\n"
},
{
"answer_id": 744333,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 9,
"selected": true,
"text": "<p>Here's my standard .hgignore file for use with VS2008 that was originally modified from a Git ignore file:</p>\n\n<pre><code># Ignore file for Visual Studio 2008\n\n# use glob syntax\nsyntax: glob\n\n# Ignore Visual Studio 2008 files\n*.obj\n*.exe\n*.pdb\n*.user\n*.aps\n*.pch\n*.vspscc\n*_i.c\n*_p.c\n*.ncb\n*.suo\n*.tlb\n*.tlh\n*.bak\n*.cache\n*.ilk\n*.log\n*.lib\n*.sbr\n*.scc\n[Bb]in\n[Dd]ebug*/\nobj/\n[Rr]elease*/\n_ReSharper*/\n[Tt]est[Rr]esult*\n[Bb]uild[Ll]og.*\n*.[Pp]ublish.xml\n</code></pre>\n"
},
{
"answer_id": 2294025,
"author": "AlGonzalez",
"author_id": 276368,
"author_profile": "https://Stackoverflow.com/users/276368",
"pm_score": 3,
"selected": false,
"text": "<p>My Mercurial .hgignore file contents:</p>\n\n<pre><code>syntax: glob\n#-- Files\n*.bak.*\n*.bak\nthumbs.db\n\n#-- Directories\nApp_Data/*\nbin/\nobj/\n_ReSharper.*/\ntmp/\n\n#-- Microsoft Visual Studio specific\n*.user\n*.suo\n\n#-- MonoDevelop specific\n*.pidb\n*.userprefs\n*.usertasks\n</code></pre>\n\n<p>Keep in mind that I mainly work on WinForms, ASP.NET MVC and Mobile projects using Microsoft Visual Studio and occasionally MonoDevelop. Depending on your toolset and project types, you will probably encounter other files that should be ignored.</p>\n\n<p>I try to keep the latest version on CodePaste.NET at <a href=\"http://codepaste.net/zxov7i\" rel=\"noreferrer\">http://codepaste.net/zxov7i</a></p>\n"
},
{
"answer_id": 2555413,
"author": "Damian Powell",
"author_id": 30321,
"author_profile": "https://Stackoverflow.com/users/30321",
"pm_score": 5,
"selected": false,
"text": "<p>I feel left out of the conversation. Here's my .hgignore file. It covers C#, C++ and Visual Studio development in general, including COM stuff (type libraries), some final builder files, CodeRush, ReSharper, and Visual Studio project upgrades. It also has some ignores for modern (c.2015) web development.</p>\n\n<pre><code>syntax: glob\n\n* - [Cc]opy\n* - [Cc]opy/\n* - [Cc]opy (?)/\n* - [Cc]opy.*\n* - [Cc]opy (?).*\n**/.*\n**/scss/*.css\n*.*scc\n*.FileListAbsolute.txt\n*.aps\n*.bak\n*.bin\n*.[Cc]ache\n*.clw\n*.css.map\n*.eto\n*.exe\n*.fb6lck\n*.fbl6\n*.fbpInf\n*.ilk\n*.lib\n*.log\n*.ncb\n*.nlb\n*.nupkg\n*.obj\n*.old\n*.orig\n*.patch\n*.pch\n*.pdb\n*.plg\n*.[Pp]ublish.xml\n*.rdl.data\n*.sbr\n*.scc\n*.sig\n*.sqlsuo\n*.suo\n*.svclog\n*.tlb\n*.tlh\n*.tli\n*.tmp\n*.user\n*.vshost.*\n*.docstates\n*DXCore.Solution\n*_i.c\n*_p.c\n__MVC_BACKUP/\n_[Rr]e[Ss]harper.*/\n_UpgradeReport_Files/\nAnkh.Load\nBackup*\n[Bb]in/\nbower_components/\n[Bb]uild/\nCVS/\n[Dd]ebug/\n[Ee]xternal/\nhgignore[.-]*\nignore[.-]*\nlint.db\nnode_modules/\n[Oo]bj/\n[Pp]ackages/\nPrecompiledWeb/\n[Pp]ublished/\n[Rr]elease/\nsvnignore[.-]*\n[Tt]humbs.db\nUpgradeLog*.*\n</code></pre>\n"
},
{
"answer_id": 2578567,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 2,
"selected": false,
"text": "<p>some others I use:</p>\n\n<pre><code>output\nPrecompiledWeb\n_UpgradeReport_Files\n\n#Guidance Automation Toolkit\n*.gpState\n#patches\n*.patch\n</code></pre>\n"
},
{
"answer_id": 7798061,
"author": "Nathan Donnellan",
"author_id": 997216,
"author_profile": "https://Stackoverflow.com/users/997216",
"pm_score": 2,
"selected": false,
"text": "<p>Here are a couple pesky ones: Matlab and Excel/Office autosaves.</p>\n\n<pre><code># use glob syntax\nsyntax: glob\n\n# Matlab ignore files\n*.asv\n\n# Microsoft Office\n~$*\n</code></pre>\n\n<p>If I accidentally add them and then close the real file that was open, Excel and/or Matlab will delete the auto-save and then Mercurial will be stuck wondering where they went. I'm sure there are other programs that do similar things.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] | What is a good setup for .hgignore file when working with Visual Studio 2008?
I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.
I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?
Thanks!
p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.
```
# regexp syntax.
syntax: glob
*.pdb
syntax: regexp
/obj/
``` | Here's my standard .hgignore file for use with VS2008 that was originally modified from a Git ignore file:
```
# Ignore file for Visual Studio 2008
# use glob syntax
syntax: glob
# Ignore Visual Studio 2008 files
*.obj
*.exe
*.pdb
*.user
*.aps
*.pch
*.vspscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.cache
*.ilk
*.log
*.lib
*.sbr
*.scc
[Bb]in
[Dd]ebug*/
obj/
[Rr]elease*/
_ReSharper*/
[Tt]est[Rr]esult*
[Bb]uild[Ll]og.*
*.[Pp]ublish.xml
``` |
34,790 | <p>The <code>datepicker</code> function only works on the first input box that is created.</p>
<p>I'm trying to duplicate a datepicker by cloning the <code>div</code> that is containing it.</p>
<pre><code><a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>
</code></pre>
<p>To initialize the datepicker, according to the <a href="http://docs.jquery.com/UI/Datepicker" rel="nofollow noreferrer">jQuery UI documentation</a> I only have to do <code>$('#example').datepicker();</code> and it does work, but only on the first datepicker that is created.</p>
<p>The code to duplicate the <code>div</code> is the following:</p>
<pre><code>$("a#dupMe").click(function(event){
event.preventDefault();
i++;
var a = $("#template")
.clone(true)
.insertBefore("#template")
.hide()
.fadeIn(1000);
a.find("input#txt").attr('value', i);
a.find("input#example").datepicker();
});
</code></pre>
<p>The strangest thing is that on the <code>document.ready</code> I have:</p>
<pre><code>$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });
</code></pre>
<p>and if I click on the <code>#txt</code> it always works.</p>
| [
{
"answer_id": 34807,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": false,
"text": "<p>I use a CSS class instead:</p>\n\n<pre><code><input type=\"text\" id=\"BeginDate\" class=\"calendar\" />\n<input type=\"text\" id=\"EndDate\" class=\"calendar\" />\n</code></pre>\n\n<p>Then, in your <code>document.ready</code> function:</p>\n\n<pre><code>$('.calendar').datepicker();\n</code></pre>\n\n<p>Using it that way for multiple calendar fields works for me.</p>\n"
},
{
"answer_id": 34855,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 4,
"selected": true,
"text": "<p>I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template <code>div</code> (to be called after each duplication). Something like:</p>\n\n<pre><code>function makeDatePickers() {\n $(\"#template input[type=text]\").datepicker();\n}\n</code></pre>\n"
},
{
"answer_id": 1423156,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I had a very similar problem which after hours of testing I found a solution. I was copying a block of HTML code and inserting it after a section that already contained a jQuery date picker calendar. What I failed to realize at first was the jQuery UI calendar modifies the class of the element when executing the <code>.datepicker()</code> function. The result is when you try to copy the code and initiate a new instance of the calendar for that new section it fails because the according to the CSS there already is one. If you attempt to use <code>.datepicker('destroy')</code> this fails to destroy this ghost instance because it doesn't actually exist. I solved the problem by resetting the class of the date picker element in my HTML then adding the datepicker to that element...</p>\n\n<p>Below is the code I was using. Hopefully this saves someone else some time...</p>\n\n<pre><code>$('#addaddress').click(function() {\n var count = $('.address_template').size();\n var html = $('.address_template').eq(0).html();\n $('#addaddress').before('<div class=\"address_template\">' + html + '</div>');\n $('.address_template H1').eq(count).html(\"Previous Address \" + count);\n $('.address_date').eq(count).attr(\"class\",\"address_date\");\n $('.address_date').eq(count).attr(\"id\",\"movein\" + count);\n $(\"#movein\" + count).datepicker();\n});\n</code></pre>\n"
},
{
"answer_id": 9199379,
"author": "philip_kobernik",
"author_id": 1128839,
"author_profile": "https://Stackoverflow.com/users/1128839",
"pm_score": 0,
"selected": false,
"text": "<p>The html I am cloning has multiple datepicker inputs.</p>\n\n<p>Using Ryan Stemkoski's answer and Alex King's comment, I came up with this solution:</p>\n\n<pre><code>var clonedObject = this.el.find('.jLo:last-child')\nclonedObject.find('input.ui-datepicker').each(function(index, element) {\n $(element).removeClass('hasDatepicker');\n $(element).datepicker();\n});\nclonedObject.appendTo('.jLo');\n</code></pre>\n\n<p>Thanks yall.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842864/"
] | The `datepicker` function only works on the first input box that is created.
I'm trying to duplicate a datepicker by cloning the `div` that is containing it.
```
<a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>
```
To initialize the datepicker, according to the [jQuery UI documentation](http://docs.jquery.com/UI/Datepicker) I only have to do `$('#example').datepicker();` and it does work, but only on the first datepicker that is created.
The code to duplicate the `div` is the following:
```
$("a#dupMe").click(function(event){
event.preventDefault();
i++;
var a = $("#template")
.clone(true)
.insertBefore("#template")
.hide()
.fadeIn(1000);
a.find("input#txt").attr('value', i);
a.find("input#example").datepicker();
});
```
The strangest thing is that on the `document.ready` I have:
```
$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });
```
and if I click on the `#txt` it always works. | I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template `div` (to be called after each duplication). Something like:
```
function makeDatePickers() {
$("#template input[type=text]").datepicker();
}
``` |
34,798 | <p>I have a gridview that is within an updatepanel for a modal popup I have on a page.<br>
The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.</p>
<p>Does any one know what I am missing. </p>
<p><strong>Edit:</strong> I entered a better solution at the bottom</p>
| [
{
"answer_id": 34875,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>do you have ChildrenAsTriggers=\"false\" on the UpdatePanel?</p>\n\n<p>Are there any javascript errors on the page?</p>\n"
},
{
"answer_id": 35082,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": "<p>Is the Modal Window popped up using the IE Modal window? Or is it a DIV that you are showing?</p>\n\n<p>If it is an IE Modal Pop up you need to ensure you have </p>\n\n<pre><code> <base target=\"_self\" /> \n</code></pre>\n\n<p>To make sure the post back are to the modal page.</p>\n\n<p>If it is a DIV make sure you have your XHTML correct or it might not know what to update.</p>\n"
},
{
"answer_id": 35151,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure you have the following set on the UpdatePanel:\nChildrenAsTriggers=false and UpdateMode=Conditional</p>\n"
},
{
"answer_id": 35189,
"author": "Steven Williams",
"author_id": 3294,
"author_profile": "https://Stackoverflow.com/users/3294",
"pm_score": 1,
"selected": false,
"text": "<p>Are you testing in Firefox or IE? We have a similar issue where the entire page refreshes in Firefox (but not IE). To get around it we use a hidden asp:button with the useSubmitBehavior=\"false\" set.</p>\n\n<pre><code><asp:Button ID=\"btnRefresh\" runat=\"server\" OnClick=\"btnRefresh_Click\" Style=\"display: none\" UseSubmitBehavior=\"false\" />\n</code></pre>\n"
},
{
"answer_id": 35229,
"author": "Steven Williams",
"author_id": 3294,
"author_profile": "https://Stackoverflow.com/users/3294",
"pm_score": 0,
"selected": false,
"text": "<p>I would leave the onClick and set it as the trigger for the updatePanel.</p>\n\n<p>That's odd that it works in FF and not IE. That is opposite from the behavior we experience.</p>\n"
},
{
"answer_id": 75388,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 0,
"selected": false,
"text": "<p>UpdatePanels can be sensitive to malformed HTML. Do a View Source from your browser and run it through something like the W3C validator to look for anything weird (unclosed div or table being the usual suspects)</p>\n\n<p>If you use Firefox, there's a HTML validator Extension/AddOn available that works quite nicely.</p>\n"
},
{
"answer_id": 200777,
"author": "bitsprint",
"author_id": 9948,
"author_profile": "https://Stackoverflow.com/users/9948",
"pm_score": 2,
"selected": false,
"text": "<p>I had this problem and came across the following article:</p>\n\n<p><a href=\"http://bloggingabout.net/blogs/rick/archive/2008/04/02/linkbutton-inside-updatepanel-results-in-full-postback-updatepanel-not-triggered.aspx\" rel=\"nofollow noreferrer\">http://bloggingabout.net/blogs/rick/archive/2008/04/02/linkbutton-inside-updatepanel-results-in-full-postback-updatepanel-not-triggered.aspx</a></p>\n\n<p>My button wasn't dynamically created in the code like in this example, but when I checked the code in the aspx sure enough it was missing an ID property. On adding the ID the postback became asynchronous and started to behave as expected.</p>\n\n<p>So, in summary, check your button has an ID!</p>\n"
},
{
"answer_id": 403473,
"author": "Josh Mein",
"author_id": 2486,
"author_profile": "https://Stackoverflow.com/users/2486",
"pm_score": 2,
"selected": true,
"text": "<p>Several months later this problem was fixed. The project I was working in was a previous v1.1 which was converted with 2.0. However, in the web.config this line remained:</p>\n\n<pre><code><xhtmlConformance mode=\"Legacy\"/>\n</code></pre>\n\n<p>When it was commented out all of the bugs that we seemed to have with the ajax control toolkit disappeared</p>\n"
},
{
"answer_id": 13273075,
"author": "Scotty.NET",
"author_id": 1123275,
"author_profile": "https://Stackoverflow.com/users/1123275",
"pm_score": 0,
"selected": false,
"text": "<p>For reference..</p>\n\n<p>I've also noticed, when using the dreaded <code><asp:UpdatePanel ... /></code> and <code><asp:LinkButton ... /></code>, that as well as <code>UpdateMode=\"Conditional\"</code> on the <code>UpdatePanel</code> the following other changes are required: </p>\n\n<ul>\n<li><code>ViewStateMode=\"Enabled\"</code> is required on <code><asp:Content ... /></code> (I've set it to <code>Disabled</code> in the <code>MasterPage</code>)</li>\n<li><code>ClientIDMode=\"Static\"</code> had to be removed from <code><%@ Page ... /></code></li>\n</ul>\n"
},
{
"answer_id": 33972528,
"author": "Bortus",
"author_id": 3968481,
"author_profile": "https://Stackoverflow.com/users/3968481",
"pm_score": 0,
"selected": false,
"text": "<p>To prevent post-backs add return false to the onclick event.</p>\n\n<p>button.attribute.add(\"onclick\",\"return false;\");</p>\n\n<p><strong>Sample:</strong></p>\n\n<pre><code>string PopupURL = Common.GetAppPopupPath() + \"Popups/StockChart.aspx?s=\" + symbol;\nhlLargeChart.Attributes.Add(\"onclick\", String.Format(\"ShowPopupStdControls(PCStockChartWindow,'{0}');return false;\", PopupURL));\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | I have a gridview that is within an updatepanel for a modal popup I have on a page.
The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.
Does any one know what I am missing.
**Edit:** I entered a better solution at the bottom | Several months later this problem was fixed. The project I was working in was a previous v1.1 which was converted with 2.0. However, in the web.config this line remained:
```
<xhtmlConformance mode="Legacy"/>
```
When it was commented out all of the bugs that we seemed to have with the ajax control toolkit disappeared |
34,802 | <p>I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?</p>
| [
{
"answer_id": 34885,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": true,
"text": "<p>First, I'd create a simple DependencyObject class to hold your collection: </p>\n\n<pre><code>class YourCollectionType : DependencyObject {\n\n [PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]\n\n}\n</code></pre>\n\n<p>Then, on your ValidationRule-derived class, create a property:</p>\n\n<pre><code>YourCollectionType ListToCheck { get; set; }\n</code></pre>\n\n<p>Then, in the XAML, do this:</p>\n\n<pre><code><Binding.ValidationRules>\n <YourValidationRule>\n <YourValidationRule.ListToCheck> \n <YourCollectionType BoundList=\"{Binding Path=TheCollectionYouWantToCheck}\" />\n </YourValidationRule.ListToCheck>\n </YourValidationRule>\n</Binding.ValidationRules>\n</code></pre>\n\n<p>Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true.</p>\n"
},
{
"answer_id": 46980091,
"author": "Patrick",
"author_id": 278889,
"author_profile": "https://Stackoverflow.com/users/278889",
"pm_score": 1,
"selected": false,
"text": "<p>I would only create a custom dependency object if there were other properties I wanted to bind to the rule. Since in this case all we're doing is attaching a single collection of values to check against, I made my <code><UniqueValueValidationRule.OtherValues></code> property a <code><CollectionContainer></code>.</p>\n\n<p>From there, to get past the problem of the <code>DataContext</code> not being inherited, <code><TextBox.Resources></code> needed to have a <code><CollectionViewSource></code> to hold the actual binding and give it a <code>{StaticResource}</code> key, which <code>OtherValues</code> could then use as binding source.</p>\n\n<p>The validation rule itself then need only loop through <code>OtherValues.Collection</code> and perform equality checks.</p>\n\n<p>Observe:</p>\n\n<pre><code> <TextBox>\n <TextBox.Resources>\n <CollectionViewSource x:Key=\"otherNames\" Source=\"{Binding OtherNames}\"/>\n </TextBox.Resources>\n <TextBox.Text>\n <Binding Path=\"Name\">\n <Binding.ValidationRules>\n <t:UniqueValueValidationRule>\n <t:UniqueValueValidationRule.OtherValues>\n <CollectionContainer Collection=\"{Binding Source={StaticResource otherNames}}\"/>\n </t:UniqueValueValidationRule.OtherValues>\n </t:UniqueValueValidationRule>\n </Binding.ValidationRules>\n </Binding>\n </TextBox.Text>\n </TextBox>\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this? | First, I'd create a simple DependencyObject class to hold your collection:
```
class YourCollectionType : DependencyObject {
[PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]
}
```
Then, on your ValidationRule-derived class, create a property:
```
YourCollectionType ListToCheck { get; set; }
```
Then, in the XAML, do this:
```
<Binding.ValidationRules>
<YourValidationRule>
<YourValidationRule.ListToCheck>
<YourCollectionType BoundList="{Binding Path=TheCollectionYouWantToCheck}" />
</YourValidationRule.ListToCheck>
</YourValidationRule>
</Binding.ValidationRules>
```
Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true. |
34,806 | <p>I have a little dilemma that maybe you can help me sort out. </p>
<p>I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not. </p>
<p>What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned. </p>
<p>Having said that, my problem has nothing to do with it, it's a generic class design issue. </p>
<p>I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description. </p>
<p>I can think of the following scenarios: </p>
<ol>
<li><p>Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer. </p></li>
<li><p>Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it. </p></li>
<li><p>Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation. </p></li>
</ol>
<p>I think the best option is the third one... </p>
<p>How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... </p>
| [
{
"answer_id": 34832,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": true,
"text": "<p>I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode):</p>\n\n<pre><code>class Base {\n public final constructor(name) {\n constructor(name, null)\n end\n\n public abstract constructor(name, description);\n}\n</code></pre>\n\n<p>or, alternatively:</p>\n\n<pre><code>class Base {\n public abstract constructor(name);\n\n public final constructor(name, description) {\n constructor(name)\n this.set_description(description)\n }\n\n private final set_description(description) {\n ...\n }\n}\n</code></pre>\n\n<p>There's a rule in Java that supports this decision: \"never call non-final methods from a constructor.\"</p>\n"
},
{
"answer_id": 34990,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>To answer the first part of your post, check out AzMan (Authorization Manager), which, incidentally, is built into windows. It has the capability to specify operations which can be recombined into roles or assigned directly to users.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc300469.aspx\" rel=\"nofollow noreferrer\">Check out</a></p>\n\n<p>To answer the second part of your question, I wouldn't use an Abstract class. Instead just provide the functionality in the constructor and be done with it. It appeasr you want the specified behavior, and you don't want it to change. Why force descendents to provide the implementation.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I have a little dilemma that maybe you can help me sort out.
I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not.
What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned.
Having said that, my problem has nothing to do with it, it's a generic class design issue.
I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description.
I can think of the following scenarios:
1. Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer.
2. Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it.
3. Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation.
I think the best option is the third one...
How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... | I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode):
```
class Base {
public final constructor(name) {
constructor(name, null)
end
public abstract constructor(name, description);
}
```
or, alternatively:
```
class Base {
public abstract constructor(name);
public final constructor(name, description) {
constructor(name)
this.set_description(description)
}
private final set_description(description) {
...
}
}
```
There's a rule in Java that supports this decision: "never call non-final methods from a constructor." |
34,848 | <p>When using a <code>Zend_Form</code>, the only way to validate that an input is not left blank is to do</p>
<pre><code>$element->setRequired(true);
</code></pre>
<p>If this is not set and the element is blank, it appears to me that validation is not run on the element.</p>
<p>If I do use <code>setRequired()</code>, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the <code>Zend_Validate_NotEmpty</code> class, but this is a bit hacky.</p>
<p>I would ideally like to be able to use my own class (derived from <code>Zend_Validate_NotEmpty</code>) to perform the not empty check.</p>
| [
{
"answer_id": 34862,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 1,
"selected": false,
"text": "<p>Change the <a href=\"http://framework.zend.com/manual/en/zend.form.forms.html#zend.form.forms.validation.errors\" rel=\"nofollow noreferrer\">error message</a>.</p>\n"
},
{
"answer_id": 34921,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I can see <a href=\"http://framework.zend.com/manual/en/zend.form.forms.html#zend.form.forms.validation.errors/\" rel=\"nofollow noreferrer\">Changing the error message</a> has no way of changing the message of a specific error. Plus the manual makes it look like like this is a function belonging to Zend_Form, but I get method not found when using it on an instance of Zend_Form.</p>\n\n<p>And example of the useage would be really great.</p>\n"
},
{
"answer_id": 35894,
"author": "crono",
"author_id": 1462,
"author_profile": "https://Stackoverflow.com/users/1462",
"pm_score": 3,
"selected": true,
"text": "<p>I did it this way (ZF 1.5):</p>\n\n<pre><code>$name = new Zend_Form_Element_Text('name');\n$name->setLabel('Full Name: ')\n ->setRequired(true)\n ->addFilter('StripTags')\n ->addFilter('StringTrim')\n ->addValidator($MyNotEmpty);\n</code></pre>\n\n<p>so, the addValidator() is the interesting part. The Message is set in an \"Errormessage File\" (to bundle all custom messages in one file):</p>\n\n<pre><code>$MyNotEmpty = new Zend_Validate_NotEmpty();\n$MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY);\n</code></pre>\n\n<p>hope this helps...</p>\n"
},
{
"answer_id": 191889,
"author": "Toxygene",
"author_id": 8428,
"author_profile": "https://Stackoverflow.com/users/8428",
"pm_score": 2,
"selected": false,
"text": "<p>By default, setRequired(true) tells isValid() to add a NonEmpty validation <em>if one doesn't already exist</em>. Since this validation doesn't exist until isValid() is called, you can't set the message.</p>\n\n<p>The easiest solution is to simply manually add a NonEmpty validation before isValid() is called and set it's message accordingly.</p>\n\n<pre><code>$username = new Zend_Form_Element_Text('username');\n$username->setRequired(true)\n ->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Empty!')));\n</code></pre>\n"
},
{
"answer_id": 318213,
"author": "duma",
"author_id": 245644,
"author_profile": "https://Stackoverflow.com/users/245644",
"pm_score": 2,
"selected": false,
"text": "<p>Add a NotEmpty validator, and add your own message:</p>\n\n<pre><code>// In the form class:\n$username = $this->createElement('text', 'username');\n$username->setRequired(); // Note that this seems to be required!\n$username->addValidator('NotEmpty', true, array(\n 'messages' => array(\n 'isEmpty' => 'my localized err msg')));\n</code></pre>\n\n<p><strong>Note</strong> that the NotEmpty validator doesn't seem to be triggered unless you've also called setRequired() on the element.</p>\n\n<p>In the controller (or wherever), call $form->setTranslator($yourTranslator) to localize the error message when it's printed to the page.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349865/"
] | When using a `Zend_Form`, the only way to validate that an input is not left blank is to do
```
$element->setRequired(true);
```
If this is not set and the element is blank, it appears to me that validation is not run on the element.
If I do use `setRequired()`, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the `Zend_Validate_NotEmpty` class, but this is a bit hacky.
I would ideally like to be able to use my own class (derived from `Zend_Validate_NotEmpty`) to perform the not empty check. | I did it this way (ZF 1.5):
```
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Full Name: ')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator($MyNotEmpty);
```
so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file):
```
$MyNotEmpty = new Zend_Validate_NotEmpty();
$MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY);
```
hope this helps... |
34,852 | <p>I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:</p>
<pre><code>public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName))
.List<Customer>();
}
</code></pre>
<p>I am calling <code>Session.Flush()</code> at the end of the <code>HttpRequest</code>, and I get a <code>HibernateAdoException</code>. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the <code>flush</code>, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing?</p>
<hr>
<p>Here's the code from the exception:</p>
<pre><code>[SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?]
</code></pre>
<p>No parameters are showing as being passed.</p>
| [
{
"answer_id": 34965,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 5,
"selected": true,
"text": "<p>I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping?</p>\n"
},
{
"answer_id": 1146711,
"author": "Richard Dingwall",
"author_id": 91551,
"author_profile": "https://Stackoverflow.com/users/91551",
"pm_score": 0,
"selected": false,
"text": "<p>I also experienced this problem in NH 2.0.1 when trying to hide the inverse ends of many-to-many bags using access=\"noop\" (hint: this doesn't work). </p>\n\n<p>Converting them to access=\"field\" + adding a field on the class fixed the problem. Pretty hard to track them down though.</p>\n"
},
{
"answer_id": 1434275,
"author": "Andriy Volkov",
"author_id": 76859,
"author_profile": "https://Stackoverflow.com/users/76859",
"pm_score": 6,
"selected": false,
"text": "<p>Always be careful with NULLable fields whenever you deal with NHibernate. If your field is NULLable in DB, make sure corresponding .NET class uses Nullable type too. Otherwise, all kinds of weird things will happen. The symptom is usually will be that NHibernate will try to update the record in DB, even though you have not changed any fields since you read the entity from the database.</p>\n\n<p>The following sequence explains why this happens:</p>\n\n<ol>\n<li>NHibernate retrieves raw entity's data from DB using ADO.NET</li>\n<li>NHibernate constructs the entity and sets its properties</li>\n<li>If DB field contained NULL the property will be set to the defaul value for its type:\n\n<ul>\n<li>properties of reference types will be set to null</li>\n<li>properties of integer and floating point types will be set to 0</li>\n<li>properties of boolean type will be set to false</li>\n<li>properties of DateTime type will be set to DateTime.MinValue</li>\n<li>etc.</li>\n</ul></li>\n<li>Now, when transaction is committed, NHibernate compares the value of the property to the original field value it read form DB, and since the field contained NULL but the property contains a non-null value, <strong>NHibernate considers the property dirty, and forces an update of the enity.</strong></li>\n</ol>\n\n<p>Not only this hurts performance (you get extra round-trip to DB and extra update every time you retrieve the entity) but it also may cause hard to troubleshoot errors with DateTime columns. Indeed, when DateTime property is initialized to its default value it's set to 1/1/0001. When this value is saved to DB, ADO.NET's SqlClient can't convert it to a valid SqlDateTime value since the smallest possible SqlDateTime is 1/1/1753!!!</p>\n\n<p>The easiest fix is to make the class property use Nullable type, in this case \"DateTime?\". Alternatively, you could implement a custom type mapper by implementing IUserType with its Equals method properly comparing DbNull.Value with whatever default value of your value type. In our case Equals would need to return true when comparing 1/1/0001 with DbNull.Value. Implementing a full-functional IUserType is not really that hard but it does require knowledge of NHibernate trivia so prepare to do some substantial googling if you choose to go that way.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] | I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:
```
public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName))
.List<Customer>();
}
```
I am calling `Session.Flush()` at the end of the `HttpRequest`, and I get a `HibernateAdoException`. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the `flush`, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing?
---
Here's the code from the exception:
```
[SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?]
```
No parameters are showing as being passed. | I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping? |
34,868 | <p>In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the <a href="http://php.net/date" rel="noreferrer"><code>date()</code></a> function, the manual reads:</p>
<pre><code>string date ( string $format [, int $timestamp = time() ] )
</code></pre>
<p>Where <code>$timestamp</code> is an optional parameter, and when left blank it defaults to the <a href="http://php.net/time" rel="noreferrer"><code>time()</code></a> function's return value.</p>
<p>How do you go about creating optional parameters like this when defining a custom function in PHP?</p>
| [
{
"answer_id": 34869,
"author": "Jeff Winkworth",
"author_id": 1306,
"author_profile": "https://Stackoverflow.com/users/1306",
"pm_score": 9,
"selected": true,
"text": "<p>Much like the manual, use an equals (<code>=</code>) sign in your definition of the parameters:</p>\n\n<pre><code>function dosomething($var1, $var2, $var3 = 'somevalue'){\n // Rest of function here...\n}\n</code></pre>\n"
},
{
"answer_id": 34877,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 4,
"selected": false,
"text": "<p>Give the optional argument a default value. </p>\n\n<pre><code>function date ($format, $timestamp='') {\n}\n</code></pre>\n"
},
{
"answer_id": 34999,
"author": "gregh",
"author_id": 2687,
"author_profile": "https://Stackoverflow.com/users/2687",
"pm_score": 5,
"selected": false,
"text": "<p>Some notes that I also found useful:</p>\n\n<ul>\n<li><p>Keep your default values on the right side.</p>\n\n<pre><code>function whatever($var1, $var2, $var3=\"constant\", $var4=\"another\")\n</code></pre></li>\n<li><p>The default value of the argument must be a constant expression. It can't be a variable or a function call.</p></li>\n</ul>\n"
},
{
"answer_id": 35034,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>The default value of the argument must be a constant expression. It can't be a variable or a function call.</p>\n</blockquote>\n\n<p>If you need this functionality however:</p>\n\n<pre><code>function foo($foo, $bar = false)\n{\n if(!$bar)\n {\n $bar = $foo;\n }\n}\n</code></pre>\n\n<p>Assuming <code>$bar</code> isn't expected to be a boolean of course.</p>\n"
},
{
"answer_id": 16881443,
"author": "Lars Gyrup Brink Nielsen",
"author_id": 1071200,
"author_profile": "https://Stackoverflow.com/users/1071200",
"pm_score": 4,
"selected": false,
"text": "<p>The date function would be defined something like this:</p>\n\n<pre><code>function date($format, $timestamp = null)\n{\n if ($timestamp === null) {\n $timestamp = time();\n }\n\n // Format the timestamp according to $format\n}\n</code></pre>\n\n<p>Usually, you would put the default value like this:</p>\n\n<pre><code>function foo($required, $optional = 42)\n{\n // This function can be passed one or more arguments\n}\n</code></pre>\n\n<p>However, only <em>literals</em> are valid default arguments, which is why I used <code>null</code> as default argument in the first example, <strong>not</strong> <code>$timestamp = time()</code>, and combined it with a null check. Literals include arrays (<code>array()</code> or <code>[]</code>), booleans, numbers, strings, and <code>null</code>.</p>\n"
},
{
"answer_id": 35749448,
"author": "Gergely Lukacsy",
"author_id": 1957951,
"author_profile": "https://Stackoverflow.com/users/1957951",
"pm_score": 4,
"selected": false,
"text": "<p>If you don't know how many attributes need to be processed, you can use the variadic argument list token(<code>...</code>) introduced in PHP 5.6 (<a href=\"http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list\" rel=\"noreferrer\">see full documentation here</a>).</p>\n\n<p>Syntax:</p>\n\n<pre><code>function <functionName> ([<type> ]...<$paramName>) {}\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>function someVariadricFunc(...$arguments) {\n foreach ($arguments as $arg) {\n // do some stuff with $arg...\n }\n}\n\nsomeVariadricFunc(); // an empty array going to be passed\nsomeVariadricFunc('apple'); // provides a one-element array\nsomeVariadricFunc('apple', 'pear', 'orange', 'banana');\n</code></pre>\n\n<p>As you can see, this token basically turns all parameters to an array, which you can process in any way you like.</p>\n"
},
{
"answer_id": 70110910,
"author": "Arkadii Chyzhov",
"author_id": 5554825,
"author_profile": "https://Stackoverflow.com/users/5554825",
"pm_score": 3,
"selected": false,
"text": "<p>Starting with 7.1 there is a type hinting for nullable parameters</p>\n<pre><code>function func(?Object $object) {}\n</code></pre>\n<p>It will work for these cases:</p>\n<pre><code>func(null); //as nullable parameter\nfunc(new Object()); // as parameter of declared type\n</code></pre>\n<p>But for optional value signature should look like.</p>\n<pre><code>function func(Object $object = null) {} // In case of objects\nfunction func(?Object $object = null) {} // or the same with nullable parameter\n\nfunction func(string $object = '') {} // In case of scalar type - string, with string value as default value\nfunction func(string $object = null) {} // In case of scalar type - string, with null as default value\nfunction func(?string $object = '') {} // or the same with nullable parameter\n\nfunction func(int $object = 0) {} // In case of scalar type - integer, with integer value as default value\nfunction func(int $object = null) {} // In case of scalar type - integer, with null as default value\nfunction func(?int $object = 0) {} // or the same with nullable parameter\n</code></pre>\n<p>than it can be invoked as </p>\n<pre><code>func(); // as optional parameter\nfunc(null); // as nullable parameter\nfunc(new Object()); // as parameter of declared type\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2687/"
] | In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the [`date()`](http://php.net/date) function, the manual reads:
```
string date ( string $format [, int $timestamp = time() ] )
```
Where `$timestamp` is an optional parameter, and when left blank it defaults to the [`time()`](http://php.net/time) function's return value.
How do you go about creating optional parameters like this when defining a custom function in PHP? | Much like the manual, use an equals (`=`) sign in your definition of the parameters:
```
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
``` |
34,879 | <p>I need debug some old code that uses a Hashtable to store response from various threads.</p>
<p>I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.</p>
<p>How can this be done?</p>
| [
{
"answer_id": 34884,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": "<pre><code>foreach(string key in hashTable.Keys)\n{\n Console.WriteLine(String.Format(\"{0}: {1}\", key, hashTable[key]));\n}\n</code></pre>\n"
},
{
"answer_id": 34887,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 2,
"selected": false,
"text": "<pre><code>\n public static void PrintKeysAndValues( Hashtable myList ) {\n IDictionaryEnumerator myEnumerator = myList.GetEnumerator();\n Console.WriteLine( \"\\t-KEY-\\t-VALUE-\" );\n while ( myEnumerator.MoveNext() )\n Console.WriteLine(\"\\t{0}:\\t{1}\", myEnumerator.Key, myEnumerator.Value);\n Console.WriteLine();\n }\n</code></pre>\n\n<p>from: <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.hashtable(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.collections.hashtable(VS.71).aspx</a></p>\n"
},
{
"answer_id": 34894,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<p>This should work for pretty much every version of the framework...</p>\n\n<pre><code>foreach (string HashKey in TargetHash.Keys)\n{\n Console.WriteLine(\"Key: \" + HashKey + \" Value: \" + TargetHash[HashKey]);\n}\n</code></pre>\n\n<p>The trick is that you can get a list/collection of the keys (or the values) of a given hash to iterate through.</p>\n\n<p>EDIT: Wow, you try to pretty your code a little and next thing ya know there 5 answers... 8^D</p>\n"
},
{
"answer_id": 34909,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "<p>I also found that this will work too.</p>\n\n<pre><code>System.Collections.IDictionaryEnumerator enumerator = hashTable.GetEnumerator();\n\nwhile (enumerator.MoveNext())\n{\n string key = enumerator.Key.ToString();\n string value = enumerator.Value.ToString();\n\n Console.WriteLine((\"Key = '{0}'; Value = '{0}'\", key, value);\n}\n</code></pre>\n\n<p>Thanks for the help.</p>\n"
},
{
"answer_id": 35024,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 3,
"selected": false,
"text": "<p>I like:</p>\n\n<pre><code>foreach(DictionaryEntry entry in hashtable)\n{\n Console.WriteLine(entry.Key + \":\" + entry.Value);\n}\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] | I need debug some old code that uses a Hashtable to store response from various threads.
I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.
How can this be done? | ```
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
``` |
34,913 | <p>I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.</p>
<p>As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.</p>
<pre><code>╔════════╦═════════════╦════════╦══════╗
║ SiteId ║ VisitorType ║ Last30 ║ Total║
╠════════╬═════════════╬════════╬══════╣
║ 1 ║ 1 ║ 10 ║ 100 ║
║ 1 ║ 2 ║ 40 ║ 140 ║
║ 2 ║ 1 ║ 20 ║ 180 ║
╚════════╩═════════════╩════════╩══════╝
</code></pre>
<p>In SQL, I can easily get the counts for SiteID 1 with the following:</p>
<pre><code>SELECT SiteId,
SUM(Last30) AS Last30Sum
FROM Sites
WHERE SiteId = 1
GROUP BY SiteId
</code></pre>
<p>and should get a row like...</p>
<pre><code>╔════════╦════════════╗
║ SiteId ║ Last30Total║
╠════════╬════════════╣
║ 1 ║ 50 ║
╚════════╩════════════╝
</code></pre>
<p>However I'm not sure how to get this result using Linq. I've tried:</p>
<pre><code>var statsRecord = from ss in db.SiteStats
where ss.SiteId == siteId
group ss by ss.SiteId into ss
select ss;
</code></pre>
<p>but I'm not able to get back the total with something like <code>statsRecord.Last30</code></p>
<p>Can someone please let me know where I'm going wrong? Any help is appreciated.</p>
| [
{
"answer_id": 34951,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 2,
"selected": false,
"text": "<p>Easiest way for me to illustrate is using in-memory objects so it's clear what's happening. LINQ to SQL should be able to take that same LINQ query and translate it into appropriate SQL.</p>\n\n<pre><code>public class Site\n{\n static void Main()\n {\n List<Site> sites = new List<Site>()\n {\n new Site() { SiteID = 1, VisitorType = 1, Last30 = 10, Total = 100, },\n new Site() { SiteID = 1, VisitorType = 2, Last30 = 40, Total = 140, },\n new Site() { SiteID = 2, VisitorType = 1, Last30 = 20, Total = 180, },\n };\n\n var totals =\n from s in sites\n group s by s.SiteID into grouped\n select new\n {\n SiteID = grouped.Key,\n Last30Sum = \n (from value in grouped\n select value.Last30).Sum(),\n };\n\n foreach (var total in totals)\n {\n Console.WriteLine(\"Site: {0}, Last30Sum: {1}\", total.SiteID, total.Last30Sum);\n }\n }\n\n public int SiteID { get; set; }\n public int VisitorType { get; set; }\n public int Last30 { get; set; }\n public int Total { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 36678,
"author": "Ben Laan",
"author_id": 2918,
"author_profile": "https://Stackoverflow.com/users/2918",
"pm_score": 6,
"selected": true,
"text": "<p>Actually, although Thomas' code will work, it is more succint to use a lambda expression:</p>\n\n<pre><code>var totals =\nfrom s in sites\ngroup s by s.SiteID into grouped\nselect new\n{\n SiteID = grouped.Key,\n Last30Sum = grouped.Sum( s => s.Last30 )\n};\n</code></pre>\n\n<p>which uses the Sum extension method without the need for a nested LINQ operation.</p>\n\n<p>as per the LINQ 101 examples - <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped</a></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] | I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.
As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.
```
╔════════╦═════════════╦════════╦══════╗
║ SiteId ║ VisitorType ║ Last30 ║ Total║
╠════════╬═════════════╬════════╬══════╣
║ 1 ║ 1 ║ 10 ║ 100 ║
║ 1 ║ 2 ║ 40 ║ 140 ║
║ 2 ║ 1 ║ 20 ║ 180 ║
╚════════╩═════════════╩════════╩══════╝
```
In SQL, I can easily get the counts for SiteID 1 with the following:
```
SELECT SiteId,
SUM(Last30) AS Last30Sum
FROM Sites
WHERE SiteId = 1
GROUP BY SiteId
```
and should get a row like...
```
╔════════╦════════════╗
║ SiteId ║ Last30Total║
╠════════╬════════════╣
║ 1 ║ 50 ║
╚════════╩════════════╝
```
However I'm not sure how to get this result using Linq. I've tried:
```
var statsRecord = from ss in db.SiteStats
where ss.SiteId == siteId
group ss by ss.SiteId into ss
select ss;
```
but I'm not able to get back the total with something like `statsRecord.Last30`
Can someone please let me know where I'm going wrong? Any help is appreciated. | Actually, although Thomas' code will work, it is more succint to use a lambda expression:
```
var totals =
from s in sites
group s by s.SiteID into grouped
select new
{
SiteID = grouped.Key,
Last30Sum = grouped.Sum( s => s.Last30 )
};
```
which uses the Sum extension method without the need for a nested LINQ operation.
as per the LINQ 101 examples - <http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped> |
34,914 | <p>The manual page for <code>XML::Parser::Style::Objects</code> is horrible. A simple hello world style program would really be helpful.</p>
<p>I really wanted to do something like this: (not real code of course)</p>
<pre><code>use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();
MyNode::doSomething() {
my $self = shift;
print "This is a normal node";
for $kid ($self->Kids)
{
$kid->doSomething();
}
}
MyNode::special::doSomething() {
my $self = shift;
print "This is a special node";
}
</code></pre>
| [
{
"answer_id": 35450,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>When ever I need to do something similar, usually I end up using <a href=\"http://search.cpan.org/~ebohlman/XML-Parser-EasyTree-0.01/EasyTree.pm\" rel=\"nofollow noreferrer\">XML::Parser::EasyTree </a> it has better documentation and is simpler to use.</p>\n\n<p>I highly recommend it.</p>\n"
},
{
"answer_id": 35467,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": true,
"text": "<p>In all cases here is actual code that runs ... doesn't mean much but produces output and hopefully can get you started ...</p>\n\n<pre><code>use XML::Parser;\n\npackage MyNode::inner;\n sub doSomething {\n my $self = shift;\n print \"This is an inner node containing : \";\n print $self->{Kids}->[0]->{Text};\n print \"\\n\";\n }\npackage MyNode::Characters;\n sub doSomething {}\npackage MyNode::foo;\n sub doSomething {\n my $self = shift;\n print \"This is an external node\\n\";\n for $kid (@ { $self->{Kids} }) {\n $kid->doSomething();\n }\n }\n\npackage main;\n\nmy $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');\nmy $tree = $p->parsefile('foo.xml');\nfor (@$tree) {\n $_->doSomething();\n}\n</code></pre>\n\n<p>with foo.xml</p>\n\n<pre><code> <foo> <inner>some text</inner> <inner>something else</inner></foo>\n</code></pre>\n\n<p>which outputs</p>\n\n<pre><code>>perl -w \"tree.pl\" \nThis is an external node\nThis is an inner node containing : some text\nThis is an inner node containing : something else\n</code></pre>\n\n<p>Hope that helps.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
] | The manual page for `XML::Parser::Style::Objects` is horrible. A simple hello world style program would really be helpful.
I really wanted to do something like this: (not real code of course)
```
use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();
MyNode::doSomething() {
my $self = shift;
print "This is a normal node";
for $kid ($self->Kids)
{
$kid->doSomething();
}
}
MyNode::special::doSomething() {
my $self = shift;
print "This is a special node";
}
``` | In all cases here is actual code that runs ... doesn't mean much but produces output and hopefully can get you started ...
```
use XML::Parser;
package MyNode::inner;
sub doSomething {
my $self = shift;
print "This is an inner node containing : ";
print $self->{Kids}->[0]->{Text};
print "\n";
}
package MyNode::Characters;
sub doSomething {}
package MyNode::foo;
sub doSomething {
my $self = shift;
print "This is an external node\n";
for $kid (@ { $self->{Kids} }) {
$kid->doSomething();
}
}
package main;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
for (@$tree) {
$_->doSomething();
}
```
with foo.xml
```
<foo> <inner>some text</inner> <inner>something else</inner></foo>
```
which outputs
```
>perl -w "tree.pl"
This is an external node
This is an inner node containing : some text
This is an inner node containing : something else
```
Hope that helps. |
34,920 | <p>What is the best way to create a lock on a file in Perl?</p>
<p>Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?</p>
| [
{
"answer_id": 34928,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"http://perldoc.perl.org/functions/flock.html\" rel=\"nofollow noreferrer\">flock</a> Luke. </p>\n\n<p><strong>Edit:</strong> <a href=\"http://www.perlmonks.org/?node_id=7058\" rel=\"nofollow noreferrer\">This</a> is a good explanation.</p>\n"
},
{
"answer_id": 34929,
"author": "Michael Ratanapintha",
"author_id": 1879,
"author_profile": "https://Stackoverflow.com/users/1879",
"pm_score": 0,
"selected": false,
"text": "<p>flock creates Unix-style file locks, and is available on most OS's Perl runs on. However flock's locks are advisory only.</p>\n\n<p>edit: emphasized that flock is portable</p>\n"
},
{
"answer_id": 34933,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 6,
"selected": true,
"text": "<p>If you end up using flock, here's some code to do it:</p>\n\n<pre><code>use Fcntl ':flock'; # Import LOCK_* constants\n\n# We will use this file path in error messages and function calls.\n# Don't type it out more than once in your code. Use a variable.\nmy $file = '/path/to/some/file';\n\n# Open the file for appending. Note the file path is quoted\n# in the error message. This helps debug situations where you\n# have a stray space at the start or end of the path.\nopen(my $fh, '>>', $file) or die \"Could not open '$file' - $!\";\n\n# Get exclusive lock (will block until it does)\nflock($fh, LOCK_EX) or die \"Could not lock '$file' - $!\";\n\n# Do something with the file here...\n\n# Do NOT use flock() to unlock the file if you wrote to the\n# file in the \"do something\" section above. This could create\n# a race condition. The close() call below will unlock the\n# file for you, but only after writing any buffered data.\n\n# In a world of buffered i/o, some or all of your data may not \n# be written until close() completes. Always, always, ALWAYS \n# check the return value of close() if you wrote to the file!\nclose($fh) or die \"Could not write '$file' - $!\";\n</code></pre>\n\n<p>Some useful links:</p>\n\n<ul>\n<li><a href=\"http://www.perlmonks.org/?node_id=7058\" rel=\"noreferrer\">PerlMonks file locking tutorial</a> (somewhat old)</li>\n<li><a href=\"http://perldoc.perl.org/functions/flock.html\" rel=\"noreferrer\"><code>flock()</code> documentation</a></li>\n</ul>\n\n<p>In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics).</p>\n"
},
{
"answer_id": 38101,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 3,
"selected": false,
"text": "<p>CPAN to the rescue: <a href=\"http://search.cpan.org/~rani/IO-LockedFile-0.23/LockedFile.pm\" rel=\"noreferrer\">IO::LockedFile</a>. </p>\n"
},
{
"answer_id": 79295,
"author": "Ryan P",
"author_id": 1539,
"author_profile": "https://Stackoverflow.com/users/1539",
"pm_score": 1,
"selected": false,
"text": "<p>My goal in this question was to lock a file being used as a data store for several scripts. In the end I used similar code to the following (from Chris):</p>\n\n<pre><code>open (FILE, '>>', test.dat') ; # open the file \nflock FILE, 2; # try to lock the file \n# do something with the file here \nclose(FILE); # close the file\n</code></pre>\n\n<p>In his example I removed the flock FILE, 8 as the close(FILE) performs this action as well. The real problem was when the script starts it has to hold the current counter, and when it ends it has to update the counter. This is where Perl has a problem, to read the file you:</p>\n\n<pre><code> open (FILE, '<', test.dat');\n flock FILE, 2;\n</code></pre>\n\n<p>Now I want to write out the results and since i want to overwrite the file I need to reopen and truncate which results in the following:</p>\n\n<pre><code> open (FILE, '>', test.dat'); #single arrow truncates double appends\n flock FILE, 2;\n</code></pre>\n\n<p>In this case the file is actually unlocked for a short period of time while the file is reopened. This demonstrates the case for the external lock file. If you are going to be changing contexts of the file, use a lock file. The modified code:</p>\n\n<pre><code>open (LOCK_FILE, '<', test.dat.lock') or die \"Could not obtain lock\";\nflock LOCK_FILE, 2;\nopen (FILE, '<', test.dat') or die \"Could not open file\";\n# read file\n# ...\nopen (FILE, '>', test.dat') or die \"Could not reopen file\";\n#write file\nclose (FILE);\nclose (LOCK_FILE);\n</code></pre>\n"
},
{
"answer_id": 79435,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered using the <a href=\"http://search.cpan.org/perldoc?LockFile::Simple\" rel=\"nofollow noreferrer\">LockFile::Simple module</a>? It does most of the work for you already.</p>\n\n<p>In my past experience, I have found it very easy to use and sturdy.</p>\n"
},
{
"answer_id": 80825,
"author": "szabgab",
"author_id": 11827,
"author_profile": "https://Stackoverflow.com/users/11827",
"pm_score": 3,
"selected": false,
"text": "<p>I think it would be much better to show this with lexical variables as file handlers\nand error handling.\nIt is also better to use the constants from the Fcntl module than hard code the magic number 2 which might not be the right number on all operating systems.</p>\n\n<pre>\n use Fcntl ':flock'; # import LOCK_* constants\n\n # open the file for appending\n open (my $fh, '>>', 'test.dat') or die $!;\n\n # try to lock the file exclusively, will wait till you get the lock\n flock($fh, LOCK_EX);\n\n # do something with the file here (print to it in our case)\n\n # actually you should not unlock the file\n # close the file will unlock it\n close($fh) or warn \"Could not close file $!\";\n</pre>\n\n<p>Check out the full <a href=\"http://perldoc.perl.org/functions/flock.html\" rel=\"nofollow noreferrer\">documentation of flock</a> and the <a href=\"http://www.perlmonks.org/?node_id=7058\" rel=\"nofollow noreferrer\">File locking tutorial</a> on PerlMonks even though that also uses the old style of file handle usage.</p>\n\n<p>Actually I usually skip the error handling on close() as there is not\nmuch I can do if it fails anyway.</p>\n\n<p>Regarding what to lock, if you are working in a single file then lock that file. If you need to lock several files at once then - in order to avoid dead locks - it is better to pick one file that you are locking. Does not really matter if that is one of the several files you really need to lock or a separate file you create just for the locking purpose.</p>\n"
},
{
"answer_id": 81019,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "<p>Ryan P wrote:</p>\n\n<blockquote>\n <p>In this case the file is actually unlocked for a short period of time while the file is reopened.</p>\n</blockquote>\n\n<p>So don’t do that. Instead, <code>open</code> the file for read/write:</p>\n\n<pre><code>open my $fh, '+<', 'test.dat'\n or die \"Couldn’t open test.dat: $!\\n\";\n</code></pre>\n\n<p>When you are ready to write the counter, just <code>seek</code> back to the start of the file. Note that if you do that, you should <code>truncate</code> just before <code>close</code>, so that the file isn’t left with trailing garbage if its new contents are shorter than its previous ones. (Usually, the current position in the file is at its end, so you can just write <code>truncate $fh, tell $fh</code>.)</p>\n\n<p>Also, note that I used three-argument <code>open</code> and a lexical file handle, and I also checked the success of the operation. Please avoid global file handles (global variables are bad, mmkay?) and magic two-argument <code>open</code> (which has been a source of many a(n exploitable) bug in Perl code), and always test whether your <code>open</code>s succeed.</p>\n"
},
{
"answer_id": 182465,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 2,
"selected": false,
"text": "<pre><code>use strict;\n\nuse Fcntl ':flock'; # Import LOCK_* constants\n\n# We will use this file path in error messages and function calls.\n# Don't type it out more than once in your code. Use a variable.\nmy $file = '/path/to/some/file';\n\n# Open the file for appending. Note the file path is in quoted\n# in the error message. This helps debug situations where you\n# have a stray space at the start or end of the path.\nopen(my $fh, '>>', $file) or die \"Could not open '$file' - $!\";\n\n# Get exclusive lock (will block until it does)\nflock($fh, LOCK_EX);\n\n\n# Do something with the file here...\n\n\n# Do NOT use flock() to unlock the file if you wrote to the\n# file in the \"do something\" section above. This could create\n# a race condition. The close() call below will unlock it\n# for you, but only after writing any buffered data.\n\n# In a world of buffered i/o, some or all of your data will not \n# be written until close() completes. Always, always, ALWAYS \n# check the return value on close()!\nclose($fh) or die \"Could not write '$file' - $!\";\n</code></pre>\n"
},
{
"answer_id": 1427007,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my solution to reading and writing in one lock...</p>\n\n<pre><code>open (TST,\"+< readwrite_test.txt\") or die \"Cannot open file\\n$!\";\nflock(TST, LOCK_EX);\n# Read the file:\n@LINES=<TST>;\n# Wipe the file:\nseek(TST, 0, 0); truncate(TST, 0);\n# Do something with the contents here:\npush @LINES,\"grappig, he!\\n\";\n$LINES[3]=\"Gekke henkie!\\n\";\n# Write the file:\nforeach $l (@LINES)\n{\n print TST $l;\n}\nclose(TST) or die \"Cannot close file\\n$!\";\n</code></pre>\n"
},
{
"answer_id": 7695560,
"author": "Alex Dupuy",
"author_id": 18829,
"author_profile": "https://Stackoverflow.com/users/18829",
"pm_score": 4,
"selected": false,
"text": "<p>The other answers cover Perl flock locking pretty well, but on many Unix/Linux systems there are actually two independent locking systems: BSD flock() and POSIX fcntl()-based locks.</p>\n\n<p>Unless you provide special options to configure when building Perl, its flock will use flock() if available. This is generally fine and probably what you want if you just need locking within your application (running on a single system). However, sometimes you need to interact with another application that uses fcntl() locks (like Sendmail, on many systems) or perhaps you need to do file locking across NFS-mounted filesystems.</p>\n\n<p>In those cases, you might want to look at <a href=\"http://search.cpan.org/~jtt/File-FcntlLock-0.12/lib/File/FcntlLock.pm\">File::FcntlLock</a> or <a href=\"http://search.cpan.org/~phenson/File-Lockf-0.20/lockf.pm\">File::lockf</a>. It is also possible to do fcntl()-based locking in pure Perl (with some hairy and non-portable bits of pack()).</p>\n\n<p>Quick overview of flock/fcntl/lockf differences:</p>\n\n<p>lockf is almost always implemented on top of fcntl, has file-level locking only. If implemented using fcntl, limitations below also apply to lockf.</p>\n\n<p>fcntl provides range-level locking (within a file) and network locking over NFS, but locks are not inherited by child processes after a fork(). On many systems, you must have the filehandle open read-only to request a shared lock, and read-write to request an exclusive lock.</p>\n\n<p>flock has file-level locking only, locking is only within a single machine (you can lock an NFS-mounted file, but only local processes will see the lock). Locks are inherited by children (assuming that the file descriptor is not closed).</p>\n\n<p>Sometimes (SYSV systems) flock is emulated using lockf, or fcntl; on some BSD systems lockf is emulated using flock. Generally these sorts of emulation work poorly and you are well advised to avoid them.</p>\n"
},
{
"answer_id": 11473761,
"author": "sean ur",
"author_id": 1523990,
"author_profile": "https://Stackoverflow.com/users/1523990",
"pm_score": 1,
"selected": false,
"text": "<p>Developed off of <a href=\"http://metacpan.org/pod/File%3a%3aFcntlLock\" rel=\"nofollow\">http://metacpan.org/pod/File::FcntlLock</a></p>\n\n<pre><code>use Fcntl qw(:DEFAULT :flock :seek :Fcompat);\nuse File::FcntlLock;\nsub acquire_lock {\n my $fn = shift;\n my $justPrint = shift || 0;\n confess \"Too many args\" if defined shift;\n confess \"Not enough args\" if !defined $justPrint;\n\n my $rv = TRUE;\n my $fh;\n sysopen($fh, $fn, O_RDWR | O_CREAT) or LOGDIE \"failed to open: $fn: $!\";\n $fh->autoflush(1);\n ALWAYS \"acquiring lock: $fn\";\n my $fs = new File::FcntlLock;\n $fs->l_type( F_WRLCK );\n $fs->l_whence( SEEK_SET );\n $fs->l_start( 0 );\n $fs->lock( $fh, F_SETLKW ) or LOGDIE \"failed to get write lock: $fn:\" . $fs->error;\n my $num = <$fh> || 0;\n return ($fh, $num);\n}\n\nsub release_lock {\n my $fn = shift;\n my $fh = shift;\n my $num = shift;\n my $justPrint = shift || 0;\n\n seek($fh, 0, SEEK_SET) or LOGDIE \"seek failed: $fn: $!\";\n print $fh \"$num\\n\" or LOGDIE \"write failed: $fn: $!\";\n truncate($fh, tell($fh)) or LOGDIE \"truncate failed: $fn: $!\";\n my $fs = new File::FcntlLock;\n $fs->l_type(F_UNLCK);\n ALWAYS \"releasing lock: $fn\";\n $fs->lock( $fh, F_SETLK ) or LOGDIE \"unlock failed: $fn: \" . $fs->error;\n close($fh) or LOGDIE \"close failed: $fn: $!\";\n}\n</code></pre>\n"
},
{
"answer_id": 25940666,
"author": "Mark Lawrence",
"author_id": 1450404,
"author_profile": "https://Stackoverflow.com/users/1450404",
"pm_score": 1,
"selected": false,
"text": "<p>One alternative to the lock <em>file</em> approach is to use a lock <em>socket</em>. See <a href=\"http://metacpan.org/pod/Lock::Socket\" rel=\"nofollow\">Lock::Socket</a> on CPAN for such an implementation. Usage is as simple as the following:</p>\n\n<pre><code>use Lock::Socket qw/lock_socket/;\nmy $lock = lock_socket(5197); # raises exception if lock already taken\n</code></pre>\n\n<p>There are a couple of advantages to using a socket:</p>\n\n<ul>\n<li>guaranteed (through the operating system) that no two applications will hold the same lock: there is no race condition.</li>\n<li>guaranteed (again through the operating system) to clean up neatly when your process exits, so there are no stale locks to deal with.</li>\n<li>relies on functionality that is well supported by anything that Perl runs on: no issues with flock(2) support on Win32 for example.</li>\n</ul>\n\n<p>The obvious disadvantage is of course that the lock namespace is global. It is possible for a kind of denial-of-service if another process decides to lock the port you need.</p>\n\n<p>[disclosure: I am the author of the afor-mentioned module]</p>\n"
},
{
"answer_id": 60920788,
"author": "Ben White",
"author_id": 7141376,
"author_profile": "https://Stackoverflow.com/users/7141376",
"pm_score": 0,
"selected": false,
"text": "<p>Flock is probably the best but requires you to write all the supporting code around it - timeouts, stale locks, non-existant files etc.\nI trued LockFile::Simple but found it started setting the default umask to readonly and not cleaning this up. Resulting in random permissions problems on a multi process/multi-threaded application on modperl\nI've settled on wrapping up NFSLock with some empty file handling.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539/"
] | What is the best way to create a lock on a file in Perl?
Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file? | If you end up using flock, here's some code to do it:
```
use Fcntl ':flock'; # Import LOCK_* constants
# We will use this file path in error messages and function calls.
# Don't type it out more than once in your code. Use a variable.
my $file = '/path/to/some/file';
# Open the file for appending. Note the file path is quoted
# in the error message. This helps debug situations where you
# have a stray space at the start or end of the path.
open(my $fh, '>>', $file) or die "Could not open '$file' - $!";
# Get exclusive lock (will block until it does)
flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";
# Do something with the file here...
# Do NOT use flock() to unlock the file if you wrote to the
# file in the "do something" section above. This could create
# a race condition. The close() call below will unlock the
# file for you, but only after writing any buffered data.
# In a world of buffered i/o, some or all of your data may not
# be written until close() completes. Always, always, ALWAYS
# check the return value of close() if you wrote to the file!
close($fh) or die "Could not write '$file' - $!";
```
Some useful links:
* [PerlMonks file locking tutorial](http://www.perlmonks.org/?node_id=7058) (somewhat old)
* [`flock()` documentation](http://perldoc.perl.org/functions/flock.html)
In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics). |
34,925 | <p>I've seen quite a few posts on changes in .NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running .NET 3.5 RTM).</p>
<pre><code>[XmlRoot("foo")]
public class Foo
{
static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @"<foo name='ack' />";
using (StringReader sr = new StringReader(xml))
{
Foo foo = serializer.Deserialize(sr) as Foo;
}
}
[XmlAttribute("name")]
public string Name { get; set; }
public Foo Bar { get; private set; }
}
</code></pre>
<p>In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException:</p>
<blockquote>
<p>Unable to generate a temporary class (result=1).
error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only</p>
</blockquote>
<p>Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property.</p>
<p>My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature? </p>
<p><strong>EDIT</strong>: In SP1, if I added a <code><Bar /></code> element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed.</p>
<p>This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception.</p>
<p><strong>EDIT</strong>: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag:</p>
<pre><code><system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="1" />
</switches>
</system.diagnostics>
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
</code></pre>
<p>Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, <a href="http://support.microsoft.com/kb/951847" rel="nofollow noreferrer">change lists</a>, or the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlignoreattribute.aspx" rel="nofollow noreferrer">XmlIgnoreAttribute documentation</a>.</p>
| [
{
"answer_id": 35223,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 3,
"selected": true,
"text": "<p>In SP1 does the foo.Bar property get properly deserialized?</p>\n\n<p>In pre SP1 you wouldn't be able to deserialize the object because the set method of the Bar property is private so the XmlSerializer doesn't have a way to set that value. I'm not sure how SP1 is pulling it off.</p>\n\n<p>You could try adding this to your web.config/app.config</p>\n\n<pre><code><system.xml.serialization> \n <xmlSerializer tempFilesLocation=\"c:\\\\foo\"/> \n</system.xml.serialization> \n</code></pre>\n\n<p>That will put the class generated by the XmlSerializer into c:\\foo so you can see what it is doing in SP1 vs RTM</p>\n"
},
{
"answer_id": 35363,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 0,
"selected": false,
"text": "<p>I rather like this new (?) behavior because the XML document doesn't have any mention of Bar in it, so the deserializer should not even be attempting to set it.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2314/"
] | I've seen quite a few posts on changes in .NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running .NET 3.5 RTM).
```
[XmlRoot("foo")]
public class Foo
{
static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @"<foo name='ack' />";
using (StringReader sr = new StringReader(xml))
{
Foo foo = serializer.Deserialize(sr) as Foo;
}
}
[XmlAttribute("name")]
public string Name { get; set; }
public Foo Bar { get; private set; }
}
```
In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException:
>
> Unable to generate a temporary class (result=1).
> error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only
>
>
>
Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property.
My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature?
**EDIT**: In SP1, if I added a `<Bar />` element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed.
This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception.
**EDIT**: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag:
```
<system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="1" />
</switches>
</system.diagnostics>
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
```
Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, [change lists](http://support.microsoft.com/kb/951847), or the [XmlIgnoreAttribute documentation](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlignoreattribute.aspx). | In SP1 does the foo.Bar property get properly deserialized?
In pre SP1 you wouldn't be able to deserialize the object because the set method of the Bar property is private so the XmlSerializer doesn't have a way to set that value. I'm not sure how SP1 is pulling it off.
You could try adding this to your web.config/app.config
```
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
```
That will put the class generated by the XmlSerializer into c:\foo so you can see what it is doing in SP1 vs RTM |
34,926 | <p>my <b>SSRS DataSet</b> returns a field with HTML, e.g.</p>
<pre><code><b>blah blah </b><i> blah </i>.
</code></pre>
<p>how do i strip all the HTML tags? has to be done with <b>inline</b> VB.NET</p>
<p>Changing the data in the table is not an option.</p>
<p><strong>Solution found</strong> ... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","")</p>
| [
{
"answer_id": 34935,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a good example using Regular Expressions: <a href=\"https://web.archive.org/web/20210619174622/https://www.4guysfromrolla.com/webtech/042501-1.shtml\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210619174622/https://www.4guysfromrolla.com/webtech/042501-1.shtml</a></p>\n"
},
{
"answer_id": 34942,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": false,
"text": "<p>If you know the HTML is well-formed enough, you could, if you make sure it has a root node, convert the data in that field into a System.Xml.XmlDocument and then get the InnerText value from it.</p>\n\n<p>Again, you will have to make sure the text has a root node, which you can add yourself if needs be, since it will not matter, and make sure the HTML is well formed.</p>\n"
},
{
"answer_id": 35012,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 5,
"selected": true,
"text": "<p>Thanx to Daniel, but I needed it to be done inline ... here's the solution:</p>\n\n<p><code>= System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, \"<[^>]+>\",\"\")</code></p>\n\n<p>Here are the links:</p>\n\n<p><a href=\"http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx</a><br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms157328.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms157328.aspx</a></p>\n"
},
{
"answer_id": 36543,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use regular expressions (for example if you need better performance) you could try <a href=\"http://www.codeproject.com/KB/MCMS/htmlTagStripper.aspx\" rel=\"nofollow noreferrer\">a small method I wrote a while ago, posted at CodeProject</a>.</p>\n"
},
{
"answer_id": 23781709,
"author": "Peter",
"author_id": 58553,
"author_profile": "https://Stackoverflow.com/users/58553",
"pm_score": 1,
"selected": false,
"text": "<p>I would go to Report Properties and then code and add the following</p>\n\n<pre><code>Dim mRemoveTagRegex AS NEW System.Text.RegularExpressions.Regex(\"<(.|\\n)+?>\", System.Text.RegularExpressions.RegexOptions.Compiled)\n\nFunction RemoveHtml(ByVal text As string) AS string\n If text IsNot Nothing Then\n Return mRemoveTagRegex.Replace(text, \"\")\n End If \nEnd Function\n</code></pre>\n\n<p>Then you can use <code>Code.RemoveHtml(Fields!Content.Value)</code> to remove the html tags.</p>\n\n<p>In my opinion this is preferable then having multiple copies of the regex.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] | my **SSRS DataSet** returns a field with HTML, e.g.
```
<b>blah blah </b><i> blah </i>.
```
how do i strip all the HTML tags? has to be done with **inline** VB.NET
Changing the data in the table is not an option.
**Solution found** ... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") | Thanx to Daniel, but I needed it to be done inline ... here's the solution:
`= System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","")`
Here are the links:
<http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx>
<http://msdn.microsoft.com/en-us/library/ms157328.aspx> |
34,938 | <p>I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.</p>
<p>if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?</p>
<pre><code>if ( (condition1) | (condition2) ){
// do this
}
</code></pre>
<p>or would I need to nest two if statements to only check the second condition if the first evaluates to false?</p>
<pre><code>if (condition1){
// do this
}else if (condition2){
// do this
}
</code></pre>
<p>I am working in PHP, however, I assume that this may be language-agnostic.</p>
| [
{
"answer_id": 34941,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 0,
"selected": false,
"text": "<p>Since this is tagged language agnostic I'll chime in. For Perl at least, the first option is sufficient, I'm not familiar with PHP. It evaluates left to right and drops out as soon as the condition is met.</p>\n"
},
{
"answer_id": 34945,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 2,
"selected": false,
"text": "<p>Pretty much every language does a short circuit evaluation. Meaning the second condition is only evaluated if it's aboslutely necessary to. For this to work, most languages use the double pipe, ||, not the single one, |.</p>\n\n<p>See <a href=\"http://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Short-circuit_evaluation</a></p>\n"
},
{
"answer_id": 34949,
"author": "levand",
"author_id": 3044,
"author_profile": "https://Stackoverflow.com/users/3044",
"pm_score": 0,
"selected": false,
"text": "<p>In most languages with decent optimization the former will work just fine.</p>\n"
},
{
"answer_id": 34954,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 4,
"selected": true,
"text": "<p>For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.</p>\n\n<p>An old trick for doing obfuscated code was to use this to create if statements, such as:</p>\n\n<pre><code>a || b();\n</code></pre>\n\n<p>if \"a\" is true, \"b()\" would never be evaluated, so we can rewrite it into:</p>\n\n<pre><code>if(!a)\n b();\n</code></pre>\n\n<p>and similarly:</p>\n\n<pre><code>a && b();\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>if(a)\n b();\n</code></pre>\n\n<p><strong>Please note</strong> that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not \"optimised\".</p>\n\n<p>EDIT:\nAs mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.</p>\n\n<p>First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.</p>\n\n<p>Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless.</p>\n"
},
{
"answer_id": 34960,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 2,
"selected": false,
"text": "<p>I've seen a lot of these types of questions lately--optimization to the nth degree.</p>\n\n<p>I think it makes sense in certain circumstances:</p>\n\n<ol>\n<li>Computing condition 2 is not a constant time operation</li>\n<li>You are asking strictly for educational purposes--you want to know how the language works, not to save 3us.</li>\n</ol>\n\n<p>In other cases, worrying about the \"fastest\" way to iterate or check a conditional is silly. Instead of writing tests which require millions of trials to see any recordable (but insignificant) difference, focus on clarity.</p>\n\n<p>When someone else (could be you!) picks up this code in a month or a year, what's going to be most important is clarity.</p>\n\n<p>In this case, your first example is shorter, clearer and doesn't require you to repeat yourself.</p>\n"
},
{
"answer_id": 34961,
"author": "Farinha",
"author_id": 2841,
"author_profile": "https://Stackoverflow.com/users/2841",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://www.kekh.com/chapter-6/short-circuit-evaluation/\" rel=\"nofollow noreferrer\">this article</a> PHP does short circuit evaluation, which means that if the first condition is met the second is not even evaluated.\nIt's quite easy to test also (from the article):</p>\n\n<pre><code><?php\n/* ch06ex07 – shows no output because of short circuit evaluation */\n\nif (true || $intVal = 5) // short circuits after true\n{\n\necho $intVal; // will be empty because the assignment never took place\n}\n\n?>\n</code></pre>\n"
},
{
"answer_id": 34963,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 2,
"selected": false,
"text": "<p>In C, C++ and Java, the statement:\n<code><pre>\nif (condition1 | condition2) {\n ...\n}\n</code></pre></p>\n\n<p>will evaluate both conditions every time and only be true if the entire expression is true. </p>\n\n<p>The statement:</p>\n\n<p><pre><code>\nif (condition1 || condition2) {\n ...\n}\n</pre></code></p>\n\n<p>will evaluate <code>condition2</code> only if <code>condition1</code> is false. The difference is significant if condition2 is a function or another expression with a side-effect. </p>\n\n<p>There is, however, no difference between the <code>||</code> case and the <code>if</code>/<code>else</code> case.</p>\n"
},
{
"answer_id": 34997,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>|</code> is a bitwise operator in PHP. It does not mean <code>$a OR $b</code>, exactly. You'll want to use the double-pipe. And yes, as mentioned, PHP does short-circuit evaluation. In similar fashion, if the first condition of an <code>&&</code> clause evaluates to false, PHP does not evaluate the rest of the clause, either.</p>\n"
},
{
"answer_id": 35391,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 1,
"selected": false,
"text": "<p>While using short-circuiting for the purposes of optimization is often overkill, there are certainly other compelling reasons to use it. One such example (in C++) is the following:</p>\n\n<pre><code>if( pObj != NULL && *pObj == \"username\" ) {\n // Do something...\n}\n</code></pre>\n\n<p>Here, short-circuiting is being relied upon to ensure that <code>pObj</code> has been allocated prior to dereferencing it. This is far more concise than having nested <code>if</code> statements.</p>\n"
},
{
"answer_id": 35399,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>VB.net has two wonderful expression called \"OrElse\" and \"AndAlso\"</p>\n\n<p>OrElse will short circuit itself the first time it reaches a True evaluation and execute the code you desire.</p>\n\n<pre><code>If FirstName = \"Luke\" OrElse FirstName = \"Darth\" Then\n Console.Writeline \"Greetings Exalted One!\"\nEnd If\n</code></pre>\n\n<p>AndAlso will short circuit itself the first time it a False evaluation and not evaluate the code within the block.</p>\n\n<pre><code>If FirstName = \"Luke\" AndAlso LastName = \"Skywalker\" Then\n Console.Writeline \"You are the one and only.\"\nEnd If\n</code></pre>\n\n<p>I find both of these helpful.</p>\n"
},
{
"answer_id": 77527,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The short-circuiting is not for optimization. It's main purpose is to avoid calling code that will not work, yet result in a readable test. Example:</p>\n\n<pre><code>if (i < array.size() && array[i]==foo) ...\n</code></pre>\n\n<p>Note that array[i] may very well get an access violation if i is out of range and crash the program. Thus this program is certainly depending on short-circuiting the evaluation!</p>\n\n<p>I believe this is the reason for writing expressions this way far more often than optimization concerns.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083/"
] | I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.
if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?
```
if ( (condition1) | (condition2) ){
// do this
}
```
or would I need to nest two if statements to only check the second condition if the first evaluates to false?
```
if (condition1){
// do this
}else if (condition2){
// do this
}
```
I am working in PHP, however, I assume that this may be language-agnostic. | For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.
An old trick for doing obfuscated code was to use this to create if statements, such as:
```
a || b();
```
if "a" is true, "b()" would never be evaluated, so we can rewrite it into:
```
if(!a)
b();
```
and similarly:
```
a && b();
```
would become
```
if(a)
b();
```
**Please note** that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised".
EDIT:
As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.
First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.
Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless. |
34,955 | <p>When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?</p>
| [
{
"answer_id": 34967,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>One of the common linking errors I've run into is when a function is used differently from how it's defined. If you see such an error you should make sure that every function you use is properly declared in some .h file.<br>\nYou should also make sure that all the relevant source files are compiled into the same lib file. An error I've run into is when I have two sets of files compiled into two separate libraries, and I cross-call between libraries.</p>\n\n<p>Is there a failure you have in mind?</p>\n"
},
{
"answer_id": 34993,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>The C-runtime libraries are often the biggest culprit. Making sure all your projects have the same settings wrt single vs multi-threading and static vs dll.</p>\n\n<p>The MSDN documentation is good for pointing out which lib a particular Win32 API call requires if it comes up as missing.</p>\n\n<p>Other than that it usually comes down to turning on the verbose flag and wading through the output looking for clues.</p>\n"
},
{
"answer_id": 41043,
"author": "Joe Schneider",
"author_id": 1541,
"author_profile": "https://Stackoverflow.com/users/1541",
"pm_score": 6,
"selected": true,
"text": "<p>Not sure what your level of expertise is, but here are the basics. </p>\n\n<p>Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it.</p>\n\n<pre><code>ByteComparator.obj : error LNK2019: unresolved external symbol \"int __cdecl does_not_exist(void)\" (?does_not_exist@@YAHXZ) referenced in function \"void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)\" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)\n</code></pre>\n\n<p>There are a couple of points to focus on: </p>\n\n<ul>\n<li>\"ByteComparator.obj\" - Look for a ByteComparator.cpp file, this is the source of the linker problem</li>\n<li>\"int __cdecl does_not_exist(void)\" - This is the symbol it couldn't find, in this case a function named does_not_exist()</li>\n</ul>\n\n<p>At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together.</p>\n\n<p>If you're using VS2005, you would use the \"Project Dependencies...\" right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file.</p>\n\n<hr>\n\n<p>In a second scenario, you may be missing an \"external\" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to <a href=\"http://msdn.microsoft.com/en-us/default.aspx\" rel=\"noreferrer\">MSDN</a> or <a href=\"http://www.google.com/microsoft\" rel=\"noreferrer\">\"Microsoft Google\"</a> and search for the API. At the bottom of the API description the library name is given. Add this to your project properties \"Configuration Properties->Linker->Input->Additional Dependencies\" list. For example, the function timeGetTime()'s <a href=\"http://msdn.microsoft.com/en-us/library/ms713418(VS.85).aspx\" rel=\"noreferrer\">page on MSDN</a> tells you to use Winmm.lib at the bottom of the page.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
] | When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors? | Not sure what your level of expertise is, but here are the basics.
Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it.
```
ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)
```
There are a couple of points to focus on:
* "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem
* "int \_\_cdecl does\_not\_exist(void)" - This is the symbol it couldn't find, in this case a function named does\_not\_exist()
At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together.
If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file.
---
In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to [MSDN](http://msdn.microsoft.com/en-us/default.aspx) or ["Microsoft Google"](http://www.google.com/microsoft) and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s [page on MSDN](http://msdn.microsoft.com/en-us/library/ms713418(VS.85).aspx) tells you to use Winmm.lib at the bottom of the page. |
34,977 | <p>I have a protocol that requires a length field up to 32-bits, and it must be
generated at runtime to describe how many bytes are in a given packet.</p>
<p>The code below is kind of ugly but I am wondering if this can be refactored to
be slightly more efficient or easily understandable. The problem is that the
code will only generate enough bytes to describe the length of the packet, so
less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length
etc...</p>
<pre><code>{
extern char byte_stream[];
int bytes = offset_in_packet;
int n = length_of_packet;
/* Under 4 billion, so this can be represented in 32 bits. */
int t;
/* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */
unsigned char first, second, third, fourth;
t = n & 0xFF000000;
/* We have used AND to "mask out" the first byte of the number. */
/* The only bits which can be on in t are the first 8 bits. */
first = t >> 24;
if (t) {
printf("byte 1: 0x%02x\n",first );
byte_stream[bytes] = first; bytes++;
write_zeros = 1;
}
/* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */
t = n & 0x00FF0000;
second = t >> 16;
if (t || write_zeros) {
printf("byte 2: 0x%02x\n", second );
byte_stream[bytes] = second; bytes++;
write_zeros = 1;
}
t = n & 0x0000FF00;
third = t >> 8;
if ( t || write_zeros) {
printf("byte 3: 0x%02x\n", third );
byte_stream[bytes] = third; bytes++;
write_zeros = 1;
}
t = n & 0x000000FF;
fourth = t;
if (t || write_zeros) {
printf("byte 4: 0x%02x\n", fourth);
byte_stream[bytes] = fourth; bytes++;
}
}
</code></pre>
| [
{
"answer_id": 35027,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>Try this loop:</p>\n\n<pre><code>{\n extern char byte_stream[];\n int bytes = offset_in_packet;\n int n = length_of_packet; /* Under 4 billion, so this can be represented in 32 bits. */\n int t; /* 32-bit number used for temporary storage. */\n int i;\n\n unsigned char curByte;\n\n for (i = 0; i < 4; i++) {\n t = n & (0xFF000000 >> (i * 16));\n\n curByte = t >> (24 - (i * 8));\n if (t || write_zeros) {\n printf(\"byte %d: 0x%02x\\n\", i, curByte );\n byte_stream[bytes] = curByte;\n bytes++;\n write_zeros = 1;\n }\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 35036,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure I understand your question. What exactly are you trying to count? If I understand correctly you're trying to find the Most Significant non-zero byte.<br>\nYou're probably better off using a loop like this: </p>\n\n<pre><code>int i; \nint write_zeros = 0; \nfor (i = 3; i >=0 ; --i) { \n t = (n >> (8 * i)) & 0xff; \n if (t || write_zeros) { \n write_zeros = 1; \n printf (\"byte %d : 0x%02x\\n\", 4-i, t); \n byte_stream[bytes++] = t;\n } \n}\n</code></pre>\n"
},
{
"answer_id": 35068,
"author": "Tryke",
"author_id": 773,
"author_profile": "https://Stackoverflow.com/users/773",
"pm_score": 2,
"selected": false,
"text": "<p>You should really use a fixed-width field for your length.</p>\n\n<ul>\n<li>When the program on the receiving end has to read the length field of your packet, how does it know where the length stops?</li>\n<li>If the length of a packet can potentially reach 4 GB, does a 1-3 byte overhead really matter?</li>\n<li>Do you see how complex your code has already become? </li>\n</ul>\n"
},
{
"answer_id": 41051,
"author": "Bart",
"author_id": 4343,
"author_profile": "https://Stackoverflow.com/users/4343",
"pm_score": 1,
"selected": true,
"text": "<p>Really you're only doing four calculations, so <strong><em>readability seems way more important</em></strong> here than efficiency. My approach to make something like this more readable is to </p>\n\n<ol>\n<li>Extract common code to a function</li>\n<li>Put similar calculations together to make the patterns more obvious</li>\n<li>Get rid of the intermediate variable print_zeroes and be explicit about the cases in which you output bytes even if they're zero (i.e. the preceding byte was non-zero)</li>\n</ol>\n\n<p>I've changed the random code block into a function and changed a few variables (underscores are giving me trouble in the markdown preview screen). I've also assumed that <em>bytes</em> is being passed in, and that whoever is passing it in will pass us a pointer so we can modify it.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>/* append byte b to stream, increment index */\n/* really needs to check length of stream before appending */\nvoid output( int i, unsigned char b, char stream[], int *index )\n{\n printf(\"byte %d: 0x%02x\\n\", i, b);\n stream[(*index)++] = b;\n}\n\n\nvoid answer( char bytestream[], unsigned int *bytes, unsigned int n)\n{\n /* mask out four bytes from word n */\n first = (n & 0xFF000000) >> 24;\n second = (n & 0x00FF0000) >> 16;\n third = (n & 0x0000FF00) >> 8;\n fourth = (n & 0x000000FF) >> 0;\n\n /* conditionally output each byte starting with the */\n /* first non-zero byte */\n if (first) \n output( 1, first, bytestream, bytes);\n\n if (first || second) \n output( 2, second, bytestream, bytes);\n\n if (first || second || third) \n output( 3, third, bytestream, bytes);\n\n if (first || second || third || fourth) \n output( 4, fourth, bytestream, bytes);\n }\n</code></pre>\n\n<p>Ever so slightly more efficient, and <strong><em>maybe</em></strong> easier to understand would be this modification to the last four if statements:</p>\n\n<pre><code> if (n>0x00FFFFFF) \n output( 1, first, bytestream, bytes);\n\n if (n>0x0000FFFF) \n output( 2, second, bytestream, bytes);\n\n if (n>0x000000FF) \n output( 3, third, bytestream, bytes);\n\n if (1) \n output( 4, fourth, bytestream, bytes);\n</code></pre>\n\n<p>I agree, however, that compressing this field makes the receiving state machine overly complicated. But if you can't change the protocol, this code is much easier to read.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663/"
] | I have a protocol that requires a length field up to 32-bits, and it must be
generated at runtime to describe how many bytes are in a given packet.
The code below is kind of ugly but I am wondering if this can be refactored to
be slightly more efficient or easily understandable. The problem is that the
code will only generate enough bytes to describe the length of the packet, so
less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length
etc...
```
{
extern char byte_stream[];
int bytes = offset_in_packet;
int n = length_of_packet;
/* Under 4 billion, so this can be represented in 32 bits. */
int t;
/* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */
unsigned char first, second, third, fourth;
t = n & 0xFF000000;
/* We have used AND to "mask out" the first byte of the number. */
/* The only bits which can be on in t are the first 8 bits. */
first = t >> 24;
if (t) {
printf("byte 1: 0x%02x\n",first );
byte_stream[bytes] = first; bytes++;
write_zeros = 1;
}
/* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */
t = n & 0x00FF0000;
second = t >> 16;
if (t || write_zeros) {
printf("byte 2: 0x%02x\n", second );
byte_stream[bytes] = second; bytes++;
write_zeros = 1;
}
t = n & 0x0000FF00;
third = t >> 8;
if ( t || write_zeros) {
printf("byte 3: 0x%02x\n", third );
byte_stream[bytes] = third; bytes++;
write_zeros = 1;
}
t = n & 0x000000FF;
fourth = t;
if (t || write_zeros) {
printf("byte 4: 0x%02x\n", fourth);
byte_stream[bytes] = fourth; bytes++;
}
}
``` | Really you're only doing four calculations, so ***readability seems way more important*** here than efficiency. My approach to make something like this more readable is to
1. Extract common code to a function
2. Put similar calculations together to make the patterns more obvious
3. Get rid of the intermediate variable print\_zeroes and be explicit about the cases in which you output bytes even if they're zero (i.e. the preceding byte was non-zero)
I've changed the random code block into a function and changed a few variables (underscores are giving me trouble in the markdown preview screen). I've also assumed that *bytes* is being passed in, and that whoever is passing it in will pass us a pointer so we can modify it.
Here's the code:
```
/* append byte b to stream, increment index */
/* really needs to check length of stream before appending */
void output( int i, unsigned char b, char stream[], int *index )
{
printf("byte %d: 0x%02x\n", i, b);
stream[(*index)++] = b;
}
void answer( char bytestream[], unsigned int *bytes, unsigned int n)
{
/* mask out four bytes from word n */
first = (n & 0xFF000000) >> 24;
second = (n & 0x00FF0000) >> 16;
third = (n & 0x0000FF00) >> 8;
fourth = (n & 0x000000FF) >> 0;
/* conditionally output each byte starting with the */
/* first non-zero byte */
if (first)
output( 1, first, bytestream, bytes);
if (first || second)
output( 2, second, bytestream, bytes);
if (first || second || third)
output( 3, third, bytestream, bytes);
if (first || second || third || fourth)
output( 4, fourth, bytestream, bytes);
}
```
Ever so slightly more efficient, and ***maybe*** easier to understand would be this modification to the last four if statements:
```
if (n>0x00FFFFFF)
output( 1, first, bytestream, bytes);
if (n>0x0000FFFF)
output( 2, second, bytestream, bytes);
if (n>0x000000FF)
output( 3, third, bytestream, bytes);
if (1)
output( 4, fourth, bytestream, bytes);
```
I agree, however, that compressing this field makes the receiving state machine overly complicated. But if you can't change the protocol, this code is much easier to read. |
34,987 | <p>I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?</p>
<p>Possible non-solutions:</p>
<pre><code>vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
</code></pre>
<p>Problems - no way to create the vector on one line with a list of strings</p>
<p>Possible non-solution 2:</p>
<pre><code>string list[] = {"abc", "xyz"};
</code></pre>
<p>Problems - no way to get the number of strings automatically (that I know of).</p>
<p>There must be an easy way of doing this.</p>
| [
{
"answer_id": 35006,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Problems - no way to get the number of strings automatically (that i know of).</p>\n</blockquote>\n\n<p>There is a bog-standard way of doing this, which lots of people (including MS) define macros like <code>arraysize</code> for:</p>\n\n<pre><code>#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))\n</code></pre>\n"
},
{
"answer_id": 35182,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <iterator>\n\nint main() {\n const char* const list[] = {\"zip\", \"zam\", \"bam\"};\n const size_t len = sizeof(list) / sizeof(list[0]);\n\n for (size_t i = 0; i < len; ++i)\n std::cout << list[i] << \"\\n\";\n\n const std::vector<string> v(list, list + len);\n std::copy(v.begin(), v.end(), std::ostream_iterator<string>(std::cout, \"\\n\"));\n}\n</code></pre>\n"
},
{
"answer_id": 35323,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 5,
"selected": false,
"text": "<p>You can concisely initialize a <code>vector<string></code> from a statically-created <code>char*</code> array:</p>\n\n<pre><code>char* strarray[] = {\"hey\", \"sup\", \"dogg\"};\nvector<string> strvector(strarray, strarray + 3);\n</code></pre>\n\n<p>This copies all the strings, by the way, so you use twice the memory. You can use Will Dean's suggestion to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.</p>\n\n<p>Also, if you're really gung-ho about the one line thingy, you can define a variadic macro so that a single line such as <code>DEFINE_STR_VEC(strvector, \"hi\", \"there\", \"everyone\");</code> works.</p>\n"
},
{
"answer_id": 35356,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>You can use Will Dean's suggestion [<code>#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))</code>] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.</p>\n</blockquote>\n\n<p>The case where it doesn't work is when the \"array\" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — <code>some_function(string parameter[])</code> is really <code>some_function(string *parameter)</code>.</p>\n"
},
{
"answer_id": 35424,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 7,
"selected": false,
"text": "<p>C++ 11 added initialization lists to allow the following syntax:</p>\n\n<pre><code>std::vector<std::string> v = {\"Hello\", \"World\"};\n</code></pre>\n\n<p>Support for this C++ 11 feature was added in at least <a href=\"http://gcc.gnu.org/projects/cxx0x.html\" rel=\"noreferrer\">GCC 4.4</a> and only in <a href=\"https://msdn.microsoft.com/en-us/library/hh567368.aspx#corelanguagetable\" rel=\"noreferrer\">Visual Studio 2013</a>.</p>\n"
},
{
"answer_id": 37330,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of that macro, might I suggest this one:</p>\n\n<pre><code>template<typename T, int N>\ninline size_t array_size(T(&)[N])\n{\n return N;\n}\n\n#define ARRAY_SIZE(X) (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)\n</code></pre>\n\n<p>1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.</p>\n\n<p>2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.</p>\n\n<p>So, we use the defined-ness of the function to make the macro \"safe\"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.</p>\n"
},
{
"answer_id": 47267,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#include <boost/foreach.hpp>\n\nconst char* list[] = {\"abc\", \"xyz\"};\nBOOST_FOREACH(const char* str, list)\n{\n cout << str << endl;\n}\n</code></pre>\n"
},
{
"answer_id": 66180,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "<p>One possiblity is to use a NULL pointer as a flag value:</p>\n\n<pre><code>const char *list[] = {\"dog\", \"cat\", NULL};\nfor (char **iList = list; *iList != NULL; ++iList)\n{\n cout << *iList;\n}\n</code></pre>\n"
},
{
"answer_id": 124480,
"author": "Ross Smith",
"author_id": 21426,
"author_profile": "https://Stackoverflow.com/users/21426",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <code>begin</code> and <code>end</code> functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.</p>\n\n<pre><code>const char* array[] = { \"cat\", \"dog\", \"horse\" };\nvector<string> vec(begin(array), end(array));\n</code></pre>\n"
},
{
"answer_id": 1893430,
"author": "Dominic.wig",
"author_id": 184997,
"author_profile": "https://Stackoverflow.com/users/184997",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <boost/assign/list_of.hpp>\n\nint main()\n{\n const std::vector< std::string > v = boost::assign::list_of( \"abc\" )( \"xyz\" );\n std::copy(\n v.begin(),\n v.end(),\n std::ostream_iterator< std::string >( std::cout, \"\\n\" ) );\n}\n</code></pre>\n"
},
{
"answer_id": 8820663,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Declare an array of strings in C++ like this : <code>char array_of_strings[][]</code></p>\n\n<p>For example : <code>char array_of_strings[200][8192];</code></p>\n\n<p>will hold 200 strings, each string having the size 8kb or 8192 bytes.</p>\n\n<p>use <code>strcpy(line[i],tempBuffer);</code> to put data in the array of strings.</p>\n"
},
{
"answer_id": 35067543,
"author": "kajol jain",
"author_id": 5853232,
"author_profile": "https://Stackoverflow.com/users/5853232",
"pm_score": 1,
"selected": false,
"text": "<p>You can directly declare an array of strings like <code>string s[100];</code>.\nThen if you want to access specific elements, you can get it directly like <code>s[2][90]</code>. For iteration purposes, take the size of string using the\n<code>s[i].size()</code> function.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/34987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779/"
] | I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?
Possible non-solutions:
```
vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
```
Problems - no way to create the vector on one line with a list of strings
Possible non-solution 2:
```
string list[] = {"abc", "xyz"};
```
Problems - no way to get the number of strings automatically (that I know of).
There must be an easy way of doing this. | C++ 11 added initialization lists to allow the following syntax:
```
std::vector<std::string> v = {"Hello", "World"};
```
Support for this C++ 11 feature was added in at least [GCC 4.4](http://gcc.gnu.org/projects/cxx0x.html) and only in [Visual Studio 2013](https://msdn.microsoft.com/en-us/library/hh567368.aspx#corelanguagetable). |
35,002 | <p><strong>Is there anything built into the core C# libraries that can give me an immutable Dictionary?</strong> </p>
<p>Something along the lines of <em>Java's</em>:</p>
<pre><code>Collections.unmodifiableMap(myMap);
</code></pre>
<p>And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called (<code>Add, Remove, Clear</code>).</p>
| [
{
"answer_id": 35045,
"author": "Kevin Dente",
"author_id": 9,
"author_profile": "https://Stackoverflow.com/users/9",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think so. There is a way to create a read-only List and read only Collection, but I don't think there's a built in read only Dictionary. System.ServiceModel has a ReadOnlyDictinoary implementation, but its internal. Probably wouldn't be too hard to copy it though, using Reflector, or to simply create your own from scratch. It basically wraps an Dictionary and throws when a mutator is called.</p>\n"
},
{
"answer_id": 35059,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 5,
"selected": false,
"text": "<p>As far as I know, there is not. But maybe you can copy some code (and learn a lot) from these articles:</p>\n\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability\" rel=\"nofollow noreferrer\">Immutability in C# Part One: Kinds of Immutability</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-two-a-simple-immutable-stack\" rel=\"nofollow noreferrer\">Immutability in C# Part Two: A Simple Immutable Stack</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-three-a-covariant-immutable-stack\" rel=\"nofollow noreferrer\">Immutability in C# Part Three: A Covariant Immutable Stack</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-four-an-immutable-queue\" rel=\"nofollow noreferrer\">Immutability in C# Part Four: An Immutable Queue</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-five-lolz\" rel=\"nofollow noreferrer\">Immutability in C# Part Five: LOLZ</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-six-a-simple-binary-tree\" rel=\"nofollow noreferrer\">Immutability in C# Part Six: A Simple Binary Tree</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-seven-more-on-binary-trees\" rel=\"nofollow noreferrer\">Immutability in C# Part Seven: More on Binary Trees</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-eight-even-more-on-binary-trees\" rel=\"nofollow noreferrer\">Immutability in C# Part Eight: Even More On Binary Trees</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-nine-academic-plus-my-avl-tree-implementation\" rel=\"nofollow noreferrer\">Immutability in C# Part Nine: Academic? Plus my AVL tree implementation</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-10-a-double-ended-queue\" rel=\"nofollow noreferrer\">Immutability in C# Part 10: A double-ended queue</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-eleven-a-working-double-ended-queue\" rel=\"nofollow noreferrer\">Immutability in C# Part Eleven: A working double-ended queue</a></li>\n</ul>\n"
},
{
"answer_id": 35099,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>\"Out of the box\" there is not a way to do this. You can create one by deriving your own Dictionary class and implementing the restrictions you need.</p>\n"
},
{
"answer_id": 35144,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>One workaround might be, throw a new list of KeyValuePair from the Dictionary to keep the original unmodified.</p>\n\n<pre><code>var dict = new Dictionary<string, string>();\n\ndict.Add(\"Hello\", \"World\");\ndict.Add(\"The\", \"Quick\");\ndict.Add(\"Brown\", \"Fox\");\n\nvar dictCopy = dict.Select(\n item => new KeyValuePair<string, string>(item.Key, item.Value));\n\n// returns dictCopy;\n</code></pre>\n\n<p>This way the original dictionary won't get modified.</p>\n"
},
{
"answer_id": 35666,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 7,
"selected": true,
"text": "<p>No, but a wrapper is rather trivial:</p>\n\n<pre><code>public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>\n{\n IDictionary<TKey, TValue> _dict;\n\n public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict)\n {\n _dict = backingDict;\n }\n\n public void Add(TKey key, TValue value)\n {\n throw new InvalidOperationException();\n }\n\n public bool ContainsKey(TKey key)\n {\n return _dict.ContainsKey(key);\n }\n\n public ICollection<TKey> Keys\n {\n get { return _dict.Keys; }\n }\n\n public bool Remove(TKey key)\n {\n throw new InvalidOperationException();\n }\n\n public bool TryGetValue(TKey key, out TValue value)\n {\n return _dict.TryGetValue(key, out value);\n }\n\n public ICollection<TValue> Values\n {\n get { return _dict.Values; }\n }\n\n public TValue this[TKey key]\n {\n get { return _dict[key]; }\n set { throw new InvalidOperationException(); }\n }\n\n public void Add(KeyValuePair<TKey, TValue> item)\n {\n throw new InvalidOperationException();\n }\n\n public void Clear()\n {\n throw new InvalidOperationException();\n }\n\n public bool Contains(KeyValuePair<TKey, TValue> item)\n {\n return _dict.Contains(item);\n }\n\n public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)\n {\n _dict.CopyTo(array, arrayIndex);\n }\n\n public int Count\n {\n get { return _dict.Count; }\n }\n\n public bool IsReadOnly\n {\n get { return true; }\n }\n\n public bool Remove(KeyValuePair<TKey, TValue> item)\n {\n throw new InvalidOperationException();\n }\n\n public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()\n {\n return _dict.GetEnumerator();\n }\n\n System.Collections.IEnumerator \n System.Collections.IEnumerable.GetEnumerator()\n {\n return ((System.Collections.IEnumerable)_dict).GetEnumerator();\n }\n}\n</code></pre>\n\n<p>Obviously, you can change the this[] setter above if you want to allow modifying values. </p>\n"
},
{
"answer_id": 503344,
"author": "Olmo",
"author_id": 38670,
"author_profile": "https://Stackoverflow.com/users/38670",
"pm_score": 1,
"selected": false,
"text": "<p>I've found an implementation of an Inmutable (not READONLY) implementation of a AVLTree for C# here. </p>\n\n<p>An AVL tree has logarithmic (not constant) cost on each operation, but stills fast.</p>\n\n<p><a href=\"http://csharpfeeds.com/post/7512/Immutability_in_Csharp_Part_Nine_Academic_Plus_my_AVL_tree_implementation.aspx\" rel=\"nofollow noreferrer\">http://csharpfeeds.com/post/7512/Immutability_in_Csharp_Part_Nine_Academic_Plus_my_AVL_tree_implementation.aspx</a></p>\n"
},
{
"answer_id": 1104668,
"author": "Sarah Vessels",
"author_id": 38743,
"author_profile": "https://Stackoverflow.com/users/38743",
"pm_score": 2,
"selected": false,
"text": "<p>Adding onto <a href=\"https://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary/35666#35666\">dbkk's answer</a>, I wanted to be able to use an object initializer when first creating my ReadOnlyDictionary. I made the following modifications:</p>\n\n<pre><code>private readonly int _finalCount;\n\n/// <summary>\n/// Takes a count of how many key-value pairs should be allowed.\n/// Dictionary can be modified to add up to that many pairs, but no\n/// pair can be modified or removed after it is added. Intended to be\n/// used with an object initializer.\n/// </summary>\n/// <param name=\"count\"></param>\npublic ReadOnlyDictionary(int count)\n{\n _dict = new SortedDictionary<TKey, TValue>();\n _finalCount = count;\n}\n\n/// <summary>\n/// To allow object initializers, this will allow the dictionary to be\n/// added onto up to a certain number, specifically the count set in\n/// one of the constructors.\n/// </summary>\n/// <param name=\"key\"></param>\n/// <param name=\"value\"></param>\npublic void Add(TKey key, TValue value)\n{\n if (_dict.Keys.Count < _finalCount)\n {\n _dict.Add(key, value);\n }\n else\n {\n throw new InvalidOperationException(\n \"Cannot add pair <\" + key + \", \" + value + \"> because \" +\n \"maximum final count \" + _finalCount + \" has been reached\"\n );\n }\n}\n</code></pre>\n\n<p>Now I can use the class like so:</p>\n\n<pre><code>ReadOnlyDictionary<string, string> Fields =\n new ReadOnlyDictionary<string, string>(2)\n {\n {\"hey\", \"now\"},\n {\"you\", \"there\"}\n };\n</code></pre>\n"
},
{
"answer_id": 1428665,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Since Linq, there is a generic interface <strong>ILookup</strong>. \nRead more in <a href=\"http://msdn.microsoft.com/en-us/library/bb534291.aspx\" rel=\"nofollow noreferrer\">MSDN</a>.</p>\n\n<p>Therefore, To simply get immutable dictionary you may call:</p>\n\n<pre><code>using System.Linq;\n// (...)\nvar dictionary = new Dictionary<string, object>();\n// (...)\nvar read_only = dictionary.ToLookup(kv => kv.Key, kv => kv.Value);\n</code></pre>\n"
},
{
"answer_id": 4057390,
"author": "SoftwareRockstar",
"author_id": 491973,
"author_profile": "https://Stackoverflow.com/users/491973",
"pm_score": -1,
"selected": false,
"text": "<p>There's also another alternative as I have described at:</p>\n\n<p><a href=\"http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/\" rel=\"nofollow\">http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/</a></p>\n\n<p>Essentially it's a subclass of ReadOnlyCollection>, which gets the work done in a more elegant manner. Elegant in the sense that it has compile-time support for making the Dictionary read-only rather than throwing exceptions from methods that modify the items within it.</p>\n"
},
{
"answer_id": 6471072,
"author": "David Moles",
"author_id": 27358,
"author_profile": "https://Stackoverflow.com/users/27358",
"pm_score": 2,
"selected": false,
"text": "<p>The open-source <a href=\"http://powercollections.codeplex.com/\" rel=\"nofollow\">PowerCollections</a> library includes a read-only dictionary wrapper (as well as read-only wrappers for pretty much everything else), accessible via a static <code>ReadOnly()</code> method on the <code>Algorithms</code> class. </p>\n"
},
{
"answer_id": 8585197,
"author": "uglybugger",
"author_id": 94697,
"author_profile": "https://Stackoverflow.com/users/94697",
"pm_score": 1,
"selected": false,
"text": "<p>You could try something like this:</p>\n\n<pre><code>private readonly Dictionary<string, string> _someDictionary;\n\npublic IEnumerable<KeyValuePair<string, string>> SomeDictionary\n{\n get { return _someDictionary; }\n}\n</code></pre>\n\n<p>This would remove the mutability problem in favour of having your caller have to either convert it to their own dictionary:</p>\n\n<pre><code>foo.SomeDictionary.ToDictionary(kvp => kvp.Key);\n</code></pre>\n\n<p>... or use a comparison operation on the key rather than an index lookup, e.g.:</p>\n\n<pre><code>foo.SomeDictionary.First(kvp => kvp.Key == \"SomeKey\");\n</code></pre>\n"
},
{
"answer_id": 12463109,
"author": "Dylan Meador",
"author_id": 684831,
"author_profile": "https://Stackoverflow.com/users/684831",
"pm_score": 4,
"selected": false,
"text": "<p>With the release of .NET 4.5, there is a new <a href=\"http://msdn.microsoft.com/en-us/library/gg712875.aspx\" rel=\"nofollow noreferrer\">ReadOnlyDictionary</a> class. You simply pass an <code>IDictionary</code> to the constructor to create the immutable dictionary.</p>\n\n<p><a href=\"https://stackoverflow.com/a/678404/684831\">Here</a> is a helpful extension method which can be used to simplify creating the readonly dictionary.</p>\n"
},
{
"answer_id": 19387663,
"author": "Fredrik Solhaug",
"author_id": 2883636,
"author_profile": "https://Stackoverflow.com/users/2883636",
"pm_score": 1,
"selected": false,
"text": "<p>In general it is a much better idea to not pass around any dictionaries in the first place (if you don't HAVE to).</p>\n\n<p>Instead - create a domain-object with an interface that doesn't offer any methods <em>modifying</em> the dictionary (that it wraps). Instead offering required LookUp-method that retrieves element from the dictionary by key (bonus is it makes it easier to use than a dictionary as well).</p>\n\n<pre><code>public interface IMyDomainObjectDictionary \n{\n IMyDomainObject GetMyDomainObject(string key);\n}\n\ninternal class MyDomainObjectDictionary : IMyDomainObjectDictionary \n{\n public IDictionary<string, IMyDomainObject> _myDictionary { get; set; }\n public IMyDomainObject GetMyDomainObject(string key) {.._myDictionary .TryGetValue..etc...};\n}\n</code></pre>\n"
},
{
"answer_id": 61090094,
"author": "Andrej Lucansky",
"author_id": 1503963,
"author_profile": "https://Stackoverflow.com/users/1503963",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is a very old question, but I somehow found it in 2020 so I suppose it may be worth noting that there is a way to create immutable dictionary now:</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutabledictionary.toimmutabledictionary?view=netcore-3.1\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutabledictionary.toimmutabledictionary?view=netcore-3.1</a></p>\n\n<p>Usage:</p>\n\n<pre><code>using System.Collections.Immutable;\n\npublic MyClass {\n private Dictionary<KeyType, ValueType> myDictionary;\n\n public ImmutableDictionary<KeyType, ValueType> GetImmutable()\n {\n return myDictionary.ToImmutableDictionary();\n }\n}\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] | **Is there anything built into the core C# libraries that can give me an immutable Dictionary?**
Something along the lines of *Java's*:
```
Collections.unmodifiableMap(myMap);
```
And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called (`Add, Remove, Clear`). | No, but a wrapper is rather trivial:
```
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
IDictionary<TKey, TValue> _dict;
public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict)
{
_dict = backingDict;
}
public void Add(TKey key, TValue value)
{
throw new InvalidOperationException();
}
public bool ContainsKey(TKey key)
{
return _dict.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return _dict.Keys; }
}
public bool Remove(TKey key)
{
throw new InvalidOperationException();
}
public bool TryGetValue(TKey key, out TValue value)
{
return _dict.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get { return _dict.Values; }
}
public TValue this[TKey key]
{
get { return _dict[key]; }
set { throw new InvalidOperationException(); }
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new InvalidOperationException();
}
public void Clear()
{
throw new InvalidOperationException();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _dict.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_dict.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _dict.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new InvalidOperationException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dict.GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)_dict).GetEnumerator();
}
}
```
Obviously, you can change the this[] setter above if you want to allow modifying values. |
35,007 | <p>Every time I create an object that has a collection property I go back and forth on the best way to do it?</p>
<ol>
<li>public property with a getter that
returns a reference to private variable</li>
<li>explicit get_ObjList and set_ObjList
methods that return and create new or cloned
objects every time</li>
<li>explicit get_ObjList that returns an
IEnumerator and a set_ObjList that
takes IEnumerator</li>
</ol>
<p>Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?</p>
<p>If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?</p>
<p>And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?</p>
<p>The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has <a href="http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx" rel="noreferrer">enumeration concerns</a> </p>
<p>Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.</p>
<p>Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?</p>
| [
{
"answer_id": 35018,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 0,
"selected": false,
"text": "<p>If you're simply looking to expose a collection on your instance, then using a getter/setter to a private member variable seems like the most sensible solution to me (your first proposed option).</p>\n"
},
{
"answer_id": 35065,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>I usually go for this, a public getter that returns System.Collections.ObjectModel.ReadOnlyCollection:</p>\n\n<pre><code>public ReadOnlyCollection<SomeClass> Collection\n{\n get\n {\n return new ReadOnlyCollection<SomeClass>(myList);\n }\n}\n</code></pre>\n\n<p>And public methods on the object to modify the collection.</p>\n\n<pre><code>Clear();\nAdd(SomeClass class);\n</code></pre>\n\n<p>If the class is supposed to be a repository for other people to mess with then I just expose the private variable as per method #1 as it saves writing your own API, but I tend to shy away from that in production code.</p>\n"
},
{
"answer_id": 35154,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 0,
"selected": false,
"text": "<p>I'm a java developer but I think this is the same for c#.</p>\n\n<p>I never expose a private collection property because other parts of the program can change it without parent noticing, so that in the getter method I return an array with the objects of the collection and in the setter method I call a <code>clearAll()</code> over the collection and then an <code>addAll()</code></p>\n"
},
{
"answer_id": 38410,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 7,
"selected": true,
"text": "<p>How you expose a collection depends entirely on how users are intended to interact with it.</p>\n\n<p><strong>1)</strong> If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question):</p>\n\n<pre><code>private readonly Collection<T> myCollection_ = new ...;\npublic Collection<T> MyCollection {\n get { return this.myCollection_; }\n}\n</code></pre>\n\n<p>This strategy is used for the <code>Items</code> collections on the WindowsForms and WPF <code>ItemsControl</code> controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items.</p>\n\n<p>WPF also exposes some settable collections to allow users to display a collection of items they control, such as the <code>ItemsSource</code> property on <code>ItemsControl</code> (option #3 from the original question). However, this is not a common use case.</p>\n\n<p><br/>\n<strong>2)</strong> If users will only be reading data maintained by the object, then you can use a readonly collection, as <a href=\"https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property#35065\">Quibblesome</a> suggested:</p>\n\n<pre><code>private readonly List<T> myPrivateCollection_ = new ...;\nprivate ReadOnlyCollection<T> myPrivateCollectionView_;\npublic ReadOnlyCollection<T> MyCollection {\n get {\n if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ }\n return this.myPrivateCollectionView_;\n }\n}\n</code></pre>\n\n<p>Note that <code>ReadOnlyCollection<T></code> provides a live view of the underlying collection, so you only need to create the view once.</p>\n\n<p>If the internal collection does not implement <code>IList<T></code>, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator:</p>\n\n<pre><code>public IEnumerable<T> MyCollection {\n get {\n foreach( T item in this.myPrivateCollection_ )\n yield return item;\n }\n}\n</code></pre>\n\n<p>This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection.</p>\n\n<p><br/>\n<strong>3)</strong> Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question):</p>\n\n<pre><code>private T[] myArray_;\npublic T[] GetMyArray( ) {\n T[] copy = new T[this.myArray_.Length];\n this.myArray_.CopyTo( copy, 0 );\n return copy;\n // Note: if you are using LINQ, calling the 'ToArray( )' \n // extension method will create a copy for you.\n}\n</code></pre>\n\n<p>You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding <code>SetMyArray( T[] array )</code> method, or use a custom indexer:</p>\n\n<pre><code>public T this[int index] {\n get { return this.myArray_[index]; }\n set {\n // TODO: validate new value; raise change event; etc.\n this.myArray_[index] = value;\n }\n}\n</code></pre>\n\n<p>(of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :)</p>\n"
},
{
"answer_id": 1235566,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 0,
"selected": false,
"text": "<p>Why do you suggest using ReadOnlyCollection(T) is a compromise? If you still need to get change notifications made on the original wrapped IList you could also use a <a href=\"http://msdn.microsoft.com/en-us/library/ms668620.aspx\" rel=\"nofollow noreferrer\">ReadOnlyObservableCollection(T)</a> to wrap your collection. Would this be less of a compromise in your scenario?</p>\n"
},
{
"answer_id": 30313404,
"author": "Johannes",
"author_id": 48621,
"author_profile": "https://Stackoverflow.com/users/48621",
"pm_score": 1,
"selected": false,
"text": "<p>ReadOnlyCollection still has the disadvantage that the consumer can't be sure that the original collection won't be changed at an inopportune time. Instead you can use <a href=\"https://msdn.microsoft.com/en-us/library/dn769092%28v=vs.111%29.aspx\" rel=\"nofollow\">Immutable Collections</a>. If you need to do a change then instead changing the original you are being given a modified copy. The way it is implemented it is competitive with the performance of the mutable collections. Or even better if you don't have to copy the original several times to make a number of different (incompatible) changes afterwards to each copy.</p>\n"
},
{
"answer_id": 32914905,
"author": "jbe",
"author_id": 103988,
"author_profile": "https://Stackoverflow.com/users/103988",
"pm_score": 1,
"selected": false,
"text": "<p>I recommend to use the new <code>IReadOnlyList<T></code> and <code>IReadOnlyCollection<T></code> Interfaces to expose a collection (requires .NET 4.5).</p>\n\n<p><em>Example:</em></p>\n\n<pre><code>public class AddressBook\n{\n private readonly List<Contact> contacts;\n\n public AddressBook()\n {\n this.contacts = new List<Contact>();\n }\n\n public IReadOnlyList<Contact> Contacts { get { return contacts; } }\n\n public void AddContact(Contact contact)\n {\n contacts.Add(contact);\n }\n\n public void RemoveContact(Contact contact)\n {\n contacts.Remove(contact);\n }\n}\n</code></pre>\n\n<p>If you need to guarantee that the collection can not be manipulated from outside then consider <code>ReadOnlyCollection<T></code> or the new Immutable collections.</p>\n\n<p><strong>Avoid</strong> using the interface <code>IEnumerable<T></code> to expose a collection.\nThis interface does not define any guarantee that multiple enumerations perform well. If the IEnumerable represents a query then every enumeration execute the query again. Developers that get an instance of IEnumerable do not know if it represents a collection or a query.</p>\n\n<p>More about this topic can be read on this <a href=\"https://github.com/jbe2277/waf/wiki/How-should-a-class-expose-a-collection%3F\" rel=\"nofollow\">Wiki page</a>.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582/"
] | Every time I create an object that has a collection property I go back and forth on the best way to do it?
1. public property with a getter that
returns a reference to private variable
2. explicit get\_ObjList and set\_ObjList
methods that return and create new or cloned
objects every time
3. explicit get\_ObjList that returns an
IEnumerator and a set\_ObjList that
takes IEnumerator
Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?
If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?
And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?
The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has [enumeration concerns](http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx)
Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.
Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.? | How you expose a collection depends entirely on how users are intended to interact with it.
**1)** If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question):
```
private readonly Collection<T> myCollection_ = new ...;
public Collection<T> MyCollection {
get { return this.myCollection_; }
}
```
This strategy is used for the `Items` collections on the WindowsForms and WPF `ItemsControl` controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items.
WPF also exposes some settable collections to allow users to display a collection of items they control, such as the `ItemsSource` property on `ItemsControl` (option #3 from the original question). However, this is not a common use case.
**2)** If users will only be reading data maintained by the object, then you can use a readonly collection, as [Quibblesome](https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property#35065) suggested:
```
private readonly List<T> myPrivateCollection_ = new ...;
private ReadOnlyCollection<T> myPrivateCollectionView_;
public ReadOnlyCollection<T> MyCollection {
get {
if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ }
return this.myPrivateCollectionView_;
}
}
```
Note that `ReadOnlyCollection<T>` provides a live view of the underlying collection, so you only need to create the view once.
If the internal collection does not implement `IList<T>`, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator:
```
public IEnumerable<T> MyCollection {
get {
foreach( T item in this.myPrivateCollection_ )
yield return item;
}
}
```
This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection.
**3)** Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question):
```
private T[] myArray_;
public T[] GetMyArray( ) {
T[] copy = new T[this.myArray_.Length];
this.myArray_.CopyTo( copy, 0 );
return copy;
// Note: if you are using LINQ, calling the 'ToArray( )'
// extension method will create a copy for you.
}
```
You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding `SetMyArray( T[] array )` method, or use a custom indexer:
```
public T this[int index] {
get { return this.myArray_[index]; }
set {
// TODO: validate new value; raise change event; etc.
this.myArray_[index] = value;
}
}
```
(of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :) |
35,011 | <p>I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?</p>
| [
{
"answer_id": 35057,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 6,
"selected": true,
"text": "<p>GACUTIL doesn't register DLLs -- not in the \"COM\" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL \"register a folder\" (not that you can do that with RegSvr32 either).</p>\n\n<p>You can use a batch FOR command such as:</p>\n\n<pre><code>FOR %a IN (C:\\MyFolderWithAssemblies\\*.dll) DO GACUTIL /i %a\n</code></pre>\n\n<p>If you place that in a batch file, you must replace %a with %%a</p>\n"
},
{
"answer_id": 35064,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the script you would put into a batch file to register all of the files in the current directory with Gacutil. You don't need to put it in a batch file (you can just copy/paste it to a Command Prompt) to do it.</p>\n\n<pre><code>FOR %1 IN (*) DO Gacutil /i %1\n</code></pre>\n\n<p>Edit: Bah, sorry I was late. I didn't see the previous post when I posted mine.</p>\n"
},
{
"answer_id": 30016364,
"author": "Legends",
"author_id": 2581562,
"author_profile": "https://Stackoverflow.com/users/2581562",
"pm_score": 2,
"selected": false,
"text": "<p>Use </p>\n\n<blockquote>\n <p>gacutil /il YourPathTo_A_TextFile.txt</p>\n</blockquote>\n\n<p>switch, if you have dlls in multiple different folders. Otherwise go with the <code>for ... in</code> loop mentioned by Euro.</p>\n\n<p>The text file should contain a list of assembly paths (one path per line) which should be installed. The paths can also be different folders all over the system.\nRun the command line as an administrator!</p>\n\n<p><strong>Here an example of the YourPathTo_A_TextFile.txt:</strong></p>\n\n<blockquote>\n <p>C:\\...Microsoft.Practices.EnterpriseLibrary.Common.dll\n C:\\...Microsoft.Practices.EnterpriseLibrary.Configuration.Design.HostAdapter.dll\n C:\\...Microsoft.Practices.EnterpriseLibrary.Configuration.Design.HostAdapterV5.dll\n C:\\...Microsoft.Practices.EnterpriseLibrary.Configuration.DesignTime.dll\n C:\\...Microsoft.Practices.EnterpriseLibrary.Configuration.EnvironmentalOverrides.dll\n C:\\...Microsoft.Practices.EnterpriseLibrary.Data.dll</p>\n</blockquote>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/667/"
] | I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution? | GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either).
You can use a batch FOR command such as:
```
FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a
```
If you place that in a batch file, you must replace %a with %%a |
35,037 | <p>I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links:</p>
<pre><code><A HREF="path to file">filename</A>
</code></pre>
<p>The filenames can be complicated:</p>
<pre><code>LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf
</code></pre>
<p>What is the correct way to link to this file on a Linux/Apache server?</p>
<p>Is there a PHP function to do this conversion?</p>
| [
{
"answer_id": 35046,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://se.php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\">urlencode()</a> should probably do what you want.</p>\n\n<p><strong>Edit</strong>: urlencode() works fine on swedish characters.</p>\n\n<pre><code>\n <?php\n echo urlencode(\"åäö\"); \n ?>\n</code></pre>\n\n<p>converts to:</p>\n\n<pre><code>\n %E5%E4%F6\n</code></pre>\n"
},
{
"answer_id": 35048,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Url_encoding\" rel=\"nofollow noreferrer\">URL encoding</a>. I think it's <code>urlencode()</code> in PHP.</p>\n"
},
{
"answer_id": 35052,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"http://php.net/manual/en/function.rawurlencode.php\" rel=\"nofollow noreferrer\">rawurlencode()</a> to convert a string according to the RFC 1738 spec.\nThis function replaces all non-alphanumeric characters by their associated code.</p>\n\n<p>The difference with <a href=\"http://php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\">urlencode()</a> is that spaces are encoded as plus signs.</p>\n\n<p>You'll probably want to use the last one.</p>\n\n<p>This technique is called Percent or URL encoding. See <a href=\"http://en.wikipedia.org/wiki/Url_encoding\" rel=\"nofollow noreferrer\">Wikipedia</a> for more details.</p>\n"
},
{
"answer_id": 35058,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.rawurlencode.php\" rel=\"nofollow noreferrer\">rawurlencode</a> will encode \"exotic\" characters in a URL.</p>\n"
},
{
"answer_id": 35077,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 1,
"selected": false,
"text": "<p>The urlencode() function will convert spaces into plus signs (+), so it won't work. The rawurlencode does the trick. Thanks.</p>\n\n<p>Be sure to convert each part of the path separately, otherwise path/file will be converted into path%2Ffile. (which was what I missed)</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2703/"
] | I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links:
```
<A HREF="path to file">filename</A>
```
The filenames can be complicated:
```
LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf
```
What is the correct way to link to this file on a Linux/Apache server?
Is there a PHP function to do this conversion? | You can use [rawurlencode()](http://php.net/manual/en/function.rawurlencode.php) to convert a string according to the RFC 1738 spec.
This function replaces all non-alphanumeric characters by their associated code.
The difference with [urlencode()](http://php.net/manual/en/function.urlencode.php) is that spaces are encoded as plus signs.
You'll probably want to use the last one.
This technique is called Percent or URL encoding. See [Wikipedia](http://en.wikipedia.org/wiki/Url_encoding) for more details. |
35,047 | <p>Perhaps the biggest risk in pushing new functionality to live lies with the database modifications required by the new code. In Rails, I believe they have 'migrations', in which you can programmatically make changes to your development host, and then make the same changes live along with the code that uses the revised schema. And roll both backs if needs be, in a synchronized fashion.</p>
<p>Has anyone come across a similar toolset for PHP/MySQL? Would love to hear about it, or any programmatic or process solutions to help make this less risky...</p>
| [
{
"answer_id": 35061,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 2,
"selected": false,
"text": "<p>Symfony has a plugin called sfMigrationsLight that handles basic migrations. CakePHP also has migrations.</p>\n\n<p>For whatever reason, migration support has never really been a high priority for most of the PHP frameworks and ORMs out there.</p>\n"
},
{
"answer_id": 35440,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 3,
"selected": false,
"text": "<p>I've never come across a tool that would do the job. Instead I've used individual files, numbered so that I know which order to run them: essentially, a manual version of Rails migrations, but without the rollback.</p>\n\n<p>Here's the sort of thing I'm talking about:</p>\n\n<pre><code>000-clean.sql # wipe out everything in the DB\n001-schema.sql # create the initial DB objects\n002-fk.sql # apply referential integrity (simple if kept separate)\n003-reference-pop.sql # populate reference data\n004-release-pop.sql # populate release data\n005-add-new-table.sql # modification\n006-rename-table.sql # another modification...\n</code></pre>\n\n<p>I've never actually run into any problems doing this, but it's not very elegant. It's up to you to track which scripts need to run for a given update (a smarter numbering scheme could help). It also works fine with source control.</p>\n\n<p>Dealing with surrogate key values (from autonumber columns) can be a pain, since the production database will likely have different values than the development DB. So, I try never to reference a literal surrogate key value in any of my modification scripts if at all possible.</p>\n"
},
{
"answer_id": 35444,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>I don't trust programmatic migrations. If it's a simple change, such as adding a NULLable column, I'll just add it directly to the live server. If it's more complex or requires data changes, I'll write a pair of SQL migration files and test them against a replica database.</p>\n\n<p>When using migrations, <em>always</em> test the rollback migration. It is your emergency \"oh shit\" button.</p>\n"
},
{
"answer_id": 35972,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://www.webyog.com\" rel=\"nofollow noreferrer\">SQLyog</a> to copy the structure, and I ALWAYS, let me repeat ALWAYS make a backup first.</p>\n"
},
{
"answer_id": 87489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've used this tool before and it worked perfectly.</p>\n\n<p><a href=\"http://www.mysqldiff.org/\" rel=\"nofollow noreferrer\">http://www.mysqldiff.org/</a></p>\n\n<p>It takes as an input either a DB connection or a SQL file, and compares it to the same (either another DB connection or another SQL file). It can spit out the SQL to make the changes or make the changes for you.</p>\n"
},
{
"answer_id": 87595,
"author": "Lot105",
"author_id": 9801,
"author_profile": "https://Stackoverflow.com/users/9801",
"pm_score": 2,
"selected": false,
"text": "<p>@[yukondude] </p>\n\n<p>I'm using Perl myself, and I've gone down the route of Rails-style migrations semi-manually in the same way. </p>\n\n<p>What I did was have a single table \"version\" with a single column \"version\", containing a single row of one number which is the current schema version. Then it was (quite) trivial to write a script to read that number, look in a certain directory and apply all the numbered migrations to get from there to here (and then updating the number).</p>\n\n<p>In my dev/stage environment I frequently (via another script) pull the production data into the staging database, and run the migration script. If you do this before you go live you'll be pretty sure the migrations will work. Obviously you test extensively in your staging environment.</p>\n\n<p>I tag up the new code and the required migrations under one version control tag. To deploy to stage or live you just update everything to this tag and run the migration script fairly quick. (You might want to have arranged a short downtime if it's really wacky schema changes.)</p>\n"
},
{
"answer_id": 87631,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 2,
"selected": false,
"text": "<p>Pretty much what Lot105 described.</p>\n\n<p>Each migration needs an apply and rollback script, and you have some kind of control script which checks which migration(s) need to be applied and applies them in the appropriate order. </p>\n\n<p>Each developer then keeps their db in sync using this scheme, and when applied to production the relevant changes are applied. The rollback scripts can be kept to back out a change if that becomes necessary.</p>\n\n<p>Some changes can't be done with a simple ALTER script such as a tool like sqldiff would produce; some changes don't require a schema change but a programmatic change to existing data. So you can't really generalise, which is why you need a human-edited script.</p>\n"
},
{
"answer_id": 1047119,
"author": "Paulo",
"author_id": 68041,
"author_profile": "https://Stackoverflow.com/users/68041",
"pm_score": 0,
"selected": false,
"text": "<p>I've always preferred to keep my development site pointing to the same DB as the live site. This may sound risky at first but in reality it solves many problems. If you have two sites on the same server pointing to the same DB, you get a real time and accurate view of what your users will see when it goes live. </p>\n\n<p>You will only ever have 1 database and so long as you make it a policy to never delete a column from a table, you know your new code will match up with the database you are using.</p>\n\n<p>There is also significantly less havoc when migrating. You only need to move over the PHP scripts and they are already tested using the same DB.</p>\n\n<p>I also tend to create a symlink to any folder that is a target for user uploads. This means there is no confusion on which user files have been updated.</p>\n\n<p>Another side affect is the option of porting over a small group of 'beta-testers' to use the site in everyday use. This can lead to a lot of feedback that you can implement <em>before</em> the public launch.</p>\n\n<p>This may not work in all cases but I've started moving all my updates to this model. It's caused much smoother development and launches.</p>\n"
},
{
"answer_id": 3488657,
"author": "Mike Howsden",
"author_id": 227651,
"author_profile": "https://Stackoverflow.com/users/227651",
"pm_score": 2,
"selected": false,
"text": "<p>The solution I use (originally developed by a friend of mine) is another addendum to yukondude. </p>\n\n<ol>\n<li>Create a schema directory under version control and then for each db change you make keep a .sql file with the SQL you want executed along with the sql query to update the db_schema table. </li>\n<li>Create a database table called \"db_schema\" with an integer column named version.</li>\n<li>In the schema directory create two shell scripts, \"current\" and \"update\". Executing current tells you which version of the db schema the database you're connected to is currently at. Running update executes each .sql file numbered greater than the version in the db_schema table sequentially until you're up to the greatest numbered file in your schema dir.</li>\n</ol>\n\n<p>Files in the schema dir:</p>\n\n<blockquote>\n<pre><code>0-init.sql \n1-add-name-to-user.sql\n2-add-bio.sql\n</code></pre>\n</blockquote>\n\n<p>What a typical file looks like, note the db_schema update at the end of every .sql file:</p>\n\n<pre><code>BEGIN;\n-- comment about what this is doing\nALTER TABLE user ADD COLUMN bio text NULL;\n\nUPDATE db_schema SET version = 2;\nCOMMIT;\n</code></pre>\n\n<p>The \"current\" script (for psql):</p>\n\n<pre><code>#!/bin/sh\n\nVERSION=`psql -q -t <<EOF\n\\set ON_ERROR_STOP on\nSELECT version FROM db_schema;\nEOF\n`\n\n[ $? -eq 0 ] && {\n echo $VERSION\n exit 0\n}\n\necho 0\n</code></pre>\n\n<p>the update script (also psql):</p>\n\n<pre><code>#!/bin/sh\n\nCURRENT=`./current`\nLATEST=`ls -vr *.sql |egrep -o \"^[0-9]+\" |head -n1`\n\necho current is $CURRENT\necho latest is $LATEST\n\n[[ $CURRENT -gt $LATEST ]] && {\n echo That seems to be a problem.\n exit 1\n}\n\n[[ $CURRENT -eq $LATEST ]] && exit 0\n\n#SCRIPT_SET=\"-q\"\nSCRIPT_SET=\"\"\n\nfor (( I = $CURRENT + 1 ; I <= $LATEST ; I++ )); do\n SCRIPT=`ls $I-*.sql |head -n1`\n echo \"Adding '$SCRIPT'\"\n SCRIPT_SET=\"$SCRIPT_SET $SCRIPT\"\ndone\n\necho \"Applying updates...\"\necho $SCRIPT_SET\nfor S in $SCRIPT_SET ; do\n psql -v ON_ERROR_STOP=TRUE -f $S || {\n echo FAIL\n exit 1\n }\ndone\necho OK\n</code></pre>\n\n<p>My 0-init.sql has the full initial schema structure along with the initial \"UPDATE db_schema SET version = 0;\". Shouldn't be too hard to modify these scripts for MySQL. In my case I also have </p>\n\n<blockquote>\n<pre><code>export PGDATABASE=\"dbname\"\nexport PGUSER=\"mike\"\n</code></pre>\n</blockquote>\n\n<p>in my .bashrc. And it prompts for password with each file that's being executed.</p>\n"
},
{
"answer_id": 6504248,
"author": "chiborg",
"author_id": 130121,
"author_profile": "https://Stackoverflow.com/users/130121",
"pm_score": 0,
"selected": false,
"text": "<p>In the past I have used <a href=\"http://www.liquibase.org/\" rel=\"nofollow\">LiquiBase</a>, a Java-based tool where you configure your migrations as XML files. You can generate the necessary SQL with it.</p>\n\n<p>Today I'd use the <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow\">Doctrine 2</a> library which has <a href=\"http://www.doctrine-project.org/projects/migrations/2.0/docs/reference/managing-migrations/en\" rel=\"nofollow\">migration facilities</a> similar to Ruby. </p>\n\n<p>The <a href=\"http://symfony.com/\" rel=\"nofollow\">Symfony 2</a> framework also has a nice way to deal with schema changes - its command line tool can analyze the existing schema and generate SQL to match the database to the changed schema definitions.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | Perhaps the biggest risk in pushing new functionality to live lies with the database modifications required by the new code. In Rails, I believe they have 'migrations', in which you can programmatically make changes to your development host, and then make the same changes live along with the code that uses the revised schema. And roll both backs if needs be, in a synchronized fashion.
Has anyone come across a similar toolset for PHP/MySQL? Would love to hear about it, or any programmatic or process solutions to help make this less risky... | I've never come across a tool that would do the job. Instead I've used individual files, numbered so that I know which order to run them: essentially, a manual version of Rails migrations, but without the rollback.
Here's the sort of thing I'm talking about:
```
000-clean.sql # wipe out everything in the DB
001-schema.sql # create the initial DB objects
002-fk.sql # apply referential integrity (simple if kept separate)
003-reference-pop.sql # populate reference data
004-release-pop.sql # populate release data
005-add-new-table.sql # modification
006-rename-table.sql # another modification...
```
I've never actually run into any problems doing this, but it's not very elegant. It's up to you to track which scripts need to run for a given update (a smarter numbering scheme could help). It also works fine with source control.
Dealing with surrogate key values (from autonumber columns) can be a pain, since the production database will likely have different values than the development DB. So, I try never to reference a literal surrogate key value in any of my modification scripts if at all possible. |
35,070 | <p>What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.</p>
<p>Or, if there's a better way to unit test against the registry...</p>
| [
{
"answer_id": 35092,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 2,
"selected": false,
"text": "<p>I looked into it by checking out my file associations.</p>\n\n<p>It seems that a .reg file is just called as the first parameter to the <code>regedit.exe</code> executable on Windows. </p>\n\n<p>So you can just say <code>regedit.exe \"mytest.reg\"</code>. What I'm not sure of is how to get rid of the dialog box that pops up that asks for your confirmation.</p>\n"
},
{
"answer_id": 35098,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 1,
"selected": false,
"text": "<p>Use the Win32 API function ShellExecute() or ShellExecuteEx(). If the comment is 'open' it should merge the .reg file. I haven't tested it, but it should work.</p>\n"
},
{
"answer_id": 35162,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 4,
"selected": true,
"text": "<p>It is possible to remove registry keys using a .reg file, although I'm not sure how well it's documented. Here's how:</p>\n\n<pre><code>REGEDIT4\n\n[-HKEY_CURRENT_USER\\Software\\<otherpath>]\n</code></pre>\n\n<p>The <code>-</code> in front of the key name tells <code>Regedit</code> that you want to remove the key.</p>\n\n<p>To run this silently, type:</p>\n\n<pre><code>regedit /s \"myfile.reg\"\n</code></pre>\n"
},
{
"answer_id": 53014,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>One of the most frustrating things about writing unit tests is dealing with dependencies. One of the greatest things about Test-Driven Development is that it produces code that is decoupled from its dependencies. Cool, huh?</p>\n\n<p>When I find myself asking questions like this one, I look for ways to decouple the code I'm writing from the dependency. Separate out the reading of the registry from the complexity that you'd like to test.</p>\n"
},
{
"answer_id": 53017,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": false,
"text": "<p>If you're shelling out, I'd use the reg command (details below). If you can tell us what language you're working with, we could provide language specific code.</p>\n\n<p>C:>reg /?</p>\n\n<p>REG Operation [Parameter List]</p>\n\n<p>Operation [ QUERY | ADD | DELETE | COPY |\n SAVE | LOAD | UNLOAD | RESTORE |\n COMPARE | EXPORT | IMPORT | FLAGS ]</p>\n\n<p>Return Code: (Except for REG COMPARE)</p>\n\n<p>0 - Successful\n 1 - Failed</p>\n\n<p>For help on a specific operation type:</p>\n\n<p>REG ADD /?\n REG DELETE /?\n[snipped]</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] | What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.
Or, if there's a better way to unit test against the registry... | It is possible to remove registry keys using a .reg file, although I'm not sure how well it's documented. Here's how:
```
REGEDIT4
[-HKEY_CURRENT_USER\Software\<otherpath>]
```
The `-` in front of the key name tells `Regedit` that you want to remove the key.
To run this silently, type:
```
regedit /s "myfile.reg"
``` |
35,076 | <p>I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove.</p>
<p>The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used.</p>
<p>What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this?</p>
| [
{
"answer_id": 35087,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>If you have lastupdate columns you can check for the writes, there is really no easy way to check for reads. You could run profiler, save the trace to a table and check in there</p>\n\n<p>What I usually do is rename the table by prefixing it with an underscrore, when people start to scream I just rename it back</p>\n"
},
{
"answer_id": 35094,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>If by not used, you mean your application has no more references to the tables in question and you are using dynamic sql, you could do a search for the table names in your app, if they don't exist blow them away.</p>\n\n<p>I've also outputted all sprocs, functions, etc. to a text file and done a search for the table names. If not found, or found in procedures that will need to be deleted too, blow them away.</p>\n"
},
{
"answer_id": 35100,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 4,
"selected": true,
"text": "<p>MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications. </p>\n\n<p>Another way I think you might check if there's any \"writes\" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type </p>\n\n<pre><code>select * from ...\n</code></pre>\n\n<p>then they will receive a new column and that might cause you some problems. </p>\n"
},
{
"answer_id": 35157,
"author": "tonygambone",
"author_id": 3344,
"author_profile": "https://Stackoverflow.com/users/3344",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like using the Profiler is going to work. Once I've let it run for a while, I should have a good list of used tables. Anyone who doesn't use their tables every day can probably wait for them to be restored from backup. Thanks, folks.</p>\n"
},
{
"answer_id": 35197,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 1,
"selected": false,
"text": "<p>Another suggestion for tracking tables that have been written to is to use <a href=\"http://www.red-gate.com/products/SQL_Log_Rescue/index.htm\" rel=\"nofollow noreferrer\">Red Gate SQL Log Rescue</a> (free). This tool dives into the log of the database and will show you all inserts, updates and deletes. The list is fully searchable, too.</p>\n\n<p>It doesn't meet your criteria for researching reads into the database, but I think the SQL Profiler technique will get you a fair idea as far as that goes.</p>\n"
},
{
"answer_id": 213915,
"author": "John MacIntyre",
"author_id": 29043,
"author_profile": "https://Stackoverflow.com/users/29043",
"pm_score": 0,
"selected": false,
"text": "<p>Probably too late to help mogrify, but for anybody doing a search; I would search for all objects using this object in my code, then in SQL Server by running this :</p>\n\n<p>select distinct '[' + object_name(id) + ']'<br/>\nfrom syscomments<br/>\nwhere text like '%MY_TABLE_NAME%'</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3344/"
] | I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove.
The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used.
What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this? | MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications.
Another way I think you might check if there's any "writes" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type
```
select * from ...
```
then they will receive a new column and that might cause you some problems. |
35,102 | <p>In emacs, I've read the following code snippet in <code>simple.el</code>:</p>
<pre><code>(frame-parameter frame 'buried-buffer-list)
</code></pre>
<p>What is the exact meaning of the <code>'buried-buffer-list</code> parameter?
What it is used for?</p>
| [
{
"answer_id": 35087,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>If you have lastupdate columns you can check for the writes, there is really no easy way to check for reads. You could run profiler, save the trace to a table and check in there</p>\n\n<p>What I usually do is rename the table by prefixing it with an underscrore, when people start to scream I just rename it back</p>\n"
},
{
"answer_id": 35094,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>If by not used, you mean your application has no more references to the tables in question and you are using dynamic sql, you could do a search for the table names in your app, if they don't exist blow them away.</p>\n\n<p>I've also outputted all sprocs, functions, etc. to a text file and done a search for the table names. If not found, or found in procedures that will need to be deleted too, blow them away.</p>\n"
},
{
"answer_id": 35100,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 4,
"selected": true,
"text": "<p>MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications. </p>\n\n<p>Another way I think you might check if there's any \"writes\" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type </p>\n\n<pre><code>select * from ...\n</code></pre>\n\n<p>then they will receive a new column and that might cause you some problems. </p>\n"
},
{
"answer_id": 35157,
"author": "tonygambone",
"author_id": 3344,
"author_profile": "https://Stackoverflow.com/users/3344",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like using the Profiler is going to work. Once I've let it run for a while, I should have a good list of used tables. Anyone who doesn't use their tables every day can probably wait for them to be restored from backup. Thanks, folks.</p>\n"
},
{
"answer_id": 35197,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 1,
"selected": false,
"text": "<p>Another suggestion for tracking tables that have been written to is to use <a href=\"http://www.red-gate.com/products/SQL_Log_Rescue/index.htm\" rel=\"nofollow noreferrer\">Red Gate SQL Log Rescue</a> (free). This tool dives into the log of the database and will show you all inserts, updates and deletes. The list is fully searchable, too.</p>\n\n<p>It doesn't meet your criteria for researching reads into the database, but I think the SQL Profiler technique will get you a fair idea as far as that goes.</p>\n"
},
{
"answer_id": 213915,
"author": "John MacIntyre",
"author_id": 29043,
"author_profile": "https://Stackoverflow.com/users/29043",
"pm_score": 0,
"selected": false,
"text": "<p>Probably too late to help mogrify, but for anybody doing a search; I would search for all objects using this object in my code, then in SQL Server by running this :</p>\n\n<p>select distinct '[' + object_name(id) + ']'<br/>\nfrom syscomments<br/>\nwhere text like '%MY_TABLE_NAME%'</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3673/"
] | In emacs, I've read the following code snippet in `simple.el`:
```
(frame-parameter frame 'buried-buffer-list)
```
What is the exact meaning of the `'buried-buffer-list` parameter?
What it is used for? | MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications.
Another way I think you might check if there's any "writes" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type
```
select * from ...
```
then they will receive a new column and that might cause you some problems. |
35,103 | <p>I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file.</p>
<p>Essentially if someone modifies this file outside of the program the program should fail to load it again.</p>
<p>EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place.</p>
<p>The configuration still needs to be editable though so compiling an individual copy for each customer is not an option.</p>
<hr>
<p>It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes.</p>
| [
{
"answer_id": 35109,
"author": "Joel Martinez",
"author_id": 3433,
"author_profile": "https://Stackoverflow.com/users/3433",
"pm_score": -1,
"selected": false,
"text": "<p>just make a const string that holds the md5 hash and compile it into your app ... your app can then just refer to this const string when validating the configuration file</p>\n"
},
{
"answer_id": 35116,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 5,
"selected": true,
"text": "<p>A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret \"key\" value, like a fixed guid, in the MD5.</p>\n\n<pre><code>write(MD5(SecretKey + ConfigFileText));\n</code></pre>\n\n<p>Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key.</p>\n\n<p>Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. </p>\n\n<p>A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort.</p>\n\n<p>If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is <em>virus like</em> behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.</p>\n\n<p><strong>Update:</strong> I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you <em>must</em> do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael.</p>\n\n<p><strong>Update:</strong> The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere \"secret\" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances.</p>\n\n<p><strong>UPDATE:</strong> For a Credit Card system you might want to consider some real security. You should retain the services of a <em>security and cryptography consultant</em>. More information needs to be exchanged. They need to analyze your specific needs and risks. </p>\n\n<p>Also, if you want security with .NET you need to first start with a really good .NET obfuscator (<a href=\"http://www.google.com/search?hl=en&q=.NET%20obfuscator&aq=f&oq=\" rel=\"nofollow noreferrer\">just Google it</a>). A .NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. </p>\n"
},
{
"answer_id": 35117,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p>Out of pure curiosity, what's your reasoning for never wanting to load the file if it's been changed?</p>\n\n<p>Why not just keep all of the configuration information compiled in the executable? Why bother with an external file at all?</p>\n\n<p><strong><em>Edit</em></strong></p>\n\n<p>I just read your edit about this being a credit card info program. That poses a very interesting challenge.</p>\n\n<p>I would think, for that level of security, some sort of pretty major encryption would be necessary but I don't know anything about handling that sort of thing in such a way that the cryptographic secrets can't just be extracted from the executable.</p>\n\n<p>Is authenticating against some sort of online source a possibility?</p>\n"
},
{
"answer_id": 35161,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest you use a <strong>Assymmetric Key Encryption</strong> to encrypt your configuration file, wherever they are stored, inside the executable or not.</p>\n<p>If I remember correctly, RSA is one the variants.</p>\n<p>For the explanation of it, see <a href=\"http://en.wikipedia.org/wiki/Public-key_cryptography\" rel=\"nofollow noreferrer\">Public-key cryptography</a> on Wikipedia</p>\n<p>Store the "reading" key in your executable and keep to yourself the "writing" key. So no one but you can modify the configuration.</p>\n<p>This has the advantages of:</p>\n<ul>\n<li>No-one can modify the configuration unless they have the "writing" key because any modification will <em>corrupt</em> it entirely, even if they know the "reading" key it would takes ages to compute the other key.</li>\n<li>Modification guarantee.</li>\n<li>It's not hard - there are plenty of libraries available these days. There're also a lot of key-generation programs that can generate really, really long keys.</li>\n</ul>\n<p>Do take some research on how to properly implement them though.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] | I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file.
Essentially if someone modifies this file outside of the program the program should fail to load it again.
EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place.
The configuration still needs to be editable though so compiling an individual copy for each customer is not an option.
---
It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes. | A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5.
```
write(MD5(SecretKey + ConfigFileText));
```
Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key.
Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored.
A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort.
If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is *virus like* behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.
**Update:** I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you *must* do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael.
**Update:** The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances.
**UPDATE:** For a Credit Card system you might want to consider some real security. You should retain the services of a *security and cryptography consultant*. More information needs to be exchanged. They need to analyze your specific needs and risks.
Also, if you want security with .NET you need to first start with a really good .NET obfuscator ([just Google it](http://www.google.com/search?hl=en&q=.NET%20obfuscator&aq=f&oq=)). A .NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. |
35,106 | <p>I've found <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.scriptingjsonserializationsection.scriptingjsonserializationsection.aspx" rel="noreferrer"><code>ScriptingJsonSerializationSection</code></a> but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <code><System.Web.Services.WebMethod()></code> and <code><System.Web.Script.Services.ScriptMethod()></code> attributes so there must be a built-in way that I'm missing. </p>
<p>PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.</p>
| [
{
"answer_id": 35125,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 5,
"selected": true,
"text": "<p>This should do the trick</p>\n\n<pre><code>Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer\nDim jsonString as String = jsonSerialiser.Serialize(yourObject)\n</code></pre>\n"
},
{
"answer_id": 35128,
"author": "Joseph Kingry",
"author_id": 3046,
"author_profile": "https://Stackoverflow.com/users/3046",
"pm_score": 3,
"selected": false,
"text": "<p>I think what you're looking for is this class:</p>\n\n<p><code>System.ServiceModel.Web.DataContractJsonSerializer</code></p>\n\n<p>Here's an example from Rick Strahl: <a href=\"http://www.west-wind.com/WebLog/posts/218001.aspx\" rel=\"nofollow noreferrer\">DataContractJsonSerializer in .NET 3.5</a></p>\n"
},
{
"answer_id": 35132,
"author": "Jarrod Dixon",
"author_id": 3,
"author_profile": "https://Stackoverflow.com/users/3",
"pm_score": 2,
"selected": false,
"text": "<p>In the System.Web.Extensions assembly, version 3.5.0.0, there's a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\" rel=\"nofollow noreferrer\">JavaScriptSerializer</a> class that should handle what you want.</p>\n"
},
{
"answer_id": 35133,
"author": "Steven Williams",
"author_id": 3294,
"author_profile": "https://Stackoverflow.com/users/3294",
"pm_score": 1,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>System.Web.Script.Serialization.JavaScriptSerializer\n</code></pre>\n\n<p>or Check out <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON.org</a> there is a whole list of libraries written to do exactly what you want.</p>\n"
},
{
"answer_id": 35134,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 2,
"selected": false,
"text": "<p>Since the JavaScriptSerializer class is technically being deprecated, I believe <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx\" rel=\"nofollow noreferrer\">DataContractJsonSerializer</a> is the preferable way to go if you're using 3.0+.</p>\n"
},
{
"answer_id": 35136,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I am currently using the following extension methods to serialize and deserialize objects:</p>\n\n<pre><code>using System.Web.Script.Serialization;\n\npublic static string ToJSON(this object objectToSerialize)\n{\n JavaScriptSerializer jss = new JavaScriptSerializer();\n return jss.Serialize(objectToSerialize);\n}\n\n/// <typeparam name=\"T\">The type we are deserializing the JSON to.</typeparam>\npublic static T FromJSON<T>(this string json)\n{\n JavaScriptSerializer jss = new JavaScriptSerializer();\n return jss.Deserialize<T>(json);\n}\n</code></pre>\n\n<p>I use this quite a bit - be forewarned, this implementation is a bit naive (i.e. there are some potential problems with it, depending on what you are serializing and how you use it on the client, particularly with DateTimes).</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | I've found [`ScriptingJsonSerializationSection`](http://msdn.microsoft.com/en-us/library/system.web.configuration.scriptingjsonserializationsection.scriptingjsonserializationsection.aspx) but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the `<System.Web.Services.WebMethod()>` and `<System.Web.Script.Services.ScriptMethod()>` attributes so there must be a built-in way that I'm missing.
PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it. | This should do the trick
```
Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString as String = jsonSerialiser.Serialize(yourObject)
``` |
35,123 | <p>What did I do wrong?</p>
<p>Here is an excerpt from my code:</p>
<pre><code>public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
mParent = new Composite(scrollBox, SWT.NONE);
scrollBox.setContent(mParent);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.layout();
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
}
</code></pre>
<p>...but it clips the last button:
<img src="https://i.stack.imgur.com/1ubzc.png" alt="alt text" title="Screenshot"></p>
<p>bigbrother82: That didn't work.</p>
<p>SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that.</p>
| [
{
"answer_id": 35503,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 0,
"selected": false,
"text": "<p>Don't you need to recompute the size of the scrollBox after the layout?</p>\n"
},
{
"answer_id": 36306,
"author": "Jacob Schoen",
"author_id": 3340,
"author_profile": "https://Stackoverflow.com/users/3340",
"pm_score": 2,
"selected": false,
"text": "<p>If I am not mistaken you need to swap the </p>\n\n<pre><code>mParent.layout();\n</code></pre>\n\n<p>and</p>\n\n<pre><code>mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));\n</code></pre>\n\n<p>so that you have:</p>\n\n<pre><code>public void createPartControl(Composite parent) {\n parent.setLayout(new FillLayout());\n ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);\n scrollBox.setExpandHorizontal(true);\n mParent = new Composite(scrollBox, SWT.NONE);\n scrollBox.setContent(mParent);\n FormLayout layout = new FormLayout();\n mParent.setLayout(layout);\n // Adds a bunch of controls here\n mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));\n mParent.layout();\n}\n</code></pre>\n"
},
{
"answer_id": 152324,
"author": "alexmcchessers",
"author_id": 998,
"author_profile": "https://Stackoverflow.com/users/998",
"pm_score": 0,
"selected": false,
"text": "<p>Try setting .setMinWidth and .setMinHeight on the ScrolledComposite once the layout has been done, passing it the size of the main composite.</p>\n"
},
{
"answer_id": 159454,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 5,
"selected": true,
"text": "<p>This is a common hurdle when using <code>ScrolledComposite</code>. When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the minimum height needed by the content composite.</p>\n\n<p>You need to listen for width changes on the content composite (<code>mParent</code>), compute the minimum height again given the new content width, and call <code>setMinHeight()</code> on the scrolled composite with new height.</p>\n\n<pre><code>public void createPartControl(Composite parent) {\n parent.setLayout(new FillLayout());\n ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);\n scrollBox.setExpandHorizontal(true);\n scrollBox.setExpandVertical(true);\n\n // Using 0 here ensures the horizontal scroll bar will never appear. If\n // you want the horizontal bar to appear at some threshold (say 100\n // pixels) then send that value instead.\n scrollBox.setMinWidth(0);\n\n mParent = new Composite(scrollBox, SWT.NONE);\n\n FormLayout layout = new FormLayout();\n mParent.setLayout(layout);\n\n // Adds a bunch of controls here\n\n mParent.addListener(SWT.Resize, new Listener() {\n int width = -1;\n public void handleEvent(Event e) {\n int newWidth = mParent.getSize().x;\n if (newWidth != width) {\n scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y);\n width = newWidth;\n }\n }\n }\n\n // Wait until here to set content pane. This way the resize listener will\n // fire when the scrolled composite first resizes mParent, which in turn\n // computes the minimum height and calls setMinHeight()\n scrollBox.setContent(mParent);\n}\n</code></pre>\n\n<p>In listening for size changes, note that we ignore any resize events where the width stays the same. This is because changes in the height of the content do not affect the <i>minimum</i> height of the content, as long as the width is the same.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
] | What did I do wrong?
Here is an excerpt from my code:
```
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
mParent = new Composite(scrollBox, SWT.NONE);
scrollBox.setContent(mParent);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.layout();
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
}
```
...but it clips the last button:

bigbrother82: That didn't work.
SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that. | This is a common hurdle when using `ScrolledComposite`. When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the minimum height needed by the content composite.
You need to listen for width changes on the content composite (`mParent`), compute the minimum height again given the new content width, and call `setMinHeight()` on the scrolled composite with new height.
```
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
scrollBox.setExpandVertical(true);
// Using 0 here ensures the horizontal scroll bar will never appear. If
// you want the horizontal bar to appear at some threshold (say 100
// pixels) then send that value instead.
scrollBox.setMinWidth(0);
mParent = new Composite(scrollBox, SWT.NONE);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.addListener(SWT.Resize, new Listener() {
int width = -1;
public void handleEvent(Event e) {
int newWidth = mParent.getSize().x;
if (newWidth != width) {
scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y);
width = newWidth;
}
}
}
// Wait until here to set content pane. This way the resize listener will
// fire when the scrolled composite first resizes mParent, which in turn
// computes the minimum height and calls setMinHeight()
scrollBox.setContent(mParent);
}
```
In listening for size changes, note that we ignore any resize events where the width stays the same. This is because changes in the height of the content do not affect the *minimum* height of the content, as long as the width is the same. |
35,167 | <p>I know that the following is true</p>
<pre><code>int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
</code></pre>
<p>But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with.</p>
<p>Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop.</p>
| [
{
"answer_id": 35172,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 7,
"selected": true,
"text": "<p>If you know the size of type, you could do something like:</p>\n\n<pre><code>uint i = 17;\nuint j = i << 1 | i >> 31;\n</code></pre>\n\n<p>... which would perform a circular shift of a 32 bit value.</p>\n\n<p>As a generalization to circular shift left n bits, on a b bit variable:</p>\n\n<pre><code>/*some unsigned numeric type*/ input = 17;\nvar result = input << n | input >> (b - n);\n</code></pre>\n\n<p><hr/>\n@The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this <a href=\"http://www.blackwasp.co.uk/CSharpShiftOperators.aspx\" rel=\"noreferrer\">here</a>. I also changed the example to use a uint.</p>\n"
},
{
"answer_id": 185743,
"author": "jaircazarin-old-account",
"author_id": 20915,
"author_profile": "https://Stackoverflow.com/users/20915",
"pm_score": 4,
"selected": false,
"text": "<p>One year ago I've to implement MD4 for my undergraduate thesis. Here it is my implementation of circular bit shift using a UInt32.</p>\n\n<pre><code>private UInt32 RotateLeft(UInt32 x, Byte n)\n{\n return UInt32((x << n) | (x >> (32 - n)));\n}\n</code></pre>\n"
},
{
"answer_id": 1042452,
"author": "yeyeyerman",
"author_id": 110466,
"author_profile": "https://Stackoverflow.com/users/110466",
"pm_score": 2,
"selected": false,
"text": "<p>Just as reference on how to do it, these two functions work perfectly for rotating the bits of 1/2word:</p>\n\n<pre><code>static public uint ShiftRight(uint z_value, int z_shift)\n{\n return ((z_value >> z_shift) | (z_value << (16 - z_shift))) & 0x0000FFFF;\n}\n\nstatic public uint ShiftLeft(uint z_value, int z_shift)\n{\n return ((z_value << z_shift) | (z_value >> (16 - z_shift))) & 0x0000FFFF;\n}\n</code></pre>\n\n<p>It would be easy to extend it for any given size.</p>\n"
},
{
"answer_id": 60161031,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": false,
"text": "<p>Sincce .NET Core 3.0 and up there's <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.numerics.bitoperations.rotateleft?view=netcore-3.1\" rel=\"noreferrer\"><code>BitOperations.RotateLeft()</code></a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.numerics.bitoperations.rotateright?view=netcore-3.1\" rel=\"noreferrer\"><code>BitOperations.RotateRight()</code></a> so you can just use something like</p>\n\n<pre><code>BitOperations.RotateRight(12, 3);\nBitOperations.RotateLeft(34L, 5);\n</code></pre>\n\n<p>In previous versions you can use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.utilities.bitrotator.rotateleft?view=visualstudiosdk-2015\" rel=\"noreferrer\"><code>BitRotator.RotateLeft()</code></a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.utilities.bitrotator.rotateright?view=visualstudiosdk-2015\" rel=\"noreferrer\"><code>BitRotator.RotateRight()</code></a> in Microsoft.VisualStudio.Utilities</p>\n"
},
{
"answer_id": 66592889,
"author": "Soleil",
"author_id": 1447389,
"author_profile": "https://Stackoverflow.com/users/1447389",
"pm_score": 1,
"selected": false,
"text": "<p>The extension methods for rotating bits of a <code>uint</code> (32 bits):</p>\n<pre><code>public static uint ROR(this uint x, int nbitsShift)\n => (x >> nbitsShift) | (x << (32 - nbitsShift));\n\npublic static uint ROL(this uint x, int nbitsShift)\n => (x << nbitsShift) | (x >> (32 - nbitsShift));\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] | I know that the following is true
```
int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
```
But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with.
Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop. | If you know the size of type, you could do something like:
```
uint i = 17;
uint j = i << 1 | i >> 31;
```
... which would perform a circular shift of a 32 bit value.
As a generalization to circular shift left n bits, on a b bit variable:
```
/*some unsigned numeric type*/ input = 17;
var result = input << n | input >> (b - n);
```
---
@The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this [here](http://www.blackwasp.co.uk/CSharpShiftOperators.aspx). I also changed the example to use a uint. |
35,170 | <p>What does it mean if a task is declared with the automatic keyword in Verilog?</p>
<pre><code>task automatic do_things;
input [31:0] number_of_things;
reg [31:0] tmp_thing;
begin
// ...
end
endtask;
</code></pre>
<p>Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :)</p>
| [
{
"answer_id": 35193,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": true,
"text": "<p>It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task.</p>\n\n<p>You see - some of us do Verilog... (ugh)</p>\n"
},
{
"answer_id": 38600,
"author": "Marty",
"author_id": 4131,
"author_profile": "https://Stackoverflow.com/users/4131",
"pm_score": 2,
"selected": false,
"text": "<p>The \"automatic\" keyword also allows you to write recursive functions (since verilog 2001). I believe they should be synthesisable if they bottom out, but I'm not sure if they have tool support. </p>\n\n<p>I too, do verilog! </p>\n"
},
{
"answer_id": 70497,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>As Will and Marty say, the automatic was intended for recursive functions.</p>\n\n<p>If a normal (i.e. not automatic) function is called with different values and processed by the simulator in the same time slice, the returned value is indeterminate. That can be quite a tricky bug to spot! This is only a simulation issue, when synthesised the logic will be correct.</p>\n\n<p>Making the function automatic fixes this.</p>\n"
},
{
"answer_id": 99929,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 5,
"selected": false,
"text": "<p>\"automatic\" does in fact mean \"re-entrant\". The term itself is stolen from software languages -- for example, C has the \"auto\" keyword for declaring variables as being allocated on the stack when the scope it's in is executed, and deallocated afterwards, so that multiple invocations of the same scope do not see persistent values of that variable. The reason you may not have heard of this keyword in C is that it is the default storage class for all types :-) The alternatives are \"static\", which means \"allocate this variable statically (to a single global location in memory), and refer to this same memory location throughout the execution of the program, regardless of how many times the function is invoked\", and \"volatile\", which means \"this is a register elsewhere on my SoC or something on another device which I have no control over; compiler, please don't optimize reads to me away, even when you think you know my value from previous reads with no intermediate writes in the code\".</p>\n\n<p>\"automatic\" is intended for recursive functions, but also for running the same function in different threads of execution concurrently. For instance, if you \"fork\" off N different blocks (using Verilog's fork->join statement), and have them all call the same function at the same time, the same problems arise as a function calling itself recursively.</p>\n\n<p>In many cases, your code will be just fine without declaring the task or function as \"automatic\", but it's good practice to put it in there unless you specifically need it to be otherwise.</p>\n"
},
{
"answer_id": 57490184,
"author": "TRoa",
"author_id": 9547499,
"author_profile": "https://Stackoverflow.com/users/9547499",
"pm_score": 0,
"selected": false,
"text": "<p>In computing, a computer program or subroutine is called re-entrant if multiple invocations can safely run concurrently (Wikipedia). \nIn simple words, the keyword automatic makes it safe, when multiple instances of a task run at a same time.\n:D</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | What does it mean if a task is declared with the automatic keyword in Verilog?
```
task automatic do_things;
input [31:0] number_of_things;
reg [31:0] tmp_thing;
begin
// ...
end
endtask;
```
Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :) | It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task.
You see - some of us do Verilog... (ugh) |
35,178 | <p>I am working on a C++ code base that was recently moved from X/Motif to Qt. I am trying to write a Perl script that will replace all occurrences of Boolean (from X) with bool. The script just does a simple replacement. </p>
<pre><code>s/\bBoolean\b/bool/g
</code></pre>
<p>There are a few conditions. </p>
<p>1) We have CORBA in our code and \b matches CORBA::Boolean which should <strong>not</strong> be changed.<br>
2) It should not match if it was found as a string (i.e. "Boolean")</p>
<p><strong>Updated:</strong></p>
<p>For #1, I used lookbehind</p>
<pre><code>s/(?<!:)\bBoolean\b/bool/g;
</code></pre>
<p>For #2, I used lookahead.</p>
<pre><code>s/(?<!:)\bBoolean\b(?!")/bool/g</pre>
</code></pre>
<p>This will most likely work for my situation but how about the following improvements?</p>
<p>3) Do not match if in the middle of a string (thanks <a href="https://stackoverflow.com/users/3101/nohat">nohat</a>).<br>
4) Do not match if in a comment. (// or /**/) </p>
| [
{
"answer_id": 35198,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>To fix condition 1 try:</p>\n\n<pre><code>s/[^:]\\bBoolean\\b(?!\")/bool/g\n</code></pre>\n\n<p>The [^:] says to match any character other than \":\". </p>\n"
},
{
"answer_id": 35203,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 1,
"selected": false,
"text": "<pre><code>s/[^:]\\bBoolean\\b[^\"]/bool/g\n</code></pre>\n\n<p>Edit: Rats, beaten again. +1 for beating me, good sir.</p>\n"
},
{
"answer_id": 35220,
"author": "KannoN",
"author_id": 2897,
"author_profile": "https://Stackoverflow.com/users/2897",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>s/[^:]\\bBoolean\\b(?!\")/bool/g</p>\n</blockquote>\n\n<p>This does not match strings where Boolean is at that the beginning of the line becuase [^:] is \"match a character that is not :\".</p>\n"
},
{
"answer_id": 35358,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 2,
"selected": false,
"text": "<p>Watch out with that quote-matching lookahead assertion. That'll only match if <em>Boolean</em> is the last part of a string, but not in the middle of the string. You'll need to match an even number of quote marks preceding the match if you want to be sure you're not in a string (assuming no multi-line strings and no escaped embedded quote marks).</p>\n"
},
{
"answer_id": 43729,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>3) Do not match if in the middle of a string (thanks nohat).</p>\n</blockquote>\n\n<p>You can perhaps write a reg ex to check \".*Boolean.*\". But what if you have quote(\") inside the string? So, you have more work to not exclude (\\\") pattern. </p>\n\n<blockquote>\n <p>4) Do not match if in a comment. (// or /* */)</p>\n</blockquote>\n\n<p>For '//', you can have a regex to exclude //.* But, better could be to first put a regex to compare the whole line for the // comments ((.*)(//.*)) and then apply replacement only on $1 (first matching pattern).</p>\n\n<p>For /* */, it is more complex as this is multiline pattern. One approach can be to first run whole of you code to match multiline comments and then take out only the parts not matching ... something like ... (.*)(/*.**/)(.*). But, the actual regex would be even more complex as you would have not one but more of multi-line comments.</p>\n\n<p>Now, what if you have /* or */ inside // block? (I dont know why would you have it.. but Murphy's law says that you can have it). There is obviously some way out but my idea is to emphasize how bad-looking the regex will become.</p>\n\n<p>My suggestion here would be to use some lexical tool for C++ and replace the token Boolean with bool. Your thoughts?</p>\n"
},
{
"answer_id": 86617,
"author": "piCookie",
"author_id": 8763,
"author_profile": "https://Stackoverflow.com/users/8763",
"pm_score": 0,
"selected": false,
"text": "<p>In order to avoid writing a full C parser in perl, you're trying to strike a balance. Depending on how much needs changing, I would be inclined to do something like a very restrictive s/// and then anything that still matches /Boolean/ gets written to an exception file for human decision making. That way you're not trying to parse the C middle strings, multi-line comment, conditional compiled out text, etc. that could be present.</p>\n"
},
{
"answer_id": 86920,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>…</li>\n <li>…</li>\n <li>Do not match if in the middle of a string (thanks nohat).</li>\n <li>Do not match if in a comment. (// or /**/)</li>\n </ol>\n</blockquote>\n\n<p>No can do with a <em>simple</em> regex. For that, you need to actually look at <em>every single</em> character left-to-right and decide what kind of thing it is, at least well enough to tell apart comments from multi-line comments from strings from other stuff, and <em>then</em> you need to see if the “other stuff” part contains things you want to change.</p>\n\n<p>Now, I don’t know the <strong>exact</strong> syntactical rules for comments and strings in C++ so the following is going to be imprecise and completely undebugged, but it’ll give you an idea of the complexity you’re up against.</p>\n\n<pre><code>my $line_comment = qr! (?> // .* \\n? ) !x;\nmy $multiline_comment = qr! (?> /\\* [^*]* (?: \\* (?: [^/*] [^*]* )? )* )* \\*/ ) !x;\nmy $string = qr! (?> \" [^\"\\\\]* (?: \\\\ . [^\"\\\\]* )* \" ) !x;\nmy $boolean_type = qr! (?<!:) \\b Boolean \\b !x;\n\n$code =~ s{ \\G (\n $line_comment\n | $multiline_comment\n | $string\n | ( $boolean_type )\n | .\n) }{\n defined $2 ? 'bool' : $1\n}gex;\n</code></pre>\n\n<p>Please don’t ask me to explain this in all its intricacies, it would take me a day and another. Just buy and read Jeff Friedl’s <a href=\"http://regex.info/\" rel=\"nofollow noreferrer\"><i>Mastering Regular Expressions</i></a> if you want to understand exactly what is going on here.</p>\n"
},
{
"answer_id": 88938,
"author": "Victor",
"author_id": 14514,
"author_profile": "https://Stackoverflow.com/users/14514",
"pm_score": 0,
"selected": false,
"text": "<p>The \"'Boolean' in the middle of a string\" part sounds a bit unlikely, I'd check first if there is any occurrence of it in the code with something like</p>\n\n<pre><code>m/\"[^\"]*Boolean[^\"]*\"/\n</code></pre>\n\n<p>And if there is none or a few, just ignore that case.</p>\n"
},
{
"answer_id": 95149,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#define Boolean bool\n</code></pre>\n\n<p>Let the preprocesser take care of this. Every time you see a Boolean you can either manually fix it or hope a regex doesn't make a mistake. Depending on how many macros you use you can you could dump the out of cpp.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897/"
] | I am working on a C++ code base that was recently moved from X/Motif to Qt. I am trying to write a Perl script that will replace all occurrences of Boolean (from X) with bool. The script just does a simple replacement.
```
s/\bBoolean\b/bool/g
```
There are a few conditions.
1) We have CORBA in our code and \b matches CORBA::Boolean which should **not** be changed.
2) It should not match if it was found as a string (i.e. "Boolean")
**Updated:**
For #1, I used lookbehind
```
s/(?<!:)\bBoolean\b/bool/g;
```
For #2, I used lookahead.
```
s/(?<!:)\bBoolean\b(?!")/bool/g</pre>
```
This will most likely work for my situation but how about the following improvements?
3) Do not match if in the middle of a string (thanks [nohat](https://stackoverflow.com/users/3101/nohat)).
4) Do not match if in a comment. (// or /\*\*/) | >
> s/[^:]\bBoolean\b(?!")/bool/g
>
>
>
This does not match strings where Boolean is at that the beginning of the line becuase [^:] is "match a character that is not :". |
35,185 | <p>What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.</p>
<p>So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm.</p>
| [
{
"answer_id": 35192,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 0,
"selected": false,
"text": "<p>You need to specify what you mean by \"best\" - to some, speed is all that matters and would qualify an answer as \"best\" - for others, they might forgive a few hundred milliseconds if the solution was more readable.</p>\n\n<p>\"Best\" is subjective unless you are more specific.</p>\n\n<hr>\n\n<p>That said:</p>\n\n<p>Iterate through the numbers, for each number search the list for that number and when you reach the number that returns only a 1 for the number of search results, you are done.</p>\n"
},
{
"answer_id": 35195,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 4,
"selected": false,
"text": "<p><strong>O(N) time, O(N) memory</strong></p>\n\n<p>HT= Hash Table </p>\n\n<p>HT.clear()\ngo over the list in order \nfor each item you see</p>\n\n<pre><code>if(HT.Contains(item)) -> HT.Remove(item)\nelse\nht.add(item)\n</code></pre>\n\n<p>at the end, the item in the HT is the item you are looking for.</p>\n\n<p>Note (credit @Jared Updike): This system will find all Odd instances of items.</p>\n\n<hr>\n\n<p><strong>comment</strong>: I don't see how can people vote up solutions that give you NLogN performance. in which universe is that \"better\" ? \nI am even more shocked you marked the accepted answer s NLogN solution...</p>\n\n<p>I do agree however that if memory is required to be constant, then NLogN would be (so far) the best solution.</p>\n"
},
{
"answer_id": 35200,
"author": "Farinha",
"author_id": 2841,
"author_profile": "https://Stackoverflow.com/users/2841",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that using a sorting algorithm and then going through the sorted list to find the number is a good way to do it.</p>\n\n<p>And now the problem is finding \"the best\" sorting algorithm. There are a lot of sorting algorithms, each of them with its strong and weak points, so this is quite a complicated question. The <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"nofollow noreferrer\">Wikipedia entry</a> seems like a nice source of info on that.</p>\n"
},
{
"answer_id": 35204,
"author": "levand",
"author_id": 3044,
"author_profile": "https://Stackoverflow.com/users/3044",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like the best you could do is to iterate through the list, for every item add it to a list of \"seen\" items or else remove it from the \"seen\" if it's already there, and at the end your list of \"seen\" items will include the singular element. This is O(n) in regards to time and n in regards to space (in the worst case, it will be much better if the list is sorted). </p>\n\n<p>The fact that they're integers doesn't really factor in, since there's nothing special you can do with adding them up... is there?</p>\n\n<p><strong>Question</strong></p>\n\n<p>I don't understand why the selected answer is \"best\" by any standard. O(N*lgN) > O(N), and it changes the list (or else creates a copy of it, which is still more expensive in space and time). Am I missing something?</p>\n"
},
{
"answer_id": 35235,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": -1,
"selected": false,
"text": "<p>You could simply put the elements in the set into a hash until you find a collision. In ruby, this is a one-liner.</p>\n\n<pre><code>def find_dupe(array)\n h={}\n array.detect { |e| h[e]||(h[e]=true; false) }\nend\n</code></pre>\n\n<p>So, <code>find_dupe([1,2,3,4,5,1])</code> would return 1. </p>\n\n<p>This is actually a common \"trick\" interview question though. It is normally about a list of consecutive integers with one duplicate. In this case the interviewer is often looking for you to use the Gaussian sum of <em>n</em>-integers trick e.g. <code>n*(n+1)/2</code> subtracted from the actual sum. The textbook answer is something like this. </p>\n\n<pre><code>def find_dupe_for_consecutive_integers(array)\n n=array.size-1 # subtract one from array.size because of the dupe\n array.sum - n*(n+1)/2\nend\n</code></pre>\n"
},
{
"answer_id": 35244,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>Depends on how large/small/diverse the numbers are though. A radix sort might be applicable which would reduce the sorting time of the O(N log N) solution by a large degree.</p>\n"
},
{
"answer_id": 35271,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 8,
"selected": true,
"text": "<p>The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation.</p>\n\n<p>In C:</p>\n\n<pre><code>int arr[] = {3, 2, 5, 2, 1, 5, 3};\n\nint num = 0, i;\n\nfor (i=0; i < 7; i++)\n num ^= arr[i];\n\nprintf(\"%i\\n\", num);\n</code></pre>\n\n<p>This prints \"1\", which is the only one that occurs once.</p>\n\n<p>This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate.</p>\n"
},
{
"answer_id": 35348,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 4,
"selected": false,
"text": "<p>By the way, you can expand on this idea to very quickly find <em>two</em> unique numbers among a list of duplicates.</p>\n\n<p>Let's call the unique numbers a and b. First take the XOR of everything, as Kyle suggested. What we get is a^b. We know a^b != 0, since a != b. Choose any 1 bit of a^b, and use that as a mask -- in more detail: choose x as a power of 2 so that x & (a^b) is nonzero.</p>\n\n<p>Now split the list into two sublists -- one sublist contains all numbers y with y&x == 0, and the rest go in the other sublist. By the way we chose x, we know that a and b are in different buckets. We also know that each pair of duplicates is still in the same bucket. So we can now apply ye olde \"XOR-em-all\" trick to each bucket independently, and discover what a and b are completely.</p>\n\n<p>Bam.</p>\n"
},
{
"answer_id": 37523,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The sorting method and the XOR method have the same time complexity. The XOR method is only O(n) if you assume that bitwise XOR of two strings is a constant time operation. This is equivalent to saying that the size of the integers in the array is bounded by a constant. In that case you can use Radix sort to sort the array in O(n).</p>\n\n<p>If the numbers are not bounded, then bitwise XOR takes time O(k) where k is the length of the bit string, and the XOR method takes O(nk). Now again Radix sort will sort the array in time O(nk).</p>\n"
},
{
"answer_id": 41632,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 2,
"selected": false,
"text": "<p>Kyle's solution would obviously not catch situations were the data set does not follow the rules. If all numbers were in pairs the algorithm would give a result of zero, the exact same value as if zero would be the only value with single occurance.</p>\n\n<p>If there were multiple single occurance values or triples, the result would be errouness as well.</p>\n\n<p>Testing the data set might well end up with a more costly algorithm, either in memory or time.</p>\n\n<p>Csmba's solution does show some errouness data (no or more then one single occurence value), but not other (quadrouples). Regarding his solution, depending on the implementation of HT, either memory and/or time is more then O(n).</p>\n\n<p>If we cannot be sure about the correctness of the input set, sorting and counting or using a hashtable counting occurances with the integer itself being the hash key would both be feasible.</p>\n"
},
{
"answer_id": 25834770,
"author": "SuperNova",
"author_id": 3464971,
"author_profile": "https://Stackoverflow.com/users/3464971",
"pm_score": 1,
"selected": false,
"text": "<p>Implementation in Ruby:</p>\n\n<pre><code>a = [1,2,3,4,123,1,2,.........]\nt = a.length-1\nfor i in 0..t\n s = a.index(a[i])+1\n b = a[s..t]\n w = b.include?a[i]\n if w == false\n puts a[i]\n end\nend\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.
So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm. | The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation.
In C:
```
int arr[] = {3, 2, 5, 2, 1, 5, 3};
int num = 0, i;
for (i=0; i < 7; i++)
num ^= arr[i];
printf("%i\n", num);
```
This prints "1", which is the only one that occurs once.
This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate. |
35,208 | <p>I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following?</p>
| [
{
"answer_id": 35213,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 0,
"selected": false,
"text": "<p>You should be setting ValidationGroup property to a different value for each group of elements. Your validator's ValidationGroup must only be same with the control that submit its form.</p>\n"
},
{
"answer_id": 35226,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 4,
"selected": true,
"text": "<p>Are you using ValidationGroups? Try assigning each control with a validation group as well as the validator that you want to use. Something like:</p>\n\n<pre><code><asp:TextBox ID=\"txt1\" ValidationGroup=\"Group1\" ruant=\"server\" />\n<asp:RequiredFieldValidator ID=\"rfv1\" ... ValidationGroup=\"Group1\" />\n</code></pre>\n\n<p>Note, if a button doesn't specify a validation group it will validate all controls that aren't assigned to a validation group.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] | I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following? | Are you using ValidationGroups? Try assigning each control with a validation group as well as the validator that you want to use. Something like:
```
<asp:TextBox ID="txt1" ValidationGroup="Group1" ruant="server" />
<asp:RequiredFieldValidator ID="rfv1" ... ValidationGroup="Group1" />
```
Note, if a button doesn't specify a validation group it will validate all controls that aren't assigned to a validation group. |
35,211 | <p>The compiler usually chokes when an event doesn't appear beside a <code>+=</code> or a <code>-=</code>, so I'm not sure if this is possible.</p>
<p>I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:</p>
<pre><code>using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
// act here
} // throws on Dispose() if MyEventToWatch hasn't fired
</code></pre>
<p>My questions are twofold:</p>
<ol>
<li>Will the compiler choke? And if so, any suggestions on how to prevent this?</li>
<li>How can I parse the Expression object from the constructor in order to attach to the <code>MyEventToWatch</code> event of <code>target</code>?</li>
</ol>
| [
{
"answer_id": 36255,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>A .NET event isn't actually an object, it's an endpoint represented by two functions -- one for adding and one for removing a handler. That's why the compiler won't let you do anything other than += (which represents the add) or -= (which represents the remove).</p>\n\n<p>The only way to refer to an event for metaprogramming purposes is as a System.Reflection.EventInfo, and reflection is probably the best way (if not the only way) to get ahold of one.</p>\n\n<p>EDIT: Emperor XLII has written some beautiful code which should work for your own events, provided you've declared them from C# simply as</p>\n\n<pre><code>public event DelegateType EventName;\n</code></pre>\n\n<p>That's because C# creates two things for you from that declaration:</p>\n\n<ol>\n<li>A private delegate field to serve as the backing\nstorage for the event</li>\n<li>The actual event along with\nimplementation code that makes use\nof the delegate.</li>\n</ol>\n\n<p>Conveniently, both of these have the same name. That's why the sample code will work for your own events.</p>\n\n<p>However, you can't rely on this to be the case when using events implemented by other libraries. In particular, the events in Windows Forms and in WPF don't have their own backing storage, so the sample code will not work for them.</p>\n"
},
{
"answer_id": 37315,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Edit:</strong> As <a href=\"https://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255\">Curt</a> has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of \"<code>x => x.MyEvent</code>\" returning the event, it was returning the backing field, which is only accessble by the class.</p>\n\n<p>Since expressions cannot contain assignment statements, a modified expression like \"<code>( x, h ) => x.MyEvent += h</code>\" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the <code>EventInfo</code> for the event (which, unfortunatley, will not be strongly typed).</p>\n\n<p>Otherwise, the only updates that need to be made are to store the reflected <code>EventInfo</code>, and use the <code>AddEventHandler</code>/<code>RemoveEventHandler</code> methods to register the listener (instead of the manual <code>Delegate</code> <code>Combine</code>/<code>Remove</code> calls and field sets). The rest of the implementation should not need to be changed. Good luck :)</p>\n\n<hr>\n\n<p><strong>Note:</strong> This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)</p>\n\n<pre><code>public sealed class EventWatcher : IDisposable {\n private readonly object target_;\n private readonly string eventName_;\n private readonly FieldInfo eventField_;\n private readonly Delegate listener_;\n private bool eventWasRaised_;\n\n public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {\n return new EventWatcher( target, accessor );\n }\n\n private EventWatcher( object target, LambdaExpression accessor ) {\n this.target_ = target;\n\n // Retrieve event definition from expression.\n var eventAccessor = accessor.Body as MemberExpression;\n this.eventField_ = eventAccessor.Member as FieldInfo;\n this.eventName_ = this.eventField_.Name;\n\n // Create our event listener and add it to the declaring object's event field.\n this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );\n var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;\n var newEventList = Delegate.Combine( currentEventList, this.listener_ );\n this.eventField_.SetValue( this.target_, newEventList );\n }\n\n public void SetEventWasRaised( ) {\n this.eventWasRaised_ = true;\n }\n\n private Delegate CreateEventListenerDelegate( Type eventType ) {\n // Create the event listener's body, setting the 'eventWasRaised_' field.\n var setMethod = typeof( EventWatcher ).GetMethod( \"SetEventWasRaised\" );\n var body = Expression.Call( Expression.Constant( this ), setMethod );\n\n // Get the event delegate's parameters from its 'Invoke' method.\n var invokeMethod = eventType.GetMethod( \"Invoke\" );\n var parameters = invokeMethod.GetParameters( )\n .Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );\n\n // Create the listener.\n var listener = Expression.Lambda( eventType, body, parameters );\n return listener.Compile( );\n }\n\n void IDisposable.Dispose( ) {\n // Remove the event listener.\n var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;\n var newEventList = Delegate.Remove( currentEventList, this.listener_ );\n this.eventField_.SetValue( this.target_, newEventList );\n\n // Ensure event was raised.\n if( !this.eventWasRaised_ )\n throw new InvalidOperationException( \"Event was not raised: \" + this.eventName_ );\n }\n}\n</code></pre>\n\n<p>Usage is slightly different from that suggested, in order to take advantage of type inference:</p>\n\n<pre><code>try {\n using( EventWatcher.Create( o, x => x.MyEvent ) ) {\n //o.RaiseEvent( ); // Uncomment for test to succeed.\n }\n Console.WriteLine( \"Event raised successfully\" );\n}\ncatch( InvalidOperationException ex ) {\n Console.WriteLine( ex.Message );\n}\n</code></pre>\n"
},
{
"answer_id": 5521046,
"author": "bryanbcook",
"author_id": 30809,
"author_profile": "https://Stackoverflow.com/users/30809",
"pm_score": 1,
"selected": false,
"text": "<p>While Emperor XLII already gave the answer for this, I thought it was worth while to share my rewrite of this. Sadly, no ability to get the Event via Expression Tree, I'm using the name of the Event.</p>\n\n<pre><code>public sealed class EventWatcher : IDisposable {\n private readonly object _target;\n private readonly EventInfo _eventInfo;\n private readonly Delegate _listener;\n private bool _eventWasRaised;\n\n public static EventWatcher Create<T>(T target, string eventName) {\n EventInfo eventInfo = typeof(T).GetEvent(eventName);\n if (eventInfo == null)\n throw new ArgumentException(\"Event was not found.\", eventName);\n return new EventWatcher(target, eventInfo);\n }\n\n private EventWatcher(object target, EventInfo eventInfo) {\n _target = target;\n _eventInfo = event;\n _listener = CreateEventDelegateForType(_eventInfo.EventHandlerType);\n _eventInfo.AddEventHandler(_target, _listener);\n }\n\n // SetEventWasRaised()\n // CreateEventDelegateForType\n\n void IDisposable.Dispose() {\n _eventInfo.RemoveEventHandler(_target, _listener);\n if (!_eventWasRaised)\n throw new InvalidOperationException(\"event was not raised.\");\n }\n}\n</code></pre>\n\n<p>And usage is:</p>\n\n<pre><code>using(EventWatcher.Create(o, \"MyEvent\")) {\n o.RaiseEvent();\n}\n</code></pre>\n"
},
{
"answer_id": 11084822,
"author": "sacha barber",
"author_id": 1089655,
"author_profile": "https://Stackoverflow.com/users/1089655",
"pm_score": 2,
"selected": false,
"text": "<p>I too wanted to do this, and I have come up with a pretty cool way that does something like Emperor XLII idea. It doesn't use Expression trees though, as mentioned this can't be done as Expression trees do not allow the use of <code>+=</code> or <code>-=</code>. </p>\n\n<p>We can however use a neat trick where we use .NET Remoting Proxy (or any other Proxy such as LinFu or Castle DP) to intercept a call to Add/Remove handler on a very short lived proxy object. The role of this proxy object is to simply have some method called on it, and to allow its method calls to be intercepted, at which point we can find out the name of the event.</p>\n\n<p>This sounds weird but here is the code (which by the way ONLY works if you have a <code>MarshalByRefObject</code> or an interface for the proxied object)</p>\n\n<p>Assume we have the following interface and class</p>\n\n<pre><code>public interface ISomeClassWithEvent {\n event EventHandler<EventArgs> Changed;\n}\n\n\npublic class SomeClassWithEvent : ISomeClassWithEvent {\n public event EventHandler<EventArgs> Changed;\n\n protected virtual void OnChanged(EventArgs e) {\n if (Changed != null)\n Changed(this, e);\n }\n}\n</code></pre>\n\n<p>Then we can have a very simply class that expects an <code>Action<T></code> delegate that will get passed some instance of <code>T</code>. </p>\n\n<p>Here is the code</p>\n\n<pre><code>public class EventWatcher<T> {\n public void WatchEvent(Action<T> eventToWatch) {\n CustomProxy<T> proxy = new CustomProxy<T>(InvocationType.Event);\n T tester = (T) proxy.GetTransparentProxy();\n eventToWatch(tester);\n\n Console.WriteLine(string.Format(\"Event to watch = {0}\", proxy.Invocations.First()));\n }\n}\n</code></pre>\n\n<p>The trick is to pass the proxied object to the <code>Action<T></code> delegate provided. </p>\n\n<p>Where we have the following <code>CustomProxy<T></code> code, who intercepts the call to <code>+=</code> and <code>-=</code> on the proxied object</p>\n\n<pre><code>public enum InvocationType { Event }\n\npublic class CustomProxy<T> : RealProxy {\n private List<string> invocations = new List<string>();\n private InvocationType invocationType;\n\n public CustomProxy(InvocationType invocationType) : base(typeof(T)) {\n this.invocations = new List<string>();\n this.invocationType = invocationType;\n }\n\n public List<string> Invocations {\n get { \n return invocations; \n }\n }\n\n [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]\n [DebuggerStepThrough]\n public override IMessage Invoke(IMessage msg) {\n String methodName = (String) msg.Properties[\"__MethodName\"];\n Type[] parameterTypes = (Type[]) msg.Properties[\"__MethodSignature\"];\n MethodBase method = typeof(T).GetMethod(methodName, parameterTypes);\n\n switch (invocationType) {\n case InvocationType.Event:\n invocations.Add(ReplaceAddRemovePrefixes(method.Name));\n break;\n // You could deal with other cases here if needed\n }\n\n IMethodCallMessage message = msg as IMethodCallMessage;\n Object response = null;\n ReturnMessage responseMessage = new ReturnMessage(response, null, 0, null, message);\n return responseMessage;\n }\n\n private string ReplaceAddRemovePrefixes(string method) {\n if (method.Contains(\"add_\"))\n return method.Replace(\"add_\",\"\");\n if (method.Contains(\"remove_\"))\n return method.Replace(\"remove_\",\"\");\n return method;\n }\n}\n</code></pre>\n\n<p>And then we all that's left is to use this as follows</p>\n\n<pre><code>class Program {\n static void Main(string[] args) {\n EventWatcher<ISomeClassWithEvent> eventWatcher = new EventWatcher<ISomeClassWithEvent>();\n eventWatcher.WatchEvent(x => x.Changed += null);\n eventWatcher.WatchEvent(x => x.Changed -= null);\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Doing this I will see this output:</p>\n\n<pre><code>Event to watch = Changed\nEvent to watch = Changed\n</code></pre>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The compiler usually chokes when an event doesn't appear beside a `+=` or a `-=`, so I'm not sure if this is possible.
I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:
```
using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
// act here
} // throws on Dispose() if MyEventToWatch hasn't fired
```
My questions are twofold:
1. Will the compiler choke? And if so, any suggestions on how to prevent this?
2. How can I parse the Expression object from the constructor in order to attach to the `MyEventToWatch` event of `target`? | **Edit:** As [Curt](https://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255) has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "`x => x.MyEvent`" returning the event, it was returning the backing field, which is only accessble by the class.
Since expressions cannot contain assignment statements, a modified expression like "`( x, h ) => x.MyEvent += h`" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the `EventInfo` for the event (which, unfortunatley, will not be strongly typed).
Otherwise, the only updates that need to be made are to store the reflected `EventInfo`, and use the `AddEventHandler`/`RemoveEventHandler` methods to register the listener (instead of the manual `Delegate` `Combine`/`Remove` calls and field sets). The rest of the implementation should not need to be changed. Good luck :)
---
**Note:** This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)
```
public sealed class EventWatcher : IDisposable {
private readonly object target_;
private readonly string eventName_;
private readonly FieldInfo eventField_;
private readonly Delegate listener_;
private bool eventWasRaised_;
public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {
return new EventWatcher( target, accessor );
}
private EventWatcher( object target, LambdaExpression accessor ) {
this.target_ = target;
// Retrieve event definition from expression.
var eventAccessor = accessor.Body as MemberExpression;
this.eventField_ = eventAccessor.Member as FieldInfo;
this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field.
this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Combine( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
}
public void SetEventWasRaised( ) {
this.eventWasRaised_ = true;
}
private Delegate CreateEventListenerDelegate( Type eventType ) {
// Create the event listener's body, setting the 'eventWasRaised_' field.
var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );
var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method.
var invokeMethod = eventType.GetMethod( "Invoke" );
var parameters = invokeMethod.GetParameters( )
.Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener.
var listener = Expression.Lambda( eventType, body, parameters );
return listener.Compile( );
}
void IDisposable.Dispose( ) {
// Remove the event listener.
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Remove( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised.
if( !this.eventWasRaised_ )
throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );
}
}
```
Usage is slightly different from that suggested, in order to take advantage of type inference:
```
try {
using( EventWatcher.Create( o, x => x.MyEvent ) ) {
//o.RaiseEvent( ); // Uncomment for test to succeed.
}
Console.WriteLine( "Event raised successfully" );
}
catch( InvalidOperationException ex ) {
Console.WriteLine( ex.Message );
}
``` |
35,240 | <p>I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.</p>
<p>I've tried poking around in the iframe objects looking for some sort of <code>status_code</code> attribute, but haven't been able to find anything like that.</p>
<hr>
<p>The <code>$.ajax()</code> function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden <code>iframe</code> method.</p>
| [
{
"answer_id": 1847965,
"author": "Coyod",
"author_id": 223888,
"author_profile": "https://Stackoverflow.com/users/223888",
"pm_score": 4,
"selected": false,
"text": "<p>You can't get page headers by JS, but you can distinguish error from success:\nTry something like this:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n var uploadStarted = false;\n function OnUploadStart(){ \n uploadStarted = true;\n }\n\n function OnUploadComplete(state,message){ \n\n if(state == 1)\n alert(\"Success: \"+message); \n else\n if(state == 0 && uploadStarted)\n alert(\"Error:\"+( message ? message : \"unknow\" ));\n } \n\n</script>\n\n\n<iframe id=\"uploader\" name=\"uploader\" onload=\"OnUploadComplete(0)\" style=\"width:0px;height:0px;border:none;\"></iframe>\n\n<form id=\"sender\" action=\"/upload.php\" method=\"post\" target=\"uploader\" enctype=\"multipart/form-data\" onsubmit=\"OnUploadStart()\">\n<input type=\"file\" name=\"files[upload]\"/>\n<input type=\"submit\" value=\"Upload\"/>\n</form>\n</code></pre>\n\n<p>On server side:</p>\n\n<pre><code>/*\n file: upload.php\n*/\n<?php \n\n // do some stuff with file \n\n print '<script type=\"text/javascript\">';\n if(success)\n print 'window.parent.OnUploadComplete(1,\"File uploaded!\");';\n else\n print 'window.parent.OnUploadComplete(0, \"File too large!\");';\n print '</script>';\n?>\n</code></pre>\n"
},
{
"answer_id": 29068651,
"author": "choi gray",
"author_id": 4674666,
"author_profile": "https://Stackoverflow.com/users/4674666",
"pm_score": -1,
"selected": false,
"text": "<p>You can't retrieving HTTP status code from loaded \"iframe\" directly.\nBut when an http error occured, the server will returned nothing to the \"iframe\".\nSo the iframe has not content.\nyou can check the iframe body, when the body of iframe is blank, use ajax with the same url to get the response from server. Then you can retrieve the http status code from response.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560/"
] | I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.
I've tried poking around in the iframe objects looking for some sort of `status_code` attribute, but haven't been able to find anything like that.
---
The `$.ajax()` function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden `iframe` method. | You can't get page headers by JS, but you can distinguish error from success:
Try something like this:
```
<script type="text/javascript">
var uploadStarted = false;
function OnUploadStart(){
uploadStarted = true;
}
function OnUploadComplete(state,message){
if(state == 1)
alert("Success: "+message);
else
if(state == 0 && uploadStarted)
alert("Error:"+( message ? message : "unknow" ));
}
</script>
<iframe id="uploader" name="uploader" onload="OnUploadComplete(0)" style="width:0px;height:0px;border:none;"></iframe>
<form id="sender" action="/upload.php" method="post" target="uploader" enctype="multipart/form-data" onsubmit="OnUploadStart()">
<input type="file" name="files[upload]"/>
<input type="submit" value="Upload"/>
</form>
```
On server side:
```
/*
file: upload.php
*/
<?php
// do some stuff with file
print '<script type="text/javascript">';
if(success)
print 'window.parent.OnUploadComplete(1,"File uploaded!");';
else
print 'window.parent.OnUploadComplete(0, "File too large!");';
print '</script>';
?>
``` |
35,286 | <p>I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:</p>
<pre><code>set FILENAME=%~f1
sed 's/Some Pattern/%FILENAME%/' inputfile
</code></pre>
<p>(Note: <code>%~f1</code> - expands <code>%1</code> to a Fully qualified path name - <code>C:\utils\MyFile.txt</code>)</p>
<p>I found that the backslashes in <code>%FILENAME%</code> are just escaping the next letter.</p>
<p>How can I double them up so that they are escaped?</p>
<p>(I have cygwin installed so feel free to use any other *nix commands)</p>
<h1>Solution</h1>
<p>Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have</p>
<pre><code>set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
</code></pre>
| [
{
"answer_id": 35386,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 3,
"selected": true,
"text": "<p>This will work. It's messy because in BAT files you can't use set var=`cmd` like you can in unix.\nThe fact that echo doesn't understand quotes is also messy, and could lead to trouble if <code>Some Pattern</code> contains shell meta characters.</p>\n\n<pre><code>set FILENAME=%~f1\necho s/Some Pattern/%FILENAME%/ | sed -e \"s/\\\\/\\\\\\\\/g\" >sedcmd.tmp\nsed -f sedcmd.tmp inputfile\ndel /q sedcmd.tmp\n</code></pre>\n\n<p>[Edited]: I am suprised that it didn't work for you. I just tested it, and it worked on my machine. I am using sed from <a href=\"http://sourceforge.net/projects/unxutils\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/unxutils</a> and using cmd.exe to run those commands in a bat file.</p>\n"
},
{
"answer_id": 35389,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 2,
"selected": false,
"text": "<p>You could try as alternative (from the command prompt) ...</p>\n\n<pre><code>> cygpath -m c:\\some\\path\nc:/some/path\n</code></pre>\n\n<p>As you can guess, it converts backslashes to slashes.</p>\n"
},
{
"answer_id": 35419,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 0,
"selected": false,
"text": "<p>@Alexandru & Jeremy, Thanks for your help. You both get upvotes</p>\n\n<p>@Jeremy</p>\n\n<p>Using your method I got the following error:</p>\n\n<blockquote>\n <p>sed: -e expression #1, char 8:\n unterminated `s' command</p>\n</blockquote>\n\n<p>If you can edit your answer to make it work I'd accept it. (pasting my solution doesn't count)</p>\n\n<p><strong>Update:</strong> Ok, I tried it with UnixUtils and it worked. (For reference, the UnixUtils I downloaded was dated March 1, 2007, and uses GNU sed version 3.02, my Cygwin install has GNU sed version 4.1.5)</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] | I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:
```
set FILENAME=%~f1
sed 's/Some Pattern/%FILENAME%/' inputfile
```
(Note: `%~f1` - expands `%1` to a Fully qualified path name - `C:\utils\MyFile.txt`)
I found that the backslashes in `%FILENAME%` are just escaping the next letter.
How can I double them up so that they are escaped?
(I have cygwin installed so feel free to use any other \*nix commands)
Solution
========
Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have
```
set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
``` | This will work. It's messy because in BAT files you can't use set var=`cmd` like you can in unix.
The fact that echo doesn't understand quotes is also messy, and could lead to trouble if `Some Pattern` contains shell meta characters.
```
set FILENAME=%~f1
echo s/Some Pattern/%FILENAME%/ | sed -e "s/\\/\\\\/g" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
```
[Edited]: I am suprised that it didn't work for you. I just tested it, and it worked on my machine. I am using sed from <http://sourceforge.net/projects/unxutils> and using cmd.exe to run those commands in a bat file. |
35,301 | <p>I have always used <code>||</code> (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: <code>|</code>. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?</p>
| [
{
"answer_id": 35303,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 5,
"selected": false,
"text": "<p>One is a \"bitwise or\".</p>\n\n<blockquote>\n <p>10011b | 01000b => 11011b</p>\n</blockquote>\n\n<p>The other is a logic or.</p>\n\n<blockquote>\n <p>true or false => true</p>\n</blockquote>\n"
},
{
"answer_id": 35306,
"author": "homeskillet",
"author_id": 3400,
"author_profile": "https://Stackoverflow.com/users/3400",
"pm_score": -1,
"selected": false,
"text": "<p>The | operator performs a bitwise OR of its two operands (meaning both sides must evaluate to false for it to return false) while the || operator will only evaluate the second operator if it needs to.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx</a></p>\n"
},
{
"answer_id": 35308,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": -1,
"selected": false,
"text": "<p>The singe pipe \"|\" is the \"bitwise\" or and should only be used when you know what you're doing. The double pipe \"||\" is a logical or, and can be used in logical statements, like \"x == 0 || x == 1\".</p>\n\n<p>Here's an example of what the bitwise or does: if a=0101 and b=0011, then a|b=0111. If you're dealing with a logic system that treats any non-zero as true, then the bitwise or will act in the same way as the logical or, but it's counterpart (bitwise and, \"&\") will NOT. Also the bitwise or does not perform short circuit evaluation.</p>\n"
},
{
"answer_id": 35311,
"author": "Dane",
"author_id": 2929,
"author_profile": "https://Stackoverflow.com/users/2929",
"pm_score": -1,
"selected": false,
"text": "<p>A single pipe (|) is the <a href=\"http://en.wikipedia.org/wiki/Bitwise_operation\" rel=\"nofollow noreferrer\">bitwise OR operator</a>.</p>\n\n<p>Two pipes (||) is the logical OR operator.</p>\n\n<p>They are not interchangeable.</p>\n"
},
{
"answer_id": 35313,
"author": "Evan Shaw",
"author_id": 510,
"author_profile": "https://Stackoverflow.com/users/510",
"pm_score": 6,
"selected": false,
"text": "<p>|| is the logical OR operator. It sounds like you basically know what that is. It's used in conditional statements such as if, while, etc.</p>\n\n<pre><code>condition1 || condition2\n</code></pre>\n\n<p>Evaluates to true if either condition1 OR condition2 is true.</p>\n\n<p>| is the bitwise OR operator. It's used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:</p>\n\n<pre><code>A = 01010101\nB = 10101010\nA | B = 11111111\n\nA = 00000001\nB = 00010000\nA | B = 00010001\n\nA = 10001011\nB = 00101100\n\nA | B = 10101111\n</code></pre>\n\n<p>Hopefully that makes sense.</p>\n\n<p>So to answer the last two questions, I wouldn't say there are any caveats besides \"know the difference between the two operators.\" They're not interchangeable because they do two completely different things.</p>\n"
},
{
"answer_id": 35314,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 10,
"selected": true,
"text": "<p>Just like the <code>&</code> and <code>&&</code> operator, the double Operator is a \"short-circuit\" operator.</p>\n\n<p>For example:</p>\n\n<pre><code>if(condition1 || condition2 || condition3)\n</code></pre>\n\n<p>If condition1 is true, condition 2 and 3 will NOT be checked.</p>\n\n<pre><code>if(condition1 | condition2 | condition3)\n</code></pre>\n\n<p>This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.</p>\n\n<p>There is one big caveat, NullReferences or similar problems. For example:</p>\n\n<pre><code>if(class != null && class.someVar < 20)\n</code></pre>\n\n<p>If class is null, the if-statement will stop after <code>class != null</code> is false. If you only use &, it will try to check <code>class.someVar</code> and you get a nice <code>NullReferenceException</code>. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.</p>\n\n<p>No one ever uses the single <code>&</code> or <code>|</code> operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The <code>&</code> operator does \"run these 3 functions, and if one of them returns false, execute the else block\", while the <code>|</code> does \"only run the else block if none return false\" - can be useful, but as said, often it's a design smell.</p>\n\n<p>There is a Second use of the <code>|</code> and <code>&</code> operator though: <a href=\"http://www.c-sharpcorner.com/UploadFile/chandrahundigam/BitWiserOpsInCS11082005050940AM/BitWiserOpsInCS.aspx\" rel=\"noreferrer\">Bitwise Operations</a>.</p>\n"
},
{
"answer_id": 35331,
"author": "Trevor Abell",
"author_id": 2916,
"author_profile": "https://Stackoverflow.com/users/2916",
"pm_score": 4,
"selected": false,
"text": "<p>Good question. These two operators work the same in PHP and C#.</p>\n\n<p><code>|</code> is a bitwise OR. It will compare two values by their bits. E.g. 1101 | 0010 = 1111. This is extremely useful when using bit options. E.g. Read = 01 (0X01) Write = 10 (0X02) Read-Write = 11 (0X03). One useful example would be opening files. A simple example would be: </p>\n\n<pre><code>File.Open(FileAccess.Read | FileAccess.Write); //Gives read/write access to the file\n</code></pre>\n\n<p><code>||</code> is a logical OR. This is the way most people think of OR and compares two values based on their truth. E.g. I am going to the store or I will go to the mall. This is the one used most often in code. For example:</p>\n\n<pre><code>if(Name == \"Admin\" || Name == \"Developer\") { //allow access } //checks if name equals Admin OR Name equals Developer\n</code></pre>\n\n<p>PHP Resource: <a href=\"http://us3.php.net/language.operators.bitwise\" rel=\"noreferrer\">http://us3.php.net/language.operators.bitwise</a></p>\n\n<p>C# Resources: <a href=\"http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx</a></p>\n"
},
{
"answer_id": 35337,
"author": "codeLes",
"author_id": 3030,
"author_profile": "https://Stackoverflow.com/users/3030",
"pm_score": -1,
"selected": false,
"text": "<p>The single pipe, |, is one of the <a href=\"http://en.wikipedia.org/wiki/Bitwise_operation#OR\" rel=\"nofollow noreferrer\">bitwise</a> operators.</p>\n\n<p>From Wikipedia: </p>\n\n<blockquote>\n <p>In the C programming language family, the bitwise OR operator is \"|\" (pipe). Again, this operator must not be confused with its Boolean \"logical or\" counterpart, which treats its operands as Boolean values, and is written \"||\" (two pipes).</p>\n</blockquote>\n"
},
{
"answer_id": 9835789,
"author": "vishesh",
"author_id": 1219463,
"author_profile": "https://Stackoverflow.com/users/1219463",
"pm_score": 3,
"selected": false,
"text": "<p>Simple example in java</p>\n\n<pre><code>public class Driver {\n\n static int x;\n static int y;\n\npublic static void main(String[] args) \nthrows Exception {\n\nSystem.out.println(\"using double pipe\");\n if(setX() || setY())\n {System.out.println(\"x = \"+x);\n System.out.println(\"y = \"+y);\n }\n\n\n\nSystem.out.println(\"using single pipe\");\nif(setX() | setY())\n {System.out.println(\"x = \"+x);\n System.out.println(\"y = \"+y);\n }\n\n}\n\n static boolean setX(){\n x=5;\n return true;\n }\n static boolean setY(){\n y=5;\n return true;\n }\n}\n</code></pre>\n\n<p>output : </p>\n\n<pre><code>using double pipe\nx = 5\ny = 0\nusing single pipe\nx = 5\ny = 5\n</code></pre>\n"
},
{
"answer_id": 39677610,
"author": "Dragos Bandur",
"author_id": 6874836,
"author_profile": "https://Stackoverflow.com/users/6874836",
"pm_score": 0,
"selected": false,
"text": "<p>By their mathematical definition, OR and AND are binary operators; they verify the LHS and RHS conditions regardless, similarly to | and &. </p>\n\n<p>|| and && alter the properties of the OR and AND operators by stopping them when the LHS condition isn't fulfilled.</p>\n"
},
{
"answer_id": 47277418,
"author": "Bhai Saab",
"author_id": 8917503,
"author_profile": "https://Stackoverflow.com/users/8917503",
"pm_score": 4,
"selected": false,
"text": "<p>& - (Condition 1 & Condition 2): checks both cases even if first one is false</p>\n\n<p>&& - (Condition 1 && Condition 2): dosen't bother to check second case if case one \n is false </p>\n\n<p>&& - operator will make your code run faster, professionally & is rarely used</p>\n\n<p>| - (Condition 1 | Condition 2): checks both cases even if case 1 is true</p>\n\n<p>|| - (Condition 1 || Condition 2): dosen't bother to check second case if first \n one is true </p>\n\n<p>|| - operator will make your code run faster, professionally | is rarely used</p>\n"
},
{
"answer_id": 62966167,
"author": "RvSingh3213",
"author_id": 13728648,
"author_profile": "https://Stackoverflow.com/users/13728648",
"pm_score": -1,
"selected": false,
"text": "<p>For bitwise <code>|</code> and Logicall <code>||</code></p>\n<p>OR</p>\n<p>bitwise <code>&</code> and logicall <code>&&</code></p>\n<p>it means <code> if( a>b | a==0)</code>\nin this first left <code>a>b</code> will be evaluated and then <code>a==0</code> will be evaluated then <code>|</code> operation will be done</p>\n<p>but in<code>|| if a>b</code> then if wont check for next RHS</p>\n<p>Similarly for & and &&</p>\n<p><code>if(A>0 & B>0)</code></p>\n<p>it will evalue LHS and then RHS then do bitwise & but</p>\n<p>in<code>(A>0 && B>0)</code></p>\n<p><code>if(A>0)</code> is <code>false</code>(LHS) it will directly <code>return false;</code></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
] | I have always used `||` (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: `|`. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable? | Just like the `&` and `&&` operator, the double Operator is a "short-circuit" operator.
For example:
```
if(condition1 || condition2 || condition3)
```
If condition1 is true, condition 2 and 3 will NOT be checked.
```
if(condition1 | condition2 | condition3)
```
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
```
if(class != null && class.someVar < 20)
```
If class is null, the if-statement will stop after `class != null` is false. If you only use &, it will try to check `class.someVar` and you get a nice `NullReferenceException`. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.
No one ever uses the single `&` or `|` operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The `&` operator does "run these 3 functions, and if one of them returns false, execute the else block", while the `|` does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the `|` and `&` operator though: [Bitwise Operations](http://www.c-sharpcorner.com/UploadFile/chandrahundigam/BitWiserOpsInCS11082005050940AM/BitWiserOpsInCS.aspx). |
35,317 | <p>When I log into a remote machine using ssh X11 forwarding, Vista pops up a box complaining about a process that died unexpectedly. Once I dismiss the box, everything is fine. So I really don't care if some process died. How do I get Vista to shut up about it?</p>
<hr>
<p>Specifically, the message reads:</p>
<pre><code>sh.exe has stopped working
</code></pre>
<p>So it's not ssh itself that died, but some sub-process.</p>
<p>The problem details textbox reads:</p>
<pre><code>Problem signature:
Problem Event Name: APPCRASH
Application Name: sh.exe
Application Version: 0.0.0.0
Application Timestamp: 48a031a1
Fault Module Name: comctl32.dll_unloaded
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4549bcb0
Exception Code: c0000005
Exception Offset: 73dc5b17
OS Version: 6.0.6000.2.0.0.768.3
Locale ID: 1033
Additional Information 1: fc4d
Additional Information 2: d203a7335117760e7b4d2cf9dc2925f9
Additional Information 3: 1bc1
Additional Information 4: 7bc0b00964c4a1bd48f87b2415df3372
Read our privacy statement:
http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
</code></pre>
<p>I notice the problem occurs when I use the <strong>-Y</strong> option to enable X11 forwarding in an X terminal under Vista.</p>
<p>The dialog box that pops up doesn't automatically gain focus, so pressing Enter serves no purpose. I have to wait for the box to appear, grab it with the mouse, and dismiss it. Even forcing the error to receive focus would be a step in the right direction.</p>
<hr>
<p>Per DrPizza I have sent an <a href="http://cygwin.com/ml/cygwin/2008-08/msg00880.html" rel="nofollow noreferrer">email</a> to the Cygwin mailing list. The trimmed down subject line represents my repeated attempts to bypass an over-aggressive spam filter and highlights the need for something like StackOverflow.</p>
| [
{
"answer_id": 35324,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is, the process didn't just die, it died unexpectedly. Sounds like there's a bug in your SSH client that Vista is pointing out.</p>\n"
},
{
"answer_id": 35368,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is going to be heresy for a cygwin user, but you could just use <a href=\"http://www.chiark.greenend.org.uk/~sgtatham/putty/\" rel=\"nofollow noreferrer\">PuTTY</a> instead.</p>\n"
},
{
"answer_id": 35387,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": true,
"text": "<p>Well, I don't know what the original problem was, but when I update Cygwin recently the error message stopped popping up.</p>\n\n<p>My guess it that <a href=\"http://sourceware.org/ml/cygwin/2006-11/msg00059.html\" rel=\"nofollow noreferrer\">rebasing</a> was necessary.</p>\n"
},
{
"answer_id": 35401,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>What does unexpectedly mean in this context? Does it mean it core dumped or just exited non-zero?</p>\n</blockquote>\n\n<p>It means it died with an unhandled exception, i.e. it crashed.</p>\n"
},
{
"answer_id": 1203513,
"author": "Marsh Ray",
"author_id": 116270,
"author_profile": "https://Stackoverflow.com/users/116270",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Fault Module Name: comctl32.dll_unloaded\n Exception Code: c0000005</p>\n</blockquote>\n\n<p>Something had triggered loading of comctl32.dll, but it was later unloaded.</p>\n\n<p>c0000005 means 'access violation'. Probably something tried calling a function in the unloaded dll.</p>\n\n<p>I agree with one of the cygwin commentators that it's possibly a bug in some antivirus program or \"desktop enhancement\" software. Video card companies like to inject their stuff into every process, too. It's easy to use comctl32.dll for things without realizing it, however.</p>\n\n<p>Try downloading and installing WinDbg from Microsoft. <code>http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx</code> Set it as the default JIT debugger \"windbg.exe -I\". Next time this happens you should get the nice debugger window pop up. Type \"kv100\" to get a stack trace. Look at the dlls listed in the calling path, there's a good chance one of them is the culprit.</p>\n\n<p>If you see a dll that's not from Microsoft or Cygwin there, uninstall that application and see if the problem goes away. Otherwise, the Cygwin list might be interested in the stack trace.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | When I log into a remote machine using ssh X11 forwarding, Vista pops up a box complaining about a process that died unexpectedly. Once I dismiss the box, everything is fine. So I really don't care if some process died. How do I get Vista to shut up about it?
---
Specifically, the message reads:
```
sh.exe has stopped working
```
So it's not ssh itself that died, but some sub-process.
The problem details textbox reads:
```
Problem signature:
Problem Event Name: APPCRASH
Application Name: sh.exe
Application Version: 0.0.0.0
Application Timestamp: 48a031a1
Fault Module Name: comctl32.dll_unloaded
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4549bcb0
Exception Code: c0000005
Exception Offset: 73dc5b17
OS Version: 6.0.6000.2.0.0.768.3
Locale ID: 1033
Additional Information 1: fc4d
Additional Information 2: d203a7335117760e7b4d2cf9dc2925f9
Additional Information 3: 1bc1
Additional Information 4: 7bc0b00964c4a1bd48f87b2415df3372
Read our privacy statement:
http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
```
I notice the problem occurs when I use the **-Y** option to enable X11 forwarding in an X terminal under Vista.
The dialog box that pops up doesn't automatically gain focus, so pressing Enter serves no purpose. I have to wait for the box to appear, grab it with the mouse, and dismiss it. Even forcing the error to receive focus would be a step in the right direction.
---
Per DrPizza I have sent an [email](http://cygwin.com/ml/cygwin/2008-08/msg00880.html) to the Cygwin mailing list. The trimmed down subject line represents my repeated attempts to bypass an over-aggressive spam filter and highlights the need for something like StackOverflow. | Well, I don't know what the original problem was, but when I update Cygwin recently the error message stopped popping up.
My guess it that [rebasing](http://sourceware.org/ml/cygwin/2006-11/msg00059.html) was necessary. |
35,320 | <p>In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.</p>
<pre><code>DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
</code></pre>
<p>So if tblCustomer looks like this: </p>
<pre><code>ParentID CustID
5 5
1 8
5 4
4 1
</code></pre>
<p>The result I get from the code above is: </p>
<pre><code>ParentID CustID
4 1
5 4
5 5
</code></pre>
<p>What I want is just the last row of that result: </p>
<pre><code>ParentID CustID
5 5
</code></pre>
<p>How do I just return the last record generated in the CTE (which would be highest level CustID)?</p>
<p>Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT * FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy.</p>
| [
{
"answer_id": 35425,
"author": "Trevor Abell",
"author_id": 2916,
"author_profile": "https://Stackoverflow.com/users/2916",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not certain I fully understand the problem, but just to hack & slash at it you could try:</p>\n\n<pre><code>SELECT TOP 1 FROM cteLevelOne ORDER BY CustID DESC\n</code></pre>\n\n<p>That assumes that the CustID is also in order as in the example, and not something like a GUID.</p>\n"
},
{
"answer_id": 35557,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 3,
"selected": true,
"text": "<p>If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so:</p>\n\n<pre><code>DECLARE @LookupID int\n\n--Our test value\nSET @LookupID = 1;\n\nWITH cteLevelOne (ParentID, CustID, Depth) AS\n(\n SELECT a.ParentID, a.CustID, 1\n FROM tblCustomer AS a\n WHERE a.CustID = @LookupID\n UNION ALL\n SELECT a.ParentID, a.CustID, c.Depth + 1\n FROM tblCustomer AS a\n INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID \n WHERE c.CustID <> a.CustID\n)\nselect * from CTELevelone where Depth = (select max(Depth) from CTELevelone)\n</code></pre>\n\n<p>or, adapting what trevor suggests, this could be used with the same CTE: </p>\n\n<pre><code>select top 1 * from CTELevelone order by Depth desc\n</code></pre>\n\n<p>I don't think CustomerID was necessarily what you wanted to order by in the case you described, but I wasn't perfectly clear on the question either.</p>\n"
},
{
"answer_id": 24691911,
"author": "Naveen raj",
"author_id": 3828330,
"author_profile": "https://Stackoverflow.com/users/3828330",
"pm_score": 0,
"selected": false,
"text": "<p>First the cte will not be finished if any of the parent child are same. As it is a recursive CTE it has to be terminated. Having Parent and cust id same , the loop will not end.</p>\n\n<p>Msg 530, Level 16, State 1, Line 15\nThe statement terminated. The maximum recursion 100 has been exhausted before statement completion.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677/"
] | In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.
```
DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
```
So if tblCustomer looks like this:
```
ParentID CustID
5 5
1 8
5 4
4 1
```
The result I get from the code above is:
```
ParentID CustID
4 1
5 4
5 5
```
What I want is just the last row of that result:
```
ParentID CustID
5 5
```
How do I just return the last record generated in the CTE (which would be highest level CustID)?
Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT \* FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy. | If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so:
```
DECLARE @LookupID int
--Our test value
SET @LookupID = 1;
WITH cteLevelOne (ParentID, CustID, Depth) AS
(
SELECT a.ParentID, a.CustID, 1
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID, c.Depth + 1
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustID
)
select * from CTELevelone where Depth = (select max(Depth) from CTELevelone)
```
or, adapting what trevor suggests, this could be used with the same CTE:
```
select top 1 * from CTELevelone order by Depth desc
```
I don't think CustomerID was necessarily what you wanted to order by in the case you described, but I wasn't perfectly clear on the question either. |
35,322 | <p>I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough.</p>
<p>Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? </p>
<p>I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior.</p>
<p>Note: As a test I added this to my global.asax and it didn't bypass forms auth:</p>
<pre><code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SkipAuthorization = true;
}
</code></pre>
<hr>
<p>@Dale and Andy</p>
<p>I'm using the AuthorizeAttributeFilter provided in MVC preview 4. This is returning an HttpUnauthorizedResult. This result is correctly setting the statusCode to 401. The problem, as i understand it, is that asp.net is intercepting the response (since its taged as a 401) and redirecting to the login page instead of just letting it go through. I want to bypass this interception for certain urls.</p>
| [
{
"answer_id": 35341,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": -1,
"selected": false,
"text": "<p>I did some googling and this is what I came up with:</p>\n\n<pre><code>\n HttpContext.Current.Response.StatusCode = 401;\n</code></pre>\n\n<p>Not sure if it works or not, I haven't tested it. Either way, it's worth a try, right? :)</p>\n"
},
{
"answer_id": 35352,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>Did you write your own FormsAuth attribute for the action? If so, in the OnActionExecuting method, you get passed the FilterExecutingContext. You can use this to pass back the 401 code.</p>\n\n<pre><code>public class FormsAuth : ActionFilterAttribute\n{\n public override void OnActionExecuting(FilterExecutingContext filterContext)\n {\n filterContext.HttpContext.Response.StatusCode = 401;\n filterContext.Cancel = true;\n }\n}\n</code></pre>\n\n<p>This should work. I am not sure if you wrote the FormsAuth attribute or if you got it from somewhere else.</p>\n"
},
{
"answer_id": 35415,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't used the AuthorizeAttribute that comes in Preview 4 yet. I rolled my own, because I have been using the MVC framework since the first CTP. I took a quick look at the attribute in reflector and it is doing what I mentioned above internally, except they use the hex equivalent of 401. I will need to look further up the call, to see where the exception is caught, because more than likely that is where they are doing the redirect. This is the functionality you will need to override. I am not sure if you can do it yet, but I will post back when I find it and give you a work around, unless Haacked sees this and posts it himself.</p>\n"
},
{
"answer_id": 35516,
"author": "Dane O'Connor",
"author_id": 1946,
"author_profile": "https://Stackoverflow.com/users/1946",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, I worked around this. I made a custom ActionResult (HttpForbiddenResult) and custom ActionFilter (NoFallBackAuthorize).</p>\n\n<p>To avoid redirection, HttpForbiddenResult marks responses with status code 403. FormsAuthentication doesn't catch responses with this code so the login redirection is effectively skipped. The NoFallBackAuthorize filter checks to see if the user is authorized much like the, included, Authorize filter. It differs in that it returns HttpForbiddenResult when access is denied. </p>\n\n<p>The HttpForbiddenResult is pretty trivial:</p>\n\n<pre>\npublic class HttpForbiddenResult : ActionResult\n{\n public override void ExecuteResult(ControllerContext context)\n {\n if (context == null)\n {\n throw new ArgumentNullException(\"context\");\n }\n context.HttpContext.Response.StatusCode = 0x193; // 403\n }\n}\n</pre>\n\n<p>It doesn't appear to be possible to skip the login page redirection in the FormsAuthenticationModule.</p>\n"
},
{
"answer_id": 35518,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 1,
"selected": false,
"text": "<p>Might be a kludge (and may not even work) but on your Login page see if <code>Request.QueryString[\"ReturnUrl\"] != null</code> and if so set <code>Response.StatusCode = 401</code>.</p>\n\n<p>Bear in mind that you'll still need to get your console app to authenticate somehow. You don't get HTTP basic auth for free: you have to roll your own, but there are plenty of implementations about.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] | I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough.
Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page?
I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior.
Note: As a test I added this to my global.asax and it didn't bypass forms auth:
```
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SkipAuthorization = true;
}
```
---
@Dale and Andy
I'm using the AuthorizeAttributeFilter provided in MVC preview 4. This is returning an HttpUnauthorizedResult. This result is correctly setting the statusCode to 401. The problem, as i understand it, is that asp.net is intercepting the response (since its taged as a 401) and redirecting to the login page instead of just letting it go through. I want to bypass this interception for certain urls. | Ok, I worked around this. I made a custom ActionResult (HttpForbiddenResult) and custom ActionFilter (NoFallBackAuthorize).
To avoid redirection, HttpForbiddenResult marks responses with status code 403. FormsAuthentication doesn't catch responses with this code so the login redirection is effectively skipped. The NoFallBackAuthorize filter checks to see if the user is authorized much like the, included, Authorize filter. It differs in that it returns HttpForbiddenResult when access is denied.
The HttpForbiddenResult is pretty trivial:
```
public class HttpForbiddenResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.HttpContext.Response.StatusCode = 0x193; // 403
}
}
```
It doesn't appear to be possible to skip the login page redirection in the FormsAuthenticationModule. |
35,333 | <p>I'm compiling a simple .c in visual c++ with Compile as C Code (/TC)
and i get this compiler error </p>
<blockquote>
<p>error C2143: syntax error : missing ';' before 'type'</p>
</blockquote>
<p>on a line that calls for a simple struct </p>
<pre><code> struct foo test;
</code></pre>
<p>same goes for using the typedef of the struct.</p>
<blockquote>
<p>error C2275: 'FOO' : illegal use of this type as an expression</p>
</blockquote>
| [
{
"answer_id": 35336,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>Did you accidentally omit a semicolon on a previous line? If the previous line is an <code>#include</code>, you might have to look elsewhere for the missing semicolon.</p>\n\n<p>Edit: If the rest of your code is valid C++, then there probably isn't enough information to determine what the problem is. Perhaps you could post your code to a <a href=\"http://pastebin.ca\" rel=\"nofollow noreferrer\">pastebin</a> so we can see the whole thing.</p>\n\n<p>Ideally, in the process of making it smaller to post, it will suddenly start working and you'll then have discovered the problem!</p>\n"
},
{
"answer_id": 35362,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "<p>How is your structure type defined? There are two ways to do it:</p>\n\n<pre><code>// This will define a typedef for S1, in both C and in C++\ntypedef struct {\n int data;\n int text;\n} S1;\n\n// This will define a typedef for S2 ONLY in C++, will create error in C.\nstruct S2 {\n int data;\n int text; \n};\n</code></pre>\n"
},
{
"answer_id": 35417,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "<p>Because you've already made a typedef for the struct (because you used the 's1' version), you should write:</p>\n\n<pre><code>foo test;\n</code></pre>\n\n<p>rather than </p>\n\n<pre><code>struct foo test;\n</code></pre>\n\n<p>That will work in both C and C++</p>\n"
},
{
"answer_id": 35464,
"author": "Andrew O'Reilly",
"author_id": 3692,
"author_profile": "https://Stackoverflow.com/users/3692",
"pm_score": 0,
"selected": false,
"text": "<p>C2143 basically says that the compiler got a token that it thinks is illegal in the current context. One of the implications of this error is that the actual problem may exist before the line that triggers the compiler error. As Greg said I think we need to see more of your code to diagnose this problem.</p>\n\n<p>I'm also not sure why you think the fact that this is valid C++ code is helpful when attempting to figure out why it doesn't compile as C? C++ is (largely) a superset of C so there's any number of reasons why valid C++ code might not be syntactically correct C code, not least that C++ treats structs as classes!</p>\n"
},
{
"answer_id": 35477,
"author": "CiNN",
"author_id": 2566,
"author_profile": "https://Stackoverflow.com/users/2566",
"pm_score": 4,
"selected": true,
"text": "<p>I forgot that in C you have to declare all your variables before any code.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | I'm compiling a simple .c in visual c++ with Compile as C Code (/TC)
and i get this compiler error
>
> error C2143: syntax error : missing ';' before 'type'
>
>
>
on a line that calls for a simple struct
```
struct foo test;
```
same goes for using the typedef of the struct.
>
> error C2275: 'FOO' : illegal use of this type as an expression
>
>
> | I forgot that in C you have to declare all your variables before any code. |
35,407 | <p>I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron.</p>
<p>The invocation looks like:</p>
<pre><code>make -k -j 4 -l 3.99 -C [dir] [12 targets]
</code></pre>
<p>The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem.</p>
<p>Edit: Sometimes a target does fail but I use the -k option to have the rest of the make still run. I haven't noticed any correlation with jobs failing and the next job not starting.</p>
| [
{
"answer_id": 35447,
"author": "KannoN",
"author_id": 2897,
"author_profile": "https://Stackoverflow.com/users/2897",
"pm_score": 0,
"selected": false,
"text": "<p>Does make think one of the targets is failing? If so, it will stop the make after the running jobs finish. You can use -k to tell it to continue even if an error occurs.</p>\n"
},
{
"answer_id": 35526,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 1,
"selected": false,
"text": "<p>I'd drop the '-l'</p>\n\n<p>If all you plan to run the the system is this build I <em>think</em> the -j 4 does what you want.</p>\n\n<p>Based on my memory, if you have anything else running (crond?), that can push the load average over 4.</p>\n\n<p><a href=\"http://sunsite.ualberta.ca/Documentation/Gnu/make-3.79/html_chapter/make_5.html#SEC47\" rel=\"nofollow noreferrer\">GNU make ref</a></p>\n"
},
{
"answer_id": 36211,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 0,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/users/1343/bcs\">BCS</a></p>\n\n<p>I'm 99.9% sure that the -l isn't causeing the problem because I can watch the load average on the machine and it drops down to about three and sometimes as low as one (!) without starting the next job.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447/"
] | I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron.
The invocation looks like:
```
make -k -j 4 -l 3.99 -C [dir] [12 targets]
```
The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem.
Edit: Sometimes a target does fail but I use the -k option to have the rest of the make still run. I haven't noticed any correlation with jobs failing and the next job not starting. | I'd drop the '-l'
If all you plan to run the the system is this build I *think* the -j 4 does what you want.
Based on my memory, if you have anything else running (crond?), that can push the load average over 4.
[GNU make ref](http://sunsite.ualberta.ca/Documentation/Gnu/make-3.79/html_chapter/make_5.html#SEC47) |
35,420 | <p>I've had a tough time setting up my replication server. Is there any program (OS X, Windows, Linux, or PHP no problem) that lets me monitor and resolve replication issues? (btw, for those following, I've been on this issue <a href="https://stackoverflow.com/questions/8166/mysql-replication-if-i-dont-specify-any-databases-will-logbin-log-everything">here</a>, <a href="https://stackoverflow.com/questions/3798/full-complete-mysql-db-replication-ideas-what-do-people-do">here</a>, <a href="https://stackoverflow.com/questions/8365/mysql-administrator-backups-compatibility-mode-what-exactly-is-this-doing">here</a> and <a href="https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors">here</a>)</p>
<p>My production database is several megs in size and growing. Every time the database replication stops and the databases inevitably begin to slide out of sync i cringe. My last resync from dump took almost 4 hours roundtrip!</p>
<p>As always, even after sync, I run into this kind of show-stopping error:</p>
<pre><code>Error 'Duplicate entry '252440' for key 1' on query.
</code></pre>
<p>I would love it if there was some way to closely monitor whats going on and perhaps let the software deal with it. I'm even all ears for service companies which may help me monitor my data better. Or an alternate way to mirror altogether.</p>
<p><strong>Edit</strong>: going through my previous questions i found <a href="https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors#30889">this</a> which helps tremendously. I'm still all ears on the monitoring solution.</p>
| [
{
"answer_id": 35438,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 3,
"selected": true,
"text": "<p>To monitor the servers we use the free <a href=\"http://www.maatkit.org/tools.html\" rel=\"nofollow noreferrer\">tools from Maatkit</a> ... simple, yet efficient.</p>\n\n<p>The binary replication is available in 5.1, so I guess you've got some balls. We still use 5.0 and it works OK, but of course we had our share of issues with it.</p>\n\n<p>We use a Master-Master replication with a MySql Proxy as a load-balancer in front, and to prevent it from having errors:</p>\n\n<ul>\n<li>we removed all unique indexes</li>\n<li>for the few cases where we really needed unique constraints we made sure we used REPLACE instead of INSERT (MySql Proxy can be used to guard for proper usage ... it can even rewrite your queries)</li>\n<li>scheduled scripts doing intensive reports are always accessing the same server (not the load-balancer) ... so that dangerous operations are replicated safely</li>\n</ul>\n\n<p>Yeah, I know it sounds simple and stupid, but it solved 95% of all the problems we had.</p>\n"
},
{
"answer_id": 45929,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 0,
"selected": false,
"text": "<p>We use mysql replication to replicate data to close to 30 servers. We monitor them with nagios. You can probably check the replication status and use an event handler to restart it with 'SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; Start Slave;'. That will fix the error, but you'll lose the insert that caused the error. </p>\n\n<p>About the error, do you use memory tables on your slaves? I ask this because the only time we ever got a lot of these error they where caused by a bug in the latests releases of mysql. 'Delete From Table Where Field = Value' will delete only one row in memory tables even though they where multiple rows.</p>\n\n<p><a href=\"http://bugs.mysql.com/bug.php?id=30590\" rel=\"nofollow noreferrer\">mysql bug descritpion</a></p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | I've had a tough time setting up my replication server. Is there any program (OS X, Windows, Linux, or PHP no problem) that lets me monitor and resolve replication issues? (btw, for those following, I've been on this issue [here](https://stackoverflow.com/questions/8166/mysql-replication-if-i-dont-specify-any-databases-will-logbin-log-everything), [here](https://stackoverflow.com/questions/3798/full-complete-mysql-db-replication-ideas-what-do-people-do), [here](https://stackoverflow.com/questions/8365/mysql-administrator-backups-compatibility-mode-what-exactly-is-this-doing) and [here](https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors))
My production database is several megs in size and growing. Every time the database replication stops and the databases inevitably begin to slide out of sync i cringe. My last resync from dump took almost 4 hours roundtrip!
As always, even after sync, I run into this kind of show-stopping error:
```
Error 'Duplicate entry '252440' for key 1' on query.
```
I would love it if there was some way to closely monitor whats going on and perhaps let the software deal with it. I'm even all ears for service companies which may help me monitor my data better. Or an alternate way to mirror altogether.
**Edit**: going through my previous questions i found [this](https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors#30889) which helps tremendously. I'm still all ears on the monitoring solution. | To monitor the servers we use the free [tools from Maatkit](http://www.maatkit.org/tools.html) ... simple, yet efficient.
The binary replication is available in 5.1, so I guess you've got some balls. We still use 5.0 and it works OK, but of course we had our share of issues with it.
We use a Master-Master replication with a MySql Proxy as a load-balancer in front, and to prevent it from having errors:
* we removed all unique indexes
* for the few cases where we really needed unique constraints we made sure we used REPLACE instead of INSERT (MySql Proxy can be used to guard for proper usage ... it can even rewrite your queries)
* scheduled scripts doing intensive reports are always accessing the same server (not the load-balancer) ... so that dangerous operations are replicated safely
Yeah, I know it sounds simple and stupid, but it solved 95% of all the problems we had. |
35,463 | <p>Some code that rounds up the division to demonstrate (C-syntax):</p>
<pre><code>#define SINT64 long long int
#define SINT32 long int
SINT64 divRound(SINT64 dividend, SINT64 divisor)
{
SINT32 quotient1 = dividend / divisor;
SINT32 modResult = dividend % divisor;
SINT32 multResult = modResult * 2;
SINT32 quotient2 = multResult / divisor;
SINT64 result = quotient1 + quotient2;
return ( result );
}
</code></pre>
<p>Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. <code>divdi3()</code> for division). Chances are we link with <code>libgcc</code> without even knowing it. The problem is that Kernel-space is different (e.g. no <code>libgcc</code>). What to do?</p>
<p>Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:</p>
<pre><code>#define UINT64 long long int
#define UINT32 long int
UINT64 divRound(UINT64 dividend, UINT64 divisor)
{
UINT32 quotient1 = dividend / divisor;
UINT32 modResult = dividend % divisor;
UINT32 multResult = modResult * 2;
UINT32 quotient2 = multResult / divisor;
UINT64 result = quotient1 + quotient2;
return ( result );
}
</code></pre>
<p>I know how to fix this one: Override <code>udivdi3()</code> and <code>umoddi3()</code> with <code>do_div()</code> from <em>asm/div64.h</em>. Done right? Wrong. Signed is not the same as unsigned, <code>sdivdi3()</code> does not simply call <code>udivdi3()</code>, they are separate functions for a reason.</p>
<p>Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.</p>
<p>Thanks,
Chad</p>
| [
{
"answer_id": 35468,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 0,
"selected": false,
"text": "<p><code>ldiv</code> ?</p>\n\n<p>Edit: reread title, so you might want to ignore this. Or not, depending on if it has an appropriate non-library version.</p>\n"
},
{
"answer_id": 35472,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my really naive solution. Your mileage may vary.</p>\n\n<p>Keep a sign bit, which is <code>sign(dividend) ^ sign(divisor)</code>. (Or <code>*</code>, or <code>/</code>, if you're storing your sign as 1 and -1, as opposed to false and true. Basically, negative if either one is negative, positive if none or both are negative.)</p>\n\n<p>Then, call the unsigned division function on the absolute values of both. Then tack the sign back onto the result.</p>\n\n<p>P.S. That is actually how <code>__divdi3</code> is implemented in <code>libgcc2.c</code> (from GCC 4.2.3, the version that's installed on my Ubuntu system). I just checked. :-)</p>\n"
},
{
"answer_id": 39889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think (at least can't find a way to make) <a href=\"https://stackoverflow.com/questions/35463/how-to-divide-two-64-bit-numbers-in-linux-kernel#35472\">Chris' answer</a> work in this case because <strong><em>do_div()</em></strong> actually changes the dividend in-place. Getting the absolute value implies a temporary variable whose value will change the way I require but can't be passed out of my <strong><em>__divdi3()</em></strong> override. </p>\n\n<p>I don't see a way around the parameter-by-value signature of <strong><em>__divdi3()</em></strong> at this point except to mimic the technique used by <strong><em>do_div()</em></strong>.</p>\n\n<p>It might seem like I'm bending over backwards here and should just come up with an algorithm to do the 64-bit/32-bit division I actually need. The added complication here though is that I have a bunch of numerical code using the '/' operator and would need to go through that code and replace every '/' with my function calls.</p>\n\n<p>I'm getting desperate enough to do just that though.</p>\n\n<p>Thanks for any follow-up,\nChad</p>\n"
},
{
"answer_id": 196172,
"author": "colgur",
"author_id": 1059,
"author_profile": "https://Stackoverflow.com/users/1059",
"pm_score": 3,
"selected": false,
"text": "<p>This functionality is introduced in <a href=\"http://lxr.linux.no/linux+v2.6.22/lib/div64.c\" rel=\"noreferrer\">/linux/lib/div64.c</a> as early as kernel v2.6.22.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Some code that rounds up the division to demonstrate (C-syntax):
```
#define SINT64 long long int
#define SINT32 long int
SINT64 divRound(SINT64 dividend, SINT64 divisor)
{
SINT32 quotient1 = dividend / divisor;
SINT32 modResult = dividend % divisor;
SINT32 multResult = modResult * 2;
SINT32 quotient2 = multResult / divisor;
SINT64 result = quotient1 + quotient2;
return ( result );
}
```
Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. `divdi3()` for division). Chances are we link with `libgcc` without even knowing it. The problem is that Kernel-space is different (e.g. no `libgcc`). What to do?
Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:
```
#define UINT64 long long int
#define UINT32 long int
UINT64 divRound(UINT64 dividend, UINT64 divisor)
{
UINT32 quotient1 = dividend / divisor;
UINT32 modResult = dividend % divisor;
UINT32 multResult = modResult * 2;
UINT32 quotient2 = multResult / divisor;
UINT64 result = quotient1 + quotient2;
return ( result );
}
```
I know how to fix this one: Override `udivdi3()` and `umoddi3()` with `do_div()` from *asm/div64.h*. Done right? Wrong. Signed is not the same as unsigned, `sdivdi3()` does not simply call `udivdi3()`, they are separate functions for a reason.
Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.
Thanks,
Chad | This functionality is introduced in [/linux/lib/div64.c](http://lxr.linux.no/linux+v2.6.22/lib/div64.c) as early as kernel v2.6.22. |
35,480 | <p>I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod_perl implementation, so an instance of a class can be quite old between times that it is accessed.
From the man pages I found two options:</p>
<pre><code>Music::DBI->clear_object_index();
</code></pre>
<p>And:</p>
<pre><code>Music::Artist->purge_object_index_every(2000);
</code></pre>
<p>Now, when I add clear_object_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version.
purge_object_index_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.</p>
<p>Any suggestions for clearing this out?</p>
| [
{
"answer_id": 35529,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 4,
"selected": true,
"text": "<p>The \"<a href=\"http://wiki.class-dbi.com/wiki/Common_problems\" rel=\"nofollow noreferrer\">common problems</a>\" page on the <a href=\"http://wiki.class-dbi.com/wiki\" rel=\"nofollow noreferrer\">Class::DBI wiki</a> has a <a href=\"http://wiki.class-dbi.com/wiki/Common_problems#Old_data_due_to_object_index\" rel=\"nofollow noreferrer\">section</a> on this subject. The simplest solution is to disable the live object index entirely using:</p>\n\n<pre><code>$Class::DBI::Weaken_Is_Available = 0;\n</code></pre>\n"
},
{
"answer_id": 47568,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "<p>I've used remove_from_object_index successfully in the past, so that when a page is called that modifies the database, it always explicitly reset that object in the cache as part of the confirmation page.</p>\n"
},
{
"answer_id": 47599,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 2,
"selected": false,
"text": "<p>$obj->dbi_commit(); may be what you are looking for if you have uncompleted transactions. However, this is not very likely the case, as it tends to complete any lingering transactions automatically on destruction.</p>\n\n<p>When you do this:</p>\n\n<pre><code>Music::Artist->purge_object_index_every(2000);\n</code></pre>\n\n<p>You are telling it to examine the object cache every 2000 object loads and remove any dead references to conserve memory use. I don't think that is what you want at all.</p>\n\n<p>Furthermore,</p>\n\n<pre><code>Music::DBI->clear_object_index();\n</code></pre>\n\n<p>Removes all objects form the live object index. I don't know how this would help at all; it's not flushing them to disk, really.</p>\n\n<p>It sounds like what you are trying to do should work just fine the way you have it, but there may be a problem with your SQL or elsewhere that is preventing the INSERT or UPDATE from working. Are you doing error checking for each database query as the perldoc suggests? Perhaps you can begin there or in your database error logs, watching the queries to see why they aren't being completed or if they ever arrive.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 2007971,
"author": "Shlomi Fish",
"author_id": 7709,
"author_profile": "https://Stackoverflow.com/users/7709",
"pm_score": -1,
"selected": false,
"text": "<p>I should note that Class::DBI is deprecated and you should port your code to <a href=\"http://search.cpan.org/dist/DBIx-Class/\" rel=\"nofollow noreferrer\">DBIx::Class</a> instead.</p>\n"
}
] | 2008/08/29 | [
"https://Stackoverflow.com/questions/35480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3421/"
] | I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod\_perl implementation, so an instance of a class can be quite old between times that it is accessed.
From the man pages I found two options:
```
Music::DBI->clear_object_index();
```
And:
```
Music::Artist->purge_object_index_every(2000);
```
Now, when I add clear\_object\_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version.
purge\_object\_index\_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.
Any suggestions for clearing this out? | The "[common problems](http://wiki.class-dbi.com/wiki/Common_problems)" page on the [Class::DBI wiki](http://wiki.class-dbi.com/wiki) has a [section](http://wiki.class-dbi.com/wiki/Common_problems#Old_data_due_to_object_index) on this subject. The simplest solution is to disable the live object index entirely using:
```
$Class::DBI::Weaken_Is_Available = 0;
``` |
35,485 | <p>I want to be able to get an estimate of how much code & static data is used by my C++ program?</p>
<p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p>
<p>Will objdump & readelf help?</p>
| [
{
"answer_id": 35508,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "<p><code>readelf</code> will indeed help. You can use the <code>-S</code> option; that will show the sizes of all sections. <code>.text</code> is (the bulk of) your executable code. <code>.data</code> and <code>.rodata</code> is your static data. There are other sections too, some of which are used at runtime, others only at link time.</p>\n"
},
{
"answer_id": 35738,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "<p>\"size\" is the traditional tool. \"readelf\" has a lot of options.</p>\n\n<pre><code>$ size /bin/sh\n text data bss dec hex filename\n 712739 37524 21832 772095 bc7ff /bin/sh\n</code></pre>\n"
},
{
"answer_id": 47033,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to take the next step of identifying the functions and data structures to focus on for footprint reduction, the --size-sort argument to nm can show you:</p>\n\n<pre><code>$ nm --size-sort /usr/bin/fld | tail -10\n000000ae T FontLoadFontx\n000000b0 T CodingByRegistry\n000000b1 t ShmFont\n000000ec t FontLoadw\n000000ef T LoadFontFile\n000000f6 T FontLoadDFontx\n00000108 D fSRegs\n00000170 T FontLoadMinix\n000001e7 T main\n00000508 T FontLoadBdf\n</code></pre>\n"
},
{
"answer_id": 106984,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 1,
"selected": false,
"text": "<pre>\nsize -A\n</pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] | I want to be able to get an estimate of how much code & static data is used by my C++ program?
Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?
Will objdump & readelf help? | "size" is the traditional tool. "readelf" has a lot of options.
```
$ size /bin/sh
text data bss dec hex filename
712739 37524 21832 772095 bc7ff /bin/sh
``` |
35,491 | <p>I want to be able to get an estimate of how much code & static data is used by my C++ program?</p>
<p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p>
<p>Will otool help?</p>
| [
{
"answer_id": 35583,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 2,
"selected": false,
"text": "<p>I think otool can help. Specifically, \"otool -s {segment} {section}\" should print out the details. I'm not sure if you can get information about __DATA or __TEXT without specifying a section. Maybe those sizes are reported in the mach header: \"otool -h\"?</p>\n\n<pre><code>otool -s __DATA __data MyApp.bundle/Contents/MacOS/MyApp\notool -s __TEXT __text MyApp.bundle/Contents/MacOS/MyApp\n</code></pre>\n\n<p>Anyway, Apple documents what gets copied into each section per-segment here: <a href=\"http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html#//apple_ref/doc/uid/TP40000895-CH248-95874\" rel=\"nofollow noreferrer\">Apple's mach-o format documentation</a></p>\n"
},
{
"answer_id": 35694,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "<ul>\n<li>\"size\" is the traditional tool and works on all unix flavors. </li>\n<li>\"otool\" has a bit finer grain control and has a lot of options.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>$ size python\n__TEXT __DATA __OBJC others dec hex\n860160 159744 0 2453504 3473408 350000\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] | I want to be able to get an estimate of how much code & static data is used by my C++ program?
Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?
Will otool help? | * "size" is the traditional tool and works on all unix flavors.
* "otool" has a bit finer grain control and has a lot of options.
.
```
$ size python
__TEXT __DATA __OBJC others dec hex
860160 159744 0 2453504 3473408 350000
``` |
35,507 | <p>I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file.</p>
<p>I have all in default structure like: </p>
<pre>
application
|-- <i><b>META-INF</b></i> -- Some configs are here
|-- <i><b>WEB-INF</b></i> -- others here
| |-- classes
| | |-- META-INF
| | `-- mypackage
| | `-- class-files
| `-- lib
|-- css
`-- <i><b>tpl</b></i> -- Template dir to be relocated
</pre>
<p>And I apparently can't find documentation about how to setup (probably in struts.xml) where my templates go, and where config files will be.</p>
<p>I think I will have to use configurations on the application server too (I am using Jetty 5.1.14).</p>
<p>So, any lights on how to configure it ? </p>
<p>Thanks</p>
<hr>
<p>Well, the whole thing about changing templates place is to put the templates in a designer accessible area, so any modification needed, the designer can load them to his/her computer, edit, and upload it again. I think this is a common scenario. So, probably I am missing something in my research. Maybe I am focusing in configuring it on the wrong place ... Any thoughts ?</p>
| [
{
"answer_id": 35867,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 0,
"selected": false,
"text": "<p>For <em>persistence.xml</em>, specifically, you can put a persistence unit in a separate JAR, which you can deploy separately from your web application WAR, or both together in an EAR archive, depending on what your application server supports. For example, the JBoss manual describes this as <a href=\"http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta422/html/ch01s04s02.html\" rel=\"nofollow noreferrer\">Deploy EAR with EJB3 JAR</a>. </p>\n\n<p>For <em>struts-config.xml</em> I expect that you are going to have to override the Struts code that loads it, if you want to use a non-standard location.</p>\n\n<p>I don't know about the Velocity templates.</p>\n\n<p>In general, web applications only load resources from within the WAR, for security reasons. There are other techniques you can use, but you may find it easier to try <a href=\"https://weblets.dev.java.net/\" rel=\"nofollow noreferrer\">weblets</a>, which seems to be a framework designed to let you load resources from a separate JAR.</p>\n"
},
{
"answer_id": 197980,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You need to look into <code>velocity.properties</code> file in your WEB_INF folder.IMHO it is here where you need to change your <em>template root</em> changing the property <code>file.resource.loader.path</code>.</p>\n\n<p>Hope it helps,\nPetr</p>\n"
},
{
"answer_id": 234746,
"author": "RayOK",
"author_id": 31246,
"author_profile": "https://Stackoverflow.com/users/31246",
"pm_score": 2,
"selected": true,
"text": "<p>If I understood your question about Struts config files right, they are specified in web.xml. Find the Struts servlet config param. The param-value can be a list of comma separated list of XML files to load. Eg:</p>\n\n<pre><code><servlet>\n <servlet-name>action</servlet-name>\n <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>\n <init-param>\n <param-name>config</param-name>\n <param-value>\n WEB-INF/config/struts-config.xml,\n WEB-INF/config/struts-config-stuff.xml,\n WEB-INF/config/struts-config-good.xml,\n WEB-INF/config/struts-config-bad.xml,\n WEB-INF/config/struts-config-ugly.xml\n </param-value>\n </init-param>\n ...\n</servlet>\n</code></pre>\n\n<p>See this <a href=\"http://struts.apache.org/1.x/userGuide/configuration.html\" rel=\"nofollow noreferrer\">Struts guide</a> under 5.3.2. And yes, this applies to 2.x also.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file.
I have all in default structure like:
```
application
|-- ***META-INF*** -- Some configs are here
|-- ***WEB-INF*** -- others here
| |-- classes
| | |-- META-INF
| | `-- mypackage
| | `-- class-files
| `-- lib
|-- css
`-- ***tpl*** -- Template dir to be relocated
```
And I apparently can't find documentation about how to setup (probably in struts.xml) where my templates go, and where config files will be.
I think I will have to use configurations on the application server too (I am using Jetty 5.1.14).
So, any lights on how to configure it ?
Thanks
---
Well, the whole thing about changing templates place is to put the templates in a designer accessible area, so any modification needed, the designer can load them to his/her computer, edit, and upload it again. I think this is a common scenario. So, probably I am missing something in my research. Maybe I am focusing in configuring it on the wrong place ... Any thoughts ? | If I understood your question about Struts config files right, they are specified in web.xml. Find the Struts servlet config param. The param-value can be a list of comma separated list of XML files to load. Eg:
```
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
WEB-INF/config/struts-config.xml,
WEB-INF/config/struts-config-stuff.xml,
WEB-INF/config/struts-config-good.xml,
WEB-INF/config/struts-config-bad.xml,
WEB-INF/config/struts-config-ugly.xml
</param-value>
</init-param>
...
</servlet>
```
See this [Struts guide](http://struts.apache.org/1.x/userGuide/configuration.html) under 5.3.2. And yes, this applies to 2.x also. |
35,538 | <p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
| [
{
"answer_id": 35543,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p>XHTML is easy, use <a href=\"http://lxml.de/validation.html\" rel=\"noreferrer\">lxml</a>.</p>\n\n<pre><code>from lxml import etree\nfrom StringIO import StringIO\netree.parse(StringIO(html), etree.HTMLParser(recover=False))\n</code></pre>\n\n<p>HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as <a href=\"http://www.jclark.com/sp/\" rel=\"noreferrer\">nsgmls</a> or <a href=\"http://openjade.sourceforge.net/\" rel=\"noreferrer\">OpenJade</a>, and then parse their output.</p>\n"
},
{
"answer_id": 35562,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 2,
"selected": false,
"text": "<p>I think that <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\">HTML tidy</a> will do what you want. There is a Python binding for it.</p>\n"
},
{
"answer_id": 35572,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 3,
"selected": false,
"text": "<p>Try tidylib. You can get some really basic bindings as part of the elementtidy module (builds elementtrees from HTML documents). <a href=\"http://effbot.org/downloads/#elementtidy\" rel=\"noreferrer\">http://effbot.org/downloads/#elementtidy</a></p>\n\n<pre><code>>>> import _elementtidy\n>>> xhtml, log = _elementtidy.fixup(\"<html></html>\")\n>>> print log\nline 1 column 1 - Warning: missing <!DOCTYPE> declaration\nline 1 column 7 - Warning: discarding unexpected </html>\nline 1 column 14 - Warning: inserting missing 'title' element\n</code></pre>\n\n<p>Parsing the log should give you pretty much everything you need.</p>\n"
},
{
"answer_id": 646877,
"author": "karlcow",
"author_id": 62262,
"author_profile": "https://Stackoverflow.com/users/62262",
"pm_score": 4,
"selected": false,
"text": "<p>You can decide to install the HTML validator locally and create a client to request the validation. </p>\n\n<p>Here I had made a program to validate a list of urls in a txt file. I was just checking the HEAD to get the validation status, but if you do a GET you would get the full results. Look at the API of the validator, there are plenty of options for it.</p>\n\n<pre><code>import httplib2\nimport time\n\nh = httplib2.Http(\".cache\")\n\nf = open(\"urllistfile.txt\", \"r\")\nurllist = f.readlines()\nf.close()\n\nfor url in urllist:\n # wait 10 seconds before the next request - be nice with the validator\n time.sleep(10)\n resp= {}\n url = url.strip()\n urlrequest = \"http://qa-dev.w3.org/wmvs/HEAD/check?doctype=HTML5&uri=\"+url\n try:\n resp, content = h.request(urlrequest, \"HEAD\")\n if resp['x-w3c-validator-status'] == \"Abort\":\n print url, \"FAIL\"\n else:\n print url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings']\n except:\n pass\n</code></pre>\n"
},
{
"answer_id": 1279293,
"author": "Dave Brondsema",
"author_id": 79697,
"author_profile": "https://Stackoverflow.com/users/79697",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://countergram.github.io/pytidylib/\" rel=\"noreferrer\">PyTidyLib</a> is a nice python binding for HTML Tidy. Their example:</p>\n\n<pre><code>from tidylib import tidy_document\ndocument, errors = tidy_document('''<p>f&otilde;o <img src=\"bar.jpg\">''',\n options={'numeric-entities':1})\nprint document\nprint errors\n</code></pre>\n\n<p>Moreover it's compatible with both <a href=\"http://tidy.sourceforge.net/\" rel=\"noreferrer\">legacy HTML Tidy</a> and the <a href=\"http://www.html-tidy.org/\" rel=\"noreferrer\">new tidy-html5</a>.</p>\n"
},
{
"answer_id": 10519634,
"author": "Martin Hepp",
"author_id": 516699,
"author_profile": "https://Stackoverflow.com/users/516699",
"pm_score": 4,
"selected": false,
"text": "<p>I think the most elegant way it to invoke the W3C Validation Service at</p>\n\n<pre><code>http://validator.w3.org/\n</code></pre>\n\n<p>programmatically. Few people know that you do not have to screen-scrape the results in order to get the results, because the service returns non-standard HTTP header paramaters </p>\n\n<pre><code>X-W3C-Validator-Recursion: 1\nX-W3C-Validator-Status: Invalid (or Valid)\nX-W3C-Validator-Errors: 6\nX-W3C-Validator-Warnings: 0\n</code></pre>\n\n<p>for indicating the validity and the number of errors and warnings.</p>\n\n<p>For instance, the command line </p>\n\n<pre><code>curl -I \"http://validator.w3.org/check?uri=http%3A%2F%2Fwww.stalsoft.com\"\n</code></pre>\n\n<p>returns</p>\n\n<pre><code>HTTP/1.1 200 OK\nDate: Wed, 09 May 2012 15:23:58 GMT\nServer: Apache/2.2.9 (Debian) mod_python/3.3.1 Python/2.5.2\nContent-Language: en\nX-W3C-Validator-Recursion: 1\nX-W3C-Validator-Status: Invalid\nX-W3C-Validator-Errors: 6\nX-W3C-Validator-Warnings: 0\nContent-Type: text/html; charset=UTF-8\nVary: Accept-Encoding\nConnection: close\n</code></pre>\n\n<p>Thus, you can elegantly invoke the W3C Validation Service and extract the results from the HTTP header:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code># Programmatic XHTML Validations in Python\n# Martin Hepp and Alex Stolz\n# [email protected] / [email protected]\n\nimport urllib\nimport urllib2\n\nURL = \"http://validator.w3.org/check?uri=%s\"\nSITE_URL = \"http://www.heppnetz.de\"\n\n# pattern for HEAD request taken from \n# http://stackoverflow.com/questions/4421170/python-head-request-with-urllib2\n\nrequest = urllib2.Request(URL % urllib.quote(SITE_URL))\nrequest.get_method = lambda : 'HEAD'\nresponse = urllib2.urlopen(request)\n\nvalid = response.info().getheader('X-W3C-Validator-Status')\nif valid == \"Valid\":\n valid = True\nelse:\n valid = False\nerrors = int(response.info().getheader('X-W3C-Validator-Errors'))\nwarnings = int(response.info().getheader('X-W3C-Validator-Warnings'))\n\nprint \"Valid markup: %s (Errors: %i, Warnings: %i) \" % (valid, errors, warnings)\n</code></pre>\n"
},
{
"answer_id": 39336630,
"author": "user9869932",
"author_id": 1183098,
"author_profile": "https://Stackoverflow.com/users/1183098",
"pm_score": 2,
"selected": false,
"text": "<p>In my case the python W3C/HTML cli validation packages did not work (as of sept 2016).</p>\n<p>I did it manually using <code>requests</code> like so</p>\n<p>code:</p>\n<pre><code>r = requests.post('https://validator.w3.org/nu/', \n data=open('FILE.html','rb').read(), params={'out': 'json'}, \n headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36', \n 'Content-Type': 'text/html; charset=UTF-8'})\n\nprint r.json()\n</code></pre>\n<p>in the console:</p>\n<pre><code>$ echo '<!doctype html><html lang=en><head><title>blah</title></head><body></body></html>' | tee FILE.html \n$ pip install requests\n\n$ python\nPython 2.7.12 (default, Jun 29 2016, 12:46:54)\n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin\nType "help", "copyright", "credits" or "license" for more information.\n\n>>> import requests\n\n>>> r = requests.post('https://validator.w3.org/nu/', \n... data=open('FILE.html', 'rb').read(), \n... params={'out': 'json'}, \n... headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36', \n... 'Content-Type': 'text/html; charset=UTF-8'})\n\n>>> r.text\n>>> u'{"messages":[]}\\n'\n\n>>> r.json()\n>>> {u'messages': []}\n</code></pre>\n<p>More documentation here <a href=\"http://docs.python-requests.org/en/master/user/quickstart/#binary-response-content\" rel=\"nofollow noreferrer\">python requests</a>, <a href=\"https://github.com/validator/validator/wiki/Service:-Input:-POST-body\" rel=\"nofollow noreferrer\">W3C Validator API</a></p>\n"
},
{
"answer_id": 40229004,
"author": "speedplane",
"author_id": 234270,
"author_profile": "https://Stackoverflow.com/users/234270",
"pm_score": 2,
"selected": false,
"text": "<p>This is a very basic html validator based on lxml's HTMLParser. It is not a complete html validator, but does a few basic checks, doesn't require any internet connection, and doesn't require a large library.</p>\n\n<pre><code>_html_parser = None\ndef validate_html(html):\n global _html_parser\n from lxml import etree\n from StringIO import StringIO\n if not _html_parser:\n _html_parser = etree.HTMLParser(recover = False)\n return etree.parse(StringIO(html), _html_parser)\n</code></pre>\n\n<p>Note that this will not check for closing tags, so for example, the following will pass:</p>\n\n<pre><code>validate_html(\"<a href='example.com'>foo\")\n> <lxml.etree._ElementTree at 0xb2fd888>\n</code></pre>\n\n<p>However, the following wont:</p>\n\n<pre><code>validate_html(\"<a href='example.com'>foo</a\")\n> XMLSyntaxError: End tag : expected '>', line 1, column 29\n</code></pre>\n"
},
{
"answer_id": 60886392,
"author": "Changaco",
"author_id": 2729778,
"author_profile": "https://Stackoverflow.com/users/2729778",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"https://pypi.org/project/html5lib/\" rel=\"noreferrer\">html5lib</a> module can be used to validate an HTML5 document:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> import html5lib\n>>> html5parser = html5lib.HTMLParser(strict=True)\n>>> html5parser.parse('<html></html>')\nTraceback (most recent call last):\n ...\nhtml5lib.html5parser.ParseError: Unexpected start tag (html). Expected DOCTYPE.\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | XHTML is easy, use [lxml](http://lxml.de/validation.html).
```
from lxml import etree
from StringIO import StringIO
etree.parse(StringIO(html), etree.HTMLParser(recover=False))
```
HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as [nsgmls](http://www.jclark.com/sp/) or [OpenJade](http://openjade.sourceforge.net/), and then parse their output. |
35,548 | <p>I use this tool called <a href="http://www.lazycplusplus.com/" rel="nofollow noreferrer">Lazy C++</a> which breaks a single C++ .lzz file into a .h and .cpp file. I want <a href="http://makepp.sourceforge.net/" rel="nofollow noreferrer">Makepp</a> to expect both of these files to exist after my rule for building .lzz files, but I'm not sure how to put two targets into a single build line.</p>
| [
{
"answer_id": 35592,
"author": "Tynan",
"author_id": 3548,
"author_profile": "https://Stackoverflow.com/users/3548",
"pm_score": 3,
"selected": true,
"text": "<p>I've never used Makepp personally, but since it's a drop-in replacement for GNU Make, you should be able to do something like:</p>\n\n<pre><code>build: foo.h foo.cpp\n g++ $(CFLAGS) foo.cpp -o $(LFLAGS) foo\n\nfoo.h foo.cpp: foo.lzz\n lzz foo.lzz\n</code></pre>\n\n<p>Also not sure about the lzz invocation there, but that should help. You can read more about this at <a href=\"http://theory.uwinnipeg.ca/gnu/make/make_37.html\" rel=\"nofollow noreferrer\">http://theory.uwinnipeg.ca/gnu/make/make_37.html</a>.</p>\n"
},
{
"answer_id": 2717514,
"author": "Daniel",
"author_id": 326407,
"author_profile": "https://Stackoverflow.com/users/326407",
"pm_score": 2,
"selected": false,
"text": "<p>Lzz is amazing! This is just what I was looking for <a href=\"http://groups.google.com/group/comp.lang.c++/browse_thread/thread/c50de73b70a6a957/f3f47fcdcfb6bc09\" rel=\"nofollow noreferrer\">http://groups.google.com/group/comp.lang.c++/browse_thread/thread/c50de73b70a6a957/f3f47fcdcfb6bc09</a></p>\n\n<p>Actually all you need is to depend (typically) on foo.o in your link rule, and a pattern rule to call lzz:</p>\n\n<pre><code>%.cpp %.h: %.lzz\n lzz $(input)\n</code></pre>\n\n<p>The rest will fall into place automatically. When compiling any source that includes foo.h, or linking foo.o to a library or program, lzz will first get called automatically.</p>\n\n<p>Makepp will also recognize if only the timestamp but not the content of the produced file changed, and ignore that. But it can't hurt to give it less to do, by using the lzz options to suppress recreating an identical file.</p>\n\n<p>Regards -- Daniel</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | I use this tool called [Lazy C++](http://www.lazycplusplus.com/) which breaks a single C++ .lzz file into a .h and .cpp file. I want [Makepp](http://makepp.sourceforge.net/) to expect both of these files to exist after my rule for building .lzz files, but I'm not sure how to put two targets into a single build line. | I've never used Makepp personally, but since it's a drop-in replacement for GNU Make, you should be able to do something like:
```
build: foo.h foo.cpp
g++ $(CFLAGS) foo.cpp -o $(LFLAGS) foo
foo.h foo.cpp: foo.lzz
lzz foo.lzz
```
Also not sure about the lzz invocation there, but that should help. You can read more about this at <http://theory.uwinnipeg.ca/gnu/make/make_37.html>. |
35,551 | <p>In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels.</p>
<p>I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work.</p>
<p>This is the attribute that FxCop copied to the clipboard.</p>
<pre><code>[module: SuppressMessage("Microsoft.Globalization",
"CA1303:DoNotPassLiteralsAsLocalizedParameters",
Scope = "member",
Target = "WindowsClient.MainForm.InitializeComponent():System.Void",
MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
</code></pre>
<p>Anyone knows the correct attribute to suppress this messages?</p>
<p>PS: I'm using Visual Studio 2005, C#, FxCop 1.36 beta.</p>
| [
{
"answer_id": 35556,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>You've probably got the right code, but you also need to add CODE_ANALYSIS as a precompiler defined symbol in the project properties. I think those SuppressMessage attributes are only left in the compiled binaries if CODE_ANALYSIS is defined.</p>\n"
},
{
"answer_id": 35570,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "<p>Module level suppression messages need to be pasted into the same file as the code that is raising the FxCop error before the namespace declaration or in assemblyinfo.cs. Additionally, you will need to have CODE_ANALYSIS defined as a conditional compiler symbols (Project > Properties > Build). Once that is in place, do a complete rebuild of project and the next time you run FxCop the error should be moved to the \"Excluded in Source\" tab.</p>\n\n<p>Also, one small tip, but if you are dealing with a lot of FxCop exclusions it might be useful to wrap a region around them so you can get them out of the way.</p>\n"
},
{
"answer_id": 35575,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>In FxCop 1.36 there is actually a project option on the \"Spelling & Analysis\" tab that will supress analysis for any generated code.</p>\n\n<p>If you don't want to turn analysis off for all generated code, you need to make sure that you add a CODE_ANALYSIS symbol to the list of conditional compilation symbols (project properties, Build tab). Without this symbol defined, the SupressMessage attributes will be removed from the compiled code so FxCop won't see them.</p>\n\n<p>The other problem with your SuppressMessage attribute is that you are listing a \"Target\" of a specific method name (in this case WindowsClient.MainForm.InitializeComponent():System.Void) and listing a specific \"Scope\". You may want to try removing these; otherwise you should add this SuppressMessage to each instance of the method.</p>\n\n<p>You should also upgrade to the <a href=\"http://davesbox.com/archive/2008/08/17/fxcop-1-36-released.aspx\" rel=\"nofollow noreferrer\">RTM version</a> of FxCop 1.36, the beta will not automatically detect the newer version. </p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
] | In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels.
I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work.
This is the attribute that FxCop copied to the clipboard.
```
[module: SuppressMessage("Microsoft.Globalization",
"CA1303:DoNotPassLiteralsAsLocalizedParameters",
Scope = "member",
Target = "WindowsClient.MainForm.InitializeComponent():System.Void",
MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
```
Anyone knows the correct attribute to suppress this messages?
PS: I'm using Visual Studio 2005, C#, FxCop 1.36 beta. | You've probably got the right code, but you also need to add CODE\_ANALYSIS as a precompiler defined symbol in the project properties. I think those SuppressMessage attributes are only left in the compiled binaries if CODE\_ANALYSIS is defined. |
35,699 | <p>I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content. </p>
<p>Here's a paired down example of my template to illustrate the problem.</p>
<pre><code><div style="float:left; width: 150px; border: 1px solid;">
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
<li>nav4</li>
</ul>
</div>
<div style="float:left; width: 250px">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
....
</div>
</code></pre>
| [
{
"answer_id": 35711,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 3,
"selected": false,
"text": "<p>Your simplest answer lies in the next version of css (3), which currently no browser supports.</p>\n\n<p>For now you are relegated to calculating heights in javascript and setting them on the left side. </p>\n\n<p>If the navigation is so important to be positioned in such a way, run it along the top.</p>\n\n<p>you could also do a visual trick by moving the borders to the container and the bigger inner, and make it appear to be the same size.</p>\n\n<p>this makes it look the same, but it isn't.</p>\n\n<pre><code><div style=\"border-left:solid 1px black;border-bottom:solid 1px black;\">\n <div style=\"float:left; width: 150px; border-top: 1px solid;\">\n <ul>\n <li>nav1</li>\n <li>nav2</li>\n <li>nav3</li>\n <li>nav4</li>\n </ul>\n </div>\n <div style=\"float:left; width: 250px; border:solid 1px black;border-bottom:0;\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n sed do eiusmod tempor incididunt ut labore et dolore magna\n Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n ...\n </div>\n <div style=\"clear:both;\" ></div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 35718,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>@hoyhoy</p>\n\n<p>If a designer can make this work in html, then he can have this design. If he is a true master of web design, he will realize that this is a limitation of the media, as video is not possible in magazine ads.</p>\n\n<p>If he would like to simulate weight by giving the 2 columns equal importance, than change the borders, so that they appear to be of the same weight, and make the colors of the borders contrast to the font color of the columns. </p>\n\n<p>But as for making the physical elements the same height, you can only do that with a table construct, or setting the heights, at this point in time. To simulate them appearing the same size, they don't have to be the same size.</p>\n"
},
{
"answer_id": 35880,
"author": "Silviu Postavaru",
"author_id": 3718,
"author_profile": "https://Stackoverflow.com/users/3718",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it in jQuery really simple, but I am not sure JS should be used for such things. The best way is to do it with pure css.</p>\n\n<ol>\n<li><p>Take a look at <a href=\"http://www.alistapart.com/articles/fauxcolumns/\" rel=\"nofollow noreferrer\">faux columns</a> or even <a href=\"http://www.communitymx.com/content/article.cfm?cid=AFC58\" rel=\"nofollow noreferrer\">Fluid Faux Columns</a></p></li>\n<li><p>Also another technique(doesn't work on the beautiful IE6) is to position:relative the parent container. The child container(the nav list in your case) should be positioned absolute and forced to occupy the whole space with 'top:0; bottom:0;'</p></li>\n</ol>\n"
},
{
"answer_id": 47403,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 2,
"selected": false,
"text": "<p>This is one of those perfectly reasonable, simple things that CSS can't do. Faux Columns, as suggested by Silviu, is a hacky but functional workaround.\nIt would be lovely if someday there was a way to say</p>\n\n<pre>\ndiv.foo {\nheight: $(div.blah.height);\n}\n</pre>\n"
},
{
"answer_id": 53010,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 3,
"selected": false,
"text": "<p>It can be done in CSS! Don't let people tell you otherwise.</p>\n\n<p>The easiest, most pain-free way to do it is to use the <a href=\"http://www.alistapart.com/articles/fauxcolumns/\" rel=\"noreferrer\">Faux Columns</a> method.</p>\n\n<p>However, if that solution doesn't work for you, you'll want to read up on <a href=\"http://www.positioniseverything.net/articles/onetruelayout/equalheight\" rel=\"noreferrer\">this technique</a>. But be warned, this is the kind of CSS hackery that will make you wake up in a cold sweat in the middle of the night.</p>\n\n<p>The gist of it is that you assign a large amount of padding to the bottom of the column, and a negative margin of the same size. Then you place your columns in a container that has <code>overflow: hidden</code> set. More or less the padding/margin values allow the box to keep expanding until it reaches the end of the wrapper (which is determined by the column with the most content), and any extra space generated by the padding is cut off as overflow. It doesn't make much sense, I know...</p>\n\n<pre><code><div id=\"wrapper\">\n <div id=\"col1\">Content</div>\n <div id=\"col2\">Longer Content</div>\n</div>\n\n#wrapper {\n overflow: hidden;\n}\n\n#col1, #col2 {\n padding-bottom: 9999px;\n margin-bottom: -9999px;\n}\n</code></pre>\n\n<p>Be sure to read the entire article I linked to, there are a number of caveats and other implementation issues. It's not a pretty technique, but it works fairly well.</p>\n"
},
{
"answer_id": 54779,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 0,
"selected": false,
"text": "<p>Come to think of it, I've never done it with a bottom border on the column. It's probably just overflowing, and getting cut off. You might want to have the bottom border come from a separate element that's part of the column content.</p>\n\n<p>Anyway, I know it's not a perfect magic bullet solution. You might just have to play with it, or hack around its shortcomings.</p>\n"
},
{
"answer_id": 396336,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This <strong>can</strong> be done with css using background colors</p>\n\n<pre><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>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>Untitled Document</title>\n<style type=\"text/css\">\n* {\n margin: 0;\n padding: 0;\n}\nbody {\n font-family: Arial, Helvetica, sans-serif;\n background: #87ceeb;\n font-size: 1.2em;\n}\n#container {\n width:100%; /* any width including 100% will work */\n color: inherit;\n margin:0 auto; /* remove if 100% width */\n background:#FFF;\n}\n#header {\n width: 100%;\n height: 160px;\n background: #1e90ff;\n}\n#content {/* use for left sidebar, menu etc. */\n background: #99C;\n color: #000;\n float: right;/* float left for right sidebar */\n margin: 0 0 0 -200px; /* adjust margin if borders added */\n width: 100%;\n }\n#content .wrapper {\n background: #FFF;\n margin: 0 0 0 200px;\n overflow: hidden;\n padding: 10px; /* optional, feel free to remove */\n}\n#sidebar {\n background: #99C;\n color: inherit;\n float: left;\n width: 180px;\n padding: 10px;\n}\n.clearer {\n height: 1px;\n font-size: -1px;\n clear: both;\n}\n\n/* content styles */\n#header h1 {\n padding: 0 0 0 5px;\n}\n#menu p {\n font-size: 1em;\n font-weight: bold;\n padding: 5px 0 5px 5px;\n}\n#footer {\n clear: both;\n border-top: 1px solid #1e90ff; \n border-bottom: 10px solid #1e90ff;\n text-align: center;\n font-size: 50%;\n font-weight: bold;\n}\n#footer p {\n padding: 10px 0;\n} \n</style>\n</head>\n\n<body>\n\n\n<div id=\"container\">\n<!--header and menu content goes here -->\n\n<div id=\"header\">\n<h1>Header Goes Here</h1>\n</div>\n<div id=\"content\">\n<div class=\"wrapper\">\n<!--main page content goes here -->\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc \n\nvitae purus. Aenean viverra malesuada libero. </p>\n</div>\n</div>\n\n<div id=\"sidebar\">\n<!--sidebar content, menu goes here -->\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus.</p>\n</div>\n\n<div class=\"clearer\"></div><!--clears footer from content-->\n<!--footer content goes here -->\n<div id=\"footer\">\n<p>Footer Info Here</p>\n</div>\n</div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 396350,
"author": "Burak Erdem",
"author_id": 49380,
"author_profile": "https://Stackoverflow.com/users/49380",
"pm_score": 0,
"selected": false,
"text": "<p>There is also a Javascript based solution. If you have jQuery, you can use the below plugin.</p>\n\n<pre><code><script type=\"text/javascript\">\n// plugin\njQuery.fn.equalHeights=function() {\n var maxHeight=0;\n\n this.each(function(){\n if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}\n });\n\n this.each(function(){\n $(this).height(maxHeight + \"px\");\n if (this.offsetHeight>maxHeight) {\n $(this).height((maxHeight-(this.offsetHeight-maxHeight))+\"px\");\n }\n });\n};\n\n// usage\n$(function() {\n $('.column1, .column2, .column3').equalHeights();\n});\n</script>\n</code></pre>\n"
},
{
"answer_id": 594021,
"author": "Stiropor",
"author_id": 67325,
"author_profile": "https://Stackoverflow.com/users/67325",
"pm_score": 0,
"selected": false,
"text": "<p>I use this to align 2 columns with ID \"center\" and \"right\":</p>\n\n<pre><code>var c = $(\"#center\");\nvar cp = parseInt(c.css(\"padding-top\"), 10) + parseInt(c.css(\"padding-bottom\"), 10) + parseInt(c.css(\"borderTopWidth\"), 10) + parseInt(c.css(\"borderBottomWidth\"), 10);\nvar r = $(\"#right\");\nvar rp = parseInt(r.css(\"padding-top\"), 10) + parseInt(r.css(\"padding-bottom\"), 10) + parseInt(r.css(\"borderTopWidth\"), 10) + parseInt(r.css(\"borderBottomWidth\"), 10);\n\nif (c.outerHeight() < r.outerHeight()) {\n c.height(r.height () + rp - cp);\n} else {\n r.height(c.height () + cp - rp);\n}\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 1842279,
"author": "cutcliffe",
"author_id": 224182,
"author_profile": "https://Stackoverflow.com/users/224182",
"pm_score": 3,
"selected": true,
"text": "<p>Use jQuery for this problem; just call this function in your ready function:</p>\n\n<pre><code>function setHeight(){\n var height = $(document).height(); //optionally, subtract some from the height\n $(\"#leftDiv\").css(\"height\", height + \"px\");\n}\n</code></pre>\n"
},
{
"answer_id": 22628960,
"author": "Chandrakant Manekar",
"author_id": 3454979,
"author_profile": "https://Stackoverflow.com/users/3454979",
"pm_score": 0,
"selected": false,
"text": "<p>To grow the <strong><em>left menu div</em></strong> with same height as the right content div.</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title>Untitled Document</title>\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\">\n</script>\n<script>\n $(document).ready(function () {\n var height = $(document).height(); //optionally, subtract some from the height\n $(\"#menu\").css(\"height\", (height) + \"px\");\n $(\"#content\").css(\"height\", (height) + \"px\");\n });\n</script>\n<style type=\"text/css\">\n <!--\n\n html, body {\n font-family: Arial;\n font-size: 12px;\n }\n\n\n #header {\n background-color: #F9C;\n height: 200px;\n width: 100%;\n float: left;\n position: relative;\n }\n\n #menu {\n background-color: #6CF;\n float: left;\n min-height: 100%;\n height: auto;\n width: 10%;\n position: relative;\n }\n\n #content {\n background-color: #6f6;\n float: right;\n height: auto;\n width: 90%;\n position: relative;\n }\n\n #footer {\n background-color: #996;\n float: left;\n height: 100px;\n width: 100%;\n position: relative;\n }\n -->\n</style>\n</head>\n\n\n<body>\n<div id=\"header\">\n i am a header\n</div>\n<div id=\"menu\">\n i am a menu\n</div>\n<div id=\"content\">\n I am an example of how to do layout with css rules and divs.\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n\n</div>\n<div id=\"footer\">\n footer\n</div>\n\n\n</body>\n</html>\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] | I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content.
Here's a paired down example of my template to illustrate the problem.
```
<div style="float:left; width: 150px; border: 1px solid;">
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
<li>nav4</li>
</ul>
</div>
<div style="float:left; width: 250px">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
....
</div>
``` | Use jQuery for this problem; just call this function in your ready function:
```
function setHeight(){
var height = $(document).height(); //optionally, subtract some from the height
$("#leftDiv").css("height", height + "px");
}
``` |
35,743 | <p>According to <a href="http://msdn.microsoft.com/en-us/library/bb386454.aspx" rel="noreferrer">Microsoft</a> the FileUpload control is not compatible with an AJAX UpdatePanel. </p>
<p>I am aware that a PostBackTrigger can be added to the submit button of the form like this:</p>
<pre><code><Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</code></pre>
<p>The problem is that this forces the form to perform a full post-back which voids out the whole point of using the UpdatePanel in the first place. Is there a workaround to this issue that does not cause the whole page to refresh?</p>
| [
{
"answer_id": 35754,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 3,
"selected": false,
"text": "<p>I know of a third party component that can do that. It's called <a href=\"http://swfupload.org/\" rel=\"noreferrer\">\"<em>swfupload</em>\"</a> and is free to use and open source, and uses javascript and flash to do the magic.</p>\n\n<p>here is a list of the features they offer:\n(from their site)</p>\n\n<blockquote>\n <ul>\n <li>Upload multiple files at once by ctrl/shift-selecting in dialog</li>\n <li>Javascript callbacks on all events</li>\n <li>Get file information before upload starts</li>\n <li>Style upload elements with XHTML and css</li>\n <li>Display information while files are uploading using HTML</li>\n <li>No page reloads necessary</li>\n <li>Works on all platforms/browsers that has Flash support.</li>\n <li>Degrades gracefully to normal HTML upload form if Flash or javascript is\n unavailable</li>\n <li>Control filesize before upload starts</li>\n <li>Only display chosen filetypes in dialog</li>\n <li>Queue uploads, remove/add files before starting upload</li>\n </ul>\n</blockquote>\n\n<p>They also have a <a href=\"http://www.swfupload.org/documentation/demonstration\" rel=\"noreferrer\">demo area</a> where you can play around with their control. That way you can make sure it is exactly what you want.</p>\n\n<p>We used it in one of our projects and it has never failed us so far, so I think this is a safe bet.</p>\n\n<p>oh and here is the download page: <a href=\"http://code.google.com/p/swfupload/\" rel=\"noreferrer\">http://code.google.com/p/swfupload/</a></p>\n"
},
{
"answer_id": 36859,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 2,
"selected": false,
"text": "<p>You can't upload file(s) via <code>AJAX</code> only by reloading a whole <code>HTML</code> document. You should either use <code>iframe</code>s if you prefer pure HTML (this is more common, eg. used by WordPress) or something else like swfupload suggested by Sven.</p>\n"
},
{
"answer_id": 74904,
"author": "weffey",
"author_id": 13208,
"author_profile": "https://Stackoverflow.com/users/13208",
"pm_score": 1,
"selected": false,
"text": "<p>I found this the other day when I ran into the same problem: <a href=\"http://vinayakshrestha.wordpress.com/2007/03/13/uploading-files-using-aspnet-ajax-extensions/\" rel=\"nofollow noreferrer\">http://vinayakshrestha.wordpress.com/2007/03/13/uploading-files-using-aspnet-ajax-extensions/</a>.</p>\n\n<p>For my implementation, I put the iframe in a modal popup and added a button with style=\"display:none\" to handle the closing of the popup. In the javascript function that watches for the change in the iframe, I added document.getElementById(\"<%=btnCloseUpload.ClientID%>\").click(); for the hidden button.</p>\n"
},
{
"answer_id": 217722,
"author": "user10859",
"author_id": 10859,
"author_profile": "https://Stackoverflow.com/users/10859",
"pm_score": 2,
"selected": false,
"text": "<p>Add this to your button control:</p>\n\n<pre><code>OnClientClick=\"javascript:document.forms[0].encoding = 'multipart/form-data';\"\n</code></pre>\n\n<p>-or- </p>\n\n<p>Make your page Form tag look like:</p>\n\n<pre><code><form id=\"form1\" runat=\"server\" enctype=\"multipart/form-data\">\n</code></pre>\n"
},
{
"answer_id": 2222808,
"author": "David Neale",
"author_id": 234645,
"author_profile": "https://Stackoverflow.com/users/234645",
"pm_score": 1,
"selected": false,
"text": "<p>Try the AJAX AsyncFileUpload. It works well if used in the matter it is intended to be used (handle the UploadedComplete event).</p>\n\n<p><a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AsyncFileUpload/AsyncFileUpload.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AsyncFileUpload/AsyncFileUpload.aspx</a></p>\n"
},
{
"answer_id": 9537496,
"author": "Houston77mr",
"author_id": 1245623,
"author_profile": "https://Stackoverflow.com/users/1245623",
"pm_score": -1,
"selected": false,
"text": "<p>The button that is triggering the upload event needs to have <code>UseSubmitBehavior</code> property set to false:</p>\n\n<pre><code>clsUploadButton.UseSubmitBehavior = False;\n</code></pre>\n"
},
{
"answer_id": 18716442,
"author": "Harry Sarshogh",
"author_id": 2031820,
"author_profile": "https://Stackoverflow.com/users/2031820",
"pm_score": 0,
"selected": false,
"text": "<p>Can use IFrame have \"target\" attribute which mention to FileUpload Page OR use Jquery example at link\n<a href=\"https://stackoverflow.com/questions/2909442/how-to-make-asynchronousajax-file-upload-using-iframe\">How to make Asynchronous(AJAX) File Upload using iframe?</a></p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677/"
] | According to [Microsoft](http://msdn.microsoft.com/en-us/library/bb386454.aspx) the FileUpload control is not compatible with an AJAX UpdatePanel.
I am aware that a PostBackTrigger can be added to the submit button of the form like this:
```
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
```
The problem is that this forces the form to perform a full post-back which voids out the whole point of using the UpdatePanel in the first place. Is there a workaround to this issue that does not cause the whole page to refresh? | I know of a third party component that can do that. It's called ["*swfupload*"](http://swfupload.org/) and is free to use and open source, and uses javascript and flash to do the magic.
here is a list of the features they offer:
(from their site)
>
> * Upload multiple files at once by ctrl/shift-selecting in dialog
> * Javascript callbacks on all events
> * Get file information before upload starts
> * Style upload elements with XHTML and css
> * Display information while files are uploading using HTML
> * No page reloads necessary
> * Works on all platforms/browsers that has Flash support.
> * Degrades gracefully to normal HTML upload form if Flash or javascript is
> unavailable
> * Control filesize before upload starts
> * Only display chosen filetypes in dialog
> * Queue uploads, remove/add files before starting upload
>
>
>
They also have a [demo area](http://www.swfupload.org/documentation/demonstration) where you can play around with their control. That way you can make sure it is exactly what you want.
We used it in one of our projects and it has never failed us so far, so I think this is a safe bet.
oh and here is the download page: <http://code.google.com/p/swfupload/> |
35,782 | <p>I need to produce a calculation trace file containing tabular data showing intermediate results. I am currently using a combination of the standard ascii pipe symbols (|) and dashes (-) to draw the table lines:</p>
<p>E.g. </p>
<pre><code>Numerator | Denominator | Result
----------|-------------|-------
6 | 2 | 3
10 | 5 | 2
</code></pre>
<p>Are there any unicode characters that could be used to produce a more professional looking table?</p>
<p>(The file must be a raw text format and cannot use HTML or any other markup)</p>
<p><strong>Edit:</strong> I've added an example of what the table now looks like having taken the suggestion on board and used the unicode box drawing characters:</p>
<pre><code>Numerator │ Denominator │ Result
──────────┼─────────────┼───────
6 │ 2 │ 3
10 │ 5 │ 2
</code></pre>
| [
{
"answer_id": 35784,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "<p>There are <a href=\"http://www.unicode.org/charts/symbols.html\" rel=\"nofollow noreferrer\">Unicode box drawing characters</a> (look for Box Drawing under Geometrical Symbols - the <a href=\"http://www.unicode.org/charts/PDF/U2500.pdf\" rel=\"nofollow noreferrer\">chart itself</a> is a PDF). I don't have any idea how widely supported those characters are, though.</p>\n"
},
{
"answer_id": 61394278,
"author": "Keith Thomas",
"author_id": 12898396,
"author_profile": "https://Stackoverflow.com/users/12898396",
"pm_score": 1,
"selected": false,
"text": "<p>Your table is getting help from the monospaced font triggered by the code tags here. Proportional fonts can prevent tabular alignment of the digits. Unicode has digits that retain tabular alignment regardless of fonts in the Mathematical Alphanumeric Symbols from 1D7CE-1D7FF like these 𝟶𝟷𝟸𝟹𝟺𝟻𝟼𝟽𝟾𝟿\n&#x1D7F6 &#x1D7F7 &#x1D7F8 &#x1D7F9 &#x1D7FA &#x1D7FB &#x1D7FC &#x1D7FD &#x1D7FE &#x1D7FF</p>\n"
},
{
"answer_id": 61968123,
"author": "kliop",
"author_id": 13600794,
"author_profile": "https://Stackoverflow.com/users/13600794",
"pm_score": 0,
"selected": false,
"text": "<p>You should look at this <a href=\"https://marklodato.github.io/js-boxdrawing/\" rel=\"nofollow noreferrer\"><strong>Javascript Box Drawing Demo</strong></a>. This is a JavaScript Unicode box drawing tool whose purpose is to make it easy for users to draw <strong>Unicode box art in HTML textareas</strong>. There you will see how to draw boxes using the arrow keys.</p>\n\n<ul>\n<li><p>First you should select a style other than \"<strong>Off</strong>\". </p></li>\n<li><p>Then using the <strong>arrow keys</strong> move around and you will see the box being drawn as you type</p></li>\n<li><p>Once you are satisfied with the look of your drawing, simply copy it from the box and paste it on your HTML code.</p></li>\n</ul>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131/"
] | I need to produce a calculation trace file containing tabular data showing intermediate results. I am currently using a combination of the standard ascii pipe symbols (|) and dashes (-) to draw the table lines:
E.g.
```
Numerator | Denominator | Result
----------|-------------|-------
6 | 2 | 3
10 | 5 | 2
```
Are there any unicode characters that could be used to produce a more professional looking table?
(The file must be a raw text format and cannot use HTML or any other markup)
**Edit:** I've added an example of what the table now looks like having taken the suggestion on board and used the unicode box drawing characters:
```
Numerator │ Denominator │ Result
──────────┼─────────────┼───────
6 │ 2 │ 3
10 │ 5 │ 2
``` | There are [Unicode box drawing characters](http://www.unicode.org/charts/symbols.html) (look for Box Drawing under Geometrical Symbols - the [chart itself](http://www.unicode.org/charts/PDF/U2500.pdf) is a PDF). I don't have any idea how widely supported those characters are, though. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.