qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
171,529 |
<p>I have this Task model:</p>
<pre><code>class Task < ActiveRecord::Base
acts_as_tree :order => 'sort_order'
end
</code></pre>
<p>And I have this test</p>
<pre><code>class TaskTest < Test::Unit::TestCase
def setup
@root = create_root
end
def test_destroying_a_task_should_destroy_all_of_its_descendants
d1 = create_task(:parent_id => @root.id, :sort_order => 2)
d2 = create_task(:parent_id => d1.id, :sort_order => 3)
d3 = create_task(:parent_id => d2.id, :sort_order => 4)
d4 = create_task(:parent_id => d1.id, :sort_order => 5)
assert_equal 5, Task.count
d1.destroy
assert_equal @root, Task.find(:first)
assert_equal 1, Task.count
end
end
</code></pre>
<p>The test is successful: when I destroy d1, it destroys all the descendants of d1. Thus, after the destroy only the root is left.</p>
<p>However, this test is now failing after I have added a before_save callback to the Task. This is the code I added to Task:</p>
<pre><code>before_save :update_descendants_if_necessary
def update_descendants_if_necessary
handle_parent_id_change if self.parent_id_changed?
return true
end
def handle_parent_id_change
self.children.each do |sub_task|
#the code within the loop is deliberately commented out
end
end
</code></pre>
<p>When I added this code, <code>assert_equal 1, Task.count</code> fails, with <code>Task.count == 4</code>. I think <code>self.children</code> under <code>handled_parent_id_change</code> is the culprit, because when I comment out the <code>self.children.each do |sub_task|</code> block, the test passes again.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 172553,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p><code>children</code> <a href=\"http://github.com/rails/acts_as_tree/tree/master/lib/active_record/acts/tree.rb#L47\" rel=\"nofollow noreferrer\">is a simple has_many association</a></p>\n\n<p>This means, when you call <code>.children</code>, it will load them from the database (if not already present). It will then cache them.</p>\n\n<p>I was going to say that your second 'test' will actually be looking at the cached values not the real database, but that shouldn't happen as you are just using <code>Task.count</code> rather than <code>d1.children.count</code>. Hrm</p>\n\n<p>Have you looked at the logs? They will show you the SQL which is being executed. You may see a mysql error in there which will tell you what's going on</p>\n"
},
{
"answer_id": 173169,
"author": "gsmendoza",
"author_id": 11082,
"author_profile": "https://Stackoverflow.com/users/11082",
"pm_score": 3,
"selected": true,
"text": "<p>I found the bug. The line</p>\n\n<pre><code>d1 = create_task(:parent_id => @root.id, :sort_order => 2)\n</code></pre>\n\n<p>creates d1. This calls the <code>before_save</code> callback, which in turn calls <code>self.children</code>. As Orion pointed out, this caches the children of d1.</p>\n\n<p>However, at this point, d1 doesn't have any children yet. So d1's cache of children is empty.</p>\n\n<p>Thus, when I try to destroy d1, the program tries to destroy d1's children. It encounters the cache, finds that it is empty, and a result doesn't destroy d2, d3, and d4.</p>\n\n<p>I solved this by changing the task creations like this:</p>\n\n<pre><code>@root.children << (d1 = new_task(:sort_order => 2))\[email protected]!\n</code></pre>\n\n<p>This worked so I'm ok with it :) I think it is also possible to fix this by either reloading d1 (<code>d1.reload</code>) or self.children (<code>self.children(true)</code>) although I didn't try any of these solutions.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082/"
] |
I have this Task model:
```
class Task < ActiveRecord::Base
acts_as_tree :order => 'sort_order'
end
```
And I have this test
```
class TaskTest < Test::Unit::TestCase
def setup
@root = create_root
end
def test_destroying_a_task_should_destroy_all_of_its_descendants
d1 = create_task(:parent_id => @root.id, :sort_order => 2)
d2 = create_task(:parent_id => d1.id, :sort_order => 3)
d3 = create_task(:parent_id => d2.id, :sort_order => 4)
d4 = create_task(:parent_id => d1.id, :sort_order => 5)
assert_equal 5, Task.count
d1.destroy
assert_equal @root, Task.find(:first)
assert_equal 1, Task.count
end
end
```
The test is successful: when I destroy d1, it destroys all the descendants of d1. Thus, after the destroy only the root is left.
However, this test is now failing after I have added a before\_save callback to the Task. This is the code I added to Task:
```
before_save :update_descendants_if_necessary
def update_descendants_if_necessary
handle_parent_id_change if self.parent_id_changed?
return true
end
def handle_parent_id_change
self.children.each do |sub_task|
#the code within the loop is deliberately commented out
end
end
```
When I added this code, `assert_equal 1, Task.count` fails, with `Task.count == 4`. I think `self.children` under `handled_parent_id_change` is the culprit, because when I comment out the `self.children.each do |sub_task|` block, the test passes again.
Any ideas?
|
I found the bug. The line
```
d1 = create_task(:parent_id => @root.id, :sort_order => 2)
```
creates d1. This calls the `before_save` callback, which in turn calls `self.children`. As Orion pointed out, this caches the children of d1.
However, at this point, d1 doesn't have any children yet. So d1's cache of children is empty.
Thus, when I try to destroy d1, the program tries to destroy d1's children. It encounters the cache, finds that it is empty, and a result doesn't destroy d2, d3, and d4.
I solved this by changing the task creations like this:
```
@root.children << (d1 = new_task(:sort_order => 2))
@root.save!
```
This worked so I'm ok with it :) I think it is also possible to fix this by either reloading d1 (`d1.reload`) or self.children (`self.children(true)`) although I didn't try any of these solutions.
|
171,541 |
<p>I have a service app that creates AppDomain's during the course of its use for long running tasks. I've been tracking these by storing them in a Hashtable with a unique ID.</p>
<p>After a task is completed the service app then unloads the AppDomain allocated to that task and then it's removed it from the appdomain Hashtable.</p>
<p>Purely from a sanity checking point of view, is there a way I can query the CLR to see what app domains are still loaded by the creating app domain (i.e. so I can compare the tracking Hashtable against what the CLR actually sees)?</p>
|
[
{
"answer_id": 172553,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p><code>children</code> <a href=\"http://github.com/rails/acts_as_tree/tree/master/lib/active_record/acts/tree.rb#L47\" rel=\"nofollow noreferrer\">is a simple has_many association</a></p>\n\n<p>This means, when you call <code>.children</code>, it will load them from the database (if not already present). It will then cache them.</p>\n\n<p>I was going to say that your second 'test' will actually be looking at the cached values not the real database, but that shouldn't happen as you are just using <code>Task.count</code> rather than <code>d1.children.count</code>. Hrm</p>\n\n<p>Have you looked at the logs? They will show you the SQL which is being executed. You may see a mysql error in there which will tell you what's going on</p>\n"
},
{
"answer_id": 173169,
"author": "gsmendoza",
"author_id": 11082,
"author_profile": "https://Stackoverflow.com/users/11082",
"pm_score": 3,
"selected": true,
"text": "<p>I found the bug. The line</p>\n\n<pre><code>d1 = create_task(:parent_id => @root.id, :sort_order => 2)\n</code></pre>\n\n<p>creates d1. This calls the <code>before_save</code> callback, which in turn calls <code>self.children</code>. As Orion pointed out, this caches the children of d1.</p>\n\n<p>However, at this point, d1 doesn't have any children yet. So d1's cache of children is empty.</p>\n\n<p>Thus, when I try to destroy d1, the program tries to destroy d1's children. It encounters the cache, finds that it is empty, and a result doesn't destroy d2, d3, and d4.</p>\n\n<p>I solved this by changing the task creations like this:</p>\n\n<pre><code>@root.children << (d1 = new_task(:sort_order => 2))\[email protected]!\n</code></pre>\n\n<p>This worked so I'm ok with it :) I think it is also possible to fix this by either reloading d1 (<code>d1.reload</code>) or self.children (<code>self.children(true)</code>) although I didn't try any of these solutions.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] |
I have a service app that creates AppDomain's during the course of its use for long running tasks. I've been tracking these by storing them in a Hashtable with a unique ID.
After a task is completed the service app then unloads the AppDomain allocated to that task and then it's removed it from the appdomain Hashtable.
Purely from a sanity checking point of view, is there a way I can query the CLR to see what app domains are still loaded by the creating app domain (i.e. so I can compare the tracking Hashtable against what the CLR actually sees)?
|
I found the bug. The line
```
d1 = create_task(:parent_id => @root.id, :sort_order => 2)
```
creates d1. This calls the `before_save` callback, which in turn calls `self.children`. As Orion pointed out, this caches the children of d1.
However, at this point, d1 doesn't have any children yet. So d1's cache of children is empty.
Thus, when I try to destroy d1, the program tries to destroy d1's children. It encounters the cache, finds that it is empty, and a result doesn't destroy d2, d3, and d4.
I solved this by changing the task creations like this:
```
@root.children << (d1 = new_task(:sort_order => 2))
@root.save!
```
This worked so I'm ok with it :) I think it is also possible to fix this by either reloading d1 (`d1.reload`) or self.children (`self.children(true)`) although I didn't try any of these solutions.
|
171,542 |
<p>I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using <pre>document.body.clientHeight</pre> but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big. </p>
<p>Now, I really don't want to use browser specific logic and substract a pixel or 2 from each dimension just for IE6. Also, I am not using CSS (width: 100% etc.) for this because I need the pixel amounts.</p>
<p>Does anyone know a better way to fill the viewport with an element in IE6+ (obviously all good browsers, too)?</p>
<p>Edit: Thanks Owen for the suggestion, I'm sure jQuery will work. I should have specified that I need a toolkit-agnostic solution. </p>
|
[
{
"answer_id": 171544,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<p>This <em>may</em> help the cause ...</p>\n\n<blockquote>\n <p>From <a href=\"http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/\" rel=\"nofollow noreferrer\">http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/</a> :</p>\n</blockquote>\n\n<pre><code><script type=\"text/javascript\">\n<!--\n\n var viewportwidth;\n var viewportheight;\n\n // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight\n\n if (typeof window.innerWidth != 'undefined')\n {\n viewportwidth = window.innerWidth,\n viewportheight = window.innerHeight\n }\n\n// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)\n\n else if (typeof document.documentElement != 'undefined'\n && typeof document.documentElement.clientWidth !=\n 'undefined' && document.documentElement.clientWidth != 0)\n {\n viewportwidth = document.documentElement.clientWidth,\n viewportheight = document.documentElement.clientHeight\n }\n\n // older versions of IE\n\n else\n {\n viewportwidth = document.getElementsByTagName('body')[0].clientWidth,\n viewportheight = document.getElementsByTagName('body')[0].clientHeight\n }\ndocument.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');\n//-->\n</script>\n</code></pre>\n"
},
{
"answer_id": 171632,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "<p>have you considered using <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a>? it abstracts most of the browser specific functionality away into a common interface.</p>\n\n<pre><code>var width = $(document).width();\nvar height = $(document.height();\n\n$('#mySpecialElement').width(width).height(height);\n</code></pre>\n"
},
{
"answer_id": 192258,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 1,
"selected": false,
"text": "<p>Ah ha! I forgot about <pre>document.documentElement.clientLeft</pre> and <pre>document.documentElement.clientTop</pre>.</p>\n\n<p>They were 2 in IE and 0 in the good browsers. \nSo using <pre>var WIDTH = ((document.documentElement.clientWidth - document.documentElement.clientLeft) || document.body.clientWidth);</pre>\netc. did the trick, similar idea for HEIGHT!</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25066/"
] |
I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using
```
document.body.clientHeight
```
but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big.
Now, I really don't want to use browser specific logic and substract a pixel or 2 from each dimension just for IE6. Also, I am not using CSS (width: 100% etc.) for this because I need the pixel amounts.
Does anyone know a better way to fill the viewport with an element in IE6+ (obviously all good browsers, too)?
Edit: Thanks Owen for the suggestion, I'm sure jQuery will work. I should have specified that I need a toolkit-agnostic solution.
|
have you considered using [jQuery](http://jquery.com)? it abstracts most of the browser specific functionality away into a common interface.
```
var width = $(document).width();
var height = $(document.height();
$('#mySpecialElement').width(width).height(height);
```
|
171,550 |
<blockquote>
<p><strong>See also:</strong> <br/>
<em><a href="https://stackoverflow.com/questions/4950725">How can I see which Git branches are tracking which remote / upstream branch?</a></em></p>
</blockquote>
<p>How can I find out which remote branch a local branch is tracking?</p>
<p>Do I need to parse <code>git config</code> output, or is there a command that would do this for me?</p>
|
[
{
"answer_id": 172075,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": -1,
"selected": false,
"text": "<p>I use <a href=\"https://people.gnome.org/~newren/eg/\" rel=\"nofollow noreferrer\">EasyGit (a.k.a. \"eg\")</a> as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an \"info\" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is \"foo\"):</p>\n\n<pre>\npknotz@s883422: (foo) ~/workspace/bd\n$ eg info\nTotal commits: 175\nLocal repository: .git\nNamed remote repositories: (name -> location)\n origin -> git://sahp7577/home/pknotz/bd.git\nCurrent branch: foo\n Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf\n Default pull/push repository: origin\n Default pull/push options:\n branch.foo.remote = origin\n branch.foo.merge = refs/heads/aal_devel_1\n Number of contributors: 3\n Number of files: 28\n Number of directories: 20\n Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)\n Commits: 62\n</pre>\n"
},
{
"answer_id": 6425090,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know if this counts as parsing the output of git config, but this will determine the URL of the remote that master is tracking:</p>\n\n<pre>\n$ git config remote.$(git config branch.master.remote).url\n</pre>\n"
},
{
"answer_id": 7251377,
"author": "Aaron Wells",
"author_id": 468642,
"author_profile": "https://Stackoverflow.com/users/468642",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Update:</strong> Well, it's been several years since I posted this! For my specific purpose of comparing HEAD to upstream, I now use <code>@{u}</code>, which is a shortcut that refers to the HEAD of the upstream tracking branch. (See <a href=\"https://git-scm.com/docs/gitrevisions#gitrevisions-emltbranchnamegtupstreamemegemmasterupstreamememuem\" rel=\"noreferrer\">https://git-scm.com/docs/gitrevisions#gitrevisions-emltbranchnamegtupstreamemegemmasterupstreamememuem</a> ).</p>\n\n<p><strong>Original answer:</strong> I've run across this problem as well. I often use multiple remotes in a single repository, and it's easy to forget which one your current branch is tracking against. And sometimes it's handy to know that, such as when you want to look at your local commits via <code>git log remotename/branchname..HEAD</code>.</p>\n\n<p>All this stuff is stored in git config variables, but you don't have to parse the git config output. If you invoke git config followed by the name of a variable, it will just print the value of that variable, no parsing required. With that in mind, here are some commands to get info about your current branch's tracking setup:</p>\n\n<pre><code>LOCAL_BRANCH=`git name-rev --name-only HEAD`\nTRACKING_BRANCH=`git config branch.$LOCAL_BRANCH.merge`\nTRACKING_REMOTE=`git config branch.$LOCAL_BRANCH.remote`\nREMOTE_URL=`git config remote.$TRACKING_REMOTE.url`\n</code></pre>\n\n<p>In my case, since I'm only interested in finding out the name of my current remote, I do this:</p>\n\n<pre><code>git config branch.`git name-rev --name-only HEAD`.remote\n</code></pre>\n"
},
{
"answer_id": 7733266,
"author": "Ajit George",
"author_id": 36661,
"author_profile": "https://Stackoverflow.com/users/36661",
"pm_score": 8,
"selected": false,
"text": "<p>I think <code>git branch -av</code> only tells you what branches you have and which commit they're at, leaving you to infer which remote branches the local branches are tracking.</p>\n\n<p><code>git remote show origin</code> explicitly tells you which branches are tracking which remote branches. Here's example output from a repository with a single commit and a remote branch called <code>abranch</code>:</p>\n\n<pre><code>$ git branch -av\n* abranch d875bf4 initial commit\n master d875bf4 initial commit\n remotes/origin/HEAD -> origin/master\n remotes/origin/abranch d875bf4 initial commit\n remotes/origin/master d875bf4 initial commit\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>$ git remote show origin\n* remote origin\n Fetch URL: /home/ageorge/tmp/d/../exrepo/\n Push URL: /home/ageorge/tmp/d/../exrepo/\n HEAD branch (remote HEAD is ambiguous, may be one of the following):\n abranch\n master\n Remote branches:\n abranch tracked\n master tracked\n Local branches configured for 'git pull':\n abranch merges with remote abranch\n master merges with remote master\n Local refs configured for 'git push':\n abranch pushes to abranch (up to date)\n master pushes to master (up to date)\n</code></pre>\n"
},
{
"answer_id": 9753364,
"author": "cdunn2001",
"author_id": 263998,
"author_profile": "https://Stackoverflow.com/users/263998",
"pm_score": 9,
"selected": false,
"text": "<p>Two choices:</p>\n\n<pre><code>% git rev-parse --abbrev-ref --symbolic-full-name @{u}\norigin/mainline\n</code></pre>\n\n<p>or</p>\n\n<pre><code>% git for-each-ref --format='%(upstream:short)' \"$(git symbolic-ref -q HEAD)\"\norigin/mainline\n</code></pre>\n"
},
{
"answer_id": 10014285,
"author": "Olivier Refalo",
"author_id": 258689,
"author_profile": "https://Stackoverflow.com/users/258689",
"pm_score": 1,
"selected": false,
"text": "<p>I use this alias</p>\n\n<pre><code>git config --global alias.track '!sh -c \"\nif [ \\$# -eq 2 ]\n then\n echo \\\"Setting tracking for branch \\\" \\$1 \\\" -> \\\" \\$2;\n git branch --set-upstream \\$1 \\$2;\n else\n git for-each-ref --format=\\\"local: %(refname:short) <--sync--> remote: %(upstream:short)\\\" refs/heads && echo --URLs && git remote -v;\nfi \n\" -'\n</code></pre>\n\n<p>then</p>\n\n<pre><code>git track\n</code></pre>\n\n<p>note that the script can also be used to setup tracking.</p>\n\n<p>More great aliases at <a href=\"https://github.com/orefalo/bash-profiles\" rel=\"nofollow\">https://github.com/orefalo/bash-profiles</a></p>\n"
},
{
"answer_id": 12538667,
"author": "jdsumsion",
"author_id": 1667497,
"author_profile": "https://Stackoverflow.com/users/1667497",
"pm_score": 10,
"selected": false,
"text": "<p><a href=\"https://git-scm.com/docs/git-branch#Documentation/git-branch.txt--vv\" rel=\"noreferrer\">Here</a> is a command that gives you all tracking branches (configured for 'pull'), see:</p>\n\n<pre><code>$ git branch -vv\n main aaf02f0 [main/master: ahead 25] Some other commit\n* master add0a03 [jdsumsion/master] Some commit\n</code></pre>\n\n<p>You have to wade through the SHA and any long-wrapping commit messages, but it's quick to type and I get the tracking branches aligned vertically in the 3rd column.</p>\n\n<p>If you need info on both 'pull' and 'push' configuration per branch, see the other answer on <code>git remote show origin</code>.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>Starting in git version 1.8.5 you can show the upstream branch with <code>git status</code> and <code>git status -sb</code></p>\n"
},
{
"answer_id": 26526119,
"author": "Eugene Yarmash",
"author_id": 244297,
"author_profile": "https://Stackoverflow.com/users/244297",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <code>git checkout</code>, i.e. \"check out the current branch\". This is a no-op with a side-effects to show the tracking information, if exists, for the current branch.</p>\n\n<pre><code>$ git checkout \nYour branch is up-to-date with 'origin/master'.\n</code></pre>\n"
},
{
"answer_id": 27395297,
"author": "Trickmaster",
"author_id": 2652482,
"author_profile": "https://Stackoverflow.com/users/2652482",
"pm_score": 4,
"selected": false,
"text": "<p>Another simple way is to use</p>\n\n<p><code>cat .git/config</code> in a git repo</p>\n\n<p>This will list details for local branches</p>\n"
},
{
"answer_id": 31308161,
"author": "Nagaraja G Devadiga",
"author_id": 2732527,
"author_profile": "https://Stackoverflow.com/users/2732527",
"pm_score": 1,
"selected": false,
"text": "<p>Following command will remote origin current fork is referring to </p>\n\n<blockquote>\n <p>git remote -v </p>\n</blockquote>\n\n<p>For adding a remote path, </p>\n\n<blockquote>\n <p>git remote add origin path_name </p>\n</blockquote>\n"
},
{
"answer_id": 32255813,
"author": "Wayne Walker",
"author_id": 448831,
"author_profile": "https://Stackoverflow.com/users/448831",
"pm_score": 3,
"selected": false,
"text": "<p>Another method (thanks osse), if you just want to know whether or not it exists:</p>\n\n<pre><code>if git rev-parse @{u} > /dev/null 2>&1\nthen\n printf \"has an upstream\\n\"\nelse\n printf \"has no upstream\\n\"\nfi\n</code></pre>\n"
},
{
"answer_id": 32613805,
"author": "FragLegs",
"author_id": 912374,
"author_profile": "https://Stackoverflow.com/users/912374",
"pm_score": 4,
"selected": false,
"text": "<p>Yet another way</p>\n\n<pre><code>git status -b --porcelain\n</code></pre>\n\n<p>This will give you</p>\n\n<pre><code>## BRANCH(...REMOTE)\nmodified and untracked files\n</code></pre>\n"
},
{
"answer_id": 35835293,
"author": "Ranushka Goonesekere",
"author_id": 3234426,
"author_profile": "https://Stackoverflow.com/users/3234426",
"pm_score": 3,
"selected": false,
"text": "<pre><code>git branch -r -vv\n</code></pre>\n\n<p>will list all branches including remote.</p>\n"
},
{
"answer_id": 38406646,
"author": "nikkypx",
"author_id": 1395009,
"author_profile": "https://Stackoverflow.com/users/1395009",
"pm_score": 6,
"selected": false,
"text": "<p>The local branches and their remotes.</p>\n\n<pre><code>git branch -vv \n</code></pre>\n\n<p>All branches and tracking remotes.</p>\n\n<pre><code>git branch -a -vv\n</code></pre>\n\n<p>See where the local branches are explicitly configured for push and pull.</p>\n\n<pre><code>git remote show {remote_name}\n</code></pre>\n"
},
{
"answer_id": 39456421,
"author": "ravikanth",
"author_id": 1030360,
"author_profile": "https://Stackoverflow.com/users/1030360",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using Gradle,</p>\n\n<pre><code>def gitHash = new ByteArrayOutputStream()\n project.exec {\n commandLine 'git', 'rev-parse', '--short', 'HEAD'\n standardOutput = gitHash\n }\n\ndef gitBranch = new ByteArrayOutputStream()\n project.exec {\n def gitCmd = \"git symbolic-ref --short -q HEAD || git branch -rq --contains \"+getGitHash()+\" | sed -e '2,\\$d' -e 's/\\\\(.*\\\\)\\\\/\\\\(.*\\\\)\\$/\\\\2/' || echo 'master'\"\n commandLine \"bash\", \"-c\", \"${gitCmd}\"\n standardOutput = gitBranch\n }\n</code></pre>\n"
},
{
"answer_id": 40630957,
"author": "rubo77",
"author_id": 1069083,
"author_profile": "https://Stackoverflow.com/users/1069083",
"pm_score": 5,
"selected": false,
"text": "<p>This will show you the branch you are on:</p>\n\n<pre><code>$ git branch -vv\n</code></pre>\n\n<p>This will show <strong>only</strong> the current branch you are on:</p>\n\n<pre><code>$ git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)\n</code></pre>\n\n<p>for example:</p>\n\n<pre><code>myremote/mybranch\n</code></pre>\n\n<p>You can find out the URL of the <strong>remote</strong> that is used by the <strong>current branch</strong> you are on with:</p>\n\n<pre><code>$ git remote get-url $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)|cut -d/ -f1)\n</code></pre>\n\n<p>for example:</p>\n\n<pre><code>https://github.com/someone/somerepo.git\n</code></pre>\n"
},
{
"answer_id": 52896538,
"author": "Tom Hale",
"author_id": 5353461,
"author_profile": "https://Stackoverflow.com/users/5353461",
"pm_score": 2,
"selected": false,
"text": "<p>Improving on <a href=\"https://stackoverflow.com/a/7251377/5353461\">this answer</a>, I came up with these <code>.gitconfig</code> aliases:</p>\n\n<pre><code>branch-name = \"symbolic-ref --short HEAD\"\nbranch-remote-fetch = !\"branch=$(git branch-name) && git config branch.\\\"$branch\\\".remote || echo origin #\"\nbranch-remote-push = !\"branch=$(git branch-name) && git config branch.\\\"$branch\\\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #\"\nbranch-url-fetch = !\"remote=$(git branch-remote-fetch) && git remote get-url \\\"$remote\\\" #\" # cognizant of insteadOf\nbranch-url-push = !\"remote=$(git branch-remote-push ) && git remote get-url --push \\\"$remote\\\" #\" # cognizant of pushInsteadOf\n</code></pre>\n"
},
{
"answer_id": 52930908,
"author": "Jeremy Thomerson",
"author_id": 1011988,
"author_profile": "https://Stackoverflow.com/users/1011988",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to find the upstream for <em>any</em> branch (as opposed to just the one you are on), here is a slight modification to @cdunn2001's answer:</p>\n\n<p><code>git rev-parse --abbrev-ref --symbolic-full-name YOUR_LOCAL_BRANCH_NAME@{upstream}</code></p>\n\n<p>That will give you the remote branch name for the local branch named <code>YOUR_LOCAL_BRANCH_NAME</code>.</p>\n"
},
{
"answer_id": 55698562,
"author": "joseluisq",
"author_id": 2510591,
"author_profile": "https://Stackoverflow.com/users/2510591",
"pm_score": 3,
"selected": false,
"text": "<p>Lists both local and remote branches:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ git branch -ra\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code> feature/feature1\n feature/feature2\n hotfix/hotfix1\n* master\n remotes/origin/HEAD -> origin/master\n remotes/origin/develop\n remotes/origin/master\n</code></pre>\n"
},
{
"answer_id": 55968741,
"author": "xpioneer",
"author_id": 3729270,
"author_profile": "https://Stackoverflow.com/users/3729270",
"pm_score": 3,
"selected": false,
"text": "<p>You can try this : </p>\n\n<pre><code>git remote show origin | grep \"branch_name\"\n</code></pre>\n\n<p><code>branch_name</code> needs to be replaced with your branch</p>\n"
},
{
"answer_id": 58872860,
"author": "Sabyasachi Ghosh",
"author_id": 11169852,
"author_profile": "https://Stackoverflow.com/users/11169852",
"pm_score": 5,
"selected": false,
"text": "<p><code>git branch -vv | grep 'BRANCH_NAME'</code></p>\n\n<p><code>git branch -vv</code> : This part will show all local branches along with their upstream branch . </p>\n\n<p><code>grep 'BRANCH_NAME'</code> : It will filter the current branch from the branch list.</p>\n"
},
{
"answer_id": 60297250,
"author": "AndiDog",
"author_id": 245706,
"author_profile": "https://Stackoverflow.com/users/245706",
"pm_score": 4,
"selected": false,
"text": "<p>git-status porcelain (machine-readable) v2 output looks like this:</p>\n\n<pre><code>$ git status -b --porcelain=v2\n# branch.oid d0de00da833720abb1cefe7356493d773140b460\n# branch.head the-branch-name\n# branch.upstream gitlab/the-branch-name\n# branch.ab +2 -2\n</code></pre>\n\n<p>And to get the branch upstream only:</p>\n\n<pre><code>$ git status -b --porcelain=v2 | grep -m 1 \"^# branch.upstream \" | cut -d \" \" -f 3-\ngitlab/the-branch-name\n</code></pre>\n\n<p>If the branch has no upstream, the above command will produce an empty output (or fail with <code>set -o pipefail</code>).</p>\n"
},
{
"answer_id": 63585578,
"author": "Erik Aronesty",
"author_id": 627042,
"author_profile": "https://Stackoverflow.com/users/627042",
"pm_score": 2,
"selected": false,
"text": "<p>Having tried all of the solutions here, I realized none of them were good in all situations:</p>\n<ul>\n<li>works on local branches</li>\n<li>works on detached branches</li>\n<li>works under CI</li>\n</ul>\n<p>This command gets all names:</p>\n<pre><code>git branch -a --contains HEAD --list --format='%(refname:short)'\n</code></pre>\n<p>For my application, I had to filter out the HEAD & master refs, prefer remote refs, and strip off the word 'origin/'. and then if that wasn't found, use the first non HEAD ref that didn't have a <code>/</code> or a <code>(</code> in it.</p>\n"
},
{
"answer_id": 71040132,
"author": "Fred Yang",
"author_id": 98563,
"author_profile": "https://Stackoverflow.com/users/98563",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-sh prettyprint-override\"><code>git branch -vv | grep 'hardcode-branch-name'\n# "git rev-parse --abbrev-ref head" will get your current branch name\n# $(git rev-parse --abbrev-ref head) save it as string\n# find the tracking branch by grep filtering the current branch \ngit branch -vv | grep $(git rev-parse --abbrev-ref head)\n</code></pre>\n"
},
{
"answer_id": 72717025,
"author": "PhillipMcCubbin",
"author_id": 13977551,
"author_profile": "https://Stackoverflow.com/users/13977551",
"pm_score": 1,
"selected": false,
"text": "<p>Display only current branch info <strong>without</strong> using <code>grep</code>:</p>\n<pre><code>git branch -vv --contains\n</code></pre>\n<p>This is short for:</p>\n<pre><code>git branch -vv --contains HEAD\n</code></pre>\n<p>and if your current HEAD's commit id is in other branches, those branches will display also.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
>
> **See also:**
>
> *[How can I see which Git branches are tracking which remote / upstream branch?](https://stackoverflow.com/questions/4950725)*
>
>
>
How can I find out which remote branch a local branch is tracking?
Do I need to parse `git config` output, or is there a command that would do this for me?
|
[Here](https://git-scm.com/docs/git-branch#Documentation/git-branch.txt--vv) is a command that gives you all tracking branches (configured for 'pull'), see:
```
$ git branch -vv
main aaf02f0 [main/master: ahead 25] Some other commit
* master add0a03 [jdsumsion/master] Some commit
```
You have to wade through the SHA and any long-wrapping commit messages, but it's quick to type and I get the tracking branches aligned vertically in the 3rd column.
If you need info on both 'pull' and 'push' configuration per branch, see the other answer on `git remote show origin`.
---
**Update**
Starting in git version 1.8.5 you can show the upstream branch with `git status` and `git status -sb`
|
171,566 |
<p>Im using delphi's ttreeview as an 'options' menu. how would i go upon selecting the next node at runtime like a previous and next button? i tried the getprev and getnext methods but no luck.</p>
|
[
{
"answer_id": 171722,
"author": "John Thomas",
"author_id": 22599,
"author_profile": "https://Stackoverflow.com/users/22599",
"pm_score": 3,
"selected": false,
"text": "<p>Here you have the 'Next' behavior. For 'Previous' I leave as exercise for you: :-)</p>\n\n<pre><code>procedure TForm8.btn1Click(Sender: TObject); \nvar \n crt: TTreeNode;\n\nbegin\n with tv1 do //this is our tree\n begin\n if Selected=nil then\n crt:=Items[0] //the first one\n else\n crt:=Selected.GetNext; //for previous you'll have 'GetPrev' \n\n if crt<>nil then //can be 'nil' if we reached to the end\n Selected:=crt;\n end;\nend;\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 176430,
"author": "DiGi",
"author_id": 12042,
"author_profile": "https://Stackoverflow.com/users/12042",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe there is some space in tree item to store pointer to you correct page.</p>\n\n<p>But - if you have some time - try to explore <a href=\"http://www.delphi-gems.com/index.php?option=com_content&task=view&id=12&Itemid=38\" rel=\"nofollow noreferrer\">Virtual Treeview</a> - it's Delphi's best treeview component.</p>\n"
},
{
"answer_id": 2968900,
"author": "Remus Rigo",
"author_id": 184401,
"author_profile": "https://Stackoverflow.com/users/184401",
"pm_score": 0,
"selected": false,
"text": "<p>here is another way to do this:</p>\n\n<pre><code>type TfrmMain = class(TForm)\n...\n public\n DLLHandle : THandle;\n function GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\n\n...\n\nfunction TfrmMain.GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\nbegin\n Result:='';\n while Assigned(node) do\n begin\n Result:=delimiter+node.Text+Result;\n node:=node.Parent;\n end;\n if Result <> '' then\n Delete(Result, 1, 1);\nend;\n\n...\n</code></pre>\n\n<p>here is how to use it: on your treeview's click or doubleclick event do this</p>\n\n<pre><code>...\nvar\n path : String;\nbegin\n path:=GetNodePath(yourTreeView.Selected);\n ShowMessage(path);\n...\n</code></pre>\n\n<p>if you have a 'Item 1' and a subitem called 'Item 1' and click on Item 2 than the message should be 'Item 1\\Item 2'. By doing this you can have a better control...</p>\n\n<p>hope this gives you another idea to enhance your code</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Im using delphi's ttreeview as an 'options' menu. how would i go upon selecting the next node at runtime like a previous and next button? i tried the getprev and getnext methods but no luck.
|
Here you have the 'Next' behavior. For 'Previous' I leave as exercise for you: :-)
```
procedure TForm8.btn1Click(Sender: TObject);
var
crt: TTreeNode;
begin
with tv1 do //this is our tree
begin
if Selected=nil then
crt:=Items[0] //the first one
else
crt:=Selected.GetNext; //for previous you'll have 'GetPrev'
if crt<>nil then //can be 'nil' if we reached to the end
Selected:=crt;
end;
end;
```
HTH
|
171,569 |
<p>Actually I will want to use that JeOS for our webserver. Is it a good choice?</p>
|
[
{
"answer_id": 171722,
"author": "John Thomas",
"author_id": 22599,
"author_profile": "https://Stackoverflow.com/users/22599",
"pm_score": 3,
"selected": false,
"text": "<p>Here you have the 'Next' behavior. For 'Previous' I leave as exercise for you: :-)</p>\n\n<pre><code>procedure TForm8.btn1Click(Sender: TObject); \nvar \n crt: TTreeNode;\n\nbegin\n with tv1 do //this is our tree\n begin\n if Selected=nil then\n crt:=Items[0] //the first one\n else\n crt:=Selected.GetNext; //for previous you'll have 'GetPrev' \n\n if crt<>nil then //can be 'nil' if we reached to the end\n Selected:=crt;\n end;\nend;\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 176430,
"author": "DiGi",
"author_id": 12042,
"author_profile": "https://Stackoverflow.com/users/12042",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe there is some space in tree item to store pointer to you correct page.</p>\n\n<p>But - if you have some time - try to explore <a href=\"http://www.delphi-gems.com/index.php?option=com_content&task=view&id=12&Itemid=38\" rel=\"nofollow noreferrer\">Virtual Treeview</a> - it's Delphi's best treeview component.</p>\n"
},
{
"answer_id": 2968900,
"author": "Remus Rigo",
"author_id": 184401,
"author_profile": "https://Stackoverflow.com/users/184401",
"pm_score": 0,
"selected": false,
"text": "<p>here is another way to do this:</p>\n\n<pre><code>type TfrmMain = class(TForm)\n...\n public\n DLLHandle : THandle;\n function GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\n\n...\n\nfunction TfrmMain.GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\nbegin\n Result:='';\n while Assigned(node) do\n begin\n Result:=delimiter+node.Text+Result;\n node:=node.Parent;\n end;\n if Result <> '' then\n Delete(Result, 1, 1);\nend;\n\n...\n</code></pre>\n\n<p>here is how to use it: on your treeview's click or doubleclick event do this</p>\n\n<pre><code>...\nvar\n path : String;\nbegin\n path:=GetNodePath(yourTreeView.Selected);\n ShowMessage(path);\n...\n</code></pre>\n\n<p>if you have a 'Item 1' and a subitem called 'Item 1' and click on Item 2 than the message should be 'Item 1\\Item 2'. By doing this you can have a better control...</p>\n\n<p>hope this gives you another idea to enhance your code</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Actually I will want to use that JeOS for our webserver. Is it a good choice?
|
Here you have the 'Next' behavior. For 'Previous' I leave as exercise for you: :-)
```
procedure TForm8.btn1Click(Sender: TObject);
var
crt: TTreeNode;
begin
with tv1 do //this is our tree
begin
if Selected=nil then
crt:=Items[0] //the first one
else
crt:=Selected.GetNext; //for previous you'll have 'GetPrev'
if crt<>nil then //can be 'nil' if we reached to the end
Selected:=crt;
end;
end;
```
HTH
|
171,588 |
<p>If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?</p>
|
[
{
"answer_id": 171593,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 6,
"selected": false,
"text": "<p>By design there isn't a <strong>built in</strong> mechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from \"My Computer -> Properties ->Advanced Settings -> Environment Variables\".</p>\n\n<p>If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt. </p>\n\n<p>The <a href=\"https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in#171737\">latest accepted answer</a> shows a partial work-around by manually refreshing <em>all</em> the environment variables in a script. The script handles the use case of changing environment variables globally in \"My Computer...Environment Variables\", but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.</p>\n"
},
{
"answer_id": 171737,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 8,
"selected": true,
"text": "<p>You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.</p>\n\n<p>Create a file named <code>resetvars.vbs</code> containing this code, and save it on the path:</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Set oShell = WScript.CreateObject(\"WScript.Shell\")\nfilename = oShell.ExpandEnvironmentStrings(\"%TEMP%\\resetvars.bat\")\nSet objFileSystem = CreateObject(\"Scripting.fileSystemObject\")\nSet oFile = objFileSystem.CreateTextFile(filename, TRUE)\n\nset oEnv=oShell.Environment(\"System\")\nfor each sitem in oEnv \n oFile.WriteLine(\"SET \" & sitem)\nnext\npath = oEnv(\"PATH\")\n\nset oEnv=oShell.Environment(\"User\")\nfor each sitem in oEnv \n oFile.WriteLine(\"SET \" & sitem)\nnext\n\npath = path & \";\" & oEnv(\"PATH\")\noFile.WriteLine(\"SET PATH=\" & path)\noFile.Close\n</code></pre>\n\n<p>create another file name resetvars.bat containing this code, same location:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>@echo off\n%~dp0resetvars.vbs\ncall \"%TEMP%\\resetvars.bat\"\n</code></pre>\n\n<p>When you want to refresh the environment variables, just run <code>resetvars.bat</code></p>\n\n<hr>\n\n<p><em>Apologetics</em>:</p>\n\n<p>The two main problems I had coming up with this solution were</p>\n\n<p><strong>a.</strong> I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and </p>\n\n<p><strong>b.</strong> the PATH environment variable is a concatenation of the user and the system PATH variables.</p>\n\n<p>I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.</p>\n\n<p>I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.</p>\n\n<p><strong>Note</strong>: this script does not delete variables.</p>\n\n<p>This can probably be improved.</p>\n\n<p><strong>ADDED</strong></p>\n\n<p>If you need to export the environment from one cmd window to another, use this script (let's call it <code>exportvars.vbs</code>):</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Set oShell = WScript.CreateObject(\"WScript.Shell\")\nfilename = oShell.ExpandEnvironmentStrings(\"%TEMP%\\resetvars.bat\")\nSet objFileSystem = CreateObject(\"Scripting.fileSystemObject\")\nSet oFile = objFileSystem.CreateTextFile(filename, TRUE)\n\nset oEnv=oShell.Environment(\"Process\")\nfor each sitem in oEnv \n oFile.WriteLine(\"SET \" & sitem)\nnext\noFile.Close\n</code></pre>\n\n<p>Run <code>exportvars.vbs</code> in the window you want to export <strong>from</strong>, then switch to the window you want to export <strong>to</strong>, and type:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>\"%TEMP%\\resetvars.bat\"\n</code></pre>\n"
},
{
"answer_id": 172049,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>There is no straight way, as Kev said. In most cases, it is simpler to spawn another CMD box. More annoyingly, running programs are not aware of changes either (although IIRC there might be a broadcast message to watch to be notified of such change).</p>\n\n<p>It have been worse: in older versions of Windows, you had to log off then log back to take in account the changes...</p>\n"
},
{
"answer_id": 2479615,
"author": "Brian Weed",
"author_id": 297617,
"author_profile": "https://Stackoverflow.com/users/297617",
"pm_score": 4,
"selected": false,
"text": "<p>Calling this function has worked for me:</p>\n\n<pre><code>VOID Win32ForceSettingsChange()\n{\n DWORD dwReturnValue;\n ::SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) \"Environment\", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);\n}\n</code></pre>\n"
},
{
"answer_id": 5111086,
"author": "Algonaut",
"author_id": 472554,
"author_profile": "https://Stackoverflow.com/users/472554",
"pm_score": 3,
"selected": false,
"text": "<p>Environment variables are kept in HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet\\Control\\Session Manager\\Environment.</p>\n\n<p>Many of the useful env vars, such as Path, are stored as REG_SZ. There are several ways to access the registry including REGEDIT:</p>\n\n<p><code><code>REGEDIT /E &lt;filename&gt; \"HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment\"</code></code></p>\n\n<p>The output starts with magic numbers. So to search it with the find command it needs to be typed and redirected: <code>type <filename> | findstr -c:\\\"Path\\\"</code></p>\n\n<p>So, if you just want to refresh the path variable in your current command session with what's in system properties the following batch script works fine:</p>\n\n<p>RefreshPath.cmd:</p>\n\n<pre>\n\n @echo off\n\n REM This solution requests elevation in order to read from the registry.\n\n if exist %temp%\\env.reg del %temp%\\env.reg /q /f\n\n REGEDIT /E %temp%\\env.reg \"HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment\"\n\n if not exist %temp%\\env.reg (\n echo \"Unable to write registry to temp location\"\n exit 1\n )\n\n SETLOCAL EnableDelayedExpansion\n\n for /f \"tokens=1,2* delims==\" %%i in ('type %temp%\\env.reg ^| findstr -c:\\\"Path\\\"=') do (\n set upath=%%~j\n echo !upath:\\\\=\\! >%temp%\\newpath\n )\n\n ENDLOCAL\n\n for /f \"tokens=*\" %%i in (%temp%\\newpath) do set path=%%i</pre>\n"
},
{
"answer_id": 9016150,
"author": "kristofer månsson",
"author_id": 1170948,
"author_profile": "https://Stackoverflow.com/users/1170948",
"pm_score": 5,
"selected": false,
"text": "<p>This works on windows 7: <code>SET PATH=%PATH%;C:\\CmdShortcuts</code></p>\n\n<p>tested by typing echo %PATH% and it worked, fine. also set if you open a new cmd, no need for those pesky reboots any more :)</p>\n"
},
{
"answer_id": 11147132,
"author": "Christopher Holmes",
"author_id": 1473406,
"author_profile": "https://Stackoverflow.com/users/1473406",
"pm_score": 4,
"selected": false,
"text": "<p>The best method I came up with was to just do a Registry query. Here is my example.</p>\n\n<p>In my example I did an install using a Batch file that added new environment variables. I needed to do things with this as soon as the install was complete, but was unable to spawn a new process with those new variables. I tested spawning another explorer window and called back to cmd.exe and this worked but on Vista and Windows 7, Explorer only runs as a single instance and normally as the person logged in. This would fail with automation since I need my admin creds to do things regardless of running from local system or as an administrator on the box. The limitation to this is that it does not handle things like path, this only worked on simple enviroment variables. This allowed me to use a batch to get over to a directory (with spaces) and copy in files run .exes and etc. This was written today from may resources on stackoverflow.com</p>\n\n<p>Orginal Batch calls to new Batch:</p>\n\n<p>testenvget.cmd SDROOT (or whatever the variable)</p>\n\n<pre><code>@ECHO OFF\nsetlocal ENABLEEXTENSIONS\nset keyname=HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\nset value=%1\nSET ERRKEY=0\n\nREG QUERY \"%KEYNAME%\" /v \"%VALUE%\" 2>NUL| FIND /I \"%VALUE%\"\nIF %ERRORLEVEL% EQU 0 (\nECHO The Registry Key Exists \n) ELSE (\nSET ERRKEY=1\nEcho The Registry Key Does not Exist\n)\n\nEcho %ERRKEY%\nIF %ERRKEY% EQU 1 GOTO :ERROR\n\nFOR /F \"tokens=1-7\" %%A IN ('REG QUERY \"%KEYNAME%\" /v \"%VALUE%\" 2^>NUL^| FIND /I \"%VALUE%\"') DO (\nECHO %%A\nECHO %%B\nECHO %%C\nECHO %%D\nECHO %%E\nECHO %%F\nECHO %%G\nSET ValueName=%%A\nSET ValueType=%%B\nSET C1=%%C\nSET C2=%%D\nSET C3=%%E\nSET C4=%%F\nSET C5=%%G\n)\n\nSET VALUE1=%C1% %C2% %C3% %C4% %C5%\necho The Value of %VALUE% is %C1% %C2% %C3% %C4% %C5%\ncd /d \"%VALUE1%\"\npause\nREM **RUN Extra Commands here**\nGOTO :EOF\n\n:ERROR\nEcho The the Enviroment Variable does not exist.\npause\nGOTO :EOF\n</code></pre>\n\n<p>Also there is another method that I came up with from various different ideas. Please see below. This basically will get the newest path variable from the registry however, this will cause a number of issues beacuse the registry query is going to give variables in itself, that means everywhere there is a variable this will not work, so to combat this issue I basically double up the path. Very nasty. The more perfered method would be to do:\n Set Path=%Path%;C:\\Program Files\\Software....\\</p>\n\n<p>Regardless here is the new batch file, please use caution.</p>\n\n<pre><code>@ECHO OFF\nSETLOCAL ENABLEEXTENSIONS\nset org=%PATH%\nfor /f \"tokens=2*\" %%A in ('REG QUERY \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v Path ^|FIND /I \"Path\"') DO (\nSET path=%%B\n)\nSET PATH=%org%;%PATH%\nset path\n</code></pre>\n"
},
{
"answer_id": 11955920,
"author": "Jens A. Koch",
"author_id": 1163786,
"author_profile": "https://Stackoverflow.com/users/1163786",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Use \"setx\" and restart cmd prompt</strong></p>\n\n<p>There is a command line tool named \"<a href=\"http://technet.microsoft.com/en-us/library/cc755104%28v=ws.10%29.aspx\">setx</a>\" for this job.\nIt's for <strong>reading and writing</strong> env variables.\nThe variables persist after the command window has been closed.</p>\n\n<p>It \"Creates or modifies environment variables in the user or system environment, without requiring programming or scripting. The <a href=\"http://technet.microsoft.com/en-us/library/cc755104%28v=ws.10%29.aspx\">setx</a> command also retrieves the values of registry keys and writes them to text files.\"</p>\n\n<p>Note: variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window. So, you have to restart.</p>\n\n<p>If <code>setx</code> is missing: </p>\n\n<ul>\n<li><a href=\"http://download.microsoft.com/download/win2000platform/setx/1.00.0.1/nt5/en-us/setx_setup.exe\">http://download.microsoft.com/download/win2000platform/setx/1.00.0.1/nt5/en-us/setx_setup.exe</a></li>\n</ul>\n\n<hr>\n\n<p><strong>Or modify the registry</strong></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms682653(v=vs.85).aspx\">MSDN</a> says: </p>\n\n<blockquote>\n <p>To programmatically add or modify system environment variables, add\n them to the\n <strong>HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session\n Manager\\Environment</strong> registry key, then broadcast a <strong>WM_SETTINGCHANGE</strong>\n message with <strong>lParam</strong> set to the string \"<strong>Environment</strong>\". </p>\n \n <p>This allows applications, such as the shell, to pick up your updates.</p>\n</blockquote>\n"
},
{
"answer_id": 14289383,
"author": "wardies",
"author_id": 1970593,
"author_profile": "https://Stackoverflow.com/users/1970593",
"pm_score": 0,
"selected": false,
"text": "<p>Edit: this only works if the environment changes you're doing are as a result of running a batch file.</p>\n\n<p>If a batch file begins with <code>SETLOCAL</code> then it will always unravel back to your original environment on exit even if you forget to call <code>ENDLOCAL</code> before the batch exits, or if it aborts unexpectedly.</p>\n\n<p>Almost every batch file I write begins with <code>SETLOCAL</code> since in most cases I don't want the side-effects of environment changes to remain. In cases where I do want certain environment variable changes to propagate outside the batch file then my last <code>ENDLOCAL</code> looks like this:</p>\n\n<pre><code>ENDLOCAL & (\n SET RESULT1=%RESULT1%\n SET RESULT2=%RESULT2%\n)\n</code></pre>\n"
},
{
"answer_id": 18257168,
"author": "josh poley",
"author_id": 858968,
"author_profile": "https://Stackoverflow.com/users/858968",
"pm_score": 3,
"selected": false,
"text": "<p>It is possible to do this by overwriting the Environment Table within a specified process itself.</p>\n\n<p>As a proof of concept I wrote this sample app, which just edited a single (known) environment variable in a cmd.exe process:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>typedef DWORD (__stdcall *NtQueryInformationProcessPtr)(HANDLE, DWORD, PVOID, ULONG, PULONG);\n\nint __cdecl main(int argc, char* argv[])\n{\n HMODULE hNtDll = GetModuleHandleA(\"ntdll.dll\");\n NtQueryInformationProcessPtr NtQueryInformationProcess = (NtQueryInformationProcessPtr)GetProcAddress(hNtDll, \"NtQueryInformationProcess\");\n\n int processId = atoi(argv[1]);\n printf(\"Target PID: %u\\n\", processId);\n\n // open the process with read+write access\n HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, 0, processId);\n if(hProcess == NULL)\n {\n printf(\"Error opening process (%u)\\n\", GetLastError());\n return 0;\n }\n\n // find the location of the PEB\n PROCESS_BASIC_INFORMATION pbi = {0};\n NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);\n if(status != 0)\n {\n printf(\"Error ProcessBasicInformation (0x%8X)\\n\", status);\n }\n printf(\"PEB: %p\\n\", pbi.PebBaseAddress);\n\n // find the process parameters\n char *processParamsOffset = (char*)pbi.PebBaseAddress + 0x20; // hard coded offset for x64 apps\n char *processParameters = NULL;\n if(ReadProcessMemory(hProcess, processParamsOffset, &processParameters, sizeof(processParameters), NULL))\n {\n printf(\"UserProcessParameters: %p\\n\", processParameters);\n }\n else\n {\n printf(\"Error ReadProcessMemory (%u)\\n\", GetLastError());\n }\n\n // find the address to the environment table\n char *environmentOffset = processParameters + 0x80; // hard coded offset for x64 apps\n char *environment = NULL;\n ReadProcessMemory(hProcess, environmentOffset, &environment, sizeof(environment), NULL);\n printf(\"environment: %p\\n\", environment);\n\n // copy the environment table into our own memory for scanning\n wchar_t *localEnvBlock = new wchar_t[64*1024];\n ReadProcessMemory(hProcess, environment, localEnvBlock, sizeof(wchar_t)*64*1024, NULL);\n\n // find the variable to edit\n wchar_t *found = NULL;\n wchar_t *varOffset = localEnvBlock;\n while(varOffset < localEnvBlock + 64*1024)\n {\n if(varOffset[0] == '\\0')\n {\n // we reached the end\n break;\n }\n if(wcsncmp(varOffset, L\"ENVTEST=\", 8) == 0)\n {\n found = varOffset;\n break;\n }\n varOffset += wcslen(varOffset)+1;\n }\n\n // check to see if we found one\n if(found)\n {\n size_t offset = (found - localEnvBlock) * sizeof(wchar_t);\n printf(\"Offset: %Iu\\n\", offset);\n\n // write a new version (if the size of the value changes then we have to rewrite the entire block)\n if(!WriteProcessMemory(hProcess, environment + offset, L\"ENVTEST=def\", 12*sizeof(wchar_t), NULL))\n {\n printf(\"Error WriteProcessMemory (%u)\\n\", GetLastError());\n }\n }\n\n // cleanup\n delete[] localEnvBlock;\n CloseHandle(hProcess);\n\n return 0;\n}\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>>set ENVTEST=abc\n\n>cppTest.exe 13796\nTarget PID: 13796\nPEB: 000007FFFFFD3000\nUserProcessParameters: 00000000004B2F30\nenvironment: 000000000052E700\nOffset: 1528\n\n>set ENVTEST\nENVTEST=def\n</code></pre>\n\n<h2>Notes</h2>\n\n<p>This approach would also be limited to security restrictions. If the target is run at higher elevation or a higher account (such as SYSTEM) then we wouldn't have permission to edit its memory.</p>\n\n<p>If you wanted to do this to a 32-bit app, the hard coded offsets above would change to 0x10 and 0x48 respectively. These offsets can be found by dumping out the _PEB and _RTL_USER_PROCESS_PARAMETERS structs in a debugger (e.g. in WinDbg <code>dt _PEB</code> and <code>dt _RTL_USER_PROCESS_PARAMETERS</code>)</p>\n\n<p>To change the proof-of-concept into a what the OP needs, it would just enumerate the current system and user environment variables (such as documented by @tsadok's answer) and write the entire environment table into the target process' memory.</p>\n\n<p><em>Edit:</em> The size of the environment block is also stored in the _RTL_USER_PROCESS_PARAMETERS struct, but the memory is allocated on the process' heap. So from an external process we wouldn't have the ability to resize it and make it larger. I played around with using VirtualAllocEx to allocate additional memory in the target process for the environment storage, and was able to set and read an entirely new table. Unfortunately any attempt to modify the environment from normal means will crash and burn as the address no longer points to the heap (it will crash in RtlSizeHeap).</p>\n"
},
{
"answer_id": 22027353,
"author": "wharding28",
"author_id": 2132305,
"author_profile": "https://Stackoverflow.com/users/2132305",
"pm_score": 6,
"selected": false,
"text": "<p>I came across this answer before eventually finding an easier solution. </p>\n\n<p>Simply restart <code>explorer.exe</code> in Task Manager.</p>\n\n<p>I didn't test, but you may also need to reopen you command prompt.</p>\n\n<p>Credit to <a href=\"https://stackoverflow.com/users/175071/timo-huovinen\">Timo Huovinen</a> here: <a href=\"https://stackoverflow.com/questions/10129505/node-not-recognized-although-successfully-installed#comment19877828_10129850\">Node not recognized although successfully installed</a> (if this helped you, please go give this man's comment credit).</p>\n"
},
{
"answer_id": 23777960,
"author": "Sebastian",
"author_id": 3032994,
"author_profile": "https://Stackoverflow.com/users/3032994",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following code in my batch scripts:</p>\n\n<pre><code>if not defined MY_ENV_VAR (\n setx MY_ENV_VAR \"VALUE\" > nul\n set MY_ENV_VAR=VALUE\n)\necho %MY_ENV_VAR%\n</code></pre>\n\n<p>By using <strong>SET</strong> after <strong>SETX</strong> it is possible to use the \"local\" variable directly without restarting the command window. And on the next run, the enviroment variable will be used.</p>\n"
},
{
"answer_id": 29891036,
"author": "Jens Hykkelbjerg",
"author_id": 2298901,
"author_profile": "https://Stackoverflow.com/users/2298901",
"pm_score": 0,
"selected": false,
"text": "<p>To solve this I have changed the environment variable using BOTH setx and set, and then restarted all instances of explorer.exe. This way any process subsequently started will have the new environment variable.</p>\n\n<p>My batch script to do this:</p>\n\n<pre><code>setx /M ENVVAR \"NEWVALUE\"\nset ENVVAR=\"NEWVALUE\"\n\ntaskkill /f /IM explorer.exe\nstart explorer.exe >nul\nexit\n</code></pre>\n\n<p>The problem with this approach is that all explorer windows that are currently opened will be closed, which is probably a bad idea - But see the post by Kev to learn why this is necessary</p>\n"
},
{
"answer_id": 32420542,
"author": "anonymous coward",
"author_id": 5305271,
"author_profile": "https://Stackoverflow.com/users/5305271",
"pm_score": 7,
"selected": false,
"text": "<p>Here is what Chocolatey uses.</p>\n<p><a href=\"https://github.com/chocolatey/choco/blob/master/src/chocolatey.resources/redirects/RefreshEnv.cmd\" rel=\"noreferrer\">https://github.com/chocolatey/choco/blob/master/src/chocolatey.resources/redirects/RefreshEnv.cmd</a></p>\n<pre><code>@echo off\n::\n:: RefreshEnv.cmd\n::\n:: Batch file to read environment variables from registry and\n:: set session variables to these values.\n::\n:: With this batch file, there should be no need to reload command\n:: environment every time you want environment changes to propagate\n\n::echo "RefreshEnv.cmd only works from cmd.exe, please install the Chocolatey Profile to take advantage of refreshenv from PowerShell"\necho | set /p dummy="Refreshing environment variables from registry for cmd.exe. Please wait..."\n\ngoto main\n\n:: Set one environment variable from registry key\n:SetFromReg\n "%WinDir%\\System32\\Reg" QUERY "%~1" /v "%~2" > "%TEMP%\\_envset.tmp" 2>NUL\n for /f "usebackq skip=2 tokens=2,*" %%A IN ("%TEMP%\\_envset.tmp") do (\n echo/set "%~3=%%B"\n )\n goto :EOF\n\n:: Get a list of environment variables from registry\n:GetRegEnv\n "%WinDir%\\System32\\Reg" QUERY "%~1" > "%TEMP%\\_envget.tmp"\n for /f "usebackq skip=2" %%A IN ("%TEMP%\\_envget.tmp") do (\n if /I not "%%~A"=="Path" (\n call :SetFromReg "%~1" "%%~A" "%%~A"\n )\n )\n goto :EOF\n\n:main\n echo/@echo off >"%TEMP%\\_env.cmd"\n\n :: Slowly generating final file\n call :GetRegEnv "HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment" >> "%TEMP%\\_env.cmd"\n call :GetRegEnv "HKCU\\Environment">>"%TEMP%\\_env.cmd" >> "%TEMP%\\_env.cmd"\n\n :: Special handling for PATH - mix both User and System\n call :SetFromReg "HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment" Path Path_HKLM >> "%TEMP%\\_env.cmd"\n call :SetFromReg "HKCU\\Environment" Path Path_HKCU >> "%TEMP%\\_env.cmd"\n\n :: Caution: do not insert space-chars before >> redirection sign\n echo/set "Path=%%Path_HKLM%%;%%Path_HKCU%%" >> "%TEMP%\\_env.cmd"\n\n :: Cleanup\n del /f /q "%TEMP%\\_envset.tmp" 2>nul\n del /f /q "%TEMP%\\_envget.tmp" 2>nul\n\n :: capture user / architecture\n SET "OriginalUserName=%USERNAME%"\n SET "OriginalArchitecture=%PROCESSOR_ARCHITECTURE%"\n\n :: Set these variables\n call "%TEMP%\\_env.cmd"\n\n :: Cleanup\n del /f /q "%TEMP%\\_env.cmd" 2>nul\n\n :: reset user / architecture\n SET "USERNAME=%OriginalUserName%"\n SET "PROCESSOR_ARCHITECTURE=%OriginalArchitecture%"\n\n echo | set /p dummy="Finished."\n echo .\n</code></pre>\n"
},
{
"answer_id": 34424260,
"author": "estebro",
"author_id": 1906617,
"author_profile": "https://Stackoverflow.com/users/1906617",
"pm_score": 3,
"selected": false,
"text": "<p>Try opening a new command prompt as an administrator. This worked for me on Windows 10. (I know this is an old answer, but I had to share this because having to write a VBS script just for this is absurd).</p>\n"
},
{
"answer_id": 37357801,
"author": "DieterDP",
"author_id": 1436932,
"author_profile": "https://Stackoverflow.com/users/1436932",
"pm_score": 2,
"selected": false,
"text": "<p>I liked the approach followed by chocolatey, as posted in anonymous coward's answer, since it is a pure batch approach. However, it leaves a temporary file and some temporary variables lying around. I made a cleaner version for myself.</p>\n\n<p>Make a file <code>refreshEnv.bat</code> somewhere on your <code>PATH</code>. Refresh your console environment by executing <code>refreshEnv</code>.</p>\n\n<pre><code>@ECHO OFF\nREM Source found on https://github.com/DieterDePaepe/windows-scripts\nREM Please share any improvements made!\n\nREM Code inspired by http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w\n\nIF [%1]==[/?] GOTO :help\nIF [%1]==[/help] GOTO :help\nIF [%1]==[--help] GOTO :help\nIF [%1]==[] GOTO :main\n\nECHO Unknown command: %1\nEXIT /b 1 \n\n:help\nECHO Refresh the environment variables in the console.\nECHO.\nECHO refreshEnv Refresh all environment variables.\nECHO refreshEnv /? Display this help.\nGOTO :EOF\n\n:main\nREM Because the environment variables may refer to other variables, we need a 2-step approach.\nREM One option is to use delayed variable evaluation, but this forces use of SETLOCAL and\nREM may pose problems for files with an '!' in the name.\nREM The option used here is to create a temporary batch file that will define all the variables.\n\nREM Check to make sure we don't overwrite an actual file.\nIF EXIST %TEMP%\\__refreshEnvironment.bat (\n ECHO Environment refresh failed!\n ECHO.\n ECHO This script uses a temporary file \"%TEMP%\\__refreshEnvironment.bat\", which already exists. The script was aborted in order to prevent accidental data loss. Delete this file to enable this script.\n EXIT /b 1\n)\n\nREM Read the system environment variables from the registry.\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\"`) DO (\n REM /I -> ignore casing, since PATH may also be called Path\n IF /I NOT [%%I]==[PATH] (\n ECHO SET %%I=%%K>>%TEMP%\\__refreshEnvironment.bat\n )\n)\n\nREM Read the user environment variables from the registry.\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY HKCU\\Environment`) DO (\n REM /I -> ignore casing, since PATH may also be called Path\n IF /I NOT [%%I]==[PATH] (\n ECHO SET %%I=%%K>>%TEMP%\\__refreshEnvironment.bat\n )\n)\n\nREM PATH is a special variable: it is automatically merged based on the values in the\nREM system and user variables.\nREM Read the PATH variable from the system and user environment variables.\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v PATH`) DO (\n ECHO SET PATH=%%K>>%TEMP%\\__refreshEnvironment.bat\n)\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY HKCU\\Environment /v PATH`) DO (\n ECHO SET PATH=%%PATH%%;%%K>>%TEMP%\\__refreshEnvironment.bat\n)\n\nREM Load the variable definitions from our temporary file.\nCALL %TEMP%\\__refreshEnvironment.bat\n\nREM Clean up after ourselves.\nDEL /Q %TEMP%\\__refreshEnvironment.bat\n\nECHO Environment successfully refreshed.\n</code></pre>\n"
},
{
"answer_id": 38087205,
"author": "Richard Woodruff",
"author_id": 6525677,
"author_profile": "https://Stackoverflow.com/users/6525677",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way to add a variable to the path without rebooting for the current session is to open the command prompt and type: </p>\n\n<pre><code>PATH=(VARIABLE);%path%\n</code></pre>\n\n<p>and press <kbd>enter</kbd>. </p>\n\n<p>to check if your variable loaded, type </p>\n\n<pre><code>PATH\n</code></pre>\n\n<p>and press <kbd>enter</kbd>. However, the variable will only be a part of the path until you reboot.</p>\n"
},
{
"answer_id": 41612026,
"author": "noname",
"author_id": 1365722,
"author_profile": "https://Stackoverflow.com/users/1365722",
"pm_score": 1,
"selected": false,
"text": "<p>I use this Powershell script to add to the <strong>PATH</strong> variable.\nWith a little adjustment it can work in your case too I believe.</p>\n\n<pre><code>#REQUIRES -Version 3.0\n\nif (-not (\"win32.nativemethods\" -as [type])) {\n # import sendmessagetimeout from win32\n add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @\"\n[DllImport(\"user32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\npublic static extern IntPtr SendMessageTimeout(\n IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,\n uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);\n\"@\n}\n\n$HWND_BROADCAST = [intptr]0xffff;\n$WM_SETTINGCHANGE = 0x1a;\n$result = [uintptr]::zero\n\nfunction global:ADD-PATH\n{\n [Cmdletbinding()]\n param ( \n [parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)] \n [string] $Folder\n )\n\n # See if a folder variable has been supplied.\n if (!$Folder -or $Folder -eq \"\" -or $Folder -eq $null) { \n throw 'No Folder Supplied. $ENV:PATH Unchanged'\n }\n\n # Get the current search path from the environment keys in the registry.\n $oldPath=$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH).Path\n\n # See if the new Folder is already in the path.\n if ($oldPath | Select-String -SimpleMatch $Folder){ \n return 'Folder already within $ENV:PATH' \n }\n\n # Set the New Path and add the ; in front\n $newPath=$oldPath+';'+$Folder\n Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH -Value $newPath -ErrorAction Stop\n\n # Show our results back to the world\n return 'This is the new PATH content: '+$newPath\n\n # notify all windows of environment block change\n [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, \"Environment\", 2, 5000, [ref]$result)\n}\n\nfunction global:REMOVE-PATH {\n [Cmdletbinding()]\n param ( \n [parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)]\n [String] $Folder\n )\n\n # See if a folder variable has been supplied.\n if (!$Folder -or $Folder -eq \"\" -or $Folder -eq $NULL) { \n throw 'No Folder Supplied. $ENV:PATH Unchanged'\n }\n\n # add a leading \";\" if missing\n if ($Folder[0] -ne \";\") {\n $Folder = \";\" + $Folder;\n }\n\n # Get the Current Search Path from the environment keys in the registry\n $newPath=$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH).Path\n\n # Find the value to remove, replace it with $NULL. If it's not found, nothing will change and you get a message.\n if ($newPath -match [regex]::Escape($Folder)) { \n $newPath=$newPath -replace [regex]::Escape($Folder),$NULL \n } else { \n return \"The folder you mentioned does not exist in the PATH environment\" \n }\n\n # Update the Environment Path\n Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH -Value $newPath -ErrorAction Stop\n\n # Show what we just did\n return 'This is the new PATH content: '+$newPath\n\n # notify all windows of environment block change\n [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, \"Environment\", 2, 5000, [ref]$result)\n}\n\n\n# Use ADD-PATH or REMOVE-PATH accordingly.\n\n#Anything to Add?\n\n#Anything to Remove?\n\nREMOVE-PATH \"%_installpath_bin%\"\n</code></pre>\n"
},
{
"answer_id": 42116634,
"author": "Vince",
"author_id": 6574586,
"author_profile": "https://Stackoverflow.com/users/6574586",
"pm_score": 4,
"selected": false,
"text": "<p>Restarting explorer did this for me, but only for new cmd terminals. </p>\n\n<p>The terminal I set the path could see the new Path variable already (in Windows 7).</p>\n\n<pre><code>taskkill /f /im explorer.exe && explorer.exe\n</code></pre>\n"
},
{
"answer_id": 44669930,
"author": "Jeroen van Dijk-Jun",
"author_id": 4336408,
"author_profile": "https://Stackoverflow.com/users/4336408",
"pm_score": 2,
"selected": false,
"text": "<p>If it concerns just one (or a few) specific vars you want to change, I think the easiest way is a <strong>workaround</strong>: just set in in your environment AND in your current console session</p>\n\n<ul>\n<li>Set will put the var in your current session</li>\n<li>SetX will put the var in the environment, but NOT in your current session</li>\n</ul>\n\n<p>I have this simple batch script to change my Maven from Java7 to Java8 (which are both env. vars) The batch-folder is in my <em>PATH</em> var so I can always call '<strong>j8</strong>' and within my console and in the environment my JAVA_HOME var gets changed:</p>\n\n<p><strong>j8.bat:</strong></p>\n\n<pre><code>@echo off\nset JAVA_HOME=%JAVA_HOME_8%\nsetx JAVA_HOME \"%JAVA_HOME_8%\"\n</code></pre>\n\n<p>Till now I find this working best and easiest. \nYou probably want this to be in one command, but it simply isn't there in Windows...</p>\n"
},
{
"answer_id": 44807922,
"author": "jolly",
"author_id": 2583495,
"author_profile": "https://Stackoverflow.com/users/2583495",
"pm_score": 8,
"selected": false,
"text": "<p>On Windows 7/8/10, you can install Chocolatey, which has a script for this built-in.</p>\n<p>After installing Chocolatey, just type <code>RefreshEnv.cmd</code>.</p>\n"
},
{
"answer_id": 45080843,
"author": "Daniel Fensterheim",
"author_id": 4948410,
"author_profile": "https://Stackoverflow.com/users/4948410",
"pm_score": 3,
"selected": false,
"text": "<p>The confusing thing might be that there are a few places to start the cmd from.\nIn my case I ran <strong>cmd from windows explorer</strong> and the environment <strong>variables did not change</strong> while when starting <strong>cmd from the \"run\"</strong> (windows key + r) the environment <strong>variables were changed</strong>.</p>\n\n<p>In my case I just had to <strong>kill the windows explorer process from the task manager and then restart it again from the task manager</strong>.</p>\n\n<p>Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.</p>\n"
},
{
"answer_id": 56562186,
"author": "Andy McRae",
"author_id": 2299775,
"author_profile": "https://Stackoverflow.com/users/2299775",
"pm_score": 2,
"selected": false,
"text": "<p>Thank you for posting this question which is quite interesting, even in 2019 (Indeed, it is not easy to renew the shell cmd since it is a single instance as mentioned above), because renewing environment variables in windows allows to accomplish many automation tasks without having to manually restart the command line. </p>\n\n<p>For example, we use this to allow software to be deployed and configured on a large number of machines that we reinstall regularly. And I must admit that having to restart the command line during the deployment of our software would be very impractical and would require us to find workarounds that are not necessarily pleasant. \nLet's get to our problem.\nWe proceed as follows. </p>\n\n<p>1 - We have a batch script that in turn calls a powershell script like this </p>\n\n<p><strong>[file: task.cmd]</strong>. </p>\n\n<p>cmd <code>> powershell.exe -executionpolicy unrestricted -File C:\\path_here\\refresh.ps1</code></p>\n\n<p>2 - After this, the refresh.ps1 script renews the environment variables using registry keys (GetValueNames(), etc.). \nThen, in the same powershell script, we just have to call the new environment variables available.\nFor example, in a typical case, if we have just installed nodeJS before with cmd using silent commands, after the function has been called, we can directly call npm to install, in the same session, particular packages like follows. </p>\n\n<p><strong>[file: refresh.ps1]</strong></p>\n\n<pre><code>function Update-Environment {\n $locations = 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',\n 'HKCU:\\Environment'\n $locations | ForEach-Object {\n $k = Get-Item $_\n $k.GetValueNames() | ForEach-Object {\n $name = $_\n $value = $k.GetValue($_)\n\n if ($userLocation -and $name -ieq 'PATH') {\n $env:Path += \";$value\"\n } else {\n\n Set-Item -Path Env:\\$name -Value $value\n }\n }\n $userLocation = $true\n }\n}\nUpdate-Environment\n#Here we can use newly added environment variables like for example npm install.. \nnpm install -g create-react-app serve\n</code></pre>\n\n<p>Once the powershell script is over, the cmd script goes on with other tasks.\nNow, one thing to keep in mind is that after the task is completed, cmd has still no access to the new environment variables, even if the powershell script has updated those in its own session. Thats why we do all the needed tasks in the powershell script which can call the same commands as cmd of course. </p>\n"
},
{
"answer_id": 59065248,
"author": "Charles Grunwald",
"author_id": 1017636,
"author_profile": "https://Stackoverflow.com/users/1017636",
"pm_score": 2,
"selected": false,
"text": "<p>The solution I've been using for a few years now:</p>\n\n<pre><code>@echo off\nrem Refresh PATH from registry.\nsetlocal\nset USR_PATH=\nset SYS_PATH=\nfor /F \"tokens=3* skip=2\" %%P in ('%SystemRoot%\\system32\\reg.exe query \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v PATH') do @set \"SYS_PATH=%%P %%Q\"\nfor /F \"tokens=3* skip=2\" %%P in ('%SystemRoot%\\system32\\reg.exe query \"HKCU\\Environment\" /v PATH') do @set \"USR_PATH=%%P %%Q\"\nif \"%SYS_PATH:~-1%\"==\" \" set \"SYS_PATH=%SYS_PATH:~0,-1%\"\nif \"%USR_PATH:~-1%\"==\" \" set \"USR_PATH=%USR_PATH:~0,-1%\"\nendlocal & call set \"PATH=%SYS_PATH%;%USR_PATH%\"\ngoto :EOF\n</code></pre>\n\n<p><strong>Edit:</strong> Woops, here's the updated version.</p>\n"
},
{
"answer_id": 69408975,
"author": "Badr Elmers",
"author_id": 3020379,
"author_profile": "https://Stackoverflow.com/users/3020379",
"pm_score": 3,
"selected": false,
"text": "<p>I made a better alternative to the Chocolatey refreshenv for cmd and cygwin which solves a lot of problems like:</p>\n<ul>\n<li><p>The Chocolatey <strong>refreshenv</strong> is so <strong>bad</strong> if the variable have some\ncmd meta-characters, see this test:</p>\n<p>add this to the path in HKCU\\Environment: <code>test & echo baaaaaaaaaad</code>,\nand run the chocolatey <code>refreshenv</code> you will see that it prints\n<code>baaaaaaaaaad</code> which is very bad, and the new path is not added to\nyour path variable.</p>\n<p>This script solve this and you can test it with any meta-character, even something so bad like:</p>\n<pre><code>; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \\ / " : ? * = . - _ & echo baaaad\n</code></pre>\n</li>\n<li><p>refreshenv adds only <strong>system</strong> and <strong>user</strong>\nenvironment variables, but CMD adds <strong>volatile</strong> variables too\n(HKCU\\Volatile Environment). This script will merge all the three and\n<strong>remove any duplicates</strong>.</p>\n</li>\n<li><p>refreshenv reset your PATH. This script append the new path to the\nold path of the parent script which called this script. It is better\nthan overwriting the old path, otherwise it will delete any newly\nadded path by the parent script.</p>\n</li>\n<li><p>This script solve this problem described in a comment here by @Gene\nMayevsky: refreshenv <em>modifies env variables TEMP and TMP replacing\nthem with values stored in HKCU\\Environment. In my case I run the\nscript to update env variables modified by Jenkins job on a slave\nthat's running under SYSTEM account, so TEMP and TMP get substituted\nby %USERPROFILE%\\AppData\\Local\\Temp instead of C:\\Windows\\Temp. This\nbreaks build because linker cannot open system profile's Temp folder.</em></p>\n</li>\n</ul>\n<p>I made one script for cmd and another for cygwin/bash,\nyou can found them here: <a href=\"https://github.com/badrelmers/RefrEnv\" rel=\"noreferrer\">https://github.com/badrelmers/RefrEnv</a></p>\n<h2>For cmd</h2>\n<p>This script uses vbscript so it works in all windows versions <strong>xp+</strong></p>\n<p>to use it save it as <strong>refrenv.bat</strong> and call it with <code>call refrenv.bat</code></p>\n<pre class=\"lang-vbs prettyprint-override\"><code><!-- : Begin batch script\n@echo off\nREM PUSHD "%~dp0"\n\n\nREM author: Badr Elmers 2021\nREM description: refrenv = refresh environment. this is a better alternative to the chocolatey refreshenv for cmd\nREM https://github.com/badrelmers/RefrEnv\nREM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w\n\nREM ___USAGE_____________________________________________________________\nREM usage: \nREM call refrenv.bat full refresh. refresh all non critical variables*, and refresh the PATH\n\nREM debug:\nREM to debug what this script do create this variable in your parent script like that\nREM set debugme=yes\nREM then the folder containing the files used to set the variables will be open. Then see\nREM _NewEnv.cmd this is the file which run inside your script to setup the new variables, you\nREM can also revise the intermediate files _NewEnv.cmd_temp_.cmd and _NewEnv.cmd_temp2_.cmd \nREM (those two contains all the variables before removing the duplicates and the unwanted variables)\n\n\nREM you can also put this script in windows\\systems32 or another place in your %PATH% then call it from an interactive console by writing refrenv\n\nREM *critical variables: are variables which belong to cmd/windows and should not be refreshed normally like:\nREM - windows vars:\nREM ALLUSERSPROFILE APPDATA CommonProgramFiles CommonProgramFiles(x86) CommonProgramW6432 COMPUTERNAME ComSpec HOMEDRIVE HOMEPATH LOCALAPPDATA LOGONSERVER NUMBER_OF_PROCESSORS OS PATHEXT PROCESSOR_ARCHITECTURE PROCESSOR_ARCHITEW6432 PROCESSOR_IDENTIFIER PROCESSOR_LEVEL PROCESSOR_REVISION ProgramData ProgramFiles ProgramFiles(x86) ProgramW6432 PUBLIC SystemDrive SystemRoot TEMP TMP USERDOMAIN USERDOMAIN_ROAMINGPROFILE USERNAME USERPROFILE windir SESSIONNAME\n\n\nREM ___INFO_____________________________________________________________\nREM :: this script reload environment variables inside cmd every time you want environment changes to propagate, so you do not need to restart cmd after setting a new variable with setx or when installing new apps which add new variables ...etc\n\n\nREM This is a better alternative to the chocolatey refreshenv for cmd, which solves a lot of problems like:\n\nREM The Chocolatey refreshenv is so bad if the variable have some cmd meta-characters, see this test:\n REM add this to the path in HKCU\\Environment: test & echo baaaaaaaaaad, and run the chocolatey refreshenv you will see that it prints baaaaaaaaaad which is very bad, and the new path is not added to your path variable.\n REM This script solve this and you can test it with any meta-character, even something so bad like:\n REM ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \\ / " : ? * = . - _ & echo baaaad\n \nREM refreshenv adds only system and user environment variables, but CMD adds volatile variables too (HKCU\\Volatile Environment). This script will merge all the three and remove any duplicates.\n\nREM refreshenv reset your PATH. This script append the new path to the old path of the parent script which called this script. It is better than overwriting the old path, otherwise it will delete any newly added path by the parent script.\n\nREM This script solve this problem described in a comment by @Gene Mayevsky: refreshenv modifies env variables TEMP and TMP replacing them with values stored in HKCU\\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\\AppData\\Local\\Temp instead of C:\\Windows\\Temp. This breaks build because linker cannot open system profile's Temp folder.\n\nREM ________\nREM this script solve things like that too:\nREM The confusing thing might be that there are a few places to start the cmd from. In my case I run cmd from windows explorer and the environment variables did not change while when starting cmd from the "run" (windows key + r) the environment variables were changed.\n\nREM In my case I just had to kill the windows explorer process from the task manager and then restart it again from the task manager.\nREM Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.\n\nREM my conclusion:\nREM if I add a new variable with setx, i can access it in cmd only if i run cmd as admin, without admin right i have to restart explorer to see that new variable. but running this script inside my script (who sets the variable with setx) solve this problem and i do not have to restart explorer\n\n\nREM ________\nREM windows recreate the path using three places at less:\nREM the User namespace: HKCU\\Environment\nREM the System namespace: HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\nREM the Session namespace: HKCU\\Volatile Environment\nREM but the original chocolatey script did not add the volatile path. This script will merge all the three and remove any duplicates. this is what windows do by default too\n\nREM there is this too which cmd seems to read when first running, but it contains only TEMP and TMP,so i will not use it\nREM HKEY_USERS\\.DEFAULT\\Environment\n\n\nREM ___TESTING_____________________________________________________________\nREM to test this script with extreme cases do\n REM :: Set a bad variable\n REM add a var in reg HKCU\\Environment as the following, and see that echo is not executed. if you use refreshenv of chocolatey you will see that echo is executed which is so bad!\n REM so save this in reg:\n REM all 32 characters: & % ' ( ) ~ + @ # $ { } [ ] ; , ` ! ^ | > < \\ / " : ? * = . - _ & echo baaaad\n REM and this:\n REM (^.*)(Form Product=")([^"]*") FormType="[^"]*" FormID="([0-9][0-9]*)".*$\n REM and use set to print those variables and see if they are saved without change ; refreshenv fail dramatically with those variables\n \n \nREM invalid characters (illegal characters in file names) in Windows using NTFS\nREM \\ / : * ? " < > | and ^ in FAT \n\n\n\nREM __________________________________________________________________________________________\nREM __________________________________________________________________________________________\nREM __________________________________________________________________________________________\nREM this is a hybrid script which call vbs from cmd directly\nREM :: The only restriction is the batch code cannot contain - - > (without space between - - > of course)\nREM :: The only restriction is the VBS code cannot contain </script>.\nREM :: The only risk is the undocumented use of "%~f0?.wsf" as the script to load. Somehow the parser properly finds and loads the running .BAT script "%~f0", and the ?.wsf suffix mysteriously instructs CSCRIPT to interpret the script as WSF. Hopefully MicroSoft will never disable that "feature".\nREM :: https://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a\n\nif "%debugme%"=="yes" (\n echo RefrEnv - Refresh the Environment for CMD - ^(Debug enabled^)\n) else (\n echo RefrEnv - Refresh the Environment for CMD\n)\n\nset "TEMPDir=%TEMP%\\refrenv"\nIF NOT EXIST "%TEMPDir%" mkdir "%TEMPDir%"\nset "outputfile=%TEMPDir%\\_NewEnv.cmd"\n\n\nREM detect if DelayedExpansion is enabled\nREM It relies on the fact, that the last caret will be removed only in delayed mode.\nREM https://www.dostips.com/forum/viewtopic.php?t=6496\nset "DelayedExpansionState=IsDisabled"\nIF "^!" == "^!^" (\n REM echo DelayedExpansion is enabled\n set "DelayedExpansionState=IsEnabled"\n)\n\n\nREM :: generate %outputfile% which contain all the new variables\nREM cscript //nologo "%~f0?.wsf" %1\ncscript //nologo "%~f0?.wsf" "%outputfile%" %DelayedExpansionState%\n\n\nREM ::set the new variables generated with vbscript script above\nREM for this to work always it is necessary to use DisableDelayedExpansion or escape ! and ^ when using EnableDelayedExpansion, but this script already solve this, so no worry about that now, thanks to God\nREM test it with some bad var like:\nREM all 32 characters: ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \\ / " : ? * = . - _ & echo baaaad\nREM For /f delims^=^ eol^= %%a in (%outputfile%) do %%a\nREM for /f "delims== tokens=1,2" %%G in (%outputfile%) do set "%%G=%%H"\nFor /f delims^=^ eol^= %%a in (%outputfile%) do set %%a\n\n\nREM for safely print a variable with bad charachters do:\nREM SETLOCAL EnableDelayedExpansion\nREM echo "!z9!"\nREM or\nREM set z9\nREM but generally paths and environment variables should not have bad metacharacters, but it is not a rule!\n\n\nif "%debugme%"=="yes" (\n explorer "%TEMPDir%"\n) else (\n rmdir /Q /S "%TEMPDir%"\n)\n\nREM cleanup\nset "TEMPDir="\nset "outputfile="\nset "DelayedExpansionState="\nset "debugme="\n\n\nREM pause\nexit /b\n\n\n\nREM #############################################################################\nREM :: to run jscript you have to put <script language="JScript"> directly after ----- Begin wsf script --->\n----- Begin wsf script --->\n<job><script language="VBScript">\nREM #############################################################################\nREM ### put you code here #######################################################\nREM #############################################################################\n\nREM based on itsadok script from here\nREM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w\n\nREM and it is faster as stated by this comment\nREM While I prefer the Chocolatey code-wise for being pure batch code, overall I decided to use this one, since it's faster. (~0.3 seconds instead of ~1 second -- which is nice, since I use it frequently in my Explorer "start cmd here" entry) – \n\nREM and it is safer based on my tests, the Chocolatey refreshenv is so bad if the variable have some cmd metacharacters\n\n\nConst ForReading = 1 \nConst ForWriting = 2\nConst ForAppending = 8 \n\nSet WshShell = WScript.CreateObject("WScript.Shell")\nfilename=WScript.Arguments.Item(0)\nDelayedExpansionState=WScript.Arguments.Item(1)\n\nTMPfilename=filename & "_temp_.cmd"\nSet fso = CreateObject("Scripting.fileSystemObject")\nSet tmpF = fso.CreateTextFile(TMPfilename, TRUE)\n\n\nset oEnvS=WshShell.Environment("System")\nfor each sitem in oEnvS\n tmpF.WriteLine(sitem)\nnext\nSystemPath = oEnvS("PATH")\n\nset oEnvU=WshShell.Environment("User")\nfor each sitem in oEnvU\n tmpF.WriteLine(sitem)\nnext\nUserPath = oEnvU("PATH")\n\nset oEnvV=WshShell.Environment("Volatile")\nfor each sitem in oEnvV\n tmpF.WriteLine(sitem)\nnext\nVolatilePath = oEnvV("PATH")\n\nset oEnvP=WshShell.Environment("Process")\nREM i will not save the process env but only its path, because it have strange variables like =::=::\\ and =F:=.... which seems to be added by vbscript\nREM for each sitem in oEnvP\n REM tmpF.WriteLine(sitem)\nREM next\nREM here we add the actual session path, so we do not reset the original path, because maybe the parent script added some folders to the path, If we need to reset the path then comment the following line\nProcessPath = oEnvP("PATH")\n\nREM merge System, User, Volatile, and process PATHs\nNewPath = SystemPath & ";" & UserPath & ";" & VolatilePath & ";" & ProcessPath\n\n\nREM ________________________________________________________________\nREM :: remove duplicates from path\nREM :: expand variables so they become like windows do when he read reg and create path, then Remove duplicates without sorting \n REM why i will clean the path from duplicates? because:\n REM the maximum string length in cmd is 8191 characters. But string length doesnt mean that you can save 8191 characters in a variable because also the assignment belongs to the string. you can save 8189 characters because the remaining 2 characters are needed for "a="\n \n REM based on my tests: \n REM when i open cmd as user , windows does not remove any duplicates from the path, and merge system+user+volatil path\n REM when i open cmd as admin, windows do: system+user path (here windows do not remove duplicates which is stupid!) , then it adds volatil path after removing from it any duplicates \n\nREM ' https://www.rosettacode.org/wiki/Remove_duplicate_elements#VBScript\nFunction remove_duplicates(list)\n arr = Split(list,";")\n Set dict = CreateObject("Scripting.Dictionary")\n REM ' force dictionary compare to be case-insensitive , uncomment to force case-sensitive\n dict.CompareMode = 1\n\n For i = 0 To UBound(arr)\n If dict.Exists(arr(i)) = False Then\n dict.Add arr(i),""\n End If\n Next\n For Each key In dict.Keys\n tmp = tmp & key & ";"\n Next\n remove_duplicates = Left(tmp,Len(tmp)-1)\nEnd Function\n \nREM expand variables\nNewPath = WshShell.ExpandEnvironmentStrings(NewPath)\nREM remove duplicates\nNewPath=remove_duplicates(NewPath)\n\nREM remove_duplicates() will add a ; to the end so lets remove it if the last letter is ;\nIf Right(NewPath, 1) = ";" Then \n NewPath = Left(NewPath, Len(NewPath) - 1) \nEnd If\n \ntmpF.WriteLine("PATH=" & NewPath)\ntmpF.Close\n\nREM ________________________________________________________________\nREM :: exclude setting variables which may be dangerous to change\n\n REM when i run a script from task scheduler using SYSTEM user the following variables are the differences between the scheduler env and a normal cmd script, so i will not override those variables\n REM APPDATA=D:\\Users\\LLED2\\AppData\\Roaming\n REM APPDATA=D:\\Windows\\system32\\config\\systemprofile\\AppData\\Roaming\n\n REM LOCALAPPDATA=D:\\Users\\LLED2\\AppData\\Local\n REM LOCALAPPDATA=D:\\Windows\\system32\\config\\systemprofile\\AppData\\Local\n\n REM TEMP=D:\\Users\\LLED2\\AppData\\Local\\Temp\n REM TEMP=D:\\Windows\\TEMP\n\n REM TMP=D:\\Users\\LLED2\\AppData\\Local\\Temp\n REM TMP=D:\\Windows\\TEMP\n\n REM USERDOMAIN=LLED2-PC\n REM USERDOMAIN=WORKGROUP\n\n REM USERNAME=LLED2\n REM USERNAME=LLED2-PC$\n\n REM USERPROFILE=D:\\Users\\LLED2\n REM USERPROFILE=D:\\Windows\\system32\\config\\systemprofile\n\n REM i know this thanks to this comment\n REM The solution is good but it modifies env variables TEMP and TMP replacing them with values stored in HKCU\\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\\AppData\\Local\\Temp instead of C:\\Windows\\Temp. This breaks build because linker cannot open system profile's Temp folder. – Gene Mayevsky Sep 26 '19 at 20:51\n\n\nREM Delete Lines of a Text File Beginning with a Specified String\nREM those are the variables which should not be changed by this script \narrBlackList = Array("ALLUSERSPROFILE=", "APPDATA=", "CommonProgramFiles=", "CommonProgramFiles(x86)=", "CommonProgramW6432=", "COMPUTERNAME=", "ComSpec=", "HOMEDRIVE=", "HOMEPATH=", "LOCALAPPDATA=", "LOGONSERVER=", "NUMBER_OF_PROCESSORS=", "OS=", "PATHEXT=", "PROCESSOR_ARCHITECTURE=", "PROCESSOR_ARCHITEW6432=", "PROCESSOR_IDENTIFIER=", "PROCESSOR_LEVEL=", "PROCESSOR_REVISION=", "ProgramData=", "ProgramFiles=", "ProgramFiles(x86)=", "ProgramW6432=", "PUBLIC=", "SystemDrive=", "SystemRoot=", "TEMP=", "TMP=", "USERDOMAIN=", "USERDOMAIN_ROAMINGPROFILE=", "USERNAME=", "USERPROFILE=", "windir=", "SESSIONNAME=")\n\nSet objFS = CreateObject("Scripting.FileSystemObject")\nSet objTS = objFS.OpenTextFile(TMPfilename, ForReading)\nstrContents = objTS.ReadAll\nobjTS.Close\n\nTMPfilename2= filename & "_temp2_.cmd"\narrLines = Split(strContents, vbNewLine)\nSet objTS = objFS.OpenTextFile(TMPfilename2, ForWriting, True)\n\nREM this is the equivalent of findstr /V /I /L or grep -i -v , i don t know a better way to do it, but it works fine\nFor Each strLine In arrLines\n bypassThisLine=False\n For Each BlackWord In arrBlackList\n If Left(UCase(LTrim(strLine)),Len(BlackWord)) = UCase(BlackWord) Then\n bypassThisLine=True\n End If\n Next\n If bypassThisLine=False Then\n objTS.WriteLine strLine\n End If\nNext\n\nREM ____________________________________________________________\nREM :: expand variables because registry save some variables as unexpanded %....%\nREM :: and escape ! and ^ for cmd EnableDelayedExpansion mode\n\nset f=fso.OpenTextFile(TMPfilename2,ForReading)\nREM Write file: ForAppending = 8 ForReading = 1 ForWriting = 2 , True=create file if not exist\nset fW=fso.OpenTextFile(filename,ForWriting,True)\nDo Until f.AtEndOfStream\n LineContent = f.ReadLine\n REM expand variables\n LineContent = WshShell.ExpandEnvironmentStrings(LineContent)\n \n REM _____this part is so important_____\n REM if cmd delayedexpansion is enabled in the parent script which calls this script then bad thing happen to variables saved in the registry if they contain ! . if var have ! then ! and ^ are removed; if var do not have ! then ^ is not removed . to understand what happens read this :\n REM how cmd delayed expansion parse things\n REM https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912\n REM For each parsed token, first check if it contains any !. If not, then the token is not parsed - important for ^ characters. If the token does contain !, then scan each character from left to right:\n REM - If it is a caret (^) the next character has no special meaning, the caret itself is removed\n REM - If it is an exclamation mark, search for the next exclamation mark (carets are not observed anymore), expand to the value of the variable.\n REM - Consecutive opening ! are collapsed into a single !\n REM - Any remaining unpaired ! is removed\n REM ...\n REM Look at next string of characters, breaking before !, :, or <LF>, and call them VAR\n\n REM conclusion:\n REM when delayedexpansion is enabled and var have ! then i have to escape ^ and ! ,BUT IF VAR DO NOT HAVE ! THEN DO NOT ESCAPE ^ .this made me crazy to discover\n REM when delayedexpansion is disabled then i do not have to escape anything\n \n If DelayedExpansionState="IsEnabled" Then\n If InStr(LineContent, "!") > 0 Then\n LineContent=Replace(LineContent,"^","^^")\n LineContent=Replace(LineContent,"!","^!")\n End If\n End If\n REM __________\n \n fW.WriteLine(LineContent)\nLoop\n\nf.Close\nfW.Close\n\nREM #############################################################################\nREM ### end of vbscript code ####################################################\nREM #############################################################################\nREM this must be at the end for the hybrid trick, do not remove it\n</script></job>\n\n\n</code></pre>\n<h2>For cygwin/bash:</h2>\n<p>I cannot post it here I reached the post limit, so download it from <a href=\"https://github.com/badrelmers/RefrEnv/blob/main/refrenv.sh\" rel=\"noreferrer\">here</a></p>\n<p>call it from bash with: <code>source refrenv.sh</code></p>\n<h2>For Powershell:</h2>\n<p>download it from <a href=\"https://github.com/badrelmers/RefrEnv/blob/main/refrenv.ps1\" rel=\"noreferrer\">here</a></p>\n<p>Call it from Powershell with: <code>. .\\refrenv.ps1</code></p>\n"
},
{
"answer_id": 70504233,
"author": "Amey Mahajan",
"author_id": 15311773,
"author_profile": "https://Stackoverflow.com/users/15311773",
"pm_score": 0,
"selected": false,
"text": "<p>I just wanted to state that, those who use Anaconda, when you use the chocolatey <code>Refreshenv</code> command; all the environment variables associated with conda will be lost.\nTo counter this, the best way is to restart CMD. :(</p>\n"
},
{
"answer_id": 73965028,
"author": "Greg",
"author_id": 3934764,
"author_profile": "https://Stackoverflow.com/users/3934764",
"pm_score": 0,
"selected": false,
"text": "<p>This doesn't directly answer your question but if you just want interprocess communication, and you can use PowerShell, you can just use the Clipboard.</p>\n<p>In one process</p>\n<p>Set-Clipboard("MyText")</p>\n<p>In separate process</p>\n<p>$clipValue=Get-Clipboard</p>\n<p>then you can use clipValue as any other string. This actually give you the ability to send the entire list of environment variables to another process using a CSV text string</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?
|
You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.
Create a file named `resetvars.vbs` containing this code, and save it on the path:
```vb
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("System")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")
set oEnv=oShell.Environment("User")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close
```
create another file name resetvars.bat containing this code, same location:
```vb
@echo off
%~dp0resetvars.vbs
call "%TEMP%\resetvars.bat"
```
When you want to refresh the environment variables, just run `resetvars.bat`
---
*Apologetics*:
The two main problems I had coming up with this solution were
**a.** I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and
**b.** the PATH environment variable is a concatenation of the user and the system PATH variables.
I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.
I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.
**Note**: this script does not delete variables.
This can probably be improved.
**ADDED**
If you need to export the environment from one cmd window to another, use this script (let's call it `exportvars.vbs`):
```vb
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("Process")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
oFile.Close
```
Run `exportvars.vbs` in the window you want to export **from**, then switch to the window you want to export **to**, and type:
```vb
"%TEMP%\resetvars.bat"
```
|
171,596 |
<p>After having implemented the strategy pattern, I wanted to make an array of the interface-type, to which I can then add any concrete type. </p>
<p>For those who don't know the strategy pattern:
<a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Strategy_pattern</a>
In this particular example I would want to make a StrategyInterface array, which I can then fill with concrete type's A, B and C. However, because this is an abstract class, I can't get it done. Is there a way to do this, or is it completely impossible, without removing the abstract method?</p>
|
[
{
"answer_id": 171599,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 2,
"selected": false,
"text": "<p>store pointers not objects..... use boost::shared_ptr if you are wanting to store objects.</p>\n"
},
{
"answer_id": 171605,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "<p>Make the array store pointers to the interface type:</p>\n\n<pre><code>typedef std::vector<Interface *> Array;\nArray myArray;\nmyArray.push_back(new A());\n</code></pre>\n\n<p>Additionally, you can use ptr_vector which manages memory for you:</p>\n\n<pre><code>typedef boost::ptr_vector<Interface> Array;\n// the rest is the same\n</code></pre>\n"
},
{
"answer_id": 171608,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 1,
"selected": false,
"text": "<p>errr, for example... \n std::vector< boost::shared_ptr< AbstractStrategy > > </p>\n\n<p></p>\n"
},
{
"answer_id": 171679,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 1,
"selected": false,
"text": "<p>How about using boost any?</p>\n\n<p>Here's an example of what it would look like</p>\n\n<pre><code>#include <list>\n#include <boost/any.hpp>\n\nusing boost::any_cast;\ntypedef std::list<boost::any> many;\n\nvoid append_int(many & values, int value)\n{\n boost::any to_append = value;\n values.push_back(to_append);\n}\n\nvoid append_string(many & values, const std::string & value)\n{\n values.push_back(value);\n}\n\nvoid append_char_ptr(many & values, const char * value)\n{\n values.push_back(value);\n}\n\nvoid append_any(many & values, const boost::any & value)\n{\n values.push_back(value);\n}\n\nvoid append_nothing(many & values)\n{\n values.push_back(boost::any());\n}\n</code></pre>\n\n<p>Seems nice and elegant, plus you get well tested code and can treat your values as objects instead of pointers</p>\n\n<p>Note: These function names are informative, but you could use overriding to have a single interface.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23163/"
] |
After having implemented the strategy pattern, I wanted to make an array of the interface-type, to which I can then add any concrete type.
For those who don't know the strategy pattern:
<http://en.wikipedia.org/wiki/Strategy_pattern>
In this particular example I would want to make a StrategyInterface array, which I can then fill with concrete type's A, B and C. However, because this is an abstract class, I can't get it done. Is there a way to do this, or is it completely impossible, without removing the abstract method?
|
Make the array store pointers to the interface type:
```
typedef std::vector<Interface *> Array;
Array myArray;
myArray.push_back(new A());
```
Additionally, you can use ptr\_vector which manages memory for you:
```
typedef boost::ptr_vector<Interface> Array;
// the rest is the same
```
|
171,640 |
<p>In multi-threaded code, when an instance may be read or written by multiple threads, they need to be locked on to perform these operations safely.</p>
<p>To avoid the repetition of creating an object to lock on and writing a bunch of lock statements through code, I've created a generic class to handle the locking. </p>
<p>Am I missing anything, conceptually? This should work, right?</p>
<pre><code>public class Locked<T> where T : new()
{
private readonly object locker = new object();
private T value;
public Locked()
: this(default(T))
{ }
public Locked(T value)
{
this.value = value;
}
public T Get()
{
lock (this.locker)
{
return this.value;
}
}
public void Set(T value)
{
lock (this.locker)
{
this.value = value;
}
}
}
</code></pre>
<p>And an example of it being used in a class:</p>
<pre><code>private Locked<bool> stopWorkerThread = new Locked<bool>();
public void WorkerThreadEntryPoint()
{
while (true)
{
if (this.stopWorkerThread.Get())
{
break;
}
</code></pre>
<p>Also, how would I test something like this, in an automated way (e.g. create a unit test)?</p>
<p>Lastly, what can I do to implement a ++ and -- operator, to avoid this:</p>
<pre><code> this.runningThreads.Set(this.runningThreads.Get() + 1);
</code></pre>
|
[
{
"answer_id": 171659,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>That only locks for the duration of the get/set; of course, in many common cases this will be atomic anyway, simply due to to data size.</p>\n\n<p>However, in reality most locks need to span more than this, in the same way that collections locking over just the Add etc don't help much - a caller typically needs a single lock to span the \"is it there? if so update, else add\" sequence.</p>\n\n<p>For something as simple as a bool, \"volatile\" might solve the problem a lot more simply - especially if it is just for a loop exit.</p>\n\n<p>You might also want to consider [MethodImpl(MethodImplOptions.Synchronized)] - although personally I prefer a private lock object (like you have used) to prevent issues with external people locking on the object (the above uses \"this\" as the lock).</p>\n\n<p>For unit testing this, you'd need something to prove it broken first - which would be hard since the operations are so small (and already atomic for most data types). One of the other things it avoids (that volatile also fixes) is caching in a register, but again that is an optimisation and hard to force to prove it is broken.</p>\n\n<p>If you are interested in a lock-wrapper, you might consider existing code like <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/locking.html\" rel=\"nofollow noreferrer\">this</a>.</p>\n"
},
{
"answer_id": 171665,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>Your code above has quite a few potential and real multi-threading issues, and I wouldn't use something like it in a real-world situation. For example:</p>\n\n<pre><code>this.runningThreads.Set(this.runningThreads.Get() + 1);\n</code></pre>\n\n<p>There is a pretty obvious race condition here. When the <code>Get()</code> call returns, the object is no longer locked. To do a real post or pre increment, the counter would need to be locked from before the <code>Get</code> to after the <code>Set</code>.</p>\n\n<p>Also you don't always need to do a full lock if all you are doing is synchronous reads.</p>\n\n<p>A better lock interface would (I think) require you to explicitly lock the instance where you need to do it. My experience is mainly with C++ so I can't recommend a full implementation, but my preferred syntax might look something like this:</p>\n\n<pre><code>using (Locked<T> lock = Locked<T>(instance))\n{\n // write value\n instance++;\n}\n\n// read value\nprint instance;\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] |
In multi-threaded code, when an instance may be read or written by multiple threads, they need to be locked on to perform these operations safely.
To avoid the repetition of creating an object to lock on and writing a bunch of lock statements through code, I've created a generic class to handle the locking.
Am I missing anything, conceptually? This should work, right?
```
public class Locked<T> where T : new()
{
private readonly object locker = new object();
private T value;
public Locked()
: this(default(T))
{ }
public Locked(T value)
{
this.value = value;
}
public T Get()
{
lock (this.locker)
{
return this.value;
}
}
public void Set(T value)
{
lock (this.locker)
{
this.value = value;
}
}
}
```
And an example of it being used in a class:
```
private Locked<bool> stopWorkerThread = new Locked<bool>();
public void WorkerThreadEntryPoint()
{
while (true)
{
if (this.stopWorkerThread.Get())
{
break;
}
```
Also, how would I test something like this, in an automated way (e.g. create a unit test)?
Lastly, what can I do to implement a ++ and -- operator, to avoid this:
```
this.runningThreads.Set(this.runningThreads.Get() + 1);
```
|
That only locks for the duration of the get/set; of course, in many common cases this will be atomic anyway, simply due to to data size.
However, in reality most locks need to span more than this, in the same way that collections locking over just the Add etc don't help much - a caller typically needs a single lock to span the "is it there? if so update, else add" sequence.
For something as simple as a bool, "volatile" might solve the problem a lot more simply - especially if it is just for a loop exit.
You might also want to consider [MethodImpl(MethodImplOptions.Synchronized)] - although personally I prefer a private lock object (like you have used) to prevent issues with external people locking on the object (the above uses "this" as the lock).
For unit testing this, you'd need something to prove it broken first - which would be hard since the operations are so small (and already atomic for most data types). One of the other things it avoids (that volatile also fixes) is caching in a register, but again that is an optimisation and hard to force to prove it is broken.
If you are interested in a lock-wrapper, you might consider existing code like [this](http://www.yoda.arachsys.com/csharp/miscutil/usage/locking.html).
|
171,641 |
<p>When maintaining a <code>COM</code> interface should an empty <code>BSTR</code> be treated the same way as <code>NULL</code>?
In other words should these two function calls produce the same result?</p>
<pre><code> // Empty BSTR
CComBSTR empty(L""); // Or SysAllocString(L"")
someObj->Foo(empty);
// NULL BSTR
someObj->Foo(NULL);
</code></pre>
|
[
{
"answer_id": 171644,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 5,
"selected": true,
"text": "<p>Yes - a NULL BSTR is the same as an empty one. I remember we had all sorts of bugs that were uncovered when we switched from VS6 to 2003 - the CComBSTR class had a change to the default constructor that allocated it using NULL rather than an empty string. This happens when you for example treat a BSTR as a regular C style string and pass it to some function like <code>strlen</code>, or try to initialise a <code>std::string</code> with it.</p>\n<p>Eric Lippert discusses BSTR's in great detail in <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/erics-complete-guide-to-bstr-semantics\" rel=\"nofollow noreferrer\">Eric's Complete Guide To BSTR Semantics</a>:</p>\n<blockquote>\n<p>Let me list the differences first and\nthen discuss each point in\nexcruciating detail.</p>\n<ol>\n<li><p>A BSTR must have identical\nsemantics for NULL and for "". A PWSZ\nfrequently has different semantics for\nthose.</p>\n</li>\n<li><p>A BSTR must be allocated and freed\nwith the SysAlloc* family of\nfunctions. A PWSZ can be an\nautomatic-storage buffer from the\nstack or allocated with malloc, new,\nLocalAlloc or any other memory\nallocator.</p>\n</li>\n<li><p>A BSTR is of fixed length. A PWSZ\nmay be of any length, limited only by\nthe amount of valid memory in its\nbuffer.</p>\n</li>\n<li><p>A BSTR always points to the first\nvalid character in the buffer. A PWSZ\nmay be a pointer to the middle or end\nof a string buffer.</p>\n</li>\n<li><p>When allocating an n-byte BSTR you\nhave room for n/2 wide characters.\nWhen you allocate n bytes for a PWSZ\nyou can store n / 2 - 1 characters --\nyou have to leave room for the null.</p>\n</li>\n<li><p>A BSTR may contain any Unicode data\nincluding the zero character. A PWSZ\nnever contains the zero character\nexcept as an end-of-string marker.\nBoth a BSTR and a PWSZ always have a\nzero character after their last valid\ncharacter, but in a BSTR a valid\ncharacter may be a zero character.</p>\n</li>\n<li><p>A BSTR may actually contain an odd\nnumber of bytes -- it may be used for\nmoving binary data around. A PWSZ is\nalmost always an even number of bytes\nand used only for storing Unicode\nstrings.</p>\n</li>\n</ol>\n</blockquote>\n"
},
{
"answer_id": 171818,
"author": "HS.",
"author_id": 1398,
"author_profile": "https://Stackoverflow.com/users/1398",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way to handle this dilemma is to use CComBSTR and check for .Length() to be zero. That works for both empty and NULL values.</p>\n\n<p>However, keep in mind, empty BSTR must be released or there will be a memory leak. I saw some of those recently in other's code. Quite hard to find, if you are not looking carefully.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
When maintaining a `COM` interface should an empty `BSTR` be treated the same way as `NULL`?
In other words should these two function calls produce the same result?
```
// Empty BSTR
CComBSTR empty(L""); // Or SysAllocString(L"")
someObj->Foo(empty);
// NULL BSTR
someObj->Foo(NULL);
```
|
Yes - a NULL BSTR is the same as an empty one. I remember we had all sorts of bugs that were uncovered when we switched from VS6 to 2003 - the CComBSTR class had a change to the default constructor that allocated it using NULL rather than an empty string. This happens when you for example treat a BSTR as a regular C style string and pass it to some function like `strlen`, or try to initialise a `std::string` with it.
Eric Lippert discusses BSTR's in great detail in [Eric's Complete Guide To BSTR Semantics](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/erics-complete-guide-to-bstr-semantics):
>
> Let me list the differences first and
> then discuss each point in
> excruciating detail.
>
>
> 1. A BSTR must have identical
> semantics for NULL and for "". A PWSZ
> frequently has different semantics for
> those.
> 2. A BSTR must be allocated and freed
> with the SysAlloc\* family of
> functions. A PWSZ can be an
> automatic-storage buffer from the
> stack or allocated with malloc, new,
> LocalAlloc or any other memory
> allocator.
> 3. A BSTR is of fixed length. A PWSZ
> may be of any length, limited only by
> the amount of valid memory in its
> buffer.
> 4. A BSTR always points to the first
> valid character in the buffer. A PWSZ
> may be a pointer to the middle or end
> of a string buffer.
> 5. When allocating an n-byte BSTR you
> have room for n/2 wide characters.
> When you allocate n bytes for a PWSZ
> you can store n / 2 - 1 characters --
> you have to leave room for the null.
> 6. A BSTR may contain any Unicode data
> including the zero character. A PWSZ
> never contains the zero character
> except as an end-of-string marker.
> Both a BSTR and a PWSZ always have a
> zero character after their last valid
> character, but in a BSTR a valid
> character may be a zero character.
> 7. A BSTR may actually contain an odd
> number of bytes -- it may be used for
> moving binary data around. A PWSZ is
> almost always an even number of bytes
> and used only for storing Unicode
> strings.
>
>
>
|
171,662 |
<p>I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into "normal text" is by using the <strong>string.join</strong> method. However, it only takes 2 arguments so I can only make a single column using "\n". I thought trying to make a loop that would simply add a tab between columns would do it but the logic didn't work correctly.</p>
<p>I found an <a href="http://code.activestate.com/recipes/302380/" rel="noreferrer">ActiveState page</a> that has a fairly complicated way of doing it but it's from 4 years ago. Is there an easy way to do it nowadays?</p>
<hr>
<p><strong>Edit</strong> Here is the list that I want to use.</p>
<pre><code>skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology",
"CBE:Combat Engineer", "CHM:Chemistry", "CMP:Computers",
"CRM:Combat Rifeman", "CVE:Civil Engineer", "DIS:Disguise",
"ELC:Electronics","EQ:Equestrian", "FO:Forward Observer",
"FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing",
"GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire",
"INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow",
"LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language",
"LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic",
"MED:Medical", "MET:Meterology", "MNE:Mining Engineer",
"MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead",
"PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot",
"SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging",
"SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver",
"WVD:Wheeled Vehicle Driver"]
</code></pre>
<p>I just want to output this list into a simple, 2 column format to reduce space. Ideally there should be a standard amount of space between the columns but I can work with it.</p>
<pre><code>ACM:Aircraft Mechanic BC:Body Combat
BIO:Biology CBE:Combat Engineer
CHM:Chemistry CMP:Computers
CRM:Combat Rifeman CVE:Civil Engineer
DIS:Disguise ELC:Electronics
EQ:Equestrian FO:Forward Observer
FOR:Forage FRG:Forgery
FRM:Farming FSH:Fishing
GEO:Geology GS:Gunsmith
HW:Heavy Weapons IF:Indirect Fire
INS:Instruction INT:Interrogation
JP:Jet Pilot LB:Longbow
LAP:Light Aircraft Pilot LCG:Large Caliber Gun
LNG:Language LP:Lockpick
MC:Melee Combat MCY:Motorcycle
MEC:Mechanic MED:Medical
MET:Meterology MNE:Mining Engineer
MTL:Metallurgy MTN:Mountaineering
NWH:Nuclear Warhead PAR:Parachute
PST:Pistol RCN:Recon
RWP:Rotary Wing Pilot SBH:Small Boat Handling
SCD:Scuba Diving SCR:Scrounging
SWM:Swimming TW:Thrown Weapon
TVD:Tracked Vehicle Driver WVD:Wheeled Vehicle Driver
</code></pre>
|
[
{
"answer_id": 171686,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<pre><code>data = [ (\"1\",\"2\"),(\"3\",\"4\") ]\nprint \"\\n\".join(map(\"\\t\".join,data))\n</code></pre>\n\n<p>Not as flexible as the ActiveState solution, but shorter :-)</p>\n"
},
{
"answer_id": 171707,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "<p>Two columns, separated by tabs, joined into lines. Look in <em>itertools</em> for iterator equivalents, to achieve a space-efficient solution.</p>\n\n<pre><code>import string\ndef fmtpairs(mylist):\n pairs = zip(mylist[::2],mylist[1::2])\n return '\\n'.join('\\t'.join(i) for i in pairs)\n\nprint fmtpairs(list(string.ascii_uppercase))\n\nA B\nC D\nE F\nG H\nI J\n...\n</code></pre>\n\n<p>Oops... got caught by S.Lott (thank you).</p>\n\n<p>A more general solution, handles any number of columns and odd lists. Slightly modified from <a href=\"https://stackoverflow.com/questions/171662/formatting-a-list-of-text-into-columns#173823\">S.lott</a>, using generators to save space.</p>\n\n<pre><code>def fmtcols(mylist, cols):\n lines = (\"\\t\".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))\n return '\\n'.join(lines)\n</code></pre>\n"
},
{
"answer_id": 173823,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>It's long-winded, so I'll break it into two parts.</p>\n\n<pre><code>def columns( skills_defs, cols=2 ):\n pairs = [ \"\\t\".join(skills_defs[i:i+cols]) for i in range(0,len(skills_defs),cols) ]\n return \"\\n\".join( pairs )\n</code></pre>\n\n<p>It can, obviously, be done as a single loooong statement.</p>\n\n<p>This works for an odd number of skills, also.</p>\n"
},
{
"answer_id": 173933,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>format_columns</code> function should do what you want:</p>\n\n<pre><code>from __future__ import generators\ntry: import itertools\nexcept ImportError: mymap, myzip= map, zip\nelse: mymap, myzip= itertools.imap, itertools.izip\n\ndef format_columns(string_list, columns, separator=\" \"):\n \"Produce equal-width columns from string_list\"\n sublists= []\n\n # empty_str based on item 0 of string_list\n try:\n empty_str= type(string_list[0])()\n except IndexError: # string_list is empty\n return\n\n # create a sublist for every column\n for column in xrange(columns):\n sublists.append(string_list[column::columns])\n\n # find maximum length of a column\n max_sublist_len= max(mymap(len, sublists))\n\n # make all columns same length\n for sublist in sublists:\n if len(sublist) < max_sublist_len:\n sublist.append(empty_str)\n\n # calculate a format string for the output lines\n format_str= separator.join(\n \"%%-%ds\" % max(mymap(len, sublist))\n for sublist in sublists)\n\n for line_items in myzip(*sublists):\n yield format_str % line_items\n\nif __name__ == \"__main__\":\n skills_defs = [\"ACM:Aircraft Mechanic\", \"BC:Body Combat\", \"BIO:Biology\",\n \"CBE:Combat Engineer\", \"CHM:Chemistry\", \"CMP:Computers\",\n \"CRM:Combat Rifeman\", \"CVE:Civil Engineer\", \"DIS:Disguise\",\n \"ELC:Electronics\",\"EQ:Equestrian\", \"FO:Forward Observer\",\n \"FOR:Forage\", \"FRG:Forgery\", \"FRM:Farming\", \"FSH:Fishing\",\n \"GEO:Geology\", \"GS:Gunsmith\", \"HW:Heavy Weapons\", \"IF:Indirect Fire\",\n \"INS:Instruction\", \"INT:Interrogation\", \"JP:Jet Pilot\", \"LB:Longbow\",\n \"LAP:Light Aircraft Pilot\", \"LCG:Large Caliber Gun\", \"LNG:Language\",\n \"LP:Lockpick\", \"MC:Melee Combat\", \"MCY:Motorcycle\", \"MEC:Mechanic\",\n \"MED:Medical\", \"MET:Meterology\", \"MNE:Mining Engineer\",\n \"MTL:Metallurgy\", \"MTN:Mountaineering\", \"NWH:Nuclear Warhead\",\n \"PAR:Parachute\", \"PST:Pistol\", \"RCN:Recon\", \"RWP:Rotary Wing Pilot\",\n \"SBH:Small Boat Handling\",\"SCD:Scuba Diving\", \"SCR:Scrounging\",\n \"SWM:Swimming\", \"TW:Thrown Weapon\", \"TVD:Tracked Vehicle Driver\",\n \"WVD:Wheeled Vehicle Driver\"]\n\n for line in format_columns(skills_defs, 2):\n print line\n</code></pre>\n\n<p>This assumes that you have a Python with generators available.</p>\n"
},
{
"answer_id": 12721559,
"author": "ruwan800",
"author_id": 1511978,
"author_profile": "https://Stackoverflow.com/users/1511978",
"pm_score": 2,
"selected": false,
"text": "<p>This works</p>\n\n<pre><code>it = iter(skills_defs)\nfor i in it:\n print('{:<60}{}'.format(i, next(it, \"\")))\n</code></pre>\n\n<p>See:\n<a href=\"http://docs.python.org/library/string.html#format-examples\" rel=\"nofollow noreferrer\"> String format examples</a></p>\n"
},
{
"answer_id": 24876899,
"author": "masat",
"author_id": 1913361,
"author_profile": "https://Stackoverflow.com/users/1913361",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an extension of the solution provided by gimel, which allows to print equally spaced columns.</p>\n\n<pre><code>def fmtcols(mylist, cols):\n maxwidth = max(map(lambda x: len(x), mylist))\n justifyList = map(lambda x: x.ljust(maxwidth), mylist)\n lines = (' '.join(justifyList[i:i+cols]) \n for i in xrange(0,len(justifyList),cols))\n print \"\\n\".join(lines)\n</code></pre>\n\n<p>which returns something like this</p>\n\n<p><code>ACM:Aircraft Mechanic BC:Body Combat</code><br>\n<code>BIO:Biology CBE:Combat Engineer</code><br>\n<code>CHM:Chemistry CMP:Computers</code><br>\n<code>CRM:Combat Rifeman CVE:Civil Engineer</code><br>\n<code>DIS:Disguise ELC:Electronics</code>\n ... ...`</p>\n"
},
{
"answer_id": 27027373,
"author": "sidewinderguy",
"author_id": 214974,
"author_profile": "https://Stackoverflow.com/users/214974",
"pm_score": 0,
"selected": false,
"text": "<p>I think many of these solutions are conflating two separate things into one.</p>\n\n<p>You want to:</p>\n\n<ol>\n<li>be able to force a string to be a certain width</li>\n<li>print a table</li>\n</ol>\n\n<p>Here's a really simple take on how to do this:</p>\n\n<pre><code>import sys\n\nskills_defs = [\"ACM:Aircraft Mechanic\", \"BC:Body Combat\", \"BIO:Biology\",\n\"CBE:Combat Engineer\", \"CHM:Chemistry\", \"CMP:Computers\",\n\"CRM:Combat Rifeman\", \"CVE:Civil Engineer\", \"DIS:Disguise\",\n\"ELC:Electronics\",\"EQ:Equestrian\", \"FO:Forward Observer\",\n\"FOR:Forage\", \"FRG:Forgery\", \"FRM:Farming\", \"FSH:Fishing\",\n\"GEO:Geology\", \"GS:Gunsmith\", \"HW:Heavy Weapons\", \"IF:Indirect Fire\",\n\"INS:Instruction\", \"INT:Interrogation\", \"JP:Jet Pilot\", \"LB:Longbow\",\n\"LAP:Light Aircraft Pilot\", \"LCG:Large Caliber Gun\", \"LNG:Language\",\n\"LP:Lockpick\", \"MC:Melee Combat\", \"MCY:Motorcycle\", \"MEC:Mechanic\",\n\"MED:Medical\", \"MET:Meterology\", \"MNE:Mining Engineer\",\n\"MTL:Metallurgy\", \"MTN:Mountaineering\", \"NWH:Nuclear Warhead\",\n\"PAR:Parachute\", \"PST:Pistol\", \"RCN:Recon\", \"RWP:Rotary Wing Pilot\",\n\"SBH:Small Boat Handling\",\"SCD:Scuba Diving\", \"SCR:Scrounging\",\n\"SWM:Swimming\", \"TW:Thrown Weapon\", \"TVD:Tracked Vehicle Driver\",\n\"WVD:Wheeled Vehicle Driver\"]\n\n# The only thing \"colform\" does is return a modified version of \"txt\" that is\n# ensured to be exactly \"width\" characters long. It truncates or adds spaces\n# on the end as needed.\ndef colform(txt, width):\n if len(txt) > width:\n txt = txt[:width]\n elif len(txt) < width:\n txt = txt + (\" \" * (width - len(txt)))\n return txt\n\n# Now that you have colform you can use it to print out columns any way you wish.\n# Here's one brain-dead way to print in two columns:\nfor i in xrange(len(skills_defs)):\n sys.stdout.write(colform(skills_defs[i], 30))\n if i % 2 == 1:\n sys.stdout.write('\\n')\n</code></pre>\n"
},
{
"answer_id": 62495173,
"author": "Ayush Jain",
"author_id": 13779749,
"author_profile": "https://Stackoverflow.com/users/13779749",
"pm_score": 0,
"selected": false,
"text": "<p>This might also help you.</p>\n<pre><code>for i in skills_defs:\nif skills_defs.index(i)%2 ==0:\n print(i.ljust(30),end = " ")\nelse:\n print(i.ljust(30))\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into "normal text" is by using the **string.join** method. However, it only takes 2 arguments so I can only make a single column using "\n". I thought trying to make a loop that would simply add a tab between columns would do it but the logic didn't work correctly.
I found an [ActiveState page](http://code.activestate.com/recipes/302380/) that has a fairly complicated way of doing it but it's from 4 years ago. Is there an easy way to do it nowadays?
---
**Edit** Here is the list that I want to use.
```
skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology",
"CBE:Combat Engineer", "CHM:Chemistry", "CMP:Computers",
"CRM:Combat Rifeman", "CVE:Civil Engineer", "DIS:Disguise",
"ELC:Electronics","EQ:Equestrian", "FO:Forward Observer",
"FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing",
"GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire",
"INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow",
"LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language",
"LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic",
"MED:Medical", "MET:Meterology", "MNE:Mining Engineer",
"MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead",
"PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot",
"SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging",
"SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver",
"WVD:Wheeled Vehicle Driver"]
```
I just want to output this list into a simple, 2 column format to reduce space. Ideally there should be a standard amount of space between the columns but I can work with it.
```
ACM:Aircraft Mechanic BC:Body Combat
BIO:Biology CBE:Combat Engineer
CHM:Chemistry CMP:Computers
CRM:Combat Rifeman CVE:Civil Engineer
DIS:Disguise ELC:Electronics
EQ:Equestrian FO:Forward Observer
FOR:Forage FRG:Forgery
FRM:Farming FSH:Fishing
GEO:Geology GS:Gunsmith
HW:Heavy Weapons IF:Indirect Fire
INS:Instruction INT:Interrogation
JP:Jet Pilot LB:Longbow
LAP:Light Aircraft Pilot LCG:Large Caliber Gun
LNG:Language LP:Lockpick
MC:Melee Combat MCY:Motorcycle
MEC:Mechanic MED:Medical
MET:Meterology MNE:Mining Engineer
MTL:Metallurgy MTN:Mountaineering
NWH:Nuclear Warhead PAR:Parachute
PST:Pistol RCN:Recon
RWP:Rotary Wing Pilot SBH:Small Boat Handling
SCD:Scuba Diving SCR:Scrounging
SWM:Swimming TW:Thrown Weapon
TVD:Tracked Vehicle Driver WVD:Wheeled Vehicle Driver
```
|
Two columns, separated by tabs, joined into lines. Look in *itertools* for iterator equivalents, to achieve a space-efficient solution.
```
import string
def fmtpairs(mylist):
pairs = zip(mylist[::2],mylist[1::2])
return '\n'.join('\t'.join(i) for i in pairs)
print fmtpairs(list(string.ascii_uppercase))
A B
C D
E F
G H
I J
...
```
Oops... got caught by S.Lott (thank you).
A more general solution, handles any number of columns and odd lists. Slightly modified from [S.lott](https://stackoverflow.com/questions/171662/formatting-a-list-of-text-into-columns#173823), using generators to save space.
```
def fmtcols(mylist, cols):
lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))
return '\n'.join(lines)
```
|
171,664 |
<p>I have not used generics much and so cannot figure out if it is possible to turn the following three methods into one using generics to reduce duplication. Actually my code currently has six methods but if you can solve it for the three then the rest should just work anyway with the same solution.</p>
<pre><code> private object EvaluateUInt64(UInt64 x, UInt64 y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateFloat(float x, float y)
{
switch(Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateDouble(double x, double y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
</code></pre>
<p>I am building a simple expression parser that then needs to evaluate the simple binary operations such as addition/subtraction etc. I use the above methods to get the actual maths performed using the relevant types. But there has got to be a better answer!</p>
|
[
{
"answer_id": 171668,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>Generics doesn't natively support arithmetic. However, it can be done with .NET 3.5, <a href=\"http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow noreferrer\">like so</a>. The Operator class is part of <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/\" rel=\"nofollow noreferrer\">MiscUtil</a>. This then becomes:</p>\n\n<pre><code> public T Evaluate<T>(T x, T y) {\n switch (Operation)\n {\n case BinaryOp.Add:\n return Operator.Add(x, y);\n case BinaryOp.Subtract:\n return Operator.Subtract(x, y);\n ... etc\n</code></pre>\n\n<p>Since you are writing an expression parser, it might be a good idea to use Expression directly, but you're welcome to use the above.</p>\n"
},
{
"answer_id": 171675,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Marc Gravell has done a lot of work on making generic maths viable. See the <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow noreferrer\">MiscUtil</a> \nand <a href=\"http://www.yoda.arachsys.com/csharp/genericoperators.html\" rel=\"nofollow noreferrer\">general article about the issue</a>.</p>\n\n<p>The code in the current version of MiscUtil requires .NET 3.5 due to its use of expression trees. However, I believe Marc has a version which works with .NET 2.0 as well. If this would be useful to people, I'm sure we could incorporate it somehow (possibly with a facade in MiscUtil itself which would use the appropriate implementation based on framework version at runtime).</p>\n\n<p>For the future, I'd like to see <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces.aspx\" rel=\"nofollow noreferrer\">static interfaces</a> which could provide an alternative way of working with generic maths types.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
] |
I have not used generics much and so cannot figure out if it is possible to turn the following three methods into one using generics to reduce duplication. Actually my code currently has six methods but if you can solve it for the three then the rest should just work anyway with the same solution.
```
private object EvaluateUInt64(UInt64 x, UInt64 y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateFloat(float x, float y)
{
switch(Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateDouble(double x, double y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
```
I am building a simple expression parser that then needs to evaluate the simple binary operations such as addition/subtraction etc. I use the above methods to get the actual maths performed using the relevant types. But there has got to be a better answer!
|
Generics doesn't natively support arithmetic. However, it can be done with .NET 3.5, [like so](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html). The Operator class is part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/). This then becomes:
```
public T Evaluate<T>(T x, T y) {
switch (Operation)
{
case BinaryOp.Add:
return Operator.Add(x, y);
case BinaryOp.Subtract:
return Operator.Subtract(x, y);
... etc
```
Since you are writing an expression parser, it might be a good idea to use Expression directly, but you're welcome to use the above.
|
171,673 |
<p>I've been trying to create a Windows Media Player plugin in Visual Studio 2008, and am having great difficulty finding the correct template. MSDN provides advice <a href="http://msdn.microsoft.com/en-us/library/bb262076(VS.85).aspx" rel="nofollow noreferrer">here</a>, but it does not appear to be relevant to VS2008.</p>
<p>Can anyone suggest how to start a WMP plugin in Visual Studio?</p>
<p>EDIT: Ive accepted this answer because it worked for me, but I'm afraid it isn't the most elegant of solutions. If anyone has a better idea, please add it!</p>
|
[
{
"answer_id": 171668,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>Generics doesn't natively support arithmetic. However, it can be done with .NET 3.5, <a href=\"http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow noreferrer\">like so</a>. The Operator class is part of <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/\" rel=\"nofollow noreferrer\">MiscUtil</a>. This then becomes:</p>\n\n<pre><code> public T Evaluate<T>(T x, T y) {\n switch (Operation)\n {\n case BinaryOp.Add:\n return Operator.Add(x, y);\n case BinaryOp.Subtract:\n return Operator.Subtract(x, y);\n ... etc\n</code></pre>\n\n<p>Since you are writing an expression parser, it might be a good idea to use Expression directly, but you're welcome to use the above.</p>\n"
},
{
"answer_id": 171675,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Marc Gravell has done a lot of work on making generic maths viable. See the <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow noreferrer\">MiscUtil</a> \nand <a href=\"http://www.yoda.arachsys.com/csharp/genericoperators.html\" rel=\"nofollow noreferrer\">general article about the issue</a>.</p>\n\n<p>The code in the current version of MiscUtil requires .NET 3.5 due to its use of expression trees. However, I believe Marc has a version which works with .NET 2.0 as well. If this would be useful to people, I'm sure we could incorporate it somehow (possibly with a facade in MiscUtil itself which would use the appropriate implementation based on framework version at runtime).</p>\n\n<p>For the future, I'd like to see <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces.aspx\" rel=\"nofollow noreferrer\">static interfaces</a> which could provide an alternative way of working with generic maths types.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11484/"
] |
I've been trying to create a Windows Media Player plugin in Visual Studio 2008, and am having great difficulty finding the correct template. MSDN provides advice [here](http://msdn.microsoft.com/en-us/library/bb262076(VS.85).aspx), but it does not appear to be relevant to VS2008.
Can anyone suggest how to start a WMP plugin in Visual Studio?
EDIT: Ive accepted this answer because it worked for me, but I'm afraid it isn't the most elegant of solutions. If anyone has a better idea, please add it!
|
Generics doesn't natively support arithmetic. However, it can be done with .NET 3.5, [like so](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html). The Operator class is part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/). This then becomes:
```
public T Evaluate<T>(T x, T y) {
switch (Operation)
{
case BinaryOp.Add:
return Operator.Add(x, y);
case BinaryOp.Subtract:
return Operator.Subtract(x, y);
... etc
```
Since you are writing an expression parser, it might be a good idea to use Expression directly, but you're welcome to use the above.
|
171,730 |
<p>I have a small problem with interfaces. Here it is in Pseudo code :</p>
<pre><code>type
Interface1 = interface
end;
Interface2 = interface
end;
TParentClass = class(TInterfacedObject, Interface1)
private
fChild : Interface2;
public
procedure AddChild(aChild : Interface2);
end;
TChildClass = class(TInterfacedObject, Interface2)
private
fParent : Interface2;
public
constructor Create(aPArent : Interface1);
end;
</code></pre>
<p>Can anyone see the flaw? I need the child to have a reference to it's parent, but the reference counting doesn't work in this situation. If I create a ParentClass instance, and add a child, then the parent class is never released. I can see why. How do I get round it?</p>
|
[
{
"answer_id": 171738,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p>You must make a method that explicitly unlinks the right references. There is no way to get the automatic reference counting working properly in this case.</p>\n"
},
{
"answer_id": 171789,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 2,
"selected": false,
"text": "<p>Well, the reference counting of course <strong>does</strong> work in this situation - it just doesn't solve the problem.</p>\n\n<p>That's the biggest problem with reference counting - when you have a circular reference, you have to explicitely 'break' it (set one interface reference to 'nil', for example). That's also why reference counting is not really a replacement for garbage collection - garbage collectors are aware that cycles may exist and can release such cyclic structures when they are not referenced from the 'outside'.</p>\n"
},
{
"answer_id": 171795,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 4,
"selected": true,
"text": "<p>A reference-counted reference has two semantics: it acts as a share of ownership as well as a means of navigating the object graph.</p>\n\n<p>Typically, you don't need <strong>both</strong> of these semantics on all links in a cycle in the graph of references. Perhaps only parents own children, and not the other way around? If that is the case, you can make the child references to the parent <em>weak links</em>, by storing them as pointers, like this:</p>\n\n<pre><code>TChildClass = class(TInterfacedObject, Interface2)\nprivate\n fParent : Pointer;\n function GetParent: Interface1;\npublic\n constructor Create(aPArent : Interface1);\n property Parent: Interface1 read GetParent;\nend;\n\nfunction TChildClass.GetParent: Interface1;\nbegin\n Result := Interface1(fParent);\nend;\n\nconstructor TChildClass.Create(AParent: Interface1);\nbegin\n fParent := Pointer(AParent);\nend;\n</code></pre>\n\n<p>This is safe if the root of the tree of instances is guaranteed to be kept alive somewhere, i.e. you are not relying on only keeping a reference to a branch of the tree and still being able to navigate the whole of it.</p>\n"
},
{
"answer_id": 175907,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 0,
"selected": false,
"text": "<p>With the use of a function pointer in the first example then the cyclic reference problem doesn't exist. .NET uses delegates, and VB6 uses events. All of which have the benefit of not incrementing the reference count of the object being pointed too.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22712/"
] |
I have a small problem with interfaces. Here it is in Pseudo code :
```
type
Interface1 = interface
end;
Interface2 = interface
end;
TParentClass = class(TInterfacedObject, Interface1)
private
fChild : Interface2;
public
procedure AddChild(aChild : Interface2);
end;
TChildClass = class(TInterfacedObject, Interface2)
private
fParent : Interface2;
public
constructor Create(aPArent : Interface1);
end;
```
Can anyone see the flaw? I need the child to have a reference to it's parent, but the reference counting doesn't work in this situation. If I create a ParentClass instance, and add a child, then the parent class is never released. I can see why. How do I get round it?
|
A reference-counted reference has two semantics: it acts as a share of ownership as well as a means of navigating the object graph.
Typically, you don't need **both** of these semantics on all links in a cycle in the graph of references. Perhaps only parents own children, and not the other way around? If that is the case, you can make the child references to the parent *weak links*, by storing them as pointers, like this:
```
TChildClass = class(TInterfacedObject, Interface2)
private
fParent : Pointer;
function GetParent: Interface1;
public
constructor Create(aPArent : Interface1);
property Parent: Interface1 read GetParent;
end;
function TChildClass.GetParent: Interface1;
begin
Result := Interface1(fParent);
end;
constructor TChildClass.Create(AParent: Interface1);
begin
fParent := Pointer(AParent);
end;
```
This is safe if the root of the tree of instances is guaranteed to be kept alive somewhere, i.e. you are not relying on only keeping a reference to a branch of the tree and still being able to navigate the whole of it.
|
171,755 |
<p>Is it possible to implement the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">Visitor Pattern</a> respecting the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" rel="noreferrer">Open/Closed Principle</a>, but still be able to add new visitable classes?</p>
<p>The Open/Closed Principle states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".</p>
<pre><code>struct ConcreteVisitable1;
struct ConcreteVisitable2;
struct AbstractVisitor
{
virtual void visit(ConcreteVisitable1& concrete1) = 0;
virtual void visit(ConcreteVisitable2& concrete2) = 0;
};
struct AbstractVisitable
{
virtual void accept(AbstractVisitor& visitor) = 0;
};
struct ConcreteVisitable1 : AbstractVisitable
{
virtual void accept(AbstractVisitor& visitor)
{
visitor.visit(*this);
}
};
struct ConcreteVisitable2 : AbstractVisitable
{
virtual void accept(AbstractVisitor& visitor)
{
visitor.visit(*this);
}
};
</code></pre>
<p>You can implement any number of classes which derives from AbstractVisitor: It is open for extension. You cannot add a new visitable class as the classes derived from AbstractVisitor will not compile: It closed for modification.</p>
<p>The AbstractVisitor class tree respects the Open/Closed Principle.
The AbstractVisitable class tree does not respect the Open/Closed Principle, as it cannot be extended.</p>
<p>Is there any other solution than to extend the AbstractVisitor and AbstractVisitable as below?</p>
<pre><code>struct ConcreteVisitable3;
struct AbstractVisitor2 : AbstractVisitor
{
virtual void visit(ConcreteVisitable3& concrete3) = 0;
};
struct AbstractVisitable2 : AbstractVisitable
{
virtual void accept(AbstractVisitor2& visitor) = 0;
};
struct ConcreteVisitable3 : AbstractVisitable2
{
virtual void accept(AbstractVisitor2& visitor)
{
visitor.visit(*this);
}
};
</code></pre>
|
[
{
"answer_id": 171768,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to check out research on \"the expression problem\", see e.g.</p>\n\n<p><a href=\"http://lambda-the-ultimate.org/node/2232\" rel=\"nofollow noreferrer\">http://lambda-the-ultimate.org/node/2232</a></p>\n\n<p>I think the problem is mostly academic, but it's something that has been studied a lot, so there's a bit of stuff you can read about different ways to implement it in existing languages or with various language extensions.</p>\n"
},
{
"answer_id": 171817,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 4,
"selected": true,
"text": "<p>In C++, <a href=\"https://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf\" rel=\"nofollow noreferrer\">Acyclic Visitor</a> (pdf) gets you what you want.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19100/"
] |
Is it possible to implement the [Visitor Pattern](http://en.wikipedia.org/wiki/Visitor_pattern) respecting the [Open/Closed Principle](http://en.wikipedia.org/wiki/Open/closed_principle), but still be able to add new visitable classes?
The Open/Closed Principle states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".
```
struct ConcreteVisitable1;
struct ConcreteVisitable2;
struct AbstractVisitor
{
virtual void visit(ConcreteVisitable1& concrete1) = 0;
virtual void visit(ConcreteVisitable2& concrete2) = 0;
};
struct AbstractVisitable
{
virtual void accept(AbstractVisitor& visitor) = 0;
};
struct ConcreteVisitable1 : AbstractVisitable
{
virtual void accept(AbstractVisitor& visitor)
{
visitor.visit(*this);
}
};
struct ConcreteVisitable2 : AbstractVisitable
{
virtual void accept(AbstractVisitor& visitor)
{
visitor.visit(*this);
}
};
```
You can implement any number of classes which derives from AbstractVisitor: It is open for extension. You cannot add a new visitable class as the classes derived from AbstractVisitor will not compile: It closed for modification.
The AbstractVisitor class tree respects the Open/Closed Principle.
The AbstractVisitable class tree does not respect the Open/Closed Principle, as it cannot be extended.
Is there any other solution than to extend the AbstractVisitor and AbstractVisitable as below?
```
struct ConcreteVisitable3;
struct AbstractVisitor2 : AbstractVisitor
{
virtual void visit(ConcreteVisitable3& concrete3) = 0;
};
struct AbstractVisitable2 : AbstractVisitable
{
virtual void accept(AbstractVisitor2& visitor) = 0;
};
struct ConcreteVisitable3 : AbstractVisitable2
{
virtual void accept(AbstractVisitor2& visitor)
{
visitor.visit(*this);
}
};
```
|
In C++, [Acyclic Visitor](https://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) (pdf) gets you what you want.
|
171,765 |
<p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br>
(factor2, multiplicity2)<br>
(factor3, multiplicity3)<br>
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<hr>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="https://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
|
[
{
"answer_id": 171779,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 5,
"selected": false,
"text": "<p>To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do <code>n / i</code>, and this will cover the whole problem space.</p>\n\n<p>As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.</p>\n\n<p>Python code:</p>\n\n<pre><code>import math\n\ndef divisorGenerator(n):\n large_divisors = []\n for i in xrange(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\n\nprint list(divisorGenerator(100))\n</code></pre>\n\n<p>Which should output a list like:</p>\n\n<pre>\n[1, 2, 4, 5, 10, 20, 25, 50, 100]\n</pre>\n"
},
{
"answer_id": 171784,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": "<p>Given your <code>factorGenerator</code> function, here is a <code>divisorGen</code> that should work:</p>\n<pre><code>def divisorGen(n):\n factors = list(factorGenerator(n))\n nfactors = len(factors)\n f = [0] * nfactors\n while True:\n yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)\n i = 0\n while True:\n f[i] += 1\n if f[i] <= factors[i][1]:\n break\n f[i] = 0\n i += 1\n if i >= nfactors:\n return\n</code></pre>\n<p>The overall efficiency of this algorithm will depend entirely on the efficiency of the <code>factorGenerator</code>.</p>\n"
},
{
"answer_id": 371129,
"author": "Pietro Speroni",
"author_id": 46634,
"author_profile": "https://Stackoverflow.com/users/46634",
"pm_score": 3,
"selected": false,
"text": "<p>I like Greg solution, but I wish it was more python like.\nI feel it would be faster and more readable; \nso after some time of coding I came out with this.</p>\n\n<p>The first two functions are needed to make the cartesian product of lists. \nAnd can be reused whnever this problem arises. \nBy the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.</p>\n\n<p>\"Factorgenerator\" now returns a dictionary. And then the dictionary is fed into \"divisors\", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime.\nThen we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor.\nWe sort them, and return them.</p>\n\n<p>I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.</p>\n\n<p>Pietro Speroni (pietrosperoni dot it)</p>\n\n<pre><code>from math import sqrt\n\n\n##############################################################\n### cartesian product of lists ##################################\n##############################################################\n\ndef appendEs2Sequences(sequences,es):\n result=[]\n if not sequences:\n for e in es:\n result.append([e])\n else:\n for e in es:\n result+=[seq+[e] for seq in sequences]\n return result\n\n\ndef cartesianproduct(lists):\n \"\"\"\n given a list of lists,\n returns all the possible combinations taking one element from each list\n The list does not have to be of equal length\n \"\"\"\n return reduce(appendEs2Sequences,lists,[])\n\n##############################################################\n### prime factors of a natural ##################################\n##############################################################\n\ndef primefactors(n):\n '''lists prime factors, from greatest to smallest''' \n i = 2\n while i<=sqrt(n):\n if n%i==0:\n l = primefactors(n/i)\n l.append(i)\n return l\n i+=1\n return [n] # n is prime\n\n\n##############################################################\n### factorization of a natural ##################################\n##############################################################\n\ndef factorGenerator(n):\n p = primefactors(n)\n factors={}\n for p1 in p:\n try:\n factors[p1]+=1\n except KeyError:\n factors[p1]=1\n return factors\n\ndef divisors(n):\n factors = factorGenerator(n)\n divisors=[]\n listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]\n listfactors=cartesianproduct(listexponents)\n for f in listfactors:\n divisors.append(reduce(lambda x, y: x*y, f, 1))\n divisors.sort()\n return divisors\n\n\n\nprint divisors(60668796879)\n</code></pre>\n\n<p>P.S. \nit is the first time I am posting to stackoverflow. \nI am looking forward for any feedback.</p>\n"
},
{
"answer_id": 15025068,
"author": "YvesgereY",
"author_id": 995896,
"author_profile": "https://Stackoverflow.com/users/995896",
"pm_score": 2,
"selected": false,
"text": "<p>Adapted from <a href=\"https://codereview.stackexchange.com/a/23015/8431\">CodeReview</a>, here is a variant which works with <code>num=1</code> !</p>\n\n<pre><code>from itertools import product\nimport operator\n\ndef prod(ls):\n return reduce(operator.mul, ls, 1)\n\ndef powered(factors, powers):\n return prod(f**p for (f,p) in zip(factors, powers))\n\n\ndef divisors(num) :\n\n pf = dict(prime_factors(num))\n primes = pf.keys()\n #For each prime, possible exponents\n exponents = [range(i+1) for i in pf.values()]\n return (powered(primes,es) for es in product(*exponents))\n</code></pre>\n"
},
{
"answer_id": 18366032,
"author": "user448810",
"author_id": 448810,
"author_profile": "https://Stackoverflow.com/users/448810",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that the <code>factors</code> function returns the factors of <em>n</em> (for instance, <code>factors(60)</code> returns the list [2, 2, 3, 5]), here is a function to compute the divisors of <em>n</em>:</p>\n\n<pre><code>function divisors(n)\n divs := [1]\n for fact in factors(n)\n temp := []\n for div in divs\n if fact * div not in divs\n append fact * div to temp\n divs := divs + temp\n return divs\n</code></pre>\n"
},
{
"answer_id": 23983542,
"author": "user3697453",
"author_id": 3697453,
"author_profile": "https://Stackoverflow.com/users/3697453",
"pm_score": 0,
"selected": false,
"text": "<pre><code>return [x for x in range(n+1) if n/x==int(n/x)]\n</code></pre>\n"
},
{
"answer_id": 31340346,
"author": "Amber Xue",
"author_id": 3371387,
"author_profile": "https://Stackoverflow.com/users/3371387",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my solution. It seems to be dumb but works well...and I was trying to find all proper divisors so the loop started from i = 2. </p>\n\n<pre><code>import math as m \n\ndef findfac(n):\n faclist = [1]\n for i in range(2, int(m.sqrt(n) + 2)):\n if n%i == 0:\n if i not in faclist:\n faclist.append(i)\n if n/i not in faclist:\n faclist.append(n/i)\n return facts\n</code></pre>\n"
},
{
"answer_id": 36070582,
"author": "joksnet",
"author_id": 408564,
"author_profile": "https://Stackoverflow.com/users/408564",
"pm_score": 2,
"selected": false,
"text": "<p>Old question, but here is my take:</p>\n\n<pre><code>def divs(n, m):\n if m == 1: return [1]\n if n % m == 0: return [m] + divs(n, m - 1)\n return divs(n, m - 1)\n</code></pre>\n\n<p>You can proxy with:</p>\n\n<pre><code>def divisorGenerator(n):\n for x in reversed(divs(n, n)):\n yield x\n</code></pre>\n\n<p>NOTE: For languages that support, this could be tail recursive.</p>\n"
},
{
"answer_id": 36700288,
"author": "Anivarth",
"author_id": 3442438,
"author_profile": "https://Stackoverflow.com/users/3442438",
"pm_score": 5,
"selected": false,
"text": "<p>I think you can stop at <code>math.sqrt(n)</code> instead of n/2. </p>\n\n<p>I will give you example so that you can understand it easily. Now the <code>sqrt(28)</code> is <code>5.29</code> so <code>ceil(5.29)</code> will be 6. So I if I will stop at 6 then I will can get all the divisors. How?</p>\n\n<p>First see the code and then see image:</p>\n\n<pre><code>import math\ndef divisors(n):\n divs = [1]\n for i in xrange(2,int(math.sqrt(n))+1):\n if n%i == 0:\n divs.extend([i,n/i])\n divs.extend([n])\n return list(set(divs))\n</code></pre>\n\n<p>Now, See the image below:</p>\n\n<p>Lets say I have already added <code>1</code> to my divisors list and I start with <code>i=2</code> so</p>\n\n<p><a href=\"https://i.stack.imgur.com/jsBas.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/jsBas.jpg\" alt=\"Divisors of a 28\"></a></p>\n\n<p>So at the end of all the iterations as I have added the quotient and the divisor to my list all the divisors of 28 are populated. </p>\n\n<p>Source: <a href=\"http://www.wikihow.com/Determine-the-Number-of-Divisors-of-an-Integer\" rel=\"noreferrer\">How to determine the divisors of a number</a></p>\n"
},
{
"answer_id": 37058745,
"author": "Tomas Kulich",
"author_id": 1761457,
"author_profile": "https://Stackoverflow.com/users/1761457",
"pm_score": 5,
"selected": false,
"text": "<p>Although there are already many solutions to this, I really have to post this :)</p>\n\n<p>This one is:</p>\n\n<ul>\n<li>readable </li>\n<li>short</li>\n<li>self contained, copy & paste ready</li>\n<li>quick (in cases with a lot of prime factors and divisors, > 10 times faster than the accepted solution)</li>\n<li>python3, python2 and pypy compliant</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>def divisors(n):\n # get factors and their counts\n factors = {}\n nn = n\n i = 2\n while i*i <= nn:\n while nn % i == 0:\n factors[i] = factors.get(i, 0) + 1\n nn //= i\n i += 1\n if nn > 1:\n factors[nn] = factors.get(nn, 0) + 1\n\n primes = list(factors.keys())\n\n # generates factors from primes[k:] subset\n def generate(k):\n if k == len(primes):\n yield 1\n else:\n rest = generate(k+1)\n prime = primes[k]\n for factor in rest:\n prime_to_i = 1\n # prime_to_i iterates prime**i values, i being all possible exponents\n for _ in range(factors[prime] + 1):\n yield factor * prime_to_i\n prime_to_i *= prime\n\n # in python3, `yield from generate(0)` would also work\n for factor in generate(0):\n yield factor\n</code></pre>\n"
},
{
"answer_id": 46637377,
"author": "Bruno Astrolino",
"author_id": 8694657,
"author_profile": "https://Stackoverflow.com/users/8694657",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a smart and fast way to do it for numbers up to and around 10**16 in pure Python 3.6,</p>\n\n<pre><code>from itertools import compress\n\ndef primes(n):\n \"\"\" Returns a list of primes < n for n > 2 \"\"\"\n sieve = bytearray([True]) * (n//2)\n for i in range(3,int(n**0.5)+1,2):\n if sieve[i//2]:\n sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)\n return [2,*compress(range(3,n,2), sieve[1:])]\n\ndef factorization(n):\n \"\"\" Returns a list of the prime factorization of n \"\"\"\n pf = []\n for p in primeslist:\n if p*p > n : break\n count = 0\n while not n % p:\n n //= p\n count += 1\n if count > 0: pf.append((p, count))\n if n > 1: pf.append((n, 1))\n return pf\n\ndef divisors(n):\n \"\"\" Returns an unsorted list of the divisors of n \"\"\"\n divs = [1]\n for p, e in factorization(n):\n divs += [x*p**k for k in range(1,e+1) for x in divs]\n return divs\n\nn = 600851475143\nprimeslist = primes(int(n**0.5)+1) \nprint(divisors(n))\n</code></pre>\n"
},
{
"answer_id": 49888733,
"author": "Sadiq",
"author_id": 3575229,
"author_profile": "https://Stackoverflow.com/users/3575229",
"pm_score": 0,
"selected": false,
"text": "<p>If you only care about using list comprehensions and nothing else matters to you!</p>\n\n<pre><code>from itertools import combinations\nfrom functools import reduce\n\ndef get_devisors(n):\n f = [f for f,e in list(factorGenerator(n)) for i in range(e)]\n fc = [x for l in range(len(f)+1) for x in combinations(f, l)]\n devisors = [1 if c==() else reduce((lambda x, y: x * y), c) for c in set(fc)]\n return sorted(devisors)\n</code></pre>\n"
},
{
"answer_id": 54047215,
"author": "ppw0",
"author_id": 7143340,
"author_profile": "https://Stackoverflow.com/users/7143340",
"pm_score": 4,
"selected": false,
"text": "<p>An illustrative Pythonic one-liner:</p>\n<pre><code>from itertools import chain\nfrom math import sqrt\n\ndef divisors(n):\n return set(chain.from_iterable((i,n//i) for i in range(1,int(sqrt(n))+1) if n%i == 0))\n</code></pre>\n<p>But better yet, just use sympy:</p>\n<pre><code>from sympy import divisors\n</code></pre>\n"
},
{
"answer_id": 63416316,
"author": "Mathieu Villion",
"author_id": 6175500,
"author_profile": "https://Stackoverflow.com/users/6175500",
"pm_score": 2,
"selected": false,
"text": "<p>If your PC has tons of memory, a brute single line can be fast enough with numpy:</p>\n<pre><code>N = 10000000; tst = np.arange(1, N); tst[np.mod(N, tst) == 0]\nOut: \narray([ 1, 2, 4, 5, 8, 10, 16,\n 20, 25, 32, 40, 50, 64, 80,\n 100, 125, 128, 160, 200, 250, 320,\n 400, 500, 625, 640, 800, 1000, 1250,\n 1600, 2000, 2500, 3125, 3200, 4000, 5000,\n 6250, 8000, 10000, 12500, 15625, 16000, 20000,\n 25000, 31250, 40000, 50000, 62500, 78125, 80000,\n 100000, 125000, 156250, 200000, 250000, 312500, 400000,\n 500000, 625000, 1000000, 1250000, 2000000, 2500000, 5000000])\n</code></pre>\n<p>Takes less than 1s on my slow PC.</p>\n"
},
{
"answer_id": 63450265,
"author": "Eugene",
"author_id": 9135063,
"author_profile": "https://Stackoverflow.com/users/9135063",
"pm_score": 0,
"selected": false,
"text": "<p>My solution via generator function is:</p>\n<pre><code>def divisor(num):\n for x in range(1, num + 1):\n if num % x == 0:\n yield x\n while True:\n yield None\n</code></pre>\n"
},
{
"answer_id": 67455769,
"author": "Arvind Pant",
"author_id": 4878423,
"author_profile": "https://Stackoverflow.com/users/4878423",
"pm_score": 0,
"selected": false,
"text": "<p>Try to calculate square root a given number and then loop range(1,square_root+1).</p>\n<pre><code>number = int(input("Enter a Number: "))\nsquare_root = round(number ** (1.0 / 2))\nprint(square_root)\ndivisor_list = []\nfor i in range(1,square_root+1):\n if number % i == 0: # Check if mod return 0 if yes then append i and number/i in the list\n divisor_list.append(i)\n divisor_list.append(int(number/i))\n\nprint(divisor_list)\n</code></pre>\n"
},
{
"answer_id": 69464666,
"author": "amiralidev",
"author_id": 11753050,
"author_profile": "https://Stackoverflow.com/users/11753050",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def divisorGen(n): v = n last = [] for i in range(1, v+1) : if n % i == 0 : last.append(i)\n</code></pre>\n"
},
{
"answer_id": 70406267,
"author": "Rodrigo V",
"author_id": 12647804,
"author_profile": "https://Stackoverflow.com/users/12647804",
"pm_score": 0,
"selected": false,
"text": "<p>I don´t understand why there are so many complicated solutions to this problem.</p>\n<p>Here is my take on it:</p>\n<pre><code>def divisors(n):\n lis =[1]\n s = math.ceil(math.sqrt(n))\n for g in range(s,1, -1):\n if n % g == 0:\n lis.append(g)\n lis.append(int(n / g))\n return (set(lis))\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21384/"
] |
Here's the very dumb way:
```
def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
```
The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)
I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:
(factor1, multiplicity1)
(factor2, multiplicity2)
(factor3, multiplicity3)
and so on...
i.e. the output of
```
for i in factorGenerator(100):
print i
```
is:
```
(2, 2)
(5, 2)
```
I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make
```
for i in divisorGen(100):
print i
```
output this:
```
1
2
4
5
10
20
25
50
100
```
---
**UPDATE:** Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D
**UPDATE 2:** Stop saying this is a duplicate of [this](https://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number) post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.
|
Given your `factorGenerator` function, here is a `divisorGen` that should work:
```
def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
while True:
f[i] += 1
if f[i] <= factors[i][1]:
break
f[i] = 0
i += 1
if i >= nfactors:
return
```
The overall efficiency of this algorithm will depend entirely on the efficiency of the `factorGenerator`.
|
171,771 |
<p>Okay, so I'm doing my first foray into using the ADO.NET Entity Framework. </p>
<p>My test case right now includes a SQL Server 2008 database with 2 tables, Member and Profile, with a 1:1 relationship.</p>
<p>I then used the Entity Data Model wizard to auto-generate the EDM from the database. It generated a model with the correct association. Now I want to do this:</p>
<pre><code>ObjectQuery<Member> members = entities.Member;
IQueryable<Member> membersQuery = from m in members select m;
foreach (Member m in membersQuery)
{
Profile p = m.Profile;
...
}
</code></pre>
<p>Which halfway works. I am able to iterate through all of the Members. But the problem I'm having is that m.Profile is always null. The examples for LINQ to Entities on the MSDN library seem to suggest that I will be able to seamlessly follow the navigation relationships like that, but it doesn't seem to work that way. I found that if I first load the profiles in a separate call somehow, such as using entities.Profile.ToList, then m.Profile will point to a valid Profile.</p>
<p>So my question is, is there an elegant way to force the framework to automatically load the data along the navigation relationships, or do I need to do that explicitly with a join or something else?</p>
<p>Thanks</p>
|
[
{
"answer_id": 173273,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 4,
"selected": true,
"text": "<p>Okay I managed to find the answer I needed here <a href=\"http://msdn.microsoft.com/en-us/magazine/cc507640.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc507640.aspx</a>. The following query will make sure that the Profile entity is loaded:</p>\n\n<pre><code>IQueryable<Member> membersQuery = from m in members.Include(\"Profile\") select m;\n</code></pre>\n"
},
{
"answer_id": 329342,
"author": "WestDiscGolf",
"author_id": 33116,
"author_profile": "https://Stackoverflow.com/users/33116",
"pm_score": 1,
"selected": false,
"text": "<p>I used this technique on a 1 to many relationship and works well. I have a Survey class and many questions as part of that from a different db table and using this technique managed to extract the related questions ...</p>\n\n<pre><code>context.Survey.Include(\"SurveyQuestion\").Where(x => x.Id == id).First()\n</code></pre>\n\n<p>(context being the generated ObjectContext).</p>\n\n<pre><code>context.Survey.Include<T>().Where(x => x.Id == id).First()\n</code></pre>\n\n<p>I just spend 10mins trying to put together an extention method to do this, the closest I could come up with is ...</p>\n\n<pre><code> public static ObjectQuery<T> Include<T,U>(this ObjectQuery<T> context)\n {\n string path = typeof(U).ToString();\n string[] split = path.Split('.');\n\n return context.Include(split[split.Length - 1]);\n }\n</code></pre>\n\n<p>Any pointers for the improvements would be most welcome :-)</p>\n"
},
{
"answer_id": 329376,
"author": "WestDiscGolf",
"author_id": 33116,
"author_profile": "https://Stackoverflow.com/users/33116",
"pm_score": 1,
"selected": false,
"text": "<p>On doing a bit more research found this ... <a href=\"https://stackoverflow.com/questions/179700/get-the-name-of-a-class-as-a-string-in-c\">StackOverflow link</a> which has a post to <a href=\"http://msmvps.com/blogs/matthieu/archive/2008/06/06/entityframework-include-with-func.aspx\" rel=\"nofollow noreferrer\">Func link</a> which is a lot better than my extension method attempt :-)</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19404/"
] |
Okay, so I'm doing my first foray into using the ADO.NET Entity Framework.
My test case right now includes a SQL Server 2008 database with 2 tables, Member and Profile, with a 1:1 relationship.
I then used the Entity Data Model wizard to auto-generate the EDM from the database. It generated a model with the correct association. Now I want to do this:
```
ObjectQuery<Member> members = entities.Member;
IQueryable<Member> membersQuery = from m in members select m;
foreach (Member m in membersQuery)
{
Profile p = m.Profile;
...
}
```
Which halfway works. I am able to iterate through all of the Members. But the problem I'm having is that m.Profile is always null. The examples for LINQ to Entities on the MSDN library seem to suggest that I will be able to seamlessly follow the navigation relationships like that, but it doesn't seem to work that way. I found that if I first load the profiles in a separate call somehow, such as using entities.Profile.ToList, then m.Profile will point to a valid Profile.
So my question is, is there an elegant way to force the framework to automatically load the data along the navigation relationships, or do I need to do that explicitly with a join or something else?
Thanks
|
Okay I managed to find the answer I needed here <http://msdn.microsoft.com/en-us/magazine/cc507640.aspx>. The following query will make sure that the Profile entity is loaded:
```
IQueryable<Member> membersQuery = from m in members.Include("Profile") select m;
```
|
171,776 |
<p>I've looked at <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">this explanation on Wikipedia</a>, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example?</p>
<hr>
<p>What I can make from the answers so far, it seems to me to be just a more complex way of doing this:</p>
<pre><code>have an abstract class: MoveAlong with a virtual method: DoIt()
have class Car inherit from MoveAlong,
implementing DoIt() { ..start-car-and-drive..}
have class HorseCart inherit from MoveAlong,
implementing DoIt() { ..hit-horse..}
have class Bicycle inherit from MoveAlong,
implementing DoIt() { ..pedal..}
now I can call any function taking MoveAlong as parm
passing any of the three classes and call DoIt
Isn't this what Strategy intents? (just simpler?)
</code></pre>
<p>[Edit-update]
The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.)</p>
<hr>
<p>[Edit-update] <strong>Conclusion</strong></p>
<p>The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!).</p>
|
[
{
"answer_id": 171781,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "<p>In the Wikipedia example, those instances can be passed into a function that doesn't have to care which class those instances belong to. The function just calls <code>execute</code> on the object passed, and know that the Right Thing will happen.</p>\n\n<p>A typical example of the Strategy Pattern is how files work in Unix. Given a file descriptor, you can read from it, write to it, poll it, seek on it, send <code>ioctl</code>s to it, etc., without having to know whether you're dealing with a file, directory, pipe, socket, device, etc. (Of course some operations, like seek, don't work on pipes and sockets. But reads and writes will work just fine in these cases.)</p>\n\n<p>That means you can write generic code to handle all these different types of \"files\", without having to write separate code to deal with files versus directories, etc. The Unix kernel takes care of delegating the calls to the right code.</p>\n\n<p>Now, this is Strategy Pattern as used in kernel code, but you didn't specify that it had to be user code, just a real world example. :-)</p>\n"
},
{
"answer_id": 171782,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<p>In Java you use a cipher input stream to decrypt like so:</p>\n\n<pre><code>String path = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), ???);\n</code></pre>\n\n<p>But the cipher stream has no knowledge of what encryption algorithm you intend to use or the block size, padding strategy etc... New algorithms will be added all the time so hardcoding them is not practical. Instead we pass in a Cipher <strong>strategy object</strong> to tell it how to perform the decryption... </p>\n\n<pre><code>String path = ... ;\nCipher strategy = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), strategy);\n</code></pre>\n\n<p>In general you use the strategy pattern any time you have any object that knows <strong>what</strong> it needs to do but not <strong>how</strong> to do it. Another good example is layout managers in Swing, although in that case it didnt work out quite as well, see <a href=\"http://madbean.com/anim/totallygridbag\" rel=\"noreferrer\">Totally GridBag</a> for an amusing illustration.</p>\n\n<p>NB: There are two patterns at work here, as the wrapping of streams in streams is an example of <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"noreferrer\">Decorator</a>.</p>\n"
},
{
"answer_id": 171793,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": 2,
"selected": false,
"text": "<p>This design pattern allows to <strong>encapsulate algorithms</strong> in classes.</p>\n\n<p>The class that uses the strategy, the client class, is decoupled from the algorithm implementation. You can change the algorithms implementation, or add new algorithm without having to modify the client. This can also be done dynamically: the client can choose the algorithm he will use. </p>\n\n<p>For an example, imagine an application that needs to save an image to a file ; the image can be saved in different formats (PNG, JPG ...). The encoding algorithms will all be implemented in different classes sharing the same interface. The client class will choose one depending on the user preference. </p>\n"
},
{
"answer_id": 171797,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 2,
"selected": false,
"text": "<p>The strategy pattern allows you to exploit polimorphism without extending your main class. In essence, you are putting all variable parts in the strategy interface and implementations and the main class delegates to them. If your main object uses only one strategy, it's almost the same as having an abstract (pure virtual) method and different implementations in each subclass.</p>\n\n<p>The strategy approach offers some benefits:</p>\n\n<ul>\n<li>you can change strategy at runtime - compare this to changing the class type at runtime, which is much more difficult, compiler specific and impossible for non-virtual methods</li>\n<li>one main class can use more than one strategies which allows you to recombine them in multiple ways. Consider a class that walks a tree and evaluates a function based on each node and the current result. You can have a walking strategy (depth-first or breadth-first) and calculation strategy (some functor - i.e. 'count positive numbers' or 'sum'). If you do not use strategies, you will need to implement subclass for each combination of walking/calculation.</li>\n<li>code is easier to maintain as modifying or understanding strategy does not require you to understand the whole main object</li>\n</ul>\n\n<p>The drawback is that in many cases, the strategy pattern is an overkill - the switch/case operator is there for a reason. Consider starting with simple control flow statements (switch/case or if) then only if necessary move to class hierarchy and if you have more than one dimensions of variability, extract strategies out of it. Function pointers fall somewhere in the middle of this continuum.</p>\n\n<p>Recommended reading: </p>\n\n<ul>\n<li><a href=\"http://www.industriallogic.com/xp/refactoring/\" rel=\"nofollow noreferrer\">http://www.industriallogic.com/xp/refactoring/</a></li>\n<li><a href=\"http://www.refactoring.com/\" rel=\"nofollow noreferrer\">http://www.refactoring.com/</a></li>\n</ul>\n"
},
{
"answer_id": 171803,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 5,
"selected": true,
"text": "<p>The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface:</p>\n\n<pre><code>class IClockDisplay\n{\n public:\n virtual void Display( int hour, int minute, int second ) = 0;\n};\n</code></pre>\n\n<p>Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like:</p>\n\n<pre><code>class Clock\n{\n protected:\n IClockDisplay* mDisplay;\n int mHour;\n int mMinute;\n int mSecond;\n\n public:\n Clock( IClockDisplay* display )\n {\n mDisplay = display;\n }\n\n void Start(); // initiate the timer\n\n void OnTimer()\n {\n mDisplay->Display( mHour, mMinute, mSecond );\n }\n\n void ChangeDisplay( IClockDisplay* display )\n {\n mDisplay = display;\n }\n};\n</code></pre>\n\n<p>Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface.</p>\n\n<p>So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.</p>\n"
},
{
"answer_id": 171963,
"author": "questzen",
"author_id": 25210,
"author_profile": "https://Stackoverflow.com/users/25210",
"pm_score": 3,
"selected": false,
"text": "<p>There is a difference between strategy and decision/choice. Most of the time a we would be handling decisions/choices in our code, and realise them using if()/switch() constructs. Strategy pattern is useful when there is a need to decouple the logic/algorithm from usage. </p>\n\n<p>As an example, Think of a polling mechanism, where different users would check for resources/updates. Now we may want some of the priveliged users to be notified with a quicker turnaround time or with more details. Essentailly the logic being used changes based on user roles. Strategy makes sense from a design/architecture view point, at lower levels of granularity it should always be questioned.</p>\n"
},
{
"answer_id": 180839,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>One way to look at this is when you have a variety of actions you want to execute and those actions are determined at runtime. If you create a hashtable or dictionary of strategies, you could retrieve those strategies that correspond to command values or parameters. Once your subset is selected, you can simply iterate the list of strategies and execute in succession.</p>\n\n<p>One concrete example would be calculation the total of an order. Your parameters or commands would be base price, local tax, city tax, state tax, ground shipping and coupon discount. The flexibility come into play when you handle the variation of orders - some states will not have sales tax, while other orders will need to apply a coupon. You can dynamically assign the order of calculations. As long as you have accounted for all your calculations, you can accommodate all combinations without re-compiling.</p>\n"
},
{
"answer_id": 42359459,
"author": "PapaDiHatti",
"author_id": 3600304,
"author_profile": "https://Stackoverflow.com/users/3600304",
"pm_score": 0,
"selected": false,
"text": "<p>Strategy pattern works on simple idea i.e. \"Favor Composition over Inheritance\" so that strategy/algorithm can be changed at run time. To illustrate let's take an example where in we need to encrypt different messages based on its type e.g. MailMessage, ChatMessage etc.</p>\n\n<pre><code>class CEncryptor\n{\n virtual void encrypt () = 0;\n virtual void decrypt () = 0;\n};\nclass CMessage\n{\nprivate:\n shared_ptr<CEncryptor> m_pcEncryptor;\npublic:\n virtual void send() = 0;\n\n virtual void receive() = 0;\n\n void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor)\n {\n m_pcEncryptor = arg_pcEncryptor;\n }\n\n void performEncryption()\n {\n m_pcEncryptor->encrypt();\n }\n};\n</code></pre>\n\n<p>Now at runtime you can instantiate different Messages inherited from CMessage (like CMailMessage:public CMessage) with different encryptors (like CDESEncryptor:public CEncryptor)</p>\n\n<pre><code>CMessage *ptr = new CMailMessage();\nptr->setEncryptor(new CDESEncrypto());\nptr->performEncryption();\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
] |
I've looked at [this explanation on Wikipedia](http://en.wikipedia.org/wiki/Strategy_pattern), specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example?
---
What I can make from the answers so far, it seems to me to be just a more complex way of doing this:
```
have an abstract class: MoveAlong with a virtual method: DoIt()
have class Car inherit from MoveAlong,
implementing DoIt() { ..start-car-and-drive..}
have class HorseCart inherit from MoveAlong,
implementing DoIt() { ..hit-horse..}
have class Bicycle inherit from MoveAlong,
implementing DoIt() { ..pedal..}
now I can call any function taking MoveAlong as parm
passing any of the three classes and call DoIt
Isn't this what Strategy intents? (just simpler?)
```
[Edit-update]
The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.)
---
[Edit-update] **Conclusion**
The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!).
|
The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface:
```
class IClockDisplay
{
public:
virtual void Display( int hour, int minute, int second ) = 0;
};
```
Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like:
```
class Clock
{
protected:
IClockDisplay* mDisplay;
int mHour;
int mMinute;
int mSecond;
public:
Clock( IClockDisplay* display )
{
mDisplay = display;
}
void Start(); // initiate the timer
void OnTimer()
{
mDisplay->Display( mHour, mMinute, mSecond );
}
void ChangeDisplay( IClockDisplay* display )
{
mDisplay = display;
}
};
```
Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface.
So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.
|
171,778 |
<p>Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle).</p>
<p>Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order?</p>
<p>Based on the answer to the question referenced by nickf the answer is:</p>
<pre><code>select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty
</code></pre>
|
[
{
"answer_id": 171781,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "<p>In the Wikipedia example, those instances can be passed into a function that doesn't have to care which class those instances belong to. The function just calls <code>execute</code> on the object passed, and know that the Right Thing will happen.</p>\n\n<p>A typical example of the Strategy Pattern is how files work in Unix. Given a file descriptor, you can read from it, write to it, poll it, seek on it, send <code>ioctl</code>s to it, etc., without having to know whether you're dealing with a file, directory, pipe, socket, device, etc. (Of course some operations, like seek, don't work on pipes and sockets. But reads and writes will work just fine in these cases.)</p>\n\n<p>That means you can write generic code to handle all these different types of \"files\", without having to write separate code to deal with files versus directories, etc. The Unix kernel takes care of delegating the calls to the right code.</p>\n\n<p>Now, this is Strategy Pattern as used in kernel code, but you didn't specify that it had to be user code, just a real world example. :-)</p>\n"
},
{
"answer_id": 171782,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<p>In Java you use a cipher input stream to decrypt like so:</p>\n\n<pre><code>String path = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), ???);\n</code></pre>\n\n<p>But the cipher stream has no knowledge of what encryption algorithm you intend to use or the block size, padding strategy etc... New algorithms will be added all the time so hardcoding them is not practical. Instead we pass in a Cipher <strong>strategy object</strong> to tell it how to perform the decryption... </p>\n\n<pre><code>String path = ... ;\nCipher strategy = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), strategy);\n</code></pre>\n\n<p>In general you use the strategy pattern any time you have any object that knows <strong>what</strong> it needs to do but not <strong>how</strong> to do it. Another good example is layout managers in Swing, although in that case it didnt work out quite as well, see <a href=\"http://madbean.com/anim/totallygridbag\" rel=\"noreferrer\">Totally GridBag</a> for an amusing illustration.</p>\n\n<p>NB: There are two patterns at work here, as the wrapping of streams in streams is an example of <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"noreferrer\">Decorator</a>.</p>\n"
},
{
"answer_id": 171793,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": 2,
"selected": false,
"text": "<p>This design pattern allows to <strong>encapsulate algorithms</strong> in classes.</p>\n\n<p>The class that uses the strategy, the client class, is decoupled from the algorithm implementation. You can change the algorithms implementation, or add new algorithm without having to modify the client. This can also be done dynamically: the client can choose the algorithm he will use. </p>\n\n<p>For an example, imagine an application that needs to save an image to a file ; the image can be saved in different formats (PNG, JPG ...). The encoding algorithms will all be implemented in different classes sharing the same interface. The client class will choose one depending on the user preference. </p>\n"
},
{
"answer_id": 171797,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 2,
"selected": false,
"text": "<p>The strategy pattern allows you to exploit polimorphism without extending your main class. In essence, you are putting all variable parts in the strategy interface and implementations and the main class delegates to them. If your main object uses only one strategy, it's almost the same as having an abstract (pure virtual) method and different implementations in each subclass.</p>\n\n<p>The strategy approach offers some benefits:</p>\n\n<ul>\n<li>you can change strategy at runtime - compare this to changing the class type at runtime, which is much more difficult, compiler specific and impossible for non-virtual methods</li>\n<li>one main class can use more than one strategies which allows you to recombine them in multiple ways. Consider a class that walks a tree and evaluates a function based on each node and the current result. You can have a walking strategy (depth-first or breadth-first) and calculation strategy (some functor - i.e. 'count positive numbers' or 'sum'). If you do not use strategies, you will need to implement subclass for each combination of walking/calculation.</li>\n<li>code is easier to maintain as modifying or understanding strategy does not require you to understand the whole main object</li>\n</ul>\n\n<p>The drawback is that in many cases, the strategy pattern is an overkill - the switch/case operator is there for a reason. Consider starting with simple control flow statements (switch/case or if) then only if necessary move to class hierarchy and if you have more than one dimensions of variability, extract strategies out of it. Function pointers fall somewhere in the middle of this continuum.</p>\n\n<p>Recommended reading: </p>\n\n<ul>\n<li><a href=\"http://www.industriallogic.com/xp/refactoring/\" rel=\"nofollow noreferrer\">http://www.industriallogic.com/xp/refactoring/</a></li>\n<li><a href=\"http://www.refactoring.com/\" rel=\"nofollow noreferrer\">http://www.refactoring.com/</a></li>\n</ul>\n"
},
{
"answer_id": 171803,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 5,
"selected": true,
"text": "<p>The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface:</p>\n\n<pre><code>class IClockDisplay\n{\n public:\n virtual void Display( int hour, int minute, int second ) = 0;\n};\n</code></pre>\n\n<p>Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like:</p>\n\n<pre><code>class Clock\n{\n protected:\n IClockDisplay* mDisplay;\n int mHour;\n int mMinute;\n int mSecond;\n\n public:\n Clock( IClockDisplay* display )\n {\n mDisplay = display;\n }\n\n void Start(); // initiate the timer\n\n void OnTimer()\n {\n mDisplay->Display( mHour, mMinute, mSecond );\n }\n\n void ChangeDisplay( IClockDisplay* display )\n {\n mDisplay = display;\n }\n};\n</code></pre>\n\n<p>Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface.</p>\n\n<p>So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.</p>\n"
},
{
"answer_id": 171963,
"author": "questzen",
"author_id": 25210,
"author_profile": "https://Stackoverflow.com/users/25210",
"pm_score": 3,
"selected": false,
"text": "<p>There is a difference between strategy and decision/choice. Most of the time a we would be handling decisions/choices in our code, and realise them using if()/switch() constructs. Strategy pattern is useful when there is a need to decouple the logic/algorithm from usage. </p>\n\n<p>As an example, Think of a polling mechanism, where different users would check for resources/updates. Now we may want some of the priveliged users to be notified with a quicker turnaround time or with more details. Essentailly the logic being used changes based on user roles. Strategy makes sense from a design/architecture view point, at lower levels of granularity it should always be questioned.</p>\n"
},
{
"answer_id": 180839,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>One way to look at this is when you have a variety of actions you want to execute and those actions are determined at runtime. If you create a hashtable or dictionary of strategies, you could retrieve those strategies that correspond to command values or parameters. Once your subset is selected, you can simply iterate the list of strategies and execute in succession.</p>\n\n<p>One concrete example would be calculation the total of an order. Your parameters or commands would be base price, local tax, city tax, state tax, ground shipping and coupon discount. The flexibility come into play when you handle the variation of orders - some states will not have sales tax, while other orders will need to apply a coupon. You can dynamically assign the order of calculations. As long as you have accounted for all your calculations, you can accommodate all combinations without re-compiling.</p>\n"
},
{
"answer_id": 42359459,
"author": "PapaDiHatti",
"author_id": 3600304,
"author_profile": "https://Stackoverflow.com/users/3600304",
"pm_score": 0,
"selected": false,
"text": "<p>Strategy pattern works on simple idea i.e. \"Favor Composition over Inheritance\" so that strategy/algorithm can be changed at run time. To illustrate let's take an example where in we need to encrypt different messages based on its type e.g. MailMessage, ChatMessage etc.</p>\n\n<pre><code>class CEncryptor\n{\n virtual void encrypt () = 0;\n virtual void decrypt () = 0;\n};\nclass CMessage\n{\nprivate:\n shared_ptr<CEncryptor> m_pcEncryptor;\npublic:\n virtual void send() = 0;\n\n virtual void receive() = 0;\n\n void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor)\n {\n m_pcEncryptor = arg_pcEncryptor;\n }\n\n void performEncryption()\n {\n m_pcEncryptor->encrypt();\n }\n};\n</code></pre>\n\n<p>Now at runtime you can instantiate different Messages inherited from CMessage (like CMailMessage:public CMessage) with different encryptors (like CDESEncryptor:public CEncryptor)</p>\n\n<pre><code>CMessage *ptr = new CMailMessage();\nptr->setEncryptor(new CDESEncrypto());\nptr->performEncryption();\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3509/"
] |
Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle).
Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order?
Based on the answer to the question referenced by nickf the answer is:
```
select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty
```
|
The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface:
```
class IClockDisplay
{
public:
virtual void Display( int hour, int minute, int second ) = 0;
};
```
Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like:
```
class Clock
{
protected:
IClockDisplay* mDisplay;
int mHour;
int mMinute;
int mSecond;
public:
Clock( IClockDisplay* display )
{
mDisplay = display;
}
void Start(); // initiate the timer
void OnTimer()
{
mDisplay->Display( mHour, mMinute, mSecond );
}
void ChangeDisplay( IClockDisplay* display )
{
mDisplay = display;
}
};
```
Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface.
So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.
|
171,824 |
<p>I have a plug-in to an Eclipse RCP application that has a view. After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu.</p>
<p>I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere.</p>
|
[
{
"answer_id": 172082,
"author": "ILikeCoffee",
"author_id": 25270,
"author_profile": "https://Stackoverflow.com/users/25270",
"pm_score": 7,
"selected": true,
"text": "<p>You are probably looking for this:</p>\n\n<pre><code>PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(\"viewId\");\n</code></pre>\n"
},
{
"answer_id": 675164,
"author": "Imaskar",
"author_id": 78569,
"author_profile": "https://Stackoverflow.com/users/78569",
"pm_score": 4,
"selected": false,
"text": "<p>If called from handler of a command</p>\n\n<pre><code>HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().showView(viewId);\n</code></pre>\n\n<p>would be better, as I know. </p>\n"
},
{
"answer_id": 888682,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I found the need to bring the view to the front after it had been opened and pushed to the background. The activate method does the trick.</p>\n\n<pre><code>PlatformUI.getWorkbench()\n .getActiveWorkbenchWindow()\n .getActivePage()\n .activate(workbenchPartToActivate);\n</code></pre>\n\n<p>NOTE: The workbenchPartToActivate is an instance of <code>IWorkbenchPart</code>.</p>\n"
},
{
"answer_id": 22612362,
"author": "Max Hohenegger",
"author_id": 794836,
"author_profile": "https://Stackoverflow.com/users/794836",
"pm_score": 0,
"selected": false,
"text": "<p>In e4, the EPartService is responsible for opening Parts. This can also be used to open e3 ViewParts. Instantiate the following class through your IEclipseContext, call the openPart-Method, and you should see the Eclipse internal browser view.</p>\n\n<pre><code>public class Opener {\n @Inject\n EPartService partService;\n\n public void openPart() {\n MPart part = partService.createPart(\"org.eclipse.ui.browser.view\");\n part.setLabel(\"Browser\");\n\n partService.showPart(part, PartState.ACTIVATE);\n }\n}\n</code></pre>\n\n<p><a href=\"http://www.vogella.com/tutorials/Eclipse4Services/article.html#selectedservices_partservice5\" rel=\"nofollow\">Here</a> you can find an example of how this works together with your Application.e4xmi. </p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/725/"
] |
I have a plug-in to an Eclipse RCP application that has a view. After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu.
I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere.
|
You are probably looking for this:
```
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("viewId");
```
|
171,828 |
<p>When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question.</p>
<p>I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look in/at the JAR and switch to the same branch, version or tag that was the source of the released JAR.</p>
<p>How can I best adjust the ant build process so that the version information in the svn checkout remains in the created build?</p>
<p>I was thinking along the lines of:</p>
<ul>
<li>adding a VERSION file, but with what content?</li>
<li>storing information in the META-INF file, but under what property with which content?</li>
<li>copying sources into the result archive</li>
<li>added svn:properties to all sources with keywords in places the compiler leaves them be</li>
</ul>
<hr>
<p>I ended up using the svnversion approach (the accepted anwser), because it scans the entire subtree as opposed to svn info which just looks at the current file / directory. For this I defined the SVN task in the ant file to make it more portable. </p>
<pre><code><taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask">
<classpath>
<pathelement location="${dir.lib}/ant/svnant.jar"/>
<pathelement location="${dir.lib}/ant/svnClientAdapter.jar"/>
<pathelement location="${dir.lib}/ant/svnkit.jar"/>
<pathelement location="${dir.lib}/ant/svnjavahl.jar"/>
</classpath>
</taskdef>
</code></pre>
<p>Not all builds result in webservices. The ear file before deployment must remain the same name because of updating in the application server. Making the file executable is still an option, but until then I just include a version information file.</p>
<pre><code><target name="version">
<svn><wcVersion path="${dir.source}"/></svn>
<echo file="${dir.build}/VERSION">${revision.range}</echo>
</target>
</code></pre>
<p>Refs:<br>
svnrevision: <a href="http://svnbook.red-bean.com/en/1.1/re57.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.1/re57.html</a><br>
svn info <a href="http://svnbook.red-bean.com/en/1.1/re13.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.1/re13.html</a><br>
subclipse svn task: <a href="http://subclipse.tigris.org/svnant/svn.html" rel="noreferrer">http://subclipse.tigris.org/svnant/svn.html</a><br>
svn client: <a href="http://svnkit.com/" rel="noreferrer">http://svnkit.com/</a></p>
|
[
{
"answer_id": 171851,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 1,
"selected": false,
"text": "<p>From the top of my mind. A tag for each jar build?</p>\n"
},
{
"answer_id": 171858,
"author": "Martin",
"author_id": 24364,
"author_profile": "https://Stackoverflow.com/users/24364",
"pm_score": 1,
"selected": false,
"text": "<p>We have the first part of our build create a version.txt file in the root of the package and dump the tag used to check the code out from (in our case) CVS... Additionally, the final part of our build process checks the fully built EAR back into CVS for future reference.</p>\n\n<p>That way, if we have an issue with a webapp - it's just a case of asking the reporter to hit /app/version.txt - from there we can drill down the particular build history in CVS to locate the relevant components (handles different versions of libraries in apps) to locate the error.</p>\n\n<p>Not sure how much help this is to our support folk - but it's definitely something they complain about <strong>not</strong> being there!</p>\n"
},
{
"answer_id": 171859,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": false,
"text": "<p>You'd want to provide the Subversion branch and repository number. As discussed in <a href=\"https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number\">How to access the current Subversion build number?</a>, the <code>svn info</code> command will give you this information, which you can then use to build a VERSION file or place in any of the other files that you're building into your *AR files. If you've nothing else in mind, you could consider using the <a href=\"http://ant.apache.org/manual/Tasks/xmlproperty.html\" rel=\"nofollow noreferrer\">XmlProperty Ant task</a> to extract the relevant information from the output of your\nsvn info --xml command</p>\n"
},
{
"answer_id": 171861,
"author": "Rolf",
"author_id": 3540161,
"author_profile": "https://Stackoverflow.com/users/3540161",
"pm_score": 1,
"selected": false,
"text": "<p>Do automatic builds, and place a tag (with a date stamp) on the codebase when the build is succesful (with unittest ofcourse).</p>\n\n<p>In your delivery process, only deliver tagged builds to the customer. This way you are in control, and can place the tag name in a readme.txt somewhere, or have the filename of the ear file reflect the tagname.</p>\n\n<p>I personally switched back to CVS, and this is one of the reasons. In CVS, I can have a class report it's tag. All my jar files contain a \"main\" which makes them runnable. With support questions, I ask the customer to do a \"java -jar somejar.jar\" and send the output to me alongside the question.</p>\n\n<p>This way I'm sure of the build they-re using, and I can even have information like java version, OS type and version. Without the customer having to answer strange questions.</p>\n\n<p>It's simple but very effective.</p>\n"
},
{
"answer_id": 171865,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 1,
"selected": false,
"text": "<p>Why not put the build number into a properties file... this can then be easily read by the java and output to a Help | About dialog (applet/application), web-page footer or whatever other GUI you might have.</p>\n\n<p>(See the footer on every SOF page.... has the SVN version number there.)</p>\n\n<p>Seems a load easier than looking in the WAR/EAR/JAR etc easy time?</p>\n"
},
{
"answer_id": 171927,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 4,
"selected": true,
"text": "<p>Use the <em>svnversion</em> command in your Ant script to get the revision number:</p>\n\n<pre><code><exec executable=\"svnversion\" outputproperty=\"svnversion\" failonerror=\"true\">\n <env key=\"path\" value=\"/usr/bin\"/>\n <arg value=\"--no-newline\" />\n</exec>\n</code></pre>\n\n<p>Then use the <em>${svnversion}</em> property somewhere in your EAR. We put it in the EAR file name, but you could also put it in a readme or version file inside the EAR, or specify the version in the EAR's <em>META-INF/manifest.mf</em>:</p>\n\n<pre><code><!-- myapp-r1234.ear -->\n<property name=\"ear\" value=\"myapp-r${svnrevision}.ear\" />\n</code></pre>\n"
},
{
"answer_id": 219857,
"author": "Mike Miller",
"author_id": 16138,
"author_profile": "https://Stackoverflow.com/users/16138",
"pm_score": 0,
"selected": false,
"text": "<p>I store the absolute repository revision as a part of my full version number. This gives people a quick glance to see if a given change is in a given version or not.</p>\n\n<p>We also store the version number / build date / etc in the manifest file of the ear as custom properties, these are mostly informational only. We also store it in a properties file that is built into our jar, so the application can read it.</p>\n"
},
{
"answer_id": 2566341,
"author": "Mark O'Connor",
"author_id": 256618,
"author_profile": "https://Stackoverflow.com/users/256618",
"pm_score": 2,
"selected": false,
"text": "<p>Check out the <a href=\"http://jreleaseinfo.sourceforge.net/intro_e.html\" rel=\"nofollow noreferrer\">jreleaseinfo</a> project. Contains a ANT task that can generate a java class that can be called at runtime to display the release info for your project.</p>\n\n<p>I like its simplicity. </p>\n"
},
{
"answer_id": 2885741,
"author": "Ed Brannin",
"author_id": 25625,
"author_profile": "https://Stackoverflow.com/users/25625",
"pm_score": 2,
"selected": false,
"text": "<p>See also this question: <a href=\"https://stackoverflow.com/questions/690419/build-and-version-numbering-for-java-projects-ant-cvs-hudson\">Build and Version Numbering for Java Projects (ant, cvs, hudson)</a></p>\n\n<p>It includes several helpful code snippets.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16352/"
] |
When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question.
I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look in/at the JAR and switch to the same branch, version or tag that was the source of the released JAR.
How can I best adjust the ant build process so that the version information in the svn checkout remains in the created build?
I was thinking along the lines of:
* adding a VERSION file, but with what content?
* storing information in the META-INF file, but under what property with which content?
* copying sources into the result archive
* added svn:properties to all sources with keywords in places the compiler leaves them be
---
I ended up using the svnversion approach (the accepted anwser), because it scans the entire subtree as opposed to svn info which just looks at the current file / directory. For this I defined the SVN task in the ant file to make it more portable.
```
<taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask">
<classpath>
<pathelement location="${dir.lib}/ant/svnant.jar"/>
<pathelement location="${dir.lib}/ant/svnClientAdapter.jar"/>
<pathelement location="${dir.lib}/ant/svnkit.jar"/>
<pathelement location="${dir.lib}/ant/svnjavahl.jar"/>
</classpath>
</taskdef>
```
Not all builds result in webservices. The ear file before deployment must remain the same name because of updating in the application server. Making the file executable is still an option, but until then I just include a version information file.
```
<target name="version">
<svn><wcVersion path="${dir.source}"/></svn>
<echo file="${dir.build}/VERSION">${revision.range}</echo>
</target>
```
Refs:
svnrevision: <http://svnbook.red-bean.com/en/1.1/re57.html>
svn info <http://svnbook.red-bean.com/en/1.1/re13.html>
subclipse svn task: <http://subclipse.tigris.org/svnant/svn.html>
svn client: <http://svnkit.com/>
|
Use the *svnversion* command in your Ant script to get the revision number:
```
<exec executable="svnversion" outputproperty="svnversion" failonerror="true">
<env key="path" value="/usr/bin"/>
<arg value="--no-newline" />
</exec>
```
Then use the *${svnversion}* property somewhere in your EAR. We put it in the EAR file name, but you could also put it in a readme or version file inside the EAR, or specify the version in the EAR's *META-INF/manifest.mf*:
```
<!-- myapp-r1234.ear -->
<property name="ear" value="myapp-r${svnrevision}.ear" />
```
|
171,849 |
<p>I have a program that spits out an Excel workbook in Excel 2003 XML format. It works fine with one problem, I cannot get the column widths to set automatically.</p>
<p>A snippet of what I produce:</p>
<pre><code> <Table >
<Column ss:AutoFitWidth="1" ss:Width="2"/>
<Row ss:AutoFitHeight="0" ss:Height="14.55">
<Cell ss:StyleID="s62"><Data ss:Type="String">Database</Data></Cell>
</code></pre>
<p>This does not set the column to autofit. I have tried not setting width, I have tried many things and I am stuck.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 172057,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>Only date and number values are autofitted :-(\nquote: \"... We do not autofit textual values\"</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa140066.aspx#odc_xmlss_ss:column\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa140066.aspx#odc_xmlss_ss:column</a></p>\n"
},
{
"answer_id": 19912103,
"author": "supermankelly",
"author_id": 2547478,
"author_profile": "https://Stackoverflow.com/users/2547478",
"pm_score": 2,
"selected": false,
"text": "<p>Take your string length before passing to XML and construct the ss:Width=\"length\". </p>\n"
},
{
"answer_id": 26046306,
"author": "Mathijs Beentjes",
"author_id": 4080802,
"author_profile": "https://Stackoverflow.com/users/4080802",
"pm_score": 0,
"selected": false,
"text": "<p>Autofit does not work on cells with strings.\nTry to replace the Column-line in your example by the following code:</p>\n\n<pre><code> <xsl:for-each select=\"/*/*[1]/*\">\n <Column>\n <xsl:variable name=\"columnNum\" select=\"position()\"/>\n <xsl:for-each select=\"/*/*/*[position()=$columnNum]\">\n <xsl:sort select=\"concat(string-length(string-length(.)),string-length(.))\" order=\"descending\"/>\n <xsl:if test=\"position()=1\">\n <xsl:if test=\"string-length(.) &lt; 201\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"5.25 * (string-length(.)+2)\"/>\n </xsl:attribute>\n </xsl:if>\n <xsl:if test=\"string-length(.) &gt; 200\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"1000\"/>\n </xsl:attribute>\n </xsl:if>\n </xsl:if>\n <xsl:if test = \"local-name() = 'Sorteer'\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"0\"/>\n </xsl:attribute>\n </xsl:if>\n </xsl:for-each>\n </Column>\n </xsl:for-each>\n</code></pre>\n\n<p>Explanation: It sorts on string-length (longest string first), take first line of sorted strings, take length of that string * 5.25 and you will have a reasonable autofit.</p>\n\n<p>Sorting line:</p>\n\n<pre><code> <xsl:sort select=\"concat(string-length(string-length(.)),string-length(.))\" order=\"descending\"/>\n</code></pre>\n\n<p>explanation: if you just sort on length, like</p>\n\n<pre><code> <xsl:sort select=\"string-length(.)\" order=\"descending\"/>\n</code></pre>\n\n<p>because the lengths are handled as strings, 2 comes after 10, which you don't want. So you should left-pad the lengths in order to get it sorted right (because 002 comes before 010). However, as I couldn't find that padding function, I solved it by concattenating the length of the length with the length. A string with length of 100 will be translated to 3100 (first digit is length of length), you will see that the solution will always get string-sorted right. for example: 2 will be \"12\" and 10 will be \"210\", so this wil be string-sorted correctly. Only when the length of the length > 9 will cause problems, but strings of length 100000000 cannot be handled by Excel.</p>\n\n<p>Explantion of </p>\n\n<pre><code> <xsl:if test=\"string-length(.) &lt; 201\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"5.25 * (string-length(.)+2)\"/>\n </xsl:attribute>\n </xsl:if>\n <xsl:if test=\"string-length(.) &gt; 200\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"1000\"/>\n </xsl:attribute>\n </xsl:if>\n</code></pre>\n\n<p>I wanted to maximize length of string to about 200, but I could not get the Min function to work, like </p>\n\n<pre><code> <xsl:value-of select=\"5.25 * Min((string-length(.)+2),200)\"/>\n</code></pre>\n\n<p>So I had to do it the dirty way.</p>\n\n<p>I hope you can autofit now!</p>\n"
},
{
"answer_id": 45016090,
"author": "m.nachury",
"author_id": 8282397,
"author_profile": "https://Stackoverflow.com/users/8282397",
"pm_score": 0,
"selected": false,
"text": "<p>I know this post is old, but I'm updating it with a solution I coded if anyone still use openXml. It works fine with big files and small files.</p>\n\n<p>The algorithm is in vb, it takes an arraylist of arraylist of string (can be changed according to needs) to materialise a excel array.</p>\n\n<p>I used a Windows form to find width of rendered text, and links to select only the biggest cells (for big files efficiency)</p>\n\n<p>There:</p>\n\n<pre><code>Dim colsTmp as ArrayList '(of Arraylist(of String))\nDim cols as Arraylist '(of Integer) Max size of cols\n'Whe populate the Arraylist\nDim width As Integer\n'For each column\nFor i As Integer = 0 To colsTmp.Count - 1\n 'Whe sort cells by the length of their String\n colsTmp(i) = (From f In CType(colsTmp(i), String()) Order By f.Length).ToArray\n Dim deb As Integer = 0\n 'If they are more than a 100 cells whe only take the biggest 10%\n If colsTmp(i).length > 100 Then\n deb = colsTmp(i).length * 0.9\n End If\n 'For each cell taken\n For j As Integer = deb To colsTmp(i).length - 1\n 'Whe messure the lenght with the good font and size\n width = Windows.Forms.TextRenderer.MeasureText(colsTmp(i)(j), font).Width\n 'Whe convert it to \"excel lenght\"\n width = (width / 1.42) + 10\n 'Whe update the max Width\n If width > cols(i) Then cols(i) = width\n Next\nNext\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189/"
] |
I have a program that spits out an Excel workbook in Excel 2003 XML format. It works fine with one problem, I cannot get the column widths to set automatically.
A snippet of what I produce:
```
<Table >
<Column ss:AutoFitWidth="1" ss:Width="2"/>
<Row ss:AutoFitHeight="0" ss:Height="14.55">
<Cell ss:StyleID="s62"><Data ss:Type="String">Database</Data></Cell>
```
This does not set the column to autofit. I have tried not setting width, I have tried many things and I am stuck.
Thanks.
|
Only date and number values are autofitted :-(
quote: "... We do not autofit textual values"
<http://msdn.microsoft.com/en-us/library/aa140066.aspx#odc_xmlss_ss:column>
|
171,862 |
<p>When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:</p>
<pre><code>namespace Lib {
class A {
};
A operator+(const A&, const A&);
} // namespace Lib
</code></pre>
<p>or the global namespace</p>
<pre><code>namespace Lib {
class A {
};
} // namespace Lib
Lib::A operator+(const Lib::A&, const Lib::A&);
</code></pre>
<p>From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?</p>
|
[
{
"answer_id": 171869,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 6,
"selected": true,
"text": "<p>You should define them in the library namespace.\nThe compiler will find them anyway through argument dependant lookup.</p>\n\n<p>No need to pollute the global namespace.</p>\n"
},
{
"answer_id": 171881,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "<p>You should define it in the namespace, both because the syntax will be less verbose and not to clutter the global namespace.</p>\n\n<p>Actually, if you define your overloads in your class definition, this becomes a moot question:</p>\n\n<pre><code>namespace Lib {\n\nclass A {\npublic:\n A operator+(const A&);\n};\n\n} // namespace Lib\n</code></pre>\n"
},
{
"answer_id": 171882,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": false,
"text": "<p>Putting it into the library namespace works because of <a href=\"http://en.wikipedia.org/wiki/Argument_dependent_name_lookup\" rel=\"noreferrer\">Koenig lookup</a>.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78437/"
] |
When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:
```
namespace Lib {
class A {
};
A operator+(const A&, const A&);
} // namespace Lib
```
or the global namespace
```
namespace Lib {
class A {
};
} // namespace Lib
Lib::A operator+(const Lib::A&, const Lib::A&);
```
From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?
|
You should define them in the library namespace.
The compiler will find them anyway through argument dependant lookup.
No need to pollute the global namespace.
|
171,873 |
<p>I try to write KSH script for processing a file consisting of name-value pairs, several of them on each line.</p>
<p>Format is:</p>
<pre><code>NAME1 VALUE1,NAME2 VALUE2,NAME3 VALUE3, etc
</code></pre>
<p>Suppose I write:</p>
<pre><code>read l
IFS=","
set -A nvls $l
echo "$nvls[2]"
</code></pre>
<p>This will give me second name-value pair, nice and easy. Now, suppose that the task is extended so that values could include commas. They should be escaped, like this:</p>
<pre><code>NAME1 VALUE1,NAME2 VALUE2_1\,VALUE2_2,NAME3 VALUE3, etc
</code></pre>
<p>Obviously, my code no longer works, since "read" strips all quoting and second element of array will be just "NAME2 VALUE2_1". </p>
<p>I'm stuck with older ksh that does not have "read -A array". I tried various tricks with "read -r" and "eval set -A ....", to no avail. I can't use "read nvl1 nvl2 nvl3" to do unescaping and splitting inside read, since I dont know beforehand how many name-value pairs are in each line.</p>
<p>Does anyone have a useful trick up their sleeve for me?</p>
<p>PS
I know that I have do this in a nick of time in Perl, Python, even in awk. However, I have to do it in ksh (... or die trying ;)</p>
|
[
{
"answer_id": 171945,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 1,
"selected": false,
"text": "<p>As it often happens, I deviced an answer minutes after asking the question in public forum :(</p>\n\n<p>I worked around the quoting/unquoting issue by piping the input file through the following sed script:</p>\n\n<pre><code>sed -e 's/\\([^\\]\\),/\\1\\\n/g;s/$/\\\n/\n</code></pre>\n\n<p>It converted the input into:</p>\n\n<pre><code>NAME1.1 VALUE1.1\nNAME1.2 VALUE1.2_1\\,VALUE1.2_2\nNAME1.3 VALUE1.3\n<empty line>\nNAME2.1 VALUE2.1\n<second record continues>\n</code></pre>\n\n<p>Now, I can parse this input like this:</p>\n\n<pre><code>while read name value ; do\n echo \"$name => $value\"\ndone\n</code></pre>\n\n<p>Value will have its commas unquoted by \"read\", and I can stuff \"name\" and \"value\" in some associative array, if I like.</p>\n\n<p>PS\nSince I cant accept my own answer, should I delete the question, or ...?</p>\n"
},
{
"answer_id": 249153,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": true,
"text": "<p>You can also change the <code>\\,</code> pattern to something else that is known not to appear in any of your strings, and then change it back after you've split the input into an array. You can use the ksh builtin pattern-substitution syntax to do this, you don't need to use sed or awk or anything.</p>\n\n<pre><code>read l\nl=${l//\\\\,/!!}\nIFS=\",\"\nset -A nvls $l\nunset IFS\necho ${nvls[2]/!!/,}\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10105/"
] |
I try to write KSH script for processing a file consisting of name-value pairs, several of them on each line.
Format is:
```
NAME1 VALUE1,NAME2 VALUE2,NAME3 VALUE3, etc
```
Suppose I write:
```
read l
IFS=","
set -A nvls $l
echo "$nvls[2]"
```
This will give me second name-value pair, nice and easy. Now, suppose that the task is extended so that values could include commas. They should be escaped, like this:
```
NAME1 VALUE1,NAME2 VALUE2_1\,VALUE2_2,NAME3 VALUE3, etc
```
Obviously, my code no longer works, since "read" strips all quoting and second element of array will be just "NAME2 VALUE2\_1".
I'm stuck with older ksh that does not have "read -A array". I tried various tricks with "read -r" and "eval set -A ....", to no avail. I can't use "read nvl1 nvl2 nvl3" to do unescaping and splitting inside read, since I dont know beforehand how many name-value pairs are in each line.
Does anyone have a useful trick up their sleeve for me?
PS
I know that I have do this in a nick of time in Perl, Python, even in awk. However, I have to do it in ksh (... or die trying ;)
|
You can also change the `\,` pattern to something else that is known not to appear in any of your strings, and then change it back after you've split the input into an array. You can use the ksh builtin pattern-substitution syntax to do this, you don't need to use sed or awk or anything.
```
read l
l=${l//\\,/!!}
IFS=","
set -A nvls $l
unset IFS
echo ${nvls[2]/!!/,}
```
|
171,924 |
<p>Is it possible to check a bash script syntax without executing it?</p>
<p>Using Perl, I can run <code>perl -c 'script name'</code>. Is there any equivalent command for bash scripts?</p>
|
[
{
"answer_id": 171932,
"author": "andy",
"author_id": 6152,
"author_profile": "https://Stackoverflow.com/users/6152",
"pm_score": 10,
"selected": true,
"text": "<pre><code>bash -n scriptname\n</code></pre>\n\n<p>Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like <code>ech hello</code> instead of <code>echo hello</code>.</p>\n"
},
{
"answer_id": 4874883,
"author": "Jeevan",
"author_id": 600032,
"author_profile": "https://Stackoverflow.com/users/600032",
"pm_score": 5,
"selected": false,
"text": "<pre><code>sh -n script-name \n</code></pre>\n\n<p>Run this. If there are any syntax errors in the script, then it returns the same error message.\nIf there are no errors, then it comes out without giving any message. You can check immediately by using <code>echo $?</code>, which will return <code>0</code> confirming successful without any mistake.</p>\n\n<p>It worked for me well. I ran on Linux OS, Bash Shell.</p>\n"
},
{
"answer_id": 10721734,
"author": "Diego Tercero",
"author_id": 2046272,
"author_profile": "https://Stackoverflow.com/users/2046272",
"pm_score": 5,
"selected": false,
"text": "<p>I also enable the 'u' option on every bash script I write in order to do some extra checking:</p>\n\n<pre><code>set -u \n</code></pre>\n\n<p>This will report the usage of uninitialized variables, like in the following script 'check_init.sh'</p>\n\n<pre><code>#!/bin/sh\nset -u\nmessage=hello\necho $mesage\n</code></pre>\n\n<p>Running the script :</p>\n\n<pre><code>$ check_init.sh\n</code></pre>\n\n<p>Will report the following :</p>\n\n<blockquote>\n <p>./check_init.sh[4]: mesage: Parameter not set.</p>\n</blockquote>\n\n<p>Very useful to catch typos</p>\n"
},
{
"answer_id": 19573083,
"author": "dvd818",
"author_id": 328138,
"author_profile": "https://Stackoverflow.com/users/328138",
"pm_score": 7,
"selected": false,
"text": "<p>Time changes everything. <a href=\"http://www.shellcheck.net\" rel=\"noreferrer\">Here is a web site</a> which provide online syntax checking for shell script.</p>\n\n<p>I found it is very powerful detecting common errors.</p>\n\n<p><img src=\"https://i.stack.imgur.com/21zpv.png\" alt=\"enter image description here\"></p>\n\n<h3>About ShellCheck</h3>\n\n<p><a href=\"http://www.shellcheck.net/about.html\" rel=\"noreferrer\">ShellCheck</a> is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.</p>\n\n<p>Haskell source code is available on GitHub!</p>\n"
},
{
"answer_id": 21183850,
"author": "mug896",
"author_id": 1330706,
"author_profile": "https://Stackoverflow.com/users/1330706",
"pm_score": 2,
"selected": false,
"text": "<p>null command [colon] also useful when debugging to see variable's value</p>\n\n<pre><code>set -x\nfor i in {1..10}; do\n let i=i+1\n : i=$i\ndone\nset - \n</code></pre>\n"
},
{
"answer_id": 34109145,
"author": "Cengiz",
"author_id": 745827,
"author_profile": "https://Stackoverflow.com/users/745827",
"pm_score": 2,
"selected": false,
"text": "<p>There is <a href=\"https://plugins.jetbrains.com/plugin/4230?pr=idea\" rel=\"nofollow\">BashSupport plugin</a> for <a href=\"https://www.jetbrains.com/idea/\" rel=\"nofollow\">IntelliJ IDEA</a> which checks the syntax.</p>\n"
},
{
"answer_id": 45483537,
"author": "Gerald Hughes",
"author_id": 3264998,
"author_profile": "https://Stackoverflow.com/users/3264998",
"pm_score": 3,
"selected": false,
"text": "<p>I actually check all bash scripts in current dir for syntax errors WITHOUT running them using <code>find</code> tool:</p>\n<p><strong>Example:</strong></p>\n<p><code>find . -name '*.sh' -print0 | xargs -0 -P"$(nproc)" -I{} bash -n "{}"</code></p>\n<p>If you want to use it for a single file, just edit the wildcard with the name of the file.</p>\n"
},
{
"answer_id": 57053947,
"author": "E Ciotti",
"author_id": 415032,
"author_profile": "https://Stackoverflow.com/users/415032",
"pm_score": 1,
"selected": false,
"text": "<p>If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the \"sh -n\" or \"bash -n\" commands (see other answers) in a variable, and have a \"if/else\" based on that</p>\n\n<pre><code>bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \\; 2>&1 > /dev/null)\n if [ \"$bashErrLines\" != \"\" ]; then \n # at least one sh file in the bin dir has a syntax error\n echo $bashErrLines; \n exit; \n fi\n</code></pre>\n\n<p>Change \"sh\" with \"bash\" depending on your needs</p>\n"
},
{
"answer_id": 66181192,
"author": "Alberto Salvia Novella",
"author_id": 4620617,
"author_profile": "https://Stackoverflow.com/users/4620617",
"pm_score": 2,
"selected": false,
"text": "<p>For only <strong>validating</strong> syntax:</p>\n<blockquote>\n<p><a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a> [programPath]</p>\n</blockquote>\n<p>For <strong>running</strong> the program only if syntax passes, so debugging both syntax and execution:</p>\n<blockquote>\n<p><a href=\"https://gitlab.com/es20490446e/shellproof\" rel=\"nofollow noreferrer\">shellproof</a> [programPath]</p>\n</blockquote>\n"
},
{
"answer_id": 68978644,
"author": "Mike",
"author_id": 16783589,
"author_profile": "https://Stackoverflow.com/users/16783589",
"pm_score": 2,
"selected": false,
"text": "<p>Bash shell scripts will run a syntax check if you enable syntax checking with</p>\n<pre><code>set -o noexec\n</code></pre>\n<p>if you want to turn off syntax checking</p>\n<pre><code>set +o noexec\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
Is it possible to check a bash script syntax without executing it?
Using Perl, I can run `perl -c 'script name'`. Is there any equivalent command for bash scripts?
|
```
bash -n scriptname
```
Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like `ech hello` instead of `echo hello`.
|
171,928 |
<p>I am using the <a href="https://jqueryui.com/dialog/" rel="noreferrer"><code>jquery-ui-dialog</code></a> plugin</p>
<p>I am looking for way to refresh the page when in some circumstances when the dialog is closed.</p>
<p>Is there a way to capture a close event from the dialog?</p>
<p>I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner.</p>
|
[
{
"answer_id": 171953,
"author": "andy",
"author_id": 6152,
"author_profile": "https://Stackoverflow.com/users/6152",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm understanding the type of window you're talking about, wouldn't <b>$(window).unload()</b> (for the dialog window) give you the hook you need?\n<p>\n(And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then <b>all</b> the ways of closing that window are elements you could register click handers for.)\n<p>\n<b>Edit:</b> Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS. You can hook the <b>X</b> which closes the window by registering a click handler for the element with the class <b>ui-dialog-titlebar-close</b>.\n<p>\nMore useful, perhaps, is you tell you how to figure that out quickly. While displaying the dialog, just pop open FireBug and <b>Inspect</b> the elements that can close the window. You'll instantly see how they are defined and that gives you what you need to register the click handlers.\n<p>\nSo to directly answer your question, I believe the answer is really \"no\" -- there's isn't a close event you can hook, but \"yes\" -- you can hook all the ways to close the dialog box fairly easily and get what you want.</p>\n"
},
{
"answer_id": 172000,
"author": "Brownie",
"author_id": 6600,
"author_profile": "https://Stackoverflow.com/users/6600",
"pm_score": 9,
"selected": true,
"text": "<p>I have found it!</p>\n\n<p>You can catch the close event using the following code:</p>\n\n<pre><code> $('div#popup_content').on('dialogclose', function(event) {\n alert('closed');\n });\n</code></pre>\n\n<p>Obviously I can replace the alert with whatever I need to do.<br>\n<strong>Edit:</strong> As of Jquery 1.7, the bind() has become on()</p>\n"
},
{
"answer_id": 172506,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 8,
"selected": false,
"text": "<p>I believe you can also do it while creating the dialog (copied from a project I did):</p>\n\n<pre><code>dialog = $('#dialog').dialog({\n modal: true,\n autoOpen: false,\n width: 700,\n height: 500,\n minWidth: 700,\n minHeight: 500,\n position: [\"center\", 200],\n close: CloseFunction,\n overlay: {\n opacity: 0.5,\n background: \"black\"\n }\n});\n</code></pre>\n\n<p>Note <code>close: CloseFunction</code></p>\n"
},
{
"answer_id": 1706313,
"author": "Mo Ming C",
"author_id": 207599,
"author_profile": "https://Stackoverflow.com/users/207599",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$(\"#dialog\").dialog({\n autoOpen: false,\n resizable: false,\n width: 400,\n height: 140,\n modal: true, \n buttons: {\n \"SUBMIT\": function() { \n $(\"form\").submit();\n }, \n \"CANCEL\": function() { \n $(this).dialog(\"close\");\n } \n },\n close: function() {\n alert('close');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 6371397,
"author": "Alexei",
"author_id": 801390,
"author_profile": "https://Stackoverflow.com/users/801390",
"pm_score": 2,
"selected": false,
"text": "<p>You may try the following code for capturing the closing event for any item : page, dialog etc.</p>\n\n<pre><code>$(\"#dialog\").live('pagehide', function(event, ui) {\n $(this).hide();\n});\n</code></pre>\n"
},
{
"answer_id": 6751789,
"author": "morttan",
"author_id": 852580,
"author_profile": "https://Stackoverflow.com/users/852580",
"pm_score": 3,
"selected": false,
"text": "<p>This is what worked for me...</p>\n\n<pre><code>$('#dialog').live(\"dialogclose\", function(){\n //code to run on dialog close\n});\n</code></pre>\n"
},
{
"answer_id": 11116841,
"author": "Umair Noor",
"author_id": 1300558,
"author_profile": "https://Stackoverflow.com/users/1300558",
"pm_score": 4,
"selected": false,
"text": "<p>U can also try this</p>\n\n<pre><code>$(\"#dialog\").dialog({\n autoOpen: false,\n resizable: true,\n height: 400,\n width: 150,\n position: 'center',\n title: 'Term Sheet',\n beforeClose: function(event, ui) { \n console.log('Event Fire');\n },\n modal: true,\n buttons: {\n \"Submit\": function () {\n $(this).dialog(\"close\");\n },\n \"Cancel\": function () {\n $(this).dialog(\"close\");\n }\n }\n });\n</code></pre>\n"
},
{
"answer_id": 24798789,
"author": "Taksh",
"author_id": 3828576,
"author_profile": "https://Stackoverflow.com/users/3828576",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$( \"#dialogueForm\" ).dialog({\n autoOpen: false,\n height: \"auto\",\n width: \"auto\",\n modal: true,\n my: \"center\",\n at: \"center\",\n of: window,\n close : function(){\n // functionality goes here\n } \n });\n</code></pre>\n\n<p>\"close\" property of dialog gives the close event for the same.</p>\n"
},
{
"answer_id": 26839292,
"author": "Disper",
"author_id": 799750,
"author_profile": "https://Stackoverflow.com/users/799750",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.</p>\n</blockquote>\n\n<p>Because no one actually created an answer with using .<code>on()</code> instead of <code>bind()</code> i decided to create one.</p>\n\n<pre><code>$('div#dialog').on('dialogclose', function(event) {\n //custom logic fired after dialog is closed. \n});\n</code></pre>\n"
},
{
"answer_id": 40784613,
"author": "Mehdi Roostaeian",
"author_id": 5321043,
"author_profile": "https://Stackoverflow.com/users/5321043",
"pm_score": 3,
"selected": false,
"text": "<p>add option 'close' like under sample and do what you want inline function</p>\n\n<pre><code>close: function(e){\n //do something\n}\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600/"
] |
I am using the [`jquery-ui-dialog`](https://jqueryui.com/dialog/) plugin
I am looking for way to refresh the page when in some circumstances when the dialog is closed.
Is there a way to capture a close event from the dialog?
I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner.
|
I have found it!
You can catch the close event using the following code:
```
$('div#popup_content').on('dialogclose', function(event) {
alert('closed');
});
```
Obviously I can replace the alert with whatever I need to do.
**Edit:** As of Jquery 1.7, the bind() has become on()
|
171,962 |
<p>I'm storing all localizable strings in a <code>ResourceDictionary</code> (in <code>App.xaml</code>) and assign those via the <code>StaticResource</code> markup extension to <code>TextBlock.Text</code>, <code>Button.Content</code> etc.</p>
<p>In Beta 2 and RC0, <em>sometimes</em> parsing the XAML in <code>InitializeComponent()</code> will fail with an <code>AG_E_PARSER_BAD_PROPERTY_VALUE</code> on the line and position where I set the attribute value to the <code>StaticResource</code>.</p>
<p>It only happens sometimes: When restarting the app, it parses and displays without any problems. The same interface code works for days or weeks, then it happens again.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 179607,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": false,
"text": "<p>Parser, at least in beta 2, didnt like whitespace...</p>\n\n<p>For instance: </p>\n\n<pre><code>Text=\"{StaticResource bleh}\" \n</code></pre>\n\n<p>worked</p>\n\n<p>however this:</p>\n\n<pre><code>Text = \"{StaticResource bleh}\"\n</code></pre>\n\n<p>bombed</p>\n"
},
{
"answer_id": 3926850,
"author": "Amature Developer",
"author_id": 468657,
"author_profile": "https://Stackoverflow.com/users/468657",
"pm_score": 0,
"selected": false,
"text": "<p>Basically it means bad xaml somewhere in the code you can see the Line number and Position and see something is wrong .. I got the same error in my xaml Once corrected everything seems working </p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23222/"
] |
I'm storing all localizable strings in a `ResourceDictionary` (in `App.xaml`) and assign those via the `StaticResource` markup extension to `TextBlock.Text`, `Button.Content` etc.
In Beta 2 and RC0, *sometimes* parsing the XAML in `InitializeComponent()` will fail with an `AG_E_PARSER_BAD_PROPERTY_VALUE` on the line and position where I set the attribute value to the `StaticResource`.
It only happens sometimes: When restarting the app, it parses and displays without any problems. The same interface code works for days or weeks, then it happens again.
Any ideas?
|
Parser, at least in beta 2, didnt like whitespace...
For instance:
```
Text="{StaticResource bleh}"
```
worked
however this:
```
Text = "{StaticResource bleh}"
```
bombed
|
171,970 |
<p>When logging in C#, how can I learn the name of the method that called the current method? I know all about <code>System.Reflection.MethodBase.GetCurrentMethod()</code>, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like <code>Assembly.GetCallingAssembly()</code> but for methods.</p>
|
[
{
"answer_id": 171974,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 10,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>using System.Diagnostics;\n// Get call stack\nStackTrace stackTrace = new StackTrace(); \n// Get calling method name\nConsole.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);\n</code></pre>\n\n<p>one-liner:</p>\n\n<pre><code>(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name\n</code></pre>\n\n<p>It is from <em><a href=\"http://www.csharp-examples.net/reflection-calling-method-name/\" rel=\"noreferrer\">Get Calling Method using Reflection [C#]</a></em>.</p>\n"
},
{
"answer_id": 171980,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "<p>Note that doing so will be unreliable in release code, due to optimization. Additionally, running the application in sandbox mode (network share) won't allow you to grab the stack frame at all.</p>\n\n<p>Consider <a href=\"http://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"noreferrer\">aspect-oriented programming</a> (AOP), like <a href=\"https://www.postsharp.net/\" rel=\"noreferrer\">PostSharp</a>, which instead of being called from your code, modifies your code, and thus knows where it is at all times.</p>\n"
},
{
"answer_id": 172015,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 6,
"selected": false,
"text": "<p>In general, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx\" rel=\"noreferrer\"><code>System.Diagnostics.StackTrace</code></a> class to get a <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.aspx\" rel=\"noreferrer\"><code>System.Diagnostics.StackFrame</code></a>, and then use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx\" rel=\"noreferrer\"><code>GetMethod()</code></a> method to get a <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.aspx\" rel=\"noreferrer\"><code>System.Reflection.MethodBase</code></a> object. However, there are <a href=\"http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx\" rel=\"noreferrer\">some caveats</a> to this approach:</p>\n\n<ol>\n<li>It represents the <strong>runtime</strong> stack -- optimizations could inline a method, and you will <em><strong>not</strong></em> see that method in the stack trace.</li>\n<li>It will <strong><em>not</em></strong> show any native frames, so if there's even a chance your method is being called by a native method, this will <strong><em>not</em></strong> work, and there is in-fact no currently available way to do it.</li>\n</ol>\n\n<p>(<em>NOTE: I am just expanding on <a href=\"https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method#171974\">the answer</a> provided by Firas Assad</em>.)</p>\n"
},
{
"answer_id": 172487,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": false,
"text": "<p>We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack:</p>\n\n<pre><code>new StackFrame(1).GetMethod().Name;\n</code></pre>\n\n<p>This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that <code>new StackFrame(1)</code> or <code>.GetFrame(1)</code> don't return <code>null</code>, as unlikely as that possibility might seem.</p>\n\n<p>See this related question:\n<a href=\"https://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method\">Can you use reflection to find the name of the currently executing method?</a></p>\n"
},
{
"answer_id": 172558,
"author": "jesal",
"author_id": 20092,
"author_profile": "https://Stackoverflow.com/users/20092",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe you are looking for something like this:</p>\n\n<pre><code>StackFrame frame = new StackFrame(1);\nframe.GetMethod().Name; //Gets the current method name\n\nMethodBase method = frame.GetMethod();\nmethod.DeclaringType.Name //Gets the current class name\n</code></pre>\n"
},
{
"answer_id": 207091,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 2,
"selected": false,
"text": "<p>Another approach I have used is to add a parameter to the method in question. For example, instead of <code>void Foo()</code>, use <code>void Foo(string context)</code>. Then pass in some unique string that indicates the calling context.</p>\n\n<p>If you only need the caller/context for development, you can remove the <code>param</code> before shipping.</p>\n"
},
{
"answer_id": 2932128,
"author": "Flanders",
"author_id": 353229,
"author_profile": "https://Stackoverflow.com/users/353229",
"pm_score": 3,
"selected": false,
"text": "<pre><code>/// <summary>\n/// Returns the call that occurred just before the \"GetCallingMethod\".\n/// </summary>\npublic static string GetCallingMethod()\n{\n return GetCallingMethod(\"GetCallingMethod\");\n}\n\n/// <summary>\n/// Returns the call that occurred just before the the method specified.\n/// </summary>\n/// <param name=\"MethodAfter\">The named method to see what happened just before it was called. (case sensitive)</param>\n/// <returns>The method name.</returns>\npublic static string GetCallingMethod(string MethodAfter)\n{\n string str = \"\";\n try\n {\n StackTrace st = new StackTrace();\n StackFrame[] frames = st.GetFrames();\n for (int i = 0; i < st.FrameCount - 1; i++)\n {\n if (frames[i].GetMethod().Name.Equals(MethodAfter))\n {\n if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.\n {\n str = frames[i + 1].GetMethod().ReflectedType.FullName + \".\" + frames[i + 1].GetMethod().Name;\n break;\n }\n }\n }\n }\n catch (Exception) { ; }\n return str;\n}\n</code></pre>\n"
},
{
"answer_id": 5197900,
"author": "Orson",
"author_id": 207756,
"author_profile": "https://Stackoverflow.com/users/207756",
"pm_score": 2,
"selected": false,
"text": "<pre><code>private static MethodBase GetCallingMethod()\n{\n return new StackFrame(2, false).GetMethod();\n}\n\nprivate static Type GetCallingType()\n{\n return new StackFrame(2, false).GetMethod().DeclaringType;\n}\n</code></pre>\n\n<p>A fantastic class is here: <a href=\"http://www.csharp411.com/c-get-calling-method/\" rel=\"nofollow\">http://www.csharp411.com/c-get-calling-method/</a></p>\n"
},
{
"answer_id": 9621581,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 9,
"selected": false,
"text": "<p>In C# 5, you can get that information using <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/caller-information\" rel=\"noreferrer\">caller info</a>:</p>\n<pre><code>//using System.Runtime.CompilerServices;\npublic void SendError(string Message, [CallerMemberName] string callerName = "") \n{ \n Console.WriteLine(callerName + "called me."); \n} \n</code></pre>\n<p>You can also get the <code>[CallerFilePath]</code> and <code>[CallerLineNumber]</code>.</p>\n"
},
{
"answer_id": 13496108,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 7,
"selected": false,
"text": "<p>You can use Caller Information and optional parameters:</p>\n\n<pre><code>public static string WhoseThere([CallerMemberName] string memberName = \"\")\n{\n return memberName;\n}\n</code></pre>\n\n<p>This test illustrates this:</p>\n\n<pre><code>[Test]\npublic void Should_get_name_of_calling_method()\n{\n var methodName = CachingHelpers.WhoseThere();\n Assert.That(methodName, Is.EqualTo(\"Should_get_name_of_calling_method\"));\n}\n</code></pre>\n\n<p>While the StackTrace works quite fast above and would not be a performance issue in most cases the Caller Information is much faster still. In a sample of 1000 iterations, I clocked it as 40 times faster.</p>\n"
},
{
"answer_id": 13874947,
"author": "caner",
"author_id": 1829714,
"author_profile": "https://Stackoverflow.com/users/1829714",
"pm_score": 0,
"selected": false,
"text": "<pre><code>StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1);\nstring methodName = caller.GetMethod().Name;\n</code></pre>\n\n<p>will be enough, I think.</p>\n"
},
{
"answer_id": 16840439,
"author": "smiron",
"author_id": 1662637,
"author_profile": "https://Stackoverflow.com/users/1662637",
"pm_score": 1,
"selected": false,
"text": "<p>We can also use lambda's in order to find the caller.</p>\n\n<p>Suppose you have a method defined by you:</p>\n\n<pre><code>public void MethodA()\n {\n /*\n * Method code here\n */\n }\n</code></pre>\n\n<p>and you want to find it's caller.</p>\n\n<p><em>1</em>. Change the method signature so we have a parameter of type Action (Func will also work):</p>\n\n<pre><code>public void MethodA(Action helperAction)\n {\n /*\n * Method code here\n */\n }\n</code></pre>\n\n<p><em>2</em>. Lambda names are not generated randomly. The rule seems to be: > <CallerMethodName>__X\nwhere CallerMethodName is replaced by the previous function and X is an index.</p>\n\n<pre><code>private MethodInfo GetCallingMethodInfo(string funcName)\n {\n return GetType().GetMethod(\n funcName.Substring(1,\n funcName.IndexOf(\"&gt;\", 1, StringComparison.Ordinal) - 1)\n );\n }\n</code></pre>\n\n<p><em>3</em>. When we call MethodA the Action/Func parameter has to be generated by the caller method.\nExample:</p>\n\n<pre><code>MethodA(() => {});\n</code></pre>\n\n<p><em>4</em>. Inside MethodA we can now call the helper function defined above and find the MethodInfo of the caller method.</p>\n\n<p>Example:</p>\n\n<pre><code>MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name);\n</code></pre>\n"
},
{
"answer_id": 33237690,
"author": "Ivan Pinto",
"author_id": 5467316,
"author_profile": "https://Stackoverflow.com/users/5467316",
"pm_score": 6,
"selected": false,
"text": "<p><em>As of .NET 4.5 you can use <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information\" rel=\"noreferrer\">Caller Information</a> Attributes:</em></p>\n\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerfilepathattribute\" rel=\"noreferrer\"><code>CallerFilePath</code></a> - The source file that called the function;</li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerlinenumberattribute\" rel=\"noreferrer\"><code>CallerLineNumber</code></a> - Line of code that called the function; </li>\n<li><p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute\" rel=\"noreferrer\"><code>CallerMemberName</code></a> - Member that called the function.</p>\n\n<pre><code>public void WriteLine(\n [CallerFilePath] string callerFilePath = \"\", \n [CallerLineNumber] long callerLineNumber = 0,\n [CallerMemberName] string callerMember= \"\")\n{\n Debug.WriteLine(\n \"Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}\", \n callerFilePath,\n callerLineNumber,\n callerMember);\n}\n</code></pre></li>\n</ul>\n\n<p> </p>\n\n<p>This facility is also present in \".NET Core\" and \".NET Standard\".</p>\n\n<p><strong>References</strong></p>\n\n<ol>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information\" rel=\"noreferrer\">Microsoft - Caller Information (C#)</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerfilepathattribute\" rel=\"noreferrer\">Microsoft - <code>CallerFilePathAttribute</code> Class</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerlinenumberattribute\" rel=\"noreferrer\">Microsoft - <code>CallerLineNumberAttribute</code> Class</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute\" rel=\"noreferrer\">Microsoft - <code>CallerMemberNameAttribute</code> Class</a></li>\n</ol>\n"
},
{
"answer_id": 33939304,
"author": "Tikall",
"author_id": 2470012,
"author_profile": "https://Stackoverflow.com/users/2470012",
"pm_score": 7,
"selected": false,
"text": "<p>A quick recap of the 2 approaches with speed comparison being the important part.</p>\n\n<p><a href=\"http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx\">http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx</a></p>\n\n<p><strong>Determining the caller at compile-time</strong></p>\n\n<pre><code>static void Log(object message, \n[CallerMemberName] string memberName = \"\",\n[CallerFilePath] string fileName = \"\",\n[CallerLineNumber] int lineNumber = 0)\n{\n // we'll just use a simple Console write for now \n Console.WriteLine(\"{0}({1}):{2} - {3}\", fileName, lineNumber, memberName, message);\n}\n</code></pre>\n\n<p><strong>Determining the caller using the stack</strong></p>\n\n<pre><code>static void Log(object message)\n{\n // frame 1, true for source info\n StackFrame frame = new StackFrame(1, true);\n var method = frame.GetMethod();\n var fileName = frame.GetFileName();\n var lineNumber = frame.GetFileLineNumber();\n\n // we'll just use a simple Console write for now \n Console.WriteLine(\"{0}({1}):{2} - {3}\", fileName, lineNumber, method.Name, message);\n}\n</code></pre>\n\n<p><strong>Comparison of the 2 approaches</strong></p>\n\n<pre><code>Time for 1,000,000 iterations with Attributes: 196 ms\nTime for 1,000,000 iterations with StackTrace: 5096 ms\n</code></pre>\n\n<blockquote>\n <p>So you see, using the attributes is much, much faster! Nearly 25x\n faster in fact.</p>\n</blockquote>\n"
},
{
"answer_id": 37885619,
"author": "Camilo Terevinto",
"author_id": 2141621,
"author_profile": "https://Stackoverflow.com/users/2141621",
"pm_score": 4,
"selected": false,
"text": "<p>Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer:</p>\n<pre><code>internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "")\n{\n Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);\n}\n</code></pre>\n<p>This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text".<br />\nSample output:</p>\n<pre><code>6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized\n</code></pre>\n<p>Sample use:</p>\n<pre><code>Logger.WriteInformation<MainWindow>("MainWindow initialized");\n</code></pre>\n"
},
{
"answer_id": 53942029,
"author": "Arian",
"author_id": 648723,
"author_profile": "https://Stackoverflow.com/users/648723",
"pm_score": 2,
"selected": false,
"text": "<p>For getting Method Name and Class Name try this:</p>\n\n<pre><code> public static void Call()\n {\n StackTrace stackTrace = new StackTrace();\n\n var methodName = stackTrace.GetFrame(1).GetMethod();\n var className = methodName.DeclaringType.Name.ToString();\n\n Console.WriteLine(methodName.Name + \"*****\" + className );\n }\n</code></pre>\n"
},
{
"answer_id": 53942589,
"author": "cdev",
"author_id": 827918,
"author_profile": "https://Stackoverflow.com/users/827918",
"pm_score": 2,
"selected": false,
"text": "<p>Extra information to Firas Assaad answer.</p>\n\n<p>I have used <code>new StackFrame(1).GetMethod().Name;</code> in .net core 2.1 with dependency injection and I am getting calling method as 'Start'. </p>\n\n<p>I tried with <code>[System.Runtime.CompilerServices.CallerMemberName] string callerName = \"\"</code>\nand it gives me correct calling method</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470/"
] |
When logging in C#, how can I learn the name of the method that called the current method? I know all about `System.Reflection.MethodBase.GetCurrentMethod()`, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like `Assembly.GetCallingAssembly()` but for methods.
|
Try this:
```
using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
```
one-liner:
```
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
```
It is from *[Get Calling Method using Reflection [C#]](http://www.csharp-examples.net/reflection-calling-method-name/)*.
|
171,999 |
<p>How can I extract the whole line in a row, for example, row 3.
These data are saved in my text editor in linux.
Here's my data:</p>
<pre><code>1,julz,kath,shiela,angel
2,may,ann,janice,aika
3,christal,justine,kim
4,kris,allan,jc,mine
</code></pre>
<p>I want output like:</p>
<pre><code>3,christal,justine,kim
</code></pre>
|
[
{
"answer_id": 172005,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>You can assign the diamond operator on your filehandle to a list, each element will be a line or row.</p>\n\n<pre><code>open $fh, \"myfile.txt\";\nmy @lines = <$fh>;\n</code></pre>\n\n<p><strong>EDIT:</strong> This solution grabs all the lines so that you can access any one you want, e.g. row 3 would be <code>$lines[2]</code> ... If you really only want one specific line, that'd be a different solution, like the other answerers'.</p>\n"
},
{
"answer_id": 172017,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$ perl -ne'print if $. == 3' your_file.txt\n</code></pre>\n\n<p>Below is a script version of <a href=\"https://stackoverflow.com/questions/171999/how-can-i-extract-a-line-or-row-in-perl#172665\">@ysth's answer</a>:</p>\n\n<pre><code>$ perl -mTie::File -e'tie @lines, q(Tie::File), q(your_file.txt); \n> print $lines[2]'\n</code></pre>\n"
},
{
"answer_id": 172046,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p>The following snippet reads in the first three lines, prints only the third then exits to ensure that no unnecessary processing takes place.</p>\n\n<p>Without the exit, the script would continue to process the input file despite you knowing that you have no use for it.</p>\n\n<pre><code>perl -ne 'if ($. == 3) {print;exit}' infile.txt\n</code></pre>\n\n<p>As <a href=\"http://perldoc.perl.org/perlvar.html\" rel=\"nofollow noreferrer\">perlvar</a> points out, <code>$.</code> is the current line number for the last file handle accessed.</p>\n"
},
{
"answer_id": 172355,
"author": "Randal Schwartz",
"author_id": 22483,
"author_profile": "https://Stackoverflow.com/users/22483",
"pm_score": 3,
"selected": false,
"text": "<p>If it's always the third line:</p>\n\n<pre><code>perl -ne 'print if 3..3' <infile >outfile\n</code></pre>\n\n<p>If it's always the one that has a numeric value of \"3\" as the first column:</p>\n\n<pre><code>perl -F, -nae 'print if $F[0] == 3' <infile >outfile # thanks for the comment doh!\n</code></pre>\n\n<p>Since you didn't say how you were identifying that line, I am providing alternatives.</p>\n"
},
{
"answer_id": 172665,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "<p>Um, the -n answers are assuming the question is \"what is a script that...\". In which case, perl isn't even the best answer. But I don't read that into the question.</p>\n\n<p>In general, if the lines are not of fixed length, you have to read through a file line by\nline until you get to the line you want. <a href=\"http://search.cpan.org/dist/Tie-File\" rel=\"nofollow noreferrer\">Tie::File</a> automates this process for you (though since the code it would replace is so trivial, I rarely bother with it, myself).</p>\n\n<pre><code>use Tie::File;\nuse Fcntl \"O_RDONLY\";\ntie my @line, \"Tie::File\", \"yourfilename\", mode => O_RDONLY\n or die \"Couldn't open file: $!\";\nprint \"The third line is \", $line[2];\n</code></pre>\n"
},
{
"answer_id": 173951,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 2,
"selected": false,
"text": "<p>For a more general solution:</p>\n\n<pre><code>open my $fh, '<', 'infile.txt';\nwhile (my $line = <$fh>) {\n print $line if i_want_this_line($line);\n}\n</code></pre>\n\n<p>where i_want_this_line implements the criteria defining which line(s) you want.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/171999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I extract the whole line in a row, for example, row 3.
These data are saved in my text editor in linux.
Here's my data:
```
1,julz,kath,shiela,angel
2,may,ann,janice,aika
3,christal,justine,kim
4,kris,allan,jc,mine
```
I want output like:
```
3,christal,justine,kim
```
|
The following snippet reads in the first three lines, prints only the third then exits to ensure that no unnecessary processing takes place.
Without the exit, the script would continue to process the input file despite you knowing that you have no use for it.
```
perl -ne 'if ($. == 3) {print;exit}' infile.txt
```
As [perlvar](http://perldoc.perl.org/perlvar.html) points out, `$.` is the current line number for the last file handle accessed.
|
172,018 |
<p>Is there a way to exclude all svn externals when doing a recursive update?</p>
<p>Is there a way to exclude only 1 of all of the svn externals when doing a recursive update?</p>
<p>Basically I'd like to cut down the svn update time, and a couple of the SVN externals that I have will just about never get updated.</p>
|
[
{
"answer_id": 172043,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, there is an option for this (to ignore all):</p>\n\n<pre><code>> svn update --ignore-externals\n</code></pre>\n\n<p>I don't know of any option to specifically ignore one or some externals while updating the rest. </p>\n"
},
{
"answer_id": 454228,
"author": "Wim Coenen",
"author_id": 52626,
"author_profile": "https://Stackoverflow.com/users/52626",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using TortoiseSVN, you can do the same thing as \"svn update --ignore-externals\". Use the \"<strong>Update to revision...</strong>\" menu item instead of the normal \"<strong>Update</strong>\".\nOn that dialog you have a \"<strong>Omit Externals</strong>\" checkbox.</p>\n"
},
{
"answer_id": 576596,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 1,
"selected": false,
"text": "<p>I'd recommend changing the default context menu items to have Update to Revision on the main context menu.</p>\n\n<p>In the TortoiseSVN settings, go to 'Look and Feel', then uncheck items you want main folder context menu and check items you want in the submenu.</p>\n\n<p>I have the following <strong><em>unchecked</em></strong>. </p>\n\n<ul>\n<li>Checkout</li>\n<li>Commit</li>\n<li>Show Log</li>\n<li>Check for modifications</li>\n<li>Update to Revision</li>\n</ul>\n\n<p>The great thing about having all these items is that they only show up when relevant, ie, when the directory is a working copy. So for a non SVN folder you will just get Checkout.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
Is there a way to exclude all svn externals when doing a recursive update?
Is there a way to exclude only 1 of all of the svn externals when doing a recursive update?
Basically I'd like to cut down the svn update time, and a couple of the SVN externals that I have will just about never get updated.
|
Yes, there is an option for this (to ignore all):
```
> svn update --ignore-externals
```
I don't know of any option to specifically ignore one or some externals while updating the rest.
|
172,095 |
<p>I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc. </p>
<p>I'm using the web reference in a console application. I often change something, recompile and run. Compilation is fast, but newing up the web service reference is very slow, taking some 15-20 seconds:
<code>
CrmService service = new CrmService();
</code>
Profiling reveals that all time is spent in the SoapHttpClientProtocol constructor.</p>
<p>The culprit is apparently the fact that the XML serialization code (not included in the 90k loc mentioned above) is generated at run time, before being JIT'ed. This happens during the constructor call. The wait is rather frustrating when playing around and trying things out.</p>
<p>I've tried various combinations of sgen.exe, ngen and XGenPlus (which takes several hours and generates 500MB of additional code) but to no avail. I've considered implementing a Windows service that have few CrmService instances ready to dish out when needed but that seems excessive.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 172106,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 1,
"selected": false,
"text": "<p>You might wish to look into the <a href=\"http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>Sgen.exe</code></a> tool that comes with .NET. There's also a handy little thing in Visual Studio's C# project properties \"Build\" page, at the very bottom, called \"Build serialization assembly\" that automatically runs <code>Sgen</code> for you.</p>\n"
},
{
"answer_id": 297883,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I believe that this is not an SGEN issue. I have looked at the constructor code, and I see that it is doing a lot of reflection (based on the XmlIncludeAttribute on the class). It reflects on all of them, and can take a really long time.</p>\n"
},
{
"answer_id": 376210,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>There is a pre-generated XmlSerializer assembly that comes with CRM. Check to see whether you have SdkTypeProxy.XmlSerializers.dll and SdkProxy.XmlSerializers.dll in the GAC.</p>\n\n<p>If you don't then that means that when you create the CrmService, .net will generate the XmlSerializer assembly which can take some time.\nHope this helps</p>\n"
},
{
"answer_id": 965857,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 6,
"selected": true,
"text": "<p>The following is ripped from <a href=\"http://communities.vmware.com/thread/47063\" rel=\"noreferrer\">this</a> thread on the VMWare forums:</p>\n\n<p>Hi folks,</p>\n\n<p>We've found that sgen.exe does work. It'just that there is a couple of additional steps beyond pre-generating the serializer dll's that we missed in this thread. Here is the detailed instruction</p>\n\n<h2>PROBLEM</h2>\n\n<p>When using the VIM 2.0 SDK from .NET requires long time to instantiate the VimService class. (The VimService class is the proxy class generated by running 'wsdl.exe vim.wsdl vimService.wsdl')</p>\n\n<p>In other words, the following line of code:</p>\n\n<pre><code>_service = new VimService();\n</code></pre>\n\n<p>Could take about 50 seconds to execute.</p>\n\n<h2>CAUSE</h2>\n\n<p>Apparently, the .NET <code>XmlSerializer</code> uses the <code>System.Xml.Serialization.*</code> attributes annotating the proxy classes to generate serialization code in run time. When the proxy classes are many and large, as is the code in VimService.cs, the generation of the serialization code can take a long time.</p>\n\n<h2>SOLUTION</h2>\n\n<p>This is a known problem with how the Microsoft .NET serializer works.</p>\n\n<p>Here are some references that MSDN provides about solving this problem:</p>\n\n<p><a href=\"http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx</a>\n<a href=\"http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx</a></p>\n\n<p>Unfortunately, none of the above references describe the complete solution to the problem. Instead they focus on how to pre-generate the XML serialization code.</p>\n\n<p>The complete fix involves the following steps:</p>\n\n<ol>\n<li><p>Create an assembly (a DLL) with the pre-generated XML serializer code</p></li>\n<li><p>Remove all references to System.Xml.Serialization.* attributes from the proxy code (i.e. from the VimService.cs file)</p></li>\n<li><p>Annotate the main proxy class with the XmlSerializerAssemblyAttribute to point it to where the XML serializer assembly is.</p></li>\n</ol>\n\n<p>Skipping step 2 leads to only 20% improvement in the instantiation time for the <code>VimService</code> class. Skipping either step 1 or 3 leads to incorrect code. With all three steps 98% improvement is achieved.</p>\n\n<p>Here are step-by-step instructions:</p>\n\n<p>Before you begin, makes sure you are using .NET verison 2.0 tools. This solution will not work with version 1.1 of .NET because the sgen tool and the <code>XmlSerializationAssemblyAttribute</code> are only available in version 2.0 of .NET</p>\n\n<ol>\n<li><p>Generate the VimService.cs file from the WSDL, using wsdl.exe:</p>\n\n<p><code>wsdl.exe vim.wsdl vimService.wsdl</code></p>\n\n<p>This will output the VimService.cs file in the current directory</p></li>\n<li><p>Compile VimService.cs into a library</p>\n\n<p><code>csc /t:library /out:VimService.dll VimService.cs</code></p></li>\n<li><p>Use the sgen tool to pre-generate and compile the XML serializers:</p>\n\n<p><code>sgen /p VimService.dll</code></p>\n\n<p>This will output the VimService.XmlSerializers.dll in the current directory</p></li>\n<li><p>Go back to the VimService.cs file and remove all <code>System.Xml.Serialization.*</code> attributes. Because the code code is large, the best way to achieve that is by using some regular expression substitution tool. Be careful as you do this because not all attributes appear on a line by themselves. Some are in-lined as part of a method declaration.</p>\n\n<p>If you find this step difficult, here is a simplified way of doing it:</p>\n\n<p>Assuming you are writing C#, do a global replace on the following string:</p>\n\n<p><code>[System.Xml.Serialization.XmlIncludeAttribute</code></p>\n\n<p>and replace it with:</p>\n\n<p><code>// [System.Xml.Serialization.XmlIncludeAttribute</code></p>\n\n<p>This will get rid of the <code>Xml.Serialization</code> attributes that are the biggest culprits for the slowdown by commenting them out. If you are using some other .NET language, just modify the replaced string to be prefix-commented according to the syntax of that language. This simplified approach will get you most of the speedup that you can get. Removing the rest of the Xml.Serialization attributes only achieves an extra 0.2 sec speedup.</p></li>\n<li><p>Add the following attribute to the VimService class in VimService.cs:</p>\n\n<p><code>[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = \"VimService.XmlSerializers\")]</code></p>\n\n<p>You should end up with something like this:</p>\n\n<p><code>// ... Some code here ...\n[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = \"VimService.XmlSerializers\")]\npublic partial class VimService : System.Web.Services.Protocols.SoapHttpClientProtocol {\n// ... More code here</code></p></li>\n<li><p>Regenerate VimSerice.dll library by</p>\n\n<p><code>csc /t:library /out:VimService.dll VimService.cs</code></p></li>\n<li><p>Now, from your application, you can add a reference to VimSerice.dll library.</p></li>\n<li><p>Run your application and verify that VimService object instanciation time is reduced.</p></li>\n</ol>\n\n<h2>ADDITIONAL NOTES</h2>\n\n<p>The sgen tool is a bit of a black box and its behavior varies depending on what you have in your Machine.config file. For example, by default it is supposed to ouptut optimized non-debug code, but that is not always the case. To get some visibility into the tool, use the /k flag in step 3, which will cause it to keep all its temporary generated files, including the source files and command line option files it generated.</p>\n\n<p>Even after the above fix the time it takes to instantiate the VimService class for the first time is not instantaneous (1.5 sec). Based on empirical observation, it appears that the majority of the remaining time is due to processing the <code>SoapDocumentMethodAttribute</code> attributes. At this point it is unclear how this time can be reduced. The pre-generated XmlSerializer assembly does not account for the SOAP-related attributes, so these attributes need to remain in the code. The good news is that only the first instantiation of the VimService class for that app takes long. So if the extra 1.5 seconds are a problem, one could try to do a dummy instantiation of this class at the beginning of the application as a means to improve user experience of login time. </p>\n"
},
{
"answer_id": 13755462,
"author": "Adam Marshall",
"author_id": 1420588,
"author_profile": "https://Stackoverflow.com/users/1420588",
"pm_score": 0,
"selected": false,
"text": "<p>I came across this thread when trying to find out why my initial <code>SoapHttpClientProtocol</code> calls were taking so long. </p>\n\n<p>I found that setting the Proxy to null/Empty stopped the Proxy AutoDetect from occurring - This was taking up to 7 seconds on the initial call:</p>\n\n<pre><code>this.Proxy = GlobalProxySelection.GetEmptyWebProxy();\n</code></pre>\n"
},
{
"answer_id": 39400236,
"author": "Dragan Jovanović",
"author_id": 1506226,
"author_profile": "https://Stackoverflow.com/users/1506226",
"pm_score": 0,
"selected": false,
"text": "<p>I have used above detailed answer as guide, and went a few steps forward, making a script to automate process. Script is made out of two files :</p>\n\n<p>generateproxy.bat :</p>\n\n<pre><code>REM if your path for wsdl, csc or sgen is missing, please add it here (it varies from machine to machine)\nset PATH=%PATH%;C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.1 Tools;C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\n\nwsdl http://localhost:57237/VIM_WS.asmx?wsdl REM create source code out of WSDL\nPowerShell.exe -ExecutionPolicy Bypass -Command \"& '%~dpn0.ps1'\" REM proces source code (remove annotations, add other annotation, put class into namespace)\ncsc /t:library /out:references\\VIM_Service.dll VIM_WS.cs REM compile source into dll\nsgen /p references\\VIM_Service.dll /force REM generate serializtion dll\n</code></pre>\n\n<p>generateproxy.ps1</p>\n\n<pre><code>(Get-Content VIM.cs) | \n ForEach-Object { \n $_ -replace \"(?<attr>\\[global::System.Xml.Serialization.[^\\]]*\\])\", \"/*${attr}*/\" `\n -replace \"public partial class VIM\", \"[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = \"\"VIM_Service.XmlSerializers\"\")] `npublic partial class VIM\" `\n -replace \"using System;\", \"namespace Classes.WS_VIM { `n`nusing System;\"\n } |\nSet-Content VIM.cs\nAdd-Content VIM.cs \"`n}\"\n</code></pre>\n\n<p>I have added those two files to client project, and in the pre-build event I have added lines</p>\n\n<pre><code>cd..\\..\ngenerateproxy\n</code></pre>\n\n<p>So, before every build, proxy classes are regenerated, and developer has (almost) no need to think about it. While building, WS must be up and running, and its URL must be in bat file. As a result of prebuild, two dll files will regenerate in client project's subfolder <em>references</em>.\nAfter first execution of scripts, you should add reference to new dll.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2942/"
] |
I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc.
I'm using the web reference in a console application. I often change something, recompile and run. Compilation is fast, but newing up the web service reference is very slow, taking some 15-20 seconds:
`CrmService service = new CrmService();`
Profiling reveals that all time is spent in the SoapHttpClientProtocol constructor.
The culprit is apparently the fact that the XML serialization code (not included in the 90k loc mentioned above) is generated at run time, before being JIT'ed. This happens during the constructor call. The wait is rather frustrating when playing around and trying things out.
I've tried various combinations of sgen.exe, ngen and XGenPlus (which takes several hours and generates 500MB of additional code) but to no avail. I've considered implementing a Windows service that have few CrmService instances ready to dish out when needed but that seems excessive.
Any ideas?
|
The following is ripped from [this](http://communities.vmware.com/thread/47063) thread on the VMWare forums:
Hi folks,
We've found that sgen.exe does work. It'just that there is a couple of additional steps beyond pre-generating the serializer dll's that we missed in this thread. Here is the detailed instruction
PROBLEM
-------
When using the VIM 2.0 SDK from .NET requires long time to instantiate the VimService class. (The VimService class is the proxy class generated by running 'wsdl.exe vim.wsdl vimService.wsdl')
In other words, the following line of code:
```
_service = new VimService();
```
Could take about 50 seconds to execute.
CAUSE
-----
Apparently, the .NET `XmlSerializer` uses the `System.Xml.Serialization.*` attributes annotating the proxy classes to generate serialization code in run time. When the proxy classes are many and large, as is the code in VimService.cs, the generation of the serialization code can take a long time.
SOLUTION
--------
This is a known problem with how the Microsoft .NET serializer works.
Here are some references that MSDN provides about solving this problem:
<http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx>
<http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx>
Unfortunately, none of the above references describe the complete solution to the problem. Instead they focus on how to pre-generate the XML serialization code.
The complete fix involves the following steps:
1. Create an assembly (a DLL) with the pre-generated XML serializer code
2. Remove all references to System.Xml.Serialization.\* attributes from the proxy code (i.e. from the VimService.cs file)
3. Annotate the main proxy class with the XmlSerializerAssemblyAttribute to point it to where the XML serializer assembly is.
Skipping step 2 leads to only 20% improvement in the instantiation time for the `VimService` class. Skipping either step 1 or 3 leads to incorrect code. With all three steps 98% improvement is achieved.
Here are step-by-step instructions:
Before you begin, makes sure you are using .NET verison 2.0 tools. This solution will not work with version 1.1 of .NET because the sgen tool and the `XmlSerializationAssemblyAttribute` are only available in version 2.0 of .NET
1. Generate the VimService.cs file from the WSDL, using wsdl.exe:
`wsdl.exe vim.wsdl vimService.wsdl`
This will output the VimService.cs file in the current directory
2. Compile VimService.cs into a library
`csc /t:library /out:VimService.dll VimService.cs`
3. Use the sgen tool to pre-generate and compile the XML serializers:
`sgen /p VimService.dll`
This will output the VimService.XmlSerializers.dll in the current directory
4. Go back to the VimService.cs file and remove all `System.Xml.Serialization.*` attributes. Because the code code is large, the best way to achieve that is by using some regular expression substitution tool. Be careful as you do this because not all attributes appear on a line by themselves. Some are in-lined as part of a method declaration.
If you find this step difficult, here is a simplified way of doing it:
Assuming you are writing C#, do a global replace on the following string:
`[System.Xml.Serialization.XmlIncludeAttribute`
and replace it with:
`// [System.Xml.Serialization.XmlIncludeAttribute`
This will get rid of the `Xml.Serialization` attributes that are the biggest culprits for the slowdown by commenting them out. If you are using some other .NET language, just modify the replaced string to be prefix-commented according to the syntax of that language. This simplified approach will get you most of the speedup that you can get. Removing the rest of the Xml.Serialization attributes only achieves an extra 0.2 sec speedup.
5. Add the following attribute to the VimService class in VimService.cs:
`[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")]`
You should end up with something like this:
`// ... Some code here ...
[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")]
public partial class VimService : System.Web.Services.Protocols.SoapHttpClientProtocol {
// ... More code here`
6. Regenerate VimSerice.dll library by
`csc /t:library /out:VimService.dll VimService.cs`
7. Now, from your application, you can add a reference to VimSerice.dll library.
8. Run your application and verify that VimService object instanciation time is reduced.
ADDITIONAL NOTES
----------------
The sgen tool is a bit of a black box and its behavior varies depending on what you have in your Machine.config file. For example, by default it is supposed to ouptut optimized non-debug code, but that is not always the case. To get some visibility into the tool, use the /k flag in step 3, which will cause it to keep all its temporary generated files, including the source files and command line option files it generated.
Even after the above fix the time it takes to instantiate the VimService class for the first time is not instantaneous (1.5 sec). Based on empirical observation, it appears that the majority of the remaining time is due to processing the `SoapDocumentMethodAttribute` attributes. At this point it is unclear how this time can be reduced. The pre-generated XmlSerializer assembly does not account for the SOAP-related attributes, so these attributes need to remain in the code. The good news is that only the first instantiation of the VimService class for that app takes long. So if the extra 1.5 seconds are a problem, one could try to do a dummy instantiation of this class at the beginning of the application as a means to improve user experience of login time.
|
172,110 |
<p>How can I elegantly print the date in RFC822 format in Perl?</p>
|
[
{
"answer_id": 172119,
"author": "njsf",
"author_id": 4995,
"author_profile": "https://Stackoverflow.com/users/4995",
"pm_score": 6,
"selected": true,
"text": "<pre><code>use POSIX qw(strftime);\nprint strftime(\"%a, %d %b %Y %H:%M:%S %z\", localtime(time())) . \"\\n\";\n</code></pre>\n"
},
{
"answer_id": 172342,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": false,
"text": "<p>The DateTime suite gives you a number of different ways, e.g.:</p>\n\n<pre><code>use DateTime;\nprint DateTime->now()->strftime(\"%a, %d %b %Y %H:%M:%S %z\");\n\nuse DateTime::Format::Mail;\nprint DateTime::Format::Mail->format_datetime( DateTime->now() );\n\nprint DateTime->now( formatter => DateTime::Format::Mail->new() );\n</code></pre>\n\n<p>Update: to give time for some particular timezone, add a time_zone argument\nto now():</p>\n\n<pre><code>DateTime->now( time_zone => $ENV{'TZ'}, ... )\n</code></pre>\n"
},
{
"answer_id": 40149475,
"author": "Daniel Vérité",
"author_id": 238814,
"author_profile": "https://Stackoverflow.com/users/238814",
"pm_score": 3,
"selected": false,
"text": "<p>It can be done with <code>strftime</code>, but its <code>%a</code> (day) and <code>%b</code> (month) are expressed in the language of the current locale.</p>\n<p>From <code>man strftime</code>:</p>\n<blockquote>\n<p>%a The abbreviated weekday name according to the current locale.<br />\n%b The abbreviated month name according to the current locale.</p>\n</blockquote>\n<p>The Date field in mail <strong>must</strong> use only these names (from <a href=\"https://www.rfc-editor.org/rfc/rfc2822#page-14\" rel=\"nofollow noreferrer\">rfc2822 DATE AND TIME SPECIFICATION</a>):</p>\n<pre><code>day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"\n\nmonth = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /\n "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"\n</code></pre>\n<p>Therefore portable code should switch to the <code>C</code> locale:</p>\n<pre><code>use POSIX qw(strftime locale_h);\n\nmy $old_locale = setlocale(LC_TIME, "C");\nmy $date_rfc822 = strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time()));\nsetlocale(LC_TIME, $old_locale);\n\nprint "$date_rfc822\\n";\n</code></pre>\n"
},
{
"answer_id": 52787169,
"author": "Guido Flohr",
"author_id": 5464233,
"author_profile": "https://Stackoverflow.com/users/5464233",
"pm_score": 0,
"selected": false,
"text": "<p>Just using <code>POSIX::strftime()</code> has issues that have already been pointed out in other answers and comments on them:</p>\n<ul>\n<li>It will not work with MS-DOS aka Windows which produces strings like "W. Europe Standard Time" instead of "+0200" as required by <a href=\"https://www.rfc-editor.org/rfc/rfc822\" rel=\"nofollow noreferrer\" title=\"RFC822\">RFC822</a> for the <code>%z</code> conversion specification.</li>\n<li>It will print the abbreviated month and day names in the current locale instead of English, again required by <a href=\"https://www.rfc-editor.org/rfc/rfc822\" rel=\"nofollow noreferrer\" title=\"RFC822\">RFC822</a>.</li>\n</ul>\n<p>Switching the locale to "POSIX" resp. "C" fixes the latter problem but is potentially expensive, even more for well-behaving code that later switches back to the previous locale.</p>\n<p>But it's also not completely thread-safe. While temporarily switching locale will work without issues inside Perl interpreter threads, there are races when the Perl interpreter itself runs inside a kernel thread. This can be the case, when the Perl interpreter is embedded into a server (for example <a href=\"https://perl.apache.org/\" rel=\"nofollow noreferrer\" title=\"mod_perl\">mod_perl</a> running in a threaded Apache MPM).</p>\n<p>The following version doesn't suffer from any such limitations because it doesn't use any locale dependent functions:</p>\n<pre><code>sub rfc822_local {\n my ($epoch) = @_;\n\n my @time = localtime $epoch;\n\n use integer;\n\n my $tz_offset = (Time::Local::timegm(@time) - $now) / 60;\n my $tz = sprintf('%s%02u%02u',\n $tz_offset < 0 ? '-' : '+',\n $tz_offset / 60, $tz_offset % 60);\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u %s',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0], $tz);\n}\n</code></pre>\n<p>But it should be noted that converting from seconds since the epoch to a broken down time and vice versa are quite complex and expensive operations, even more when not dealing with GMT/UTC but local time. The latter requires the inspection of zoneinfo data that contains the current and historical DST and time zone settings for the current time zone. It's also error-prone because these parameters are subject to political decisions that <a href=\"http://europa.eu/rapid/press-release_IP-18-5302_en.htm\" rel=\"nofollow noreferrer\" title=\"may be reverted in the future\">may be reverted in the future</a>. Because of that, code relying on the zoneinfo data is brittle and may break, when the system is not regulary updated.</p>\n<p>However, the purpose of RFC822 compliant date and time specifications is not to inform other servers about the timezone settings of "your" server but to give its notion of the current date and time in a timezone indepent manner. You can save a lot of CPU cycles (they can be measured in CO2 emission) on both the sending and receiving end by simply using UTC instead of localtime:</p>\n<pre><code>sub rfc822_gm {\n my ($epoch) = @_;\n\n my @time = gmtime $epoch;\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u +0000',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0]);\n}\n</code></pre>\n<p>By hard-coding the timezone to <code>+0000</code> you avoid all of the above mentioned problems, while still being perfectly standards compliant, leave alone faster. Go with that solution, when performance could be an issue for you. Go with the first solution, when your users complain about the software reporting the "wrong" timezone.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
How can I elegantly print the date in RFC822 format in Perl?
|
```
use POSIX qw(strftime);
print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
```
|
172,111 |
<p>Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible?</p>
|
[
{
"answer_id": 172119,
"author": "njsf",
"author_id": 4995,
"author_profile": "https://Stackoverflow.com/users/4995",
"pm_score": 6,
"selected": true,
"text": "<pre><code>use POSIX qw(strftime);\nprint strftime(\"%a, %d %b %Y %H:%M:%S %z\", localtime(time())) . \"\\n\";\n</code></pre>\n"
},
{
"answer_id": 172342,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": false,
"text": "<p>The DateTime suite gives you a number of different ways, e.g.:</p>\n\n<pre><code>use DateTime;\nprint DateTime->now()->strftime(\"%a, %d %b %Y %H:%M:%S %z\");\n\nuse DateTime::Format::Mail;\nprint DateTime::Format::Mail->format_datetime( DateTime->now() );\n\nprint DateTime->now( formatter => DateTime::Format::Mail->new() );\n</code></pre>\n\n<p>Update: to give time for some particular timezone, add a time_zone argument\nto now():</p>\n\n<pre><code>DateTime->now( time_zone => $ENV{'TZ'}, ... )\n</code></pre>\n"
},
{
"answer_id": 40149475,
"author": "Daniel Vérité",
"author_id": 238814,
"author_profile": "https://Stackoverflow.com/users/238814",
"pm_score": 3,
"selected": false,
"text": "<p>It can be done with <code>strftime</code>, but its <code>%a</code> (day) and <code>%b</code> (month) are expressed in the language of the current locale.</p>\n<p>From <code>man strftime</code>:</p>\n<blockquote>\n<p>%a The abbreviated weekday name according to the current locale.<br />\n%b The abbreviated month name according to the current locale.</p>\n</blockquote>\n<p>The Date field in mail <strong>must</strong> use only these names (from <a href=\"https://www.rfc-editor.org/rfc/rfc2822#page-14\" rel=\"nofollow noreferrer\">rfc2822 DATE AND TIME SPECIFICATION</a>):</p>\n<pre><code>day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"\n\nmonth = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /\n "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"\n</code></pre>\n<p>Therefore portable code should switch to the <code>C</code> locale:</p>\n<pre><code>use POSIX qw(strftime locale_h);\n\nmy $old_locale = setlocale(LC_TIME, "C");\nmy $date_rfc822 = strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time()));\nsetlocale(LC_TIME, $old_locale);\n\nprint "$date_rfc822\\n";\n</code></pre>\n"
},
{
"answer_id": 52787169,
"author": "Guido Flohr",
"author_id": 5464233,
"author_profile": "https://Stackoverflow.com/users/5464233",
"pm_score": 0,
"selected": false,
"text": "<p>Just using <code>POSIX::strftime()</code> has issues that have already been pointed out in other answers and comments on them:</p>\n<ul>\n<li>It will not work with MS-DOS aka Windows which produces strings like "W. Europe Standard Time" instead of "+0200" as required by <a href=\"https://www.rfc-editor.org/rfc/rfc822\" rel=\"nofollow noreferrer\" title=\"RFC822\">RFC822</a> for the <code>%z</code> conversion specification.</li>\n<li>It will print the abbreviated month and day names in the current locale instead of English, again required by <a href=\"https://www.rfc-editor.org/rfc/rfc822\" rel=\"nofollow noreferrer\" title=\"RFC822\">RFC822</a>.</li>\n</ul>\n<p>Switching the locale to "POSIX" resp. "C" fixes the latter problem but is potentially expensive, even more for well-behaving code that later switches back to the previous locale.</p>\n<p>But it's also not completely thread-safe. While temporarily switching locale will work without issues inside Perl interpreter threads, there are races when the Perl interpreter itself runs inside a kernel thread. This can be the case, when the Perl interpreter is embedded into a server (for example <a href=\"https://perl.apache.org/\" rel=\"nofollow noreferrer\" title=\"mod_perl\">mod_perl</a> running in a threaded Apache MPM).</p>\n<p>The following version doesn't suffer from any such limitations because it doesn't use any locale dependent functions:</p>\n<pre><code>sub rfc822_local {\n my ($epoch) = @_;\n\n my @time = localtime $epoch;\n\n use integer;\n\n my $tz_offset = (Time::Local::timegm(@time) - $now) / 60;\n my $tz = sprintf('%s%02u%02u',\n $tz_offset < 0 ? '-' : '+',\n $tz_offset / 60, $tz_offset % 60);\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u %s',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0], $tz);\n}\n</code></pre>\n<p>But it should be noted that converting from seconds since the epoch to a broken down time and vice versa are quite complex and expensive operations, even more when not dealing with GMT/UTC but local time. The latter requires the inspection of zoneinfo data that contains the current and historical DST and time zone settings for the current time zone. It's also error-prone because these parameters are subject to political decisions that <a href=\"http://europa.eu/rapid/press-release_IP-18-5302_en.htm\" rel=\"nofollow noreferrer\" title=\"may be reverted in the future\">may be reverted in the future</a>. Because of that, code relying on the zoneinfo data is brittle and may break, when the system is not regulary updated.</p>\n<p>However, the purpose of RFC822 compliant date and time specifications is not to inform other servers about the timezone settings of "your" server but to give its notion of the current date and time in a timezone indepent manner. You can save a lot of CPU cycles (they can be measured in CO2 emission) on both the sending and receiving end by simply using UTC instead of localtime:</p>\n<pre><code>sub rfc822_gm {\n my ($epoch) = @_;\n\n my @time = gmtime $epoch;\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u +0000',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0]);\n}\n</code></pre>\n<p>By hard-coding the timezone to <code>+0000</code> you avoid all of the above mentioned problems, while still being perfectly standards compliant, leave alone faster. Go with that solution, when performance could be an issue for you. Go with the first solution, when your users complain about the software reporting the "wrong" timezone.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] |
Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible?
|
```
use POSIX qw(strftime);
print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
```
|
172,151 |
<p>I want to write a program in which plays an audio file that reads a text.
I want to highlite the current syllable that the audiofile plays in green and the rest of the current word in red.
What kind of datastructure should I use to store the audio file and the information that tells the program when to switch to the next word/syllable?</p>
|
[
{
"answer_id": 172165,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>you might want to get familiar with FreeTTS -- this open source tool : <a href=\"http://freetts.sourceforge.net/docs/index.php\" rel=\"nofollow noreferrer\">http://freetts.sourceforge.net/docs/index.php</a> -</p>\n\n<p>You might want to feed only a few words to the TTS engine at a given point of time -- highlight them and once those are SPOKEN out, de-highlight them and move to the next batch of words. </p>\n\n<p>BR,<BR>\n~A</p>\n"
},
{
"answer_id": 195543,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 1,
"selected": false,
"text": "<p>How about a simple data structure that describes what next batch of letters consists of the next syllable and the time stamp for switching to that syllable?</p>\n\n<p>Just a quick example:</p>\n\n<p>[0:00] This [0:02] is [0:05] an [0:07] ex- [0:08] am- [0:10] ple</p>\n"
},
{
"answer_id": 221661,
"author": "jim",
"author_id": 27628,
"author_profile": "https://Stackoverflow.com/users/27628",
"pm_score": 1,
"selected": false,
"text": "<p>To highlight part of word sounds like you're getting into <a href=\"http://en.wikipedia.org/wiki/Phonetics\" rel=\"nofollow noreferrer\">phonetics</a> which are sounds that make up words. It's going to be really difficult to turn a sound file into something that will \"read\" a text. Your best bet is to use the text itself to drive a phonetics based engine, like FreeTTS which is based off of the <a href=\"http://java.sun.com/products/java-media/speech/forDevelopers/jsapi-guide/index.html\" rel=\"nofollow noreferrer\">Java Speech API</a>.</p>\n\n<p>To do this you're going to have to take the text to be read, split it into each phonetic syllable and play it. so \"syllable\" is \"syl\" \"la\" \"ble\". Playing would be; highlight syl, say it and move to next one.</p>\n\n<p>This is really \"old-skool\" its been done on the original Apple II the same way.</p>\n"
},
{
"answer_id": 221712,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 3,
"selected": true,
"text": "<p>This is a slightly left-field suggestion, but have you looked at Karaoke software? It may not be seen as \"serious\" enough, but it sounds very similar to what you're doing. For example, <a href=\"http://www.aegisub.net/\" rel=\"nofollow noreferrer\">Aegisub</a> is a subtitling program that lets you create subtitles in the SSA/ASS format. It has karaoke tools for hilighting the chosen word or part.</p>\n\n<p>It's most commonly used for subtitling anime, but it also works for audio provided you have a suitable player. These are sadly quite rare on the Mac.</p>\n\n<p>The format looks similar to the one proposed by Yuval A:</p>\n\n<pre><code>{\\K132}Unmei {\\K34}no {\\K54}tobira\n{\\K60}{\\K132}yukkuri {\\K36}to {\\K142}hirakareta\n</code></pre>\n\n<p>The lengths are durations rather than absolute offsets. This makes it easier to shift the start of the line without recalculating all the offsets. The double entry indicates a pause.</p>\n\n<p>Is there a good reason this needs to be part of your Java program, or is an off the shelf solution possible?</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25282/"
] |
I want to write a program in which plays an audio file that reads a text.
I want to highlite the current syllable that the audiofile plays in green and the rest of the current word in red.
What kind of datastructure should I use to store the audio file and the information that tells the program when to switch to the next word/syllable?
|
This is a slightly left-field suggestion, but have you looked at Karaoke software? It may not be seen as "serious" enough, but it sounds very similar to what you're doing. For example, [Aegisub](http://www.aegisub.net/) is a subtitling program that lets you create subtitles in the SSA/ASS format. It has karaoke tools for hilighting the chosen word or part.
It's most commonly used for subtitling anime, but it also works for audio provided you have a suitable player. These are sadly quite rare on the Mac.
The format looks similar to the one proposed by Yuval A:
```
{\K132}Unmei {\K34}no {\K54}tobira
{\K60}{\K132}yukkuri {\K36}to {\K142}hirakareta
```
The lengths are durations rather than absolute offsets. This makes it easier to shift the start of the line without recalculating all the offsets. The double entry indicates a pause.
Is there a good reason this needs to be part of your Java program, or is an off the shelf solution possible?
|
172,156 |
<p>I get the Total length of columns in constraint is too long. erro from the following</p>
<pre><code>sql] Failed to execute: CREATE TABLE GTW_WORKFLOW_MON ( WORKFLOW_NAME VARCHAR(255) NOT
NULL, WORKFLOW_LOADED NUMERIC(20) NOT NULL, ACTIVITY_NAME VARCHAR(255) NOT NULL, FLAGS
INTEGER NOT NULL, MONITOR_NAME VARCHAR(255) NOT NULL, CLASSNAME VARCHAR(255) NOT NULL, S
TR0 VARCHAR(255), STR1 VARCHAR(255), STR2 VARCHAR(255), NUM0 VARCHAR(255), NUM1
VARCHAR(255), NUM2 VARCHAR(255), DATE0 VARCHAR(255), DATE1 VARCHAR(255), DATE2
VARCHAR(255), PRIMARY KEY (WORKFLOW_NAME,WORKFLOW_LOADED,ACTIVITY_NAME,MONITOR_NAME) )
[sql] java.sql.SQLException: Total length of columns in constraint is too long.
</code></pre>
|
[
{
"answer_id": 172382,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "<p>Your primary key constraint is 785 bytes (255+20+255+255). If you increase your database page size to 4K it should work, barely. You should also reconsider if you need your columns to be as wide as you are defining them.</p>\n\n<p>I found a discussion group where an engineer, Radhika Gadde, <a href=\"http://www.iiug.org/forums/ids/index.cgi/noframes/read/8100\" rel=\"nofollow noreferrer\">describes</a> that the maximum index size is related to page size. He says:</p>\n\n<p>which error you are getting while creation of Tables.\nMaximum Index key length can be calculated as follows:</p>\n\n<p>[(PAGESIZE -93)/5] -1</p>\n\n<p>like for 2k it is\n[( 2048-93)/5] -1 =[1955/5] -1 =391-1=390</p>\n\n<p>if PAGESIZE is 4K\nit is [(4096-93)/5] -1 =4003/5-1=800-1 =799 </p>\n"
},
{
"answer_id": 15331852,
"author": "Sumedha",
"author_id": 952684,
"author_profile": "https://Stackoverflow.com/users/952684",
"pm_score": 0,
"selected": false,
"text": "<p>Above answer is complete. But thought of adding some helpful links in case someone runs to this issue again.\nPagesize on Informix depends on Operating System. On my recent experience, I found it's 4K on Win 2008, OSX - Lion and 2K on SUSE EL4.\nYou can find the page size by using 'onstat -D'.</p>\n\n<p>I wrote <a href=\"http://sumedha.blogspot.com/2013/03/how-to-increase-informix-page-size.html\" rel=\"nofollow\">http://sumedha.blogspot.com/2013/03/how-to-increase-informix-page-size.html</a> with this experience.\nFollowing documentation link from IBM is also very helpful.</p>\n\n<p><a href=\"http://publib.boulder.ibm.com/infocenter/idshelp/v115/index.jsp?topic=/com.ibm.admin.doc/ids_admin_0564.htm\" rel=\"nofollow\">http://publib.boulder.ibm.com/infocenter/idshelp/v115/index.jsp?topic=%2Fcom.ibm.admin.doc%2Fids_admin_0564.htm</a></p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
] |
I get the Total length of columns in constraint is too long. erro from the following
```
sql] Failed to execute: CREATE TABLE GTW_WORKFLOW_MON ( WORKFLOW_NAME VARCHAR(255) NOT
NULL, WORKFLOW_LOADED NUMERIC(20) NOT NULL, ACTIVITY_NAME VARCHAR(255) NOT NULL, FLAGS
INTEGER NOT NULL, MONITOR_NAME VARCHAR(255) NOT NULL, CLASSNAME VARCHAR(255) NOT NULL, S
TR0 VARCHAR(255), STR1 VARCHAR(255), STR2 VARCHAR(255), NUM0 VARCHAR(255), NUM1
VARCHAR(255), NUM2 VARCHAR(255), DATE0 VARCHAR(255), DATE1 VARCHAR(255), DATE2
VARCHAR(255), PRIMARY KEY (WORKFLOW_NAME,WORKFLOW_LOADED,ACTIVITY_NAME,MONITOR_NAME) )
[sql] java.sql.SQLException: Total length of columns in constraint is too long.
```
|
Your primary key constraint is 785 bytes (255+20+255+255). If you increase your database page size to 4K it should work, barely. You should also reconsider if you need your columns to be as wide as you are defining them.
I found a discussion group where an engineer, Radhika Gadde, [describes](http://www.iiug.org/forums/ids/index.cgi/noframes/read/8100) that the maximum index size is related to page size. He says:
which error you are getting while creation of Tables.
Maximum Index key length can be calculated as follows:
[(PAGESIZE -93)/5] -1
like for 2k it is
[( 2048-93)/5] -1 =[1955/5] -1 =391-1=390
if PAGESIZE is 4K
it is [(4096-93)/5] -1 =4003/5-1=800-1 =799
|
172,175 |
<p>Here's my code in a gridview that is bound at runtime:</p>
<pre><code>...
<asp:templatefield>
<edititemtemplate>
<asp:dropdownlist runat="server" id="ddgvOpp" />
</edititemtemplate>
<itemtemplate>
<%# Eval("opponent.name") %>
</itemtemplate>
</asp:templatefield>
...
</code></pre>
<p>I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:</p>
<pre><code>protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //skip header row
{
DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp");
BindOpponentDD(ddOpp);
}
}
</code></pre>
<p>Where <code>BindOpponentDD()</code> is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?</p>
<p>Thanks so much in advance...</p>
|
[
{
"answer_id": 172220,
"author": "Jason",
"author_id": 7173,
"author_profile": "https://Stackoverflow.com/users/7173",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, I guess I'm just dumb. I figured it out.</p>\n\n<p>In the RowDataBound event, simply add the following conditional:</p>\n\n<pre><code>if (myGridView.EditIndex == e.Row.RowIndex)\n{\n //do work\n}\n</code></pre>\n"
},
{
"answer_id": 1198319,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (grdDevelopment.EditIndex == e.Row.RowIndex && e.Row.RowType==DataControlRowType.DataRow) \n { \n DropDownList drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl(\"ddlBuildServers\"); \n }\n}\n</code></pre>\n\n<p>Try this one</p>\n\n<p>This will help u</p>\n"
},
{
"answer_id": 4807544,
"author": "Tom Hamming",
"author_id": 412107,
"author_profile": "https://Stackoverflow.com/users/412107",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue, but this fix (Jason's, which is adding the conditional to the handler) didn't work for me; the Edit row never was databound, so that condition never evaluated to true. RowDataBound was simply never called with the same RowIndex as the GridView.EditIndex. My setup is a little different, though, in that instead of binding the dropdown programmatically I have it bound to an ObjectDataSource on the page. The dropdown still has to be bound separately per row, though, because its possible values depend on other information in the row. So the ObjectDataSource has a SessionParameter, and I make sure to set the appropriate session variable when needed for binding.</p>\n\n<pre><code><asp:ObjectDataSource ID=\"objInfo\" runat=\"server\" SelectMethod=\"GetData\" TypeName=\"MyTypeName\">\n<SelectParameters>\n <asp:SessionParameter Name=\"MyID\" SessionField=\"MID\" Type=\"Int32\" />\n</SelectParameters>\n</code></pre>\n\n<p></p>\n\n<p>And the dropdown in the relevant row:</p>\n\n<pre><code><asp:TemplateField HeaderText=\"My Info\" SortExpression=\"MyInfo\">\n <EditItemTemplate>\n <asp:DropDownList ID=\"ddlEditMyInfo\" runat=\"server\" DataSourceID=\"objInfo\" DataTextField=\"MyInfo\" DataValueField=\"MyInfoID\" SelectedValue='<%#Bind(\"ID\") %>' />\n </EditItemTemplate>\n <ItemTemplate>\n <span><%#Eval(\"MyInfo\") %></span>\n </ItemTemplate>\n </asp:TemplateField>\n</code></pre>\n\n<p>What I ended up doing was not using a CommandField in the GridView to generate my edit, delete, update and cancel buttons; I did it on my own with a TemplateField, and by setting the CommandNames appropriately, I was able to trigger the built-in edit/delete/update/cancel actions on the GridView. For the Edit button, I made the CommandArgument the information I needed to bind the dropdown, instead of the row's PK like it would usually be. This luckily did not prevent the GridView from editing the appropriate row.</p>\n\n<pre><code><asp:TemplateField>\n <ItemTemplate>\n <asp:ImageButton ID=\"ibtnDelete\" runat=\"server\" ImageUrl=\"~/images/delete.gif\" AlternateText=\"Delete\" CommandArgument='<%#Eval(\"UniqueID\") %>' CommandName=\"Delete\" />\n <asp:ImageButton ID=\"ibtnEdit\" runat=\"server\" ImageUrl=\"~/images/edit.gif\" AlternateText=\"Edit\" CommandArgument='<%#Eval(\"MyID\") %>' CommandName=\"Edit\" />\n </ItemTemplate>\n <EditItemTemplate>\n <asp:ImageButton ID=\"ibtnUpdate\" runat=\"server\" ImageUrl=\"~/images/update.gif\" AlternateText=\"Update\" CommandArgument='<%#Eval(\"UniqueID\") %>' CommandName=\"Update\" />\n <asp:ImageButton ID=\"ibtnCancel\" runat=\"server\" ImageUrl=\"~/images/cancel.gif\" AlternateText=\"Cancel\" CommandName=\"Cancel\" />\n </EditItemTemplate>\n </asp:TemplateField>\n</code></pre>\n\n<p>And in the RowCommand handler:</p>\n\n<pre><code>void grdOverrides_RowCommand(object sender, GridViewCommandEventArgs e)\n {\n if (e.CommandName == \"Edit\")\n Session[\"MID\"] = Int32.Parse(e.CommandArgument.ToString());\n }\n</code></pre>\n\n<p>The RowCommand, of course, happens before the row goes into edit mode and thus before the dropdown databinds. So everything works. It's a little bit of a hack, but I'd spent enough time trying to figure out why the edit row wasn't being databound already.</p>\n"
},
{
"answer_id": 8703063,
"author": "Amol",
"author_id": 982692,
"author_profile": "https://Stackoverflow.com/users/982692",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks to Saurabh Tripathi,</p>\n\n<p>The solution you provided worked for me.\nIn gridView_RowDataBound() event use.</p>\n\n<pre><code>if(gridView.EditIndex == e.Row.RowIndex && e.Row.RowType == DataControlRowType.DataRow)\n{\n // FindControl\n // And populate it\n}\n</code></pre>\n\n<p>If anyone is stuck with the same issue, then try this out.</p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 21546548,
"author": "Riki_VaL",
"author_id": 2746112,
"author_profile": "https://Stackoverflow.com/users/2746112",
"pm_score": 0,
"selected": false,
"text": "<p>This code will be do what you want:</p>\n\n<pre><code><asp:TemplateField HeaderText=\"garantia\" SortExpression=\"garantia\">\n <EditItemTemplate>\n <asp:DropDownList ID=\"ddgvOpp\" runat=\"server\" SelectedValue='<%# Bind(\"opponent.name\") %>'>\n <asp:ListItem Text=\"Si\" Value=\"True\"></asp:ListItem>\n <asp:ListItem Text=\"No\" Value=\"False\"></asp:ListItem>\n </asp:DropDownList>\n </EditItemTemplate>\n <ItemTemplate>\n <asp:Label ID=\"Label1\" runat=\"server\" Text='<%# Bind(\"opponent.name\") %>'></asp:Label>\n </ItemTemplate>\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7173/"
] |
Here's my code in a gridview that is bound at runtime:
```
...
<asp:templatefield>
<edititemtemplate>
<asp:dropdownlist runat="server" id="ddgvOpp" />
</edititemtemplate>
<itemtemplate>
<%# Eval("opponent.name") %>
</itemtemplate>
</asp:templatefield>
...
```
I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:
```
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //skip header row
{
DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp");
BindOpponentDD(ddOpp);
}
}
```
Where `BindOpponentDD()` is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?
Thanks so much in advance...
|
Ok, I guess I'm just dumb. I figured it out.
In the RowDataBound event, simply add the following conditional:
```
if (myGridView.EditIndex == e.Row.RowIndex)
{
//do work
}
```
|
172,176 |
<p>What is the best way to deal with storing and indexing URL's in SQL Server 2005? </p>
<p>I have a WebPage table that stores metadata and content about Web Pages. I also have many other tables related to the WebPage table. They all use URL as a key. </p>
<p>The problem is URL's can be very large, and using them as a key makes the indexes larger and slower. How much I don't know, but I have read many times using large fields for indexing is to be avoided. Assuming a URL is nvarchar(400), they are enormous fields to use as a primary key.</p>
<p>What are the alternatives? </p>
<p>How much pain would there likely to be with using URL as a key instead of a smaller field.</p>
<p>I have looked into the WebPage table having a identity column, and then using this as the primary key for a WebPage. This keeps all the associated indexes smaller and more efficient but it makes importing data a bit of a pain. Each import for the associated tables has to first lookup what the id of a url is before inserting data in the tables.</p>
<p>I have also played around with using a hash on the URL, to create a smaller index, but am still not sure if it is the best way of doing things. It wouldn't be a unique index, and would be subject to a small number of collisions. So I am unsure what foreign key would be used in this case...</p>
<p>There will be millions of records about webpages stored in the database, and there will be a lot of batch updating. Also there will be a quite a lot of activity reading and aggregating the data.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 172180,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 1,
"selected": false,
"text": "<p>I would stick with the hash solution. This generates a unique key with a fairly low chance of collision. </p>\n\n<p>An alternative would be to create GUID and use that as the key. </p>\n"
},
{
"answer_id": 172205,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 3,
"selected": true,
"text": "<p>I'd use a normal identity column as the primary key. You say:</p>\n\n<blockquote>\n <p>This keeps all the associated indexes smaller and more efficient\n but it makes importing data a bit of a pain. Each import for the\n associated tables has to first lookup what the id of a url is \n before inserting data in the tables.</p>\n</blockquote>\n\n<p>Yes, but the pain is probably worth it, and the techniques you learn in the process will be invaluable on future projects.</p>\n\n<p>On SQL Server 2005, you can create a user-defined function GetUrlId that looks something like</p>\n\n<pre><code>CREATE FUNCTION GetUrlId (@Url nvarchar(400)) \nRETURNS int\nAS BEGIN\n DECLARE @UrlId int\n SELECT @UrlId = Id FROM Url WHERE Url = @Url\n RETURN @UrlId\nEND\n</code></pre>\n\n<p>This will return the ID for urls already in your URL table, and NULL for any URL not already recorded. You can then call this function inline your import statements - something like</p>\n\n<pre><code>INSERT INTO \n UrlHistory(UrlId, Visited, RemoteIp) \nVALUES \n (dbo.GetUrlId('http://www.stackoverflow.com/'), @Visited, @RemoteIp)\n</code></pre>\n\n<p>This is probably slower than a proper join statement, but for one-time or occasional import routines it might make things easier.</p>\n"
},
{
"answer_id": 172381,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 2,
"selected": false,
"text": "<p>Break up the URL into columns based on the bits your concerned with and use the <a href=\"http://www.ietf.org/rfc/rfc1738.txt\" rel=\"nofollow noreferrer\">RFC</a> as a guide. Reverse the host and domain info so an index can group like domains (Google does this).</p>\n\n<pre><code>stackoverflow.com -> com.stackoverflow \nblog.stackoverflow.com -> com.stackoverflow.blog\n</code></pre>\n\n<p>Google has a paper that outlines what they do but I can't find right now.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Uniform_Resource_Locator</a></p>\n"
},
{
"answer_id": 177664,
"author": "Jan",
"author_id": 25727,
"author_profile": "https://Stackoverflow.com/users/25727",
"pm_score": 0,
"selected": false,
"text": "<p>I totally agree with Dylan. Use an IDENTITY column or a GUID column as surrogate key in your WebPage table. Thats a clean solution. The lookup of the id while importing isn't that painful i think.</p>\n\n<p>Using a big varchar column as key column is wasting much space and affects insert and query performance.</p>\n"
},
{
"answer_id": 177720,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Not so much a solution. More another perspective.</p>\n\n<p>Storing the total unique URI of a page perhaps defeats part of the point of URI construction. Each forward slash is supposed to refer to a unique semantic space within the domain (whether that space is actual or logical). Unless the URIs you intend to store are something along the line of www.somedomain.com/p.aspx?id=123456789 then really it might be better to break a single URI metatable into a table representing the subdomains you have represented in your site.</p>\n\n<p>For example if you're going to hold a number of \"News\" section URIs in the same table as the \"Reviews\" URIs then you're missing a trick to have a \"Sections\" table whose content contains meta information about the section and whose own ID acts as a parent to all those URIs within it.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982/"
] |
What is the best way to deal with storing and indexing URL's in SQL Server 2005?
I have a WebPage table that stores metadata and content about Web Pages. I also have many other tables related to the WebPage table. They all use URL as a key.
The problem is URL's can be very large, and using them as a key makes the indexes larger and slower. How much I don't know, but I have read many times using large fields for indexing is to be avoided. Assuming a URL is nvarchar(400), they are enormous fields to use as a primary key.
What are the alternatives?
How much pain would there likely to be with using URL as a key instead of a smaller field.
I have looked into the WebPage table having a identity column, and then using this as the primary key for a WebPage. This keeps all the associated indexes smaller and more efficient but it makes importing data a bit of a pain. Each import for the associated tables has to first lookup what the id of a url is before inserting data in the tables.
I have also played around with using a hash on the URL, to create a smaller index, but am still not sure if it is the best way of doing things. It wouldn't be a unique index, and would be subject to a small number of collisions. So I am unsure what foreign key would be used in this case...
There will be millions of records about webpages stored in the database, and there will be a lot of batch updating. Also there will be a quite a lot of activity reading and aggregating the data.
Any thoughts?
|
I'd use a normal identity column as the primary key. You say:
>
> This keeps all the associated indexes smaller and more efficient
> but it makes importing data a bit of a pain. Each import for the
> associated tables has to first lookup what the id of a url is
> before inserting data in the tables.
>
>
>
Yes, but the pain is probably worth it, and the techniques you learn in the process will be invaluable on future projects.
On SQL Server 2005, you can create a user-defined function GetUrlId that looks something like
```
CREATE FUNCTION GetUrlId (@Url nvarchar(400))
RETURNS int
AS BEGIN
DECLARE @UrlId int
SELECT @UrlId = Id FROM Url WHERE Url = @Url
RETURN @UrlId
END
```
This will return the ID for urls already in your URL table, and NULL for any URL not already recorded. You can then call this function inline your import statements - something like
```
INSERT INTO
UrlHistory(UrlId, Visited, RemoteIp)
VALUES
(dbo.GetUrlId('http://www.stackoverflow.com/'), @Visited, @RemoteIp)
```
This is probably slower than a proper join statement, but for one-time or occasional import routines it might make things easier.
|
172,199 |
<p>Where can I find a list of all types of bsd style socket errors?</p>
|
[
{
"answer_id": 172216,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 2,
"selected": false,
"text": "<p>You can also find a list of error codes (and a general description of their meaning) on the Open Group's pages for each function (like <a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/connect.html\" rel=\"nofollow noreferrer\">connect</a>, for example).</p>\n"
},
{
"answer_id": 172273,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 4,
"selected": true,
"text": "<p>In the documentation? For instance, for connect(), see:</p>\n\n<pre><code>% man connect\n...\n ECONNREFUSED\n No-one listening on the remote address.\n EISCONN\n The socket is already connected.\n\n ENETUNREACH\n Network is unreachable.\n</code></pre>\n"
},
{
"answer_id": 172301,
"author": "amo-ej1",
"author_id": 15791,
"author_profile": "https://Stackoverflow.com/users/15791",
"pm_score": 1,
"selected": false,
"text": "<p>Of you want to know all possible errno's or some comments on them you could take a look at the header files, on a Linux system there are located in </p>\n\n<ul>\n<li>/usr/include/asm-generic/errno-base.h</li>\n</ul>\n\n<pre>\n#ifndef _ASM_GENERIC_ERRNO_BASE_H\n#define _ASM_GENERIC_ERRNO_BASE_H\n\n#define EPERM 1 /* Operation not permitted */\n#define ENOENT 2 /* No such file or directory */\n#define ESRCH 3 /* No such process */\n#define EINTR 4 /* Interrupted system call */\n#define EIO 5 /* I/O error */\n#define ENXIO 6 /* No such device or address */\n#define E2BIG 7 /* Argument list too long */\n#define ENOEXEC 8 /* Exec format error */\n#define EBADF 9 /* Bad file number */\n#define ECHILD 10 /* No child processes */\n#define EAGAIN 11 /* Try again */\n...\n</pre>\n\n<ul>\n<li>/usr/include/asm-generic/errno.h</li>\n</ul>\n\n<pre>\n#ifndef _ASM_GENERIC_ERRNO_H\n#define _ASM_GENERIC_ERRNO_H\n\n#include \n\n#define EDEADLK 35 /* Resource deadlock would occur */\n#define ENAMETOOLONG 36 /* File name too long */\n#define ENOLCK 37 /* No record locks available */\n#define ENOSYS 38 /* Function not implemented */\n#define ENOTEMPTY 39 /* Directory not empty */\n#define ELOOP 40 /* Too many symbolic links encountered */\n#define EWOULDBLOCK EAGAIN /* Operation would block */\n...\n</pre>\n\n<p>If you want to know what errno a call, e.g. socket() or connect() can return, when install the development manpages and try man socket or man connect </p>\n"
},
{
"answer_id": 173533,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>Many functions will set <code>errno</code> on failure, and instead of going through <code>errno.h</code> yourself and converting the error number to strings, you are much better off calling <a href=\"http://www.rt.com/man/perror.3.html\" rel=\"nofollow noreferrer\"><code>perror</code></a>.</p>\n\n<p><code>perror</code> will print the current <code>errno</code>'s corresponding message to <code>stderr</code> with an optional prefix.</p>\n\n<p>Example usage:</p>\n\n<pre><code>if (connect())\n{\n perror(\"connect() failed in function foo\");\n ...\n}\n</code></pre>\n\n<p><code>perror</code> has friends called <code>strerror</code> and <code>strerror_r</code> who might prove useful if you want to capture the string for use in places other than <code>stderr</code>.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946/"
] |
Where can I find a list of all types of bsd style socket errors?
|
In the documentation? For instance, for connect(), see:
```
% man connect
...
ECONNREFUSED
No-one listening on the remote address.
EISCONN
The socket is already connected.
ENETUNREACH
Network is unreachable.
```
|
172,203 |
<p>I can get both System.Net.Mail and System.Web.Mail to work with GMail, but I can't get them both to work with smtp.att.yahoo.com.</p>
<p>I get the SMTP settings from my own Web.config keys. These settings work when I send using System.Web.Mail, but fail with System.Net.Mail.</p>
<pre><code> <add key="SmtpServer" value="smtp.att.yahoo.com"/>
<add key="SmtpServerAuthenticateUser" value="[email protected]"/>
<add key="SmtpServerPort" value="465"/>
<add key="SmtpUseSSL" value="1"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
</code></pre>
<p>Here is the code that grabs my settings, and works with GMail, fails with att.yahoo:</p>
<pre><code> SmtpClient smtp;
if (!string.IsNullOrEmpty(Util.get_setting("SmtpServer", "")))
{
smtp = new SmtpClient(Util.get_setting("SmtpServer", ""));
}
else
{
smtp = new SmtpClient();
}
if (!string.IsNullOrEmpty(Util.get_setting("SmtpServerAuthenticatePassword", "")))
smtp.Credentials = new System.Net.NetworkCredential(
Util.get_setting("SmtpServerAuthenticateUser", ""),
Util.get_setting("SmtpServerAuthenticatePassword", ""));
if (!string.IsNullOrEmpty(Util.get_setting("SmtpServerPort", "")))
smtp.Port = int.Parse(Util.get_setting("SmtpServerPort", ""));
if (Util.get_setting("SmtpUseSSL", "0") == "1")
smtp.EnableSsl = true;
smtp.Send(message);
</code></pre>
<p>Is this my problem?</p>
<p><a href="http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx" rel="noreferrer">http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx</a></p>
|
[
{
"answer_id": 172922,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 4,
"selected": true,
"text": "<p>I've learned the answer. The answer is:</p>\n\n<p>Because System.Net.Mail does not support \"implicit\" SSL, only \"explicit\" SSL.</p>\n"
},
{
"answer_id": 2415090,
"author": "Wayne H",
"author_id": 290283,
"author_profile": "https://Stackoverflow.com/users/290283",
"pm_score": 1,
"selected": false,
"text": "<p>Gimel's answer is back to front. He says use the new System.<strong>Net</strong>.Mail library, but the problem is that System.<strong>Net</strong>.Mail does not work for SSL on port 465 like System.<strong>Web</strong>.Mail did/does work!</p>\n\n<p>I've beaten my head against this all day and for identical settings System.<strong>Web</strong>.Mail WORKS, and System.<strong>Net</strong>.Mail DOES NOT work (at least for the SMTP server I have been testing with), and here I was thinking that I should always upgrade to Microsoft's latest offering to get the best in life. :-(</p>\n\n<p>That link to the M$ blog seems to state it all; \"System.Net.Mail only supports “Explicit SSL”.\" and I assume the SMTP server I have been testing with wants Implicit SSL. (It's a Yahoo server btw).</p>\n\n<p>Since \"upgrading\" to the new API will no doubt break functionality for users who have servers that require implicit SSL it seems like a step backwards to \"upgrade\" in this case. If you can still compile only with warnings, simply disable those warnings (0618 if I recall) and keep on trucking. Oh, and you may want to consider ensuring your application always runs against the .NET framework version you built and tested with by way of config file, just so in future if M$ rips out the old API your application is safe. </p>\n"
},
{
"answer_id": 3849754,
"author": "Bryan Allred",
"author_id": 200869,
"author_profile": "https://Stackoverflow.com/users/200869",
"pm_score": 2,
"selected": false,
"text": "<p>The previous answers concerning implicit and explicit SSL connections via System.Net.Mail is absolutely correct. The way I was able to get through this obstacle, and without having to use the now obsolete System.Web.Mail, was to use the CDO (Collaborative Data Objects).</p>\n\n<p>I detailed and gave an example on another stack overflow post (<a href=\"https://stackoverflow.com/questions/1082216/gmail-smtp-via-c-net-errors-on-all-ports/3845907#3845907\">GMail SMTP via C# .Net errors on all ports</a>) if curious. Otherwise, you can go directly to the KB article at <a href=\"http://support.microsoft.com/kb/310212\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/310212</a>.</p>\n\n<p>Hope this helps!</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
I can get both System.Net.Mail and System.Web.Mail to work with GMail, but I can't get them both to work with smtp.att.yahoo.com.
I get the SMTP settings from my own Web.config keys. These settings work when I send using System.Web.Mail, but fail with System.Net.Mail.
```
<add key="SmtpServer" value="smtp.att.yahoo.com"/>
<add key="SmtpServerAuthenticateUser" value="[email protected]"/>
<add key="SmtpServerPort" value="465"/>
<add key="SmtpUseSSL" value="1"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
```
Here is the code that grabs my settings, and works with GMail, fails with att.yahoo:
```
SmtpClient smtp;
if (!string.IsNullOrEmpty(Util.get_setting("SmtpServer", "")))
{
smtp = new SmtpClient(Util.get_setting("SmtpServer", ""));
}
else
{
smtp = new SmtpClient();
}
if (!string.IsNullOrEmpty(Util.get_setting("SmtpServerAuthenticatePassword", "")))
smtp.Credentials = new System.Net.NetworkCredential(
Util.get_setting("SmtpServerAuthenticateUser", ""),
Util.get_setting("SmtpServerAuthenticatePassword", ""));
if (!string.IsNullOrEmpty(Util.get_setting("SmtpServerPort", "")))
smtp.Port = int.Parse(Util.get_setting("SmtpServerPort", ""));
if (Util.get_setting("SmtpUseSSL", "0") == "1")
smtp.EnableSsl = true;
smtp.Send(message);
```
Is this my problem?
<http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx>
|
I've learned the answer. The answer is:
Because System.Net.Mail does not support "implicit" SSL, only "explicit" SSL.
|
172,223 |
<p>From the Apple <a href="http://developer.apple.com/internet/safari/faq.html" rel="noreferrer">developer faq</a></p>
<blockquote>
<p>Safari ships with a conservative
cookie policy which limits cookie
writes to only the pages chosen
("navigated to") by the user.</p>
</blockquote>
<p>By default Safari only allows cookies from sites you navigate to directly. (i.e. if you click on links with the url of that domainname).</p>
<p>This means that if you load a page from your own site with an iFrame with a page from another site, that the other site is not able to set cookies. (for instance, a ticketshop). As soon as you have visited the other domain directly, the other site is able to access and change its own cookies. </p>
<p>Without having access to code on the other site, how can i make the user-experience as inobtrusive as possible?</p>
<p>Is there a (javascript?) way to check if the other site's cookies
are already set, and accordingly, show a direct link to the other site first, if needed?</p>
<p>Update:</p>
<p>The HTML5 feature 'window.postmessage' seems to be a nice solution.<br>
There are some jQuery libraries that might help, and compatible with most recent browsers.<br>
In essence, the iFrame document sends messages, with Json, thru the window element.</p>
<p>The very nice <a href="http://postmessage.freebaseapps.com" rel="noreferrer">Postmessage-plugin</a>, by daepark, which i got working.<br>
and another <a href="http://benalman.com/projects/jquery-postmessage-plugin/" rel="noreferrer">jQuery postMessage</a>, by Ben Alman i found, but haven't tested.</p>
|
[
{
"answer_id": 1032746,
"author": "M.W. Felker",
"author_id": 127012,
"author_profile": "https://Stackoverflow.com/users/127012",
"pm_score": 3,
"selected": false,
"text": "<p>This is an issue known as Same Origin Policy. Essentially it is a security measure against creating security loopholes. </p>\n\n<p>When you have an iframe that points to a page on your own domain, JavaScript can access both the page you're on and the page within the Iframe. This is an acceptable parent to child and child to parent relationship.</p>\n\n<pre><code> (parent doc) (iframe doc)\n HTML --> IFRAME <-- HTML \n ^--------|---------^\n</code></pre>\n\n<p>However, once you have a file pointing to an external page, SOP comes into play and haults any information passing between the parent page and the iframe page.</p>\n\n<pre><code> (parent doc) (iframe doc)\n HTML --> IFRAME <-- HTML \n X\n</code></pre>\n\n<p>Check out this post about iframe communication, it makes a lot of sense!\n<a href=\"https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content\">Stackoverflow post</a></p>\n\n<p>These links really help too!</p>\n\n<p><strong>1)</strong> <a href=\"http://msdn.microsoft.com/en-us/library/bb735305.aspx\" rel=\"nofollow noreferrer\">Secure Cross-Domain Communication in the Browser</a><br/>\n<strong>2)</strong> <a href=\"http://en.wikipedia.org/wiki/Same_origin_policy\" rel=\"nofollow noreferrer\">wiki SOP or Same Origin Policy</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 1267191,
"author": "Cyphus",
"author_id": 1150,
"author_profile": "https://Stackoverflow.com/users/1150",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://saizai.livejournal.com/897522.html\" rel=\"nofollow noreferrer\">This page</a> suggests that you place some javascript in your pages which detects the absence of an always-there cookie. When it finds that the cookie has not been set, it posts the required session data to a page which sets the cookie, and redirects you back to the originating page. </p>\n\n<p>Apparently the POST is enough to satisfy Safari's 'have I navigated to this domain' test, so from then on it accepts cookies from that domain.</p>\n\n<p>Of course, it's not the nicest of code, but may well solve your problem.</p>\n"
},
{
"answer_id": 1288100,
"author": "tw39124",
"author_id": 142935,
"author_profile": "https://Stackoverflow.com/users/142935",
"pm_score": 2,
"selected": false,
"text": "<p>One solution (a bit messy) might be to have the parent page check for the presence of the cookie and if the cookie is not present run an AJAX call to a script on the iframe page's domain which sets the cookie.</p>\n"
},
{
"answer_id": 4001969,
"author": "Broote",
"author_id": 424410,
"author_profile": "https://Stackoverflow.com/users/424410",
"pm_score": 2,
"selected": false,
"text": "<p>This is a common issue with facebook apps displayed in Safari. The way many (including myself) have dealt with this is to have the iframed page POST to itself. When a page has posted form data, it is then allowed to set cookies. In the end, it works with a 1 page refresh, which could even be your user login POST. </p>\n"
},
{
"answer_id": 9560823,
"author": "colin moock",
"author_id": 228540,
"author_profile": "https://Stackoverflow.com/users/228540",
"pm_score": 3,
"selected": false,
"text": "<p>localStorage, supported by safari and all modern browsers, permits read/write operations even on pages loaded into iframes. if you don't mind dropping support for ie6 and ie7, try using localStorage instead of cookies in your framed site. i know your question specifically says you don't have access to code on the framed site, but for those who do, localStorage definitely solves the \"no cookies in a safari iframe\" problem.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25286/"
] |
From the Apple [developer faq](http://developer.apple.com/internet/safari/faq.html)
>
> Safari ships with a conservative
> cookie policy which limits cookie
> writes to only the pages chosen
> ("navigated to") by the user.
>
>
>
By default Safari only allows cookies from sites you navigate to directly. (i.e. if you click on links with the url of that domainname).
This means that if you load a page from your own site with an iFrame with a page from another site, that the other site is not able to set cookies. (for instance, a ticketshop). As soon as you have visited the other domain directly, the other site is able to access and change its own cookies.
Without having access to code on the other site, how can i make the user-experience as inobtrusive as possible?
Is there a (javascript?) way to check if the other site's cookies
are already set, and accordingly, show a direct link to the other site first, if needed?
Update:
The HTML5 feature 'window.postmessage' seems to be a nice solution.
There are some jQuery libraries that might help, and compatible with most recent browsers.
In essence, the iFrame document sends messages, with Json, thru the window element.
The very nice [Postmessage-plugin](http://postmessage.freebaseapps.com), by daepark, which i got working.
and another [jQuery postMessage](http://benalman.com/projects/jquery-postmessage-plugin/), by Ben Alman i found, but haven't tested.
|
This is an issue known as Same Origin Policy. Essentially it is a security measure against creating security loopholes.
When you have an iframe that points to a page on your own domain, JavaScript can access both the page you're on and the page within the Iframe. This is an acceptable parent to child and child to parent relationship.
```
(parent doc) (iframe doc)
HTML --> IFRAME <-- HTML
^--------|---------^
```
However, once you have a file pointing to an external page, SOP comes into play and haults any information passing between the parent page and the iframe page.
```
(parent doc) (iframe doc)
HTML --> IFRAME <-- HTML
X
```
Check out this post about iframe communication, it makes a lot of sense!
[Stackoverflow post](https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content)
These links really help too!
**1)** [Secure Cross-Domain Communication in the Browser](http://msdn.microsoft.com/en-us/library/bb735305.aspx)
**2)** [wiki SOP or Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy)
Good luck!
|
172,258 |
<p>I've written up a weekly-review GTD checklist for myself in TiddlyWiki, using <a href="http://www.tiddlytools.com/#CheckboxPlugin" rel="nofollow noreferrer">CheckboxPlugin</a>. After I'm finished with it each week, I'd like to click one link to uncheck (reset) all of the items on it, so it's ready for the next use.</p>
<p>I'm storing the check information as tags on a separate tiddler page. I should be able to just erase all the tags on that page and refresh the checklist page, but I haven't been able to work out how to do that yet.</p>
<p>I generally work in C, C++, and Lisp, I'm just learning about Javascript. Can anyone offer some useful pointers?</p>
<p>(And before anyone suggests it, I've looked at the ChecklistScript on the same site. It doesn't use the CheckboxPlugin stuff, and isn't compatible with it.)</p>
|
[
{
"answer_id": 178066,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Try this (adapted from ChecklistScript's \"resetall\" code):</p>\n\n<pre><code><html><form style=\"display:inline\">\n <input type=\"button\" value=\"clear all\" onclick=\"\n var tid='SomeTiddler';\n var list='tag1 [[tag 2]] tag3 tag4';\n var tags=list.readBracketedList();\n store.suspendNotifications();\n for (var t=0; t<tags.length; t++)\n store.setTiddlerTag(tid,false,tags[t]);\n store.resumeNotifications();\n story.refreshTiddler(tid,null,true);\n\"></form></html>\n</code></pre>\n"
},
{
"answer_id": 179200,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 1,
"selected": true,
"text": "<p>It took a while, but I figured it out (thanks to ELS's answer for the inspiration):</p>\n\n<pre><code><script label=\"(Reset All)\" title=\"Reset all items\" key=\"X\">\n var tid='WeeklyReviewStepsChecklistItems';\n store.getTiddler(tid).tags=[];\n story.refreshTiddler(tid,null,true);\n\n story.refreshTiddler('Weekly Review Steps',null,true);\n</script>\n</code></pre>\n\n<p>This only works because I'm storing the tags in a separate tiddler, and using the <a href=\"http://www.tiddlytools.com/#InlineJavascriptPlugin\" rel=\"nofollow noreferrer\">InlineJavascriptPlugin</a>.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
I've written up a weekly-review GTD checklist for myself in TiddlyWiki, using [CheckboxPlugin](http://www.tiddlytools.com/#CheckboxPlugin). After I'm finished with it each week, I'd like to click one link to uncheck (reset) all of the items on it, so it's ready for the next use.
I'm storing the check information as tags on a separate tiddler page. I should be able to just erase all the tags on that page and refresh the checklist page, but I haven't been able to work out how to do that yet.
I generally work in C, C++, and Lisp, I'm just learning about Javascript. Can anyone offer some useful pointers?
(And before anyone suggests it, I've looked at the ChecklistScript on the same site. It doesn't use the CheckboxPlugin stuff, and isn't compatible with it.)
|
It took a while, but I figured it out (thanks to ELS's answer for the inspiration):
```
<script label="(Reset All)" title="Reset all items" key="X">
var tid='WeeklyReviewStepsChecklistItems';
store.getTiddler(tid).tags=[];
story.refreshTiddler(tid,null,true);
story.refreshTiddler('Weekly Review Steps',null,true);
</script>
```
This only works because I'm storing the tags in a separate tiddler, and using the [InlineJavascriptPlugin](http://www.tiddlytools.com/#InlineJavascriptPlugin).
|
172,265 |
<p>I've got a WCF Web Service method whose prototype is:</p>
<pre><code>[OperationContract]
Response<List<Customer>> GetCustomers();
</code></pre>
<p>When I add the service reference to a client, Visual Studio (2005) creates a type called "ResponseOfArrayOfCustomerrleXg3IC" that is a wrapper for "Response<List<Customer>>". Is there any way I can control the wrapper name? ResponseOfArrayOfCustomerrleXg3IC doesn't sound very appealing...</p>
|
[
{
"answer_id": 172349,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": -1,
"selected": false,
"text": "<p>Yes. The OperationContractAttribute takes a parameter called Name. You could specify it like this:</p>\n\n<pre><code>[OperationContract(Name = \"NameGoesHere\")]\nResponse<List<Customer>> GetCustomers();\n</code></pre>\n"
},
{
"answer_id": 172370,
"author": "aogan",
"author_id": 4795,
"author_profile": "https://Stackoverflow.com/users/4795",
"pm_score": 2,
"selected": false,
"text": "<p>Please try this: </p>\n\n<pre><code>[OperationContract]\n[return: MessageParameter(Name=\"YOURNAME\")]\nResponse<List<Customer>> GetCustomers();\n</code></pre>\n"
},
{
"answer_id": 172671,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 5,
"selected": true,
"text": "<p>You can define your own name in the <code>DataContract</code> attribute like this:</p>\n\n<pre><code>[DataContract(Name = \"ResponseOf{0}\")]\npublic class Response<T>\n</code></pre>\n\n<p>Note that in your example the <code>{0}</code> will be replaced and your proxy reference type will be <code>ResponseOfArrayOfCustomer</code>. </p>\n\n<p>More info here: <a href=\"http://jeffbarnes.net/blog/post/2007/05/10/WCF-Serialization-and-Generics.aspx\" rel=\"nofollow noreferrer\">WCF: Serialization and Generics</a></p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
I've got a WCF Web Service method whose prototype is:
```
[OperationContract]
Response<List<Customer>> GetCustomers();
```
When I add the service reference to a client, Visual Studio (2005) creates a type called "ResponseOfArrayOfCustomerrleXg3IC" that is a wrapper for "Response<List<Customer>>". Is there any way I can control the wrapper name? ResponseOfArrayOfCustomerrleXg3IC doesn't sound very appealing...
|
You can define your own name in the `DataContract` attribute like this:
```
[DataContract(Name = "ResponseOf{0}")]
public class Response<T>
```
Note that in your example the `{0}` will be replaced and your proxy reference type will be `ResponseOfArrayOfCustomer`.
More info here: [WCF: Serialization and Generics](http://jeffbarnes.net/blog/post/2007/05/10/WCF-Serialization-and-Generics.aspx)
|
172,278 |
<p>I have a stored procedure with the following header:</p>
<pre><code>FUNCTION SaveShipment (p_user_id IN INTEGER, p_transaction_id IN INTEGER, p_vehicle_code IN VARCHAR2 DEFAULT NULL, p_seals IN VARCHAR2 DEFAULT NULL) RETURN INTEGER;
</code></pre>
<p>And I am having trouble running it from TOAD's Editor. I cannot run it as part of a select from dual statement because it preforms DML, but if I try the following syntax which I saw recommended on some forum:</p>
<pre><code>var c integer;
exec :c := orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, '');
print c;
</code></pre>
<p>I get:</p>
<pre><code>ORA-01008: not all variables bound
Details:
BEGIN :c := orm_helper.orm_helper.saveshipment (9999, 31896, null, ''); END;
Error at line 2
ORA-01008: not all variables bound
</code></pre>
<p>What's the proper syntax to run this sp manually?</p>
|
[
{
"answer_id": 172309,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 3,
"selected": true,
"text": "<p>Are you calling the stored procedure from another SP?</p>\n\n<p>I think the syntax is (if I recall correctly):</p>\n\n<pre><code>declare\n c integer;\nbegin\n\nc:=storedProc(...parameters...);\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 175856,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 0,
"selected": false,
"text": "<p>you could probably SELECT orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, '') FROM DUAL.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
I have a stored procedure with the following header:
```
FUNCTION SaveShipment (p_user_id IN INTEGER, p_transaction_id IN INTEGER, p_vehicle_code IN VARCHAR2 DEFAULT NULL, p_seals IN VARCHAR2 DEFAULT NULL) RETURN INTEGER;
```
And I am having trouble running it from TOAD's Editor. I cannot run it as part of a select from dual statement because it preforms DML, but if I try the following syntax which I saw recommended on some forum:
```
var c integer;
exec :c := orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, '');
print c;
```
I get:
```
ORA-01008: not all variables bound
Details:
BEGIN :c := orm_helper.orm_helper.saveshipment (9999, 31896, null, ''); END;
Error at line 2
ORA-01008: not all variables bound
```
What's the proper syntax to run this sp manually?
|
Are you calling the stored procedure from another SP?
I think the syntax is (if I recall correctly):
```
declare
c integer;
begin
c:=storedProc(...parameters...);
```
Hope this helps.
|
172,302 |
<p>This is for a small scheduling app. I need an algorithm to efficiently compare two "schedules", find differences, and update only the data rows which have been changed, as well as entries in another table having this table as a foreign key. This is a big question, so I'll say right away I'm looking for either <strong>general advice</strong> or <strong>specific solutions</strong>.</p>
<p><strong>EDIT:</strong> As suggested, I have significantly shortened the question.</p>
<p>In one table, I associate resources with a span of time when they are used. </p>
<p>I also have a second table (Table B) which uses the ID from Table A as a foreign key.</p>
<p>The entry from Table A corresponding to Table B will have a span of time which <strong>subsumes</strong> the span of time from Table B. Not all entries in Table A will have an entry in Table B.</p>
<p>I'm providing an interface for users to edit the resource schedule in Table A. They basically provide a new set of data for Table A that I need to treat as a <em>diff</em> from the version in the DB.</p>
<p>If they completely remove an object from Table A that is pointed to by Table B, I want to remove the entry from Table B as well.</p>
<p>So, given the following 3 sets:</p>
<ul>
<li>The original objects from Table A (from the DB)</li>
<li>The original objects from Table B (from the DB)</li>
<li>The edited set of objects from Table A (from the user, so no unique IDs)</li>
</ul>
<p>I need an algorithm that will:</p>
<ul>
<li>Leave rows in Table A and Table B untouched if no changes are needed for those objects.</li>
<li>Add rows to Table A as needed.</li>
<li>Remove rows from Table A and Table B as needed.</li>
<li>Modify rows in Table A and Table B as needed.</li>
</ul>
<p>Just sorting the objects into an arrangement where I can apply the appropriate database operations is more than adequate for a solution.</p>
<p>Again, please answer as <strong>specifically</strong> or <strong>generally</strong> as you like, I'm looking for advice but if someone has a complete algorithm that would just make my day. :)</p>
<p><strong>EDIT:</strong> In response to lassvek, I am providing some additional detail:</p>
<p>Table B's items are always contained entirely within Table A items, not merely overlapping.</p>
<p><em>Importantly,</em> Table B's items are quantized so they should fall either entirely within or entirely outside. If this doesn't happen, then I have a data integrity error that I'll have to handle separately.</p>
<p>For example (to use a shorthand):</p>
<pre>
Table A
ID Resource Start End
01 Resource A 10/6 7:00AM 10/6 11:00AM
02 Resource A 10/6 1:00PM 10/6 3:00PM
Table B
ID Table_A_ID Start End
01 02 10/6 1:00PM 10/6 2:00PM
</pre>
<p>So I want the following behaviours:</p>
<ul>
<li>If I remove ID 02 from table A, or shorten it to 2:00PM - 3:00PM, I should remove ID 01 from Table B.</li>
<li>If I extend Table A ID 01 to where it ends at 1:00PM, <strong>these two entries should be merged together into one row</strong>, and Table B ID 01 should now point to table A ID 01.</li>
<li>If I remove 8:00AM-10:00AM from Table A ID 01, that entry should be split into two entries: One for 7:00AM-8:00AM, and a new entry (ID 03) for 10:00AM-11:00AM.</li>
</ul>
|
[
{
"answer_id": 172485,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 1,
"selected": false,
"text": "<p>You post is almost in the \"too long; didnt read\" category - shortening it will probably give you more feedback.</p>\n\n<p>Anyway, on topic: you can try lookin into a thing called <a href=\"http://en.wikipedia.org/wiki/Allen's_Interval_Algebra\" rel=\"nofollow noreferrer\">\"Interval Algebra\"</a></p>\n"
},
{
"answer_id": 172519,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 1,
"selected": false,
"text": "<p>As I understand you, your users can only directly affect table A. Assuming you are programming in C#, you could use a simple ADO.Net DataSet to manage modifications to table A. The TableAdapter knows to leave untouched rows alone and to handle new, modified and deleted rows appropriately. </p>\n\n<p>In addition you should define a cascading delete in order to automatically remove corresponding objects in table B. </p>\n\n<p>The only case that is not handled this way is if a timespan in table A is shortened s.t. it does not subsume the corresponding record in Table B anymore. You could simply check for that case in an update stored procedure or alternatively define an update-trigger on table A.</p>\n"
},
{
"answer_id": 172540,
"author": "grossvogel",
"author_id": 14957,
"author_profile": "https://Stackoverflow.com/users/14957",
"pm_score": 1,
"selected": false,
"text": "<p>It seems to me like any algorithm for this will be involve a pass through NewA, matching ResourceID, StartTime, and EndTime, and keeping track of which elements from OldA get hit. Then you have two sets of non-matching data, UnmatchedNewA and UnmatchedOldA.</p>\n\n<p>The simplest way I can think of to proceed is to basically start over with these:\nWrite all of UnmatchedNewA to the DB, transfer elements of B from UnmatchedOldA into New A keys (just generated) where possible, deleting when not. Then wipe out all of UnmatchedOldA.</p>\n\n<p>If there are a lot of changes, this is certainly not an efficient way to proceed. In cases where the size of the data is not overwhelming, though, I prefer simplicity to clever optimization.</p>\n\n<hr>\n\n<p>It's impossible to know whether this final suggestion makes any sense without more background, but on the off chance that you didn't think of it this way:</p>\n\n<p>Instead of passing the entire A collection back and forth, could you use event listeners or something similar to update the data model only where changes ARE needed? This way, the objects being altered would be able to determine which DB operations are required on the fly.</p>\n"
},
{
"answer_id": 174021,
"author": "Yuval F",
"author_id": 1702,
"author_profile": "https://Stackoverflow.com/users/1702",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest you decouple your questions into two separate ones:\nThe first should be something like: \"How do I reason about resource scheduling, when representing a schedule atom as a resource with start time and end time?\" Here, ADept's suggestion to use interval algebra seems fitting. Please see <a href=\"http://en.wikipedia.org/wiki/Interval_graph\" rel=\"nofollow noreferrer\">The Wikipedia entry 'Interval Graph'</a> and <a href=\"http://www.cs.sunysb.edu/~algorith/files/scheduling.shtml\" rel=\"nofollow noreferrer\">The SUNY algorithm repository entry on scheduling</a>.\nThe second question is a database question: \"Given an algorithm which schedules intervals and indicate whether two intervals overlap or one is contained in another, how do I use this information to manage a database in the given schema?\" I believe that once the scheduling algorithm is in place, the database question will be much easier to solve.\nHTH,\nYuval</p>\n"
},
{
"answer_id": 174037,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": true,
"text": "<p>I have worked extensively with periods, but I'm afraid I don't understand entirely how table A and B work together, perhaps it's the word <em>subsume</em> that I don't understand.</p>\n\n<p>Can you give some concrete examples of what you want done?</p>\n\n<p>Do you mean that timespans recorded in table A contains entirely timespans in table B, like this?</p>\n\n<pre><code>|---------------- A -------------------|\n |--- B ----| |--- B ---|\n</code></pre>\n\n<p>or overlaps with?</p>\n\n<pre><code> |---------------- A -------------------|\n|--- B ----| |--- B ---|\n</code></pre>\n\n<p>or the opposite way, timespans in B contains/overlaps with A?</p>\n\n<p>Let's say it's the first one, where timespans in B are inside/the same as the linked timespan in table A.</p>\n\n<p>Does this mean that:</p>\n\n<pre><code>* A removed A-timespan removes all the linked timespans from B\n* An added A-timespan, what about this?\n* A shortened A-timespan removes all the linked timespans from B that now falls outside A\n* A lenghtened A-timespan, will this include all matching B-timespans now inside?\n</code></pre>\n\n<p>Here's an example:</p>\n\n<pre><code>|-------------- A1 --------------| |-------- A2 --------------|\n |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|\n</code></pre>\n\n<p>and then you lengthen A1 and shorten and move A2, so that:</p>\n\n<pre><code>|-------------- A1 ---------------------------------| |--- A2 --|\n |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|\n</code></pre>\n\n<p>this means that you want to modify the data like this:</p>\n\n<pre><code>1. Lengthen (update) A1\n2. Shorten and move (update) A2\n3. Re-link (update) B3 from A2 to A1 instead\n</code></pre>\n\n<p>how about this modification, A1 is lengthened, but not enough to contain B3 entirely, and A2 is moved/shortened the same way:</p>\n\n<pre><code>|-------------- A1 -----------------------------| |--- A2 --|\n |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|\n</code></pre>\n\n<p>Since B3 is now not entirely within either A1 or A2, remove it?</p>\n\n<p>I need some concrete examples of what you want done.</p>\n\n<hr>\n\n<p><strong>Edit</strong> More questions</p>\n\n<p>Ok, what about:</p>\n\n<pre><code>|------------------ A -----------------------|\n |------- B1 -------| |------- B2 ------|\n |---| <-- I want to remove this from A\n</code></pre>\n\n<p>What about this?</p>\n\n<p>Either:</p>\n\n<pre><code>|------------------ A1 ----| |---- A2 -----|\n |------- B1 -------| |B3| |--- B2 ---|\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>|------------------ A1 ----| |---- A2 -----|\n |------- B1 -------|\n</code></pre>\n\n<p>To summarize how I see it, with questions, so far:</p>\n\n<ul>\n<li>You want to be able to do the following operations on A's\n\n<ul>\n<li>Shorten</li>\n<li>Lengthen</li>\n<li>Combine when they are adjacent, combining two or more into one</li>\n<li>Punch holes in them by removing a period, and thus splitting it</li>\n</ul></li>\n<li>B's that are still contained within an A after the above update, relink if necessary</li>\n<li>B's that were contained, but are now entirely outside, delete them</li>\n<li>B's that were contained, but are now partially outside, <strong>Edit: Delete these, ref data integrity</strong></li>\n<li>For all the above operations, do the least minimum work necessary to bring the data in line with the operations (instead of just removing everything and inserting anew)</li>\n</ul>\n\n<p>I'll work on an implementation in C# that might work when I get home from work, I'll come back with more later tonight.</p>\n\n<hr>\n\n<p><strong>Edit</strong> Here's a stab at an algorithm.</p>\n\n<ol>\n<li>Optimize the new list first (ie. combine adjacent periods, etc.)</li>\n<li>\"merge\" this list with the master periods in the database in the following way:\n\n<ol>\n<li>keep track of where in both lists (ie. new and existing) you are</li>\n<li>if the current new period is entirely before the current existing period, add it, then move to the next new period</li>\n<li>if the current new period is entirely after the current existing period, remove the existing period and all its child periods, then move to the next existing period</li>\n<li>if the two overlap, adjust the current existing period to be equal to the new period, in the following way, then move on to the next new and existing period\n\n<ol>\n<li>if new period starts before existing period, simply move the start</li>\n<li>if new period starts after existing period, check if any child periods are in the difference-period, and remember them, then move the start</li>\n<li>do the same with the other end</li>\n</ol></li>\n</ol></li>\n<li>with any periods you \"remembered\", see if they needs to be relinked or deleted</li>\n</ol>\n\n<p>You should create a massive set of unit tests and make sure you cover all combinations of modifications.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] |
This is for a small scheduling app. I need an algorithm to efficiently compare two "schedules", find differences, and update only the data rows which have been changed, as well as entries in another table having this table as a foreign key. This is a big question, so I'll say right away I'm looking for either **general advice** or **specific solutions**.
**EDIT:** As suggested, I have significantly shortened the question.
In one table, I associate resources with a span of time when they are used.
I also have a second table (Table B) which uses the ID from Table A as a foreign key.
The entry from Table A corresponding to Table B will have a span of time which **subsumes** the span of time from Table B. Not all entries in Table A will have an entry in Table B.
I'm providing an interface for users to edit the resource schedule in Table A. They basically provide a new set of data for Table A that I need to treat as a *diff* from the version in the DB.
If they completely remove an object from Table A that is pointed to by Table B, I want to remove the entry from Table B as well.
So, given the following 3 sets:
* The original objects from Table A (from the DB)
* The original objects from Table B (from the DB)
* The edited set of objects from Table A (from the user, so no unique IDs)
I need an algorithm that will:
* Leave rows in Table A and Table B untouched if no changes are needed for those objects.
* Add rows to Table A as needed.
* Remove rows from Table A and Table B as needed.
* Modify rows in Table A and Table B as needed.
Just sorting the objects into an arrangement where I can apply the appropriate database operations is more than adequate for a solution.
Again, please answer as **specifically** or **generally** as you like, I'm looking for advice but if someone has a complete algorithm that would just make my day. :)
**EDIT:** In response to lassvek, I am providing some additional detail:
Table B's items are always contained entirely within Table A items, not merely overlapping.
*Importantly,* Table B's items are quantized so they should fall either entirely within or entirely outside. If this doesn't happen, then I have a data integrity error that I'll have to handle separately.
For example (to use a shorthand):
```
Table A
ID Resource Start End
01 Resource A 10/6 7:00AM 10/6 11:00AM
02 Resource A 10/6 1:00PM 10/6 3:00PM
Table B
ID Table_A_ID Start End
01 02 10/6 1:00PM 10/6 2:00PM
```
So I want the following behaviours:
* If I remove ID 02 from table A, or shorten it to 2:00PM - 3:00PM, I should remove ID 01 from Table B.
* If I extend Table A ID 01 to where it ends at 1:00PM, **these two entries should be merged together into one row**, and Table B ID 01 should now point to table A ID 01.
* If I remove 8:00AM-10:00AM from Table A ID 01, that entry should be split into two entries: One for 7:00AM-8:00AM, and a new entry (ID 03) for 10:00AM-11:00AM.
|
I have worked extensively with periods, but I'm afraid I don't understand entirely how table A and B work together, perhaps it's the word *subsume* that I don't understand.
Can you give some concrete examples of what you want done?
Do you mean that timespans recorded in table A contains entirely timespans in table B, like this?
```
|---------------- A -------------------|
|--- B ----| |--- B ---|
```
or overlaps with?
```
|---------------- A -------------------|
|--- B ----| |--- B ---|
```
or the opposite way, timespans in B contains/overlaps with A?
Let's say it's the first one, where timespans in B are inside/the same as the linked timespan in table A.
Does this mean that:
```
* A removed A-timespan removes all the linked timespans from B
* An added A-timespan, what about this?
* A shortened A-timespan removes all the linked timespans from B that now falls outside A
* A lenghtened A-timespan, will this include all matching B-timespans now inside?
```
Here's an example:
```
|-------------- A1 --------------| |-------- A2 --------------|
|---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|
```
and then you lengthen A1 and shorten and move A2, so that:
```
|-------------- A1 ---------------------------------| |--- A2 --|
|---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|
```
this means that you want to modify the data like this:
```
1. Lengthen (update) A1
2. Shorten and move (update) A2
3. Re-link (update) B3 from A2 to A1 instead
```
how about this modification, A1 is lengthened, but not enough to contain B3 entirely, and A2 is moved/shortened the same way:
```
|-------------- A1 -----------------------------| |--- A2 --|
|---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|
```
Since B3 is now not entirely within either A1 or A2, remove it?
I need some concrete examples of what you want done.
---
**Edit** More questions
Ok, what about:
```
|------------------ A -----------------------|
|------- B1 -------| |------- B2 ------|
|---| <-- I want to remove this from A
```
What about this?
Either:
```
|------------------ A1 ----| |---- A2 -----|
|------- B1 -------| |B3| |--- B2 ---|
```
or:
```
|------------------ A1 ----| |---- A2 -----|
|------- B1 -------|
```
To summarize how I see it, with questions, so far:
* You want to be able to do the following operations on A's
+ Shorten
+ Lengthen
+ Combine when they are adjacent, combining two or more into one
+ Punch holes in them by removing a period, and thus splitting it
* B's that are still contained within an A after the above update, relink if necessary
* B's that were contained, but are now entirely outside, delete them
* B's that were contained, but are now partially outside, **Edit: Delete these, ref data integrity**
* For all the above operations, do the least minimum work necessary to bring the data in line with the operations (instead of just removing everything and inserting anew)
I'll work on an implementation in C# that might work when I get home from work, I'll come back with more later tonight.
---
**Edit** Here's a stab at an algorithm.
1. Optimize the new list first (ie. combine adjacent periods, etc.)
2. "merge" this list with the master periods in the database in the following way:
1. keep track of where in both lists (ie. new and existing) you are
2. if the current new period is entirely before the current existing period, add it, then move to the next new period
3. if the current new period is entirely after the current existing period, remove the existing period and all its child periods, then move to the next existing period
4. if the two overlap, adjust the current existing period to be equal to the new period, in the following way, then move on to the next new and existing period
1. if new period starts before existing period, simply move the start
2. if new period starts after existing period, check if any child periods are in the difference-period, and remember them, then move the start
3. do the same with the other end
3. with any periods you "remembered", see if they needs to be relinked or deleted
You should create a massive set of unit tests and make sure you cover all combinations of modifications.
|
172,303 |
<p>Is it possible to detect a valid regular expression with another regular expression? If so please give example code below.</p>
|
[
{
"answer_id": 172312,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 8,
"selected": false,
"text": "<p>Unlikely.</p>\n\n<p>Evaluate it in a <code>try..catch</code> or whatever your language provides.</p>\n"
},
{
"answer_id": 172316,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 11,
"selected": true,
"text": "<pre><code>/\n^ # start of string\n( # first group start\n (?:\n (?:[^?+*{}()[\\]\\\\|]+ # literals and ^, $\n | \\\\. # escaped characters\n | \\[ (?: \\^?\\\\. | \\^[^\\\\] | [^\\\\^] ) # character classes\n (?: [^\\]\\\\]+ | \\\\. )* \\]\n | \\( (?:\\?[:=!]|\\?<[=!]|\\?>)? (?1)?? \\) # parenthesis, with recursive content\n | \\(\\? (?:R|[+-]?\\d+) \\) # recursive matching\n )\n (?: (?:[?+*]|\\{\\d+(?:,\\d*)?\\}) [?+]? )? # quantifiers\n | \\| # alternative\n )* # repeat content\n) # end first group\n$ # end of string\n/\n</code></pre>\n\n<p>This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.</p>\n\n<p>Without whitespace and comments:</p>\n\n<pre><code>/^((?:(?:[^?+*{}()[\\]\\\\|]+|\\\\.|\\[(?:\\^?\\\\.|\\^[^\\\\]|[^\\\\^])(?:[^\\]\\\\]+|\\\\.)*\\]|\\((?:\\?[:=!]|\\?<[=!]|\\?>)?(?1)??\\)|\\(\\?(?:R|[+-]?\\d+)\\))(?:(?:[?+*]|\\{\\d+(?:,\\d*)?\\})[?+]?)?|\\|)*)$/\n</code></pre>\n\n<hr>\n\n<p>.NET does not support recursion directly. (The <code>(?1)</code> and <code>(?R)</code> constructs.) The recursion would have to be converted to counting balanced groups:</p>\n\n<pre><code>^ # start of string\n(?:\n (?: [^?+*{}()[\\]\\\\|]+ # literals and ^, $\n | \\\\. # escaped characters\n | \\[ (?: \\^?\\\\. | \\^[^\\\\] | [^\\\\^] ) # character classes\n (?: [^\\]\\\\]+ | \\\\. )* \\]\n | \\( (?:\\?[:=!]\n | \\?<[=!]\n | \\?>\n | \\?<[^\\W\\d]\\w*>\n | \\?'[^\\W\\d]\\w*'\n )? # opening of group\n (?<N>) # increment counter\n | \\) # closing of group\n (?<-N>) # decrement counter\n )\n (?: (?:[?+*]|\\{\\d+(?:,\\d*)?\\}) [?+]? )? # quantifiers\n| \\| # alternative\n)* # repeat content\n$ # end of string\n(?(N)(?!)) # fail if counter is non-zero.\n</code></pre>\n\n<p>Compacted:</p>\n\n<pre><code>^(?:(?:[^?+*{}()[\\]\\\\|]+|\\\\.|\\[(?:\\^?\\\\.|\\^[^\\\\]|[^\\\\^])(?:[^\\]\\\\]+|\\\\.)*\\]|\\((?:\\?[:=!]|\\?<[=!]|\\?>|\\?<[^\\W\\d]\\w*>|\\?'[^\\W\\d]\\w*')?(?<N>)|\\)(?<-N>))(?:(?:[?+*]|\\{\\d+(?:,\\d*)?\\})[?+]?)?|\\|)*$(?(N)(?!))\n</code></pre>\n\n<p>From the comments:</p>\n\n<blockquote>\n <p>Will this validate substitutions and translations?</p>\n</blockquote>\n\n<p>It will validate just the regex part of substitutions and translations. <code>s/<this part>/.../</code></p>\n\n<blockquote>\n <p>It is not theoretically possible to match all valid regex grammars with a regex. </p>\n</blockquote>\n\n<p>It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.</p>\n\n<blockquote>\n <p>Indeed, a \"recursive regular expression\" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.</p>\n</blockquote>\n\n<p>\"In theory, theory and practice are the same. In practice, they're not.\" Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.</p>\n\n<blockquote>\n <p>using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions</p>\n</blockquote>\n\n<p>This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.</p>\n\n<blockquote>\n <p>Regex itself \"is not a regular language and hence cannot be parsed by regular expression...\"</p>\n</blockquote>\n\n<p>This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.</p>\n\n<blockquote>\n <p>I see where you're matching <code>[]()/\\</code>. and other special regex characters. Where are you allowing non-special characters? It seems like this will match <code>^(?:[\\.]+)$</code>, but not <code>^abcdefg$</code>. That's a valid regex.</p>\n</blockquote>\n\n<p><code>[^?+*{}()[\\]\\\\|]</code> will match any single character, not part of any of the other constructs. This includes both literal (<code>a</code> - <code>z</code>), and certain special characters (<code>^</code>, <code>$</code>, <code>.</code>).</p>\n"
},
{
"answer_id": 172338,
"author": "I GIVE CRAP ANSWERS",
"author_id": 25083,
"author_profile": "https://Stackoverflow.com/users/25083",
"pm_score": 6,
"selected": false,
"text": "<p>Good question. </p>\n\n<p>True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains <code>'('</code> and <code>')'</code> the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.</p>\n\n<p>However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you \"count\" the current nesting depth by pushing onto this stack.</p>\n\n<p>Russ Cox wrote \"<a href=\"http://swtch.com/~rsc/regexp/regexp1.html\" rel=\"noreferrer\">Regular Expression Matching Can Be Simple And Fast</a>\" which is a wonderful treatise on regex engine implementation. </p>\n"
},
{
"answer_id": 172363,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 8,
"selected": false,
"text": "<p>No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. </p>\n\n<p>There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take <code>[]</code> as an example. Whenever there is an <code>[</code> there must be a matching <code>]</code>, which is simple enough for a regex <code>\"\\[.*\\]\"</code>.</p>\n\n<p>What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets. </p>\n\n<p>This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count. </p>\n\n<hr>\n\n<p>I ended up writing \"<a href=\"https://learn.microsoft.com/archive/blogs/jaredpar/regular-expression-limitations\" rel=\"noreferrer\">Regular Expression Limitations</a>\" about this.</p>\n"
},
{
"answer_id": 174440,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 4,
"selected": false,
"text": "<p>Though it is perfectly possible to use a recursive regex as MizardX has posted, for this kind of things it is much more useful a parser. Regexes were originally intended to be used with regular languages, being recursive or having balancing groups is just a patch.</p>\n\n<p>The language that defines valid regexes is actually a context free grammar, and you should use an appropriate parser for handling it. Here is an example for a university project for parsing simple regexes (without most constructs). It uses JavaCC. And yes, comments are in Spanish, though method names are pretty self-explanatory.</p>\n\n<pre><code>SKIP :\n{\n \" \"\n| \"\\r\"\n| \"\\t\"\n| \"\\n\"\n}\nTOKEN : \n{\n < DIGITO: [\"0\" - \"9\"] >\n| < MAYUSCULA: [\"A\" - \"Z\"] >\n| < MINUSCULA: [\"a\" - \"z\"] >\n| < LAMBDA: \"LAMBDA\" >\n| < VACIO: \"VACIO\" >\n}\n\nIRegularExpression Expression() :\n{\n IRegularExpression r; \n}\n{\n r=Alternation() { return r; }\n}\n\n// Matchea disyunciones: ER | ER\nIRegularExpression Alternation() :\n{\n IRegularExpression r1 = null, r2 = null; \n}\n{\n r1=Concatenation() ( \"|\" r2=Alternation() )?\n { \n if (r2 == null) {\n return r1;\n } else {\n return createAlternation(r1,r2);\n } \n }\n}\n\n// Matchea concatenaciones: ER.ER\nIRegularExpression Concatenation() :\n{\n IRegularExpression r1 = null, r2 = null; \n}\n{\n r1=Repetition() ( \".\" r2=Repetition() { r1 = createConcatenation(r1,r2); } )*\n { return r1; }\n}\n\n// Matchea repeticiones: ER*\nIRegularExpression Repetition() :\n{\n IRegularExpression r; \n}\n{\n r=Atom() ( \"*\" { r = createRepetition(r); } )*\n { return r; }\n}\n\n// Matchea regex atomicas: (ER), Terminal, Vacio, Lambda\nIRegularExpression Atom() :\n{\n String t;\n IRegularExpression r;\n}\n{\n ( \"(\" r=Expression() \")\" {return r;}) \n | t=Terminal() { return createTerminal(t); }\n | <LAMBDA> { return createLambda(); }\n | <VACIO> { return createEmpty(); }\n}\n\n// Matchea un terminal (digito o minuscula) y devuelve su valor\nString Terminal() :\n{\n Token t;\n}\n{\n ( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; }\n}\n</code></pre>\n"
},
{
"answer_id": 2904721,
"author": "PaulMcG",
"author_id": 165216,
"author_profile": "https://Stackoverflow.com/users/165216",
"pm_score": 3,
"selected": false,
"text": "<p>The following example by Paul McGuire, originally from the pyparsing wiki, but now <a href=\"https://web.archive.org/web/20120311031702/http://pyparsing.wikispaces.com/file/view/invRegex.py\" rel=\"nofollow noreferrer\">available only through the Wayback Machine</a>, gives a grammar for parsing <em>some</em> regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.</p>\n\n<pre><code># \n# invRegex.py\n#\n# Copyright 2008, Paul McGuire\n#\n# pyparsing script to expand a regular expression into all possible matching strings\n# Supports:\n# - {n} and {m,n} repetition, but not unbounded + or * repetition\n# - ? optional elements\n# - [] character ranges\n# - () grouping\n# - | alternation\n#\n__all__ = [\"count\",\"invert\"]\n\nfrom pyparsing import (Literal, oneOf, printables, ParserElement, Combine, \n SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,\n Suppress, ParseResults, srange)\n\nclass CharacterRangeEmitter(object):\n def __init__(self,chars):\n # remove duplicate chars in character range, but preserve original order\n seen = set()\n self.charset = \"\".join( seen.add(c) or c for c in chars if c not in seen )\n def __str__(self):\n return '['+self.charset+']'\n def __repr__(self):\n return '['+self.charset+']'\n def makeGenerator(self):\n def genChars():\n for s in self.charset:\n yield s\n return genChars\n\nclass OptionalEmitter(object):\n def __init__(self,expr):\n self.expr = expr\n def makeGenerator(self):\n def optionalGen():\n yield \"\"\n for s in self.expr.makeGenerator()():\n yield s\n return optionalGen\n\nclass DotEmitter(object):\n def makeGenerator(self):\n def dotGen():\n for c in printables:\n yield c\n return dotGen\n\nclass GroupEmitter(object):\n def __init__(self,exprs):\n self.exprs = ParseResults(exprs)\n def makeGenerator(self):\n def groupGen():\n def recurseList(elist):\n if len(elist)==1:\n for s in elist[0].makeGenerator()():\n yield s\n else:\n for s in elist[0].makeGenerator()():\n for s2 in recurseList(elist[1:]):\n yield s + s2\n if self.exprs:\n for s in recurseList(self.exprs):\n yield s\n return groupGen\n\nclass AlternativeEmitter(object):\n def __init__(self,exprs):\n self.exprs = exprs\n def makeGenerator(self):\n def altGen():\n for e in self.exprs:\n for s in e.makeGenerator()():\n yield s\n return altGen\n\nclass LiteralEmitter(object):\n def __init__(self,lit):\n self.lit = lit\n def __str__(self):\n return \"Lit:\"+self.lit\n def __repr__(self):\n return \"Lit:\"+self.lit\n def makeGenerator(self):\n def litGen():\n yield self.lit\n return litGen\n\ndef handleRange(toks):\n return CharacterRangeEmitter(srange(toks[0]))\n\ndef handleRepetition(toks):\n toks=toks[0]\n if toks[1] in \"*+\":\n raise ParseFatalException(\"\",0,\"unbounded repetition operators not supported\")\n if toks[1] == \"?\":\n return OptionalEmitter(toks[0])\n if \"count\" in toks:\n return GroupEmitter([toks[0]] * int(toks.count))\n if \"minCount\" in toks:\n mincount = int(toks.minCount)\n maxcount = int(toks.maxCount)\n optcount = maxcount - mincount\n if optcount:\n opt = OptionalEmitter(toks[0])\n for i in range(1,optcount):\n opt = OptionalEmitter(GroupEmitter([toks[0],opt]))\n return GroupEmitter([toks[0]] * mincount + [opt])\n else:\n return [toks[0]] * mincount\n\ndef handleLiteral(toks):\n lit = \"\"\n for t in toks:\n if t[0] == \"\\\\\":\n if t[1] == \"t\":\n lit += '\\t'\n else:\n lit += t[1]\n else:\n lit += t\n return LiteralEmitter(lit) \n\ndef handleMacro(toks):\n macroChar = toks[0][1]\n if macroChar == \"d\":\n return CharacterRangeEmitter(\"0123456789\")\n elif macroChar == \"w\":\n return CharacterRangeEmitter(srange(\"[A-Za-z0-9_]\"))\n elif macroChar == \"s\":\n return LiteralEmitter(\" \")\n else:\n raise ParseFatalException(\"\",0,\"unsupported macro character (\" + macroChar + \")\")\n\ndef handleSequence(toks):\n return GroupEmitter(toks[0])\n\ndef handleDot():\n return CharacterRangeEmitter(printables)\n\ndef handleAlternative(toks):\n return AlternativeEmitter(toks[0])\n\n\n_parser = None\ndef parser():\n global _parser\n if _parser is None:\n ParserElement.setDefaultWhitespaceChars(\"\")\n lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,\"[]{}()\")\n\n reMacro = Combine(\"\\\\\" + oneOf(list(\"dws\")))\n escapedChar = ~reMacro + Combine(\"\\\\\" + oneOf(list(printables)))\n reLiteralChar = \"\".join(c for c in printables if c not in r\"\\[]{}().*?+|\") + \" \\t\"\n\n reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)\n reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )\n reDot = Literal(\".\")\n repetition = (\n ( lbrace + Word(nums).setResultsName(\"count\") + rbrace ) |\n ( lbrace + Word(nums).setResultsName(\"minCount\")+\",\"+ Word(nums).setResultsName(\"maxCount\") + rbrace ) |\n oneOf(list(\"*+?\")) \n )\n\n reRange.setParseAction(handleRange)\n reLiteral.setParseAction(handleLiteral)\n reMacro.setParseAction(handleMacro)\n reDot.setParseAction(handleDot)\n\n reTerm = ( reLiteral | reRange | reMacro | reDot )\n reExpr = operatorPrecedence( reTerm,\n [\n (repetition, 1, opAssoc.LEFT, handleRepetition),\n (None, 2, opAssoc.LEFT, handleSequence),\n (Suppress('|'), 2, opAssoc.LEFT, handleAlternative),\n ]\n )\n _parser = reExpr\n\n return _parser\n\ndef count(gen):\n \"\"\"Simple function to count the number of elements returned by a generator.\"\"\"\n i = 0\n for s in gen:\n i += 1\n return i\n\ndef invert(regex):\n \"\"\"Call this routine as a generator to return all the strings that\n match the input regular expression.\n for s in invert(\"[A-Z]{3}\\d{3}\"):\n print s\n \"\"\"\n invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()\n return invReGenerator()\n\ndef main():\n tests = r\"\"\"\n [A-EA]\n [A-D]*\n [A-D]{3}\n X[A-C]{3}Y\n X[A-C]{3}\\(\n X\\d\n foobar\\d\\d\n foobar{2}\n foobar{2,9}\n fooba[rz]{2}\n (foobar){2}\n ([01]\\d)|(2[0-5])\n ([01]\\d\\d)|(2[0-4]\\d)|(25[0-5])\n [A-C]{1,2}\n [A-C]{0,3}\n [A-C]\\s[A-C]\\s[A-C]\n [A-C]\\s?[A-C][A-C]\n [A-C]\\s([A-C][A-C])\n [A-C]\\s([A-C][A-C])?\n [A-C]{2}\\d{2}\n @|TH[12]\n @(@|TH[12])?\n @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?\n @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?\n (([ECMP]|HA|AK)[SD]|HS)T\n [A-CV]{2}\n A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]\n (a|b)|(x|y)\n (a|b) (x|y)\n \"\"\".split('\\n')\n\n for t in tests:\n t = t.strip()\n if not t: continue\n print '-'*50\n print t\n try:\n print count(invert(t))\n for s in invert(t):\n print s\n except ParseFatalException,pfe:\n print pfe.msg\n print\n continue\n print\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n"
},
{
"answer_id": 7222877,
"author": "Richard - Rogue Wave Limited",
"author_id": 206263,
"author_profile": "https://Stackoverflow.com/users/206263",
"pm_score": 4,
"selected": false,
"text": "<p>You can submit the regex to <code>preg_match</code> which will return false if the regex is not valid. Don't forget to use the <code>@</code> to suppress error messages:</p>\n\n<pre><code>@preg_match($regexToTest, '');\n</code></pre>\n\n<ul>\n<li>Will return 1 if the regex is <code>//</code>. </li>\n<li>Will return 0 if the regex is okay. </li>\n<li>Will return false otherwise.</li>\n</ul>\n"
},
{
"answer_id": 55575718,
"author": "Davide Visentin",
"author_id": 6761184,
"author_profile": "https://Stackoverflow.com/users/6761184",
"pm_score": 4,
"selected": false,
"text": "<p>No, if you use standard regular expressions.</p>\n\n<p>The reason is that you cannot satisfy the <a href=\"https://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages\" rel=\"nofollow noreferrer\">pumping lemma</a> for regular languages. The pumping lemma states that a string belonging to language \"L\" is regular if there exists a number \"N\" such that, after dividing the string into three substrings <code>x</code>, <code>y</code>, <code>z</code>, such that <code>|x|>=1 && |xy|<=N</code>, you can repeat <code>y</code> as many times as you want and the entire string will still belong to <code>L</code>.</p>\n\n<p>A consequence of the pumping lemma is that you cannot have regular strings in the form <code>a^Nb^Mc^N</code>, that is, two substrings having the same length separated by another string. In any way you split such strings in <code>x</code>, <code>y</code> and <code>z</code>, you cannot \"pump\" <code>y</code> without obtaining a string with a different number of \"a\" and \"c\", thus leaving the original language. That's the case, for example, with parentheses in regular expressions.</p>\n"
},
{
"answer_id": 67020534,
"author": "Charanjit Singh",
"author_id": 9275249,
"author_profile": "https://Stackoverflow.com/users/9275249",
"pm_score": 2,
"selected": false,
"text": "<p>In Javascript:</p>\n<pre><code>SyntaxError\n</code></pre>\n<p>is thrown when an invalid regex is passed to evaluate.</p>\n<pre><code>// VALID ONE\n> /yes[^]*day/\nOut: /yes[^]*day/\n\n// INVALID ONE\n> /yes[^*day/\nOut: VM227:1 Uncaught SyntaxError: Invalid regular expression: missing /\n</code></pre>\n<p>Here's the function to check if the regex string is valid:</p>\n<p>Step 1: Regex Parser</p>\n<pre><code>var RegexParser = function(input) {\n\n // Parse input\n var m = input.match(/(\\/?)(.+)\\1([a-z]*)/i);\n\n // Invalid flags\n if (m[3] && !/^(?!.*?(.).*?\\1)[gmixXsuUAJ]+$/.test(m[3])) {\n return RegExp(input);\n }\n\n // Create the regular expression\n return new RegExp(m[2], m[3]);\n};\n</code></pre>\n<p>Step 2: Use parser</p>\n<pre><code>var RegexString = "/yes.*day/"\n\nvar isRegexValid = input => {\n try {\n const regex = RegexParser(input);\n }\n catch(error) {\n if(error.name === "SyntaxError") \n {\n return false;\n }\n else \n {\n throw error;\n }\n }\n return true;\n}\n\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10950/"
] |
Is it possible to detect a valid regular expression with another regular expression? If so please give example code below.
|
```
/
^ # start of string
( # first group start
(?:
(?:[^?+*{}()[\]\\|]+ # literals and ^, $
| \\. # escaped characters
| \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
(?: [^\]\\]+ | \\. )* \]
| \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis, with recursive content
| \(\? (?:R|[+-]?\d+) \) # recursive matching
)
(?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \| # alternative
)* # repeat content
) # end first group
$ # end of string
/
```
This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.
Without whitespace and comments:
```
/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
```
---
.NET does not support recursion directly. (The `(?1)` and `(?R)` constructs.) The recursion would have to be converted to counting balanced groups:
```
^ # start of string
(?:
(?: [^?+*{}()[\]\\|]+ # literals and ^, $
| \\. # escaped characters
| \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
(?: [^\]\\]+ | \\. )* \]
| \( (?:\?[:=!]
| \?<[=!]
| \?>
| \?<[^\W\d]\w*>
| \?'[^\W\d]\w*'
)? # opening of group
(?<N>) # increment counter
| \) # closing of group
(?<-N>) # decrement counter
)
(?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \| # alternative
)* # repeat content
$ # end of string
(?(N)(?!)) # fail if counter is non-zero.
```
Compacted:
```
^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))
```
From the comments:
>
> Will this validate substitutions and translations?
>
>
>
It will validate just the regex part of substitutions and translations. `s/<this part>/.../`
>
> It is not theoretically possible to match all valid regex grammars with a regex.
>
>
>
It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.
>
> Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.
>
>
>
"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.
>
> using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions
>
>
>
This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.
>
> Regex itself "is not a regular language and hence cannot be parsed by regular expression..."
>
>
>
This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.
>
> I see where you're matching `[]()/\`. and other special regex characters. Where are you allowing non-special characters? It seems like this will match `^(?:[\.]+)$`, but not `^abcdefg$`. That's a valid regex.
>
>
>
`[^?+*{}()[\]\\|]` will match any single character, not part of any of the other constructs. This includes both literal (`a` - `z`), and certain special characters (`^`, `$`, `.`).
|
172,320 |
<p>I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.</p>
<p>Right now In my code I'm forced to do something like this:</p>
<pre><code>if( _animalType == AnimalType.Pig )
{
//namespace is pigfeet
PigFeet.Feet feet = new Feet();
feet.WashFeet();
}
if( _animalType == AnimalType.Horse )
{
//namespace is horsefeet
HorseFeet.Feet feet = new Feet();
feet.WashFeet();
}
</code></pre>
<p>This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically?</p>
|
[
{
"answer_id": 172324,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 2,
"selected": false,
"text": "<p>In your namespace imports you can assign an <a href=\"http://msdn.microsoft.com/en-us/library/aa664765(VS.71).aspx\" rel=\"nofollow noreferrer\">alias</a> to a specific namespace or member.</p>\n\n<pre><code>using PigFeet = PigFeet.Feet;\nusing HorseFeet = HorseFeet.Feet;\n\n//now your sample code should look something like\n\nif( _animalType == AnimalType.Pig )\n{ \n //namespace is pigfeet\n PigFeet feet = new PigFeet();\n feet.WashFeet();\n}\n\nif( _animalType == AnimalType.Horse )\n{\n //namespace is horsefeet\n HorseFeet feet = new HorseFeet();\n feet.WashFeet();\n }\n</code></pre>\n"
},
{
"answer_id": 172354,
"author": "Ihar Bury",
"author_id": 18001,
"author_profile": "https://Stackoverflow.com/users/18001",
"pm_score": 0,
"selected": false,
"text": "<p>Namespaces are just a way to organize your types. In your case you're having 2 or more different classes that have methods with the same signature but don't have a common interface. In case you cannot change the code of the classes, the only way to avoid duplication here is to use reflection while loosing compile-time type-safety.</p>\n"
},
{
"answer_id": 172369,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "<p>The namespace isn't the problem - it's simply that the 2 classes aren't related, so there's no inheritance chain that you can use for polymorphism. </p>\n\n<p>You'll need to look at something like <a href=\"http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx\" rel=\"nofollow noreferrer\">duck typing</a>, or an <a href=\"http://en.wikipedia.org/wiki/Adapter_pattern\" rel=\"nofollow noreferrer\">adapter pattern</a>, or building your own proxy classes to get yourself to a common interface. For small numbers of implementations, I've gotten away with just building a single adapter class that delegates to whatever non-null instance it has:</p>\n\n<pre><code>interface IFeet {\n void WashFeet();\n}\n\nclass FeetAdapter : IFeet {\n private PigFeet.Feet _pigFeet;\n private HorseFeet.Feet _horseFeet;\n\n private FeetAdapter(PigFeet.Feet pigFeet) {\n _pigFeet = pigFeet;\n }\n\n private FeetAdapter(HorseFeet.Feet horseFeet) {\n _horseFeet = horseFeet;\n }\n\n public void WashFeet() {\n if (_pigFeet != null) {\n _pigFeet.WashFeet();\n } else {\n _horseFeet.WashFeet();\n }\n }\n\n public static FeetAdapter Create(AnimalType animalType) {\n switch (animalType) {\n case AnimalType.Pig:\n return new FeetAdapter(new PigFeet.Feet());\n case AnimalType.Horse:\n return new FeetAdapter(new HorseFeet.Feet());\n }\n }\n}\n</code></pre>\n\n<p>For larger cases, you'd be better off with a separate PigFeetAdapter and HorseFeetAdapter that both implement IFeet, along with a FeetAdapterFactory to create them - but the concept is the same as I show above.</p>\n"
},
{
"answer_id": 172385,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>Here's me making things worse before making them better.</p>\n\n<p>You can encapsulate all the AnimalType decision logic in a single class.</p>\n\n<p>Between the two types (PigsFeet and HorseFeet), there are some similiar methods...\nSince WashFeet has a common signature (void with no params), System.Action can be used to reference that method. Other methods with common signatures (and parameters) may require System.Func(T). Other methods without common signatures may need to be coerced into a common signature.</p>\n\n<p>Here's the client code:</p>\n\n<pre><code>AnimalFeetFacade myFacade = new AnimalFeetFacade(_animalType);\nmyFacade.WashFeet();\n</code></pre>\n\n<p>Here's the encapsulation class.</p>\n\n<pre><code>public class AnimalFeetFacade\n{\n public AnimalFeetFacade(AnimalType theType)\n {\n if (theType == AnimalType.Pig)\n {\n _washFeet = WashPigFeet;\n //TODO reference more PigFeet methods here\n }\n else if (theType == AnimalType.Horse)\n {\n _washFeet = WashHorseFeet;\n //TODO reference more HorseFeet methods here\n }\n else\n {\n throw new NotImplementedException(\"AnimalFeetFacade only works with PigFeet and HorseFeet\");\n }\n }\n\n protected Action _washFeet;\n\n public void WashFeet()\n {\n _washFeet.Invoke();\n }\n\n protected void WashPigFeet()\n {\n PigFeet.Feet = new PigFeet.Feet()\n feet.WashFeet()\n } \n\n protected void WashHorseFeet()\n {\n HorseFeet.Feet = new HorseFeet.Feet()\n feet.WashFeet()\n }\n}\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25300/"
] |
I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.
Right now In my code I'm forced to do something like this:
```
if( _animalType == AnimalType.Pig )
{
//namespace is pigfeet
PigFeet.Feet feet = new Feet();
feet.WashFeet();
}
if( _animalType == AnimalType.Horse )
{
//namespace is horsefeet
HorseFeet.Feet feet = new Feet();
feet.WashFeet();
}
```
This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically?
|
The namespace isn't the problem - it's simply that the 2 classes aren't related, so there's no inheritance chain that you can use for polymorphism.
You'll need to look at something like [duck typing](http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx), or an [adapter pattern](http://en.wikipedia.org/wiki/Adapter_pattern), or building your own proxy classes to get yourself to a common interface. For small numbers of implementations, I've gotten away with just building a single adapter class that delegates to whatever non-null instance it has:
```
interface IFeet {
void WashFeet();
}
class FeetAdapter : IFeet {
private PigFeet.Feet _pigFeet;
private HorseFeet.Feet _horseFeet;
private FeetAdapter(PigFeet.Feet pigFeet) {
_pigFeet = pigFeet;
}
private FeetAdapter(HorseFeet.Feet horseFeet) {
_horseFeet = horseFeet;
}
public void WashFeet() {
if (_pigFeet != null) {
_pigFeet.WashFeet();
} else {
_horseFeet.WashFeet();
}
}
public static FeetAdapter Create(AnimalType animalType) {
switch (animalType) {
case AnimalType.Pig:
return new FeetAdapter(new PigFeet.Feet());
case AnimalType.Horse:
return new FeetAdapter(new HorseFeet.Feet());
}
}
}
```
For larger cases, you'd be better off with a separate PigFeetAdapter and HorseFeetAdapter that both implement IFeet, along with a FeetAdapterFactory to create them - but the concept is the same as I show above.
|
172,365 |
<p>I've created a web page that lets you input some information and then draws an image in a canvas element based on that info. I have it pretty much working the way I want except for the printing.</p>
<p>Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it?</p>
<p>Update:</p>
<p>The answer was so simple. I was thinking of a lot more complicated solution. </p>
<p>I wish I could pick more than 1 answer. I wasn't able to get the canvas to print when I used * to disable display. The simplest solution was to just turn off the form that I was using for input, using form {display:none;} in the CSS inside an @media print{}. Thanks for the quick response.</p>
<pre><code>
@media print {
form {
display:none;
}
}
</code></pre>
|
[
{
"answer_id": 172376,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% sure of the support, but you can use CSS and put an attribute in the <code><link></code> tag for <code>media=\"print\"</code>. In this CSS file, just hide the elements you don't want to show while printing: <code>display:none;</code></p>\n"
},
{
"answer_id": 172377,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 4,
"selected": true,
"text": "<p>You could try something like this:</p>\n\n<pre><code>@media print {\n * {\n display:none;\n }\n\n #SOME-CANVAS-ID {\n display:block;\n }\n}\n</code></pre>\n\n<p>I'm not sure if a canvas is block by default, but you could try something along the lines of that and see if it works. The idea is that it will hide everything (*) for print media, except for some other arbitrary element as long as the rule's precedence is higher (which is why I used the ID selector).</p>\n\n<p>Edit: If CSS3 (specifically the <a href=\"http://www.w3.org/TR/css3-selectors/#negation\" rel=\"nofollow noreferrer\">negation pseudo-class</a>) had more support, your rule could be as simple as this:</p>\n\n<pre><code>*:not(canvas) {\n display:none;\n}\n</code></pre>\n\n<p>However, this may cause the <html> and <body> tags to be hidden, effectively hiding your canvas as well...</p>\n"
},
{
"answer_id": 13531805,
"author": "Dedan",
"author_id": 1768420,
"author_profile": "https://Stackoverflow.com/users/1768420",
"pm_score": 0,
"selected": false,
"text": "<p>You can try to create a canvas just for printing:</p>\n\n<pre><code>this.Print = function () {\n var printCanvas = $('#printCanvas');\n printCanvas.attr(\"width\", mainCanvas.width);\n printCanvas.attr(\"height\", mainCanvas.height);\n var printCanvasContext = printCanvas.get(0).getContext('2d');\n window.print();\n}\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791/"
] |
I've created a web page that lets you input some information and then draws an image in a canvas element based on that info. I have it pretty much working the way I want except for the printing.
Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it?
Update:
The answer was so simple. I was thinking of a lot more complicated solution.
I wish I could pick more than 1 answer. I wasn't able to get the canvas to print when I used \* to disable display. The simplest solution was to just turn off the form that I was using for input, using form {display:none;} in the CSS inside an @media print{}. Thanks for the quick response.
```
@media print {
form {
display:none;
}
}
```
|
You could try something like this:
```
@media print {
* {
display:none;
}
#SOME-CANVAS-ID {
display:block;
}
}
```
I'm not sure if a canvas is block by default, but you could try something along the lines of that and see if it works. The idea is that it will hide everything (\*) for print media, except for some other arbitrary element as long as the rule's precedence is higher (which is why I used the ID selector).
Edit: If CSS3 (specifically the [negation pseudo-class](http://www.w3.org/TR/css3-selectors/#negation)) had more support, your rule could be as simple as this:
```
*:not(canvas) {
display:none;
}
```
However, this may cause the <html> and <body> tags to be hidden, effectively hiding your canvas as well...
|
172,372 |
<p>I am wondering about what the difference between logging and tracing is.</p>
<p>Is the difference basically that tracing is more detailed log giving developers a tool to debug applications at runtime?</p>
<p>I have been experimenting with log4net and doing logging. Now I am wondering if I should be doing tracing as well and if I could/should use log4net for that purpose.
Should I be doing tracing with log4net and is there some trace level for log4net loggers? Should I use a different log level for debug and trace purposes or is it ok to use the same?
Can you give a simple example on how I would do logging and tracing for a simple method?</p>
<p>Edit:
Despite a few helpful answers below I am still unsure how I should be doing tracing versus logging. </p>
<p>I have the following method in my Business layer and I want to add logging/tracing to it. I am wondering how to do it efficiently. Is the following method acceptable in terms of logging/tracing? Should the log messages be of type Info instead of Debug? Are the Debug messages I am logging considered trace? How would you change it?</p>
<pre>
<code>
IEnumerable<Car> GetCars()
{
try
{
logger.Debug("Getting cars");
IEnumerable<Car> cars = CarAccessor.GetCars().ConvertAll(DataAccessToBusinessConverter);
logger.Debug("Got total of " + cars.Count + " cars");
} catch (Exception e) {
logger.Error("Error when getting cars", e);
throw new Exception("Unexpected error when getting cars");
}
}
</code>
</pre>
|
[
{
"answer_id": 172375,
"author": "Karl",
"author_id": 17613,
"author_profile": "https://Stackoverflow.com/users/17613",
"pm_score": 0,
"selected": false,
"text": "<p>logging != debugging</p>\n\n<p>Sometimes keeping log files is necessary to solve issues with the client, they prove what happened on the server side.</p>\n"
},
{
"answer_id": 172399,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say yes. Logging is the only way to determine what happened in the past - if a customer calls and says something didn't happen as expected, without a log all you can do is shrug and try and reproduce the error. Sometimes that is impossible (depending on the complexity of the software and the reliance on customer data).</p>\n\n<p>There is also the question of logging for auditing, a log file can be written containing information on what the user is doing - so you can use that to narrow down the possibilities to debug a problem, or even to verify the user's claims (if you get a report that the system is broken, xyz didn't happen, you can look in the logs to find out the operator failed to start the process, or didn't click the right option to make it work)</p>\n\n<p>Then there's logging for reporting, which is what most people think logging is for.</p>\n\n<p>If you can tailor the log output then put everything in logs and reduce or increase the amount of data that gets written. If you can change the output level dynamically then that's perfect.</p>\n\n<p>You can use any means of writing logs, subject to performance issues. I find appending to a text file is the best, most portable, easiest to view, and (very importantly) easiest to retrieve when you need it.</p>\n"
},
{
"answer_id": 172488,
"author": "Bob Nadler",
"author_id": 2514,
"author_profile": "https://Stackoverflow.com/users/2514",
"pm_score": 4,
"selected": false,
"text": "<p>log4net is well suited for both. We differentiate between logging that's useful for post-release diagnostics and \"tracing\" for development purposes by using the DEBUG logging level. Specifically, developers log their tracing output (things that are only of interest during development) using <code>Debug()</code>. Our development configuration sets the Level to DEBUG:</p>\n\n<pre><code><root>\n <level value=\"DEBUG\" />\n ...\n</root>\n</code></pre>\n\n<p>Before the product is released, the level is changed to \"INFO\":</p>\n\n<pre><code><level value=\"INFO\" />\n</code></pre>\n\n<p>This removes all DEBUG output from the release logging but keeps INFO/WARN/ERROR.</p>\n\n<p>There are other log4net tools, like filters, hierarchical (by namespace) logging, multiple targets, etc., by we've found the above simple method quite effective.</p>\n"
},
{
"answer_id": 172503,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 4,
"selected": false,
"text": "<p>IMO...<br><br>Logging should <strong>not</strong> be designed for development debugging (but it inevitably gets used that way)<br>\nLogging should be designed for <em>operational</em> monitoring and trouble-shooting -- this is its raison d’être.<br><br>\nTracing should be designed for development debugging & performance tuning. If available in the field, it can be use for really low-level operational trouble-shooting, but that is not its main purpose<br><br>Given this, the most successful approaches I've seen (and designed/implemented) in the past do <em>not</em> combine the two together. Better to keep the two tools separate, each doing one job as well as possible.</p>\n"
},
{
"answer_id": 172525,
"author": "martin",
"author_id": 8421,
"author_profile": "https://Stackoverflow.com/users/8421",
"pm_score": 5,
"selected": false,
"text": "<p>Logging is the generic term for recording information - tracing is the specific form of logging used to debug.</p>\n\n<p>In .NET the System.Diagnostics.Trace and System.Diagnostics.Debug objects allow simple logging to a number of \"event listeners\" that you can configure in app.config. You can also use TraceSwitches to configure and filter (between errors and info levels, for instance).</p>\n\n<pre><code>private void TestMethod(string x)\n{\n if(x.Length> 10)\n {\n Trace.Write(\"String was \" + x.Length);\n throw new ArgumentException(\"String too long\");\n }\n}\n</code></pre>\n\n<p>In ASP.NET, there is a special version of Trace (System.Web.TraceContext) will writes to the bottom of the ASP page or Trace.axd.\nIn ASP.NET 2+, there is also a fuller logging framework called Health Monitoring.</p>\n\n<p>Log4Net is a richer and more flexible way of tracing or logging than the in-built Trace, or even ASP Health Monitoring. Like Diagnostics.Trace you configure event listeners (\"appenders\") in config. For simple tracing, the use is simple like the inbuilt Trace. The decision to use Log4Net is whether you have more complicated requirements.</p>\n\n<pre><code>private void TestMethod(string x)\n{\n Log.Info(\"String length is \" + x.Length);\n if(x.Length> 10)\n {\n Log.Error(\"String was \" + x.Length);\n throw new ArgumentException(\"String too long\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 173303,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 0,
"selected": false,
"text": "<p>Also, consider what information is logged or traced. This is especially true for senstive information.</p>\n\n<p>For example, while it may be generally OK to log an error stating </p>\n\n<p>\"User 'X' attempted to access but was rejected because of a wrong password\", </p>\n\n<p>it is not OK to log an error stating </p>\n\n<p>\"User 'X' attempted to access but was rejected because the password 'secret' is not correct.\"</p>\n\n<p>It <em>might</em> be acceptable to write such senstive information to a trace file (and warn the customer/user about that fact by \"some means\" before you ask him to enable trace for extended troubleshooting in production). However for logging, I always have it as a policy that such senstive information is <strong>never</strong> to be written (i.e. levels INFO and above in log4net speak).</p>\n\n<p>This must be enforced and checked by code reviews, of course.</p>\n"
},
{
"answer_id": 3298458,
"author": "Alois Kraus",
"author_id": 397838,
"author_profile": "https://Stackoverflow.com/users/397838",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://geekswithblogs.net/akraus1/archive/2009/06/21/132968.aspx\" rel=\"noreferrer\">Logging is not Tracing</a>. These two should be different libraries with different performance characteristics. In fact I have written one <a href=\"http://geekswithblogs.net/akraus1/archive/2010/07/04/140761.aspx\" rel=\"noreferrer\">tracing library</a> by myself with the unique property that it can trace automatically the exception when the method with tracing enabled is left with an exception. Besides this it is possible to resolve <a href=\"http://geekswithblogs.net/akraus1/archive/2010/07/19/141000.aspx\" rel=\"noreferrer\">in an elegant way</a> the problem to trigger exceptions in specific places in your code.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] |
I am wondering about what the difference between logging and tracing is.
Is the difference basically that tracing is more detailed log giving developers a tool to debug applications at runtime?
I have been experimenting with log4net and doing logging. Now I am wondering if I should be doing tracing as well and if I could/should use log4net for that purpose.
Should I be doing tracing with log4net and is there some trace level for log4net loggers? Should I use a different log level for debug and trace purposes or is it ok to use the same?
Can you give a simple example on how I would do logging and tracing for a simple method?
Edit:
Despite a few helpful answers below I am still unsure how I should be doing tracing versus logging.
I have the following method in my Business layer and I want to add logging/tracing to it. I am wondering how to do it efficiently. Is the following method acceptable in terms of logging/tracing? Should the log messages be of type Info instead of Debug? Are the Debug messages I am logging considered trace? How would you change it?
```
IEnumerable<Car> GetCars()
{
try
{
logger.Debug("Getting cars");
IEnumerable<Car> cars = CarAccessor.GetCars().ConvertAll(DataAccessToBusinessConverter);
logger.Debug("Got total of " + cars.Count + " cars");
} catch (Exception e) {
logger.Error("Error when getting cars", e);
throw new Exception("Unexpected error when getting cars");
}
}
```
|
Logging is the generic term for recording information - tracing is the specific form of logging used to debug.
In .NET the System.Diagnostics.Trace and System.Diagnostics.Debug objects allow simple logging to a number of "event listeners" that you can configure in app.config. You can also use TraceSwitches to configure and filter (between errors and info levels, for instance).
```
private void TestMethod(string x)
{
if(x.Length> 10)
{
Trace.Write("String was " + x.Length);
throw new ArgumentException("String too long");
}
}
```
In ASP.NET, there is a special version of Trace (System.Web.TraceContext) will writes to the bottom of the ASP page or Trace.axd.
In ASP.NET 2+, there is also a fuller logging framework called Health Monitoring.
Log4Net is a richer and more flexible way of tracing or logging than the in-built Trace, or even ASP Health Monitoring. Like Diagnostics.Trace you configure event listeners ("appenders") in config. For simple tracing, the use is simple like the inbuilt Trace. The decision to use Log4Net is whether you have more complicated requirements.
```
private void TestMethod(string x)
{
Log.Info("String length is " + x.Length);
if(x.Length> 10)
{
Log.Error("String was " + x.Length);
throw new ArgumentException("String too long");
}
}
```
|
172,393 |
<p>I have a method that takes an IQueryable. Is there a LINQ query that will give me back the size of each column in the IQueryable?</p>
<p>To be more clear: this is Linq-to-objects. I want to get the length of the ToString() of each "column".</p>
|
[
{
"answer_id": 172413,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": true,
"text": "<p>It depends. If you mean is there a completely generic way to make this determination the answer is no. All IQueryable will give access to is the Type of each expression. There is no way to arbitrarily map a Type to a column size. </p>\n\n<p>If on the other hand you have the ability to map a Type to members and member type to a column size then yes there is a way to get the size.</p>\n\n<pre><code>\npublic IEnumerable GetColumnSize(IQueryable source)\n{\n var types = MapTypeToMembers(source).Select(x => x.Type);\n return types.Select(x => MapTypeToSize(x));\n}\n</code></pre>\n"
},
{
"answer_id": 172463,
"author": "Ihar Bury",
"author_id": 18001,
"author_profile": "https://Stackoverflow.com/users/18001",
"pm_score": 1,
"selected": false,
"text": "<p>I guess you're talking about LINQ-to-SQL. It completely ignores column sizes. varchar(15), char(20) and nvarchar(max) are just strings for it. The overflow error will appear only on the SQL Server side.</p>\n"
},
{
"answer_id": 180723,
"author": "Lucas",
"author_id": 24231,
"author_profile": "https://Stackoverflow.com/users/24231",
"pm_score": 0,
"selected": false,
"text": "<p>You said for each \"column\", that would map to each property. In Linq to Objects, this should work, although too manual:</p>\n\n<pre><code>var lengths = from o in myObjectCollection\n select new \n {\n PropertyLength1 = o.Property1.ToString().Length,\n PropertyLength2 = o.Property2.ToString().Length,\n ...\n }\n</code></pre>\n\n<p>If you meant the ToString() length of each item (\"row\") in the collection, then:</p>\n\n<pre><code>var lengths = from o in myObjectCollection\n select o.ToString().Length;\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189/"
] |
I have a method that takes an IQueryable. Is there a LINQ query that will give me back the size of each column in the IQueryable?
To be more clear: this is Linq-to-objects. I want to get the length of the ToString() of each "column".
|
It depends. If you mean is there a completely generic way to make this determination the answer is no. All IQueryable will give access to is the Type of each expression. There is no way to arbitrarily map a Type to a column size.
If on the other hand you have the ability to map a Type to members and member type to a column size then yes there is a way to get the size.
```
public IEnumerable GetColumnSize(IQueryable source)
{
var types = MapTypeToMembers(source).Select(x => x.Type);
return types.Select(x => MapTypeToSize(x));
}
```
|
172,397 |
<p>I am trying to use the <a href="http://www.javac.info/" rel="nofollow noreferrer">BGGA closures prototype</a> with an existing JDK 6 (standard on Mac OS X Leopard). The sample code I'm compiling is from a BGGA tutorial:</p>
<pre><code>public static void main(String[] args) {
// function with no arguments; return value is always 42
int answer = { => 42 }.invoke();
System.out.println(answer);
}
</code></pre>
<p>I have tried the following, and none work:</p>
<ol>
<li>Copied closures.jar to /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/lib</li>
<li>Ran javac with -Xbootclasspath/a:/path/to/closures.jar</li>
<li>Ran javac with -J-Xbootclasspath/a:/path/to/closures.jar</li>
<li>Tried from eclipse ganymede by defining my own system library and attaching it to my project with code utilizing BGGA.</li>
</ol>
<p>In all four cases, I get compilation errors, indicating that the compiler did not pick up closures.jar on the bootstrap classpath. I'd really like to get this working from eclipse, or at the very least maven. Thanks!</p>
|
[
{
"answer_id": 172418,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried javac with -J-Xbootclasspath instead? That's used for passing -X arguments to the VM itself, which may be necessary for a change as low-level as this.</p>\n\n<p>I very much doubt this will work with Eclipse, though. System libraries are for APIs, not language changes. You'd need to patch the Eclipse compiler.</p>\n"
},
{
"answer_id": 172527,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": true,
"text": "<p>The TAR file distribution includes a modified javac.bat with a complete command line, including \"-source 7\", which is probably what you are missing here.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8217/"
] |
I am trying to use the [BGGA closures prototype](http://www.javac.info/) with an existing JDK 6 (standard on Mac OS X Leopard). The sample code I'm compiling is from a BGGA tutorial:
```
public static void main(String[] args) {
// function with no arguments; return value is always 42
int answer = { => 42 }.invoke();
System.out.println(answer);
}
```
I have tried the following, and none work:
1. Copied closures.jar to /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/lib
2. Ran javac with -Xbootclasspath/a:/path/to/closures.jar
3. Ran javac with -J-Xbootclasspath/a:/path/to/closures.jar
4. Tried from eclipse ganymede by defining my own system library and attaching it to my project with code utilizing BGGA.
In all four cases, I get compilation errors, indicating that the compiler did not pick up closures.jar on the bootstrap classpath. I'd really like to get this working from eclipse, or at the very least maven. Thanks!
|
The TAR file distribution includes a modified javac.bat with a complete command line, including "-source 7", which is probably what you are missing here.
|
172,439 |
<p>I have a multi-line string that I want to do an operation on each line, like so:</p>
<pre><code>inputString = """Line 1
Line 2
Line 3"""
</code></pre>
<p>I want to iterate on each line:</p>
<pre><code>for line in inputString:
doStuff()
</code></pre>
|
[
{
"answer_id": 172454,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 10,
"selected": true,
"text": "<pre class=\"lang-py prettyprint-override\"><code>inputString.splitlines()\n</code></pre>\n\n<p>Will give you a list with each item, the <a href=\"https://docs.python.org/3/library/stdtypes.html#str.splitlines\" rel=\"noreferrer\"><code>splitlines()</code></a> method is designed to split each line into a list element.</p>\n"
},
{
"answer_id": 172468,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 8,
"selected": false,
"text": "<p>Like the others said:</p>\n\n<pre><code>inputString.split('\\n') # --> ['Line 1', 'Line 2', 'Line 3']\n</code></pre>\n\n<p>This is identical to the above, but the string module's functions are deprecated and should be avoided:</p>\n\n<pre><code>import string\nstring.split(inputString, '\\n') # --> ['Line 1', 'Line 2', 'Line 3']\n</code></pre>\n\n<p>Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the <code>splitlines</code> method with a <code>True</code> argument:</p>\n\n<pre><code>inputString.splitlines(True) # --> ['Line 1\\n', 'Line 2\\n', 'Line 3']\n</code></pre>\n"
},
{
"answer_id": 16752366,
"author": "iruvar",
"author_id": 753731,
"author_profile": "https://Stackoverflow.com/users/753731",
"pm_score": 4,
"selected": false,
"text": "<p>Might be overkill in this particular case but another option involves using <code>StringIO</code> to create a file-like object</p>\n\n<pre><code>for line in StringIO.StringIO(inputString):\n doStuff()\n</code></pre>\n"
},
{
"answer_id": 22233816,
"author": "loopbackbee",
"author_id": 1595865,
"author_profile": "https://Stackoverflow.com/users/1595865",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Use <code>inputString.splitlines()</code></strong>.</p>\n<hr />\n<h2>Why <code>splitlines</code> is better</h2>\n<p><code>splitlines</code> handles newlines properly, unlike <code>split</code>.</p>\n<p>It also can optionally return the newline character in the split result when called with a <code>True</code> argument, which is useful in some specific scenarios.</p>\n<hr />\n<h2>Why you should NOT use <code>split("\\n")</code></h2>\n<p>Using <code>split</code> creates very confusing bugs when sharing files across operating systems.</p>\n<p><code>\\n</code> in Python represents a Unix line-break (ASCII decimal code 10), independently of the OS where you run it. However, <a href=\"https://en.wikipedia.org/wiki/Newline#Representations\" rel=\"nofollow noreferrer\">the ASCII linebreak representation is OS-dependent</a>.</p>\n<p>On Windows, <code>\\n</code> is two characters, <code>CR</code> and <code>LF</code> (ASCII decimal codes 13 and 10, <code>\\r</code> and <code>\\n</code>), while on modern Unix (Mac OS X, Linux, Android), it's the single character <code>LF</code>.</p>\n<p><code>print</code> works correctly even if you have a string with line endings that don't match your platform:</p>\n<pre><code>>>> print " a \\n b \\r\\n c "\n a \n b \n c\n</code></pre>\n<p>However, explicitly splitting on "\\n", has OS-dependent behaviour:</p>\n<pre><code>>>> " a \\n b \\r\\n c ".split("\\n")\n[' a ', ' b \\r', ' c ']\n</code></pre>\n<p>Even if you use <code>os.linesep</code>, it will only split according to the newline separator on your platform, and will fail if you're processing text created in other platforms, or with a bare <code>\\n</code>:</p>\n<pre><code>>>> " a \\n b \\r\\n c ".split(os.linesep)\n[' a \\n b ', ' c ']\n</code></pre>\n<p><code>splitlines</code> solves all these problems:</p>\n<pre><code>>>> " a \\n b \\r\\n c ".splitlines()\n[' a ', ' b ', ' c ']\n</code></pre>\n<hr />\n<p><a href=\"https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"nofollow noreferrer\">Reading files in text mode</a> partially mitigates the newline representation problem, as it converts Python's <code>\\n</code> into the platform's newline representation.</p>\n<p>However, text mode only exists on Windows. On Unix systems, all files are opened in binary mode, so using <code>split('\\n')</code> in a UNIX system with a Windows file will lead to undesired behavior. This can also happen when transferring files in the network.</p>\n"
},
{
"answer_id": 30873284,
"author": "Mike S",
"author_id": 3768749,
"author_profile": "https://Stackoverflow.com/users/3768749",
"pm_score": 0,
"selected": false,
"text": "<p>I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are <strong>not the same</strong>, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):</p>\n\n<pre><code>try:\n import cStringIO\n StringIO = cStringIO\nexcept ImportError:\n import StringIO\n\nfor line in StringIO.StringIO(variable_with_multiline_string):\n pass\nprint line.strip()\n</code></pre>\n"
},
{
"answer_id": 52282723,
"author": "Finrod Felagund",
"author_id": 7423100,
"author_profile": "https://Stackoverflow.com/users/7423100",
"pm_score": 1,
"selected": false,
"text": "<p>The original post requested for code which prints some rows (if they are true for some condition) plus the following row. \nMy implementation would be this:</p>\n\n<pre><code>text = \"\"\"1 sfasdf\nasdfasdf\n2 sfasdf\nasdfgadfg\n1 asfasdf\nsdfasdgf\n\"\"\"\n\ntext = text.splitlines()\nrows_to_print = {}\n\nfor line in range(len(text)):\n if text[line][0] == '1':\n rows_to_print = rows_to_print | {line, line + 1}\n\nrows_to_print = sorted(list(rows_to_print))\n\nfor i in rows_to_print:\n print(text[i])\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1546/"
] |
I have a multi-line string that I want to do an operation on each line, like so:
```
inputString = """Line 1
Line 2
Line 3"""
```
I want to iterate on each line:
```
for line in inputString:
doStuff()
```
|
```py
inputString.splitlines()
```
Will give you a list with each item, the [`splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) method is designed to split each line into a list element.
|
172,465 |
<pre><code>y: &pause
cd ptls5.0 &pause
sdp describe Integration.dpk &pause
z: &pause
cd ptls5.0 &pause
dir &pause
</code></pre>
<p>I have those commands in the 1.cmd file. First three are executed fine. The result of it is that after "sdp describe Integration.dpk &pause" is executed I'm given "press any key to continue..." after I hit any key. The command prompt quits. Instead of changing drive to z:>. What is wrong with it?</p>
|
[
{
"answer_id": 172471,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>Is \"sdp\" another batch file itself? If so, you will need to use <code>call</code>:</p>\n\n<pre><code>call sdp describe Integration.dpk &pause\n</code></pre>\n"
},
{
"answer_id": 172481,
"author": "SqlACID",
"author_id": 19797,
"author_profile": "https://Stackoverflow.com/users/19797",
"pm_score": 2,
"selected": false,
"text": "<p>If sdp is a .cmd or .bat file, change it to \"call sdp.....\"</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
y: &pause
cd ptls5.0 &pause
sdp describe Integration.dpk &pause
z: &pause
cd ptls5.0 &pause
dir &pause
```
I have those commands in the 1.cmd file. First three are executed fine. The result of it is that after "sdp describe Integration.dpk &pause" is executed I'm given "press any key to continue..." after I hit any key. The command prompt quits. Instead of changing drive to z:>. What is wrong with it?
|
If sdp is a .cmd or .bat file, change it to "call sdp....."
|
172,484 |
<p>I recently added <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1" rel="nofollow noreferrer">-pedantic</a> and <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-errors-1" rel="nofollow noreferrer">-pedantic-errors</a> to my make GCC compile options to help clean up my cross-platform code. All was fine until it found errors in external-included header files. Is there a way to turn off this error checking in external header files, i.e.:</p>
<p>Keep checking for files included like this:</p>
<pre><code>#include "myheader.h"
</code></pre>
<p>Stop checking for include files like this:</p>
<pre><code>#include <externalheader.h>
</code></pre>
<p>Here are the errors I am getting:</p>
<pre class="lang-none prettyprint-override"><code>g++ -Wall -Wextra -Wno-long-long -Wno-unused-parameter -pedantic --pedantic-errors
-O3 -D_FILE_OFFSET_BITS=64 -DMINGW -I"freetype/include" -I"jpeg" -I"lpng128" -I"zlib"
-I"mysql/include" -I"ffmpeg/libswscale" -I"ffmpeg/libavformat" -I"ffmpeg/libavcodec"
-I"ffmpeg/libavutil" -o omingwd/kguimovie.o -c kguimovie.cpp
In file included from ffmpeg/libavutil/avutil.h:41,
from ffmpeg/libavcodec/avcodec.h:30,
from kguimovie.cpp:44:
ffmpeg/libavutil/mathematics.h:32: error: comma at end of enumerator list
In file included from ffmpeg/libavcodec/avcodec.h:30,
from kguimovie.cpp:44:
ffmpeg/libavutil/avutil.h:110: error: comma at end of enumerator list
In file included from kguimovie.cpp:44:
ffmpeg/libavcodec/avcodec.h:277: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:303: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:334: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:345: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:2249: warning: `ImgReSampleContext' is deprecated
(declared at ffmpeg/libavcodec/avcodec.h:2243)
ffmpeg/libavcodec/avcodec.h:2259: warning: `ImgReSampleContext' is deprecated
(declared at ffmpeg/libavcodec/avcodec.h:2243)
In file included from kguimovie.cpp:45:
ffmpeg/libavformat/avformat.h:262: error: comma at end of enumerator list
In file included from ffmpeg/libavformat/rtsp.h:26,
from ffmpeg/libavformat/avformat.h:465,
from kguimovie.cpp:45:
ffmpeg/libavformat/rtspcodes.h:38: error: comma at end of enumerator list
In file included from ffmpeg/libavformat/avformat.h:465,
from kguimovie.cpp:45:
ffmpeg/libavformat/rtsp.h:32: error: comma at end of enumerator list
ffmpeg/libavformat/rtsp.h:69: error: comma at end of enumerator list
</code></pre>
|
[
{
"answer_id": 172515,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 0,
"selected": false,
"text": "<p>One idea that comes to my mind (I don't know if there's an 'out of the box' parameter for this):</p>\n<p>Prepare a script that will take your compiler's output, and remove all the lines that contain headers that aren't in a specific list (<em>your</em> headers).</p>\n<p>It shouldn't be that hard doing it this way.</p>\n"
},
{
"answer_id": 172529,
"author": "Nik Reiman",
"author_id": 14302,
"author_profile": "https://Stackoverflow.com/users/14302",
"pm_score": 5,
"selected": false,
"text": "<p>Using the <em><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wsystem-headers\" rel=\"nofollow noreferrer\">-Wsystem-headers</a></em> option, GCC will print warning messages associated with system headers, which are normally suppressed. However, you're looking to have GCC basically treat these files as system headers, so you might try passing "-isystem /usr/local/ffmpeg" (or wherever you installed that package) to get GCC to ignore errors from files included in these directories as well.</p>\n"
},
{
"answer_id": 172536,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": true,
"text": "<p>You could fix the headers and submit a patch to <a href=\"https://en.wikipedia.org/wiki/FFmpeg\" rel=\"nofollow noreferrer\">FFmpeg</a>; compatibility with <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\"><code>-pedantic</code></a> is a worthy goal, so I'm sure they'd consider it, especially if it just involved removing trailing commas and suchlike.</p>\n"
},
{
"answer_id": 761156,
"author": "Good Person",
"author_id": 87280,
"author_profile": "https://Stackoverflow.com/users/87280",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of a way to tell GCC to stop emitting those warnings. However, you could hackishly remove third-party warnings with something like <code>llvm-gcc</code> (or just gcc) <code>-pedantic 2>&1|grep -v "/usr/"</code>.</p>\n"
},
{
"answer_id": 761202,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": -1,
"selected": false,
"text": "<p>You can't tell GCC to be pedantic about some headers and not others at this time. You might suggest it as a feature, although I suspect it'll be resisted as ideally everyone would be pedantic.</p>\n<p>What you can do is fix the headers yourself, generate a patch, and then apply that patch to later versions of the headers if you upgrade the library.</p>\n<p>Submit the patch to FFmpeg as well in the hopes that they'll adopt it, but either way you're covered even if they don't accept it.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
I recently added [-pedantic](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1) and [-pedantic-errors](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-errors-1) to my make GCC compile options to help clean up my cross-platform code. All was fine until it found errors in external-included header files. Is there a way to turn off this error checking in external header files, i.e.:
Keep checking for files included like this:
```
#include "myheader.h"
```
Stop checking for include files like this:
```
#include <externalheader.h>
```
Here are the errors I am getting:
```none
g++ -Wall -Wextra -Wno-long-long -Wno-unused-parameter -pedantic --pedantic-errors
-O3 -D_FILE_OFFSET_BITS=64 -DMINGW -I"freetype/include" -I"jpeg" -I"lpng128" -I"zlib"
-I"mysql/include" -I"ffmpeg/libswscale" -I"ffmpeg/libavformat" -I"ffmpeg/libavcodec"
-I"ffmpeg/libavutil" -o omingwd/kguimovie.o -c kguimovie.cpp
In file included from ffmpeg/libavutil/avutil.h:41,
from ffmpeg/libavcodec/avcodec.h:30,
from kguimovie.cpp:44:
ffmpeg/libavutil/mathematics.h:32: error: comma at end of enumerator list
In file included from ffmpeg/libavcodec/avcodec.h:30,
from kguimovie.cpp:44:
ffmpeg/libavutil/avutil.h:110: error: comma at end of enumerator list
In file included from kguimovie.cpp:44:
ffmpeg/libavcodec/avcodec.h:277: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:303: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:334: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:345: error: comma at end of enumerator list
ffmpeg/libavcodec/avcodec.h:2249: warning: `ImgReSampleContext' is deprecated
(declared at ffmpeg/libavcodec/avcodec.h:2243)
ffmpeg/libavcodec/avcodec.h:2259: warning: `ImgReSampleContext' is deprecated
(declared at ffmpeg/libavcodec/avcodec.h:2243)
In file included from kguimovie.cpp:45:
ffmpeg/libavformat/avformat.h:262: error: comma at end of enumerator list
In file included from ffmpeg/libavformat/rtsp.h:26,
from ffmpeg/libavformat/avformat.h:465,
from kguimovie.cpp:45:
ffmpeg/libavformat/rtspcodes.h:38: error: comma at end of enumerator list
In file included from ffmpeg/libavformat/avformat.h:465,
from kguimovie.cpp:45:
ffmpeg/libavformat/rtsp.h:32: error: comma at end of enumerator list
ffmpeg/libavformat/rtsp.h:69: error: comma at end of enumerator list
```
|
You could fix the headers and submit a patch to [FFmpeg](https://en.wikipedia.org/wiki/FFmpeg); compatibility with [`-pedantic`](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1) is a worthy goal, so I'm sure they'd consider it, especially if it just involved removing trailing commas and suchlike.
|
172,524 |
<p>Last time <a href="https://stackoverflow.com/questions/169506/get-form-input-fields-with-jquery">I asked about the reverse process</a>, and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.</p>
|
[
{
"answer_id": 172532,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 4,
"selected": false,
"text": "<p>If your form elements have their ID set to the fieldname:</p>\n\n<pre><code>$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });\n</code></pre>\n"
},
{
"answer_id": 172579,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 3,
"selected": false,
"text": "<p>Or similar to the previous suggestion using the field names instead of ids:</p>\n\n<pre><code>$.each(data, function(name,value) {\n $(\"input[name='\" + name + \"']\").val(value);\n});\n</code></pre>\n"
},
{
"answer_id": 173162,
"author": "J5.",
"author_id": 25380,
"author_profile": "https://Stackoverflow.com/users/25380",
"pm_score": 4,
"selected": true,
"text": "<p>When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of:</p>\n\n<pre><code>\njQuery.each(data, function (name,value) {\n jQuery(\"input[name='\"+name+\"'],select[name='\"+name+\"']\").each(function() {\n switch (this.nodeName.toLowerCase()) {\n case \"input\":\n switch (this.type) {\n case \"radio\":\n case \"checkbox\":\n if (this.value==value) { jQuery(this).click(); }\n break;\n default:\n jQuery(this).val(value);\n break;\n }\n break;\n case \"select\":\n jQuery(\"option\",this).each(function(){\n if (this.value==value) { this.selected=true; }\n });\n break;\n }\n });\n});\n</code></pre>\n\n<p>I haven't tested this code so I hope there are no silly syntax errors that I should have caught. Hope this helps.</p>\n\n<p>I am not allowed to comment on the comments here (yet), so ....\nAs noted in the comment, the jQuery .val(val) method handles setting radio buttons,checkboxes and selects.</p>\n\n<p>You will still need to put select[name=...] into your jQuery selector pattern or the select elements won't be updated.</p>\n"
},
{
"answer_id": 1835300,
"author": "Brian Franklin",
"author_id": 223186,
"author_profile": "https://Stackoverflow.com/users/223186",
"pm_score": 1,
"selected": false,
"text": "<p>I have not seen jQuery handle passing a single (non-array) value into val() for a radio or checkbox input. You have to be sure to wrap the single value into an array.</p>\n\n<p>I have also typically not wanted to alter the values of button-ish inputs, so I filter those out.</p>\n\n<p>Here's a function that handles the array wrapping, button filtering, and also restricts the input selection to a given form element. The form parameter is optional. If left off/null/undefined, then all inputs on the page will be selected.</p>\n\n<pre><code>function populateForm(data, form) {\n $.each( data, function(name, value) {\n var input = $(\":input[name='\" + name + \"']:not(:button,:reset,:submit,:image)\", form );\n input.val( ( !$.isArray( value ) && ( input.is(':checkbox') || input.is(':radio') ) ) ? [ value ] : value );\n } );\n};\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
Last time [I asked about the reverse process](https://stackoverflow.com/questions/169506/get-form-input-fields-with-jquery), and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.
|
When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of:
```
jQuery.each(data, function (name,value) {
jQuery("input[name='"+name+"'],select[name='"+name+"']").each(function() {
switch (this.nodeName.toLowerCase()) {
case "input":
switch (this.type) {
case "radio":
case "checkbox":
if (this.value==value) { jQuery(this).click(); }
break;
default:
jQuery(this).val(value);
break;
}
break;
case "select":
jQuery("option",this).each(function(){
if (this.value==value) { this.selected=true; }
});
break;
}
});
});
```
I haven't tested this code so I hope there are no silly syntax errors that I should have caught. Hope this helps.
I am not allowed to comment on the comments here (yet), so ....
As noted in the comment, the jQuery .val(val) method handles setting radio buttons,checkboxes and selects.
You will still need to put select[name=...] into your jQuery selector pattern or the select elements won't be updated.
|
172,544 |
<p>I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.</p>
<p>How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?</p>
<pre><code>try
{
if (cbSubFolders.Checked == false)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string fileName in files)
ProcessFile(fileName);
}
else
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string fileName in files)
ProcessFile(fileName);
}
lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}
</code></pre>
|
[
{
"answer_id": 172575,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "<p>You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):</p>\n\n<pre><code>using System;\nusing System.IO;\nstatic class Program\n{\n static void Main()\n {\n string path = \"\"; // TODO\n ApplyAllFiles(path, ProcessFile);\n }\n static void ProcessFile(string path) {/* ... */}\n static void ApplyAllFiles(string folder, Action<string> fileAction)\n {\n foreach (string file in Directory.GetFiles(folder))\n {\n fileAction(file);\n }\n foreach (string subDir in Directory.GetDirectories(folder))\n {\n try\n {\n ApplyAllFiles(subDir, fileAction);\n }\n catch\n {\n // swallow, log, whatever\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 172612,
"author": "user25306",
"author_id": 25306,
"author_profile": "https://Stackoverflow.com/users/25306",
"pm_score": 1,
"selected": false,
"text": "<p>This should answer the question. I've ignored the issue of going through subdirectories, I'm assuming you have that figured out. </p>\n\n<p>Of course, you don't need to have a seperate method for this, but you might find it a useful place to also verify the path is valid, and deal with the other exceptions that you could encounter when calling GetFiles().</p>\n\n<p>Hope this helps.</p>\n\n<pre><code>private string[] GetFiles(string path)\n{\n string[] files = null;\n try\n {\n files = Directory.GetFiles(path);\n }\n catch (UnauthorizedAccessException)\n {\n // might be nice to log this, or something ...\n }\n\n return files;\n}\n\nprivate void Processor(string path, bool recursive)\n{\n // leaving the recursive directory navigation out.\n string[] files = this.GetFiles(path);\n if (null != files)\n {\n foreach (string file in files)\n {\n this.Process(file);\n }\n }\n else\n {\n // again, might want to do something when you can't access the path?\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10738882,
"author": "Malcolm",
"author_id": 89584,
"author_profile": "https://Stackoverflow.com/users/89584",
"pm_score": 2,
"selected": false,
"text": "<p>see <a href=\"https://stackoverflow.com/a/10728792/89584\">https://stackoverflow.com/a/10728792/89584</a> for a solution that handles the UnauthorisedAccessException problem.</p>\n\n<p>All the solutions above will miss files and/or directories if any calls to GetFiles() or GetDirectories() are on folders with a mix of permissions.</p>\n"
},
{
"answer_id": 24440132,
"author": "Ben Gripka",
"author_id": 530658,
"author_profile": "https://Stackoverflow.com/users/530658",
"pm_score": 4,
"selected": false,
"text": "<p>This simple function works well and meets the questions requirements.</p>\n<pre><code>private List<string> GetFiles(string path, string pattern)\n{\n var files = new List<string>();\n var directories = new string[] { };\n\n try\n {\n files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));\n directories = Directory.GetDirectories(path);\n }\n catch (UnauthorizedAccessException) { }\n\n foreach (var directory in directories)\n try\n {\n files.AddRange(GetFiles(directory, pattern));\n }\n catch (UnauthorizedAccessException) { }\n\n return files;\n}\n</code></pre>\n"
},
{
"answer_id": 38959208,
"author": "Shubham",
"author_id": 6310707,
"author_profile": "https://Stackoverflow.com/users/6310707",
"pm_score": 3,
"selected": false,
"text": "<p>A simple way to do this is by using a List for files and a Queue for directories.\nIt conserves memory.\nIf you use a recursive program to do the same task, that could throw OutOfMemory exception.\nThe output: files added in the List, are organised according to the top to bottom (breadth first) directory tree.</p>\n\n<pre><code>public static List<string> GetAllFilesFromFolder(string root, bool searchSubfolders) {\n Queue<string> folders = new Queue<string>();\n List<string> files = new List<string>();\n folders.Enqueue(root);\n while (folders.Count != 0) {\n string currentFolder = folders.Dequeue();\n try {\n string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, \"*.*\", System.IO.SearchOption.TopDirectoryOnly);\n files.AddRange(filesInCurrent);\n }\n catch {\n // Do Nothing\n }\n try {\n if (searchSubfolders) {\n string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, \"*.*\", System.IO.SearchOption.TopDirectoryOnly);\n foreach (string _current in foldersInCurrent) {\n folders.Enqueue(_current);\n }\n }\n }\n catch {\n // Do Nothing\n }\n }\n return files;\n}\n</code></pre>\n\n<h1>Steps:</h1>\n\n<ol>\n<li>Enqueue the root in the queue</li>\n<li>In a loop, Dequeue it, Add the files in that directory to the list, and Add the subfolders to the queue.</li>\n<li>Repeat untill the queue is empty.</li>\n</ol>\n"
},
{
"answer_id": 49850530,
"author": "user541686",
"author_id": 541686,
"author_profile": "https://Stackoverflow.com/users/541686",
"pm_score": 2,
"selected": false,
"text": "<h3>Here's a full-featured, .NET 2.0-compatible implementation.</h3>\n<p>You can even alter the yielded <code>List</code> of files to skip over directories in the <code>FileSystemInfo</code> version!</p>\n<p>(Beware <code>null</code> values!)</p>\n<pre><code>public static IEnumerable<KeyValuePair<string, string[]>> GetFileSystemInfosRecursive(string dir, bool depth_first)\n{\n foreach (var item in GetFileSystemObjectsRecursive(new DirectoryInfo(dir), depth_first))\n {\n string[] result;\n var children = item.Value;\n if (children != null)\n {\n result = new string[children.Count];\n for (int i = 0; i < result.Length; i++)\n { result[i] = children[i].Name; }\n }\n else { result = null; }\n string fullname;\n try { fullname = item.Key.FullName; }\n catch (IOException) { fullname = null; }\n catch (UnauthorizedAccessException) { fullname = null; }\n yield return new KeyValuePair<string, string[]>(fullname, result);\n }\n}\n\npublic static IEnumerable<KeyValuePair<DirectoryInfo, List<FileSystemInfo>>> GetFileSystemInfosRecursive(DirectoryInfo dir, bool depth_first)\n{\n var stack = depth_first ? new Stack<DirectoryInfo>() : null;\n var queue = depth_first ? null : new Queue<DirectoryInfo>();\n if (depth_first) { stack.Push(dir); }\n else { queue.Enqueue(dir); }\n for (var list = new List<FileSystemInfo>(); (depth_first ? stack.Count : queue.Count) > 0; list.Clear())\n {\n dir = depth_first ? stack.Pop() : queue.Dequeue();\n FileSystemInfo[] children;\n try { children = dir.GetFileSystemInfos(); }\n catch (UnauthorizedAccessException) { children = null; }\n catch (IOException) { children = null; }\n if (children != null) { list.AddRange(children); }\n yield return new KeyValuePair<DirectoryInfo, List<FileSystemInfo>>(dir, children != null ? list : null);\n if (depth_first) { list.Reverse(); }\n foreach (var child in list)\n {\n var asdir = child as DirectoryInfo;\n if (asdir != null)\n {\n if (depth_first) { stack.Push(asdir); }\n else { queue.Enqueue(asdir); }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61868218,
"author": "Shahin Dohan",
"author_id": 1469494,
"author_profile": "https://Stackoverflow.com/users/1469494",
"pm_score": 4,
"selected": false,
"text": "<p>Since .NET Standard 2.1 (.NET Core 3+, .NET 5+), you can now just do:</p>\n<pre><code>var filePaths = Directory.EnumerateFiles(@"C:\\my\\files", "*.xml", new EnumerationOptions\n{\n IgnoreInaccessible = true,\n RecurseSubdirectories = true\n});\n</code></pre>\n<p>According to the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.enumerationoptions?view=netstandard-2.1\" rel=\"nofollow noreferrer\">MSDN docs</a> about <strong>IgnoreInaccessible</strong>:</p>\n<blockquote>\n<p>Gets or sets a value that indicates whether to skip files or directories when access is denied (for example, UnauthorizedAccessException or SecurityException). The default is true.</p>\n</blockquote>\n<p>Default value is actually true, but I've kept it here just to show the property.</p>\n<p>The same overload is available for <code>DirectoryInfo</code> as well.</p>\n"
},
{
"answer_id": 63242543,
"author": "Ciccio Pasticcio",
"author_id": 4375410,
"author_profile": "https://Stackoverflow.com/users/4375410",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer using c# framework functions, but the function i need will be included in .net framework 5.0, so i have to write it.</p>\n<pre><code>// search file in every subdirectory ignoring access errors\n static List<string> list_files(string path)\n {\n List<string> files = new List<string>();\n\n // add the files in the current directory\n try\n {\n string[] entries = Directory.GetFiles(path);\n\n foreach (string entry in entries)\n files.Add(System.IO.Path.Combine(path,entry));\n }\n catch \n { \n // an exception in directory.getfiles is not recoverable: the directory is not accessible\n }\n\n // follow the subdirectories\n try\n {\n string[] entries = Directory.GetDirectories(path);\n\n foreach (string entry in entries)\n {\n string current_path = System.IO.Path.Combine(path, entry);\n List<string> files_in_subdir = list_files(current_path);\n\n foreach (string current_file in files_in_subdir)\n files.Add(current_file);\n }\n }\n catch\n {\n // an exception in directory.getdirectories is not recoverable: the directory is not accessible\n }\n\n return files;\n }\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2493/"
] |
I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.
How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?
```
try
{
if (cbSubFolders.Checked == false)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string fileName in files)
ProcessFile(fileName);
}
else
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string fileName in files)
ProcessFile(fileName);
}
lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}
```
|
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
```
using System;
using System.IO;
static class Program
{
static void Main()
{
string path = ""; // TODO
ApplyAllFiles(path, ProcessFile);
}
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
}
```
|
172,552 |
<p>I wrote a short bash script to complete a task that involves creating a temporary directory and storing various files in it and performing various operations on it.</p>
<p>In my first pass I just created the temp dir at /tmp/$$.$script", but then I tested the script on a computer where I didn't have write access to /tmp/, and I'd like to take that case into account. So my question is where's a good secondary location for this temp dir? Should I just use the current directory? The home directory? ~/tmp/? The output location of the script?</p>
<p>All created files do get cleaned up on script exit.</p>
|
[
{
"answer_id": 172555,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>You could try <code>/var/tmp</code>, although it's likely that <code>/tmp</code> is a symlink to that (or vice-versa).</p>\n"
},
{
"answer_id": 172556,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Many systems also have a <code>/var/tmp</code>. If the sysadmin doesn't want you writing in to <code>/tmp</code>, presumably they have provided some alternative… is the <code>$TMPDIR</code> environment variable set? For example, on my Mac:</p>\n\n<pre><code>$ echo $TMPDIR\n/var/folders/jf/jfu4pjGtGGGkUuuq8HL7UE+++TI/-Tmp-/\n</code></pre>\n"
},
{
"answer_id": 172586,
"author": "rnicholson",
"author_id": 14075,
"author_profile": "https://Stackoverflow.com/users/14075",
"pm_score": 3,
"selected": false,
"text": "<p>I would suggest ~/.[your script name]/tmp, if TMPDIR is not set, instead of ~/tmp/ since the user may have created that on their own (and you may not want to accidentally override things in there).</p>\n\n<p>Just as an off the cuff thought in bash --</p>\n\n<pre><code>case $TMPDIR in '') tmp_dir=\".${0}/tmp\";; *) tmp_dir=$TMPDIR;; esac\n</code></pre>\n"
},
{
"answer_id": 172607,
"author": "Evan Krall",
"author_id": 25327,
"author_profile": "https://Stackoverflow.com/users/25327",
"pm_score": 2,
"selected": false,
"text": "<p>Use ${TMPDIR:-/tmp} ($TMPDIR or /tmp if $TMPDIR is not set). If that's not writable, then exit with an error saying so, or ask the user for input defining it. I think asking the user where temp files should go is preferable to assuming somewhere and leaving them there if your process gets killed.</p>\n"
},
{
"answer_id": 172660,
"author": "Nick",
"author_id": 4949,
"author_profile": "https://Stackoverflow.com/users/4949",
"pm_score": 2,
"selected": false,
"text": "<p>You could try using <a href=\"http://unixhelp.ed.ac.uk/CGI/man-cgi?mktemp\" rel=\"nofollow noreferrer\">mktemp</a> (assuming it's configured correctly for the system)</p>\n\n<p>e.g. \n<code>\nMYTMPDIR=$(mktemp -d)\n</code></p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
I wrote a short bash script to complete a task that involves creating a temporary directory and storing various files in it and performing various operations on it.
In my first pass I just created the temp dir at /tmp/$$.$script", but then I tested the script on a computer where I didn't have write access to /tmp/, and I'd like to take that case into account. So my question is where's a good secondary location for this temp dir? Should I just use the current directory? The home directory? ~/tmp/? The output location of the script?
All created files do get cleaned up on script exit.
|
Many systems also have a `/var/tmp`. If the sysadmin doesn't want you writing in to `/tmp`, presumably they have provided some alternative… is the `$TMPDIR` environment variable set? For example, on my Mac:
```
$ echo $TMPDIR
/var/folders/jf/jfu4pjGtGGGkUuuq8HL7UE+++TI/-Tmp-/
```
|
172,559 |
<pre><code>function returnsAnArray ()
{
return array ('test');
}
echo returnsAnArray ()[0];
</code></pre>
<p>generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?</p>
|
[
{
"answer_id": 172570,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 1,
"selected": false,
"text": "<p>This will work if there is only one member in the array:</p>\n\n<pre><code> <?php\n echo current(returnsAnArray());\n ?>\n</code></pre>\n"
},
{
"answer_id": 172578,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 0,
"selected": false,
"text": "<p>You could do this for an indexed array of unknown length.</p>\n\n<pre>foreach ( returnsAnArray() as $item )\n echo $item;\n</pre>\n"
},
{
"answer_id": 172582,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": true,
"text": "<p>Here's one way, using the <a href=\"http://www.php.net/list\" rel=\"nofollow noreferrer\">list</a> language construct</p>\n\n<pre><code>function returnsAnArray ()\n{\n return array ('test');\n}\n\nlist($foo)=returnsAnArray();\n</code></pre>\n\n<p>You could grab a sequence of elements from an offset by combining this with <a href=\"http://www.php.net/array_slice\" rel=\"nofollow noreferrer\">array_slice</a></p>\n\n<pre><code>list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);\n</code></pre>\n"
},
{
"answer_id": 172590,
"author": "Markus",
"author_id": 18597,
"author_profile": "https://Stackoverflow.com/users/18597",
"pm_score": -1,
"selected": false,
"text": "<p>I ask myself why one would like to avoid creating a temporary variable for a returned array. Why don't you just return one value instead of an whole array? Maybe you'll have to overthink your program logic.</p>\n\n<p>Or is it a performance/memory issue? Consider using <a href=\"http://de2.php.net/manual/en/language.references.php\" rel=\"nofollow noreferrer\">references</a> instead of always creating a new array object and returning it.</p>\n"
},
{
"answer_id": 172591,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>Define a new function for returning a specific index from an array.</p>\n\n<pre><code>function arr_index($arr, $i) { return $arr[$i]; }\n</code></pre>\n\n<p>You might want to add some error and type checking there.</p>\n\n<p>And then use it like this:</p>\n\n<pre><code>echo arr_index(returnsAnArray(), 0);\n</code></pre>\n\n<p>Happy Coding :)</p>\n"
},
{
"answer_id": 172694,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>Another option:</p>\n\n<pre><code><?php\necho reset(functionThatReturnsAnArray());\n?>\n</code></pre>\n\n<p>Similar thread: <a href=\"https://stackoverflow.com/questions/68711/php-can-i-reference-a-single-member-of-an-array-that-is-returned-by-a-function\">PHP: Can I reference a single member of an array that is returned by a function?</a></p>\n"
},
{
"answer_id": 1675509,
"author": "user202817",
"author_id": 202817,
"author_profile": "https://Stackoverflow.com/users/202817",
"pm_score": 1,
"selected": false,
"text": "<p>For regular numerically indexed arrays, where func() returns such an array and $n is the index you want:</p>\n\n<p><code>array_pop(array_slice(func(),$n,1));</code></p>\n\n<p>For associative arrays (e.g. strings or other things as keys), or numeric arrays that aren't numbered and complete from 0..n, it's a little more convoluted. Where $key is the key you want:</p>\n\n<p><code>array_pop(array_intersect_keys(func(),Array($key => \"\"));</code></p>\n\n<p>This would also work for the first case.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24288/"
] |
```
function returnsAnArray ()
{
return array ('test');
}
echo returnsAnArray ()[0];
```
generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?
|
Here's one way, using the [list](http://www.php.net/list) language construct
```
function returnsAnArray ()
{
return array ('test');
}
list($foo)=returnsAnArray();
```
You could grab a sequence of elements from an offset by combining this with [array\_slice](http://www.php.net/array_slice)
```
list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);
```
|
172,573 |
<p>I've been using <a href="http://www.jcraft.com/jsch/" rel="nofollow noreferrer">JSch</a> for a couple of weeks now. It seems to <em>work</em> okay, but its API is a little bit cumbersome. I'm also a little off put by its total lack of documentation (not even javadoc style comments). Has anyone used a good Java SSH2 library that they'd recommend. I'm particularly interested in SCP file transfer and issuing commands to a remote Linux box programmatically via the SSH protocol.</p>
|
[
{
"answer_id": 172570,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 1,
"selected": false,
"text": "<p>This will work if there is only one member in the array:</p>\n\n<pre><code> <?php\n echo current(returnsAnArray());\n ?>\n</code></pre>\n"
},
{
"answer_id": 172578,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 0,
"selected": false,
"text": "<p>You could do this for an indexed array of unknown length.</p>\n\n<pre>foreach ( returnsAnArray() as $item )\n echo $item;\n</pre>\n"
},
{
"answer_id": 172582,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": true,
"text": "<p>Here's one way, using the <a href=\"http://www.php.net/list\" rel=\"nofollow noreferrer\">list</a> language construct</p>\n\n<pre><code>function returnsAnArray ()\n{\n return array ('test');\n}\n\nlist($foo)=returnsAnArray();\n</code></pre>\n\n<p>You could grab a sequence of elements from an offset by combining this with <a href=\"http://www.php.net/array_slice\" rel=\"nofollow noreferrer\">array_slice</a></p>\n\n<pre><code>list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);\n</code></pre>\n"
},
{
"answer_id": 172590,
"author": "Markus",
"author_id": 18597,
"author_profile": "https://Stackoverflow.com/users/18597",
"pm_score": -1,
"selected": false,
"text": "<p>I ask myself why one would like to avoid creating a temporary variable for a returned array. Why don't you just return one value instead of an whole array? Maybe you'll have to overthink your program logic.</p>\n\n<p>Or is it a performance/memory issue? Consider using <a href=\"http://de2.php.net/manual/en/language.references.php\" rel=\"nofollow noreferrer\">references</a> instead of always creating a new array object and returning it.</p>\n"
},
{
"answer_id": 172591,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>Define a new function for returning a specific index from an array.</p>\n\n<pre><code>function arr_index($arr, $i) { return $arr[$i]; }\n</code></pre>\n\n<p>You might want to add some error and type checking there.</p>\n\n<p>And then use it like this:</p>\n\n<pre><code>echo arr_index(returnsAnArray(), 0);\n</code></pre>\n\n<p>Happy Coding :)</p>\n"
},
{
"answer_id": 172694,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>Another option:</p>\n\n<pre><code><?php\necho reset(functionThatReturnsAnArray());\n?>\n</code></pre>\n\n<p>Similar thread: <a href=\"https://stackoverflow.com/questions/68711/php-can-i-reference-a-single-member-of-an-array-that-is-returned-by-a-function\">PHP: Can I reference a single member of an array that is returned by a function?</a></p>\n"
},
{
"answer_id": 1675509,
"author": "user202817",
"author_id": 202817,
"author_profile": "https://Stackoverflow.com/users/202817",
"pm_score": 1,
"selected": false,
"text": "<p>For regular numerically indexed arrays, where func() returns such an array and $n is the index you want:</p>\n\n<p><code>array_pop(array_slice(func(),$n,1));</code></p>\n\n<p>For associative arrays (e.g. strings or other things as keys), or numeric arrays that aren't numbered and complete from 0..n, it's a little more convoluted. Where $key is the key you want:</p>\n\n<p><code>array_pop(array_intersect_keys(func(),Array($key => \"\"));</code></p>\n\n<p>This would also work for the first case.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
I've been using [JSch](http://www.jcraft.com/jsch/) for a couple of weeks now. It seems to *work* okay, but its API is a little bit cumbersome. I'm also a little off put by its total lack of documentation (not even javadoc style comments). Has anyone used a good Java SSH2 library that they'd recommend. I'm particularly interested in SCP file transfer and issuing commands to a remote Linux box programmatically via the SSH protocol.
|
Here's one way, using the [list](http://www.php.net/list) language construct
```
function returnsAnArray ()
{
return array ('test');
}
list($foo)=returnsAnArray();
```
You could grab a sequence of elements from an offset by combining this with [array\_slice](http://www.php.net/array_slice)
```
list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);
```
|
172,598 |
<p>I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.</p>
<p>I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C. </p>
<p>Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them?</p>
<hr/>
<p>As for my findings so far.</p>
<p>It is possible to use <a href="http://www.otierney.net/objective-c.html#categories" rel="noreferrer">categories</a> [e.g. MyClass (Private)] defined in MyClass.m file to group private methods.</p>
<p>This approach has 2 issues:</p>
<ol>
<li>Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block</li>
<li>You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo".</li>
</ol>
<p>The first issue can be worked around with <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_5.html#//apple_ref/doc/uid/TP30001163-CH20-SW2" rel="noreferrer">empty category</a> [e.g. MyClass ()].<br/>
The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.</p>
|
[
{
"answer_id": 172738,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 5,
"selected": false,
"text": "<p>While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.</p>\n"
},
{
"answer_id": 173287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>There isn't really a \"private method\" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the <code>@interface</code> at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so <code>@interface GLObject (PrivateMethods)</code> can be found in <code>GLObject+PrivateMethods.h</code>. The reason for providing the header file is so that you can import it in your unit test classes :-).</p>\n\n<p>By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:</p>\n\n<pre><code>@implementation GLObject(PrivateMethods)\n- (void)secretFeature;\n@end\n</code></pre>\n\n<p>or with a class extension (the thing you call an \"empty category\"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the \"private\" methods at the end of the file.</p>\n\n<p>Even with class extensions I will often create a separate header (<code>GLObject+Extension.h</code>) so that I can use those methods if required, mimicking \"friend\" or \"protected\" visibility.</p>\n\n<p>Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your \"private\" methods completely, and whether they're above or below the calling site they'll be found by the compiler.</p>\n"
},
{
"answer_id": 651623,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 1,
"selected": false,
"text": "<p>There's no way of getting around issue #2. That's just the way the C compiler (and hence the Objective-C compiler) work. If you use the XCode editor, the function popup should make it easy to navigate the <code>@interface</code> and <code>@implementation</code> blocks in the file.</p>\n"
},
{
"answer_id": 651692,
"author": "dreamlax",
"author_id": 10320,
"author_profile": "https://Stackoverflow.com/users/10320",
"pm_score": 4,
"selected": false,
"text": "<p>You could try defining a static function below or above your implementation that takes a pointer to your instance. It will be able to access any of your instances variables.</p>\n\n<pre><code>//.h file\n@interface MyClass : Object\n{\n int test;\n}\n- (void) someMethod: anArg;\n\n@end\n\n\n//.m file \n@implementation MyClass\n\nstatic void somePrivateMethod (MyClass *myClass, id anArg)\n{\n fprintf (stderr, \"MyClass (%d) was passed %p\", myClass->test, anArg);\n}\n\n\n- (void) someMethod: (id) anArg\n{\n somePrivateMethod (self, anArg);\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 651852,
"author": "Alex",
"author_id": 35999,
"author_profile": "https://Stackoverflow.com/users/35999",
"pm_score": 9,
"selected": false,
"text": "<p>There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. <code>@interface MyClass ()</code>) called <em>Class Extension</em>. What's unique about a class extension is that the method implementations must go in the same <code>@implementation MyClass</code> as the public methods. So I structure my classes like this:</p>\n\n<p>In the .h file:</p>\n\n<pre><code>@interface MyClass {\n // My Instance Variables\n}\n\n- (void)myPublicMethod;\n\n@end\n</code></pre>\n\n<p>And in the .m file:</p>\n\n<pre><code>@interface MyClass()\n\n- (void)myPrivateMethod;\n\n@end\n\n@implementation MyClass\n\n- (void)myPublicMethod {\n // Implementation goes here\n}\n\n- (void)myPrivateMethod {\n // Implementation goes here\n}\n\n@end\n</code></pre>\n\n<p>I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.</p>\n"
},
{
"answer_id": 3401583,
"author": "rebelzach",
"author_id": 363522,
"author_profile": "https://Stackoverflow.com/users/363522",
"pm_score": 2,
"selected": false,
"text": "<p>If you wanted to avoid the <code>@interface</code> block at the top you could always put the private declarations in another file <code>MyClassPrivate.h</code> not ideal but its not cluttering up the implementation.</p>\n\n<p>MyClass.h</p>\n\n<pre><code>interface MyClass : NSObject {\n @private\n BOOL publicIvar_;\n BOOL privateIvar_;\n}\n\n@property (nonatomic, assign) BOOL publicIvar;\n//any other public methods. etc\n@end\n</code></pre>\n\n<p>MyClassPrivate.h</p>\n\n<pre><code>@interface MyClass ()\n\n@property (nonatomic, assign) BOOL privateIvar;\n//any other private methods etc.\n@end\n</code></pre>\n\n<p>MyClass.m</p>\n\n<pre><code>#import \"MyClass.h\"\n#import \"MyClassPrivate.h\"\n@implementation MyClass\n\n@synthesize privateIvar = privateIvar_;\n@synthesize publicIvar = publicIvar_;\n\n@end\n</code></pre>\n"
},
{
"answer_id": 4227000,
"author": "Zack Sheppard",
"author_id": 513736,
"author_profile": "https://Stackoverflow.com/users/513736",
"pm_score": 2,
"selected": false,
"text": "<p>every objects in Objective C conform to NSObject protocol, which holds onto the <strong>performSelector:</strong> method. I was also previously looking for a way to create some \"helper or private\" methods that I did not need exposed on a public level. If you want to create a private method with no overhead and not having to define it in your header file then give this a shot...</p>\n\n<p>define the your method with a similar signature as the code below...</p>\n\n<pre><code>-(void)myHelperMethod: (id) sender{\n // code here...\n}\n</code></pre>\n\n<p>then when you need to reference the method simply call it as a selector...</p>\n\n<pre><code>[self performSelector:@selector(myHelperMethod:)];\n</code></pre>\n\n<p>this line of code will invoke the method you created and not have an annoying warning about not having it defined in the header file.</p>\n"
},
{
"answer_id": 6978992,
"author": "Sneg",
"author_id": 838444,
"author_profile": "https://Stackoverflow.com/users/838444",
"pm_score": 1,
"selected": false,
"text": "<p>There is a benefit of private methods absence. You can move the logic that you intended to hide to the separate class and use it as delegate. In this case you can mark delegate object as private and it will not be visible from outside. Moving logic to the separate class (maybe several) makes better design of your project. Cause your classes become simpler and your methods are grouped in classes with proper names.</p>\n"
},
{
"answer_id": 11068947,
"author": "FellowMD",
"author_id": 379163,
"author_profile": "https://Stackoverflow.com/users/379163",
"pm_score": 2,
"selected": false,
"text": "<p>You could use blocks?</p>\n\n<pre><code>@implementation MyClass\n\nid (^createTheObject)() = ^(){ return [[NSObject alloc] init];};\n\nNSInteger (^addEm)(NSInteger, NSInteger) =\n^(NSInteger a, NSInteger b)\n{\n return a + b;\n};\n\n//public methods, etc.\n\n- (NSObject) thePublicOne\n{\n return createTheObject();\n}\n\n@end\n</code></pre>\n\n<p>I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.</p>\n"
},
{
"answer_id": 14867152,
"author": "Rich Schonthal",
"author_id": 2023738,
"author_profile": "https://Stackoverflow.com/users/2023738",
"pm_score": 2,
"selected": false,
"text": "<p>One more thing that I haven't seen mentioned here - Xcode supports .h files with \"_private\" in the name. Let's say you have a class MyClass - you have MyClass.m and MyClass.h and now you can also have MyClass_private.h. Xcode will recognize this and include it in the list of \"Counterparts\" in the Assistant Editor.</p>\n\n<pre><code>//MyClass.m\n#import \"MyClass.h\"\n#import \"MyClass_private.h\"\n</code></pre>\n"
},
{
"answer_id": 16758022,
"author": "justin",
"author_id": 191596,
"author_profile": "https://Stackoverflow.com/users/191596",
"pm_score": 5,
"selected": false,
"text": "<p>Defining your private methods in the <code>@implementation</code> block is ideal for most purposes. Clang will see these within the <code>@implementation</code>, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category.</p>\n\n<p>In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the <code>@implementation</code>).</p>\n\n<p><code>static</code> functions are very good for particularly sensitive or speed critical private methods.</p>\n\n<p>A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe).</p>\n\n<p>Named categories (e.g. <code>@interface MONObject (PrivateStuff)</code>) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it:</p>\n\n<pre><code>@implementation MONObject (PrivateStuff)\n...HERE...\n@end\n</code></pre>\n\n<p>Here's a little annotated cheat sheet:</p>\n\n<p>MONObject.h</p>\n\n<pre><code>@interface MONObject : NSObject\n\n// public declaration required for clients' visibility/use.\n@property (nonatomic, assign, readwrite) bool publicBool;\n\n// public declaration required for clients' visibility/use.\n- (void)publicMethod;\n\n@end\n</code></pre>\n\n<p>MONObject.m</p>\n\n<pre><code>@interface MONObject ()\n@property (nonatomic, assign, readwrite) bool privateBool;\n\n// you can use a convention where the class name prefix is reserved\n// for private methods this can reduce accidental overriding:\n- (void)MONObject_privateMethod;\n\n@end\n\n// The potentially good thing about functions is that they are truly\n// inaccessible; They may not be overridden, accidentally used,\n// looked up via the objc runtime, and will often be eliminated from\n// backtraces. Unlike methods, they can also be inlined. If unused\n// (e.g. diagnostic omitted in release) or every use is inlined,\n// they may be removed from the binary:\nstatic void PrivateMethod(MONObject * pObject) {\n pObject.privateBool = true;\n}\n\n@implementation MONObject\n{\n bool anIvar;\n}\n\nstatic void AnotherPrivateMethod(MONObject * pObject) {\n if (0 == pObject) {\n assert(0 && \"invalid parameter\");\n return;\n }\n\n // if declared in the @implementation scope, you *could* access the\n // private ivars directly (although you should rarely do this):\n pObject->anIvar = true;\n}\n\n- (void)publicMethod\n{\n // declared below -- but clang can see its declaration in this\n // translation:\n [self privateMethod];\n}\n\n// no declaration required.\n- (void)privateMethod\n{\n}\n\n- (void)MONObject_privateMethod\n{\n}\n\n@end\n</code></pre>\n\n<p>Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods.</p>\n"
},
{
"answer_id": 52979295,
"author": "Milan",
"author_id": 1998518,
"author_profile": "https://Stackoverflow.com/users/1998518",
"pm_score": 0,
"selected": false,
"text": "<p>As other people said defining private methods in the <code>@implementation</code> block is OK for most purposes.</p>\n\n<p>On the topic of <strong>code organization</strong> - I like to keep them together under <code>pragma mark private</code> for easier navigation in Xcode</p>\n\n<pre><code>@implementation MyClass \n// .. public methods\n\n# pragma mark private \n// ...\n\n@end\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294/"
] |
I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.
I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C.
Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them?
---
As for my findings so far.
It is possible to use [categories](http://www.otierney.net/objective-c.html#categories) [e.g. MyClass (Private)] defined in MyClass.m file to group private methods.
This approach has 2 issues:
1. Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block
2. You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo".
The first issue can be worked around with [empty category](http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_5.html#//apple_ref/doc/uid/TP30001163-CH20-SW2) [e.g. MyClass ()].
The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.
|
There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. `@interface MyClass ()`) called *Class Extension*. What's unique about a class extension is that the method implementations must go in the same `@implementation MyClass` as the public methods. So I structure my classes like this:
In the .h file:
```
@interface MyClass {
// My Instance Variables
}
- (void)myPublicMethod;
@end
```
And in the .m file:
```
@interface MyClass()
- (void)myPrivateMethod;
@end
@implementation MyClass
- (void)myPublicMethod {
// Implementation goes here
}
- (void)myPrivateMethod {
// Implementation goes here
}
@end
```
I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.
|
172,600 |
<p>When I try this with a generic class where this.value is T:</p>
<pre><code>if (this.value.GetType() == typeof(int))
{
((int)this.value)++;
}
else
{
throw new InvalidOperationException
("T must be an int to perform this operation");
}
</code></pre>
<p>I get a compile-time error: "Cannot convert type 'T' to 'int'"</p>
<p>What should I do to perform an integral operation on this.value when it's an int?</p>
<p>Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T. </p>
|
[
{
"answer_id": 172639,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "<p>Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):</p>\n<pre><code>int i = (int)(object)this.value;\ni++;\nthis.value = (T)(object)i;\n</code></pre>\n<p>Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic, <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html\" rel=\"noreferrer\">here</a>. The Operator class is part of <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/\" rel=\"noreferrer\">MiscUtil</a>; at the simplest level, I suspect AddAlternative would work very well:</p>\n<pre><code>this.value = Operator.AddAlternative(this.value, 1);\n</code></pre>\n<p>This should infer the implicit <T,int> automatically, or you can add them yourself:</p>\n<pre><code>this.value = Operator.AddAlternative<T,int>(this.value, 1);\n</code></pre>\n<p><strong>Benefit</strong>: This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)".</p>\n<p>I think there is also a ChangeType hiding around somewhere in there...</p>\n<p>[edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless <em>really</em> necessary. That said (as per my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix<T> [for T in decimal/float/int/double/etc] is often highly valuable.</p>\n"
},
{
"answer_id": 172651,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 2,
"selected": false,
"text": "<p>Static typing of C# will not let you do so, but you can fool it with casting to object. I would not recommend doing this, it probably shows architectural problem, but anyway: </p>\n\n<pre><code>using System;\n\nclass Foo<T>\n{\n public T value;\n\n public void Increment()\n {\n if (value is int) value = (T)(object)(((int)(object)value)+1);\n }\n}\n\nstatic class Program\n{\n static void Main()\n {\n Foo<int> x = new Foo<int>();\n x.Increment();\n x.Increment();\n Console.WriteLine(x.value); \n } \n}\n</code></pre>\n"
},
{
"answer_id": 172657,
"author": "user25306",
"author_id": 25306,
"author_profile": "https://Stackoverflow.com/users/25306",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think I understand what you are after. If you are requiring that something be a specific type, then you probably shouldn't use Generics. You could, it just seems silly. This will do what you are asking, but I don't recommend it.</p>\n\n<pre><code>namespace GenericsOne\n{\n using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n Sample<int> one = new Sample<int>();\n one.AddFive(10);\n\n // yes, this will fail, it is to show why the approach is generally not a good one.\n Sample<DateTime> two = new Sample<DateTime>();\n two.AddFive(new DateTime());\n }\n}\n\n}\n\nnamespace GenericsOne\n{\n using System;\npublic class Sample<T>\n{\n public int AddFive(T number)\n {\n int junk = 0;\n\n try\n {\n junk = Convert.ToInt32(number);\n }\n catch (Exception)\n {\n Console.WriteLine(\"Nope\");\n }\n\n return junk + 5;\n }\n}\n}\n</code></pre>\n"
},
{
"answer_id": 172669,
"author": "Collin K",
"author_id": 1369,
"author_profile": "https://Stackoverflow.com/users/1369",
"pm_score": 4,
"selected": false,
"text": "<p>In my opinion, type-specific code in a generic class is a code smell. I would refactor it to get something like this:</p>\n\n<pre><code>public class MyClass<T>\n{\n ...\n}\n\npublic class IntClass : MyClass<int>\n{\n public void IncrementMe()\n {\n this.value++;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 181689,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>This is why I really want numeric or operation constraints <a href=\"https://stackoverflow.com/questions/138367#138628\">in C#4</a>.</p>\n\n<p>@Marc Gravell's answer is the best way round this (+1), but it is frustating how this is an issue for generics.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] |
When I try this with a generic class where this.value is T:
```
if (this.value.GetType() == typeof(int))
{
((int)this.value)++;
}
else
{
throw new InvalidOperationException
("T must be an int to perform this operation");
}
```
I get a compile-time error: "Cannot convert type 'T' to 'int'"
What should I do to perform an integral operation on this.value when it's an int?
Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T.
|
Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):
```
int i = (int)(object)this.value;
i++;
this.value = (T)(object)i;
```
Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic, [here](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html). The Operator class is part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/); at the simplest level, I suspect AddAlternative would work very well:
```
this.value = Operator.AddAlternative(this.value, 1);
```
This should infer the implicit <T,int> automatically, or you can add them yourself:
```
this.value = Operator.AddAlternative<T,int>(this.value, 1);
```
**Benefit**: This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)".
I think there is also a ChangeType hiding around somewhere in there...
[edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless *really* necessary. That said (as per my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix<T> [for T in decimal/float/int/double/etc] is often highly valuable.
|
172,658 |
<p>I'm attempting to use extension methods to add an operater overload to the C# <code>StringBuilder</code> class. Specifically, given <code>StringBuilder</code> <code>sb</code>, I'd like <code>sb += "text"</code> to become equivalent to <code>sb.Append("text")</code>.</p>
<p>Here's the syntax for creating an extension method for <code>StringBuilder</code>:</p>
<pre><code>public static class sbExtensions
{
public static StringBuilder blah(this StringBuilder sb)
{
return sb;
}
}
</code></pre>
<p>It successfully adds the <code>blah</code> extension method to the <code>StringBuilder</code>.</p>
<p>Unfortunately, operator overloading does not seem to work:</p>
<pre><code>public static class sbExtensions
{
public static StringBuilder operator +(this StringBuilder sb, string s)
{
return sb.Append(s);
}
}
</code></pre>
<p>Among other issues, the keyword <code>this</code> is not allowed in this context.</p>
<p>Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?</p>
|
[
{
"answer_id": 172666,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 8,
"selected": true,
"text": "<p>This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads. But the <a href=\"https://github.com/dotnet/csharplang/issues/192\" rel=\"noreferrer\">feature is being discussed for <em>some</em> future release of C#</a>. Mads talked a bit more about implementing it <a href=\"https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen#time=32m11s\" rel=\"noreferrer\">in this video from 2017</a>.</p>\n<p>On why it isn't currently implemented, Mads Torgersen, C# Language PM says:</p>\n<blockquote>\n<p>...for the Orcas release we decided to\ntake the cautious approach and add\nonly regular extension methods, as\nopposed to extention properties,\nevents, operators, static methods, etc\netc. Regular extension methods were\nwhat we needed for LINQ, and they had\na syntactically minimal design that\ncould not be easily mimicked for some\nof the other member kinds.</p>\n<p>We are becoming increasingly aware\nthat other kinds of extension members\ncould be useful, and so we will return\nto this issue after Orcas. No\nguarantees, though!</p>\n</blockquote>\n<p>Further below in the same article:</p>\n<blockquote>\n<p>I am sorry to report that we will not\nbe doing this in the next release. We\ndid take extension members very\nseriously in our plans, and spent a\nlot of effort trying to get them\nright, but in the end we couldn't get\nit smooth enough, and decided to give\nway to other interesting features.</p>\n<p>This is still on our radar for future\nreleases. What will help is if we get\na good amount of compelling scenarios\nthat can help drive the right design.</p>\n</blockquote>\n\n"
},
{
"answer_id": 172670,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 3,
"selected": false,
"text": "<p>It appears this isn't currently possible - there's an open feedback issue requesting this very feature on Microsoft Connect:</p>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=168224\" rel=\"noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=168224</a></p>\n\n<p>suggesting it might appear in a future release but isn't implemented for the current version.</p>\n"
},
{
"answer_id": 2194671,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 6,
"selected": false,
"text": "<p>If you control the places where you want to use this \"extension operator\" (which you normally do with extension methods anyway), you can do something like this:</p>\n\n<pre><code>class Program {\n\n static void Main(string[] args) {\n StringBuilder sb = new StringBuilder();\n ReceiveImportantMessage(sb);\n Console.WriteLine(sb.ToString());\n }\n\n // the important thing is to use StringBuilderWrapper!\n private static void ReceiveImportantMessage(StringBuilderWrapper sb) {\n sb += \"Hello World!\";\n }\n\n}\n\npublic class StringBuilderWrapper {\n\n public StringBuilderWrapper(StringBuilder sb) { StringBuilder = sb; }\n public StringBuilder StringBuilder { get; private set; }\n\n public static implicit operator StringBuilderWrapper(StringBuilder sb) {\n return new StringBuilderWrapper(sb);\n }\n\n public static StringBuilderWrapper operator +(StringBuilderWrapper sbw, string s) { \n sbw.StringBuilder.Append(s);\n return sbw;\n }\n\n} \n</code></pre>\n\n<p>The <code>StringBuilderWrapper</code> class declares an <a href=\"http://msdn.microsoft.com/en-us/library/85w54y0a.aspx\" rel=\"noreferrer\">implicit conversion operator</a> from a <code>StringBuilder</code> <em>and</em> declares the desired <code>+</code> operator. This way, a <code>StringBuilder</code> can be passed to <code>ReceiveImportantMessage</code>, which will be silently converted to a <code>StringBuilderWrapper</code>, where the <code>+</code> operator can be used.</p>\n\n<p>To make this fact more transparent to callers, you can declare <code>ReceiveImportantMessage</code> as taking a <code>StringBuilder</code> and just use code like this:</p>\n\n<pre><code> private static void ReceiveImportantMessage(StringBuilder sb) {\n StringBuilderWrapper sbw = sb;\n sbw += \"Hello World!\";\n }\n</code></pre>\n\n<p>Or, to use it inline where you're already using a <code>StringBuilder</code>, you can simply do this:</p>\n\n<pre><code> StringBuilder sb = new StringBuilder();\n StringBuilderWrapper sbw = sb;\n sbw += \"Hello World!\";\n Console.WriteLine(sb.ToString());\n</code></pre>\n\n<p>I created <a href=\"http://codecrafter.blogspot.com/2010/04/more-understandable-icomparable.html\" rel=\"noreferrer\">a post</a> about using a similar approach to make <code>IComparable</code> more understandable.</p>\n"
},
{
"answer_id": 10643692,
"author": "Chuck Rostance",
"author_id": 810915,
"author_profile": "https://Stackoverflow.com/users/810915",
"pm_score": 2,
"selected": false,
"text": "<p>Though it's not possible to do the operators, you could always just create Add (or Concat), Subtract, and Compare methods....</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text; \n\nnamespace Whatever.Test\n{\n public static class Extensions\n {\n public static int Compare(this MyObject t1, MyObject t2)\n {\n if(t1.SomeValueField < t2.SomeValueField )\n return -1;\n else if (t1.SomeValueField > t2.SomeValueField )\n {\n return 1;\n }\n else\n {\n return 0;\n }\n }\n\n public static MyObject Add(this MyObject t1, MyObject t2)\n {\n var newObject = new MyObject();\n //do something \n return newObject;\n\n }\n\n public static MyObject Subtract(this MyObject t1, MyObject t2)\n {\n var newObject= new MyObject();\n //do something\n return newObject; \n }\n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 24469649,
"author": "david van brink",
"author_id": 527531,
"author_profile": "https://Stackoverflow.com/users/527531",
"pm_score": 2,
"selected": false,
"text": "<p>Hah! I was looking up "extension operator overloading" with exactly the same desire, for <code>sb += (thing)</code>.</p>\n<p>After reading the answers here (and seeing that the answer is "no"), for my particular needs, I went with an extension method which combines <code>sb.AppendLine</code> and <code>sb.AppendFormat</code>, and looks tidier than either.</p>\n<pre><code>public static class SomeExtensions\n{\n public static void Line(this StringBuilder sb, string format, params object[] args)\n {\n string s = String.Format(format + "\\n", args);\n sb.Append(s);\n }\n}\n</code></pre>\n<p>And so,</p>\n<pre><code>sb.Line("the first thing is {0}", first);\nsb.Line("the second thing is {0}", second);\n</code></pre>\n<p>Not a general answer, but may be of interest to future seekers looking at this kind of thing.</p>\n"
},
{
"answer_id": 41904854,
"author": "will motil",
"author_id": 7481241,
"author_profile": "https://Stackoverflow.com/users/7481241",
"pm_score": 0,
"selected": false,
"text": "<p>Its possible to rigg it with a wrapper and extensions but impossible to do it properly. You end with garbage which totally defeats the purpose.\nI have a post up somewhere on here that does it, but its worthless.</p>\n\n<p>Btw \nAll numeric conversions create garbage in string builder that needs to be fixed. I had to write a wrapper for that which does work and i use it. That is worth perusing.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388/"
] |
I'm attempting to use extension methods to add an operater overload to the C# `StringBuilder` class. Specifically, given `StringBuilder` `sb`, I'd like `sb += "text"` to become equivalent to `sb.Append("text")`.
Here's the syntax for creating an extension method for `StringBuilder`:
```
public static class sbExtensions
{
public static StringBuilder blah(this StringBuilder sb)
{
return sb;
}
}
```
It successfully adds the `blah` extension method to the `StringBuilder`.
Unfortunately, operator overloading does not seem to work:
```
public static class sbExtensions
{
public static StringBuilder operator +(this StringBuilder sb, string s)
{
return sb.Append(s);
}
}
```
Among other issues, the keyword `this` is not allowed in this context.
Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?
|
This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads. But the [feature is being discussed for *some* future release of C#](https://github.com/dotnet/csharplang/issues/192). Mads talked a bit more about implementing it [in this video from 2017](https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen#time=32m11s).
On why it isn't currently implemented, Mads Torgersen, C# Language PM says:
>
> ...for the Orcas release we decided to
> take the cautious approach and add
> only regular extension methods, as
> opposed to extention properties,
> events, operators, static methods, etc
> etc. Regular extension methods were
> what we needed for LINQ, and they had
> a syntactically minimal design that
> could not be easily mimicked for some
> of the other member kinds.
>
>
> We are becoming increasingly aware
> that other kinds of extension members
> could be useful, and so we will return
> to this issue after Orcas. No
> guarantees, though!
>
>
>
Further below in the same article:
>
> I am sorry to report that we will not
> be doing this in the next release. We
> did take extension members very
> seriously in our plans, and spent a
> lot of effort trying to get them
> right, but in the end we couldn't get
> it smooth enough, and decided to give
> way to other interesting features.
>
>
> This is still on our radar for future
> releases. What will help is if we get
> a good amount of compelling scenarios
> that can help drive the right design.
>
>
>
|
172,691 |
<p>I'm trying to determine if the user is using 24 hour or 12 hour time, and there doesn't seem to be a good way to figure this out other than creating an NSDateFormatter and searching the format string for the period field ('a' character)</p>
<p>Here's what I'm doing now:</p>
<pre><code>NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSRange range = [[formatter dateFormat] rangeOfString:@"a"];
BOOL is24HourFormat = range.location == NSNotFound && range.length == 0;
[formatter release];
</code></pre>
<p>Which works, but feels kinda fragile. There has to be a better way, right?</p>
|
[
{
"answer_id": 172755,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 3,
"selected": true,
"text": "<p>This information is provided in NSUserDefaults. Maybe under the NSShortTimeDateFormatString key? (Still requires parsing of course).</p>\n\n<p>(Use</p>\n\n<pre><code>NSLog(@\"%@\", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);\n</code></pre>\n\n<p>to dump all the pre-defined user defaults).</p>\n\n<p>Not quite sure why you want to do this - I bet you have a good reason - but maybe it's best just to use the defaults in NSDateFormatter instead?</p>\n"
},
{
"answer_id": 173060,
"author": "Ken",
"author_id": 17320,
"author_profile": "https://Stackoverflow.com/users/17320",
"pm_score": 0,
"selected": false,
"text": "<p>NSShortTimeDateFormatString is deprecated, and I believe it also effectively doesn't work in 10.5 and later. See the 10.4 and 10.5 Foundation release notes. Dumping all defaults is a good way to depend on stuff that is not guaranteed by the interface, though it can be interesting to sort of see what's going on under the hood.</p>\n\n<p>Why do you need this? As schwa says, everything works much better if you can get away from needing to know anything about the localized presentation.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17188/"
] |
I'm trying to determine if the user is using 24 hour or 12 hour time, and there doesn't seem to be a good way to figure this out other than creating an NSDateFormatter and searching the format string for the period field ('a' character)
Here's what I'm doing now:
```
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSRange range = [[formatter dateFormat] rangeOfString:@"a"];
BOOL is24HourFormat = range.location == NSNotFound && range.length == 0;
[formatter release];
```
Which works, but feels kinda fragile. There has to be a better way, right?
|
This information is provided in NSUserDefaults. Maybe under the NSShortTimeDateFormatString key? (Still requires parsing of course).
(Use
```
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
```
to dump all the pre-defined user defaults).
Not quite sure why you want to do this - I bet you have a good reason - but maybe it's best just to use the defaults in NSDateFormatter instead?
|
172,720 |
<p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
|
[
{
"answer_id": 172726,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": false,
"text": "<p>First thing that comes to mind: <a href=\"http://psyco.sourceforge.net/\" rel=\"nofollow noreferrer\">psyco</a>. It runs only on x86, for the time being.</p>\n\n<p>Then, <a href=\"http://code.activestate.com/recipes/277940/\" rel=\"nofollow noreferrer\">constant binding</a>. That is, make all global references (and <em>global.attr</em>, <em>global.attr.attr</em>…) be local names inside of functions and methods. This isn't always successful, but in general it works. It can be done by hand, but obviously is tedious.</p>\n\n<p>You said apart from in-code optimization, so I won't delve into this, but keep your mind open for typical mistakes (<code>for i in range(10000000)</code> comes to mind) that people do.</p>\n"
},
{
"answer_id": 172734,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 2,
"selected": false,
"text": "<p>This won't necessarily speed up any of your code, but is critical knowledge when programming in Python if you want to avoid slowing your code down. The \"Global Interpreter Lock\" (GIL), has the potential to drastically reduce the speed of your multi-threaded program if its behavior is not understood (yes, this bit me ... I had a nice 4 processor machine that wouldn't use more than 1.2 processors at a time). There's an introductory article with some links to get you started at <a href=\"http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/\" rel=\"nofollow noreferrer\">SmoothSpan</a>.</p>\n"
},
{
"answer_id": 172737,
"author": "Vicent Marti",
"author_id": 4381,
"author_profile": "https://Stackoverflow.com/users/4381",
"pm_score": 2,
"selected": false,
"text": "<p>Run your app through the Python profiler.\nFind a serious bottleneck.\nRewrite that bottleneck in C.\nRepeat.</p>\n"
},
{
"answer_id": 172740,
"author": "hacama",
"author_id": 17457,
"author_profile": "https://Stackoverflow.com/users/17457",
"pm_score": 3,
"selected": false,
"text": "<p>Cython and pyrex can be used to generate c code using a python-like syntax. Psyco is also fantastic for appropriate projects (sometimes you'll not notice much speed boost, sometimes it'll be as much as 50x as fast).\nI still reckon the best way is to profile your code (cProfile, etc.) and then just code the bottlenecks as c functions for python.</p>\n"
},
{
"answer_id": 172744,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions.</p>\n\n<p>In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this:</p>\n\n<pre><code>result = u\"\"\nfor item in my_list:\n result += unicode (item)\n</code></pre>\n\n<p>will copy the <em>entire</em> string twice per iteration. This has been well-covered, and the solution is to use <code>\"\".join</code>:</p>\n\n<pre><code>result = \"\".join (unicode (item) for item in my_list)\n</code></pre>\n\n<p>Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list.</p>\n\n<p>Finally, <strong>don't be afraid to rewrite bits in C!</strong> Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module.</p>\n\n<p>My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.</p>\n"
},
{
"answer_id": 172766,
"author": "simon",
"author_id": 14143,
"author_profile": "https://Stackoverflow.com/users/14143",
"pm_score": 2,
"selected": false,
"text": "<p>People have given some good advice, but you have to be aware that when high performance is needed, the python model is: punt to c. Efforts like psyco may in the future help a bit, but python just isn't a fast language, and it isn't designed to be. Very few languages have the ability to do the dynamic stuff really well and still generate very fast code; at least for the forseeable future (and some of the design works against fast compilation) that will be the case.</p>\n\n<p>So, if you really find yourself in this bind, your best bet will be to isolate the parts of your system that are unacceptable slow in (good) python, and design around the idea that you'll rewrite those bits in C. Sorry. Good design can help make this less painful. Prototype it in python first though, then you've easily got a sanity check on your c, as well.</p>\n\n<p>This works well enough for things like numpy, after all. I can't emphasize enough how much good design will help you though. If you just iteratively poke at your python bits and replace the slowest ones with C, you may end up with a big mess. Think about exactly where the C bits are needed, and how they can be minimized and encapsulated sensibly.</p>\n"
},
{
"answer_id": 172782,
"author": "Walter",
"author_id": 23840,
"author_profile": "https://Stackoverflow.com/users/23840",
"pm_score": 2,
"selected": false,
"text": "<p>Just a note on using psyco: In some cases it can actually produce slower run-times. Especially when trying to use psyco with code that was written in C. I can't remember the the article I read this, but the <code>map()</code> and <code>reduce()</code> functions were mentioned specifically. Luckily you can tell psyco not to handle specified functions and/or modules.</p>\n"
},
{
"answer_id": 172784,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": false,
"text": "<p>Regarding \"Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?\"</p>\n\n<p>Remember the Jackson rules of optimization: </p>\n\n<ul>\n<li>Rule 1: Don't do it.</li>\n<li>Rule 2 (for experts only): Don't do it yet.</li>\n</ul>\n\n<p>And the Knuth rule:</p>\n\n<ul>\n<li>\"Premature optimization is the root of all evil.\"</li>\n</ul>\n\n<p>The more useful rules are in the <a href=\"http://www.cs.cmu.edu/~jch/java/rules.html\" rel=\"noreferrer\">General Rules for Optimization</a>.</p>\n\n<ol>\n<li><p>Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.</p></li>\n<li><p>Remember the 80/20 rule.</p></li>\n<li><p>Always run \"before\" and \"after\" benchmarks. Otherwise, you won't know if you've found the 80%.</p></li>\n<li><p>Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.</p></li>\n</ol>\n\n<p><strong>Bottom Line</strong></p>\n\n<p>You can't prevent or avoid the \"optimize this program\" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.</p>\n"
},
{
"answer_id": 172794,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "<p>I'm surprised no one mentioned ShedSkin: <a href=\"http://code.google.com/p/shedskin/\" rel=\"noreferrer\">http://code.google.com/p/shedskin/</a>, it automagically converts your python program to C++ and in some benchmarks yields better improvements than psyco in speed. </p>\n\n<p>Plus anecdotal stories on the simplicity: <a href=\"http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin.html\" rel=\"noreferrer\">http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin.html</a></p>\n\n<p>There are limitations though, please see: <a href=\"http://tinyurl.com/shedskin-limitations\" rel=\"noreferrer\">http://tinyurl.com/shedskin-limitations</a></p>\n"
},
{
"answer_id": 172991,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>This is the procedure that I try to follow:<br></p>\n\n<ul>\n <li> import psyco; psyco.full()\n <li> If it's not fast enough, run the code through a profiler, see where the bottlenecks are. (DISABLE psyco for this step!)\n <li> Try to do things such as other people have mentioned to get the code at those bottlenecks as fast as possible.\n <ul><li>Stuff like [str(x) for x in l] or [x.strip() for x in l] is much, much slower than map(str, x) or map(str.strip, x). </ul>\n <li> After this, if I still need more speed, it's actually really easy to get PyRex up and running. I first copy a section of python code, put it directly in the pyrex code, and see what happens. Then I twiddle with it until it gets faster and faster.\n</ul>\n"
},
{
"answer_id": 173055,
"author": "I GIVE CRAP ANSWERS",
"author_id": 25083,
"author_profile": "https://Stackoverflow.com/users/25083",
"pm_score": 5,
"selected": false,
"text": "<p>Rather than just punting to C, I'd suggest:</p>\n\n<p>Make your code count. Do more with fewer executions of lines:</p>\n\n<ul>\n<li>Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.</li>\n<li>Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable</li>\n<li>Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1).</li>\n<li>Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops.</li>\n<li>If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance.</li>\n<li>Need to crunch numbers? You might want to check <code>numpy</code> out.</li>\n<li>Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the <code>Twisted</code> framework.</li>\n<li>Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter.</li>\n</ul>\n\n<p>If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.</p>\n"
},
{
"answer_id": 175283,
"author": "Peter Shinners",
"author_id": 17209,
"author_profile": "https://Stackoverflow.com/users/17209",
"pm_score": 1,
"selected": false,
"text": "<p>If using psyco, I'd recommend <code>psyco.profile()</code> instead of <code>psyco.full()</code>. For a larger project it will be smarter about the functions that got optimized and use a ton less memory.</p>\n\n<p>I would also recommend looking at iterators and generators. If your application is using large data sets this will save you many copies of containers.</p>\n"
},
{
"answer_id": 247612,
"author": "sep332",
"author_id": 13652,
"author_profile": "https://Stackoverflow.com/users/13652",
"pm_score": 2,
"selected": false,
"text": "<p>It's often possible to achieve near-C speeds (close enough for any project using Python in the first place!) by replacing explicit algorithms written out longhand in Python with an implicit algorithm using a built-in Python call. This works because most Python built-ins are written in C anyway. Well, in CPython of course ;-) <a href=\"https://www.python.org/doc/essays/list2str/\" rel=\"nofollow noreferrer\">https://www.python.org/doc/essays/list2str/</a> </p>\n"
},
{
"answer_id": 247641,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 2,
"selected": false,
"text": "<p>The canonical reference to how to improve Python code is here: <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow noreferrer\">PerformanceTips</a>. I'd recommend against optimizing in C unless you really need to though. For most applications, you can get the performance you need by following the rules posted in that link.</p>\n"
},
{
"answer_id": 364373,
"author": "ionelmc",
"author_id": 23658,
"author_profile": "https://Stackoverflow.com/users/23658",
"pm_score": 3,
"selected": false,
"text": "<p>I hope you've read: <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"noreferrer\">http://wiki.python.org/moin/PythonSpeed/PerformanceTips</a></p>\n\n<p>Resuming what's already there are usualy 3 principles:</p>\n\n<ul>\n<li>write code that gets transformed in better bytecode, like, use locals, avoid unnecessary lookups/calls, use idiomatic constructs (if there's natural syntax for what you want, use it - usually faster. eg: don't do: \"for key in some_dict.keys()\", do \"for key in some_dict\")</li>\n<li>whatever is written in C is considerably faster, abuse whatever C functions/modules you have available</li>\n<li>when in doubt, import timeit, profile</li>\n</ul>\n"
},
{
"answer_id": 863670,
"author": "Davide",
"author_id": 25891,
"author_profile": "https://Stackoverflow.com/users/25891",
"pm_score": 1,
"selected": false,
"text": "<p>Besides the (great) <a href=\"http://psyco.sourceforge.net/\" rel=\"nofollow noreferrer\">psyco</a> and the (nice) <a href=\"http://code.google.com/p/shedskin/\" rel=\"nofollow noreferrer\">shedskin</a>, I'd recommend trying <a href=\"http://www.cython.org/\" rel=\"nofollow noreferrer\">cython</a> a great fork of <a href=\"http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/\" rel=\"nofollow noreferrer\">pyrex</a>. </p>\n\n<p>Or, if you are not in a hurry, I recommend to just wait. Newer python virtual machines are coming, and <a href=\"http://code.google.com/p/unladen-swallow/\" rel=\"nofollow noreferrer\">unladen-swallow</a> will find its way into the mainstream.</p>\n"
},
{
"answer_id": 18849701,
"author": "Janus Troelsen",
"author_id": 309483,
"author_profile": "https://Stackoverflow.com/users/309483",
"pm_score": 0,
"selected": false,
"text": "<p>A couple of ways to speed up Python code were introduced after this question was asked:</p>\n\n<ul>\n<li><strong>Pypy</strong> has a JIT-compiler, which makes it a lot faster for CPU-bound code.</li>\n<li>Pypy is written in <a href=\"https://code.google.com/p/rpython/\" rel=\"nofollow\"><strong>Rpython</strong></a>, a subset of Python that compiles to native code, leveraging the LLVM tool-chain.</li>\n</ul>\n"
},
{
"answer_id": 41671464,
"author": "joydeep bhattacharjee",
"author_id": 5417164,
"author_profile": "https://Stackoverflow.com/users/5417164",
"pm_score": 0,
"selected": false,
"text": "<p>For an established project I feel the main performance gain will be from making use of python internal lib as much as possible.</p>\n\n<p>Some tips are here: <a href=\"http://blog.hackerearth.com/faster-python-code\" rel=\"nofollow noreferrer\">http://blog.hackerearth.com/faster-python-code</a></p>\n"
},
{
"answer_id": 67342288,
"author": "tav",
"author_id": 2692494,
"author_profile": "https://Stackoverflow.com/users/2692494",
"pm_score": 0,
"selected": false,
"text": "<p>There is also Python → 11l → C++ transpiler, which can be downloaded from <a href=\"https://11l-lang.org\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] |
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what are some good ways to greatly improve performance?
For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
|
The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions.
In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this:
```
result = u""
for item in my_list:
result += unicode (item)
```
will copy the *entire* string twice per iteration. This has been well-covered, and the solution is to use `"".join`:
```
result = "".join (unicode (item) for item in my_list)
```
Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list.
Finally, **don't be afraid to rewrite bits in C!** Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module.
My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.
|
172,748 |
<p>Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This:</p>
<pre><code>window.open(src, 'newWin', 'fullscreen="yes"')
</code></pre>
<p>apparently only worked for old version of IE.</p>
|
[
{
"answer_id": 172756,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 7,
"selected": true,
"text": "<p>Use <code>screen.availWidth</code> and <code>screen.availHeight</code> to calculate a suitable size for the height and width parameters in <code>window.open()</code></p>\n\n<p>Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown.</p>\n"
},
{
"answer_id": 172892,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 3,
"selected": false,
"text": "<p>More than bad design - this \"feature\" is a recipe for UI disaster. There <a href=\"http://hackademix.net/2007/08/07/java-evil-popups\" rel=\"noreferrer\">were</a> a <a href=\"http://beyondteck.blogspot.com/2007/12/fullscreen-in-firefox-on-mac-os-x.html\" rel=\"noreferrer\">number</a> of <a href=\"http://www.wilderssecurity.com/archive/index.php/t-11975.html\" rel=\"noreferrer\">malicious</a> web sites which exploited the full screen view features in JavaScript to hijack browser windows and display a screen indistinguishable from the user's desktop. While there may still be a way to do this, please for the love of all things decent, do not implement this.</p>\n"
},
{
"answer_id": 189931,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 3,
"selected": false,
"text": "<p>What about this:</p>\n\n<pre><code>var popup = window.open(URL);\nif (popup == null)\n alert('Please change your popup settings');\nelse {\n popup.moveTo(0, 0);\n popup.resizeTo(screen.width, screen.height);\n}\n</code></pre>\n"
},
{
"answer_id": 44701800,
"author": "Jitendra Tumulu",
"author_id": 3308943,
"author_profile": "https://Stackoverflow.com/users/3308943",
"pm_score": 3,
"selected": false,
"text": "<p>What about this, I gave width and height value to a big number and it works</p>\n\n<pre><code>window.open(\"https://www.w3schools.com\", \"_blank\",\"toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=4000,height=4000\");\n</code></pre>\n"
},
{
"answer_id": 54388433,
"author": "SeekLoad",
"author_id": 7371886,
"author_profile": "https://Stackoverflow.com/users/7371886",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Try this. This works for me and with any link you want, or anything in the popup</strong></p>\n\n<p>Anything you chose will be shown in a PopUp window in a full screen size within a PopUp Window.</p>\n\n<pre><code><script language=\"JavaScript\">\nfunction Full_W_P(url) {\n params = 'width='+screen.width;\n params += ', height='+screen.height;\n params += ', top=0, left=0'\n params += ', fullscreen=yes';\n params += ', directories=no';\n params += ', location=no';\n params += ', menubar=no';\n params += ', resizable=no';\n params += ', scrollbars=no';\n params += ', status=no';\n params += ', toolbar=no';\n\n\n newwin=window.open(url,'FullWindowAll', params);\n if (window.focus) {newwin.focus()}\n return false;\n}\n</script>\n\n<input type=\"button\" value=\"Open as Full Window PopUp\" onclick=\"javascript:Full_W_P('http://www.YourLink.com');\"></input>\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3037/"
] |
Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This:
```
window.open(src, 'newWin', 'fullscreen="yes"')
```
apparently only worked for old version of IE.
|
Use `screen.availWidth` and `screen.availHeight` to calculate a suitable size for the height and width parameters in `window.open()`
Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown.
|
172,753 |
<p>just wondering if anyone has ever tried embedding and actually integrating any js engine into the .net environment. I could find and actually use (after a <strong>LOT</strong> of pain and effort, since it's pretty outdated and not quite finished) spidermonkey-dotnet project. Anyone with experience in this area? Engines like SquirrelFish, V8.. </p>
<p>Not that I'm not satisfied with Mozilla's Spidermonkey (using it for Rails-like miniframework for custom components inside the core ASP.NET application), but I'd still love to explore a bit further with the options. The command-line solutions are not what I'd need, I cannot rely on anything else than CLR, I need to call methods from/to JavaScript/C# objects.</p>
<pre><code>// c# class
public class A
{
public string Hello(string msg)
{
return msg + " whatewer";
}
}
// js snippet
var a = new A();
console.log(a.Hello('Call me')); // i have a console.log implemented, don't worry, it's not a client-side code :)
</code></pre>
<p>Just to clarify - I'm not trying to actually program <strong>the application itself</strong> in server-side javascript. It's used solely for writing custom user subapplications (can be seen as some sort of DSL). It's much easier (and safer) to allow normal people programming in js than C#.</p>
|
[
{
"answer_id": 172804,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": false,
"text": "<p>I guess I am still unclear about what it is you are trying to do, but JScript.NET might be worth looking into, though <a href=\"http://blogs.msdn.com/jscript/archive/2007/05/07/introducing-managed-jscript.aspx\" rel=\"noreferrer\"><strong>Managed JScript</strong></a> seems like it may be more appropriate for your needs (it is more like JavaScript than JScript.NET).</p>\n\n<p>Personally, I thought it would be cool to integrate V8 somehow, but I didn't get past downloading the source code; wish I had the time to actually do something with it.</p>\n"
},
{
"answer_id": 173160,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 1,
"selected": false,
"text": "<p>i believe all the major opensource JS engines (JavaScriptCore, SpiderMonkey, V8, and KJS) provide embedding APIs. The only one I am actually directly familiar with is JavaScriptCore (which is name of the JS engine the SquirrelFish lives in) which provides a pure C API. If memory serves (it's been a while since i used .NET) .NET has fairly good support for linking in C API's.</p>\n\n<p>I'm honestly not sure what the API's for the other engines are like, but I do know that they all provide them.</p>\n\n<p>That said, depending on your purposes JScript.NET may be best, as all of these other engines will require you to include them with your app, as JSC is the only one that actually ships with an OS, but that OS is MacOS :D</p>\n"
},
{
"answer_id": 469393,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": false,
"text": "<p>If the language isn't a problem (any sandboxed scripted one) then there's <a href=\"http://www.codeproject.com/KB/mcpp/luanetwrapper.aspx\" rel=\"noreferrer\">LUA for .NET</a>. The Silverlight version of the .NET framework is also sandboxed afaik.</p>\n"
},
{
"answer_id": 620273,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use JSCRIPT.NET to get a library(dll) of the js . Then reference this dll in your .NET application and you are just there. DONE!</p>\n"
},
{
"answer_id": 1624532,
"author": "Sébastien Ros - MSFT",
"author_id": 142772,
"author_profile": "https://Stackoverflow.com/users/142772",
"pm_score": 7,
"selected": false,
"text": "<p>The open source JavaScript interpreter Jint (<a href=\"http://jint.codeplex.com\" rel=\"noreferrer\">http://jint.codeplex.com</a>) does exactly what you are looking for.</p>\n\n<p><strong>Edit:</strong> <br/>\nThe project has been entirely rewritten and is now hosted on Github at <a href=\"https://github.com/sebastienros/jint\" rel=\"noreferrer\">https://github.com/sebastienros/jint</a></p>\n"
},
{
"answer_id": 3182411,
"author": "Michel Boissé",
"author_id": 384020,
"author_profile": "https://Stackoverflow.com/users/384020",
"pm_score": 7,
"selected": false,
"text": "<p>Try <a href=\"https://github.com/JavascriptNet/Javascript.Net\" rel=\"noreferrer\">Javascript .NET</a>. It is hosted on GitHub It was originally hosted on CodePlex, <a href=\"http://javascriptdotnet.codeplex.com\" rel=\"noreferrer\">here</a>)</p>\n\n<p>Project discussions: <a href=\"http://javascriptdotnet.codeplex.com/discussions\" rel=\"noreferrer\">http://javascriptdotnet.codeplex.com/discussions</a></p>\n\n<p>It implements Google V8. You can compile and run JavaScript directly from .NET code with it, and supply CLI objects to be used by the JavaScript code as well. It generates native code from JavaScript.</p>\n"
},
{
"answer_id": 3560739,
"author": "Deacon Frost",
"author_id": 389762,
"author_profile": "https://Stackoverflow.com/users/389762",
"pm_score": 3,
"selected": false,
"text": "<p>Hey take a look for Javascript .NET on codeplex (<a href=\"http://javascriptdotnet.codeplex.com/\" rel=\"noreferrer\">http://javascriptdotnet.codeplex.com/</a>) with the version 0.3.1 there is some pretty sweet new features that will probly interest you.</p>\n\n<p>Check out a sample code:</p>\n\n<pre><code>// Initialize the context\nJavascriptContext context = new JavascriptContext();\n\n// Setting the externals parameters of the context\ncontext.SetParameter(\"console\", new SystemConsole());\ncontext.SetParameter(\"message\", \"Hello World !\");\ncontext.SetParameter(\"number\", 1);\n\n// Running the script\ncontext.Run(\"var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i;\");\n\n// Getting a parameter\nConsole.WriteLine(\"number: \" + context.GetParameter(\"number\"));\n</code></pre>\n"
},
{
"answer_id": 4773385,
"author": "Sergi Mansilla",
"author_id": 78640,
"author_profile": "https://Stackoverflow.com/users/78640",
"pm_score": 3,
"selected": false,
"text": "<p>You can try ironJS, looks promising although it is in heavy development. <a href=\"https://github.com/fholm/IronJS\" rel=\"noreferrer\">https://github.com/fholm/IronJS</a></p>\n"
},
{
"answer_id": 6588605,
"author": "sanosdole",
"author_id": 543682,
"author_profile": "https://Stackoverflow.com/users/543682",
"pm_score": 2,
"selected": false,
"text": "<p>I just tried <strong><a href=\"http://www.remobjects.com/script.aspx\" rel=\"nofollow\">RemObjects Script for .Net</a></strong>.</p>\n\n<p>It works, although I had to use a static factory (<code>var a=A.createA();</code>) from JavaScript instead of the <code>var a=new A()</code> syntax. (ExposeType function only exposes statics!)\nNot much documentation and the source is written with Delphi Prism, which is rather unusual for me and the RedGate Reflector.</p>\n\n<p>So: <strong>Easy to use and setup, but not much help for advanced scenarios.</strong></p>\n\n<p>Also having to install something instead of just dropping the assemblies in a directory is a negative for me...</p>\n"
},
{
"answer_id": 6839482,
"author": "SilverX",
"author_id": 383969,
"author_profile": "https://Stackoverflow.com/users/383969",
"pm_score": 1,
"selected": false,
"text": "<p>I know I'm opening up an old thread but I've done a lot of work on smnet (spidermonkey-dotnet). In the recent years. It's main development focus has been seamless embedding of .net objects into the spidermonkey engine. It supports a wide variety of conversions from js values to .net objects. Some of those including delegates and events.</p>\n\n<p>Just saying it might be worth checking into now that there's some steady development on it :).\nI do keep the SVN repo up to date with bug fixes and new features. The source and project solution files are configured to successfully build on download. If there are any problems using it, feel free to open a discussion.</p>\n\n<p>I do understand the desire to have a managed javascript solution, but of all the managed javascript's I've used they're all very lacking in some key features that help make them both robust and easy to work with. I myself am waiting on IronJS to mature a little. While I wait, I have fun playing with spidermonkey-dotnet =) </p>\n\n<p><a href=\"http://spidermonkeydotnet.codeplex.com/releases/\" rel=\"nofollow\">spidermonkey-dotnet project and download page</a></p>\n\n<p>Edit: created documentation wiki page this afternoon.</p>\n"
},
{
"answer_id": 7434021,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "<p>Microsoft's documented way to add script extensibility to anything is IActiveScript. You can use IActiveScript from within anyt .NET app, to call script logic. The logic can party on .NET objects that you've placed into the scripting context. </p>\n\n<p>This answer provides an application that does it, with code: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5939002/will-the-ie10-chakra-jscript-engine-available-as-stand-alone-accessible-from-c/7367964#7367964\">Will the IE10 Chakra JScript engine available as stand alone accessible from C#?</a></li>\n</ul>\n"
},
{
"answer_id": 8360394,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 2,
"selected": false,
"text": "<p>There is an implementation of an <a href=\"http://en.wikipedia.org/wiki/Active_Scripting\" rel=\"nofollow noreferrer\">ActiveX Scripting</a> Engine Host in C# available here: <a href=\"https://stackoverflow.com/questions/4744105/parse-and-execute-js-by-c-sharp\">parse and execute JS by C#</a></p>\n\n<p>It allows to use Javascript (or VBScript) directly from C#, in native 32-bit or 64-bit processes. The full source is ~500 lines of C# code. It only has an implicit dependency on the installed JScript (or VBScript) engine DLL.</p>\n\n<p>For example, the following code:</p>\n\n<pre><code>Console.WriteLine(ScriptEngine.Eval(\"jscript\", \"1+2/3\"));\n</code></pre>\n\n<p>will display 1.66666666666667</p>\n"
},
{
"answer_id": 8795922,
"author": "bbqchickenrobot",
"author_id": 90890,
"author_profile": "https://Stackoverflow.com/users/90890",
"pm_score": 5,
"selected": false,
"text": "<p>Anybody just tuning in check out Jurassic as well: </p>\n\n<p><a href=\"http://jurassic.codeplex.com/\" rel=\"noreferrer\">http://jurassic.codeplex.com/</a></p>\n\n<p>edit: this has moved to github (and seems active at first glance)</p>\n\n<p><a href=\"https://github.com/paulbartrum/jurassic\" rel=\"noreferrer\">https://github.com/paulbartrum/jurassic</a></p>\n"
},
{
"answer_id": 12097394,
"author": "ahmadali shafiee",
"author_id": 1003464,
"author_profile": "https://Stackoverflow.com/users/1003464",
"pm_score": -1,
"selected": false,
"text": "<p>It's Possible now with <code>ASP.Net MVC4 Razor</code> View engine. the code will be this:</p>\n\n<pre><code>// c# class\npublic class A\n{\n public string Hello(string msg)\n {\n return msg + \" whatewer\";\n }\n}\n\n// js snippet\n<script type=\"text/javascript\">\nvar a = new A();\nconsole.log('@a.Hello('Call me')'); // i have a console.log implemented, don't worry, it's not a client-side code :)\n</script>\n</code></pre>\n\n<p>and <code>Razor</code> isn't just for MVC4 or another web applications and you can use it in offline desktop applications.</p>\n"
},
{
"answer_id": 14828241,
"author": "Necowood",
"author_id": 1583954,
"author_profile": "https://Stackoverflow.com/users/1583954",
"pm_score": 1,
"selected": false,
"text": "<p>Try <a href=\"http://www.unvell.com/ReoScript/\" rel=\"nofollow\">ReoScript</a>, an open-source JavaScript interpreter implemented in C#.</p>\n\n<p>ReoScript makes your application can execute JavaScript. It has a wide variety of extension methons such as SetVariable, Function Extension, using CLR Type, .Net Event Binding and etc. </p>\n\n<p>Hello World:</p>\n\n<pre><code>ScriptRunningMachine srm = new ScriptRunningMachine();\nsrm.Run(\" alert('hello world!'); \");\n</code></pre>\n\n<p>And here is an example of script that creates a winform and show it.</p>\n\n<pre><code>import System.Windows.Forms.*; // import namespace\n\nvar f = new Form(); // create form\nf.click = function() { f.close(); }; // close when user clicked on form\n\nf.show(); // show \n</code></pre>\n"
},
{
"answer_id": 16824197,
"author": "James Wilkins",
"author_id": 1236397,
"author_profile": "https://Stackoverflow.com/users/1236397",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://github.com/rjamesnw/v8dotnet\" rel=\"nofollow noreferrer\">V8.NET</a> is a new kid on the block (as of April 2013) that more closely wraps the native V8 engine functionality. It allows for more control over the implementation.</p>\n"
},
{
"answer_id": 17110645,
"author": "JB.",
"author_id": 1214248,
"author_profile": "https://Stackoverflow.com/users/1214248",
"pm_score": 6,
"selected": false,
"text": "<p>You might also be interested in <a href=\"https://github.com/Microsoft/ClearScript\" rel=\"noreferrer\">Microsoft ClearScript</a>\nwhich is hosted on GitHub and published under the Ms-Pl licence.</p>\n\n<p>I am no Microsoft fanboy, but I must admit that the V8 support has about the same functionnalities as Javascript.Net, and more important, the project is still maintained. As far as I am concerned, the support for delegates also functions better than with Spidermonkey-dotnet.</p>\n\n<p>ps: It also support JScript and VBScript but we were not interested by this old stuff.</p>\n\n<p>ps: It is compatible with .NET 4.0 and 4.5+</p>\n"
},
{
"answer_id": 21167233,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the Chakra engine in C#. Here is an article on msdn showing how:</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/windowsdesktop/JavaScript-Runtime-Hosting-d3a13880\">http://code.msdn.microsoft.com/windowsdesktop/JavaScript-Runtime-Hosting-d3a13880</a></p>\n"
},
{
"answer_id": 21717208,
"author": "Simon",
"author_id": 53158,
"author_profile": "https://Stackoverflow.com/users/53158",
"pm_score": 2,
"selected": false,
"text": "<p>There is also <a href=\"https://github.com/Taritsyn/MsieJavaScriptEngine\" rel=\"nofollow\">MsieJavaScriptEngine</a> which uses Internet Explorers Chakra engine</p>\n"
},
{
"answer_id": 31548921,
"author": "sinanguler",
"author_id": 2011479,
"author_profile": "https://Stackoverflow.com/users/2011479",
"pm_score": 3,
"selected": false,
"text": "<p>I came up with a much simpler solution instead.</p>\n\n<p>I built a <code>.dll</code> file using Javascript and then compiled it using the Javascript compiler which is available in a VS2013 developer command prompt.</p>\n\n<p>Once we have the <code>.dll</code> we simply add it to the <code>\\Support</code> folder and then referenced it in the project which needed to eval Javascript statements.</p>\n\n<p>Detailed Steps to create a <code>.dll</code>:</p>\n\n<ol>\n<li><p>Create a file in Notepad with only these contents:</p>\n\n<pre><code>class EvalClass { function Evaluate(expression: String) { return eval(expression); } } \n</code></pre></li>\n<li><p>Save the file as <code>C:\\MyEval.js</code></p></li>\n<li><p>Open a VS2005 Command Prompt (Start, Programs, VS2005, VS2005 Tools)</p></li>\n<li><p>Type <code>Cd\\</code> to get to <code>C:\\</code></p></li>\n<li><p>Type </p>\n\n<pre><code>jsc /t:library C:\\MyEval.js\n</code></pre></li>\n<li><p>A new file is created named <code>MyEval.dll</code>.</p></li>\n<li><p>Copy <code>MyEval.dll</code> to the project and reference it (also reference <code>Microsoft.Jscript.dll</code>).</p></li>\n<li><p>Then you should be able to call it like this:</p>\n\n<pre><code>Dim jScriptEvaluator As New EvalClass\nDim objResult As Object\nobjResult = jScriptEvaluator.Evaluate(“1==1 && 2==2”)\n</code></pre></li>\n</ol>\n\n<p>objResult is <code>True</code>.</p>\n"
},
{
"answer_id": 43899650,
"author": "luiseduardohd",
"author_id": 464985,
"author_profile": "https://Stackoverflow.com/users/464985",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Rhino a Mozilla Javascript engine written on Java, and use it with IKVM , here are some instructions</p>\n\n<p>Instructions:<a href=\"https://www.codeproject.com/Articles/41792/Embedding-JavaScript-into-C-with-Rhino-and-IKVM\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/41792/Embedding-JavaScript-into-C-with-Rhino-and-IKVM</a></p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25339/"
] |
just wondering if anyone has ever tried embedding and actually integrating any js engine into the .net environment. I could find and actually use (after a **LOT** of pain and effort, since it's pretty outdated and not quite finished) spidermonkey-dotnet project. Anyone with experience in this area? Engines like SquirrelFish, V8..
Not that I'm not satisfied with Mozilla's Spidermonkey (using it for Rails-like miniframework for custom components inside the core ASP.NET application), but I'd still love to explore a bit further with the options. The command-line solutions are not what I'd need, I cannot rely on anything else than CLR, I need to call methods from/to JavaScript/C# objects.
```
// c# class
public class A
{
public string Hello(string msg)
{
return msg + " whatewer";
}
}
// js snippet
var a = new A();
console.log(a.Hello('Call me')); // i have a console.log implemented, don't worry, it's not a client-side code :)
```
Just to clarify - I'm not trying to actually program **the application itself** in server-side javascript. It's used solely for writing custom user subapplications (can be seen as some sort of DSL). It's much easier (and safer) to allow normal people programming in js than C#.
|
The open source JavaScript interpreter Jint (<http://jint.codeplex.com>) does exactly what you are looking for.
**Edit:**
The project has been entirely rewritten and is now hosted on Github at <https://github.com/sebastienros/jint>
|
172,777 |
<p>We're all familiar with the pre- and post-increment operators, e.g.</p>
<pre><code>c++; // c = c + 1
++c; // ditto
</code></pre>
<p>and the "combined operators" which extend this principle:</p>
<pre><code>c += 5; // c = c + 5
s .= ", world"; // s = s . ", world"; e.g. PHP
</code></pre>
<p>I've often had a need for a 'post-combined operator', which would allow:</p>
<pre><code>s =. "Hello "; // s = "Hello " . s
</code></pre>
<p>Obviously, this is only really useful with non-commutable operators and the meaning is altered from pre-/post-increment, even though the syntax is borrowed.</p>
<p>Are you aware of any language that offers such an operator, and why isn't it more common?</p>
|
[
{
"answer_id": 172792,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>A basic objection to the example as-given is that it'd create ambiguity:</p>\n\n<pre><code>a=-5; //'a = -5' or 'a =- 5'?\nb=*p; //'b = *p' or 'b =* p'?\nc=.5; //'c = .5' or 'c =. 5'?\n</code></pre>\n\n<p><strong>Edit:</strong> But no, I'm not aware of any languages that use them. Presumably this is because they were omitted from C from whence most other languages derive their basic operators.</p>\n\n<p>And yeah, I'd love to see them in the languages I use.</p>\n"
},
{
"answer_id": 172799,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>None that I know about, and I don't think that there will be, as it's a meta-meta-command.</p>\n\n<p>To explain, the original operators (for numbers) came from C where they mapped directly to machine code operations. This allowed the programmer to do optimization, since the early compiler didn't.<br>\nSo,</p>\n\n<pre><code>x=x+1;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>x+=1;\n</code></pre>\n\n<p>and </p>\n\n<pre><code>x++;\n</code></pre>\n\n<p>would generate three different assembler outputs. </p>\n\n<p>Now, adding += for string is a meta-command. It doesn't map to an opcode, it just follows and extends the pattern.</p>\n"
},
{
"answer_id": 172839,
"author": "Zed",
"author_id": 19202,
"author_profile": "https://Stackoverflow.com/users/19202",
"pm_score": 2,
"selected": false,
"text": "<p>Combined 'op=' operators are shorthand for <code>var = var op predicate</code>, but op doesn't have to be anything in particular. The <code>'.'</code> operator happens to be shorthand for an \"append\" operation in a number of languages, but there's nothing stopping you from defining a \"prepend\" operation — or even changing append to prepend — in any language that allows overloading an operator on whatever data type you want to work with (or on any object you might use to contain that data otherwise). If you want to make <code>textvar /= newtext</code> shorthand for <code>textobj = textobj->prepend(newtext)</code> there's nothing stopping you.</p>\n\n<p>That said, you should probably never do this, as there's no way to change an existing operator without causing loads of confusion. It is substantially easier (and clearer) to change your statement order so that you can go left to right, or use a specific function such as <code>unshift</code> to prepend things without any ambiguity.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] |
We're all familiar with the pre- and post-increment operators, e.g.
```
c++; // c = c + 1
++c; // ditto
```
and the "combined operators" which extend this principle:
```
c += 5; // c = c + 5
s .= ", world"; // s = s . ", world"; e.g. PHP
```
I've often had a need for a 'post-combined operator', which would allow:
```
s =. "Hello "; // s = "Hello " . s
```
Obviously, this is only really useful with non-commutable operators and the meaning is altered from pre-/post-increment, even though the syntax is borrowed.
Are you aware of any language that offers such an operator, and why isn't it more common?
|
A basic objection to the example as-given is that it'd create ambiguity:
```
a=-5; //'a = -5' or 'a =- 5'?
b=*p; //'b = *p' or 'b =* p'?
c=.5; //'c = .5' or 'c =. 5'?
```
**Edit:** But no, I'm not aware of any languages that use them. Presumably this is because they were omitted from C from whence most other languages derive their basic operators.
And yeah, I'd love to see them in the languages I use.
|
172,812 |
<p>I have the following style in an external CSS file called first.css</p>
<pre><code>table { width: 100%; }
</code></pre>
<p>This makes the tables fill their container. If there are only two small columns they appear too far from each other.</p>
<p>To force the columns to appear nearer I have added this style</p>
<pre><code>table { width: 50%; }
</code></pre>
<p>to a new file called second.css and linked it into the html file.</p>
<p>Is there any way to override the width property in first.css without the need to specify a width in second.css?</p>
<p>I would like the html behave as if there has never been a width property, but I do not want to modify first.css</p>
|
[
{
"answer_id": 172816,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 6,
"selected": true,
"text": "<p>You can use:</p>\n\n<pre><code>table { width: auto; }\n</code></pre>\n\n<p>in second.css, to strictly make \"the html behave as if there was never been a width property\". But I'm not 100% sure this is exactly what you want - if not, please clarify!</p>\n"
},
{
"answer_id": 173640,
"author": "Alex Gyoshev",
"author_id": 25427,
"author_profile": "https://Stackoverflow.com/users/25427",
"pm_score": 2,
"selected": false,
"text": "<p>You could also add a style=\"width: auto\" attribute to the table - this way only the html of the page will be modified.</p>\n"
},
{
"answer_id": 12200490,
"author": "Vincent Tobiaz",
"author_id": 1454437,
"author_profile": "https://Stackoverflow.com/users/1454437",
"pm_score": 2,
"selected": false,
"text": "<p>table { width: 50%; !important }</p>\n\n<p>adding !important to any Style makes it override other ones no matter if it is a parent element or child element</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14755/"
] |
I have the following style in an external CSS file called first.css
```
table { width: 100%; }
```
This makes the tables fill their container. If there are only two small columns they appear too far from each other.
To force the columns to appear nearer I have added this style
```
table { width: 50%; }
```
to a new file called second.css and linked it into the html file.
Is there any way to override the width property in first.css without the need to specify a width in second.css?
I would like the html behave as if there has never been a width property, but I do not want to modify first.css
|
You can use:
```
table { width: auto; }
```
in second.css, to strictly make "the html behave as if there was never been a width property". But I'm not 100% sure this is exactly what you want - if not, please clarify!
|
172,821 |
<p>I've got a div that contains some content that's being added and removed dynamically, so its height is changing often. I also have a div that is absolutely positioned directly underneath with javascript, so unless I can detect when the height of the div changes, I can't reposition the div below it.</p>
<p>So, how can I detect when the height of that div changes? I assume there's some jQuery event I need to use, but I'm not sure which one to hook into.</p>
|
[
{
"answer_id": 173349,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 5,
"selected": false,
"text": "<p>You can use the DOMSubtreeModified event </p>\n\n<pre><code>$(something).bind('DOMSubtreeModified' ...\n</code></pre>\n\n<p>But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.</p>\n\n<p>Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.</p>\n\n<p>Downside: IE and Opera don't implement this event.</p>\n"
},
{
"answer_id": 16654445,
"author": "Kyle",
"author_id": 1098557,
"author_profile": "https://Stackoverflow.com/users/1098557",
"pm_score": 5,
"selected": false,
"text": "<p>This is how I recently handled this problem:</p>\n\n<pre><code>$('#your-resizing-div').bind('getheight', function() {\n $('#your-resizing-div').height();\n});\n\nfunction your_function_to_load_content() {\n /*whatever your thing does*/\n $('#your-resizing-div').trigger('getheight');\n}\n</code></pre>\n\n<p>I know I'm a few years late to the party, just think my answer may help some people in the future, without having to download any plugins.</p>\n"
},
{
"answer_id": 18063124,
"author": "apaul",
"author_id": 1947286,
"author_profile": "https://Stackoverflow.com/users/1947286",
"pm_score": 3,
"selected": false,
"text": "<p><strong>In response to user007:</strong></p>\n\n<p>If the height of your element is changing due to items being appended to it using <code>.append()</code> you shouldn't need to detect the change in height. Simply add the reposition of your second element in the same function where you are appending the new content to your first element.</p>\n\n<p>As in:</p>\n\n<p><strong><a href=\"http://jsfiddle.net/apaul34208/T952A/\">Working Example</a></strong></p>\n\n<pre><code>$('.class1').click(function () {\n $('.class1').append(\"<div class='newClass'><h1>This is some content</h1></div>\");\n $('.class2').css('top', $('.class1').offset().top + $('.class1').outerHeight());\n});\n</code></pre>\n"
},
{
"answer_id": 18084164,
"author": "Selvakumar Arumugam",
"author_id": 297641,
"author_profile": "https://Stackoverflow.com/users/297641",
"pm_score": 6,
"selected": false,
"text": "<p>I wrote a plugin sometime back for <strong><a href=\"http://meetselva.github.io/attrchange/\">attrchange</a></strong> listener which basically adds a listener function on attribute change. Even though I say it as a plugin, actually it is a simple function written as a jQuery plugin.. so if you want.. strip off the plugin specfic code and use the core functions.</p>\n\n<p><strong>Note: This code doesn't use polling</strong> </p>\n\n<p>check out this simple demo <a href=\"http://jsfiddle.net/aD49d/\">http://jsfiddle.net/aD49d/</a></p>\n\n<pre><code>$(function () {\n var prevHeight = $('#test').height();\n $('#test').attrchange({\n callback: function (e) {\n var curHeight = $(this).height(); \n if (prevHeight !== curHeight) {\n $('#logger').text('height changed from ' + prevHeight + ' to ' + curHeight);\n\n prevHeight = curHeight;\n } \n }\n }).resizable();\n});\n</code></pre>\n\n<p><strong>Plugin page:</strong> <a href=\"http://meetselva.github.io/attrchange/\">http://meetselva.github.io/attrchange/</a></p>\n\n<p><strong>Minified version:</strong> (1.68kb)</p>\n\n<pre><code>(function(e){function t(){var e=document.createElement(\"p\");var t=false;if(e.addEventListener)e.addEventListener(\"DOMAttrModified\",function(){t=true},false);else if(e.attachEvent)e.attachEvent(\"onDOMAttrModified\",function(){t=true});else return false;e.setAttribute(\"id\",\"target\");return t}function n(t,n){if(t){var r=this.data(\"attr-old-value\");if(n.attributeName.indexOf(\"style\")>=0){if(!r[\"style\"])r[\"style\"]={};var i=n.attributeName.split(\".\");n.attributeName=i[0];n.oldValue=r[\"style\"][i[1]];n.newValue=i[1]+\":\"+this.prop(\"style\")[e.camelCase(i[1])];r[\"style\"][i[1]]=n.newValue}else{n.oldValue=r[n.attributeName];n.newValue=this.attr(n.attributeName);r[n.attributeName]=n.newValue}this.data(\"attr-old-value\",r)}}var r=window.MutationObserver||window.WebKitMutationObserver;e.fn.attrchange=function(i){var s={trackValues:false,callback:e.noop};if(typeof i===\"function\"){s.callback=i}else{e.extend(s,i)}if(s.trackValues){e(this).each(function(t,n){var r={};for(var i,t=0,s=n.attributes,o=s.length;t<o;t++){i=s.item(t);r[i.nodeName]=i.value}e(this).data(\"attr-old-value\",r)})}if(r){var o={subtree:false,attributes:true,attributeOldValue:s.trackValues};var u=new r(function(t){t.forEach(function(t){var n=t.target;if(s.trackValues){t.newValue=e(n).attr(t.attributeName)}s.callback.call(n,t)})});return this.each(function(){u.observe(this,o)})}else if(t()){return this.on(\"DOMAttrModified\",function(e){if(e.originalEvent)e=e.originalEvent;e.attributeName=e.attrName;e.oldValue=e.prevValue;s.callback.call(this,e)})}else if(\"onpropertychange\"in document.body){return this.on(\"propertychange\",function(t){t.attributeName=window.event.propertyName;n.call(e(this),s.trackValues,t);s.callback.call(this,t)})}return this}})(jQuery)\n</code></pre>\n"
},
{
"answer_id": 26440831,
"author": "Marc J. Schmidt",
"author_id": 979328,
"author_profile": "https://Stackoverflow.com/users/979328",
"pm_score": 6,
"selected": false,
"text": "<p>Use a resize sensor from the css-element-queries library:</p>\n\n<p><a href=\"https://github.com/marcj/css-element-queries\">https://github.com/marcj/css-element-queries</a></p>\n\n<pre><code>new ResizeSensor(jQuery('#myElement'), function() {\n console.log('myelement has been resized');\n});\n</code></pre>\n\n<p>It uses a event based approach and doesn't waste your cpu time. Works in all browsers incl. IE7+.</p>\n"
},
{
"answer_id": 26558390,
"author": "EFernandes",
"author_id": 1251884,
"author_profile": "https://Stackoverflow.com/users/1251884",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver\"><code>MutationObserver</code></a> class.</p>\n\n<p><code>MutationObserver</code> provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification.</p>\n\n<p><strong>Example</strong> (<a href=\"http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/\">source</a>)</p>\n\n<pre><code>// select the target node\nvar target = document.querySelector('#some-id');\n\n// create an observer instance\nvar observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(mutation) {\n console.log(mutation.type);\n }); \n});\n\n// configuration of the observer:\nvar config = { attributes: true, childList: true, characterData: true };\n\n// pass in the target node, as well as the observer options\nobserver.observe(target, config);\n\n// later, you can stop observing\nobserver.disconnect();\n</code></pre>\n"
},
{
"answer_id": 30597601,
"author": "Estefano Salazar",
"author_id": 1301550,
"author_profile": "https://Stackoverflow.com/users/1301550",
"pm_score": 2,
"selected": false,
"text": "<p>You can make a simple setInterval.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function someJsClass()\r\n{\r\n var _resizeInterval = null;\r\n var _lastHeight = 0;\r\n var _lastWidth = 0;\r\n \r\n this.Initialize = function(){\r\n var _resizeInterval = setInterval(_resizeIntervalTick, 200);\r\n };\r\n \r\n this.Stop = function(){\r\n if(_resizeInterval != null)\r\n clearInterval(_resizeInterval);\r\n };\r\n \r\n var _resizeIntervalTick = function () {\r\n if ($(yourDiv).width() != _lastWidth || $(yourDiv).height() != _lastHeight) {\r\n _lastWidth = $(contentBox).width();\r\n _lastHeight = $(contentBox).height();\r\n DoWhatYouWantWhenTheSizeChange();\r\n }\r\n };\r\n}\r\n\r\nvar class = new someJsClass();\r\nclass.Initialize();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>EDIT:</p>\n\n<p>This is a example with a class. But you can do something easiest.</p>\n"
},
{
"answer_id": 45993134,
"author": "Ronald Rivera",
"author_id": 7003737,
"author_profile": "https://Stackoverflow.com/users/7003737",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this, but it only supports Firefox and Chrome.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(element).bind('DOMSubtreeModified', function () {\r\n var $this = this;\r\n var updateHeight = function () {\r\n var Height = $($this).height();\r\n console.log(Height);\r\n };\r\n setTimeout(updateHeight, 2000);\r\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48829361,
"author": "Zac",
"author_id": 3780493,
"author_profile": "https://Stackoverflow.com/users/3780493",
"pm_score": 0,
"selected": false,
"text": "<p>Pretty basic but works:</p>\n\n<pre><code>function dynamicHeight() {\n var height = jQuery('').height();\n jQuery('.edito-wrapper').css('height', editoHeight);\n}\neditoHeightSize();\n\njQuery(window).resize(function () {\n editoHeightSize();\n});\n</code></pre>\n"
},
{
"answer_id": 65132782,
"author": "gitaarik",
"author_id": 1248175,
"author_profile": "https://Stackoverflow.com/users/1248175",
"pm_score": 2,
"selected": false,
"text": "<p>These days you can also use the Web API <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver\" rel=\"nofollow noreferrer\"><code>ResizeObserver</code></a>.</p>\n<p>Simple example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const myElement = document.querySelector('#myElement');\n\nconst resizeObserver = new ResizeObserver(() => {\n console.log('size of myElement changed');\n});\n\nresizeObserver.observe(myElement);\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384/"
] |
I've got a div that contains some content that's being added and removed dynamically, so its height is changing often. I also have a div that is absolutely positioned directly underneath with javascript, so unless I can detect when the height of the div changes, I can't reposition the div below it.
So, how can I detect when the height of that div changes? I assume there's some jQuery event I need to use, but I'm not sure which one to hook into.
|
I wrote a plugin sometime back for **[attrchange](http://meetselva.github.io/attrchange/)** listener which basically adds a listener function on attribute change. Even though I say it as a plugin, actually it is a simple function written as a jQuery plugin.. so if you want.. strip off the plugin specfic code and use the core functions.
**Note: This code doesn't use polling**
check out this simple demo <http://jsfiddle.net/aD49d/>
```
$(function () {
var prevHeight = $('#test').height();
$('#test').attrchange({
callback: function (e) {
var curHeight = $(this).height();
if (prevHeight !== curHeight) {
$('#logger').text('height changed from ' + prevHeight + ' to ' + curHeight);
prevHeight = curHeight;
}
}
}).resizable();
});
```
**Plugin page:** <http://meetselva.github.io/attrchange/>
**Minified version:** (1.68kb)
```
(function(e){function t(){var e=document.createElement("p");var t=false;if(e.addEventListener)e.addEventListener("DOMAttrModified",function(){t=true},false);else if(e.attachEvent)e.attachEvent("onDOMAttrModified",function(){t=true});else return false;e.setAttribute("id","target");return t}function n(t,n){if(t){var r=this.data("attr-old-value");if(n.attributeName.indexOf("style")>=0){if(!r["style"])r["style"]={};var i=n.attributeName.split(".");n.attributeName=i[0];n.oldValue=r["style"][i[1]];n.newValue=i[1]+":"+this.prop("style")[e.camelCase(i[1])];r["style"][i[1]]=n.newValue}else{n.oldValue=r[n.attributeName];n.newValue=this.attr(n.attributeName);r[n.attributeName]=n.newValue}this.data("attr-old-value",r)}}var r=window.MutationObserver||window.WebKitMutationObserver;e.fn.attrchange=function(i){var s={trackValues:false,callback:e.noop};if(typeof i==="function"){s.callback=i}else{e.extend(s,i)}if(s.trackValues){e(this).each(function(t,n){var r={};for(var i,t=0,s=n.attributes,o=s.length;t<o;t++){i=s.item(t);r[i.nodeName]=i.value}e(this).data("attr-old-value",r)})}if(r){var o={subtree:false,attributes:true,attributeOldValue:s.trackValues};var u=new r(function(t){t.forEach(function(t){var n=t.target;if(s.trackValues){t.newValue=e(n).attr(t.attributeName)}s.callback.call(n,t)})});return this.each(function(){u.observe(this,o)})}else if(t()){return this.on("DOMAttrModified",function(e){if(e.originalEvent)e=e.originalEvent;e.attributeName=e.attrName;e.oldValue=e.prevValue;s.callback.call(this,e)})}else if("onpropertychange"in document.body){return this.on("propertychange",function(t){t.attributeName=window.event.propertyName;n.call(e(this),s.trackValues,t);s.callback.call(this,t)})}return this}})(jQuery)
```
|
172,831 |
<p>If you have the following:</p>
<pre><code>$var = 3; // we'll say it's set to 3 for this example
if ($var == 4) {
// do something
} else if ($var == 5) {
// do something
} else if ($var == 2) {
// do something
} else if ($var == 3) {
// do something
} else {
// do something
}
</code></pre>
<p>If say 80% of the time <code>$var</code> is 3, do you worry about the fact that it's going through 4 if cases before finding the true case?</p>
<p>I'm thinking on a small site it's not a big deal, but what about when that if statement is going to run 1000s of times a second?</p>
<p>I'm working in PHP, but I'm thinking the language doesn't matter.</p>
|
[
{
"answer_id": 172836,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 3,
"selected": false,
"text": "<p>A classic case of this occurring (with literally 5 options as in your post) was in ffmpeg, in the decode_cabac_residual function. This was rather important, as profiling (very important--don't optimize before profiling!) showed it counted for upwards of 10-15% of the time spent in H.264 video decoding. The if statement controlled a set of statements which was calculated differently for the various types of residuals to be decoded--and, unfortunately, too much speed was lost due to code size if the function was duplicated 5 times for each of the 5 types of residual. So instead, an if chain had to be used.</p>\n\n<p>Profiling was done on many common test streams to order them in terms of likelihood; the top was the most common, the bottom the least. This gave a small speed gain.</p>\n\n<p>Now, in PHP, I suspect that there's a lot less of the low-level style speed gain that you'd get in C, as in the above example.</p>\n"
},
{
"answer_id": 172837,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": false,
"text": "<p>Well, I believe that <em>almost all the time</em>, the legibility of, say, having numerically ordered values would override any tiny benefits you may gain by reducing the number of comparison instructions.</p>\n\n<p>Having said that, as with all optimisation:</p>\n\n<ol>\n<li>Make it work</li>\n<li>Measure it</li>\n<li>If it's fast enough, leave it alone</li>\n<li>If it's too slow, THEN optimise it</li>\n</ol>\n\n<p>Oh, and I'd probably use a switch/case from the get-go! ;-)</p>\n"
},
{
"answer_id": 172850,
"author": "JPLemme",
"author_id": 1019,
"author_profile": "https://Stackoverflow.com/users/1019",
"pm_score": 1,
"selected": false,
"text": "<p>If the code has to do additional tests then it will certainly run more slowly. If performance is critical in this section of code then you should put the most common case(s) first.</p>\n\n<p>I normally agree with the \"measure, then optimize\" method when you're not sure if the performance will be fast enough, but if the code simply needs to run as fast as possible AND the fix is as easy as rearranging the tests, then I would make the code fast now and do some measuring after you go live to insure that your assumption (e.g. that 3 is going to happen 80% of the time) is actually correct.</p>\n"
},
{
"answer_id": 172870,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": "<p>Here's how we did it when I used to write software for radar systems. (Speed matters in radar. It's one of the few places where \"real time\" actually means \"real\" instead of \"fast\".)</p>\n\n<p>[I'll switch to Python syntax, it's easier for me and I'm sure you can interpret it.]</p>\n\n<pre><code>if var <= 3:\n if var == 2:\n # do something\n elif var == 3:\n # do something\n else: \n raise Exception\nelse:\n if var == 4:\n # do something\n elif var == 5:\n # do something\n else:\n raise Exception\n</code></pre>\n\n<p>Your if-statements form a tree instead of a flat list. As you add conditions to this list, you jiggle around the center of the tree. The flat sequence of <em>n</em> comparisons takes, on average, <em>n</em>/2 steps. The tree leads to a sequence of comparisons that takes log(<em>n</em>) comparisons.</p>\n"
},
{
"answer_id": 172872,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Using a switch/case statement is the definitely the way to go here.</p>\n\n<p>This gives the compiler (interpreter) the chance to utilize a jump table to get to the right branch without having to do N comparisons. Think of it creating an array of addresses indexed as 0, 1, 2, .. then it can just look the correct one up in the array in a single operation.</p>\n\n<p>Plus, since the is less syntatic overhead in a case statement, it reads easier too.</p>\n\n<p><strong>Update:</strong> if the comparisons are suitable for a switch statement then this is an area where profile guided optimizations can help. By running a PGO build with realistic test loads the system can generate branch usage information, and then use this to optimize the path taken.</p>\n"
},
{
"answer_id": 173029,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>With code where it is purely an equality analysis I would move it to a switch/case, as that provides better performance.</p>\n\n<pre><code>$var = 3; // we'll say it's set to 3 for this example\nswitch($var)\n {\n case 4:\n //do something\n break;\n case 5:\n //do something\n break;\n case:\n //do something when none of the provided cases match (same as using an else{ after the elseif{\n }\n</code></pre>\n\n<p>now if your doing more complicated comparisons I would either nest them in the switch, or just use the elseif.</p>\n"
},
{
"answer_id": 173037,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>In object-oriented languages, if an option provides massive ifs, then that means you should just move the behavior (e.g., your <code>//do something</code> blocks) to the object containing the value.</p>\n"
},
{
"answer_id": 173063,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>Only you can tell if the performance difference of optimizing the order, or rearranging it to in effect be a binary tree, would make a significant difference. But I suspect you'll have to have millions of times per second, not thousands, to even bother thinking about it in PHP (and even more so in some other languages).</p>\n\n<p>Time it. See how many times a second you can run the above if/else if/else statement with no action being taken and $var not being one of the choices.</p>\n"
},
{
"answer_id": 173089,
"author": "I GIVE CRAP ANSWERS",
"author_id": 25083,
"author_profile": "https://Stackoverflow.com/users/25083",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than answer the PHP question, I'll answer a bit more generally. It doesn't apply directly to PHP as it will go through some kind of interpretation.</p>\n\n<p>Many compilers can convert to and from if-elif-elif-... blocks to switch blocks if needed and the tests in the elif-parts are simple enough (and the rest of the semantics happens to be compatible). For 3-4 tests there is not necessarily anything to gain by using a jump table.</p>\n\n<p>The reason is that the branch-predictor in the CPU is really good at predicting what happens. In effect the only thing that happens is a bit higher pressure on instruction fetching but it is hardly going to be world-shattering.</p>\n\n<p>In your example however, most compilers would recognize that $var is a constant 3 and then replace $var with 3 in the if..elif.. blocks. This in turn makes the expressions constant so they are folded to either true of false. All the false branches is killed by the dead-code eliminator and the test for true is eliminated as well. What is left is the case where $var == 3. You can't rely on PHP being that clever though. In general you can't do the propagation of $var but it might be possible from some call-sites.</p>\n"
},
{
"answer_id": 175626,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 1,
"selected": false,
"text": "<p>You could try having an array of code blocks, which you call into. Then all code blocks have the same overhead.</p>\n<h3>Perl 6:</h3>\n<pre><code>our @code_blocks = (\n { 'Code Block 0' },\n { 'Code Block 1' },\n { 'Code Block 2' },\n { 'Code Block 3' },\n { 'Code Block 4' },\n { 'Code Block 5' },\n);\n\nif( 0 <= $var < @code_blocks.length ){\n @code_blocks[$var]->();\n}\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
If you have the following:
```
$var = 3; // we'll say it's set to 3 for this example
if ($var == 4) {
// do something
} else if ($var == 5) {
// do something
} else if ($var == 2) {
// do something
} else if ($var == 3) {
// do something
} else {
// do something
}
```
If say 80% of the time `$var` is 3, do you worry about the fact that it's going through 4 if cases before finding the true case?
I'm thinking on a small site it's not a big deal, but what about when that if statement is going to run 1000s of times a second?
I'm working in PHP, but I'm thinking the language doesn't matter.
|
Here's how we did it when I used to write software for radar systems. (Speed matters in radar. It's one of the few places where "real time" actually means "real" instead of "fast".)
[I'll switch to Python syntax, it's easier for me and I'm sure you can interpret it.]
```
if var <= 3:
if var == 2:
# do something
elif var == 3:
# do something
else:
raise Exception
else:
if var == 4:
# do something
elif var == 5:
# do something
else:
raise Exception
```
Your if-statements form a tree instead of a flat list. As you add conditions to this list, you jiggle around the center of the tree. The flat sequence of *n* comparisons takes, on average, *n*/2 steps. The tree leads to a sequence of comparisons that takes log(*n*) comparisons.
|
172,841 |
<p>I have applied a <code>Formatter</code> to a <code>JFormattedTextField</code> using a <code>FormatterFactory</code>, when a user clicks into the text field I want to select the contents. </p>
<p>A focus listener does not work as expected because the formatter gets called, which eventually causes the value to be reset which ultimately de-selects the fields contents. I think what is happening is that after the value changes, the Caret moves to the rightmost position and this deselects the field.</p>
<p>Does anyone have any knowledge of how to get around this and select the fields contents correctly?</p>
|
[
{
"answer_id": 186156,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 1,
"selected": false,
"text": "<p>which jdk are you using - any chance this is a bug in it?</p>\n"
},
{
"answer_id": 190302,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 3,
"selected": true,
"text": "<p>Quick and dirty workaround is to use \nEventQueue.invokeLater from your focusListener.</p>\n\n<pre><code> EventQueue.invokeLater(new Runnable(){\n public void run() { yourTextField.selectAll();}\n});\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18445/"
] |
I have applied a `Formatter` to a `JFormattedTextField` using a `FormatterFactory`, when a user clicks into the text field I want to select the contents.
A focus listener does not work as expected because the formatter gets called, which eventually causes the value to be reset which ultimately de-selects the fields contents. I think what is happening is that after the value changes, the Caret moves to the rightmost position and this deselects the field.
Does anyone have any knowledge of how to get around this and select the fields contents correctly?
|
Quick and dirty workaround is to use
EventQueue.invokeLater from your focusListener.
```
EventQueue.invokeLater(new Runnable(){
public void run() { yourTextField.selectAll();}
});
```
|
172,854 |
<p>I have a Boost unit test case which causes the object under test to throw an exception (that's the test, to cause an exception). How do I specify in the test to expect that particular exception.</p>
<p>I can specify that the test should have a certain number of failures by using BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES but that seems rather unspecific. I want to be able to say at a specific point in the test that an exception should be thrown and that it should not be counted as a failure.</p>
|
[
{
"answer_id": 172995,
"author": "jonner",
"author_id": 78437,
"author_profile": "https://Stackoverflow.com/users/78437",
"pm_score": 7,
"selected": true,
"text": "<p>Doesn't this work?</p>\n\n<pre><code>BOOST_CHECK_THROW (expression, an_exception_type);\n</code></pre>\n\n<p>That should cause the test to pass if the expression throws the given exception type or fail otherwise. If you need a different severity than 'CHECK', you could also use <code>BOOST_WARN_THROW()</code> or <code>BOOST_REQUIRE_THROW()</code> instead. See <a href=\"http://www.boost.org/doc/libs/1_35_0/libs/test/doc/components/test_tools/reference/BOOST_CHECK_THROW.html\" rel=\"noreferrer\">the documentation</a></p>\n"
},
{
"answer_id": 173438,
"author": "Tomek",
"author_id": 25406,
"author_profile": "https://Stackoverflow.com/users/25406",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use BOOST_CHECK_EXCEPTION, which allows you to specify test function which validates your exception.</p>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
I have a Boost unit test case which causes the object under test to throw an exception (that's the test, to cause an exception). How do I specify in the test to expect that particular exception.
I can specify that the test should have a certain number of failures by using BOOST\_AUTO\_TEST\_CASE\_EXPECTED\_FAILURES but that seems rather unspecific. I want to be able to say at a specific point in the test that an exception should be thrown and that it should not be counted as a failure.
|
Doesn't this work?
```
BOOST_CHECK_THROW (expression, an_exception_type);
```
That should cause the test to pass if the expression throws the given exception type or fail otherwise. If you need a different severity than 'CHECK', you could also use `BOOST_WARN_THROW()` or `BOOST_REQUIRE_THROW()` instead. See [the documentation](http://www.boost.org/doc/libs/1_35_0/libs/test/doc/components/test_tools/reference/BOOST_CHECK_THROW.html)
|
172,875 |
<p>Basically I'm running some performance tests and don't want the external network to be the drag factor. I'm looking into ways of disabling network LAN. What is an effective way of doing it programmatically? I'm interested in c#. If anyone has a code snippet that can drive the point home that would be cool.</p>
|
[
{
"answer_id": 6170507,
"author": "Melvyn",
"author_id": 755986,
"author_profile": "https://Stackoverflow.com/users/755986",
"pm_score": 5,
"selected": false,
"text": "<p>Found this thread while searching for the same thing, so, here is the answer :)</p>\n\n<p>The best method I tested in C# uses WMI.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394216\" rel=\"noreferrer\">Win32_NetworkAdapter on msdn</a></p>\n\n<p>C# Snippet : (System.Management must be referenced in the solution, and in using declarations)</p>\n\n<pre><code>SelectQuery wmiQuery = new SelectQuery(\"SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL\");\nManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);\nforeach (ManagementObject item in searchProcedure.Get())\n{\n if (((string)item[\"NetConnectionId\"]) == \"Local Network Connection\")\n {\n item.InvokeMethod(\"Disable\", null);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18761206,
"author": "Kamrul Hasan",
"author_id": 1557156,
"author_profile": "https://Stackoverflow.com/users/1557156",
"pm_score": 4,
"selected": false,
"text": "<p>Using netsh Command, you can enable and disable “Local Area Connection”</p>\n\n<pre><code> interfaceName is “Local Area Connection”.\n\n static void Enable(string interfaceName)\n {\n System.Diagnostics.ProcessStartInfo psi =\n new System.Diagnostics.ProcessStartInfo(\"netsh\", \"interface set interface \\\"\" + interfaceName + \"\\\" enable\");\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n p.StartInfo = psi;\n p.Start();\n }\n\n static void Disable(string interfaceName)\n {\n System.Diagnostics.ProcessStartInfo psi =\n new System.Diagnostics.ProcessStartInfo(\"netsh\", \"interface set interface \\\"\" + interfaceName + \"\\\" disable\");\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n p.StartInfo = psi;\n p.Start();\n }\n</code></pre>\n"
},
{
"answer_id": 18762316,
"author": "Kamrul Hasan",
"author_id": 1557156,
"author_profile": "https://Stackoverflow.com/users/1557156",
"pm_score": 1,
"selected": false,
"text": "<p>In VB.Net , You can also use it for toggle Local Area Connection </p>\n\n<p>Note: myself use it in Windows XP, it's work here properly. but in windows 7 it's not work properly.</p>\n\n<pre><code> Private Sub ToggleNetworkConnection()\n\n Try\n\n\n Const ssfCONTROLS = 3\n\n\n Dim sConnectionName = \"Local Area Connection\"\n\n Dim sEnableVerb = \"En&able\"\n Dim sDisableVerb = \"Disa&ble\"\n\n Dim shellApp = CreateObject(\"shell.application\")\n Dim WshShell = CreateObject(\"Wscript.Shell\")\n Dim oControlPanel = shellApp.Namespace(ssfCONTROLS)\n\n Dim oNetConnections = Nothing\n For Each folderitem In oControlPanel.items\n If folderitem.name = \"Network Connections\" Then\n oNetConnections = folderitem.getfolder : Exit For\n End If\n Next\n\n\n If oNetConnections Is Nothing Then\n MsgBox(\"Couldn't find 'Network and Dial-up Connections' folder\")\n WshShell.quit()\n End If\n\n\n Dim oLanConnection = Nothing\n For Each folderitem In oNetConnections.items\n If LCase(folderitem.name) = LCase(sConnectionName) Then\n oLanConnection = folderitem : Exit For\n End If\n Next\n\n\n If oLanConnection Is Nothing Then\n MsgBox(\"Couldn't find '\" & sConnectionName & \"' item\")\n WshShell.quit()\n End If\n\n\n Dim bEnabled = True\n Dim oEnableVerb = Nothing\n Dim oDisableVerb = Nothing\n Dim s = \"Verbs: \" & vbCrLf\n For Each verb In oLanConnection.verbs\n s = s & vbCrLf & verb.name\n If verb.name = sEnableVerb Then\n oEnableVerb = verb\n bEnabled = False\n End If\n If verb.name = sDisableVerb Then\n oDisableVerb = verb\n End If\n Next\n\n\n\n If bEnabled Then\n oDisableVerb.DoIt()\n Else\n oEnableVerb.DoIt()\n End If\n\n\n Catch ex As Exception\n MsgBox(ex.Message)\n End Try\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 46113403,
"author": "micharaze",
"author_id": 5941260,
"author_profile": "https://Stackoverflow.com/users/5941260",
"pm_score": 0,
"selected": false,
"text": "<p>I modfied the <a href=\"https://stackoverflow.com/a/18761206/5941260\">best voted solution</a> from <a href=\"https://stackoverflow.com/users/1557156/kamrul-hasan\">Kamrul Hasan</a> to one methode and added to wait for the exit of the process, cause my Unit Test code run faster than the process disable the connection.</p>\n\n<pre><code>private void Enable_LocalAreaConection(bool isEnable = true)\n {\n var interfaceName = \"Local Area Connection\";\n string control;\n if (isEnable)\n control = \"enable\";\n else\n control = \"disable\";\n System.Diagnostics.ProcessStartInfo psi =\n new System.Diagnostics.ProcessStartInfo(\"netsh\", \"interface set interface \\\"\" + interfaceName + \"\\\" \" + control);\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n p.StartInfo = psi;\n p.Start();\n p.WaitForExit();\n }\n</code></pre>\n"
},
{
"answer_id": 48671520,
"author": "Chris Bols",
"author_id": 9329423,
"author_profile": "https://Stackoverflow.com/users/9329423",
"pm_score": 1,
"selected": false,
"text": "<p>For Windows 10 Change this:\nfor diable\n(\"netsh\", \"interface set interface name=\" + interfaceName + \" admin=DISABLE\")\nand for enable\n(\"netsh\", \"interface set interface name=\" + interfaceName + \" admin=ENABLE\")\nAnd use the program as Administrator</p>\n\n<pre><code> static void Disable(string interfaceName)\n {\n\n //set interface name=\"Ethernet\" admin=DISABLE\n System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(\"netsh\", \"interface set interface name=\" + interfaceName + \" admin=DISABLE\");\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n\n p.StartInfo = psi;\n p.Start();\n }\n\n static void Enable(string interfaceName)\n {\n System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(\"netsh\", \"interface set interface name=\" + interfaceName + \" admin=ENABLE\");\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n p.StartInfo = psi;\n p.Start();\n }\n</code></pre>\n\n<p>And use the Program as Administrator !!!!!!</p>\n"
},
{
"answer_id": 56611141,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you are looking for a very simple way to do it, here you go:</p>\n\n<pre><code> System.Diagnostics.Process.Start(\"ipconfig\", \"/release\"); //For disabling internet\n System.Diagnostics.Process.Start(\"ipconfig\", \"/renew\"); //For enabling internet\n</code></pre>\n\n<p>Make sure you run as administrator. I hope you found this helpful! </p>\n"
},
{
"answer_id": 57653626,
"author": "FarhadMohseni",
"author_id": 6899111,
"author_profile": "https://Stackoverflow.com/users/6899111",
"pm_score": 1,
"selected": false,
"text": "<p>best solution is disabling all network adapters regardless of the interface name is disabling and enabling all network adapters using this snippet (Admin rights needed for running , otherwise ITS WONT WORK) :</p>\n\n<pre><code> static void runCmdCommad(string cmd)\n {\n System.Diagnostics.Process process = new System.Diagnostics.Process();\n System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();\n //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n startInfo.FileName = \"cmd.exe\";\n startInfo.Arguments = $\"/C {cmd}\";\n process.StartInfo = startInfo;\n process.Start();\n }\n static void DisableInternet(bool enable)\n {\n string disableNet = \"wmic path win32_networkadapter where PhysicalAdapter=True call disable\";\n string enableNet = \"wmic path win32_networkadapter where PhysicalAdapter=True call enable\";\n runCmdCommad(enable ? enableNet :disableNet);\n }\n</code></pre>\n"
},
{
"answer_id": 68520653,
"author": "Christopher Vickers",
"author_id": 5905688,
"author_profile": "https://Stackoverflow.com/users/5905688",
"pm_score": 0,
"selected": false,
"text": "<p>Looking at the other answers here, whilst some work, some do not. Windows 10 uses a different netsh command to the one that was used earlier in this chain. The problem with other solutions, is that they will open a window that will be visible to the user (though only for a fraction of a second). The code below will silently enable/disable a network connection.</p>\n<p>The code below can definitely be cleaned up, but this is a nice start.</p>\n<p>*** Please note that it must be run as an administrator to work ***</p>\n<pre><code>//Disable network interface\nstatic public void Disable(string interfaceName)\n{\n System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();\n startInfo.FileName = "netsh";\n startInfo.Arguments = $"interface set interface \\"{interfaceName}\\" disable";\n startInfo.RedirectStandardOutput = true;\n startInfo.RedirectStandardError = true;\n startInfo.UseShellExecute = false;\n startInfo.CreateNoWindow = true;\n System.Diagnostics.Process processTemp = new System.Diagnostics.Process();\n processTemp.StartInfo = startInfo;\n processTemp.EnableRaisingEvents = true;\n try\n {\n processTemp.Start();\n }\n catch (Exception e)\n {\n throw;\n }\n}\n\n//Enable network interface\nstatic public void Enable(string interfaceName)\n{\n System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();\n startInfo.FileName = "netsh";\n startInfo.Arguments = $"interface set interface \\"{interfaceName}\\" enable";\n startInfo.RedirectStandardOutput = true;\n startInfo.RedirectStandardError = true;\n startInfo.UseShellExecute = false;\n startInfo.CreateNoWindow = true;\n System.Diagnostics.Process processTemp = new System.Diagnostics.Process();\n processTemp.StartInfo = startInfo;\n processTemp.EnableRaisingEvents = true;\n try\n {\n processTemp.Start();\n }\n catch (Exception e)\n {\n throw;\n }\n}\n</code></pre>\n"
}
] |
2008/10/05
|
[
"https://Stackoverflow.com/questions/172875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Basically I'm running some performance tests and don't want the external network to be the drag factor. I'm looking into ways of disabling network LAN. What is an effective way of doing it programmatically? I'm interested in c#. If anyone has a code snippet that can drive the point home that would be cool.
|
Found this thread while searching for the same thing, so, here is the answer :)
The best method I tested in C# uses WMI.
<http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx>
[Win32\_NetworkAdapter on msdn](http://msdn.microsoft.com/en-us/library/aa394216)
C# Snippet : (System.Management must be referenced in the solution, and in using declarations)
```
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
```
|
172,888 |
<p>This will hopefully be an easy one. I have an F# project (latest F# CTP) with two files (Program.fs, Stack.fs). In Stack.fs I have a simple namespace and type definition</p>
<p>Stack.fs</p>
<pre><code>namespace Col
type Stack=
...
</code></pre>
<p>Now I try to include the namespace in Program.fs by declaring</p>
<pre><code>open Col
</code></pre>
<p>This doesn't work and gives me the error "The namespace or module Col is not defined." Yet it's defined within the same project. I've got to be missing something obvious</p>
|
[
{
"answer_id": 172896,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 8,
"selected": true,
"text": "<p>What order are the files in the <code>.fsproj</code> file? Stack.fs needs to come before Program.fs for Program.fs to be able to 'see' it.</p>\n<p>See also the start of</p>\n<p><a href=\"http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!444.entry\" rel=\"nofollow noreferrer\">http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!444.entry</a></p>\n<p>and the end of</p>\n<p><a href=\"http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!347.entry\" rel=\"nofollow noreferrer\">http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!347.entry</a></p>\n"
},
{
"answer_id": 212408,
"author": "Jen S.",
"author_id": 28946,
"author_profile": "https://Stackoverflow.com/users/28946",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue and it was indeed the ordering of the files. However, the links above didn't describe how to fix it in Visual Studio 2008 F# 1.9.4.19. </p>\n\n<p>If you open a module, make sure your source file comes <em>after</em> the dependency in the solution explorer. Just right click your source and select Remove. Then re-add it. This will make it appear at the bottom of the list. Hopefully you don't have circular dependencies. </p>\n"
},
{
"answer_id": 1610393,
"author": "Horacio N. Hdez.",
"author_id": 194951,
"author_profile": "https://Stackoverflow.com/users/194951",
"pm_score": 6,
"selected": false,
"text": "<p>I had the same problems, and you are right, the order of the files is taken in account by the compiler. Instead of the Remove and Add pattern, you can use the Move Up / Move Down items in the context menu associated to the .fs files. (Alt-Up and Alt-Down are the shortcut keys in most of the standard key-bindings)</p>\n"
},
{
"answer_id": 30610092,
"author": "Benj Sanders",
"author_id": 3594261,
"author_profile": "https://Stackoverflow.com/users/3594261",
"pm_score": 4,
"selected": false,
"text": "<p>All of the above are correct, but how to do this in VS2013 is another question. I had to edit my <strong>.fsproj</strong> file manually, and set the files in exact order within an ItemGroup node. In this case it would look like this:</p>\n\n<pre><code><ItemGroup>\n <Compile Include=\"Stack.fs\" />\n <Compile Include=\"Program.fs\" />\n <None Include=\"App.config\" />\n</ItemGroup>\n</code></pre>\n"
},
{
"answer_id": 56917736,
"author": "Doug",
"author_id": 142098,
"author_profile": "https://Stackoverflow.com/users/142098",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using Visual Studio for Mac - 8.1.4 and i've noticed that some .fs files are not marked as \"Compile\". You can see this by Viewing Build Output and see if all your files are there and in the correct order.</p>\n\n<p>I've had to manually make sure certain files are marked with \"Compile\", and have had to move them up and down manually until it \"takes\".</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23283/"
] |
This will hopefully be an easy one. I have an F# project (latest F# CTP) with two files (Program.fs, Stack.fs). In Stack.fs I have a simple namespace and type definition
Stack.fs
```
namespace Col
type Stack=
...
```
Now I try to include the namespace in Program.fs by declaring
```
open Col
```
This doesn't work and gives me the error "The namespace or module Col is not defined." Yet it's defined within the same project. I've got to be missing something obvious
|
What order are the files in the `.fsproj` file? Stack.fs needs to come before Program.fs for Program.fs to be able to 'see' it.
See also the start of
<http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!444.entry>
and the end of
<http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!347.entry>
|
172,895 |
<p>Is there any easy way to retrieve table creation DDL from Microsoft Access (2007) or do I have to code it myself using VBA to read the table structure? </p>
<p>I have about 30 tables that we are porting to Oracle and it would make life easier if we could create the tables from the Access definitions.</p>
|
[
{
"answer_id": 172907,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 3,
"selected": false,
"text": "<p>I've done this:</p>\n\n<p>There's a tool for \"upsizing\" from Access to SQL Server. Do that, then use the excellent SQL Server tools to generate the script.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/237980\" rel=\"noreferrer\">http://support.microsoft.com/kb/237980</a></p>\n"
},
{
"answer_id": 172979,
"author": "Gareth",
"author_id": 24352,
"author_profile": "https://Stackoverflow.com/users/24352",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the export feature in Access to export tables to an ODBC data source. Set up an ODBC data source to the Oracle database and then right click the table in the Access \"Tables\" tab and choose export. ODBC is one of the \"file formats\" - it will then bring up the usual ODBC dialog.</p>\n"
},
{
"answer_id": 173027,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 6,
"selected": true,
"text": "<p>Thanks for the other suggestions. While I was waiting I wrote some VBA code to do it. It's not perfect, but did the job for me.</p>\n\n<pre><code>Option Compare Database\nPublic Function TableCreateDDL(TableDef As TableDef) As String\n\n Dim fldDef As Field\n Dim FieldIndex As Integer\n Dim fldName As String, fldDataInfo As String\n Dim DDL As String\n Dim TableName As String\n\n TableName = TableDef.Name\n TableName = Replace(TableName, \" \", \"_\")\n DDL = \"create table \" & TableName & \"(\" & vbCrLf\n With TableDef\n For FieldIndex = 0 To .Fields.Count - 1\n Set fldDef = .Fields(FieldIndex)\n With fldDef\n fldName = .Name\n fldName = Replace(fldName, \" \", \"_\")\n Select Case .Type\n Case dbBoolean\n fldDataInfo = \"nvarchar2\"\n Case dbByte\n fldDataInfo = \"number\"\n Case dbInteger\n fldDataInfo = \"number\"\n Case dbLong\n fldDataInfo = \"number\"\n Case dbCurrency\n fldDataInfo = \"number\"\n Case dbSingle\n fldDataInfo = \"number\"\n Case dbDouble\n fldDataInfo = \"number\"\n Case dbDate\n fldDataInfo = \"date\"\n Case dbText\n fldDataInfo = \"nvarchar2(\" & Format$(.Size) & \")\"\n Case dbLongBinary\n fldDataInfo = \"****\"\n Case dbMemo\n fldDataInfo = \"****\"\n Case dbGUID\n fldDataInfo = \"nvarchar2(16)\"\n End Select\n End With\n If FieldIndex > 0 Then\n DDL = DDL & \", \" & vbCrLf\n End If\n DDL = DDL & \" \" & fldName & \" \" & fldDataInfo\n Next FieldIndex\n End With\n DDL = DDL & \");\"\n TableCreateDDL = DDL\nEnd Function\n\n\nSub ExportAllTableCreateDDL()\n\n Dim lTbl As Long\n Dim dBase As Database\n Dim Handle As Integer\n\n Set dBase = CurrentDb\n\n Handle = FreeFile\n\n Open \"c:\\export\\TableCreateDDL.txt\" For Output Access Write As #Handle\n\n For lTbl = 0 To dBase.TableDefs.Count - 1\n 'If the table name is a temporary or system table then ignore it\n If Left(dBase.TableDefs(lTbl).Name, 1) = \"~\" Or _\n Left(dBase.TableDefs(lTbl).Name, 4) = \"MSYS\" Then\n '~ indicates a temporary table\n 'MSYS indicates a system level table\n Else\n Print #Handle, TableCreateDDL(dBase.TableDefs(lTbl))\n End If\n Next lTbl\n Close Handle\n Set dBase = Nothing\nEnd Sub\n</code></pre>\n\n<p>I never claimed to be VB programmer.</p>\n"
},
{
"answer_id": 173067,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to look into ADOX to get at the schema information. Using ADOX you can get things such as the keys, views, relations, etc.</p>\n\n<p>Unfortunately I am not a VB programmer, but there are plenty of examples on the web using ADOX to get at the table schema.</p>\n"
},
{
"answer_id": 174676,
"author": "Michael OShea",
"author_id": 13178,
"author_profile": "https://Stackoverflow.com/users/13178",
"pm_score": 2,
"selected": false,
"text": "<p>Use Oracle's SQL Developer Migration Workbench.</p>\n\n<p>There's a full tutorial on converting Access databases to Oracle available <a href=\"http://www.oracle.com/technology/products/database/application_express/migrations/tutorial.html\" rel=\"nofollow noreferrer\">here</a>. If its only the structures you're after, then you can concentrate on section 3.0.</p>\n"
},
{
"answer_id": 45739042,
"author": "Stareagle",
"author_id": 8479091,
"author_profile": "https://Stackoverflow.com/users/8479091",
"pm_score": 0,
"selected": false,
"text": "<p>A bit late to the party, but I use RazorSQL to generate DDL for Access databases.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24355/"
] |
Is there any easy way to retrieve table creation DDL from Microsoft Access (2007) or do I have to code it myself using VBA to read the table structure?
I have about 30 tables that we are porting to Oracle and it would make life easier if we could create the tables from the Access definitions.
|
Thanks for the other suggestions. While I was waiting I wrote some VBA code to do it. It's not perfect, but did the job for me.
```
Option Compare Database
Public Function TableCreateDDL(TableDef As TableDef) As String
Dim fldDef As Field
Dim FieldIndex As Integer
Dim fldName As String, fldDataInfo As String
Dim DDL As String
Dim TableName As String
TableName = TableDef.Name
TableName = Replace(TableName, " ", "_")
DDL = "create table " & TableName & "(" & vbCrLf
With TableDef
For FieldIndex = 0 To .Fields.Count - 1
Set fldDef = .Fields(FieldIndex)
With fldDef
fldName = .Name
fldName = Replace(fldName, " ", "_")
Select Case .Type
Case dbBoolean
fldDataInfo = "nvarchar2"
Case dbByte
fldDataInfo = "number"
Case dbInteger
fldDataInfo = "number"
Case dbLong
fldDataInfo = "number"
Case dbCurrency
fldDataInfo = "number"
Case dbSingle
fldDataInfo = "number"
Case dbDouble
fldDataInfo = "number"
Case dbDate
fldDataInfo = "date"
Case dbText
fldDataInfo = "nvarchar2(" & Format$(.Size) & ")"
Case dbLongBinary
fldDataInfo = "****"
Case dbMemo
fldDataInfo = "****"
Case dbGUID
fldDataInfo = "nvarchar2(16)"
End Select
End With
If FieldIndex > 0 Then
DDL = DDL & ", " & vbCrLf
End If
DDL = DDL & " " & fldName & " " & fldDataInfo
Next FieldIndex
End With
DDL = DDL & ");"
TableCreateDDL = DDL
End Function
Sub ExportAllTableCreateDDL()
Dim lTbl As Long
Dim dBase As Database
Dim Handle As Integer
Set dBase = CurrentDb
Handle = FreeFile
Open "c:\export\TableCreateDDL.txt" For Output Access Write As #Handle
For lTbl = 0 To dBase.TableDefs.Count - 1
'If the table name is a temporary or system table then ignore it
If Left(dBase.TableDefs(lTbl).Name, 1) = "~" Or _
Left(dBase.TableDefs(lTbl).Name, 4) = "MSYS" Then
'~ indicates a temporary table
'MSYS indicates a system level table
Else
Print #Handle, TableCreateDDL(dBase.TableDefs(lTbl))
End If
Next lTbl
Close Handle
Set dBase = Nothing
End Sub
```
I never claimed to be VB programmer.
|
172,906 |
<p>I'd like to take XML in the format below and load each code record into a domain object in my <code>BootStrap.groovy</code>. I want to preserve the formatting of each snippet of code. </p>
<h2>XML</h2>
<pre><code><records>
<code>
<language>Groovy</language>
<snippet>
println "This is Groovy"
println "A very powerful language"
</snippet>
</code>
<code>
<language>Groovy</language>
<snippet>
3.times {
println "hello"
}
</snippet>
</code>
<code>
<language>Perl</language>
<snippet>
@foo = split(",");
</snippet>
</code>
</records>
</code></pre>
<h2>Domain Object</h2>
<pre><code>Code {
String language
String snippet
}
</code></pre>
<h2>BootStrap.groovy</h2>
<pre><code>new Code(language l, snippet: x).save()
</code></pre>
|
[
{
"answer_id": 172972,
"author": "mbrevoort",
"author_id": 18228,
"author_profile": "https://Stackoverflow.com/users/18228",
"pm_score": 2,
"selected": true,
"text": "<p>roughly something like this:</p>\n\n<pre><code>def CODE_XML = '''\n<records>\n <code>\n <language>Groovy</language>\n <snippet>\n println \"This is Groovy\"\n println \"A very powerful language\"\n </snippet>\n </code>\n <code>\n <language>Groovy</language>\n <snippet>\n 3.times {\n println \"hello\"\n }\n </snippet>\n </code>\n <code>\n <language>Perl</language>\n <snippet>\n @foo = split(\",\");\n </snippet>\n </code>\n</records>\n '''\ndef records = new XmlParser().parseText(CODE_XML)\nrecords.code.each() { code ->\n new Code(language: code.language, snippet: code.snippet).save()\n}\n</code></pre>\n"
},
{
"answer_id": 172988,
"author": "jfs",
"author_id": 6223,
"author_profile": "https://Stackoverflow.com/users/6223",
"pm_score": 0,
"selected": false,
"text": "<p>If you can specity a DTD or similar and your XML parser obeys it, I think you can specify the contents of the snippet element to be CDATA and always get it as-is.</p>\n"
},
{
"answer_id": 194692,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding <code>xml:space=\"preserve\"</code> attribute to <code><snippet></code> elements.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'd like to take XML in the format below and load each code record into a domain object in my `BootStrap.groovy`. I want to preserve the formatting of each snippet of code.
XML
---
```
<records>
<code>
<language>Groovy</language>
<snippet>
println "This is Groovy"
println "A very powerful language"
</snippet>
</code>
<code>
<language>Groovy</language>
<snippet>
3.times {
println "hello"
}
</snippet>
</code>
<code>
<language>Perl</language>
<snippet>
@foo = split(",");
</snippet>
</code>
</records>
```
Domain Object
-------------
```
Code {
String language
String snippet
}
```
BootStrap.groovy
----------------
```
new Code(language l, snippet: x).save()
```
|
roughly something like this:
```
def CODE_XML = '''
<records>
<code>
<language>Groovy</language>
<snippet>
println "This is Groovy"
println "A very powerful language"
</snippet>
</code>
<code>
<language>Groovy</language>
<snippet>
3.times {
println "hello"
}
</snippet>
</code>
<code>
<language>Perl</language>
<snippet>
@foo = split(",");
</snippet>
</code>
</records>
'''
def records = new XmlParser().parseText(CODE_XML)
records.code.each() { code ->
new Code(language: code.language, snippet: code.snippet).save()
}
```
|
172,916 |
<p>I have develop an XNA game on computer 1. When I send it to computer two (and I have everything to be able to run XNA Code). When the program execute game.run, I get an InvalidOperationException. </p>
<p>I didn't tried to run code from computer two on computer one. But I know that both machine can run the code I've wrote on them.</p>
<p>Do you have any idea ?</p>
<p>EDIT : Oh, I added the asnwer, but I can't select my post as the answer...</p>
<hr>
<p>CallStack : </p>
<blockquote>
<p>App.exe!App.Program.Main(string[] args = {Dimensions:[0]}) Line 14 C#</p>
</blockquote>
<p>And here is the code</p>
<pre><code>static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
</code></pre>
<p>And the same code run on another machine</p>
|
[
{
"answer_id": 172927,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 0,
"selected": false,
"text": "<p>The docs say Game.Run will throw that exception if Game.Run is called more than once. What does the rest of the exception say? i.e. Message, StackTrace, etc?</p>\n"
},
{
"answer_id": 172941,
"author": "Ryan Taylor",
"author_id": 6231,
"author_profile": "https://Stackoverflow.com/users/6231",
"pm_score": 0,
"selected": false,
"text": "<p>My first question would be, what is the rest of the error? Without that it'll be hard to diagnose this. If I were to give an educated guess, I'd have to say you either don't have the proper XNA runtimes installed, or your video card doesn't support Shader Model 2.0.</p>\n"
},
{
"answer_id": 178355,
"author": "Ross Anderson",
"author_id": 1601,
"author_profile": "https://Stackoverflow.com/users/1601",
"pm_score": 0,
"selected": false,
"text": "<p>Are there any .dll files that you need to package with the project that the other computer may be missing? <a href=\"http://www.dependencywalker.com/\" rel=\"nofollow noreferrer\">Dependency Walker</a> might be useful for determining which (if any) these are.</p>\n"
},
{
"answer_id": 178360,
"author": "Patrick Parent",
"author_id": 23141,
"author_profile": "https://Stackoverflow.com/users/23141",
"pm_score": 3,
"selected": true,
"text": "<p>I finally found the problem. For a reason, the hardware acceleration setting was set to None. So the project wouldn't start. </p>\n\n<p>Thanks for all your reply.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23141/"
] |
I have develop an XNA game on computer 1. When I send it to computer two (and I have everything to be able to run XNA Code). When the program execute game.run, I get an InvalidOperationException.
I didn't tried to run code from computer two on computer one. But I know that both machine can run the code I've wrote on them.
Do you have any idea ?
EDIT : Oh, I added the asnwer, but I can't select my post as the answer...
---
CallStack :
>
> App.exe!App.Program.Main(string[] args = {Dimensions:[0]}) Line 14 C#
>
>
>
And here is the code
```
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
```
And the same code run on another machine
|
I finally found the problem. For a reason, the hardware acceleration setting was set to None. So the project wouldn't start.
Thanks for all your reply.
|
172,918 |
<p>I have a container div that holds two internal divs; both should take 100% width and 100% height within the container.</p>
<p>I set both internal divs to 100% height. That works fine in Firefox, however in IE the divs do not stretch to 100% height but only the height of the text inside them.</p>
<p>The following is a simplified version of my style sheet.</p>
<pre><code>#container
{
height: auto;
width: 100%;
}
#container #mainContentsWrapper
{
float: left;
height: 100%;
width: 70%;
margin: 0;
padding: 0;
}
#container #sidebarWrapper
{
float: right;
height: 100%;
width: 29.7%;
margin: 0;
padding: 0;
}
</code></pre>
<p>Is there something I am doing wrong? Or any Firefox/IE quirks I am missing out?</p>
|
[
{
"answer_id": 172923,
"author": "Jarett Millard",
"author_id": 15882,
"author_profile": "https://Stackoverflow.com/users/15882",
"pm_score": 1,
"selected": false,
"text": "<p>You might have to put one or both of:</p>\n\n<pre><code>html { height:100%; }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>body { height:100%; }\n</code></pre>\n\n<p>EDIT: Whoops, didn't notice they were floated. You just need to float the container.</p>\n"
},
{
"answer_id": 172987,
"author": "bryansh",
"author_id": 211367,
"author_profile": "https://Stackoverflow.com/users/211367",
"pm_score": 2,
"selected": false,
"text": "<p>Its hard to give you a good answer, without seeing the html that you are actually using.</p>\n\n<p>Are you outputting a doctype / using standards mode rendering? Without actually being able to look into a html repro, that would be my first guess for a html interpretation difference between firefox and internet explorer.</p>\n"
},
{
"answer_id": 172999,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean \"make it the size needed to fully contain the content\" when what you really want is \"make both the size of the largest content.\"</p>\n\n<p>Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.</p>\n"
},
{
"answer_id": 174208,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).</p>\n\n<p>Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:</p>\n\n<pre><code>#container {\n height:100%;\n width:100%;\n overflow:hidden;\n /* for IE */\n zoom:1;\n}\n</code></pre>\n"
},
{
"answer_id": 174271,
"author": "Matt Refghi",
"author_id": 21263,
"author_profile": "https://Stackoverflow.com/users/21263",
"pm_score": 1,
"selected": false,
"text": "<p>I've done something very similar to what 'tvanfosson' said, that is, actually using JavaScript to constantly monitor the available height in the window via events like onresize, and use that information to change the container size accordingly (as pixels rather than percentage). </p>\n\n<p>Keep in mind, this <strong>does</strong> mean a JavaScript dependency, and it isn't as smooth as a CSS solution. You'd also need to ensure that the JavaScript function is capable of <em>correctly</em> returning the window dimensions across all major browsers.</p>\n\n<p>Let us know if one of the previously mentioned CSS solutions work, as it sounds like a better way to fix the problem.</p>\n"
},
{
"answer_id": 174611,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 2,
"selected": false,
"text": "<p>I've been successful in getting this to work when I set the margins of the container to 0:</p>\n\n<pre><code>#container\n{\n margin: 0 px;\n}\n</code></pre>\n\n<p>in addition to all your other styles</p>\n"
},
{
"answer_id": 176454,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>I think \"works fine in Firefox\" is in the <strong>Quirks mode</strong> rendering only.\nIn the <strong>Standard mode</strong> rendering, that might not work fine in Firefox too.</p>\n\n<p>percentage depends on \"containing block\", instead of viewport.</p>\n\n<p><a href=\"http://www.w3.org/TR/CSS21/visudet.html#the-height-property\" rel=\"noreferrer\">CSS Specification says</a></p>\n\n<blockquote>\n <p>The percentage is calculated with\n respect to the height of the generated\n box's containing block. If the height\n of the containing block is not\n specified explicitly (i.e., it depends\n on content height), and this element\n is not absolutely positioned, the\n value computes to 'auto'.</p>\n</blockquote>\n\n<p>so</p>\n\n<pre><code>#container { height: auto; }\n#container #mainContentsWrapper { height: n%; }\n#container #sidebarWrapper { height: n%; }\n</code></pre>\n\n<p>means</p>\n\n<pre><code>#container { height: auto; }\n#container #mainContentsWrapper { height: auto; }\n#container #sidebarWrapper { height: auto; }\n</code></pre>\n\n<p>To stretch to 100% height of viewport, you need to specify the height of the containing block (in this case, it's #container).\nMoreover, you also need to specify the height to body and html, because initial Containing Block is \"UA-dependent\".</p>\n\n<p>All you need is...</p>\n\n<pre><code>html, body { height:100%; }\n#container { height:100%; }\n</code></pre>\n"
},
{
"answer_id": 1906711,
"author": "Designerfoo",
"author_id": 232030,
"author_profile": "https://Stackoverflow.com/users/232030",
"pm_score": 0,
"selected": false,
"text": "<p>Try this.. </p>\n\n<pre><code>#container\n{\n height: auto;\n min-height:100%;\n width: 100%;\n}\n\n#container #mainContentsWrapper\n{\n float: left;\n\n height: auto;\n min-height:100%\n width: 70%;\n margin: 0;\n padding: 0;\n}\n\n\n#container #sidebarWrapper\n{ \n float: right;\n\n height: auto;\n min-height:100%\n width: 29.7%;\n margin: 0;\n padding: 0;\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
] |
I have a container div that holds two internal divs; both should take 100% width and 100% height within the container.
I set both internal divs to 100% height. That works fine in Firefox, however in IE the divs do not stretch to 100% height but only the height of the text inside them.
The following is a simplified version of my style sheet.
```
#container
{
height: auto;
width: 100%;
}
#container #mainContentsWrapper
{
float: left;
height: 100%;
width: 70%;
margin: 0;
padding: 0;
}
#container #sidebarWrapper
{
float: right;
height: 100%;
width: 29.7%;
margin: 0;
padding: 0;
}
```
Is there something I am doing wrong? Or any Firefox/IE quirks I am missing out?
|
I think "works fine in Firefox" is in the **Quirks mode** rendering only.
In the **Standard mode** rendering, that might not work fine in Firefox too.
percentage depends on "containing block", instead of viewport.
[CSS Specification says](http://www.w3.org/TR/CSS21/visudet.html#the-height-property)
>
> The percentage is calculated with
> respect to the height of the generated
> box's containing block. If the height
> of the containing block is not
> specified explicitly (i.e., it depends
> on content height), and this element
> is not absolutely positioned, the
> value computes to 'auto'.
>
>
>
so
```
#container { height: auto; }
#container #mainContentsWrapper { height: n%; }
#container #sidebarWrapper { height: n%; }
```
means
```
#container { height: auto; }
#container #mainContentsWrapper { height: auto; }
#container #sidebarWrapper { height: auto; }
```
To stretch to 100% height of viewport, you need to specify the height of the containing block (in this case, it's #container).
Moreover, you also need to specify the height to body and html, because initial Containing Block is "UA-dependent".
All you need is...
```
html, body { height:100%; }
#container { height:100%; }
```
|
172,921 |
<p>In order to create an arbitrary precision floating point / drop in replacement for Double, I'm trying to wrap <a href="http://www.mpfr.org/" rel="nofollow noreferrer">MPFR</a> using the FFI but despite all my efforts the simplest bit of code doesn't work. It compiles, it runs, but it crashes mockingly after pretending to work for a while. A simple C version of the code happily prints the number "1" to (640 decimal places) a total of 10,000 times. The Haskell version, when asked to do the same, silently corrupts (?) the data after only 289 print outs of "1.0000...0000" and after 385 print outs, it causes an assertion failure and bombs. I'm at a loss for how to proceed in debugging this since it "should work".</p>
<p>The code can be perused at <a href="http://hpaste.org/10923" rel="nofollow noreferrer">http://hpaste.org/10923</a> and downloaded at <a href="http://www.updike.org/mpfr-broken.tar.gz" rel="nofollow noreferrer">http://www.updike.org/mpfr-broken.tar.gz</a></p>
<p>I'm using GHC 6.83 on FreeBSD 6 and GHC 6.8.2 on Mac OS X. Note you will need MPFR (tested with 2.3.2) installed with the correct paths (change the Makefile) for libs and header files (along with those from GMP) to successfully compile this.</p>
<h2>Questions</h2>
<ul>
<li><p>Why does the C version work, but the Haskell version flake out? What else am I missing when approaching the FFI? I tried StablePtrs and had the exact same results.</p></li>
<li><p>Can someone else verify if this is a Mac/BSD only problem by compiling and running my code? (Does the C code "works" work? Does the Haskell code "noworks" work?) Can anyone on Linux and Windows attempt to compile/run and see if you get the same results?</p></li>
</ul>
<p>C code: (works.c)</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
#include <mpfr.h>
#include "mpfr_ffi.c"
int main()
{
int i;
mpfr_ptr one;
mpf_set_default_prec_decimal(640);
one = mpf_set_signed_int(1);
for (i = 0; i < 10000; i++)
{
printf("%d\n", i);
mpf_show(one);
}
}
</code></pre>
<p>Haskell code: (Main.hs --- doesn't work)</p>
<pre><code>module Main where
import Foreign.Ptr ( Ptr, FunPtr )
import Foreign.C.Types ( CInt, CLong, CULong, CDouble )
import Foreign.StablePtr ( StablePtr )
data MPFR = MPFR
foreign import ccall "mpf_set_default_prec_decimal"
c_set_default_prec_decimal :: CInt -> IO ()
setPrecisionDecimal :: Integer -> IO ()
setPrecisionDecimal decimal_digits = do
c_set_default_prec_decimal (fromInteger decimal_digits)
foreign import ccall "mpf_show"
c_show :: Ptr MPFR -> IO ()
foreign import ccall "mpf_set_signed_int"
c_set_signed_int :: CLong -> IO (Ptr MPFR)
showNums k n = do
print n
c_show k
main = do
setPrecisionDecimal 640
one <- c_set_signed_int (fromInteger 1)
mapM_ (showNums one) [1..10000]
</code></pre>
|
[
{
"answer_id": 173181,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 2,
"selected": false,
"text": "<p>Judah Jacobsen answered this on the Haskell-cafe mailing list:</p>\n\n<p>This is <a href=\"http://hackage.haskell.org/trac/ghc/ticket/311\" rel=\"nofollow noreferrer\">a known issue with GHC</a> because of the way GHC uses GMP internally (to maintain Integers).</p>\n\n<p>Apparently C data in the heap is left alone by GHC in basically all cases <em>except</em> code that uses the FFI to access GMP or any C library that relies on GMP (like MPFR that I wanted to use). There are some workarounds (painful) but the \"right\" way would be to either hack GHC (hard) or get the Simons to remove GHC's dependence on GMP (harder).</p>\n"
},
{
"answer_id": 173249,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": true,
"text": "<p>I see the problem too, on a</p>\n\n<pre><code>$ uname -a\nLinux burnup 2.6.26-gentoo-r1 #1 SMP PREEMPT Tue Sep 9 00:05:54 EDT 2008 i686 Intel(R) Pentium(R) 4 CPU 2.80GHz GenuineIntel GNU/Linux\n$ gcc --version\ngcc (GCC) 4.2.4 (Gentoo 4.2.4 p1.0)\n$ ghc --version\nThe Glorious Glasgow Haskell Compilation System, version 6.8.3\n</code></pre>\n\n<p>I also see the output changing from 1.0000...000 to 1.0000...[garbage].</p>\n\n<p>Let's see, the following does work:</p>\n\n<pre><code>main = do\n setPrecisionDecimal 640\n mapM_ (const $ c_set_signed_int (fromInteger 1) >>= c_show) [1..10000]\n</code></pre>\n\n<p>which narrows down the problem to parts of <code>one</code> being somehow clobbered during runtime. Looking at the output of <code>ghc -C</code> and <code>ghc -S</code>, though, isn't giving me any hints.</p>\n\n<p>Hmm, <code>./noworks +RTS -H1G</code> also works, and <code>./noworks +RTS -k[n]k</code>, for varying values of <code>[n]</code>, demonstrate failures in different ways.</p>\n\n<p>I've got no solid leads, but there are two possibilities that jump to my mind:</p>\n\n<ul>\n<li>GMP, which the GHC runtime uses, and MPFR having some weird interaction</li>\n<li>stack space for C functions called within the GHC runtime is limited, and MPFR not dealing well</li>\n</ul>\n\n<p>That being said... is there a reason you're rolling your own bindings rather than use <a href=\"http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmpfr\" rel=\"nofollow noreferrer\">HMPFR</a>?</p>\n"
},
{
"answer_id": 175490,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 1,
"selected": false,
"text": "<p>Aleš Bizjak, maintainer of <a href=\"http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmpfr\" rel=\"nofollow noreferrer\">HMPFR</a> posted to haskell-cafe and showed how to keep GHC from controlling allocation of the limbs (and hence leaving them alone, instead of GCing them and clobbering them):</p>\n\n<pre><code>mpfr_ptr mpf_new_mpfr() \n{ \n mpfr_ptr result = malloc(sizeof(__mpfr_struct)); \n if (result == NULL) return NULL; \n /// these three lines: \n mp_limb_t * limb = malloc(mpfr_custom_get_size(mpfr_get_default_prec())); \n mpfr_custom_init(limb, mpfr_get_default_prec()); \n mpfr_custom_init_set(result, MPFR_NAN_KIND, 0, mpfr_get_default_prec(), limb); \n return result; \n}\n</code></pre>\n\n<p>To me, this is much easier than joining the effort to write a replacement for GMP in GHC, which would be the only alternative if I really wanted to use any library that depends on GMP.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] |
In order to create an arbitrary precision floating point / drop in replacement for Double, I'm trying to wrap [MPFR](http://www.mpfr.org/) using the FFI but despite all my efforts the simplest bit of code doesn't work. It compiles, it runs, but it crashes mockingly after pretending to work for a while. A simple C version of the code happily prints the number "1" to (640 decimal places) a total of 10,000 times. The Haskell version, when asked to do the same, silently corrupts (?) the data after only 289 print outs of "1.0000...0000" and after 385 print outs, it causes an assertion failure and bombs. I'm at a loss for how to proceed in debugging this since it "should work".
The code can be perused at <http://hpaste.org/10923> and downloaded at <http://www.updike.org/mpfr-broken.tar.gz>
I'm using GHC 6.83 on FreeBSD 6 and GHC 6.8.2 on Mac OS X. Note you will need MPFR (tested with 2.3.2) installed with the correct paths (change the Makefile) for libs and header files (along with those from GMP) to successfully compile this.
Questions
---------
* Why does the C version work, but the Haskell version flake out? What else am I missing when approaching the FFI? I tried StablePtrs and had the exact same results.
* Can someone else verify if this is a Mac/BSD only problem by compiling and running my code? (Does the C code "works" work? Does the Haskell code "noworks" work?) Can anyone on Linux and Windows attempt to compile/run and see if you get the same results?
C code: (works.c)
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
#include <mpfr.h>
#include "mpfr_ffi.c"
int main()
{
int i;
mpfr_ptr one;
mpf_set_default_prec_decimal(640);
one = mpf_set_signed_int(1);
for (i = 0; i < 10000; i++)
{
printf("%d\n", i);
mpf_show(one);
}
}
```
Haskell code: (Main.hs --- doesn't work)
```
module Main where
import Foreign.Ptr ( Ptr, FunPtr )
import Foreign.C.Types ( CInt, CLong, CULong, CDouble )
import Foreign.StablePtr ( StablePtr )
data MPFR = MPFR
foreign import ccall "mpf_set_default_prec_decimal"
c_set_default_prec_decimal :: CInt -> IO ()
setPrecisionDecimal :: Integer -> IO ()
setPrecisionDecimal decimal_digits = do
c_set_default_prec_decimal (fromInteger decimal_digits)
foreign import ccall "mpf_show"
c_show :: Ptr MPFR -> IO ()
foreign import ccall "mpf_set_signed_int"
c_set_signed_int :: CLong -> IO (Ptr MPFR)
showNums k n = do
print n
c_show k
main = do
setPrecisionDecimal 640
one <- c_set_signed_int (fromInteger 1)
mapM_ (showNums one) [1..10000]
```
|
I see the problem too, on a
```
$ uname -a
Linux burnup 2.6.26-gentoo-r1 #1 SMP PREEMPT Tue Sep 9 00:05:54 EDT 2008 i686 Intel(R) Pentium(R) 4 CPU 2.80GHz GenuineIntel GNU/Linux
$ gcc --version
gcc (GCC) 4.2.4 (Gentoo 4.2.4 p1.0)
$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 6.8.3
```
I also see the output changing from 1.0000...000 to 1.0000...[garbage].
Let's see, the following does work:
```
main = do
setPrecisionDecimal 640
mapM_ (const $ c_set_signed_int (fromInteger 1) >>= c_show) [1..10000]
```
which narrows down the problem to parts of `one` being somehow clobbered during runtime. Looking at the output of `ghc -C` and `ghc -S`, though, isn't giving me any hints.
Hmm, `./noworks +RTS -H1G` also works, and `./noworks +RTS -k[n]k`, for varying values of `[n]`, demonstrate failures in different ways.
I've got no solid leads, but there are two possibilities that jump to my mind:
* GMP, which the GHC runtime uses, and MPFR having some weird interaction
* stack space for C functions called within the GHC runtime is limited, and MPFR not dealing well
That being said... is there a reason you're rolling your own bindings rather than use [HMPFR](http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmpfr)?
|
172,934 |
<p>I need to retrieve a set of Widgets from my data access layer, grouped by widget.Manufacturer, to display in a set of nested ASP.NET ListViews.</p>
<p>The problem is that (as far as I can tell) the nested ListView approach requires me to shape the data before using it, and I can't figure out the best approach to take. The best I've been able to come up with so far is to put a LINQ query in my data access layer like so:</p>
<pre><code>var result = from widget in GetAllWidgets(int widgetTypeID)
group widget by widget.Manufacturer into groupedWidgets
let widgets = from widgetGroup in groupedWidgets
select widgetGroup
select new { Manufacturer = groupedWidgets.Key, Widgets = widgets };
</code></pre>
<p>Of course, anonymous types can't be passed around, so that doesn't work. Defining a custom class to enclose data seems like the wrong way to go. Is there some way I can perform the grouping on the ASP.NET side of things? I'm using ObjectDataSources to access the DAL.</p>
<p><b>Updated</b>: OK, I'm not creating an anonymous type anymore, and instead my DAL passes an <code>IEnumerable<IGrouping<Manufacturer, Widget>></code> to the ASP.NET page, but how can I use this in my ListViews? I need to render the following HTML (or something pretty much like it)</p>
<pre><code><ul>
<li>Foo Corp.
<ol>
<li>Baz</li>
<li>Quux</li>
</ol>
</li>
<li>Bar Corp.
<ol>
<li>Thinger</li>
<li>Whatsit</li>
</ol>
</li>
</ul>
</code></pre>
<p>Originally, I had a ListView within a ListView like so:</p>
<pre><code><asp:ListView ID="ManufacturerListView">
<LayoutTemplate>
<ul>
<asp:Placeholder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Label Text='<%# Eval("Manufacturer.Name") %>' />
<li>
<asp:ListView ID="WidgetsListView" runat="server" DataSource='<%# Eval("Widgets") %>'>
<LayoutTemplate>
<ol>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</ol>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Label Text='<%# Eval("Name") %>'></li>
</ItemTemplate>
</asp:ListView>
</li>
</ItemTemplate>
</asp:ListView>
</code></pre>
<p>Note how the <code>DataSource</code> property of WidgetsListView is itself databound. How can I duplicate this functionality without reshaping the data?</p>
<p>This is getting kind of complicated, sorry if I should have just made a separate question instead.</p>
|
[
{
"answer_id": 173177,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<p>When you're using Linq to group, you can get a strongly typed object without that shaping:</p>\n\n<pre><code>List<int> myInts = new List<int>() { 1, 2, 3, 4, 5 };\nIEnumerable<IGrouping<int, int>> myGroups = myInts.GroupBy(i => i % 2);\nforeach (IGrouping<int, int> g in myGroups)\n{\n Console.WriteLine(g.Key);\n foreach (int i in g)\n {\n Console.WriteLine(\" {0}\", i);\n }\n}\nConsole.ReadLine();\n</code></pre>\n\n<p>In your case, you'd have:</p>\n\n<pre><code> IEnumerable<IGrouping<Manufacturer, Widget>> result =\n GetAllWidgets(widgetTypeId).GroupBy(w => w.Manufacturer);\n</code></pre>\n\n<p>This will let you return the result from the method.</p>\n"
},
{
"answer_id": 177279,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, I'm going to contradict my prior statement. Since eval wants some kind of property name in the nested control, we should probably shape that data.</p>\n\n<pre><code>public class CustomGroup<TKey, TValue>\n{\n public TKey Key {get;set;}\n public IEnumerable<TValue> Values {get;set;}\n}\n</code></pre>\n\n<p>// and use it thusly...</p>\n\n<pre><code>IEnumerable<CustomGroup<Manufacturer, Widget>> result =\n GetAllWidgets(widgetTypeId)\n .GroupBy(w => w.Manufacturer)\n .Select(g => new CustomGroup<Manufacturer, Widget>(){Key = g.Key, Values = g};\n</code></pre>\n\n<p>/// and even later...</p>\n\n<pre><code><asp:ListView ID=\"ManufacturerListView\">\n<LayoutTemplate>\n <ul>\n <asp:Placeholder ID=\"itemPlaceholder\" runat=\"server\" />\n </ul>\n</LayoutTemplate>\n<ItemTemplate>\n <li><asp:Label Text='<%# Eval(\"Key.Name\") %>' />\n <li>\n <asp:ListView ID=\"WidgetsListView\" runat=\"server\" DataSource='<%# Eval(\"Values\") %>'>\n <LayoutTemplate>\n <ol>\n <asp:PlaceHolder runat=\"server\" ID=\"itemPlaceholder\" />\n </ol>\n </LayoutTemplate>\n <ItemTemplate>\n <li><asp:Label Text='<%# Eval(\"Name\") %>'></li>\n </ItemTemplate>\n </asp:ListView>\n </li>\n</ItemTemplate>\n</asp:ListView>\n</code></pre>\n"
},
{
"answer_id": 1304807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I've just spent quite a while on this. Eventually found the solution and it's so simple.</p>\n\n<hr>\n\n<pre><code>var enumerableData = myData.Tables[0].AsEnumerable();\nvar groupedData = enumerableData.GroupBy(x => x[\"GroupingColumn\"]);\n\nmyParentRepeater.DataSource = groupedData;\nmyParentRepeater.DataBind();\n</code></pre>\n\n<hr>\n\n<pre><code><asp:Repeater ID=\"myParentRepeater\" runat=\"server\">\n <ItemTemplate>\n <h3><%#Eval(\"Key\") %></h3>\n <asp:Repeater ID=\"myChildRepeater\" runat=\"server\" DataSource='<%# Container.DataItem %>'>\n <ItemTemplate>\n <%#((DataRow)Container.DataItem)[\"ChildDataColumn1\"] %>\n <%#((DataRow)Container.DataItem)[\"ChildDataColumn2\"] %>\n </ItemTemplate>\n <SeparatorTemplate>\n <br />\n </SeparatorTemplate>\n </asp:Repeater>\n </ItemTemplate>\n</asp:Repeater>\n</code></pre>\n\n<hr>\n\n<p>Eval(\"Key\") returns the grouped value.\nWhen retrieving child info, Container.DataItem is of type IGrouping but you simply cast it to the correct type.</p>\n\n<p>Hope this helps someone else.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160/"
] |
I need to retrieve a set of Widgets from my data access layer, grouped by widget.Manufacturer, to display in a set of nested ASP.NET ListViews.
The problem is that (as far as I can tell) the nested ListView approach requires me to shape the data before using it, and I can't figure out the best approach to take. The best I've been able to come up with so far is to put a LINQ query in my data access layer like so:
```
var result = from widget in GetAllWidgets(int widgetTypeID)
group widget by widget.Manufacturer into groupedWidgets
let widgets = from widgetGroup in groupedWidgets
select widgetGroup
select new { Manufacturer = groupedWidgets.Key, Widgets = widgets };
```
Of course, anonymous types can't be passed around, so that doesn't work. Defining a custom class to enclose data seems like the wrong way to go. Is there some way I can perform the grouping on the ASP.NET side of things? I'm using ObjectDataSources to access the DAL.
**Updated**: OK, I'm not creating an anonymous type anymore, and instead my DAL passes an `IEnumerable<IGrouping<Manufacturer, Widget>>` to the ASP.NET page, but how can I use this in my ListViews? I need to render the following HTML (or something pretty much like it)
```
<ul>
<li>Foo Corp.
<ol>
<li>Baz</li>
<li>Quux</li>
</ol>
</li>
<li>Bar Corp.
<ol>
<li>Thinger</li>
<li>Whatsit</li>
</ol>
</li>
</ul>
```
Originally, I had a ListView within a ListView like so:
```
<asp:ListView ID="ManufacturerListView">
<LayoutTemplate>
<ul>
<asp:Placeholder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Label Text='<%# Eval("Manufacturer.Name") %>' />
<li>
<asp:ListView ID="WidgetsListView" runat="server" DataSource='<%# Eval("Widgets") %>'>
<LayoutTemplate>
<ol>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</ol>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Label Text='<%# Eval("Name") %>'></li>
</ItemTemplate>
</asp:ListView>
</li>
</ItemTemplate>
</asp:ListView>
```
Note how the `DataSource` property of WidgetsListView is itself databound. How can I duplicate this functionality without reshaping the data?
This is getting kind of complicated, sorry if I should have just made a separate question instead.
|
Ok, I'm going to contradict my prior statement. Since eval wants some kind of property name in the nested control, we should probably shape that data.
```
public class CustomGroup<TKey, TValue>
{
public TKey Key {get;set;}
public IEnumerable<TValue> Values {get;set;}
}
```
// and use it thusly...
```
IEnumerable<CustomGroup<Manufacturer, Widget>> result =
GetAllWidgets(widgetTypeId)
.GroupBy(w => w.Manufacturer)
.Select(g => new CustomGroup<Manufacturer, Widget>(){Key = g.Key, Values = g};
```
/// and even later...
```
<asp:ListView ID="ManufacturerListView">
<LayoutTemplate>
<ul>
<asp:Placeholder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Label Text='<%# Eval("Key.Name") %>' />
<li>
<asp:ListView ID="WidgetsListView" runat="server" DataSource='<%# Eval("Values") %>'>
<LayoutTemplate>
<ol>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</ol>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Label Text='<%# Eval("Name") %>'></li>
</ItemTemplate>
</asp:ListView>
</li>
</ItemTemplate>
</asp:ListView>
```
|
172,935 |
<p>After understanding (quote), I'm curious as to how one might cause the statement to execute. My first thought was</p>
<pre><code>(defvar x '(+ 2 21))
`(,@x)
</code></pre>
<p>but that just evaluates to <code>(+ 2 21)</code>, or the contents of <code>x</code>. How would one run code that was placed in a list?</p>
|
[
{
"answer_id": 172939,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 5,
"selected": true,
"text": "<p><code>(eval '(+ 2 21))</code></p>\n"
},
{
"answer_id": 175970,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 0,
"selected": false,
"text": "<p>@Christián Romo:</p>\n\n<p>Backtick example: you can kinda implement apply using eval and backtick, because you can splice arguments into a form. Not going to be the most efficient thing in the world, but:</p>\n\n<pre><code>(eval `(and ,@(loop for x from 1 upto 4 collect `(evenp ,x))))\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>(eval '(and (evenp 1) (evenp 2) (evenp 3) (evenp 4)))\n</code></pre>\n\n<p>Incidentally, this has the same result as the (much more efficient)</p>\n\n<pre><code>(every 'evenp '(1 2 3 4))\n</code></pre>\n\n<p>Hope that satisfies your curiosity!</p>\n"
},
{
"answer_id": 295479,
"author": "Anton Nazarov",
"author_id": 38204,
"author_profile": "https://Stackoverflow.com/users/38204",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at funny Lisp tutorial at <a href=\"http://lisperati.com/\" rel=\"nofollow noreferrer\">http://lisperati.com/</a>. There are versions for Common Lisp and Emacs Lisp, and it demonstrates use of quasiquote and macros.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256/"
] |
After understanding (quote), I'm curious as to how one might cause the statement to execute. My first thought was
```
(defvar x '(+ 2 21))
`(,@x)
```
but that just evaluates to `(+ 2 21)`, or the contents of `x`. How would one run code that was placed in a list?
|
`(eval '(+ 2 21))`
|
172,948 |
<p>Anyone have any idea how to do the following?</p>
<p>declare cursor
open cursor
fetch cursor
<< Start reading the cursor in a LOOP >>
Lets say the cursor have 10 records.
Read until 5th record then go to the 6th record and do some checking.</p>
<p>Now, is it possible to go back to 5th record from 6th record ?</p>
|
[
{
"answer_id": 172953,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 0,
"selected": false,
"text": "<p>How far do you need to go back? If you only need a look-ahead of one row, you could buffer just the previous row in your loop (application-side).</p>\n"
},
{
"answer_id": 173036,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 3,
"selected": false,
"text": "<p>Depends on the requirements.</p>\n\n<p>You can use the LAG() and LEAD() analytic functions to get information for the next and prior rows, i.e.</p>\n\n<pre><code>SQL> ed\nWrote file afiedt.buf\n\n 1 select ename,\n 2 sal,\n 3 lead(sal) over (order by ename) next_sal,\n 4 lag(sal) over (order by ename) prior_sal\n 5 from emp\n 6* order by ename\nSQL> /\n\nENAME SAL NEXT_SAL PRIOR_SAL\n---------- ---------- ---------- ----------\nADAMS 1100 1600\nALLEN 1600 2850 1100\nBLAKE 2850 2450 1600\nCLARK 2450 3000 2850\nFORD 3000 950 2450\nJAMES 950 2975 3000\nJONES 2975 5000 950\nKING 5000 1250 2975\nMARTIN 1250 1300 5000\nMILLER 1300 3000 1250\nSCOTT 3000 800 1300\n\nENAME SAL NEXT_SAL PRIOR_SAL\n---------- ---------- ---------- ----------\nSMITH 800 1500 3000\nTURNER 1500 1250 800\nWARD 1250 1500\n\n14 rows selected.\n</code></pre>\n\n<p>If you don't want to use analytic functions, you can use PL/SQL collections, BULK COLLECT the data into those collections (using the LIMIT clause if you have more data than you want to store in your PGA) and then move forward and backward through your collections.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
Anyone have any idea how to do the following?
declare cursor
open cursor
fetch cursor
<< Start reading the cursor in a LOOP >>
Lets say the cursor have 10 records.
Read until 5th record then go to the 6th record and do some checking.
Now, is it possible to go back to 5th record from 6th record ?
|
Depends on the requirements.
You can use the LAG() and LEAD() analytic functions to get information for the next and prior rows, i.e.
```
SQL> ed
Wrote file afiedt.buf
1 select ename,
2 sal,
3 lead(sal) over (order by ename) next_sal,
4 lag(sal) over (order by ename) prior_sal
5 from emp
6* order by ename
SQL> /
ENAME SAL NEXT_SAL PRIOR_SAL
---------- ---------- ---------- ----------
ADAMS 1100 1600
ALLEN 1600 2850 1100
BLAKE 2850 2450 1600
CLARK 2450 3000 2850
FORD 3000 950 2450
JAMES 950 2975 3000
JONES 2975 5000 950
KING 5000 1250 2975
MARTIN 1250 1300 5000
MILLER 1300 3000 1250
SCOTT 3000 800 1300
ENAME SAL NEXT_SAL PRIOR_SAL
---------- ---------- ---------- ----------
SMITH 800 1500 3000
TURNER 1500 1250 800
WARD 1250 1500
14 rows selected.
```
If you don't want to use analytic functions, you can use PL/SQL collections, BULK COLLECT the data into those collections (using the LIMIT clause if you have more data than you want to store in your PGA) and then move forward and backward through your collections.
|
172,957 |
<p>I just set up my new homepage at <a href="http://ritter.vg" rel="noreferrer">http://ritter.vg</a>. I'm using jQuery, but very minimally.<br>
It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL. </p>
<pre><code> //general functions
function getUrl(u) {
return u + '.html';
}
function loadURL(u) {
$.get(getUrl(u), function(r){
$('#main').html(r);
}
);
}
//allows bookmarking
var hash = new String(document.location).indexOf("#");
if(hash > 0)
{
page = new String(document.location).substring(hash + 1);
if(page.length > 1)
loadURL(page);
else
loadURL('news');
}
else
loadURL('news');
</code></pre>
<p>But I can't get the back and forward buttons to work. </p>
<p>Is there a way to detect when the back button has been pressed (or detect when the hash changes) without using a setInterval loop? When I tried those with .2 and 1 second timeouts, it pegged my CPU.</p>
|
[
{
"answer_id": 173075,
"author": "Komang",
"author_id": 19463,
"author_profile": "https://Stackoverflow.com/users/19463",
"pm_score": 6,
"selected": true,
"text": "<p>Use the <a href=\"https://github.com/cowboy/jquery-hashchange\" rel=\"noreferrer\">jQuery hashchange event</a> plugin instead. Regarding your full ajax navigation, try to have <a href=\"http://www.chazzuka.com/blog/?p=90\" rel=\"noreferrer\">SEO friendly ajax</a>. Otherwise your pages shown nothing in browsers with JavaScript limitations.</p>\n"
},
{
"answer_id": 2193599,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://benalman.com/projects/jquery-bbq-plugin/\" rel=\"noreferrer\"><strong>jQuery BBQ</strong> (Back Button & Query Library)</a></p>\n\n<p>A high quality hash-based browser history plugin and very much <a href=\"http://benalman.com/news/2010/01/jquery-bbq-v111-also-bbq-jquer/\" rel=\"noreferrer\">up-to-date (Jan 26, 2010) as of this writing (jQuery 1.4.1)</a>.</p>\n"
},
{
"answer_id": 3591783,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 2,
"selected": false,
"text": "<p>Another great implementation is balupton's <a href=\"https://github.com/balupton/jquery-history\" rel=\"nofollow noreferrer\">jQuery History</a> which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.</p>\n\n<p>Another project worth noting as well is <a href=\"https://github.com/balupton/jquery-ajaxy\" rel=\"nofollow noreferrer\">jQuery Ajaxy</a> which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's <a href=\"https://stackoverflow.com/questions/3205900/how-to-show-ajax-requests-in-url/3276206#3276206\">quite complicated</a>!</p>\n"
},
{
"answer_id": 4843303,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 4,
"selected": false,
"text": "<p>HTML5 has included a much better solution than using hashchange which is the HTML5 State Management APIs - <a href=\"https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history\" rel=\"noreferrer\">https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history</a> - they allow you to change the url of the page, without needing to use hashes!</p>\n\n<p>Though the HTML5 State Functionality is only available to HTML5 Browsers. So you probably want to use something like <a href=\"https://github.com/browserstate/History.js\" rel=\"noreferrer\">History.js</a> which provides a backwards compatible experience to HTML4 Browsers (via hashes, but still supports data and titles as well as the replaceState functionality).</p>\n\n<p>You can read more about it here:\n<a href=\"https://github.com/browserstate/History.js\" rel=\"noreferrer\">https://github.com/browserstate/History.js</a></p>\n"
},
{
"answer_id": 5708124,
"author": "Eugene Kerner",
"author_id": 597686,
"author_profile": "https://Stackoverflow.com/users/597686",
"pm_score": 1,
"selected": false,
"text": "<p>I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. \nIts not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...</p>\n\n<pre><code>// Add code below ...\nfunction locationHashChanged(qs)\n{\n var q = parseQs(qs);\n // ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!\n // YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION\n // THAT IS PASSED TO changeHashValue(hashQuery)\n}\n\n// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...\nfunction changeHashValue(hashQuery)\n{\n stopHashListener();\n hashValue = hashQuery;\n location.hash = hashQuery;\n startHashListener();\n}\n\n// AND DONT WORRY ABOUT ANYTHING BELOW ...\nfunction checkIfHashChanged()\n{\n var hashQuery = getHashQuery();\n if (hashQuery == hashValue)\n return;\n hashValue = hashQuery;\n locationHashChanged(hashQuery);\n}\n\nfunction parseQs(qs)\n{\n var q = {};\n var pairs = qs.split('&');\n for (var idx in pairs) {\n var arg = pairs[idx].split('=');\n q[arg[0]] = arg[1];\n }\n return q;\n}\n\nfunction startHashListener()\n{\n hashListener = setInterval(checkIfHashChanged, 1000);\n}\n\nfunction stopHashListener()\n{\n if (hashListener != null)\n clearInterval(hashListener);\n hashListener = null;\n}\n\nfunction getHashQuery()\n{\n return location.hash.replace(/^#/, '');\n}\n\nvar hashListener = null;\nvar hashValue = '';//getHashQuery();\nstartHashListener();\n</code></pre>\n"
},
{
"answer_id": 10234264,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 1,
"selected": false,
"text": "<p>Try simple & lightweight <a href=\"https://github.com/mtrpcic/pathjs\" rel=\"nofollow\">PathJS</a> lib.</p>\n\n<p>Simple example:</p>\n\n<pre><code>Path.map(\"#/page\").to(function(){\n alert('page!');\n});\n</code></pre>\n"
},
{
"answer_id": 13747338,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 6,
"selected": false,
"text": "<p>The answers here are all quite old.</p>\n\n<p>In the HTML5 world, you should the use <a href=\"https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate\" rel=\"noreferrer\"><code>onpopstate</code></a> event.</p>\n\n<pre><code>window.onpopstate = function(event)\n{\n alert(\"location: \" + document.location + \", state: \" + JSON.stringify(event.state));\n};\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>window.addEventListener('popstate', function(event)\n{\n alert(\"location: \" + document.location + \", state: \" + JSON.stringify(event.state));\n});\n</code></pre>\n\n<p>The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/172957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8435/"
] |
I just set up my new homepage at <http://ritter.vg>. I'm using jQuery, but very minimally.
It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL.
```
//general functions
function getUrl(u) {
return u + '.html';
}
function loadURL(u) {
$.get(getUrl(u), function(r){
$('#main').html(r);
}
);
}
//allows bookmarking
var hash = new String(document.location).indexOf("#");
if(hash > 0)
{
page = new String(document.location).substring(hash + 1);
if(page.length > 1)
loadURL(page);
else
loadURL('news');
}
else
loadURL('news');
```
But I can't get the back and forward buttons to work.
Is there a way to detect when the back button has been pressed (or detect when the hash changes) without using a setInterval loop? When I tried those with .2 and 1 second timeouts, it pegged my CPU.
|
Use the [jQuery hashchange event](https://github.com/cowboy/jquery-hashchange) plugin instead. Regarding your full ajax navigation, try to have [SEO friendly ajax](http://www.chazzuka.com/blog/?p=90). Otherwise your pages shown nothing in browsers with JavaScript limitations.
|
173,017 |
<p>I'm running some java processes on Windows 2003 server R2
I'm using Apache log4j-1.2.8. All my processes called via
one jar file with different parameter example</p>
<pre><code> java -jar process.jar one
java -jar process.jar two
java -jar process.jar three
</code></pre>
<p>And I config log4j.properties follow</p>
<pre><code>#===============================
# Declare Variables
#===============================
logpath=${user.dir}/log/
simple_pattern=%d{yyyy-MM-dd HH:mm:ss.SSS}%-5x - %m%n
backup_pattern='.'yyyy-MM-dd
#===============================
# PROCESS & STANDARD OUTPUT
#===============================
log4j.logger.process.Process=NULL,proclog,procstdout
log4j.appender.proclog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.proclog.File=${logpath}process.log
log4j.appender.proclog.DatePattern=${backup_pattern}
log4j.appender.proclog.layout=org.apache.log4j.PatternLayout
log4j.appender.proclog.layout.conversionPattern=${simple_pattern}
log4j.appender.procstdout=org.apache.log4j.ConsoleAppender
log4j.appender.procstdout.layout=org.apache.log4j.PatternLayout
log4j.appender.procstdout.layout.ConversionPattern=${simple_pattern}
#===============================
# ONE
#===============================
log4j.logger.process.log.One=NULL,one
log4j.appender.one=org.apache.log4j.DailyRollingFileAppender
log4j.appender.one.File=${logpath}one.log
log4j.appender.one.DatePattern=${backup_pattern}
log4j.appender.one.layout=org.apache.log4j.PatternLayout
log4j.appender.one.layout.conversionPattern=${simple_pattern}
#===============================
# TWO
#===============================
log4j.logger.process.log.Two=NULL,two
log4j.appender.two=org.apache.log4j.DailyRollingFileAppender
log4j.appender.two.File=${logpath}two.log
log4j.appender.two.DatePattern=${backup_pattern}
log4j.appender.two.layout=org.apache.log4j.PatternLayout
log4j.appender.two.layout.conversionPattern=${simple_pattern}
#===============================
# THREE
#===============================
log4j.logger.process.log.Three=NULL,three
log4j.appender.three=org.apache.log4j.DailyRollingFileAppender
log4j.appender.three.File=${logpath}three.log
log4j.appender.three.DatePattern=${backup_pattern}
log4j.appender.three.layout=org.apache.log4j.PatternLayout
log4j.appender.three.layout.conversionPattern=${simple_pattern}
</code></pre>
<p>first time I use process appender is single logger and now i separate it
to ONE, TWO and THREE logger.
my processes executed by windows schedule every 1 minute.</p>
<p><strong>So. I got Big problem
I don't know why log4j cannot generate backup files.
but when I execute manual by command line It's Ok.</strong></p>
|
[
{
"answer_id": 173053,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "<p>Is your log4j.properties file in the classpath when executed by the scheduler? I had a similar problem in the past, and it was due to the configuration file not being in the classpath.</p>\n\n<p>You can include it in your process.jar file, or specify its location like this:</p>\n\n<blockquote>\n <p>java\n -Dlog4j.configuration=file:///path/to/log4j.properties\n -jar process.jar one</p>\n</blockquote>\n"
},
{
"answer_id": 173084,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Many thanks, I will try again for your solution.</strong></p>\n\n<p>and Now My schedule executed my processes via\nbgprocess.bat </p>\n\n<p><strong>bgprocess.bat</strong></p>\n\n<pre><code>@echo off\nset CLASSPATH=.;%CLASSPATH%\nset path=C:\\j2sdk1.4.2\\bin;%path%\njavaw -jar process.jar %1\n</code></pre>\n\n<p><strong>process.jar manifest.mf</strong></p>\n\n<pre><code>Manifest-Version: 1.0\nAnt-Version: Apache Ant 1.6.2\nCreated-By: 1.4.2 (IBM Corporation)\nMain-Class: process.Process\nClass-Path: ./lib/Utility.jar ./lib/DB2LibRAD.jar ./lib/rowset.jar ./l\n ib/log4j-1.2.8.jar ./lib/com.ibm.mq.jar .\n</code></pre>\n\n<p><strong>process directory</strong></p>\n\n<pre><code> - process.jar\n - bgprocess.bat\n - lib <dir>\n - log4j-1.2.8.jar\n - com.ibm.mq.jar\n - connector.jar\n - DB2LibRAD.jar\n - rowset.jar\n - Utility.jar \n - log <dir>\n - one.log\n - two.log\n - three.log\n - process.log\n</code></pre>\n\n<p>and all log files working normally but when pass backup time\nit will <strong>truncated</strong> and begin new log at first line.</p>\n"
},
{
"answer_id": 173463,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 0,
"selected": false,
"text": "<p>Appending should be the default, according to the javadocs, but it's worth specifying it in your config file to remove the ambiguity. With luck, it might fix your problem</p>\n\n<pre><code>log4j.appender.three.Append=true\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
] |
I'm running some java processes on Windows 2003 server R2
I'm using Apache log4j-1.2.8. All my processes called via
one jar file with different parameter example
```
java -jar process.jar one
java -jar process.jar two
java -jar process.jar three
```
And I config log4j.properties follow
```
#===============================
# Declare Variables
#===============================
logpath=${user.dir}/log/
simple_pattern=%d{yyyy-MM-dd HH:mm:ss.SSS}%-5x - %m%n
backup_pattern='.'yyyy-MM-dd
#===============================
# PROCESS & STANDARD OUTPUT
#===============================
log4j.logger.process.Process=NULL,proclog,procstdout
log4j.appender.proclog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.proclog.File=${logpath}process.log
log4j.appender.proclog.DatePattern=${backup_pattern}
log4j.appender.proclog.layout=org.apache.log4j.PatternLayout
log4j.appender.proclog.layout.conversionPattern=${simple_pattern}
log4j.appender.procstdout=org.apache.log4j.ConsoleAppender
log4j.appender.procstdout.layout=org.apache.log4j.PatternLayout
log4j.appender.procstdout.layout.ConversionPattern=${simple_pattern}
#===============================
# ONE
#===============================
log4j.logger.process.log.One=NULL,one
log4j.appender.one=org.apache.log4j.DailyRollingFileAppender
log4j.appender.one.File=${logpath}one.log
log4j.appender.one.DatePattern=${backup_pattern}
log4j.appender.one.layout=org.apache.log4j.PatternLayout
log4j.appender.one.layout.conversionPattern=${simple_pattern}
#===============================
# TWO
#===============================
log4j.logger.process.log.Two=NULL,two
log4j.appender.two=org.apache.log4j.DailyRollingFileAppender
log4j.appender.two.File=${logpath}two.log
log4j.appender.two.DatePattern=${backup_pattern}
log4j.appender.two.layout=org.apache.log4j.PatternLayout
log4j.appender.two.layout.conversionPattern=${simple_pattern}
#===============================
# THREE
#===============================
log4j.logger.process.log.Three=NULL,three
log4j.appender.three=org.apache.log4j.DailyRollingFileAppender
log4j.appender.three.File=${logpath}three.log
log4j.appender.three.DatePattern=${backup_pattern}
log4j.appender.three.layout=org.apache.log4j.PatternLayout
log4j.appender.three.layout.conversionPattern=${simple_pattern}
```
first time I use process appender is single logger and now i separate it
to ONE, TWO and THREE logger.
my processes executed by windows schedule every 1 minute.
**So. I got Big problem
I don't know why log4j cannot generate backup files.
but when I execute manual by command line It's Ok.**
|
Is your log4j.properties file in the classpath when executed by the scheduler? I had a similar problem in the past, and it was due to the configuration file not being in the classpath.
You can include it in your process.jar file, or specify its location like this:
>
> java
> -Dlog4j.configuration=file:///path/to/log4j.properties
> -jar process.jar one
>
>
>
|
173,041 |
<p>Which of these queries is the faster?</p>
<p>NOT EXISTS:</p>
<pre><code>SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE NOT EXISTS (
SELECT 1
FROM Northwind..[Order Details] od
WHERE p.ProductId = od.ProductId)
</code></pre>
<p>Or NOT IN:</p>
<pre><code>SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE p.ProductID NOT IN (
SELECT ProductID
FROM Northwind..[Order Details])
</code></pre>
<p>The query execution plan says they both do the same thing. If that is the case, which is the recommended form?</p>
<p>This is based on the NorthWind database.</p>
<p>[Edit]</p>
<p>Just found this helpful article:
<a href="http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx" rel="noreferrer">http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx</a></p>
<p>I think I'll stick with NOT EXISTS.</p>
|
[
{
"answer_id": 173045,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>If the execution planner says they're the same, they're the same. Use whichever one will make your intention more obvious -- in this case, the second.</p>\n"
},
{
"answer_id": 173058,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": -1,
"selected": false,
"text": "<p>It depends..</p>\n\n<pre><code>SELECT x.col\nFROM big_table x\nWHERE x.key IN( SELECT key FROM really_big_table );\n</code></pre>\n\n<p>would not be relatively slow the isn't much to limit size of what the query check to see if they key is in. EXISTS would be preferable in this case.</p>\n\n<p>But, depending on the DBMS's optimizer, this could be no different.</p>\n\n<p>As an example of when EXISTS is better</p>\n\n<pre><code>SELECT x.col\nFROM big_table x\nWHERE EXISTS( SELECT key FROM really_big_table WHERE key = x.key);\n AND id = very_limiting_criteria\n</code></pre>\n"
},
{
"answer_id": 173069,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "<p>Actually, I believe this would be the fastest:</p>\n\n<pre><code>SELECT ProductID, ProductName \n FROM Northwind..Products p \n outer join Northwind..[Order Details] od on p.ProductId = od.ProductId)\nWHERE od.ProductId is null\n</code></pre>\n"
},
{
"answer_id": 173096,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 3,
"selected": false,
"text": "<p>In your specific example they are the same, because the optimizer has figured out what you are trying to do is the same in both examples. But it is possible that in non-trivial examples the optimizer may not do this, and in that case there are reasons to prefer one to other on occasion.</p>\n\n<p><code>NOT IN</code> should be preferred if you are testing multiple rows in your outer select. The subquery inside the <code>NOT IN</code> statement can be evaluated at the beginning of the execution, and the temporary table can be checked against each value in the outer select, rather than re-running the subselect every time as would be required with the <code>NOT EXISTS</code> statement.</p>\n\n<p>If the subquery <em>must</em> be correlated with the outer select, then <code>NOT EXISTS</code> may be preferable, since the optimizer may discover a simplification that prevents the creation of any temporary tables to perform the same function.</p>\n"
},
{
"answer_id": 173518,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "<p>If the optimizer says they are the same then consider the human factor. I prefer to see NOT EXISTS :)</p>\n"
},
{
"answer_id": 10516011,
"author": "buckley",
"author_id": 381995,
"author_profile": "https://Stackoverflow.com/users/381995",
"pm_score": 7,
"selected": false,
"text": "<p>Also be aware that NOT IN is not equivalent to NOT EXISTS when it comes to null.</p>\n\n<p>This post explains it very well </p>\n\n<p><a href=\"http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/\">http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/</a></p>\n\n<blockquote>\n <p>When the subquery returns even one null, NOT IN will not match any\n rows.</p>\n \n <p>The reason for this can be found by looking at the details of what the\n NOT IN operation actually means.</p>\n \n <p>Let’s say, for illustration purposes that there are 4 rows in the\n table called t, there’s a column called ID with values 1..4</p>\n\n<pre><code>WHERE SomeValue NOT IN (SELECT AVal FROM t)\n</code></pre>\n \n <p>is equivalent to</p>\n\n<pre><code>WHERE SomeValue != (SELECT AVal FROM t WHERE ID=1)\nAND SomeValue != (SELECT AVal FROM t WHERE ID=2)\nAND SomeValue != (SELECT AVal FROM t WHERE ID=3)\nAND SomeValue != (SELECT AVal FROM t WHERE ID=4)\n</code></pre>\n \n <p>Let’s further say that AVal is NULL where ID = 4. Hence that !=\n comparison returns UNKNOWN. The logical truth table for AND states\n that UNKNOWN and TRUE is UNKNOWN, UNKNOWN and FALSE is FALSE. There is\n no value that can be AND’d with UNKNOWN to produce the result TRUE</p>\n \n <p>Hence, if any row of that subquery returns NULL, the entire NOT IN\n operator will evaluate to either FALSE or NULL and no records will be\n returned</p>\n</blockquote>\n"
},
{
"answer_id": 11074428,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 11,
"selected": true,
"text": "<p>I always default to <code>NOT EXISTS</code>.</p>\n\n<p>The execution plans may be the same at the moment but if either column is altered in the future to allow <code>NULL</code>s the <code>NOT IN</code> version will need to do more work (even if no <code>NULL</code>s are actually present in the data) and the semantics of <code>NOT IN</code> if <code>NULL</code>s <em>are</em> present are unlikely to be the ones you want anyway.</p>\n\n<p>When neither <code>Products.ProductID</code> or <code>[Order Details].ProductID</code> allow <code>NULL</code>s the <code>NOT IN</code> will be treated identically to the following query.</p>\n\n<pre><code>SELECT ProductID,\n ProductName\nFROM Products p\nWHERE NOT EXISTS (SELECT *\n FROM [Order Details] od\n WHERE p.ProductId = od.ProductId) \n</code></pre>\n\n<p>The exact plan may vary but for my example data I get the following.</p>\n\n<p><img src=\"https://i.stack.imgur.com/lCTsG.png\" alt=\"Neither NULL\"></p>\n\n<p>A reasonably common misconception seems to be that correlated sub queries are always \"bad\" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.</p>\n\n<pre><code>/*Not valid syntax but better reflects the plan*/ \nSELECT p.ProductID,\n p.ProductName\nFROM Products p\n LEFT ANTI SEMI JOIN [Order Details] od\n ON p.ProductId = od.ProductId \n</code></pre>\n\n<p>If <code>[Order Details].ProductID</code> is <code>NULL</code>-able the query then becomes</p>\n\n<pre><code>SELECT ProductID,\n ProductName\nFROM Products p\nWHERE NOT EXISTS (SELECT *\n FROM [Order Details] od\n WHERE p.ProductId = od.ProductId)\n AND NOT EXISTS (SELECT *\n FROM [Order Details]\n WHERE ProductId IS NULL) \n</code></pre>\n\n<p>The reason for this is that the correct semantics if <code>[Order Details]</code> contains any <code>NULL</code> <code>ProductId</code>s is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.</p>\n\n<p><img src=\"https://i.stack.imgur.com/mPYhd.png\" alt=\"One NULL\"></p>\n\n<p>If <code>Products.ProductID</code> is also changed to become <code>NULL</code>-able the query then becomes</p>\n\n<pre><code>SELECT ProductID,\n ProductName\nFROM Products p\nWHERE NOT EXISTS (SELECT *\n FROM [Order Details] od\n WHERE p.ProductId = od.ProductId)\n AND NOT EXISTS (SELECT *\n FROM [Order Details]\n WHERE ProductId IS NULL)\n AND NOT EXISTS (SELECT *\n FROM (SELECT TOP 1 *\n FROM [Order Details]) S\n WHERE p.ProductID IS NULL) \n</code></pre>\n\n<p>The reason for that one is because a <code>NULL</code> <code>Products.ProductId</code> should not be returned in the results <strong>except</strong> if the <code>NOT IN</code> sub query were to return no results at all (i.e. the <code>[Order Details]</code> table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.</p>\n\n<p><img src=\"https://i.stack.imgur.com/8XAh1.png\" alt=\"Both NULL\"></p>\n\n<p>The effect of this is shown in <a href=\"http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/\" rel=\"noreferrer\">the blog post already linked by Buckley</a>. In the example there the number of logical reads increase from around 400 to 500,000.</p>\n\n<p>Additionally the fact that a single <code>NULL</code> can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no <code>NULL</code> rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, <a href=\"https://dba.stackexchange.com/q/117306/3690\">with inappropriate nested loops causing repeated execution of an expensive sub tree for example</a>. </p>\n\n<p>This is not the only possible execution plan for a <code>NOT IN</code> on a <code>NULL</code>-able column however. <a href=\"http://bradsruminations.blogspot.co.uk/2011/10/t-sql-tuesday-023-flip-side-of-join.html\" rel=\"noreferrer\">This article shows another one</a> for a query against the <code>AdventureWorks2008</code> database.</p>\n\n<p>For the <code>NOT IN</code> on a <code>NOT NULL</code> column or the <code>NOT EXISTS</code> against either a nullable or non nullable column it gives the following plan.</p>\n\n<p><img src=\"https://i.stack.imgur.com/nahUD.png\" alt=\"Not EXists\"></p>\n\n<p>When the column changes to <code>NULL</code>-able the <code>NOT IN</code> plan now looks like</p>\n\n<p><img src=\"https://i.stack.imgur.com/8o9PQ.png\" alt=\"Not In - Null\"></p>\n\n<p>It adds an extra inner join operator to the plan. This apparatus is <a href=\"https://dba.stackexchange.com/a/14812/3690\">explained here</a>. It is all there to convert the previous single correlated index seek on <code>Sales.SalesOrderDetail.ProductID = <correlated_product_id></code> to two seeks per outer row. The additional one is on <code>WHERE Sales.SalesOrderDetail.ProductID IS NULL</code>. </p>\n\n<p>As this is under an anti semi join if that one returns any rows the second seek will not occur. However if <code>Sales.SalesOrderDetail</code> does not contain any <code>NULL</code> <code>ProductID</code>s it will double the number of seek operations required.</p>\n"
},
{
"answer_id": 17090472,
"author": "ravish.hacker",
"author_id": 1367413,
"author_profile": "https://Stackoverflow.com/users/1367413",
"pm_score": 3,
"selected": false,
"text": "<p>I was using</p>\n\n<pre><code>SELECT * from TABLE1 WHERE Col1 NOT IN (SELECT Col1 FROM TABLE2)\n</code></pre>\n\n<p>and found that it was giving wrong results (By wrong I mean no results). As there was a NULL in TABLE2.Col1.</p>\n\n<p>While changing the query to </p>\n\n<pre><code>SELECT * from TABLE1 T1 WHERE NOT EXISTS (SELECT Col1 FROM TABLE2 T2 WHERE T1.Col1 = T2.Col2)\n</code></pre>\n\n<p>gave me the correct results.</p>\n\n<p>Since then I have started using NOT EXISTS every where.</p>\n"
},
{
"answer_id": 24616125,
"author": "Yella Chalamala",
"author_id": 3813341,
"author_profile": "https://Stackoverflow.com/users/3813341",
"pm_score": 4,
"selected": false,
"text": "<p>I have a table which has about 120,000 records and need to select only those which does not exist (matched with a varchar column) in four other tables with number of rows approx 1500, 4000, 40000, 200. All the involved tables have unique index on the concerned <code>Varchar</code> column. </p>\n\n<p><code>NOT IN</code> took about 10 mins, <code>NOT EXISTS</code> took 4 secs.</p>\n\n<p>I have a recursive query which might had some untuned section which might have contributed to the 10 mins, but the other option taking 4 secs explains, atleast to me that <code>NOT EXISTS</code> is far better or at least that <code>IN</code> and <code>EXISTS</code> are not exactly the same and always worth a check before going ahead with code.</p>\n"
},
{
"answer_id": 49358539,
"author": "Onga Leo-Yoda Vellem",
"author_id": 6556438,
"author_profile": "https://Stackoverflow.com/users/6556438",
"pm_score": 2,
"selected": false,
"text": "<p>They are very similar but not really the same. </p>\n\n<p>In terms of efficiency, I've found the <strong>left join is null</strong> statement more efficient (when an abundance of rows are to be selected that is) </p>\n"
},
{
"answer_id": 59946679,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 3,
"selected": false,
"text": "<h2>Database table model</h2>\n<p>Let’s assume we have the following two tables in our database, that form a one-to-many table relationship.</p>\n<p><a href=\"https://i.stack.imgur.com/uD3tb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uD3tb.png\" alt=\"SQL EXISTS tables\" /></a></p>\n<p>The <code>student</code> table is the parent, and the <code>student_grade</code> is the child table since it has a student_id Foreign Key column referencing the id Primary Key column in the student table.</p>\n<p>The <code>student table</code> contains the following two records:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>id</th>\n<th>first_name</th>\n<th>last_name</th>\n<th>admission_score</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Alice</td>\n<td>Smith</td>\n<td>8.95</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Bob</td>\n<td>Johnson</td>\n<td>8.75</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>And, the <code>student_grade</code> table stores the grades the students received:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>id</th>\n<th>class_name</th>\n<th>grade</th>\n<th>student_id</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Math</td>\n<td>10</td>\n<td>1</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Math</td>\n<td>9.5</td>\n<td>1</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Math</td>\n<td>9.75</td>\n<td>1</td>\n</tr>\n<tr>\n<td>4</td>\n<td>Science</td>\n<td>9.5</td>\n<td>1</td>\n</tr>\n<tr>\n<td>5</td>\n<td>Science</td>\n<td>9</td>\n<td>1</td>\n</tr>\n<tr>\n<td>6</td>\n<td>Science</td>\n<td>9.25</td>\n<td>1</td>\n</tr>\n<tr>\n<td>7</td>\n<td>Math</td>\n<td>8.5</td>\n<td>2</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Math</td>\n<td>9.5</td>\n<td>2</td>\n</tr>\n<tr>\n<td>9</td>\n<td>Math</td>\n<td>9</td>\n<td>2</td>\n</tr>\n<tr>\n<td>10</td>\n<td>Science</td>\n<td>10</td>\n<td>2</td>\n</tr>\n<tr>\n<td>11</td>\n<td>Science</td>\n<td>9.4</td>\n<td>2</td>\n</tr>\n</tbody>\n</table>\n</div><h2>SQL EXISTS</h2>\n<p>Let’s say we want to get all students that have received a 10 grade in Math class.</p>\n<p>If we are only interested in the student identifier, then we can run a query like this one:</p>\n<pre><code>SELECT\n student_grade.student_id\nFROM\n student_grade\nWHERE\n student_grade.grade = 10 AND\n student_grade.class_name = 'Math'\nORDER BY\n student_grade.student_id\n</code></pre>\n<p>But, the application is interested in displaying the full name of a <code>student</code>, not just the identifier, so we need info from the <code>student</code> table as well.</p>\n<p>In order to filter the <code>student</code> records that have a 10 grade in Math, we can use the EXISTS SQL operator, like this:</p>\n<pre><code>SELECT\n id, first_name, last_name\nFROM\n student\nWHERE EXISTS (\n SELECT 1\n FROM\n student_grade\n WHERE\n student_grade.student_id = student.id AND\n student_grade.grade = 10 AND\n student_grade.class_name = 'Math'\n)\nORDER BY id\n</code></pre>\n<p>When running the query above, we can see that only the Alice row is selected:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>id</th>\n<th>first_name</th>\n<th>last_name</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Alice</td>\n<td>Smith</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The outer query selects the <code>student</code> row columns we are interested in returning to the client. However, the WHERE clause is using the EXISTS operator with an associated inner subquery.</p>\n<p>The EXISTS operator returns true if the subquery returns at least one record and false if no row is selected. The database engine does not have to run the subquery entirely. If a single record is matched, the EXISTS operator returns true, and the associated other query row is selected.</p>\n<p>The inner subquery is correlated because the student_id column of the <code>student_grade</code> table is matched against the id column of the outer student table.</p>\n<h2>SQL NOT EXISTS</h2>\n<p>Let’s consider we want to select all students that have no grade lower than 9. For this, we can use NOT EXISTS, which negates the logic of the EXISTS operator.</p>\n<p>Therefore, the NOT EXISTS operator returns true if the underlying subquery returns no record. However, if a single record is matched by the inner subquery, the NOT EXISTS operator will return false, and the subquery execution can be stopped.</p>\n<p>To match all student records that have no associated student_grade with a value lower than 9, we can run the following SQL query:</p>\n<pre><code>SELECT\n id, first_name, last_name\nFROM\n student\nWHERE NOT EXISTS (\n SELECT 1\n FROM\n student_grade\n WHERE\n student_grade.student_id = student.id AND\n student_grade.grade < 9\n)\nORDER BY id\n</code></pre>\n<p>When running the query above, we can see that only the Alice record is matched:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>id</th>\n<th>first_name</th>\n<th>last_name</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Alice</td>\n<td>Smith</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>So, the advantage of using the SQL EXISTS and NOT EXISTS operators is that the inner subquery execution can be stopped as long as a matching record is found.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
Which of these queries is the faster?
NOT EXISTS:
```
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE NOT EXISTS (
SELECT 1
FROM Northwind..[Order Details] od
WHERE p.ProductId = od.ProductId)
```
Or NOT IN:
```
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE p.ProductID NOT IN (
SELECT ProductID
FROM Northwind..[Order Details])
```
The query execution plan says they both do the same thing. If that is the case, which is the recommended form?
This is based on the NorthWind database.
[Edit]
Just found this helpful article:
<http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx>
I think I'll stick with NOT EXISTS.
|
I always default to `NOT EXISTS`.
The execution plans may be the same at the moment but if either column is altered in the future to allow `NULL`s the `NOT IN` version will need to do more work (even if no `NULL`s are actually present in the data) and the semantics of `NOT IN` if `NULL`s *are* present are unlikely to be the ones you want anyway.
When neither `Products.ProductID` or `[Order Details].ProductID` allow `NULL`s the `NOT IN` will be treated identically to the following query.
```
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
```
The exact plan may vary but for my example data I get the following.

A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.
```
/*Not valid syntax but better reflects the plan*/
SELECT p.ProductID,
p.ProductName
FROM Products p
LEFT ANTI SEMI JOIN [Order Details] od
ON p.ProductId = od.ProductId
```
If `[Order Details].ProductID` is `NULL`-able the query then becomes
```
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
```
The reason for this is that the correct semantics if `[Order Details]` contains any `NULL` `ProductId`s is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.

If `Products.ProductID` is also changed to become `NULL`-able the query then becomes
```
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
AND NOT EXISTS (SELECT *
FROM (SELECT TOP 1 *
FROM [Order Details]) S
WHERE p.ProductID IS NULL)
```
The reason for that one is because a `NULL` `Products.ProductId` should not be returned in the results **except** if the `NOT IN` sub query were to return no results at all (i.e. the `[Order Details]` table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.

The effect of this is shown in [the blog post already linked by Buckley](http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/). In the example there the number of logical reads increase from around 400 to 500,000.
Additionally the fact that a single `NULL` can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no `NULL` rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, [with inappropriate nested loops causing repeated execution of an expensive sub tree for example](https://dba.stackexchange.com/q/117306/3690).
This is not the only possible execution plan for a `NOT IN` on a `NULL`-able column however. [This article shows another one](http://bradsruminations.blogspot.co.uk/2011/10/t-sql-tuesday-023-flip-side-of-join.html) for a query against the `AdventureWorks2008` database.
For the `NOT IN` on a `NOT NULL` column or the `NOT EXISTS` against either a nullable or non nullable column it gives the following plan.

When the column changes to `NULL`-able the `NOT IN` plan now looks like

It adds an extra inner join operator to the plan. This apparatus is [explained here](https://dba.stackexchange.com/a/14812/3690). It is all there to convert the previous single correlated index seek on `Sales.SalesOrderDetail.ProductID = <correlated_product_id>` to two seeks per outer row. The additional one is on `WHERE Sales.SalesOrderDetail.ProductID IS NULL`.
As this is under an anti semi join if that one returns any rows the second seek will not occur. However if `Sales.SalesOrderDetail` does not contain any `NULL` `ProductID`s it will double the number of seek operations required.
|
173,056 |
<p>I've been trying to solve this, and have been getting stuck, so I thought I'd ask.</p>
<p>Imagine two ActionBeans, A and B.</p>
<p><code>A.jsp</code> has this section in it:</p>
<pre><code>...
<jsp:include page="/B.action">
<jsp:param name="ponies" value="on"/>
</jsp:include>
<jsp:include page="/B.action">
<jsp:param name="ponies" value="off"/>
</jsp:include>
...
</code></pre>
<p>Take it as read that the B ActionBean does some terribly interesting stuff depending on whether the "ponies" parameter is set to either on or off.</p>
<p>The parameter string "ponies=on" <em>is</em> visible when you debug into the request, but it's not what's getting bound into the B ActionBean. Instead what's getting bound are the parameters to the original A.action.</p>
<p>Is there some way of getting the behaviour I want, or have I missed something fundamental?</p>
|
[
{
"answer_id": 173049,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://jqueryui.com/demos/slider/\" rel=\"noreferrer\">jQuery UI Slider</a> (<a href=\"http://docs.jquery.com/UI/Slider\" rel=\"noreferrer\">API docs</a>)</p>\n"
},
{
"answer_id": 173100,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 2,
"selected": false,
"text": "<p>script.aculo.us has a <a href=\"http://github.com/madrobby/scriptaculous/wikis/slider\" rel=\"nofollow noreferrer\">slider control</a> that might be worth checking out.</p>\n"
},
{
"answer_id": 173138,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "<p>The lightweight MooTools framework has one: <a href=\"http://demos.mootools.net/Slider\" rel=\"nofollow noreferrer\">http://demos.mootools.net/Slider</a></p>\n"
},
{
"answer_id": 173830,
"author": "Alex Gyoshev",
"author_id": 25427,
"author_profile": "https://Stackoverflow.com/users/25427",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://developer.yahoo.com/yui/\" rel=\"noreferrer\">Yahoo UI library</a> has also a <a href=\"http://developer.yahoo.com/yui/examples/slider/slider-ticks.html\" rel=\"noreferrer\">slider control</a>...</p>\n"
},
{
"answer_id": 173888,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.whatwg.org/specs/web-apps/current-work/\" rel=\"noreferrer\">HTML 5</a> with <a href=\"http://www.whatwg.org/specs/web-forms/current-work/\" rel=\"noreferrer\">Webforms 2</a> provides an <code><input type=\"range\"></code> which will make the browser generate a native slider for you. Unfortunately all browsers doesn't have support for this, however <a href=\"http://code.google.com/p/webforms2/\" rel=\"noreferrer\">google</a> has implemented all Webforms 2 controls with js. IIRC the js is intelligent enough to know if the browser has implemented the control, and triggers only if there is no native implementation.</p>\n\n<p>From my point of view it should be considered best practice to use the browsers native controls when possible.</p>\n"
},
{
"answer_id": 1888573,
"author": "unigg",
"author_id": 175962,
"author_profile": "https://Stackoverflow.com/users/175962",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a simple slider object for easy to use</p>\n\n<p><a href=\"http://www.pagecolumn.com/webparts/sliders.htm\" rel=\"nofollow noreferrer\">pagecolumn_webparts_sliders</a></p>\n"
},
{
"answer_id": 2547089,
"author": "Tom",
"author_id": 305329,
"author_profile": "https://Stackoverflow.com/users/305329",
"pm_score": 1,
"selected": false,
"text": "<p>The Carpe Slider has newer versions also: <br/>\nv1.5 <a href=\"http://carpe.ambiprospect.com/slider/\" rel=\"nofollow noreferrer\">carpe_ambiprospect_slider</a>\nv2.0b ...slider/drafts/v2.0/</p>\n"
},
{
"answer_id": 2596440,
"author": "treznik",
"author_id": 128816,
"author_profile": "https://Stackoverflow.com/users/128816",
"pm_score": 3,
"selected": false,
"text": "<p>Here is another light <a href=\"http://blog.ovidiu.ch/javascript-slider\" rel=\"noreferrer\">JavaScript Slider</a> that seems to fit your needs.</p>\n"
},
{
"answer_id": 7976206,
"author": "Farm",
"author_id": 286588,
"author_profile": "https://Stackoverflow.com/users/286588",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend Slider from Filament Group, It has very good user experience</p>\n\n<p><a href=\"http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/\" rel=\"nofollow\">http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/</a></p>\n"
},
{
"answer_id": 8385425,
"author": "Luc",
"author_id": 345086,
"author_profile": "https://Stackoverflow.com/users/345086",
"pm_score": 5,
"selected": false,
"text": "<p>hey i've just created my own JS slider because I had enough of the heavy Jquery UI one. Interested to hear people's thoughts. Been on it for 5 hours, so really really early stages.</p>\n\n<p><a href=\"http://jsfiddle.net/LucP/BPdKR/2/\" rel=\"noreferrer\">jsfiddle_slider</a></p>\n"
},
{
"answer_id": 10391073,
"author": "Martin",
"author_id": 1366768,
"author_profile": "https://Stackoverflow.com/users/1366768",
"pm_score": -1,
"selected": false,
"text": "<p>The code below should be enough to get you started. Tested in Opera, IE and Chrome.</p>\n\n<pre><code><script>\nvar l=0;\nfunction f(i){\nim = 'i' + l;\nd=document.all[im];\nd.height=99;\ndocument.all.f1.t1.value=i;\nim = 'i' + i;\nd=document.all[im];\nd.height=1;\nl=i;\n}\n</script>\n<center>\n<form id='f1'>\n<input type=text value=0 id='t1'>\n</form>\n<script>\nfor (i=0;i<=50;i++)\n {\n s = \"<img src='j.jpg' height=99 width=9 onMouseOver='f(\" + i + \")' id='i\" + i + \"'>\";\n document.write(s);\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 11195447,
"author": "Denes Ferenc",
"author_id": 1454827,
"author_profile": "https://Stackoverflow.com/users/1454827",
"pm_score": 2,
"selected": false,
"text": "<p>There's a nice javascript slider, it's very easy to implement. You can download the zip package here: <a href=\"http://ruwix.com/javascript-volume-slider-control/\" rel=\"nofollow noreferrer\">http://ruwix.com/javascript-volume-slider-control/</a></p>\n\n<p><br/>\np.s. here the simplified version of the above script:</p>\n\n<p><img src=\"https://i.stack.imgur.com/lVDzF.png\" alt=\"enter image description here\"></p>\n\n<p><a href=\"http://codepen.io/tazotodua/debug/wnDjq\" rel=\"nofollow noreferrer\"><strong>DEMO link</strong></a></p>\n"
},
{
"answer_id": 14644243,
"author": "Stephane Rolland",
"author_id": 356440,
"author_profile": "https://Stackoverflow.com/users/356440",
"pm_score": 4,
"selected": false,
"text": "<p>A simple slider: I have just tested this in <strong>pure HTML5</strong>, and <strong>it's so simple</strong> !</p>\n\n<pre><code><input type=\"range\">\n</code></pre>\n\n<p>It works like a charm on Chrome. I've not tested other browsers yet.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22419/"
] |
I've been trying to solve this, and have been getting stuck, so I thought I'd ask.
Imagine two ActionBeans, A and B.
`A.jsp` has this section in it:
```
...
<jsp:include page="/B.action">
<jsp:param name="ponies" value="on"/>
</jsp:include>
<jsp:include page="/B.action">
<jsp:param name="ponies" value="off"/>
</jsp:include>
...
```
Take it as read that the B ActionBean does some terribly interesting stuff depending on whether the "ponies" parameter is set to either on or off.
The parameter string "ponies=on" *is* visible when you debug into the request, but it's not what's getting bound into the B ActionBean. Instead what's getting bound are the parameters to the original A.action.
Is there some way of getting the behaviour I want, or have I missed something fundamental?
|
[jQuery UI Slider](http://jqueryui.com/demos/slider/) ([API docs](http://docs.jquery.com/UI/Slider))
|
173,070 |
<p>I heard that you could right-shift a number by .5 instead of using Math.floor(). I decided to check its limits to make sure that it was a suitable replacement, so I checked the following values and got the following results in Google Chrome:</p>
<pre><code>
2.5 >> .5 == 2;
2.9999 >> .5 == 2;
2.999999999999999 >> .5 == 2; // 15 9s
2.9999999999999999 >> .5 == 3; // 16 9s
</code></pre>
<p>After some fiddling, I found out that the highest possible value of two which, when right-shifted by .5, would yield 2 is 2.9999999999999997779553950749686919152736663818359374999999¯ (with the 9 repeating) in Chrome and Firefox. The number is 2.9999999999999997779¯ in IE.</p>
<p>My question is: what is the significance of the number .0000000000000007779553950749686919152736663818359374? It's a very strange number and it really piqued my curiosity.</p>
<p>I've been trying to find an answer or at least some kind of pattern, but I think my problem lies in the fact that I really don't understand the bitwise operation. I understand the idea in principle, but shifting a bit sequence by .5 doesn't make any sense at all to me. Any help is appreciated.</p>
<p>For the record, the weird digit sequence changes with 2^x. The highest possible values of the following numbers that still truncate properly:</p>
<pre>
for 0: 0.9999999999999999444888487687421729788184165954589843749¯
for 1: 1.9999999999999999888977697537484345957636833190917968749¯
for 2-3: x+.99999999999999977795539507496869191527366638183593749¯
for 4-7: x+.9999999999999995559107901499373838305473327636718749¯
for 8-15: x+.999999999999999111821580299874767661094665527343749¯
...and so forth
</pre>
|
[
{
"answer_id": 173090,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>This is possibly the single worst idea I have ever seen. Its only possible purpose for existing is for winning an obfusticated code contest. There's no significance to the long numbers you posted -- they're an artifact of the underlying floating-point implementation, filtered through god-knows how many intermediate layers. Bit-shifting by a fractional number of bytes is insane and I'm surprised it doesn't raise an exception -- but that's Javascript, always willing to redefine \"insane\".</p>\n\n<p>If I were you, I'd avoid ever using this \"feature\". Its only value is as a possible root cause for an unusual error condition. Use <code>Math.floor()</code> and take pity on the next programmer who will maintain the code.</p>\n\n<hr>\n\n<p>Confirming a couple suspicions I had when reading the question:</p>\n\n<ul>\n<li>Right-shifting any fractional number <code>x</code> by any fractional number <code>y</code> will simply truncate <code>x</code>, giving the same result as <code>Math.floor()</code> while thoroughly confusing the reader.</li>\n<li>2.999999999999999777955395074968691915... is simply the largest number that can be differentiated from \"3\". Try evaluating it by itself -- if you add anything to it, it will evaluate to 3. This is an artifact of the browser and local system's floating-point implementation.</li>\n</ul>\n"
},
{
"answer_id": 173092,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think your right shift is relevant. You are simply beyond the resolution of a double precision floating point constant.</p>\n\n<p>In Chrome:</p>\n\n<pre><code>var x = 2.999999999999999777955395074968691915273666381835937499999;\nvar y = 2.9999999999999997779553950749686919152736663818359375;\n\ndocument.write(\"x=\" + x);\ndocument.write(\" y=\" + y);\n</code></pre>\n\n<p>Prints out: x = 2.9999999999999996 y=3</p>\n"
},
{
"answer_id": 173093,
"author": "Zach Snow",
"author_id": 25381,
"author_profile": "https://Stackoverflow.com/users/25381",
"pm_score": 3,
"selected": false,
"text": "<p>Try this javascript out:\n alert(parseFloat(\"2.9999999999999997779553950749686919152736663818359374999999\"));</p>\n\n<p>Then try this:\n alert(parseFloat(\"2.9999999999999997779553950749686919152736663818359375\"));</p>\n\n<p>What you are seeing is simple floating point inaccuracy. For more information about that, see this for example: <a href=\"http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems</a>.</p>\n\n<p>The basic issue is that the closest that a floating point value can get to representing the second number is greater than or equal to 3, whereas the closes that the a float can get to the first number is strictly less than three.</p>\n\n<p>As for why right shifting by 0.5 does anything sane at all, it seems that 0.5 is just itself getting converted to an int (0) beforehand. Then the original float (2.999...) is getting converted to an int by truncation, as usual.</p>\n"
},
{
"answer_id": 173095,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 1,
"selected": false,
"text": "<p>And to add to John's answer, the odds of this being more performant than Math.floor are vanishingly small.</p>\n\n<p>I don't know if JavaScript uses floating-point numbers or some kind of infinite-precision library, but either way, you're going to get rounding errors on an operation like this -- even if it's pretty well defined.</p>\n"
},
{
"answer_id": 173098,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>The shift right operator only operates on integers (both sides). So, shifting right by .5 bits should be exactly equivalent to shifting right by 0 bits. And, the left hand side is converted to an integer before the shift operation, which does the same thing as Math.floor().</p>\n"
},
{
"answer_id": 173123,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 7,
"selected": true,
"text": "<p>Actually, you're simply ending up doing a floor() on the first operand, without any floating point operations going on. Since the left shift and right shift bitwise operations only make sense with integer operands, the JavaScript engine is converting the two operands to integers first:</p>\n\n<pre><code>2.999999 >> 0.5\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>Math.floor(2.999999) >> Math.floor(0.5)\n</code></pre>\n\n<p>Which in turn is:</p>\n\n<pre><code>2 >> 0\n</code></pre>\n\n<p>Shifting by 0 bits means \"don't do a shift\" and therefore you end up with the first operand, simply truncated to an integer.</p>\n\n<p>The SpiderMonkey source code has:</p>\n\n<pre><code>switch (op) {\n case JSOP_LSH:\n case JSOP_RSH:\n if (!js_DoubleToECMAInt32(cx, d, &i)) // Same as Math.floor()\n return JS_FALSE;\n if (!js_DoubleToECMAInt32(cx, d2, &j)) // Same as Math.floor()\n return JS_FALSE;\n j &= 31;\n d = (op == JSOP_LSH) ? i << j : i >> j;\n break;\n</code></pre>\n\n<p>Your seeing a \"rounding up\" with certain numbers is due to the fact the JavaScript engine can't handle decimal digits beyond a certain precision and therefore your number ends up getting rounded up to the next integer. Try this in your browser:</p>\n\n<pre><code>alert(2.999999999999999);\n</code></pre>\n\n<p>You'll get 2.999999999999999. Now try adding one more 9:</p>\n\n<pre><code>alert(2.9999999999999999);\n</code></pre>\n\n<p>You'll get a 3.</p>\n"
},
{
"answer_id": 173130,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 3,
"selected": false,
"text": "<p>If you wanna go deeper, read "What Every Computer Scientist Should Know About Floating-Point Arithmetic": <a href=\"https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html</a></p>\n"
},
{
"answer_id": 191580,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect that converting 2.9999999999999997779553950749686919152736663818359374999999 to its binary representation would be enlightening. It's probably only 1 bit different from true 3.</p>\n"
},
{
"answer_id": 206906,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 1,
"selected": false,
"text": "<p>It should be noted that the number \".0000000000000007779553950749686919152736663818359374\" is quite possibly the <a href=\"http://en.wikipedia.org/wiki/Machine_epsilon\" rel=\"nofollow noreferrer\">Epsilon</a>, defined as \"the smallest number E such that (1+E) > 1.\"</p>\n"
},
{
"answer_id": 249824,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I suspect that converting 2.9999999999999997779553950749686919152736663818359374999999\n to it's binary representation would be enlightening. It's probably only 1 bit different\n from true 3.</p>\n</blockquote>\n\n<p>Good guess, but no cigar.\nAs the double precision FP number has 53 bits, the last FP number before 3 is actually\n(exact): 2.999999999999999555910790149937383830547332763671875</p>\n\n<p>But why it is \n2.9999999999999997779553950749686919152736663818359375</p>\n\n<p>(and this is exact, not 49999... !)</p>\n\n<p>which is <em>higher</em> than the last displayable unit ? Rounding. The conversion routine (String to number) simply is correctly programmed to round the input the the next floating point number.</p>\n\n<p>2.999999999999999555910790149937383830547332763671875</p>\n\n<p>.......(values between, increasing) -> round down</p>\n\n<p>2.9999999999999997779553950749686919152736663818359375</p>\n\n<p>....... (values between, increasing) -> round up to 3 </p>\n\n<p>3</p>\n\n<p>The conversion input must use full precision. If the number is exactly the half between\nthose two fp numbers (which is 2.9999999999999997779553950749686919152736663818359375)\nthe rounding depends on the setted flags. The default rounding is round to even, meaning that the number will be rounded to the next even number. </p>\n\n<p>Now</p>\n\n<p>3 = 11. (binary)</p>\n\n<p>2.999... = 10.11111111111...... (binary)</p>\n\n<p>All bits are set, the number is always odd. That means that the exact half number will be rounded up, so you are getting the strange .....49999 period because it must be smaller than the exact half to be distinguishable from 3.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25357/"
] |
I heard that you could right-shift a number by .5 instead of using Math.floor(). I decided to check its limits to make sure that it was a suitable replacement, so I checked the following values and got the following results in Google Chrome:
```
2.5 >> .5 == 2;
2.9999 >> .5 == 2;
2.999999999999999 >> .5 == 2; // 15 9s
2.9999999999999999 >> .5 == 3; // 16 9s
```
After some fiddling, I found out that the highest possible value of two which, when right-shifted by .5, would yield 2 is 2.9999999999999997779553950749686919152736663818359374999999¯ (with the 9 repeating) in Chrome and Firefox. The number is 2.9999999999999997779¯ in IE.
My question is: what is the significance of the number .0000000000000007779553950749686919152736663818359374? It's a very strange number and it really piqued my curiosity.
I've been trying to find an answer or at least some kind of pattern, but I think my problem lies in the fact that I really don't understand the bitwise operation. I understand the idea in principle, but shifting a bit sequence by .5 doesn't make any sense at all to me. Any help is appreciated.
For the record, the weird digit sequence changes with 2^x. The highest possible values of the following numbers that still truncate properly:
```
for 0: 0.9999999999999999444888487687421729788184165954589843749¯
for 1: 1.9999999999999999888977697537484345957636833190917968749¯
for 2-3: x+.99999999999999977795539507496869191527366638183593749¯
for 4-7: x+.9999999999999995559107901499373838305473327636718749¯
for 8-15: x+.999999999999999111821580299874767661094665527343749¯
...and so forth
```
|
Actually, you're simply ending up doing a floor() on the first operand, without any floating point operations going on. Since the left shift and right shift bitwise operations only make sense with integer operands, the JavaScript engine is converting the two operands to integers first:
```
2.999999 >> 0.5
```
Becomes:
```
Math.floor(2.999999) >> Math.floor(0.5)
```
Which in turn is:
```
2 >> 0
```
Shifting by 0 bits means "don't do a shift" and therefore you end up with the first operand, simply truncated to an integer.
The SpiderMonkey source code has:
```
switch (op) {
case JSOP_LSH:
case JSOP_RSH:
if (!js_DoubleToECMAInt32(cx, d, &i)) // Same as Math.floor()
return JS_FALSE;
if (!js_DoubleToECMAInt32(cx, d2, &j)) // Same as Math.floor()
return JS_FALSE;
j &= 31;
d = (op == JSOP_LSH) ? i << j : i >> j;
break;
```
Your seeing a "rounding up" with certain numbers is due to the fact the JavaScript engine can't handle decimal digits beyond a certain precision and therefore your number ends up getting rounded up to the next integer. Try this in your browser:
```
alert(2.999999999999999);
```
You'll get 2.999999999999999. Now try adding one more 9:
```
alert(2.9999999999999999);
```
You'll get a 3.
|
173,115 |
<p>I'm currently working on the <code>Tips.js</code> from <code>mootools</code> library and my code breaks on the line that has those <code>el.$tmp</code>, and console says it's undefined</p>
<p>Can anybody help me?</p>
|
[
{
"answer_id": 173155,
"author": "keif",
"author_id": 19289,
"author_profile": "https://Stackoverflow.com/users/19289",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest taking your question and posting it, along with a link to the page to either/or/and:</p>\n\n<p><a href=\"http://mooforum.net\" rel=\"nofollow noreferrer\">http://mooforum.net</a></p>\n\n<p><a href=\"http://groups.google.com/group/mootools-users/topics\" rel=\"nofollow noreferrer\">http://groups.google.com/group/mootools-users/topics</a></p>\n\n<p>That's the community that swarms with it.</p>\n\n<p>Now as for answering it here - I'd need a lot more information (code example?)</p>\n"
},
{
"answer_id": 173163,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm. I'm not exactly sure what el.$tmp is a reference to in MooTools but a message stating \"console is undefined\" is probably because someone was trying to log to the Firebug (or another) console and that object does not exist if you don't have Firebug and friends.</p>\n\n<p>If you don't have http://getfirebug.com'>Firebug installed for Firefox then you might give it a shot. See if you can find the console statement and remove it. Also, if you aren't using Firefox, you can use Firebug Lite in IE, Safari, or Opera.</p>\n"
},
{
"answer_id": 242743,
"author": "Ryan",
"author_id": 32009,
"author_profile": "https://Stackoverflow.com/users/32009",
"pm_score": 2,
"selected": true,
"text": "<p>in 1.11 (haven't checked in 1.2+) $tmp is a reference to the element itself, created and used internally by the garbage collector:</p>\n\n<pre><code>var Garbage = {\n\n elements: [],\n\n collect: function(el){\n if (!el.$tmp){\n Garbage.elements.push(el);\n el.$tmp = {'opacity': 1};\n }\n return el;\n },\n\n trash: function(elements){\n for (var i = 0, j = elements.length, el; i < j; i++){\n if (!(el = elements[i]) || !el.$tmp) continue;\n if (el.$events) el.fireEvent('trash').removeEvents();\n for (var p in el.$tmp) el.$tmp[p] = null;\n for (var d in Element.prototype) el[d] = null;\n Garbage.elements[Garbage.elements.indexOf(el)] = null;\n el.htmlElement = el.$tmp = el = null;\n }\n Garbage.elements.remove(null);\n },\n\n empty: function(){\n Garbage.collect(window);\n Garbage.collect(document);\n Garbage.trash(Garbage.elements);\n }\n\n};\n</code></pre>\n\n<p>the lines <code>el.$tmp = {'opacity': 1};</code> (in collect method above) and <code>el.htmlElement = el.$tmp = el = null;</code> (in trash method above) are the only places in the source where this property is assigned that i could find, although it's called by various other methods, such as Element.setOpacity and Element.getStyle (specifically, only to return opacity value), as well as methods in the Tips class</p>\n\n<p>1.2 might not have this issue, but in any case, hope that helps and sorry i couldn't help more</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24744/"
] |
I'm currently working on the `Tips.js` from `mootools` library and my code breaks on the line that has those `el.$tmp`, and console says it's undefined
Can anybody help me?
|
in 1.11 (haven't checked in 1.2+) $tmp is a reference to the element itself, created and used internally by the garbage collector:
```
var Garbage = {
elements: [],
collect: function(el){
if (!el.$tmp){
Garbage.elements.push(el);
el.$tmp = {'opacity': 1};
}
return el;
},
trash: function(elements){
for (var i = 0, j = elements.length, el; i < j; i++){
if (!(el = elements[i]) || !el.$tmp) continue;
if (el.$events) el.fireEvent('trash').removeEvents();
for (var p in el.$tmp) el.$tmp[p] = null;
for (var d in Element.prototype) el[d] = null;
Garbage.elements[Garbage.elements.indexOf(el)] = null;
el.htmlElement = el.$tmp = el = null;
}
Garbage.elements.remove(null);
},
empty: function(){
Garbage.collect(window);
Garbage.collect(document);
Garbage.trash(Garbage.elements);
}
};
```
the lines `el.$tmp = {'opacity': 1};` (in collect method above) and `el.htmlElement = el.$tmp = el = null;` (in trash method above) are the only places in the source where this property is assigned that i could find, although it's called by various other methods, such as Element.setOpacity and Element.getStyle (specifically, only to return opacity value), as well as methods in the Tips class
1.2 might not have this issue, but in any case, hope that helps and sorry i couldn't help more
|
173,133 |
<p>1.
How can I reinterpret cast a float to an int (or a double to a long)?</p>
<pre><code>float f = 2.0f;
int i = (int)f; // causes conversion
</code></pre>
<p>I only want to copy the bit-pattern from <code>f</code> to <code>i</code>. How can this be done?</p>
<p>2.
The implicit and explicit operators in C# uses one intermediate object because the operator function is static</p>
<pre><code>public static implicit operator MyClass(double s)
{
return new MyClass(s);
}
..
..
MyClass m = 2.2; // this code uses 'm' and one intermediate object.
</code></pre>
<p>This is fine for reference types, but for value-types which are big (say 20-30 bytes), this will cause unnecessary data copy. Is my understanding correct? And If yes, then why doesn't C# have a non-static conversion operator or user-defined assignment operator so that the conversion/assignment takes place on 'this'? If it does, whats the way to do it?</p>
|
[
{
"answer_id": 173139,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx\" rel=\"noreferrer\">BitConverter</a> class can retrieve the bytes for any primitive type, which you can then use to create an int. Another option is <a href=\"http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx\" rel=\"noreferrer\">Buffer.BlockCopy</a> if you have large amounts of converting to do.</p>\n\n<pre><code>float ff = 2.0f;\nint ii = BitConverter.ToInt32(BitConverter.GetBytes(ff), 0);\n\nfloat[] ff = new float[...];\nint[] ii = new int[ff.Length];\nBuffer.BlockCopy(ff, 0, ii, 0, ff.Length * 4); // byte-wise copy of ff into ii\n</code></pre></li>\n<li><p>No there is no other option given in C#, however, I think that while you're correct in the sense that there will be a copy made, any sufficiently simple implementation will have JIT optimizations done, possibly removing the need for a copy.</p></li>\n</ol>\n"
},
{
"answer_id": 173186,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "<p>1: BitConverter (as sixlettervariables) is an option; as is unsafe code (which doesn't need an intermediate buffer):</p>\n\n<pre><code> float f = 2.0f;\n int i;\n // perform unsafe cast (preserving raw binary)\n unsafe\n {\n float* fRef = &f;\n i = *((int*)fRef);\n }\n Console.WriteLine(i);\n\n // prove same answer long-hand\n byte[] raw = BitConverter.GetBytes(f);\n int j = BitConverter.ToInt32(raw, 0); \n Console.WriteLine(j);\n</code></pre>\n\n<p>2: note that you should limit the size of structs. I can't find a citation fr it, but the number \"16 bytes\" (max, as a recommendation) seems to stick in my mind. Above this, consider an immutable reference-type (class).</p>\n"
},
{
"answer_id": 12898591,
"author": "Ani",
"author_id": 802203,
"author_profile": "https://Stackoverflow.com/users/802203",
"pm_score": 4,
"selected": false,
"text": "<p>Barring unsafe code - this is the fastest method I know of to perform a reinterpret:</p>\n\n<pre><code> [StructLayout(LayoutKind.Explicit)]\n private struct IntFloat\n {\n [FieldOffset(0)]\n public int IntValue;\n [FieldOffset(0)]\n public float FloatValue;\n }\n private static float Foo(float x)\n {\n var intFloat = new IntFloat { FloatValue = x };\n var floatAsInt = intFloat.IntValue;\n ...\n</code></pre>\n\n<p>Hope this helps someone.</p>\n"
},
{
"answer_id": 42080195,
"author": "Nick Strupat",
"author_id": 232574,
"author_profile": "https://Stackoverflow.com/users/232574",
"pm_score": 2,
"selected": false,
"text": "<p>This approach, while unsafe, works as a generic solution</p>\n\n<pre><code>static unsafe TDest ReinterpretCast<TSource, TDest>(TSource source)\n{\n var tr = __makeref(source);\n TDest w = default(TDest);\n var trw = __makeref(w);\n *((IntPtr*)&trw) = *((IntPtr*)&tr);\n return __refvalue(trw, TDest);\n}\n</code></pre>\n"
},
{
"answer_id": 49409433,
"author": "Elliott Prechter",
"author_id": 9529346,
"author_profile": "https://Stackoverflow.com/users/9529346",
"pm_score": 2,
"selected": false,
"text": "<p>This should be the fastest and cleanest way to do it:</p>\n\n<pre><code>public static class ReinterpretCastExtensions {\n public static unsafe float AsFloat( this int n ) => *(float*)&n;\n public static unsafe int AsInt( this float n ) => *(int*)&n;\n}\n\npublic static class MainClass {\n public static void Main( string[] args ) {\n Console.WriteLine( 1.0f.AsInt() );\n Console.WriteLine( 1.AsFloat() );\n }\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
1.
How can I reinterpret cast a float to an int (or a double to a long)?
```
float f = 2.0f;
int i = (int)f; // causes conversion
```
I only want to copy the bit-pattern from `f` to `i`. How can this be done?
2.
The implicit and explicit operators in C# uses one intermediate object because the operator function is static
```
public static implicit operator MyClass(double s)
{
return new MyClass(s);
}
..
..
MyClass m = 2.2; // this code uses 'm' and one intermediate object.
```
This is fine for reference types, but for value-types which are big (say 20-30 bytes), this will cause unnecessary data copy. Is my understanding correct? And If yes, then why doesn't C# have a non-static conversion operator or user-defined assignment operator so that the conversion/assignment takes place on 'this'? If it does, whats the way to do it?
|
1: BitConverter (as sixlettervariables) is an option; as is unsafe code (which doesn't need an intermediate buffer):
```
float f = 2.0f;
int i;
// perform unsafe cast (preserving raw binary)
unsafe
{
float* fRef = &f;
i = *((int*)fRef);
}
Console.WriteLine(i);
// prove same answer long-hand
byte[] raw = BitConverter.GetBytes(f);
int j = BitConverter.ToInt32(raw, 0);
Console.WriteLine(j);
```
2: note that you should limit the size of structs. I can't find a citation fr it, but the number "16 bytes" (max, as a recommendation) seems to stick in my mind. Above this, consider an immutable reference-type (class).
|
173,144 |
<p>I want to make sure people can't type the name of a PHP script in the URL and run it. What's the best way of doing this?</p>
<p>I could set a variable in the file that will be including this file, and then check that variable in the file being included, but is there an easier way?</p>
|
[
{
"answer_id": 173152,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 4,
"selected": true,
"text": "<p>You could check the URI and see if that file is being called with `</p>\n\n<pre><code>$_SERVER['SCRIPT_FILENAME']\n</code></pre>\n\n<p>or you could move the file outside the public folder, this is a better solution.</p>\n"
},
{
"answer_id": 173157,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "<p>The Zend Framework recommends you keep the files outside the web root, as Unkwntech has suggested. I'd say this is the safest and most fool proof solution.</p>\n"
},
{
"answer_id": 173161,
"author": "ThoriumBR",
"author_id": 16545,
"author_profile": "https://Stackoverflow.com/users/16545",
"pm_score": 0,
"selected": false,
"text": "<p>From a PHP Nuke module:</p>\n\n<pre><code><?php\nif (!eregi(\"modules.php\", $PHP_SELF)) {\n die (\"You can't access this file directly...\");\n}\n// more code ...\n?>\n</code></pre>\n\n<p>Replace modules.php with your file name, and that file cannot be called directly.</p>\n"
},
{
"answer_id": 173192,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": 0,
"selected": false,
"text": "<p>One way I've seen a lot is to create a variable that has to be present in every included file and check first thing in every include:</p>\n\n<pre><code>if(!isset($in_prog)){\nexit;\n}\n</code></pre>\n"
},
{
"answer_id": 173197,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 2,
"selected": false,
"text": "<p>I have long kept everything except directly viewable scripts outside the web root. Then configure PHP to include your script directory in the path. A typical set up would be:</p>\n\n<pre>appdir\n include\n html</pre>\n\n<p>In the PHP config (either the global PHP config or in a <code>.htaccess</code> file in the <code>html</code> directory) add this:</p>\n\n<pre>include_path = \".:/path/to/appdir/include:/usr/share/php\"</pre>\n\n<p>or (for Windows)</p>\n\n<pre>include_path = \".;c:\\path\\to\\appdir\\include;c:\\php\\includes\"</pre>\n\n<p>Note that this line is probably already in your <code>php.ini</code> file, but may be commented out allowing the defaults to work. It might also include other paths. Be sure to keep those, as well.</p>\n\n<p>If you are adding it to a .htaccess file, the format is:</p>\n\n<pre>php_value include_path .:/path/to/appdir/include:/usr/share/php</pre>\n\n<p>Finally, you can add the path programatically with something like this:</p>\n\n<pre><code>$parentPath = dirname(dirname(__FILE__));\n$ourPath = $parentPath . DIRECTORY_SEPARATOR . 'include';\n\n$includePath = ini_get('include_path');\n$includePaths = explode(PATH_SEPARATOR, $includePath);\n// Put our path between 'current directory' and rest of search path\nif ($includePaths[0] == '.') { \n array_shift($includePaths);\n}\n\narray_unshift($includePaths, '.', $ourPath);\n$includePath = implode(PATH_SEPARATOR, $includePaths);\nini_set('include_path', $includePath);\n</code></pre>\n\n<p><em>(Based on working code, but modified, so untested)</em></p>\n\n<p>This should be run in your frontend file (e.g. <code>index.php</code>). I put it in a separate include file which, after modifying the above, can be included with something like <code>#include '../includes/prepPath.inc'</code>.</p>\n\n<p>I've used all the versions I've presented here with success. The particular method used depends on preferences, and how the project will be deployed. In other words, if you can't modify <code>php.ini</code>, you obviously can't use that method</p>\n"
},
{
"answer_id": 173214,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": false,
"text": "<p>In a few of the open source applications I've poked around in, including Joomla and PHPBB, they declare a constant in the main includes file, and then verify that constant exists in each of the includes:</p>\n\n<pre><code>// index.php\nrequire_once 'includes.php';\n\n// includes.php\ndefine('IN_MY_PROJECT', true);\ninclude 'myInc.php';\n\n// myInc.php\ndefined('IN_MY_PROJECT') || die(\"No direct access, plsktnxbai\");\n</code></pre>\n"
},
{
"answer_id": 41519853,
"author": "Tristan Le Gacque",
"author_id": 6835308,
"author_profile": "https://Stackoverflow.com/users/6835308",
"pm_score": 0,
"selected": false,
"text": "<p>I guess the best way is to put files you want to include inside \"<strong>/include</strong>\" folder and put access right 700 to the folder</p>\n"
},
{
"answer_id": 59652999,
"author": "Rafael Carneiro de Moraes",
"author_id": 5427528,
"author_profile": "https://Stackoverflow.com/users/5427528",
"pm_score": 0,
"selected": false,
"text": "<p>This is an old question, but I found this one-liner quite effective:</p>\n\n<pre><code>$inc = get_included_files(); if(basename(__FILE__) == basename($inc[0])) exit();\n</code></pre>\n\n<p><strong>get_included_files()</strong> returns an array with the files included on the script. The first position is the root file, and the other positions are the included files.</p>\n"
},
{
"answer_id": 69076588,
"author": "D.A.H",
"author_id": 2360439,
"author_profile": "https://Stackoverflow.com/users/2360439",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative is to use this code:</p>\n<pre><code>// Prevent direct access, use exclusively as include only.\nif (count(get_included_files()) == 1) {\n http_response_code(403);\n die();\n}\n</code></pre>\n<p>If php file is called directly, then only one item is in included files array.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
I want to make sure people can't type the name of a PHP script in the URL and run it. What's the best way of doing this?
I could set a variable in the file that will be including this file, and then check that variable in the file being included, but is there an easier way?
|
You could check the URI and see if that file is being called with `
```
$_SERVER['SCRIPT_FILENAME']
```
or you could move the file outside the public folder, this is a better solution.
|
173,145 |
<p>Given:</p>
<pre><code>interface I
{
}
class B: I
{
}
class C: I
{
}
class A
{
public void Method(B arg)
{
}
public void Method(C arg)
{
}
public void Method(I arg)
{
// THIS is the method I want to simplify.
if (I is B)
{
this.Method(arg as B);
}
else if (I is C)
{
this.Method(arg as C);
}
}
}
</code></pre>
<p>I know that there are better ways to design this type of interactions, but because of
details which would take too long to explain this is not possible.
Since this pattern will be duplicated MANY times, I would like to replace the
conditional logic with a generic implementation which I could use just one line.
I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.</p>
<p>Any help would be appreciated.</p>
|
[
{
"answer_id": 173165,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't exist in a convenient form withing C# - <a href=\"https://stackoverflow.com/questions/156467/switch-pattern-matching-idea\">see here</a> for an idea based on F#'s pattern matching, that does exactly what you want. You can do some things with reflection to select the overload at runtime, but that will be very slow, and has severe issues if anything satisfies both overloads. If you had a return value you could use the conditional operator;</p>\n\n<pre><code>return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0);\n</code></pre>\n\n<p>Again - not pretty.</p>\n"
},
{
"answer_id": 173167,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 4,
"selected": false,
"text": "<p>I would put the method inside the interface and then let polymorphism decide which method to call</p>\n\n<pre><code>interface I\n{\n void Method();\n}\n\nclass B : I\n{\n public void Method() { /* previously A.Method(B) */}\n}\n\nclass C : I\n{\n public void Method() { /* previously A.Method(C) */ }\n}\n\nclass A\n{\n public void Method(I obj)\n { \n obj.Method();\n }\n}\n</code></pre>\n\n<p>Now when you need to add a new class, you only need to implement I.Method. You don't need to touch A.Method.</p>\n"
},
{
"answer_id": 173262,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 1,
"selected": false,
"text": "<p>This is kinda ugly but it gets the job done:</p>\n\n<pre><code>public void Method(B arg)\n{\n if (arg == null) return;\n...\n}\npublic void Method(C arg)\n{\n if (arg == null) return;\n...\n}\n\npublic void Method(I arg)\n{\n this.Method(arg as B);\n this.Method(arg as C);\n}\n</code></pre>\n\n<p>I don't think I would do it this way, though. It actually hurts looking at that. I'm sorry I forced you all to look at this as well.</p>\n"
},
{
"answer_id": 173263,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 0,
"selected": false,
"text": "<p>Easy. In Visual Basic I do this all the time using CallByName.</p>\n\n<pre><code>Sub MethodBase(value as Object)\n CallByName(Me, \"RealMethod\", CallType.Method, value)\n</code></pre>\n\n<p>This will call the overload of RealMethod that most closely matches the runtime type of value.</p>\n\n<p>I'm sure you can use CallByName from C# by importing Microsoft.VisualBasic.Interaction or by creating your own version using reflection.</p>\n"
},
{
"answer_id": 173397,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 4,
"selected": true,
"text": "<p>What you want is <a href=\"http://en.wikipedia.org/wiki/Double_dispatch\" rel=\"nofollow noreferrer\">double dispatch</a>, and <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">visitor pattern</a> in particular.</p>\n"
},
{
"answer_id": 176414,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 1,
"selected": false,
"text": "<pre><code>interface I\n{ \n} \n\nclass B : I\n{\n}\n\nclass C : I\n{\n} \n\nclass A \n{\n public void Method(B arg)\n {\n Console.WriteLine(\"I'm in B\");\n }\n\n public void Method(C arg)\n {\n Console.WriteLine(\"I'm in C\");\n }\n\n public void Method(I arg)\n {\n Type type = arg.GetType();\n\n MethodInfo method = typeof(A).GetMethod(\"Method\", new Type[] { type });\n method.Invoke(this, new I[] { arg });\n }\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25388/"
] |
Given:
```
interface I
{
}
class B: I
{
}
class C: I
{
}
class A
{
public void Method(B arg)
{
}
public void Method(C arg)
{
}
public void Method(I arg)
{
// THIS is the method I want to simplify.
if (I is B)
{
this.Method(arg as B);
}
else if (I is C)
{
this.Method(arg as C);
}
}
}
```
I know that there are better ways to design this type of interactions, but because of
details which would take too long to explain this is not possible.
Since this pattern will be duplicated MANY times, I would like to replace the
conditional logic with a generic implementation which I could use just one line.
I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.
Any help would be appreciated.
|
What you want is [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch), and [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) in particular.
|
173,149 |
<p>Can someone please explain how to remove the background/borders off an embedded CrystalReportViewer control in Visual Studio 2008.</p>
<p>I'm trying to remove the light gray (below the "Crystal Report" heading) and then the darker gray underneath that. I want to be left with only the white box and the report inside this.</p>
<p>This is the output I'm currently getting:</p>
<p><strong><a href="http://img411.imageshack.us/my.php?image=screenshotml3.jpg" rel="nofollow noreferrer">http://img411.imageshack.us/my.php?image=screenshotml3.jpg</a></strong></p>
<p>The HTML snippet is:</p>
<pre><code><div>
<h2>Crystal Report</h2>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
AutoDataBind="true" DisplayToolbar="False" />
</div>
</code></pre>
<p>The C# code snippet is: </p>
<pre><code>string strReportName = "CrystalReport";
string strReportPath = Server.MapPath(strReportName + ".rpt");
ReportDocument rptDocument = new ReportDocument();
rptDocument.Load(strReportPath);
CrystalReportViewer1.HasCrystalLogo = false;
CrystalReportViewer1.HasDrilldownTabs = false;
CrystalReportViewer1.HasDrillUpButton = false;
CrystalReportViewer1.HasExportButton = false;
CrystalReportViewer1.HasGotoPageButton = false;
CrystalReportViewer1.HasPageNavigationButtons = false;
CrystalReportViewer1.HasPrintButton = false;
CrystalReportViewer1.HasRefreshButton = false;
CrystalReportViewer1.HasSearchButton = false;
CrystalReportViewer1.HasToggleGroupTreeButton = false;
CrystalReportViewer1.HasToggleParameterPanelButton = false;
CrystalReportViewer1.HasZoomFactorList = false;
CrystalReportViewer1.DisplayToolbar = false;
CrystalReportViewer1.EnableDrillDown = false;
CrystalReportViewer1.BestFitPage = true;
CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
CrystalReportViewer1.BackColor = System.Drawing.Color.Red;
CrystalReportViewer1.BorderColor = System.Drawing.Color.Green;
CrystalReportViewer1.CssClass
CrystalReportViewer1.Height = 200;
CrystalReportViewer1.Width = 500;
CrystalReportViewer1.ReportSource = rptDocument;
</code></pre>
|
[
{
"answer_id": 173165,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't exist in a convenient form withing C# - <a href=\"https://stackoverflow.com/questions/156467/switch-pattern-matching-idea\">see here</a> for an idea based on F#'s pattern matching, that does exactly what you want. You can do some things with reflection to select the overload at runtime, but that will be very slow, and has severe issues if anything satisfies both overloads. If you had a return value you could use the conditional operator;</p>\n\n<pre><code>return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0);\n</code></pre>\n\n<p>Again - not pretty.</p>\n"
},
{
"answer_id": 173167,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 4,
"selected": false,
"text": "<p>I would put the method inside the interface and then let polymorphism decide which method to call</p>\n\n<pre><code>interface I\n{\n void Method();\n}\n\nclass B : I\n{\n public void Method() { /* previously A.Method(B) */}\n}\n\nclass C : I\n{\n public void Method() { /* previously A.Method(C) */ }\n}\n\nclass A\n{\n public void Method(I obj)\n { \n obj.Method();\n }\n}\n</code></pre>\n\n<p>Now when you need to add a new class, you only need to implement I.Method. You don't need to touch A.Method.</p>\n"
},
{
"answer_id": 173262,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 1,
"selected": false,
"text": "<p>This is kinda ugly but it gets the job done:</p>\n\n<pre><code>public void Method(B arg)\n{\n if (arg == null) return;\n...\n}\npublic void Method(C arg)\n{\n if (arg == null) return;\n...\n}\n\npublic void Method(I arg)\n{\n this.Method(arg as B);\n this.Method(arg as C);\n}\n</code></pre>\n\n<p>I don't think I would do it this way, though. It actually hurts looking at that. I'm sorry I forced you all to look at this as well.</p>\n"
},
{
"answer_id": 173263,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 0,
"selected": false,
"text": "<p>Easy. In Visual Basic I do this all the time using CallByName.</p>\n\n<pre><code>Sub MethodBase(value as Object)\n CallByName(Me, \"RealMethod\", CallType.Method, value)\n</code></pre>\n\n<p>This will call the overload of RealMethod that most closely matches the runtime type of value.</p>\n\n<p>I'm sure you can use CallByName from C# by importing Microsoft.VisualBasic.Interaction or by creating your own version using reflection.</p>\n"
},
{
"answer_id": 173397,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 4,
"selected": true,
"text": "<p>What you want is <a href=\"http://en.wikipedia.org/wiki/Double_dispatch\" rel=\"nofollow noreferrer\">double dispatch</a>, and <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">visitor pattern</a> in particular.</p>\n"
},
{
"answer_id": 176414,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 1,
"selected": false,
"text": "<pre><code>interface I\n{ \n} \n\nclass B : I\n{\n}\n\nclass C : I\n{\n} \n\nclass A \n{\n public void Method(B arg)\n {\n Console.WriteLine(\"I'm in B\");\n }\n\n public void Method(C arg)\n {\n Console.WriteLine(\"I'm in C\");\n }\n\n public void Method(I arg)\n {\n Type type = arg.GetType();\n\n MethodInfo method = typeof(A).GetMethod(\"Method\", new Type[] { type });\n method.Invoke(this, new I[] { arg });\n }\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Can someone please explain how to remove the background/borders off an embedded CrystalReportViewer control in Visual Studio 2008.
I'm trying to remove the light gray (below the "Crystal Report" heading) and then the darker gray underneath that. I want to be left with only the white box and the report inside this.
This is the output I'm currently getting:
**<http://img411.imageshack.us/my.php?image=screenshotml3.jpg>**
The HTML snippet is:
```
<div>
<h2>Crystal Report</h2>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
AutoDataBind="true" DisplayToolbar="False" />
</div>
```
The C# code snippet is:
```
string strReportName = "CrystalReport";
string strReportPath = Server.MapPath(strReportName + ".rpt");
ReportDocument rptDocument = new ReportDocument();
rptDocument.Load(strReportPath);
CrystalReportViewer1.HasCrystalLogo = false;
CrystalReportViewer1.HasDrilldownTabs = false;
CrystalReportViewer1.HasDrillUpButton = false;
CrystalReportViewer1.HasExportButton = false;
CrystalReportViewer1.HasGotoPageButton = false;
CrystalReportViewer1.HasPageNavigationButtons = false;
CrystalReportViewer1.HasPrintButton = false;
CrystalReportViewer1.HasRefreshButton = false;
CrystalReportViewer1.HasSearchButton = false;
CrystalReportViewer1.HasToggleGroupTreeButton = false;
CrystalReportViewer1.HasToggleParameterPanelButton = false;
CrystalReportViewer1.HasZoomFactorList = false;
CrystalReportViewer1.DisplayToolbar = false;
CrystalReportViewer1.EnableDrillDown = false;
CrystalReportViewer1.BestFitPage = true;
CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
CrystalReportViewer1.BackColor = System.Drawing.Color.Red;
CrystalReportViewer1.BorderColor = System.Drawing.Color.Green;
CrystalReportViewer1.CssClass
CrystalReportViewer1.Height = 200;
CrystalReportViewer1.Width = 500;
CrystalReportViewer1.ReportSource = rptDocument;
```
|
What you want is [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch), and [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) in particular.
|
173,209 |
<p>Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.</p>
|
[
{
"answer_id": 173221,
"author": "MrBoJangles",
"author_id": 13578,
"author_profile": "https://Stackoverflow.com/users/13578",
"pm_score": 4,
"selected": true,
"text": "<p>So here's the answer from MSDN:</p>\n\n<blockquote>\n <p>Choos[e] \"Add New Data Source\" from the\n Data menu.[And follow the connection wizard]</p>\n</blockquote>\n\n<p>Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:</p>\n\n<ul>\n<li>Click on Tools >> Connect to Database...</li>\n<li>Select \"Microsoft SQL Server Database File\", take the default Data provider, and click OK</li>\n<li>On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.</li>\n</ul>\n\n<p>Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the \"<code>AttachDbFilename</code>\" attribute and value. Example:</p>\n\n<p>The raw text from the Advanced panel:</p>\n\n<pre><code>Data Source=.\\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True\n</code></pre>\n\n<p>The actual entry in the web.config:</p>\n\n<pre><code><add name=\"SomeDataBase\" connectionString=\"Data Source=.\\SQLEXPRESS; \nAttachDbFilename=C:\\Development\\blahBlah\\App_Data\\SomeDataFile.mdf;\nIntegrated Security=True; Connect Timeout=30; User Instance=True\" />\n</code></pre>\n"
},
{
"answer_id": 173375,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 4,
"selected": false,
"text": "<p>A great resource I always keep around is <a href=\"http://connectionstrings.com\" rel=\"noreferrer\">connectionstrings.com</a>.\nIt's really handy for finding these connection strings when you can't find an example.</p>\n\n<p>Particularly <a href=\"http://connectionstrings.com/?carrier=sqlserver2005\" rel=\"noreferrer\">this page</a> applied to your problem</p>\n\n<p><strong>Attach a database file on connect to a local SQL Server Express instance</strong></p>\n\n<pre><code>Driver={SQL Native Client};Server=.\\SQLExpress;AttachDbFilename=c:\\asd\\qwe\\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;\n</code></pre>\n"
},
{
"answer_id": 180113,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Just one more -- i've always kept a udl file on my desktop to easily create and test connection strings. If you've never done it before - create a new text file and name it to connection.udl (the ext is the only important part). Open the file, start on the Provider tab and work your way through. Once you're happy with the connection rename the file giving it a .txt extension. Open the file and copy the string - it's relatively easy and lets you test the connection before using it.</p>\n"
},
{
"answer_id": 1998322,
"author": "Spice",
"author_id": 243065,
"author_profile": "https://Stackoverflow.com/users/243065",
"pm_score": 2,
"selected": false,
"text": "<pre><code><add name=\"Your Database\" connectionString=\"metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Expanse.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True&quot;\" providerName=\"System.Data.EntityClient\"/>\n</code></pre>\n"
},
{
"answer_id": 33353107,
"author": "Sudheesh",
"author_id": 4913768,
"author_profile": "https://Stackoverflow.com/users/4913768",
"pm_score": 1,
"selected": false,
"text": "<p>In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add</p>\n\n<pre><code>string constr = @\"Data Source=(LocalDB)\\v11.0; AttachDbFilename=|DataDirectory|\\myData.mdf; Integrated Security=True; Connect Timeout=30;\";\nusing (SqlConnection conn = new SqlConnection(constr))\nstring constr = ConfigurationManager.ConnectionStrings[\"myData\"].ToString();\n\nusing (SqlConnection conn = new SqlConnection(constr))\n{\nsqlQuery=\" Your Query here\"\nSqlCommand com = new SqlCommand(sqlQuery, conn);\ncom.Connection.Open();\nstring strOutput = (string)com.ExecuteScalar();\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
] |
Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App\_Data folder (an .mdf "database"). Seems easy, and it is once you know how.
|
So here's the answer from MSDN:
>
> Choos[e] "Add New Data Source" from the
> Data menu.[And follow the connection wizard]
>
>
>
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
* Click on Tools >> Connect to Database...
* Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
* On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "`AttachDbFilename`" attribute and value. Example:
The raw text from the Advanced panel:
```
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
```
The actual entry in the web.config:
```
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
```
|
173,212 |
<p>I just moved to a new hosting company and now whenever a string gets escaped using:</p>
<pre><code>mysql_real_escape_string($str);
</code></pre>
<p>the slashes remain in the database. This is the first time I've ever seen this happen so none of my scripts use</p>
<pre><code>stripslashes()
</code></pre>
<p>anymore.</p>
<p>This is on a CentOS 4.5 64bit running php 5.2.6 as fastcgi on a lighttpd 1.4 server. I've ensured that all magic_quotes options are off and the mysql client api is 5.0.51a.</p>
<p>I have the same issue on all 6 of my webservers.</p>
<p>Any help would be appreciated.</p>
<p>Thanks.</p>
<h3>Edit:</h3>
<h3>Magic Quotes isn't on. Please don't recommend turning it off. THIS IS NOT THE ISSUE.</h3>
|
[
{
"answer_id": 173234,
"author": "Steve Obbayi",
"author_id": 11190,
"author_profile": "https://Stackoverflow.com/users/11190",
"pm_score": -1,
"selected": false,
"text": "<p><code>mysql_real_escape_string($str);</code> is supposed to do exactly that. it is meant to add backslashes to special characters especially when you want to pass the query to mysql. Take note that it also takes into account the character set of mysql.</p>\n\n<p>For safer coding practices it would be good to edit your code and use <code>stripslashes()</code> to read out the data and remove the slashes.</p>\n"
},
{
"answer_id": 173238,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 4,
"selected": false,
"text": "<p>The host that you've moved probably has <code>magic_quotes_runtime</code> turned on. You can turn it off with <code>set_magic_quotes_runtime(0)</code>.</p>\n\n<p>Please turn off <code>magic_quotes_runtime</code>, and then change your code to use bind variables, rather than using the string escaping.</p>\n"
},
{
"answer_id": 173387,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>it sounds as though you have magic quotes turned on. Turning it off isn't too hard: just create a file in your root directory called <code>.htaccess</code> and put this line in it:</p>\n\n<pre><code>php_flag magic_quotes off\n</code></pre>\n\n<p>If that's not possible for whatever reason, or you want to change your application to be able to handle magic quotes, use this technique:</p>\n\n<p>Instead of accessing the request variables directly, use a function instead. That function can then check if magic quotes is on or off and strip out slashes accordingly. Simply running stripslashes() over everything won't work, because you'll get rid of slashes which you actually want.</p>\n\n<pre><code>function getVar($key) {\n if (get_magic_quotes_gpc()) {\n return stripslashes($_POST[$key]);\n } else {\n return $_POST[$key];\n }\n}\n\n$x = getVar('x');\n</code></pre>\n\n<p>Now that you've got that, all your incoming variables are ready to be escaped again and <code>mysql_real_escape_string()</code> won't stuff them up.</p>\n"
},
{
"answer_id": 175925,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 0,
"selected": false,
"text": "<p>You must probably have magic quotes turned on. Figuring out exactly how to turn it off can be quite a headache in PHP. While you can turn off magic quotes with <code>set_magic_quotes_runtime(0)</code>, it isn't enough -- Magic quotes has already altered the input data at this point, so you must undo the change. Try with this snippet: <a href=\"http://talks.php.net/show/php-best-practices/26\" rel=\"nofollow noreferrer\">http://talks.php.net/show/php-best-practices/26</a></p>\n\n<p>Or better yet -- Disable magic quotes in <code>php.ini</code>, and any .htaccess files it may be set in.</p>\n"
},
{
"answer_id": 812872,
"author": "Ryaner",
"author_id": 99215,
"author_profile": "https://Stackoverflow.com/users/99215",
"pm_score": -1,
"selected": false,
"text": "<p>Function below will correctly remove slashes <i>before</i> inserting into the database. I know you said magic quotes isn't on but something is adding slashes so try the following page and see the output. It'll help figure out where. Call with page.php?var=something-with'data_that;will`be|escaped</p>\n\n<p>You will most likely see number three outputting more slashes than needed.</p>\n\n<p>*Change the db details too.</p>\n\n<pre><code><?php\n\n$db = mysql_connect('host', 'user', 'pass');\n\n$var = $_REQUEST['var'];\necho \"1: $var :1<br />\";\necho \"2: \".stripslashes($var).\" :2<br />\";\necho \"3: \".mysql_real_escape_string($var).\" :3<br />\";\necho \"4: \".quote_smart($var).\" :4<br />\";\n\n\nfunction quote_smart($value)\n{\n // Stripslashes is gpc on\n if (get_magic_quotes_gpc())\n {\n $value = stripslashes($value);\n }\n // Quote if not a number or a numeric string\n if ( !is_numeric($value) )\n {\n $value = mysql_real_escape_string($value);\n }\n return $value;\n}\n</code></pre>\n\n<p>?></p>\n"
},
{
"answer_id": 1932579,
"author": "Mike Weller",
"author_id": 49658,
"author_profile": "https://Stackoverflow.com/users/49658",
"pm_score": 2,
"selected": false,
"text": "<p>I can think of a number of things that could cause this. But it depends how you are invoking SQL queries. If you moved to use parameterized queries like with PDO, then escaping is unnecessary which means the call to <code>mysql_real_escape_string</code> is adding the extra slashes.</p>\n\n<p>If you are using <code>mysql_query</code> etc. then there must be some code somewhere like <code>addslashes</code> which is doing this. This could either be before the data is going into the database, or after.</p>\n\n<p>Also you say you have disabled magic quotes... if you haven't already, just do a hard check in the code with something like this:</p>\n\n<pre><code>echo htmlentities($_GET['value']); // or $_POST, whichever is appropriate\n</code></pre>\n\n<p>Make sure there are no slashes in that value, then also check this:</p>\n\n<pre><code>echo \"Magic quotes is \" . (get_magic_quotes_gpc() ? \"ON\" : \"OFF\");\n</code></pre>\n\n<p>I know you've said multiple times it isn't magic quotes, but for us guys trying to help we need to be sure you have checked the actual PHP output rather than just changing the config (which might not have worked).</p>\n"
},
{
"answer_id": 12393430,
"author": "Milan",
"author_id": 1438675,
"author_profile": "https://Stackoverflow.com/users/1438675",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure if I understand the issue correctly but I had a very same problem. No matter what I did the slashes were there when the string got escaped. Since I needed the inserted value to be in the exact same format as it was entered I used</p>\n\n<pre><code>htmlentities($inserted_value)\n</code></pre>\n\n<p>this will leave all inserted quote marks unescaped but harmless.</p>\n"
},
{
"answer_id": 14274874,
"author": "Your Common Sense",
"author_id": 285587,
"author_profile": "https://Stackoverflow.com/users/285587",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>the slashes remain in the database.</p>\n</blockquote>\n\n<p>It means that your data gets double escaped.</p>\n\n<p>There are 2 possible reasons:</p>\n\n<ol>\n<li><p>magic quotes <strong>are</strong> on, despite of your feeling. Double-check it</p></li>\n<li><p>There is some code in your application, that just mimic magic quotes behaviour, escaping all input.<br>\nThis is very common misconception to have a general escaping function to \"protect\" all the incoming data. While it does no good at all, it also responsible for the cases like this.<br>\nOf so - just find that function and wipe it out.</p></li>\n</ol>\n"
},
{
"answer_id": 14275108,
"author": "Wijnand de Ridder",
"author_id": 1969398,
"author_profile": "https://Stackoverflow.com/users/1969398",
"pm_score": 0,
"selected": false,
"text": "<p>What might be the problem (it was with us) that you use <code>mysql_real_escape_string()</code> multiple times on the same var. When you use it multiple times, it will add the slashes.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538/"
] |
I just moved to a new hosting company and now whenever a string gets escaped using:
```
mysql_real_escape_string($str);
```
the slashes remain in the database. This is the first time I've ever seen this happen so none of my scripts use
```
stripslashes()
```
anymore.
This is on a CentOS 4.5 64bit running php 5.2.6 as fastcgi on a lighttpd 1.4 server. I've ensured that all magic\_quotes options are off and the mysql client api is 5.0.51a.
I have the same issue on all 6 of my webservers.
Any help would be appreciated.
Thanks.
### Edit:
### Magic Quotes isn't on. Please don't recommend turning it off. THIS IS NOT THE ISSUE.
|
The host that you've moved probably has `magic_quotes_runtime` turned on. You can turn it off with `set_magic_quotes_runtime(0)`.
Please turn off `magic_quotes_runtime`, and then change your code to use bind variables, rather than using the string escaping.
|
173,219 |
<p>I run php 5.2.6 as a cgi under lighttpd 1.4 and for some reason it's always running as root. All php-cgi processes in are owned by root and all files written to the file system are owned by root. </p>
<p>I've tried setting the user in lighttpd as non privileged, and confirmed, it's running right it's just php that runs as root. </p>
<p>How would I set php-cgi to run as a safer user?</p>
|
[
{
"answer_id": 173229,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible that you have a fastcgi process that was started on the server as root. If this is the case, then the fastcgi process will continue to run php processes called from lighttpd.</p>\n\n<p>I suggest killing the fastcgi processes on your server and restarting lighttpd.</p>\n\n<p>You might also want to take a look at any startup scripts that might launch the fastcgi daemon.</p>\n"
},
{
"answer_id": 173502,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li><p>Ensure :</p>\n\n<pre><code>server.username = \"nonprivuser\"\nserver.groupname = \"nonprivgroup\"\n</code></pre></li>\n<li><p>stop lighttpd. </p></li>\n<li>check for existing php processes and kill them. </li>\n<li>start lighttpd</li>\n<li>check php processes are running as non priv</li>\n</ol>\n\n<p>if php is still running as root, then you possibly have a SETUID script somewhere loading them ( you really shouldn't, but its feasible )</p>\n\n<p>if this is the case, check the file 'bin-path' refers to doesn't have anything funky on it.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538/"
] |
I run php 5.2.6 as a cgi under lighttpd 1.4 and for some reason it's always running as root. All php-cgi processes in are owned by root and all files written to the file system are owned by root.
I've tried setting the user in lighttpd as non privileged, and confirmed, it's running right it's just php that runs as root.
How would I set php-cgi to run as a safer user?
|
1. Ensure :
```
server.username = "nonprivuser"
server.groupname = "nonprivgroup"
```
2. stop lighttpd.
3. check for existing php processes and kill them.
4. start lighttpd
5. check php processes are running as non priv
if php is still running as root, then you possibly have a SETUID script somewhere loading them ( you really shouldn't, but its feasible )
if this is the case, check the file 'bin-path' refers to doesn't have anything funky on it.
|
173,241 |
<p>What library should be included to use TransparentBlt?</p>
<p>This is VC98 (Visual Studio 6) linking to the Gdi32.lib. (Other GDI functions such as BitBlt link as expected), and the compilers compiles with out error or warning.</p>
<p>Even though the Gdi32.lib is included, yet the linker returns this error:</p>
<pre>
mtcombo.obj : error LNK2001: unresolved external symbol __imp__TransparentBlt@44
C:\Work\Montel\Targ2_12\guitest.exe : fatal error LNK1120: 1 unresolved externals
</pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 173251,
"author": "Peter Parker",
"author_id": 23264,
"author_profile": "https://Stackoverflow.com/users/23264",
"pm_score": 3,
"selected": true,
"text": "<p>AFAIK, you will need the Msimg32.lib</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms532303(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms532303(VS.85).aspx</a></p>\n"
},
{
"answer_id": 173253,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 1,
"selected": false,
"text": "<p>Msimg32.lib</p>\n\n<p>FYI you can search the functions on <a href=\"http://msdn.microsoft.com/library\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/library</a> and at the bottom it will tell you what library you need.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137/"
] |
What library should be included to use TransparentBlt?
This is VC98 (Visual Studio 6) linking to the Gdi32.lib. (Other GDI functions such as BitBlt link as expected), and the compilers compiles with out error or warning.
Even though the Gdi32.lib is included, yet the linker returns this error:
```
mtcombo.obj : error LNK2001: unresolved external symbol __imp__TransparentBlt@44
C:\Work\Montel\Targ2_12\guitest.exe : fatal error LNK1120: 1 unresolved externals
```
What am I missing?
|
AFAIK, you will need the Msimg32.lib
<http://msdn.microsoft.com/en-us/library/ms532303(VS.85).aspx>
|
173,278 |
<p>The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.</p>
<p>The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.</p>
|
[
{
"answer_id": 173323,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 8,
"selected": true,
"text": "<p>You can call <a href=\"https://docs.python.org/library/os.html#os._exit\" rel=\"noreferrer\"><code>os._exit()</code></a> to directly exit, without throwing an exception:</p>\n\n<pre><code>import os\nos._exit(1)\n</code></pre>\n\n<p>This bypasses all of the python shutdown logic, such as the <code>atexit</code> module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be returned by the process.</p>\n"
},
{
"answer_id": 13723190,
"author": "MestreLion",
"author_id": 624066,
"author_profile": "https://Stackoverflow.com/users/624066",
"pm_score": 6,
"selected": false,
"text": "<p>As Jerub said, <code>os._exit(1)</code> is your answer. But, considering it bypasses <em>all</em> cleanup procedures, including <code>finally:</code> blocks, closing files, etc, it should really be avoided at all costs. So may I present a safer(-ish) way of using it?</p>\n<p>If your problem is <code>SystemExit</code> being caught at outer levels (i.e., unittest), then <em><strong>be the outer level yourself!</strong></em> Wrap your main code in a <code>try</code>/<code>except</code> block, catch <code>SystemExit</code>, and call <code>os._exit()</code> there, <em>and <strong>only</strong> there!</em> This way you may call <code>sys.exit</code> normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and <em>then</em> calling <code>os._exit</code>.</p>\n<p>You can even choose which exits are the "emergency" ones. The code below is an example of such approach:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys, os\n\nEMERGENCY = 255 # can be any number actually\n\ntry:\n # wrap your whole code here ...\n # ... some code\n if x: sys.exit()\n # ... some more code\n if y: sys.exit(EMERGENCY) # use only for emergency exits\n ... # yes, this is valid python!\n\n # Might instead wrap all code in a function\n # It's a common pattern to exit with main's return value, if any\n sys.exit(main())\n\nexcept SystemExit as e:\n if e.code != EMERGENCY:\n raise # normal exit, let unittest catch it at the outer level\nelse:\n os._exit(EMERGENCY) # try to stop *that*!\n</code></pre>\n<p>As for <code>e.code</code> that some readers were unaware of, it is <a href=\"https://docs.python.org/3/library/exceptions.html#SystemExit\" rel=\"noreferrer\">documented</a>, as well as the attributes of all built-in exceptions.</p>\n"
},
{
"answer_id": 61923077,
"author": "Jason",
"author_id": 3745065,
"author_profile": "https://Stackoverflow.com/users/3745065",
"pm_score": -1,
"selected": false,
"text": "<p>You can also use quit, see example below:</p>\n\n<pre><code>while True:\nprint('Type exit to exit.')\nresponse = input()\nif response == 'exit':\n quit(0)\nprint('You typed ' + response + '.')\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] |
The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.
The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.
|
You can call [`os._exit()`](https://docs.python.org/library/os.html#os._exit) to directly exit, without throwing an exception:
```
import os
os._exit(1)
```
This bypasses all of the python shutdown logic, such as the `atexit` module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be returned by the process.
|
173,290 |
<p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
|
[
{
"answer_id": 173299,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 7,
"selected": true,
"text": "<p>You actually want to do this:</p>\n\n<pre><code>for i, tag in enumerate(tag):\n tagDict[tag] = i\n</code></pre>\n\n<p>The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.</p>\n"
},
{
"answer_id": 173300,
"author": "mbesso",
"author_id": 9510,
"author_profile": "https://Stackoverflow.com/users/9510",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is what you want to do:</p>\n\n<pre><code>d = {}\nfor i, tag in enumerate(ithTag):\n d[tag] = i\n</code></pre>\n"
},
{
"answer_id": 173301,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>tagDict[ithTag] = i\n</code></pre>\n"
},
{
"answer_id": 173369,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to be clever:</p>\n\n<pre><code>tagDict.update(map(reversed, enumerate(tag)))\n</code></pre>\n\n<p>Thanks to Brian for the update. This is apparently ~5% faster than the iterative version.</p>\n\n<p>(EDIT: Thanks saverio for pointing out my answer was incorrect (now fixed). Probably the most efficient/Pythonic way would be Torsten Marek's answer, slightly modified:</p>\n\n<pre><code>tagDict.update((t, i) for (i,t) in enumerate(tag))\n</code></pre>\n\n<p>)</p>\n"
},
{
"answer_id": 179005,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": false,
"text": "<p>It's a one-liner:</p>\n\n<pre><code>tagDict = dict((t, i) for i, t in enumerate(tag))\n</code></pre>\n"
},
{
"answer_id": 13350988,
"author": "Vanuan",
"author_id": 99024,
"author_profile": "https://Stackoverflow.com/users/99024",
"pm_score": 2,
"selected": false,
"text": "<p>I think what you want is this:</p>\n\n<pre><code>for i, ithTag in enumerate(tag):\n tagDict.update({ithTag: i})\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17085/"
] |
I have a list string tag.
I am trying to initialize a dictionary with the key as the tag string and values as the array index.
```
for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
```
The above returns me {'ithTag': 608} *608 is the 608th index*
My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.
I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,
Thanks!
|
You actually want to do this:
```
for i, tag in enumerate(tag):
tagDict[tag] = i
```
The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.
|
173,295 |
<p>How do you select a datagridview row on a right-click?</p>
|
[
{
"answer_id": 173315,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code> // Clear all the previously selected rows\n foreach (DataGridViewRow row in yourDataGridView.Rows)\n {\n row.Selected = false;\n }\n\n // Get the selected Row\n DataGridView.HitTestInfo info = yourDataGridView.HitTest( e.X, e.Y );\n\n // Set as selected\n yourDataGridView.Rows[info.RowIndex].Selected = true;\n</code></pre>\n"
},
{
"answer_id": 208012,
"author": "balexandre",
"author_id": 28004,
"author_profile": "https://Stackoverflow.com/users/28004",
"pm_score": 3,
"selected": false,
"text": "<p>the cool thing is add a menu on that right click, for example with option like \"View client information\", \"verify last invoices\", \"Add a log entry to this client\", etc. </p>\n\n<p>you just need to add a ContextMenuStrip object, add your menu entries, and in the DataGridView properties just select the ContextMenuStrip of it.</p>\n\n<p>This would create a new menu in the row the user right clicked with all the options, then all you need to do is make your magic :)</p>\n\n<p>remember that you need JvR code to get what row was the user in, then grab the cell that contains the Client ID for example and pass that info.</p>\n\n<p>hope it helps improving your application</p>\n\n<p><a href=\"http://img135.imageshack.us/img135/5246/picture1ku5.png\" rel=\"noreferrer\">http://img135.imageshack.us/img135/5246/picture1ku5.png</a></p>\n\n<p><a href=\"http://img72.imageshack.us/img72/6038/picture2lb8.png\" rel=\"noreferrer\">http://img72.imageshack.us/img72/6038/picture2lb8.png</a></p>\n"
},
{
"answer_id": 457509,
"author": "Johann Blais",
"author_id": 363385,
"author_profile": "https://Stackoverflow.com/users/363385",
"pm_score": 0,
"selected": false,
"text": "<p>You can use JvR's code in the MouseDown event of your DataGridView.</p>\n"
},
{
"answer_id": 521173,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "<p>Subclass the <code>DataGridView</code> and create a <code>MouseDown</code> event for the grid,</p>\n\n<pre><code>\nprivate void SubClassedGridView_MouseDown(object sender, MouseEventArgs e)\n{\n // Sets is so the right-mousedown will select a cell\n DataGridView.HitTestInfo hti = this.HitTest(e.X, e.Y);\n // Clear all the previously selected rows\n this.ClearSelection();\n\n // Set as selected\n this.Rows[hti.RowIndex].Selected = true;\n}\n</code></pre>\n"
},
{
"answer_id": 939275,
"author": "Alan Christensen",
"author_id": 84590,
"author_profile": "https://Stackoverflow.com/users/84590",
"pm_score": 5,
"selected": false,
"text": "<p>Make it behave similarly to the left mouse button? e.g.</p>\n\n<pre><code>private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n{\n if (e.Button == MouseButtons.Right)\n {\n dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1013225,
"author": "Jürgen Steinblock",
"author_id": 98491,
"author_profile": "https://Stackoverflow.com/users/98491",
"pm_score": 0,
"selected": false,
"text": "<p>You have to do two things:</p>\n\n<ol>\n<li><p>Clear all rows and Select the current. I loop through all rows and use the Bool Expression <code>i = e.RowIndex</code> for this</p></li>\n<li><p>If you have done Step 1 you still have a big pitfall:<br>\nDataGridView1.CurrentRow does not return your previously selected row (which is quite dangerous). Since CurrentRow is Readonly you have to do </p>\n\n<p><code>Me.CurrentCell = Me.Item(e.ColumnIndex, e.RowIndex)</code></p>\n\n<pre><code>Protected Overrides Sub OnCellMouseDown(\n ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs)\n\n MyBase.OnCellMouseDown(e)\n\n Select Case e.Button\n Case Windows.Forms.MouseButtons.Right\n If Me.Rows(e.RowIndex).Selected = False Then\n For i As Integer = 0 To Me.RowCount - 1\n SetSelectedRowCore(i, i = e.RowIndex)\n Next\n End If\n\n Me.CurrentCell = Me.Item(e.ColumnIndex, e.RowIndex)\n End Select\n\nEnd Sub\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 59675151,
"author": "IT Vlogs",
"author_id": 1289476,
"author_profile": "https://Stackoverflow.com/users/1289476",
"pm_score": 1,
"selected": false,
"text": "<p>from <code>@Alan Christensen</code> code convert to VB.NET</p>\n\n<pre><code>Private Sub dgvCustomers_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvCustomers.CellMouseDown\n If e.Button = MouseButtons.Right Then\n dgvCustomers.CurrentCell = dgvCustomers(e.ColumnIndex, e.RowIndex)\n End If\nEnd Sub\n</code></pre>\n\n<p>I am tested on VS 2017 it working for me!!!</p>\n"
},
{
"answer_id": 63189155,
"author": "Deluxe23",
"author_id": 10423075,
"author_profile": "https://Stackoverflow.com/users/10423075",
"pm_score": 1,
"selected": false,
"text": "<pre><code>If e.Button = MouseButtons.Right Then\n DataGridView1.CurrentCell = DataGridView1(e.ColumnIndex, e.RowIndex)\nEnd If\n</code></pre>\n<p>code works in VS2019 too</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25078/"
] |
How do you select a datagridview row on a right-click?
|
Make it behave similarly to the left mouse button? e.g.
```
private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];
}
}
```
|
173,305 |
<p>I have a <code>QTreeView</code> class with a context menu installed as follows:</p>
<pre><code>m_ui.tree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_ui.tree, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowTreeContextMenu(const QPoint&)));
...
void ShowTreeContextMenu(const QPoint& point)
{
m_treeContextMenu->exec(m_ui.tree->viewport()->mapToGlobal(point));
}
</code></pre>
<p>However when the context menu is being displayed the <code>QTreeView</code> will no longer respond to mouse clicks. Clicking on an item in the <code>QTreeView</code> while the context menu is displayed will remove the context menu but does not select the clicked item.</p>
<p>This is especially disorientating when right clicking on a new item, as the context menu pops up over the new item, but as the item was not selected the contents of the context menu are referring to the previously selected item.</p>
|
[
{
"answer_id": 173488,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 2,
"selected": false,
"text": "<p>A possible solution which I haven't verified would be to capture the click event of the right click, manually make the selection in the tree view and then invoking the parent click event which will in turn activate the context menu.</p>\n"
},
{
"answer_id": 173535,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 1,
"selected": false,
"text": "<p>Subclass the QTreeView and add the protected method void contextMenuEvent(QContextMenuEvent *event); In this method you execute a QMenu:</p>\n\n<pre><code>class TreeView : public QTreeView{\n Q_OBJECT\npublic:\n TreeView(QWidget *parent);\n ~TreeView();\nprotected:\n void contextMenuEvent(QContextMenuEvent *event);\n};\n\nvoid TreeView::contextMenuEvent(QContextMenuEvent *event){\n QMenu menu(this);\n menu.addAction(action1);\n menu.addAction(action2);\n //...\n menu.addAction(actionN);\n menu.exec(event->globalPos());\n}\n</code></pre>\n"
},
{
"answer_id": 173549,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 2,
"selected": true,
"text": "<p>You don't say which version of Qt you are using, but we found the same problem in Qt4.4.0, it worked in 4.3. We reported this to Trolltech as a bug <a href=\"http://trolltech.com/developer/task-tracker/index_html?method=entry&id=225615\" rel=\"nofollow noreferrer\">225615</a></p>\n\n<p>This is still marked as pending, so in the meantime I would follow Shy's suggestion of intercepting the right click and making the selection yourself.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6049/"
] |
I have a `QTreeView` class with a context menu installed as follows:
```
m_ui.tree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_ui.tree, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowTreeContextMenu(const QPoint&)));
...
void ShowTreeContextMenu(const QPoint& point)
{
m_treeContextMenu->exec(m_ui.tree->viewport()->mapToGlobal(point));
}
```
However when the context menu is being displayed the `QTreeView` will no longer respond to mouse clicks. Clicking on an item in the `QTreeView` while the context menu is displayed will remove the context menu but does not select the clicked item.
This is especially disorientating when right clicking on a new item, as the context menu pops up over the new item, but as the item was not selected the contents of the context menu are referring to the previously selected item.
|
You don't say which version of Qt you are using, but we found the same problem in Qt4.4.0, it worked in 4.3. We reported this to Trolltech as a bug [225615](http://trolltech.com/developer/task-tracker/index_html?method=entry&id=225615)
This is still marked as pending, so in the meantime I would follow Shy's suggestion of intercepting the right click and making the selection yourself.
|
173,329 |
<p>I have this query in sql server 2000:</p>
<pre><code>select pwdencrypt('AAAA')
</code></pre>
<p>which outputs an encrypted string of 'AAAA':</p>
<pre>
0x0100CF465B7B12625EF019E157120D58DD46569AC7BF4118455D12625EF019E157120D58DD46569AC7BF4118455D
</pre>
<p><strong>How can I convert (decrypt) the output from its origin (which is 'AAAA')?</strong></p>
|
[
{
"answer_id": 173344,
"author": "Svet",
"author_id": 8934,
"author_profile": "https://Stackoverflow.com/users/8934",
"pm_score": 5,
"selected": true,
"text": "<p>I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible. </p>\n\n<p>If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.</p>\n\n<p>This is how you could verify a usered entered table</p>\n\n<pre><code>SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)\n</code></pre>\n\n<p>Replace userEnteredValue with (big surprise) the value that the user entered :)</p>\n"
},
{
"answer_id": 173351,
"author": "Anheledir",
"author_id": 5703,
"author_profile": "https://Stackoverflow.com/users/5703",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot decrypt this password again but there is another method named \"pwdcompare\". Here is a example how to use it with SQL syntax:</p>\n\n<pre><code>USE TEMPDB\nGO\ndeclare @hash varbinary (255)\nCREATE TABLE tempdb..h (id_num int, hash varbinary (255))\nSET @hash = pwdencrypt('123') -- encryption\nINSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)\nSET @hash = pwdencrypt('123')\nINSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)\nSELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2\nSELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison\nSELECT * FROM tempdb..h\nINSERT INTO tempdb..h (id_num,hash) \nVALUES (3,CONVERT(varbinary (255),\n0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))\nSELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3\nSELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison\nSELECT * FROM tempdb..h\nDROP TABLE tempdb..h\nGO\n</code></pre>\n"
},
{
"answer_id": 173558,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 4,
"selected": false,
"text": "<p>You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.</p>\n\n<p>Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?</p>\n"
},
{
"answer_id": 173583,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 1,
"selected": false,
"text": "<p>A quick <a href=\"http://www.google.com/search?q=pwdencrypt\" rel=\"nofollow noreferrer\">google</a> indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!</p>\n\n<p>See also this article <a href=\"http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/\" rel=\"nofollow noreferrer\">http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/</a></p>\n"
},
{
"answer_id": 173668,
"author": "Dynite",
"author_id": 16177,
"author_profile": "https://Stackoverflow.com/users/16177",
"pm_score": 2,
"selected": false,
"text": "<p>You shouldn't really be de-encrypting passwords.</p>\n\n<p>You should be encrypting the password entered into your application and comparing against the encrypted password from the database.</p>\n\n<p>Edit - and if this is because the password has been forgotten, then setup a mechanism to create a new password.</p>\n"
},
{
"answer_id": 18154134,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 5,
"selected": false,
"text": "<p>The SQL Server password hashing algorithm:</p>\n<pre><code>hashBytes = 0x0100 | fourByteSalt | SHA1(utf16EncodedPassword+fourByteSalt)\n</code></pre>\n<p>For example, to hash the password <em>"correct horse battery staple"</em>. First we generate some random salt:</p>\n<pre><code>fourByteSalt = 0x9A664D79;\n</code></pre>\n<p>And then hash the password (encoded in UTF-16) along with the salt:</p>\n<pre><code> SHA1("correct horse battery staple" + 0x9A66D79);\n=SHA1(0x63006F007200720065006300740020006200610074007400650072007900200068006F00720073006500200073007400610070006C006500 0x9A66D79)\n=0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3\n</code></pre>\n<p>The value stored in the <strong><code>syslogins</code></strong> table is the concatenation of:</p>\n<blockquote>\n<p>[header] + [salt] + [hash]<br />\n<code>0x0100</code> <code>9A664D79</code> <code>6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3</code></p>\n</blockquote>\n<p>Which you can see in SQL Server:</p>\n<pre><code>SELECT \n name, CAST(password AS varbinary(max)) AS PasswordHash\nFROM sys.syslogins\nWHERE name = 'sa'\n\nname PasswordHash\n==== ======================================================\nsa 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3\n</code></pre>\n<ul>\n<li>Version header: <code>0100</code></li>\n<li>Salt (four bytes): <code>9A664D79</code></li>\n<li>Hash: <code>6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3</code> <em>(SHA-1 is 20 bytes; 160 bits)</em></li>\n</ul>\n<h2>Validation</h2>\n<p>You validate a password by performing the same hash:</p>\n<ul>\n<li>grab the salt from the saved <code>PasswordHash</code>: 0x9A664D79</li>\n</ul>\n<p>and perform the hash again:</p>\n<pre><code>SHA1("correct horse battery staple" + 0x9A66D79);\n</code></pre>\n<p>which will come out to the same hash, and you know the password is correct.</p>\n<h2>What once was good, but now is weak</h2>\n<p>The hashing algorithm introduced with SQL Server 7, in 1999, was good for 1999.</p>\n<ul>\n<li>It is good that the password hash salted.</li>\n<li>It is good to <strong>append</strong> the salt to the password, rather than <strong>prepend</strong> it.</li>\n</ul>\n<p>But today it is out-dated. It only runs the hash once, where it should run it a few thousand times, in order to thwart brute-force attacks.</p>\n<p>In fact, Microsoft's Baseline Security Analyzer will, as part of it's checks, attempt to bruteforce passwords. If it guesses any, it reports the passwords as weak. And it does get some.</p>\n<h1>Brute Forcing</h1>\n<p>To help you test some passwords:</p>\n<pre><code>DECLARE @hash varbinary(max)\nSET @hash = 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3\n--Header: 0x0100\n--Salt: 0x9A664D79\n--Hash: 0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3\n\nDECLARE @password nvarchar(max)\nSET @password = 'password'\n\nSELECT\n @password AS CandidatePassword,\n @hash AS PasswordHash,\n \n --Header\n 0x0100\n +\n --Salt\n CONVERT(VARBINARY(4), SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))\n +\n --SHA1 of Password + Salt\n HASHBYTES('SHA1', @password + SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))\n</code></pre>\n<h2>SQL Server 2012 and SHA-512</h2>\n<p>Starting with SQL Server 2012, Microsoft switched to using SHA-2 512-bit:</p>\n<pre><code>hashBytes = 0x0200 | fourByteSalt | SHA512(utf16EncodedPassword+fourByteSalt)\n</code></pre>\n<p>Changing the version prefix to <code>0x0200</code>:</p>\n<pre><code>SELECT \n name, CAST(password AS varbinary(max)) AS PasswordHash\nFROM sys.syslogins\n\nname PasswordHash\n---- --------------------------------\nxkcd 0x02006A80BA229556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38\n</code></pre>\n<ul>\n<li>Version: <code>0200</code> <em>(SHA-2 512-bit)</em></li>\n<li>Salt: <code>6A80BA22</code></li>\n<li>Hash (64 bytes): <code>9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38</code></li>\n</ul>\n<p>This means we hash the UTF-16 encoded password, with the salt suffix:</p>\n<ul>\n<li>SHA512(<em>"correct horse battery staple"</em>+<code>6A80BA22</code>)</li>\n<li>SHA512(<code>63006f0072007200650063007400200068006f0072007300650020006200610074007400650072007900200073007400610070006c006500</code> + <code>6A80BA22</code>)</li>\n<li><code>9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38</code></li>\n</ul>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21963/"
] |
I have this query in sql server 2000:
```
select pwdencrypt('AAAA')
```
which outputs an encrypted string of 'AAAA':
```
0x0100CF465B7B12625EF019E157120D58DD46569AC7BF4118455D12625EF019E157120D58DD46569AC7BF4118455D
```
**How can I convert (decrypt) the output from its origin (which is 'AAAA')?**
|
I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
```
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
```
Replace userEnteredValue with (big surprise) the value that the user entered :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.