qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
157,959
<p>When I ssh into a remote production server I would like the colour scheme of my terminal window to change to something brigh and scary, preferably red, to warn me that I am touching a live scary server. </p> <p>How can I make it automatically detect that I have ssh'ed somewhere, and if that somewhere is on a specific list, change the colour scheme?</p> <p>I want to update the Scheme of Terminal.app, not know how I would do this in a pure linux/unix env</p>
[ { "answer_id": 157984, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 3, "selected": false, "text": "red='\\e[0;31m'\nPS1=\"$\\[${red}\\]\"\n #touch .bashrc\n" }, { "answer_id": 158170, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 2, "selected": false, "text": "case $HOSTNAME in\n live1|live2|live3) echo -e '\\e]11;1\\a' ;;\n testing1|testing2) echo -e '\\e]11;2\\a' ;;\nesac\n on_exit () {\n echo -e '\\e]11;0\\a'\n}\ntrap on_exit EXIT\n set_bg_color () {\n # color values are in '{R, G, B, A}' format, all 16-bit unsigned integers (0-65535)\n osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to $1\"\n}\n\nsshl () {\n set_bg_color \"{45000, 0, 0, 50000}\"\n ssh \"$@\"\n set_bg_color \"{0, 0, 0, 50000}\"\n}\n" }, { "answer_id": 166201, "author": "Yurii Soldak", "author_id": 20294, "author_profile": "https://Stackoverflow.com/users/20294", "pm_score": 7, "selected": true, "text": "~/bin/ssh ~/bin/ /usr/bin/ #!/bin/sh\n\nHOSTNAME=`echo $@ | sed s/.*@//`\n\nset_bg () {\n osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to $1\"\n}\n\non_exit () {\n set_bg \"{0, 0, 0, 50000}\"\n}\ntrap on_exit EXIT\n\ncase $HOSTNAME in\n production1|production2|production3) set_bg \"{45000, 0, 0, 50000}\" ;;\n *) set_bg \"{0, 45000, 0, 50000}\" ;;\nesac\n\n/usr/bin/ssh \"$@\"\n chmod +x ~/bin/ssh" }, { "answer_id": 18741645, "author": "Chris Page", "author_id": 754997, "author_profile": "https://Stackoverflow.com/users/754997", "pm_score": 5, "selected": false, "text": "ssh host.example.com" }, { "answer_id": 32760878, "author": "bingles", "author_id": 20489, "author_profile": "https://Stackoverflow.com/users/20489", "pm_score": 3, "selected": false, "text": "# Convert 8 bit r,g,b,a (0-255) to 16 bit r,g,b,a (0-65535)\n# to set terminal background.\n# r, g, b, a values default to 255\nset_bg () {\n r=${1:-255}\n g=${2:-255}\n b=${3:-255}\n a=${4:-255}\n\n r=$(($r * 256 + $r))\n g=$(($g * 256 + $g))\n b=$(($b * 256 + $b))\n a=$(($a * 256 + $a))\n\n osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to {$r, $g, $b, $a}\"\n}\n\n# Set terminal background based on hex rgba values\n# r,g,b,a default to FF\nset_bg_from_hex() {\n r=${1:-FF}\n g=${2:-FF}\n b=${3:-FF}\n a=${4:-FF}\n\n set_bg $((16#$r)) $((16#$g)) $((16#$b)) $((16#$s))\n}\n\n# Wrapping ssh command with extra functionality\nssh() {\n # If prod server of interest, change bg color\n if ...some check for server list\n then\n set_bg_from_hex 6A 05 0C\n end\n\n # Call original ssh command\n if command ssh \"$@\"\n then\n # on exit change back to your default\n set_bg_from_hex 24 34 52\n fi\n}\n" }, { "answer_id": 34513775, "author": "arnon cohen", "author_id": 2849724, "author_profile": "https://Stackoverflow.com/users/2849724", "pm_score": 3, "selected": false, "text": "Host Server1\n HostName x.x.x.x\n User ubuntu\n IdentityFile ~/Desktop/keys/1.pem\n PermitLocalCommand yes\n LocalCommand osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to {27655, 0, 0, -16373}\"\n\nHost Server2\n HostName x.x.x.x\n User ubuntu\n IdentityFile ~/Desktop/keys/2.pem\n PermitLocalCommand yes\n LocalCommand osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to {37655, 0, 0, -16373}\"\n" }, { "answer_id": 39489571, "author": "Maxim Yefremov", "author_id": 1024794, "author_profile": "https://Stackoverflow.com/users/1024794", "pm_score": 3, "selected": false, "text": "~/bin/ssh #!/bin/sh\n# https://stackoverflow.com/a/39489571/1024794\nlog(){\n echo \"$*\" >> /tmp/ssh.log\n}\nHOSTNAME=`echo $@ | sed s/.*@//`\nlog HOSTNAME=$HOSTNAME\n# to avoid changing color for commands like `ssh user@host \"some bash script\"`\n# and to avoid changing color for `git push` command:\nif [ $# -gt 3 ] || [[ \"$HOSTNAME\" = *\"git-receive-pack\"* ]]; then\n /usr/bin/ssh \"$@\"\n exit $? \nfi\n\nset_bg () {\n if [ \"$1\" != \"Basic\" ]; then\n trap on_exit EXIT;\n fi\n osascript ~/Dropbox/macCommands/StyleTerm.scpt \"$1\"\n}\n\non_exit () {\n set_bg Basic\n}\n\n\ncase $HOSTNAME in\n \"178.222.333.44 -p 2222\") set_bg \"Homebrew\" ;;\n \"178.222.333.44 -p 22\") set_bg \"Ocean\" ;;\n \"192.168.214.111\") set_bg \"Novel\" ;;\n *) set_bg \"Grass\" ;;\nesac\n\n/usr/bin/ssh \"$@\"\n chmod +x ~/bin/ssh ~/Dropbox/macCommands/StyleTerm.scpt #https://superuser.com/a/209920/195425\non run argv\n tell application \"Terminal\" to set current settings of selected tab of front window to first settings set whose name is (item 1 of argv)\nend run\n Basic, Homebrew, Ocean, Novel, Grass" }, { "answer_id": 48245314, "author": "Shayan Amani", "author_id": 3782119, "author_profile": "https://Stackoverflow.com/users/3782119", "pm_score": 0, "selected": false, "text": "~/.bash_profile export PS1=\" \\[\\033[34m\\]\\u@\\h \\[\\033[33m\\]\\w\\[\\033[31m\\]\\[\\033[00m\\] $ \"\n m 34m" }, { "answer_id": 50078642, "author": "Joshua Pinter", "author_id": 293280, "author_profile": "https://Stackoverflow.com/users/293280", "pm_score": 2, "selected": false, "text": "/.bashrc setterm ~./bashrc # Inverts console colours so that we know that we are in a remote server. \n# This is very important to avoid running commands on the server by accident.\nsetterm --inversescreen on\n\n# This ensures we restore the console colours after exiting.\nfunction restore_screen_colours {\n setterm --inversescreen off\n}\ntrap restore_screen_colours EXIT\n ~/.bashrc" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
158,008
<p>I'm updating some old AWStats config files to filter out some specific IP ranges. Here's the pertinent section of the config file:</p> <pre><code># Do not include access from clients that match following criteria. # If your log file contains IP addresses in host field, you must enter here # matching IP addresses criteria. # If DNS lookup is already done in your log file, you must enter here hostname # criteria, else enter ip address criteria. # The opposite parameter of "SkipHosts" is "OnlyHosts". # Note: Use space between each value. This parameter is not case sensitive. # Note: You can use regular expression values writing value with REGEX[value]. # Change : Effective for new updates only # Example: "127.0.0.1 REGEX[^192\.168\.] REGEX[^10\.]" # Example: "localhost REGEX[^.*\.localdomain$]" # Default: "" # SkipHosts="" </code></pre> <p>I want to, for example, filter out X.Y.Z.[97-110]</p> <p>I tried this format (Note: Not these IP values, using private range as example):</p> <pre><code>REGEX[^192\.168\.1\.[97-110]] </code></pre> <p>But it causes the following error:</p> <blockquote> <p><strong>CGI Error</strong><br/>The specified CGI application misbehaved by not returning a complete set of HTTP headers.</p> </blockquote> <p>I hate how everything uses a different RegEx syntax. Does anyone have any idea how this one works, and how I can specify a range here?</p>
[ { "answer_id": 158086, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 0, "selected": false, "text": "c:\\perlpath\\perl.exe awstats.pl config=yourconfigfile -update -logfile=yourlogfile\n" }, { "answer_id": 158114, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": true, "text": "SkipHosts = \"REGEX[^192\\.168\\.1\\.(9[7-9]|10[0-9]|110)$]\"\n" }, { "answer_id": 158118, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 2, "selected": false, "text": "SkipHosts=\"REGEX[^192\\.168\\.1\\.(97|98|99|100|101|102|103|104|105|106|107|108|109|110)]\"\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
158,044
<p>How do I use the UNIX command <code>find</code> to search for files created on a specific date?</p>
[ { "answer_id": 158074, "author": "Jeff MacDonald", "author_id": 22374, "author_profile": "https://Stackoverflow.com/users/22374", "pm_score": 5, "selected": false, "text": "find ./ -type f -ls |grep '10 Sep'\n [root@pbx etc]# find /var/ -type f -ls | grep \"Dec 24\"\n791235 4 -rw-r--r-- 1 root root 29 Dec 24 03:24 /var/lib/prelink/full\n798227 288 -rw-r--r-- 1 root root 292323 Dec 24 23:53 /var/log/sa/sar24\n797244 320 -rw-r--r-- 1 root root 321300 Dec 24 23:50 /var/log/sa/sa24\n" }, { "answer_id": 158082, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": -1, "selected": false, "text": "CNT=0\nfor i in $(find -type f -ctime +14); do\n ((CNT = CNT + 1))\n echo -n \".\" >> $PROGRESS\n rm -f $i\ndone\necho deleted $CNT files, done at $(date \"+%H:%M:%S\") >> $LOG\n" }, { "answer_id": 158092, "author": "Chris", "author_id": 4742, "author_profile": "https://Stackoverflow.com/users/4742", "pm_score": 6, "selected": false, "text": "/home/ find /home/ -ctime time_period\n -ctime +30 -ctime -30 -ctime 30" }, { "answer_id": 158095, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 6, "selected": false, "text": "touch -t 0810010000 /tmp/t\n find / -newer /tmp/t\nfind / -not -newer /tmp/t\n touch -t 0810010000 /tmp/t1\ntouch -t 0810011000 /tmp/t2\n find / -newer /tmp/t1 -and -not -newer /tmp/t2\n" }, { "answer_id": 158190, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 3, "selected": false, "text": "-atime -ctime -mtime ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))\n find find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))\n find -newerXY" }, { "answer_id": 158235, "author": "Arve", "author_id": 9595, "author_profile": "https://Stackoverflow.com/users/9595", "pm_score": 10, "selected": true, "text": "-newerXY ! -newerXY $ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08\n $ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30\n $ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30\n" }, { "answer_id": 7878375, "author": "Tintin", "author_id": 1011207, "author_profile": "https://Stackoverflow.com/users/1011207", "pm_score": -1, "selected": false, "text": "cp `ls -ltr | grep 'Jun 14' | perl -wne 's/^.*\\s+(\\S+)$/$1/; print $1 . \"\\n\";'` /some_destination_dir\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473/" ]
158,070
<p>I have a hidden DIV which contains a toolbar-like menu.</p> <p>I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.</p> <p>Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like <code>$(menu).position("topright", targetEl);</code></p>
[ { "answer_id": 158176, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 9, "selected": false, "text": "<div id=\"menu\" style=\"display: none;\">\n <!-- menu stuff in here -->\n <ul><li>Menu item</li></ul>\n</div>\n\n<div class=\"parent\">Hover over me to show the menu here</div>\n $(\".parent\").mouseover(function() {\n // .position() uses position relative to the offset parent, \n var pos = $(this).position();\n\n // .outerWidth() takes into account border and padding.\n var width = $(this).outerWidth();\n\n //show the menu directly over the placeholder\n $(\"#menu\").css({\n position: \"absolute\",\n top: pos.top + \"px\",\n left: (pos.left + width) + \"px\"\n }).show();\n});\n #menu $(this).append($(\"#menu\"));\n #menu show() position({...}) position() outerWidth() append" }, { "answer_id": 158181, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 2, "selected": false, "text": "$(menu).css(\"top\", targetE1.y + \"px\"); \n$(menu).css(\"left\", targetE1.x - widthOfMenu + \"px\");\n" }, { "answer_id": 161183, "author": "paul", "author_id": 11249, "author_profile": "https://Stackoverflow.com/users/11249", "pm_score": 4, "selected": false, "text": "var showMenu = function(el, menu) {\n //get the position of the placeholder element \n var pos = $(el).offset(); \n var eWidth = $(el).outerWidth();\n var mWidth = $(menu).outerWidth();\n var left = (pos.left + eWidth - mWidth) + \"px\";\n var top = 3+pos.top + \"px\";\n //show the menu directly over the placeholder \n $(menu).css( { \n position: 'absolute',\n zIndex: 5000,\n left: left, \n top: top\n } );\n\n $(menu).hide().fadeIn();\n};\n" }, { "answer_id": 548788, "author": "devXen", "author_id": 50021, "author_profile": "https://Stackoverflow.com/users/50021", "pm_score": 2, "selected": false, "text": "var posPersonTooltip = function(event) {\nvar tPosX = event.pageX - 5;\nvar tPosY = event.pageY + 10;\n$('#personTooltipContainer').css({top: tPosY, left: tPosX});\n" }, { "answer_id": 1128764, "author": "Venkat D.", "author_id": 67655, "author_profile": "https://Stackoverflow.com/users/67655", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n $('#el1').position('#el2', {\n anchor: ['br', 'tr'],\n offset: [-5, 5]\n });\n});\n jQuery.fn.getBox = function() {\n return {\n left: $(this).offset().left,\n top: $(this).offset().top,\n width: $(this).outerWidth(),\n height: $(this).outerHeight()\n };\n}\n\njQuery.fn.position = function(target, options) {\n var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};\n var defaults = {\n anchor: ['tl', 'tl'],\n animate: false,\n offset: [0, 0]\n };\n options = $.extend(defaults, options);\n\n var targetBox = $(target).getBox();\n var sourceBox = $(this).getBox();\n\n //origin is at the top-left of the target element\n var left = targetBox.left;\n var top = targetBox.top;\n\n //alignment with respect to source\n top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;\n left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;\n\n //alignment with respect to target\n top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;\n left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;\n\n //add offset to final coordinates\n left += options.offset[0];\n top += options.offset[1];\n\n $(this).css({\n left: left + 'px',\n top: top + 'px'\n });\n\n}\n" }, { "answer_id": 2781557, "author": "Uriel", "author_id": 334487, "author_profile": "https://Stackoverflow.com/users/334487", "pm_score": 9, "selected": true, "text": "$(\"#my_div\").position({\n my: \"left top\",\n at: \"left bottom\",\n of: this, // or $(\"#otherdiv\")\n collision: \"fit\"\n});\n" }, { "answer_id": 7596992, "author": "gtamil", "author_id": 970933, "author_profile": "https://Stackoverflow.com/users/970933", "pm_score": 2, "selected": false, "text": ".active-div{\nposition:relative;\n}\n\n.menu-div{\nposition:absolute;\ntop:0;\nright:0;\ndisplay:none;\n}\n $(function(){\n $(\".active-div\").hover(function(){\n $(\".menu-div\").prependTo(\".active-div\").show();\n },function(){$(\".menu-div\").hide();\n})\n" }, { "answer_id": 22764173, "author": "TLindig", "author_id": 496587, "author_profile": "https://Stackoverflow.com/users/496587", "pm_score": 2, "selected": false, "text": "$(\".placeholder\").on('mouseover', function() {\n var $menu = $(\"#menu\").show();// result for hidden element would be incorrect\n var pos = $.PositionCalculator( {\n target: this,\n targetAt: \"top right\",\n item: $menu,\n itemAt: \"top left\",\n flip: \"both\"\n }).calculate();\n\n $menu.css({\n top: parseInt($menu.css('top')) + pos.moveBy.y + \"px\",\n left: parseInt($menu.css('left')) + pos.moveBy.x + \"px\"\n });\n});\n <ul class=\"popup\" id=\"menu\">\n <li>Menu item</li>\n <li>Menu item</li>\n <li>Menu item</li>\n</ul>\n\n<div class=\"placeholder\">placeholder 1</div>\n<div class=\"placeholder\">placeholder 2</div>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11249/" ]
158,104
<p>I've discovered that any time I do the following:</p> <pre><code>echo '&lt;a href="http://" title="bla"&gt;huzzah&lt;/a&gt;'; </code></pre> <p>I end up with the following being rendered to the browser:</p> <pre><code>&lt;a href="http:///" title="bla"&gt;huzzah&lt;/a&gt; </code></pre> <p>This is particularly annoying when I link to a file with an extension, as it breaks the link.</p> <p>Any ideas why this is happening and how I can fix it?</p> <p><strong>Update:</strong> For those asking about my exact implementation, here it is. In my troubleshooting I've dumbed it down as much as I could, so please don't mind where I concat plain text to plaintext...</p> <pre><code>function print_it($item) { echo '&lt;div class="listItem clearfix"&gt;'; echo '&lt;div class="info"&gt;'; echo '&lt;span class="title"&gt;'; if(isset($item[6])) { echo '&lt;a href="http://" title=""&gt;' . 'me' . '&lt;/a&gt;'; } echo '&lt;/span&gt;'; echo '&lt;/div&gt;&lt;/div&gt;'; } </code></pre> <p><strong>Update:</strong> In response to Matt Long, I pasted in your line and it rendered the same.</p> <p><strong>Update:</strong> In response to Fire Lancer, I've put back in my original attempt, and will show you both below.</p> <pre><code>echo substr($item[6],13) . '&lt;br&gt;'; echo '&lt;a href="http://' . substr($item[6],13) . '" title="' . $item[0] . '"&gt;' . $item[0] . '&lt;/a&gt;'; &lt;span class="title"&gt;www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html&lt;br&gt; &lt;a href="http://www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html" title="Employment Ontario"&gt;Employment Ontario&lt;/a&gt;&lt;/span&gt; </code></pre> <p>The reason for the substr'ing is due to the URL being run through rawurlencode() elsewhere, and linking to http%3A%2F%2F makes the page think it is a local/relative link.</p> <p><strong>Update:</strong> I pasted the above response without really looking at it. So the HTML is correct when viewing source, but the actual page interprets it with another trailing slash after it.</p> <p><strong>Solution:</strong> This was all a result of rawlurlencode(). If I decoded, or skipped the encoding all together, everything worked perfectly. Something about rawurlencode() makes the browser want to stick a trailing slash in there.</p>
[ { "answer_id": 158115, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 2, "selected": false, "text": "echo '<a href=\"http://someothersite.com\">Link</a>';\necho '<a href=\"anotherpage.php\">Some page</a>';\necho '<a href=\"../pageinparentdir.php\">Another page</a>';\netc\n <a href=\"http://\" title=\"bla\">huzzah</a>\n http:///\n" }, { "answer_id": 158117, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "echo echo" }, { "answer_id": 158156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "echo \"<a href=\\\"http://\\\" title=\\\"bla\\\">huzzah</a>\";\n" }, { "answer_id": 158335, "author": "ThoriumBR", "author_id": 16545, "author_profile": "https://Stackoverflow.com/users/16545", "pm_score": 0, "selected": false, "text": "GET /path/file.php HTTP/1.0\n" }, { "answer_id": 158364, "author": "Brian", "author_id": 13264, "author_profile": "https://Stackoverflow.com/users/13264", "pm_score": -1, "selected": false, "text": "php_flag magic_quotes_gpc off" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22216/" ]
158,121
<p>Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a <code>ByteBuffer</code> with a message to output, and attempt to <code>write()</code> to the SocketChannel.</p> <p>I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buffer (this is what I expect intuitively, it's also pretty much my understanding of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/SocketChannel.html#write(java.nio.ByteBuffer)" rel="noreferrer">docs</a>), but that's not what happens. The <code>write()</code> <em>always</em> seems to return reporting the full amount written, even if it's several megabytes (the socket's SO_SNDBUF is 8KB, much, much less than my multi-megabyte output message).</p> <p>A problem here is that I can't test the code that handles the case where the output is partially written (registering an interest set of <code>WRITE</code> to a selector and doing a <code>select()</code> to wait until the remainder can be written), as that case never seems to happen. What am I not understanding?</p>
[ { "answer_id": 158144, "author": "Clay", "author_id": 16429, "author_profile": "https://Stackoverflow.com/users/16429", "pm_score": 0, "selected": false, "text": "SO_SNDBUF" }, { "answer_id": 158409, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 4, "selected": true, "text": "import java.io.InputStream;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class MyServer {\n public static void main(String[] args) throws Exception {\n final ServerSocket ss = new ServerSocket(12345);\n final Socket cs = ss.accept();\n System.out.println(\"Accepted connection\");\n\n final InputStream in = cs.getInputStream();\n final byte[] tmp = new byte[64 * 1024];\n while (in.read(tmp) != -1);\n\n Thread.sleep(100000);\n }\n}\n\n\n\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.SocketChannel;\n\npublic class MyNioClient {\n public static void main(String[] args) throws Exception {\n final SocketChannel s = SocketChannel.open();\n s.configureBlocking(false);\n s.connect(new InetSocketAddress(\"localhost\", 12345));\n s.finishConnect();\n\n final ByteBuffer buf = ByteBuffer.allocate(128 * 1024);\n for (int i = 0; i < 10; i++) {\n System.out.println(\"to write: \" + buf.remaining() + \", written: \" + s.write(buf));\n buf.position(0);\n }\n Thread.sleep(100000);\n }\n}\n 0 to write: 131072, written: 131072\nto write: 131072, written: 131072\nto write: 131072, written: 131072\n...\n to write: 131072, written: 131072\nto write: 131072, written: 0\nto write: 131072, written: 0\n... \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24173/" ]
158,122
<p>I have what I believe to be a fairly well structured .NET 3.5 forms application (Unit Tests, Dependency Injection, SoC, the forms simply relay input and display output and don't do any logic, yadda yadda) I am just missing the winforms knowledge for how to get this bit to work.</p> <p>When a connection to the database is lost - a frequent occurrence - I am detecting and handling it and would like a modal form to pop up, blocking use of the application until the connection is re-established. I am not 100% sure how to do that since I am not waiting for user input, rather I am polling the database using a timer.</p> <p>My attempt was to design a form with a label on it and to do this:</p> <pre><code>partial class MySustainedDialog : Form { public MySustainedDialog(string msg) { InitializeComponent(); lbMessage.Text = msg; } public new void Show() { base.ShowDialog(); } public new void Hide() { this.Close(); } } public class MyNoConnectionDialog : INoConnectionDialog { private FakeSustainedDialog _dialog; public void Show() { var w = new BackgroundWorker(); w.DoWork += delegate { _dialog = new MySustainedDialog("Connection Lost"); _dialog.Show(); }; w.RunWorkerAsync(); } public void Hide() { _dialog.Close(); } } </code></pre> <p>This doesn't work since _dialog.Close() is a cross-thread call. I've been able to find information on how to resolve this issue within a windows form but not in a situation like this one where you need to create the form itself.</p> <p>Can someone give me some advice how to achieve what I am trying to do?</p> <p><strong>EDIT:</strong> Please note, I only tried Background worker for lack of other ideas because I'm not tremendously familiar with how threading for the UI works so I am completely open to suggestions. I should also note that I do not want to close the form they are working on currently, I just want this to appear on top of it. Like an OK/Cancel dialog box but which I can open and close programmatically (and I need control over what it looks like to )</p>
[ { "answer_id": 158286, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 2, "selected": false, "text": " public new void Hide()\n {\n if (this.InvokeRequired)\n {\n this.BeginInvoke((MethodInvoker)delegate { this.Hide(); });\n return;\n }\n\n this.Close();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
158,124
<p>It's surprising how difficult it is to find a simple, concise answer to this question:</p> <ol> <li>I have a file, foo.zip, on my website</li> <li>What can I do to find out how many people have accessed this file?</li> <li>I could use Tomcat calls if necessary</li> </ol>
[ { "answer_id": 158142, "author": "Sean Bright", "author_id": 21926, "author_profile": "https://Stackoverflow.com/users/21926", "pm_score": 5, "selected": true, "text": "grep foo.zip /path/to/access.log | grep 200 | wc -l\n" }, { "answer_id": 12405503, "author": "Ashraf Zaman", "author_id": 1104395, "author_profile": "https://Stackoverflow.com/users/1104395", "pm_score": 3, "selected": false, "text": "$hit_count = @file_get_contents('count.txt');\n$hit_count++;\n@file_put_contents('count.txt', $hit_count);\n\nheader('Location: http://www.example.com/download/pics.zip'); // redirect to the real file to be downloaded\n count.txt downloadable_filename.ext" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
158,133
<p>They both seem to fulfill the same purpose. When would I chose one over the other?</p>
[ { "answer_id": 9672255, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 3, "selected": false, "text": "WaitHandle Monitor.Wait Monitor.Pulse Monitor.Wait Monitor.Pulse Monitor Monitor.Wait WaitHandle.WaitOne Wait WaitOne WaitSleepJoin Thread.Interrupt Pulse Set Wait WaitOne Wait Pulse BlockingCollection" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
158,149
<p>Is there a way to validate on the client side browser whether the size of a file being uploaded from a JSP page is over a set size limit without forcing the user to upload the entire file only to find out it was too large?</p> <p>I would like to stay away from any proprietary controls or techniques like Flash or ActiveX if possible.</p> <p>Thanks!</p>
[ { "answer_id": 158179, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": true, "text": "request.getHeader(\"Content-Length\")" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5061/" ]
158,151
<p>Is there a one button way to save a screenshot directly to a file in Windows?</p> <br> TheSoftwareJedi accurately answered above question for Windows 8 and 10. Below original extra material remains for posterity. <blockquote> <p>This is a very important question as the 316K views shows as of 2021. Asked in 2008, SO closed this question around 2015 as being off-topic, probably because of the last question below.</p> </blockquote> <blockquote> <p>In Windows XP, one can press Alt-PrintScreen to copy an image of the active window, or Ctrl-PrintScreen to copy an image of the full desktop.</p> <p>This can then be pasted into applications that accept images: Photoshop, Microsoft Word, etc.</p> <p>I'm wondering: <b>Is there a way to save the screenshot directly to a file?</b> Do I <i>really</i> have to open an image program, like Paint.net or Photoshop, simply to paste an image, then save it?</p> </blockquote>
[ { "answer_id": 158171, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": true, "text": "using System;\nusing System.Drawing;\nusing System.IO;\nusing System.Drawing.Imaging;\nusing System.Runtime.InteropServices;\npublic class CaptureScreen\n{\n\n static public void Main(string[] args)\n {\n\n try\n {\n Bitmap capture = CaptureScreen.GetDesktopImage();\n string file = Path.Combine(Environment.CurrentDirectory, \"screen.gif\");\n ImageFormat format = ImageFormat.Gif;\n capture.Save(file, format);\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n\n }\n\n public static Bitmap GetDesktopImage()\n {\n WIN32_API.SIZE size;\n\n IntPtr hDC = WIN32_API.GetDC(WIN32_API.GetDesktopWindow()); \n IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC);\n\n size.cx = WIN32_API.GetSystemMetrics(WIN32_API.SM_CXSCREEN);\n size.cy = WIN32_API.GetSystemMetrics(WIN32_API.SM_CYSCREEN);\n\n m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, size.cx, size.cy);\n\n if (m_HBitmap!=IntPtr.Zero)\n {\n IntPtr hOld = (IntPtr) WIN32_API.SelectObject(hMemDC, m_HBitmap);\n WIN32_API.BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC, 0, 0, WIN32_API.SRCCOPY);\n WIN32_API.SelectObject(hMemDC, hOld);\n WIN32_API.DeleteDC(hMemDC);\n WIN32_API.ReleaseDC(WIN32_API.GetDesktopWindow(), hDC);\n return System.Drawing.Image.FromHbitmap(m_HBitmap); \n }\n return null;\n }\n\n protected static IntPtr m_HBitmap;\n}\n\npublic class WIN32_API\n{\n public struct SIZE\n {\n public int cx;\n public int cy;\n }\n public const int SRCCOPY = 13369376;\n public const int SM_CXSCREEN=0;\n public const int SM_CYSCREEN=1;\n\n [DllImport(\"gdi32.dll\",EntryPoint=\"DeleteDC\")]\n public static extern IntPtr DeleteDC(IntPtr hDc);\n\n [DllImport(\"gdi32.dll\",EntryPoint=\"DeleteObject\")]\n public static extern IntPtr DeleteObject(IntPtr hDc);\n\n [DllImport(\"gdi32.dll\",EntryPoint=\"BitBlt\")]\n public static extern bool BitBlt(IntPtr hdcDest,int xDest,int yDest,int wDest,int hDest,IntPtr hdcSource,int xSrc,int ySrc,int RasterOp);\n\n [DllImport (\"gdi32.dll\",EntryPoint=\"CreateCompatibleBitmap\")]\n public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);\n\n [DllImport (\"gdi32.dll\",EntryPoint=\"CreateCompatibleDC\")]\n public static extern IntPtr CreateCompatibleDC(IntPtr hdc);\n\n [DllImport (\"gdi32.dll\",EntryPoint=\"SelectObject\")]\n public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp);\n\n [DllImport(\"user32.dll\", EntryPoint=\"GetDesktopWindow\")]\n public static extern IntPtr GetDesktopWindow();\n\n [DllImport(\"user32.dll\",EntryPoint=\"GetDC\")]\n public static extern IntPtr GetDC(IntPtr ptr);\n\n [DllImport(\"user32.dll\",EntryPoint=\"GetSystemMetrics\")]\n public static extern int GetSystemMetrics(int abc);\n\n [DllImport(\"user32.dll\",EntryPoint=\"GetWindowDC\")]\n public static extern IntPtr GetWindowDC(Int32 ptr);\n\n [DllImport(\"user32.dll\",EntryPoint=\"ReleaseDC\")]\n public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc);\n}\n" }, { "answer_id": 158281, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 7, "selected": false, "text": "<user>/Pictures/Screenshots" }, { "answer_id": 158411, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "function TForm1.GetScreenShot(OnlyActiveWindow: boolean) : TBitmap;\nvar\n w,h : integer;\n DC : HDC;\n hWin : Cardinal;\n r : TRect;\nbegin\n //take a screenshot and return it as a TBitmap.\n //if they specify \"OnlyActiveWindow\", then restrict the screenshot to the\n //currently focused window (same as alt-prtscrn)\n //Otherwise, get a normal screenshot (same as prtscrn)\n Result := TBitmap.Create;\n if OnlyActiveWindow then begin\n hWin := GetForegroundWindow;\n dc := GetWindowDC(hWin);\n GetWindowRect(hWin,r);\n w := r.Right - r.Left;\n h := r.Bottom - r.Top;\n end //if active window only\n else begin\n hWin := GetDesktopWindow;\n dc := GetDC(hWin);\n w := GetDeviceCaps(DC,HORZRES);\n h := GetDeviceCaps(DC,VERTRES);\n end; //else entire desktop\n\n try\n Result.Width := w;\n Result.Height := h;\n BitBlt(Result.Canvas.Handle,0,0,Result.Width,Result.Height,DC,0,0,SRCCOPY);\n finally\n ReleaseDC(hWin, DC) ;\n end; //try-finally\nend;\n\nprocedure TForm1.btnSaveScreenshotClick(Sender: TObject);\nvar\n bmp : TBitmap;\n savdlg : TSaveDialog;\nbegin\n //take a screenshot, prompt for where to save it\n savdlg := TSaveDialog.Create(Self);\n bmp := GetScreenshot(False);\n try\n if savdlg.Execute then begin\n bmp.SaveToFile(savdlg.FileName);\n end;\n finally\n FreeAndNil(bmp);\n FreeAndNil(savdlg);\n end; //try-finally\nend;\n" }, { "answer_id": 20840527, "author": "Karthik T", "author_id": 1520364, "author_profile": "https://Stackoverflow.com/users/1520364", "pm_score": 4, "selected": false, "text": "windows key prnt screen <user>/Pictures/Screenshots" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
158,152
<p>I have a .NET TCP Client that sends high volumes of messages to a (.NET async) TCP server.</p> <p>I need to keep sending messages to the server but I run out of ports on the client due to TIME_WAIT. </p> <p>How can a program continually and reliably send messages without using all of the available ports?</p> <p>Is there a method to keep reusing the same socket. I have looked at Disconnect() and the REUSEADDRESS socket flag but cannot find any good examples of their use. In fact most sources say not to use Disconnect as it is for lower level use (i.e. it only recycles the socket handle).</p> <p>I'm thinking that I need to switch to UDP or perhaps there is a method using C++ and IOCP?</p>
[ { "answer_id": 158199, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "open socket connection\n\nwhile(running)\n send messages over socket\n\nclose socket connection\n" }, { "answer_id": 158950, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 0, "selected": false, "text": "open a server socket // this uses the port the clients know about\n\nwhile(running)\n client_socket = server_socket.listen\n fork(new handler_object(client_socket))\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21826/" ]
158,172
<p>I have some decimal data that I am pushing into a SharePoint list where it is to be viewed. I'd like to restrict the number of significant figures displayed in the result data based on my knowledge of the specific calculation. Sometimes it'll be 3, so 12345 will become 12300 and 0.012345 will become 0.0123. Occasionally it will be 4 or 5. Is there any convenient way to handle this?</p>
[ { "answer_id": 158810, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "private static string FormatToSignificantFigures(decimal number, int amount)\n{\n if (number > 1)\n {\n int factor = Factor(amount);\n return ((int)(number/factor)*factor).ToString();\n }\n\n NumberFormatInfo nfi = new CultureInfo(\"en-US\", false).NumberFormat;\n nfi.NumberDecimalDigits = amount;\n\n return(number.ToString(\"F\", nfi));\n}\n\nprivate static int Factor(int x)\n{\n return DoCalcFactor(10, x-1);\n}\n\nprivate static int DoCalcFactor(int x, int y)\n{\n if (y == 1) return x;\n return 10*DoCalcFactor(x, y - 1);\n}\n" }, { "answer_id": 158942, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": 3, "selected": false, "text": "\ndouble Input1 = 1234567;\nstring Result1 = Convert.ToDouble(String.Format(\"{0:G3}\",Input1)).ToString(\"R0\");\n\ndouble Input2 = 0.012345;\nstring Result2 = Convert.ToDouble(String.Format(\"{0:G3}\", Input2)).ToString(\"R6\");\n" }, { "answer_id": 163354, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 1, "selected": false, "text": "/*\n * Copyright (C) 2002-2007 Stephen Ostermiller\n * http://ostermiller.org/contact.pl?regarding=Java+Utilities\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * See COPYING.TXT for details.\n */\npublic class SignificantFigures\n{\n private String original;\n private StringBuilder _digits;\n private int mantissa = -1;\n private bool sign = true;\n private bool isZero = false;\n private bool useScientificNotation = true;\n\n public SignificantFigures(String number)\n {\n original = number;\n Parse(original);\n }\n\n\n public SignificantFigures(double number)\n {\n original = Convert.ToString(number);\n try\n {\n Parse(original);\n }\n catch (Exception nfe)\n {\n _digits = null;\n }\n }\n\n\n public bool UseScientificNotation\n {\n get { return useScientificNotation; }\n set { useScientificNotation = value; }\n }\n\n\n public int GetNumberSignificantFigures()\n {\n if (_digits == null) return 0;\n return _digits.Length;\n }\n\n\n public SignificantFigures SetLSD(int place)\n {\n SetLMSD(place, Int32.MinValue);\n return this;\n }\n\n public SignificantFigures SetLMSD(int leastPlace, int mostPlace)\n {\n if (_digits != null && leastPlace != Int32.MinValue)\n {\n int significantFigures = _digits.Length;\n int current = mantissa - significantFigures + 1;\n int newLength = significantFigures - leastPlace + current;\n if (newLength <= 0)\n {\n if (mostPlace == Int32.MinValue)\n {\n original = \"NaN\";\n _digits = null;\n }\n else\n {\n newLength = mostPlace - leastPlace + 1;\n _digits.Length = newLength;\n mantissa = leastPlace;\n for (int i = 0; i < newLength; i++)\n {\n _digits[i] = '0';\n }\n isZero = true;\n sign = true;\n }\n }\n else\n {\n _digits.Length = newLength;\n for (int i = significantFigures; i < newLength; i++)\n {\n _digits[i] = '0';\n }\n }\n }\n return this;\n }\n\n\n public int GetLSD()\n {\n if (_digits == null) return Int32.MinValue;\n return mantissa - _digits.Length + 1;\n }\n\n public int GetMSD()\n {\n if (_digits == null) return Int32.MinValue;\n return mantissa + 1;\n }\n\n public override String ToString()\n {\n if (_digits == null) return original;\n StringBuilder digits = new StringBuilder(this._digits.ToString());\n int length = digits.Length;\n if ((mantissa <= -4 || mantissa >= 7 ||\n (mantissa >= length &&\n digits[digits.Length - 1] == '0') ||\n (isZero && mantissa != 0)) && useScientificNotation)\n {\n // use scientific notation.\n if (length > 1)\n {\n digits.Insert(1, '.');\n }\n if (mantissa != 0)\n {\n digits.Append(\"E\" + mantissa);\n }\n }\n else if (mantissa <= -1)\n {\n digits.Insert(0, \"0.\");\n for (int i = mantissa; i < -1; i++)\n {\n digits.Insert(2, '0');\n }\n }\n else if (mantissa + 1 == length)\n {\n if (length > 1 && digits[digits.Length - 1] == '0')\n {\n digits.Append('.');\n }\n }\n else if (mantissa < length)\n {\n digits.Insert(mantissa + 1, '.');\n }\n else\n {\n for (int i = length; i <= mantissa; i++)\n {\n digits.Append('0');\n }\n }\n if (!sign)\n {\n digits.Insert(0, '-');\n }\n return digits.ToString();\n }\n\n\n public String ToScientificNotation()\n {\n if (_digits == null) return original;\n StringBuilder digits = new StringBuilder(this._digits.ToString());\n int length = digits.Length;\n if (length > 1)\n {\n digits.Insert(1, '.');\n }\n if (mantissa != 0)\n {\n digits.Append(\"E\" + mantissa);\n }\n if (!sign)\n {\n digits.Insert(0, '-');\n }\n return digits.ToString();\n }\n\n\n private const int INITIAL = 0;\n private const int LEADZEROS = 1;\n private const int MIDZEROS = 2;\n private const int DIGITS = 3;\n private const int LEADZEROSDOT = 4;\n private const int DIGITSDOT = 5;\n private const int MANTISSA = 6;\n private const int MANTISSADIGIT = 7;\n\n private void Parse(String number)\n {\n int length = number.Length;\n _digits = new StringBuilder(length);\n int state = INITIAL;\n int mantissaStart = -1;\n bool foundMantissaDigit = false;\n // sometimes we don't know if a zero will be\n // significant or not when it is encountered.\n // keep track of the number of them so that\n // the all can be made significant if we find\n // out that they are.\n int zeroCount = 0;\n int leadZeroCount = 0;\n\n for (int i = 0; i < length; i++)\n {\n char c = number[i];\n switch (c)\n {\n case '.':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n {\n state = LEADZEROSDOT;\n }\n break;\n case MIDZEROS:\n {\n // we now know that these zeros\n // are more than just trailing place holders.\n for (int j = 0; j < zeroCount; j++)\n {\n _digits.Append('0');\n }\n zeroCount = 0;\n state = DIGITSDOT;\n }\n break;\n case DIGITS:\n {\n state = DIGITSDOT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '+':\n {\n switch (state)\n {\n case INITIAL:\n {\n sign = true;\n state = LEADZEROS;\n }\n break;\n case MANTISSA:\n {\n state = MANTISSADIGIT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '-':\n {\n switch (state)\n {\n case INITIAL:\n {\n sign = false;\n state = LEADZEROS;\n }\n break;\n case MANTISSA:\n {\n state = MANTISSADIGIT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '0':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n {\n // only significant if number\n // is all zeros.\n zeroCount++;\n leadZeroCount++;\n state = LEADZEROS;\n }\n break;\n case MIDZEROS:\n case DIGITS:\n {\n // only significant if followed\n // by a decimal point or nonzero digit.\n mantissa++;\n zeroCount++;\n state = MIDZEROS;\n }\n break;\n case LEADZEROSDOT:\n {\n // only significant if number\n // is all zeros.\n mantissa--;\n zeroCount++;\n state = LEADZEROSDOT;\n }\n break;\n case DIGITSDOT:\n {\n // non-leading zeros after\n // a decimal point are always\n // significant.\n _digits.Append(c);\n }\n break;\n case MANTISSA:\n case MANTISSADIGIT:\n {\n foundMantissaDigit = true;\n state = MANTISSADIGIT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n case DIGITS:\n {\n zeroCount = 0;\n _digits.Append(c);\n mantissa++;\n state = DIGITS;\n }\n break;\n case MIDZEROS:\n {\n // we now know that these zeros\n // are more than just trailing place holders.\n for (int j = 0; j < zeroCount; j++)\n {\n _digits.Append('0');\n }\n zeroCount = 0;\n _digits.Append(c);\n mantissa++;\n state = DIGITS;\n }\n break;\n case LEADZEROSDOT:\n case DIGITSDOT:\n {\n zeroCount = 0;\n _digits.Append(c);\n state = DIGITSDOT;\n }\n break;\n case MANTISSA:\n case MANTISSADIGIT:\n {\n state = MANTISSADIGIT;\n foundMantissaDigit = true;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case 'E':\n case 'e':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n case DIGITS:\n case LEADZEROSDOT:\n case DIGITSDOT:\n {\n // record the starting point of the mantissa\n // so we can do a substring to get it back later\n mantissaStart = i + 1;\n state = MANTISSA;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n if (mantissaStart != -1)\n {\n // if we had found an 'E'\n if (!foundMantissaDigit)\n {\n // we didn't actually find a mantissa to go with.\n throw new Exception(\n \"No digits in mantissa.\"\n );\n }\n // parse the mantissa.\n mantissa += Convert.ToInt32(number.Substring(mantissaStart));\n }\n if (_digits.Length == 0)\n {\n if (zeroCount > 0)\n {\n // if nothing but zeros all zeros are significant.\n for (int j = 0; j < zeroCount; j++)\n {\n _digits.Append('0');\n }\n mantissa += leadZeroCount;\n isZero = true;\n sign = true;\n }\n else\n {\n // a hack to catch some cases that we could catch\n // by adding a ton of extra states. Things like:\n // \"e2\" \"+e2\" \"+.\" \".\" \"+\" etc.\n throw new Exception(\n \"No digits in number.\"\n );\n }\n }\n }\n\n public SignificantFigures SetNumberSignificantFigures(int significantFigures)\n {\n if (significantFigures <= 0)\n throw new ArgumentException(\"Desired number of significant figures must be positive.\");\n if (_digits != null)\n {\n int length = _digits.Length;\n if (length < significantFigures)\n {\n // number is not long enough, pad it with zeros.\n for (int i = length; i < significantFigures; i++)\n {\n _digits.Append('0');\n }\n }\n else if (length > significantFigures)\n {\n // number is too long chop some of it off with rounding.\n bool addOne; // we need to round up if true.\n char firstInSig = _digits[significantFigures];\n if (firstInSig < '5')\n {\n // first non-significant digit less than five, round down.\n addOne = false;\n }\n else if (firstInSig == '5')\n {\n // first non-significant digit equal to five\n addOne = false;\n for (int i = significantFigures + 1; !addOne && i < length; i++)\n {\n // if its followed by any non-zero digits, round up.\n if (_digits[i] != '0')\n {\n addOne = true;\n }\n }\n if (!addOne)\n {\n // if it was not followed by non-zero digits\n // if the last significant digit is odd round up\n // if the last significant digit is even round down\n addOne = (_digits[significantFigures - 1] & 1) == 1;\n }\n }\n else\n {\n // first non-significant digit greater than five, round up.\n addOne = true;\n }\n // loop to add one (and carry a one if added to a nine)\n // to the last significant digit\n for (int i = significantFigures - 1; addOne && i >= 0; i--)\n {\n char digit = _digits[i];\n if (digit < '9')\n {\n _digits[i] = (char) (digit + 1);\n addOne = false;\n }\n else\n {\n _digits[i] = '0';\n }\n }\n if (addOne)\n {\n // if the number was all nines\n _digits.Insert(0, '1');\n mantissa++;\n }\n // chop it to the correct number of figures.\n _digits.Length = significantFigures;\n }\n }\n return this;\n }\n\n public double ToDouble()\n {\n return Convert.ToDouble(original);\n }\n\n public static String Format(double number, int significantFigures)\n {\n SignificantFigures sf = new SignificantFigures(number);\n sf.SetNumberSignificantFigures(significantFigures);\n return sf.ToString();\n }\n}\n" }, { "answer_id": 1987721, "author": "HAL9000", "author_id": 128506, "author_profile": "https://Stackoverflow.com/users/128506", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Globalization;\n\npublic static class Precision\n{\n // 2^-24\n public const float FLOAT_EPSILON = 0.0000000596046448f;\n\n // 2^-53\n public const double DOUBLE_EPSILON = 0.00000000000000011102230246251565d;\n\n public static bool AlmostEquals(this double a, double b, double epsilon = DOUBLE_EPSILON)\n {\n // ReSharper disable CompareOfFloatsByEqualityOperator\n if (a == b)\n {\n return true;\n }\n // ReSharper restore CompareOfFloatsByEqualityOperator\n\n return (System.Math.Abs(a - b) < epsilon);\n }\n\n public static bool AlmostEquals(this float a, float b, float epsilon = FLOAT_EPSILON)\n {\n // ReSharper disable CompareOfFloatsByEqualityOperator\n if (a == b)\n {\n return true;\n }\n // ReSharper restore CompareOfFloatsByEqualityOperator\n\n return (System.Math.Abs(a - b) < epsilon);\n }\n}\n\npublic static class SignificantDigits\n{\n public static double Round(this double value, int significantDigits)\n {\n int unneededRoundingPosition;\n return RoundSignificantDigits(value, significantDigits, out unneededRoundingPosition);\n }\n\n public static string ToString(this double value, int significantDigits)\n {\n // this method will round and then append zeros if needed.\n // i.e. if you round .002 to two significant figures, the resulting number should be .0020.\n\n var currentInfo = CultureInfo.CurrentCulture.NumberFormat;\n\n if (double.IsNaN(value))\n {\n return currentInfo.NaNSymbol;\n }\n\n if (double.IsPositiveInfinity(value))\n {\n return currentInfo.PositiveInfinitySymbol;\n }\n\n if (double.IsNegativeInfinity(value))\n {\n return currentInfo.NegativeInfinitySymbol;\n }\n\n int roundingPosition;\n var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition);\n\n // when rounding causes a cascading round affecting digits of greater significance, \n // need to re-round to get a correct rounding position afterwards\n // this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10\n RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition);\n\n if (Math.Abs(roundingPosition) > 9)\n {\n // use exponential notation format\n // ReSharper disable FormatStringProblem\n return string.Format(currentInfo, \"{0:E\" + (significantDigits - 1) + \"}\", roundedValue);\n // ReSharper restore FormatStringProblem\n }\n\n // string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.)\n // ReSharper disable FormatStringProblem\n return roundingPosition > 0 ? string.Format(currentInfo, \"{0:F\" + roundingPosition + \"}\", roundedValue) : roundedValue.ToString(currentInfo);\n // ReSharper restore FormatStringProblem\n }\n\n private static double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition)\n {\n // this method will return a rounded double value at a number of signifigant figures.\n // the sigFigures parameter must be between 0 and 15, exclusive.\n\n roundingPosition = 0;\n\n if (value.AlmostEquals(0d))\n {\n roundingPosition = significantDigits - 1;\n return 0d;\n }\n\n if (double.IsNaN(value))\n {\n return double.NaN;\n }\n\n if (double.IsPositiveInfinity(value))\n {\n return double.PositiveInfinity;\n }\n\n if (double.IsNegativeInfinity(value))\n {\n return double.NegativeInfinity;\n }\n\n if (significantDigits < 1 || significantDigits > 15)\n {\n throw new ArgumentOutOfRangeException(\"significantDigits\", value, \"The significantDigits argument must be between 1 and 15.\");\n }\n\n // The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places.\n roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value))));\n\n // try to use a rounding position directly, if no scale is needed.\n // this is because the scale mutliplication after the rounding can introduce error, although \n // this only happens when you're dealing with really tiny numbers, i.e 9.9e-14.\n if (roundingPosition > 0 && roundingPosition < 16)\n {\n return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero);\n }\n\n // Shouldn't get here unless we need to scale it.\n // Set the scaling value, for rounding whole numbers or decimals past 15 places\n var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value))));\n\n return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale;\n }\n}\n" }, { "answer_id": 9017180, "author": "Sae1962", "author_id": 265140, "author_profile": "https://Stackoverflow.com/users/265140", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace ConsoleApplicationRound\n{\n class Program\n {\n static void Main(string[] args)\n {\n //char cDecimal = '.'; // for English cultures\n char cDecimal = ','; // for German cultures\n List<double> l_dValue = new List<double>();\n ushort usSignificants = 5;\n\n l_dValue.Add(0);\n l_dValue.Add(0.000640589);\n l_dValue.Add(-0.000640589);\n l_dValue.Add(-123.405009);\n l_dValue.Add(123.405009);\n l_dValue.Add(-540);\n l_dValue.Add(540);\n l_dValue.Add(-540911);\n l_dValue.Add(540911);\n l_dValue.Add(-118.2);\n l_dValue.Add(118.2);\n l_dValue.Add(-118.18);\n l_dValue.Add(118.18);\n l_dValue.Add(-118.188);\n l_dValue.Add(118.188);\n\n foreach (double d in l_dValue)\n {\n Console.WriteLine(\"d = Maths.Round('\" +\n cDecimal + \"', \" + d + \", \" + usSignificants +\n \") = \" + Maths.Round(\n cDecimal, d, usSignificants));\n }\n\n Console.Read();\n }\n }\n}\n using System;\nusing System.Text;\n\nnamespace ConsoleApplicationRound\n{\n class Maths\n {\n /// <summary>\n /// The word \"Window\"\n /// </summary>\n private static String m_strZeros = \"000000000000000000000000000000000\";\n /// <summary>\n /// The minus sign\n /// </summary>\n public const char m_cDASH = '-';\n\n /// <summary>\n /// Determines the number of digits before the decimal point\n /// </summary>\n /// <param name=\"cDecimal\">\n /// Language-specific decimal separator\n /// </param>\n /// <param name=\"strValue\">\n /// Value to be scrutinised\n /// </param>\n /// <returns>\n /// Nr. of digits before the decimal point\n /// </returns>\n private static ushort NrOfDigitsBeforeDecimal(char cDecimal, String strValue)\n {\n short sDecimalPosition = (short)strValue.IndexOf(cDecimal);\n ushort usSignificantDigits = 0;\n\n if (sDecimalPosition >= 0)\n {\n strValue = strValue.Substring(0, sDecimalPosition + 1);\n }\n\n for (ushort us = 0; us < strValue.Length; us++)\n {\n if (strValue[us] != m_cDASH) usSignificantDigits++;\n\n if (strValue[us] == cDecimal)\n {\n usSignificantDigits--;\n break;\n }\n }\n\n return usSignificantDigits;\n }\n\n /// <summary>\n /// Rounds to a fixed number of significant digits\n /// </summary>\n /// <param name=\"d\">\n /// Number to be rounded\n /// </param>\n /// <param name=\"usSignificants\">\n /// Requested significant digits\n /// </param>\n /// <returns>\n /// The rounded number\n /// </returns>\n public static String Round(char cDecimal,\n double d,\n ushort usSignificants)\n {\n StringBuilder value = new StringBuilder(Convert.ToString(d));\n\n short sDecimalPosition = (short)value.ToString().IndexOf(cDecimal);\n ushort usAfterDecimal = 0;\n ushort usDigitsBeforeDecimalPoint =\n NrOfDigitsBeforeDecimal(cDecimal, value.ToString());\n\n if (usDigitsBeforeDecimalPoint == 1)\n {\n usAfterDecimal = (d == 0)\n ? usSignificants\n : (ushort)(value.Length - sDecimalPosition - 2);\n }\n else\n {\n if (usSignificants >= usDigitsBeforeDecimalPoint)\n {\n usAfterDecimal =\n (ushort)(usSignificants - usDigitsBeforeDecimalPoint);\n }\n else\n {\n double dPower = Math.Pow(10,\n usDigitsBeforeDecimalPoint - usSignificants);\n\n d = dPower*(long)(d/dPower);\n }\n }\n\n double dRounded = Math.Round(d, usAfterDecimal);\n StringBuilder result = new StringBuilder();\n\n result.Append(dRounded);\n ushort usDigits = (ushort)result.ToString().Replace(\n Convert.ToString(cDecimal), \"\").Replace(\n Convert.ToString(m_cDASH), \"\").Length;\n\n // Add lagging zeros, if necessary:\n if (usDigits < usSignificants)\n {\n if (usAfterDecimal != 0)\n {\n if (result.ToString().IndexOf(cDecimal) == -1)\n {\n result.Append(cDecimal);\n }\n\n int i = (d == 0) ? 0 : Math.Min(0, usDigits - usSignificants);\n\n result.Append(m_strZeros.Substring(0, usAfterDecimal + i));\n }\n }\n\n return result.ToString();\n }\n }\n}\n" }, { "answer_id": 24900749, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "static public string SignificantDigits(double d, int digits=10)\n{\n int magnitude = (d == 0.0) ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(d))) + 1;\n digits -= magnitude;\n if (digits < 0)\n digits = 0;\n string fmt = \"f\" + digits.ToString();\n return d.ToString(fmt);\n}\n" }, { "answer_id": 34287671, "author": "bradgonesurfing", "author_id": 158285, "author_profile": "https://Stackoverflow.com/users/158285", "pm_score": 1, "selected": false, "text": " public static int CountDigits\n (BigInteger number) => ((int)BigInteger.Log10(number))+1;\n\n private static readonly BigInteger[] BigPowers10 \n = Enumerable.Range(0, 100)\n .Select(v => BigInteger.Pow(10, v))\n .ToArray();\n public static decimal RoundToSignificantDigits\n (this decimal num,\n short n)\n {\n var bits = decimal.GetBits(num);\n var u0 = unchecked((uint)bits[0]);\n var u1 = unchecked((uint)bits[1]);\n var u2 = unchecked((uint)bits[2]);\n\n var i = new BigInteger(u0)\n + (new BigInteger(u1) << 32)\n + (new BigInteger(u2) << 64);\n\n var d = CountDigits(i);\n\n var delta = d - n;\n if (delta < 0)\n return num;\n\n var scale = BigPowers10[delta];\n var div = i/scale;\n var rem = i%scale;\n var up = rem > scale/2;\n if (up)\n div += 1;\n var shifted = div*scale;\n\n bits[0] =unchecked((int)(uint) (shifted & BigUnitMask));\n bits[1] =unchecked((int)(uint) (shifted>>32 & BigUnitMask));\n bits[2] =unchecked((int)(uint) (shifted>>64 & BigUnitMask));\n\n return new decimal(bits);\n }\n public void RoundToSignificantDigits()\n {\n WMath.RoundToSignificantDigits(0.0012345m, 2).Should().Be(0.0012m);\n WMath.RoundToSignificantDigits(0.0012645m, 2).Should().Be(0.0013m);\n WMath.RoundToSignificantDigits(0.040000000000000008, 6).Should().Be(0.04);\n WMath.RoundToSignificantDigits(0.040000010000000008, 6).Should().Be(0.04);\n WMath.RoundToSignificantDigits(0.040000100000000008, 6).Should().Be(0.0400001);\n WMath.RoundToSignificantDigits(0.040000110000000008, 6).Should().Be(0.0400001);\n WMath.RoundToSignificantDigits(0.20000000000000004, 6).Should().Be(0.2);\n WMath.RoundToSignificantDigits(0.10000000000000002, 6).Should().Be(0.1);\n WMath.RoundToSignificantDigits(0.0, 6).Should().Be(0.0);\n\n }\n public void RoundToSigFigShouldWork()\n {\n 1.2m.RoundToSignificantDigits(1).Should().Be(1m);\n 0.01235668m.RoundToSignificantDigits(3).Should().Be(0.0124m);\n 0.01m.RoundToSignificantDigits(3).Should().Be(0.01m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(4)\n .Should().Be(1.235m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(16)\n .Should().Be(1.234567891234568m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(24)\n .Should().Be(1.23456789123456789123457m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(27)\n .Should().Be(1.23456789123456789123456789m);\n }\n" }, { "answer_id": 72822009, "author": "Elliott Prechter", "author_id": 9529346, "author_profile": "https://Stackoverflow.com/users/9529346", "pm_score": 0, "selected": false, "text": "public static double ToDecimal( this double x, int significantFigures = 15 ) {\n // determine # of digits before & after the decimal\n int digitsBeforeDecimal = (int)x.Abs().Log10().Ceil().Max( 0 ),\n digitsAfterDecimal = (significantFigures - digitsBeforeDecimal).Max( 0 );\n\n // round it off\n return x.Round( digitsAfterDecimal );\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
158,174
<p>I've been reading through a lot of the rookie Java questions on <code>finalize()</code> and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come as close to a guarantee that a Connection is closed is to implement try (catch) finally. </p> <p>I was not schooled in CS, but I have been programming in Java professionally for close to a decade now and I have never seen anyone implement <code>finalize()</code> in a production system ever. This still doesn't mean that it doesn't have its uses, or that people I've worked with have been doing it right.</p> <p>So my question is, what use cases are there for implementing <code>finalize()</code> that cannot be handled more reliably via another process or syntax within the language? </p> <p>Please provide specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, as is not the intent of this question.</p>
[ { "answer_id": 158196, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 5, "selected": false, "text": "finalize()" }, { "answer_id": 158216, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 9, "selected": true, "text": "close() finalize() close() stderr try {} finally {} Object.finalize() java.lang.ref.Cleaner java.lang.ref.PhantomReference" }, { "answer_id": 158353, "author": "Steven M. Cherry", "author_id": 24193, "author_profile": "https://Stackoverflow.com/users/24193", "pm_score": 3, "selected": false, "text": "finalize()" }, { "answer_id": 158370, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 8, "selected": false, "text": "finalize()" }, { "answer_id": 158624, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 5, "selected": false, "text": "public void finalize() {\n ref1 = null;\n ref2 = null;\n othercrap = null;\n}\n" }, { "answer_id": 172079, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 5, "selected": false, "text": "itsadok@laptop ~/jdk1.6.0_02/src/\n$ find . -name \"*.java\" | xargs grep \"void finalize()\" | wc -l\n41\n" }, { "answer_id": 547035, "author": "TofuBeer", "author_id": 65868, "author_profile": "https://Stackoverflow.com/users/65868", "pm_score": 4, "selected": false, "text": "finalize()" }, { "answer_id": 937630, "author": "Kiki", "author_id": 115313, "author_profile": "https://Stackoverflow.com/users/115313", "pm_score": 4, "selected": false, "text": "class MyObject {\n Test main;\n\n public MyObject(Test t) { \n main = t; \n }\n\n protected void finalize() {\n main.ref = this; // let instance become reachable again\n System.out.println(\"This is finalize\"); //test finalize run only once\n }\n}\n\nclass Test {\n MyObject ref;\n\n public static void main(String[] args) {\n Test test = new Test();\n test.ref = new MyObject(test);\n test.ref = null; //MyObject become unreachable,finalize will be invoked\n System.gc(); \n if (test.ref != null) System.out.println(\"MyObject still alive!\"); \n }\n}\n This is finalize\n\nMyObject still alive!\n" }, { "answer_id": 2191713, "author": "user265243", "author_id": 265243, "author_profile": "https://Stackoverflow.com/users/265243", "pm_score": 2, "selected": false, "text": "@Override\npublic void finalize()\n{\n try {saveCache();} catch (Exception e) {e.printStackTrace();}\n}\n\npublic void saveCache() throws FileNotFoundException, IOException\n{\n ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(\"temp/cache.tmp\"));\n out.writeObject(cache);\n}\n" }, { "answer_id": 29082211, "author": "Ky -", "author_id": 453435, "author_profile": "https://Stackoverflow.com/users/453435", "pm_score": 0, "selected": false, "text": "finalize() finalize() public void finalize() throws Throwable {\n super.finalize();\n if (destructiveFinalize) {\n T item;\n for (int i = 0, l = length(); i < l; i++) {\n item = get(i);\n if (item == null) {\n continue;\n }\n if (item instanceof Window) {\n ((Window) get(i)).dispose();\n }\n if (item instanceof CompleteObject) {\n ((CompleteObject) get(i)).finalize();\n }\n set(i, null);\n }\n }\n}\n CompleteObject Object #finalize() #hashCode() #clone() #setDestructivelyFinalizes(boolean)" }, { "answer_id": 31017317, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 0, "selected": false, "text": "close() finally try-catch finalize() try (BufferedReader br = new BufferedReader(new FileReader(path))) {\n // Processing and other logic here.\n} catch (Exception e) {\n // log exception\n} finally {\n // Just in case we need to do some stuff here.\n}\n BufferedReader close()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8528/" ]
158,175
<p>How can you relatively position elements in WPF? The standard model is to use layout managers for everything, but what if you want to position elements (on a Canvas, for example) simply based on the position of other elements?</p> <p>For example, you may want one element (say a button) to be attached the side of another (perhaps a panel) independent of the position or layout of that panel. Anyone that's worked with engineering tools (SolidWorks, AutoCad, etc.) is familiar with this sort of relative positioning.</p> <p>Forcing everything into layout managers (the different WPF Panels) does not make much sense for certain scenarios, where you don't care that elements are maintained by some parent container and you do not want the other children to be affected by a change in the layout/appearance of each other. Does WPF support this relative positioning model in any way?</p>
[ { "answer_id": 161532, "author": "Dave Arkell", "author_id": 4002, "author_profile": "https://Stackoverflow.com/users/4002", "pm_score": 4, "selected": false, "text": "<Canvas>\n <StackPanel Canvas.Left=\"100\" Canvas.Top=\"100\" Orientation=\"Horizontal\">\n <Button>Button 1</Button><Button>Button 2</Button>\n </StackPanel>\n</Canvas>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24177/" ]
158,189
<p><a href="http://www.techonthenet.com/oracle/functions/trunc_date.php]" rel="noreferrer">This page</a> mentions how to trunc a timestamp to minutes/hours/etc. in Oracle.</p> <p>How would you trunc a timestamp to seconds in the same manner?</p>
[ { "answer_id": 158252, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 6, "selected": true, "text": "DATE TRUNC TIMESTAMP DATE select cast(systimestamp as date) \n from dual;\n" }, { "answer_id": 158322, "author": "David", "author_id": 24187, "author_profile": "https://Stackoverflow.com/users/24187", "pm_score": 1, "selected": false, "text": "timestamp CAST(timestamp AS DATE)\n TRUNC TRUNC(CAST(timestamp AS DATE), 'YEAR')\n" }, { "answer_id": 158483, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "select to_char(current_timestamp, 'SS') from dual;\n" }, { "answer_id": 700532, "author": "drnk", "author_id": 77619, "author_profile": "https://Stackoverflow.com/users/77619", "pm_score": 2, "selected": false, "text": "FUNCTION trunc_sec(p_ts IN timestamp)\nIS\n p_res timestamp;\nBEGIN\n RETURN TO_TIMESTAMP(TO_CHAR(p_ts, 'YYYYMMDDHH24MI'), 'YYYYMMDDHH24MI');\nEND trunc_sec;\n" }, { "answer_id": 2109759, "author": "bierwaermer", "author_id": 255851, "author_profile": "https://Stackoverflow.com/users/255851", "pm_score": 2, "selected": false, "text": "select cast(systimestamp as date) from dual \n CREATE OR REPLACE FUNCTION TRUNC_TS(TS IN TIMESTAMP) RETURN DATE AS\nBEGIN\n\n RETURN TS;\n\nEND;\n SELECT systimestamp\n ,trunc_ts(systimestamp) date_trunc\n ,CAST(systimestamp AS DATE) date_cast \nFROM dual;\n \n SYSTIMESTAMP DATE_TRUNC DATE_CAST\n 21.01.10 15:03:34,567350 +01:00 21.01.2010 15:03:34 21.01.2010 15:03:35\n" }, { "answer_id": 40994973, "author": "andy", "author_id": 7256928, "author_profile": "https://Stackoverflow.com/users/7256928", "pm_score": 2, "selected": false, "text": "to_char(START_TIME,'YYYYMMDDHH24MISS') select to_char(current_timestamp, 'YYYYMMDDHH24MISS') from dual;" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686/" ]
158,209
<p>curious if anyone might have some insight in how I would do the following to a binary number:</p> <p>convert </p> <pre><code> 01+0 -&gt; 10+1 (+ as in regular expressions, one or more) 01 -&gt; 10 10 -&gt; 01 </code></pre> <p>so,</p> <pre><code>10101000010100011100 01010100101010100010 </code></pre> <p>and to clarify that this isn't a simple inversion:</p> <pre><code>000000100000000000 000001010000000000 </code></pre> <p>I was thinking regex, but I'm working with binary numbers and want to stay that way. The <a href="http://graphics.stanford.edu/~seander/bithacks.html" rel="nofollow noreferrer">bit twiddling hacks</a> page hasn't given me any insight either. This clearly has some essence of cellular automata. So, anyone have a few bit operations that can take care of this? (no code is necessary, I know how to do that). </p>
[ { "answer_id": 158258, "author": "Uhall", "author_id": 19129, "author_profile": "https://Stackoverflow.com/users/19129", "pm_score": 5, "selected": true, "text": "unsigned myBitOperation(unsigned x)\n{\n return ((x<<1) | (x>>1)) & (~x);\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157/" ]
158,219
<p>I have a C# application that includes the following code:</p> <pre><code>string file = "relativePath.txt"; //Time elapses... string contents = File.ReadAllText(file); </code></pre> <p>This works fine, most of the time. The file is read relative to the directory that the app was started from. However, in testing, it has been found that if left alone for about 5 hours, the app will throw a <code>FileNotFoundException</code> saying that "C:\Documents and Settings\Adminstrator\relativePath.txt" could not be found. If the action that reads the file is run right away though, the file is read from the proper location, which we'll call "C:\foo\relativePath.txt"</p> <p>What gives? And, what is the best fix? Resolving the file against <code>Assembly.GetEntryAssembly().Location</code>?</p>
[ { "answer_id": 158292, "author": "Greg B", "author_id": 1741868, "author_profile": "https://Stackoverflow.com/users/1741868", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace CWD {\n class Program {\n static void Main (string[] args) {\n Console.WriteLine(Application.StartupPath);\n }\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
158,232
<p>After following the instructions in INSTALL.W64 I have two problems:</p> <ul> <li>The code is still written to the "out32" folder. I need to be able to link to both 32-bit and 64-bit versions of the library on my workstation, so I don't want the 64-bit versions to clobber the 32-bit libs.</li> <li>The output is still 32-bit! This means that I get "unresolved external symbol" errors when trying to link to the libraries from an x64 app.</li> </ul>
[ { "answer_id": 5218838, "author": "lrascao", "author_id": 648012, "author_profile": "https://Stackoverflow.com/users/648012", "pm_score": 1, "selected": false, "text": " echo \"Building x64 OpenSSL\"\n # save the path of the x86 msdev\n MSDEVPATH_x86=$MSDEVPATH\n # and set a new var with x64 one\n MSDEVPATH_x64=`cygpath -u $MSDEVPATH/bin/x86_amd64`\n\n # now set vars with the several lib path for x64 in windows mode\n LIBPATH_AMD64=`cygpath -w $MSDEVPATH_x86/lib/amd64`\n LIBPATH_PLATFORM_x64=`cygpath -w $MSDEVPATH_x86/PlatformSDK/lib/x64`\n # and set the LIB env var that link looks at\n export LIB=\"$LIBPATH_AMD64;$LIBPATH_PLATFORM_x64\"\n\n # the new path for nmake to look for cl, x64 at the start to override any other msdev that was set previously\n export PATH=$MSDEVPATH_x64:$PATH\n\n ./Configure VC-WIN64A zlib-dynamic --prefix=$OUT --with-zlib-include=zlib-$ZLIB_VERSION/include --with-zlib-lib=zlib-$ZLIB_VERSION/x64_lib\n\n # do the deed\n ms/do_win64a.bat\n $MSDEVPATH_x86/bin/nmake -f ms/ntdll.mak ${1:-install}\n" }, { "answer_id": 13500812, "author": "Dan", "author_id": 95559, "author_profile": "https://Stackoverflow.com/users/95559", "pm_score": 2, "selected": false, "text": "util/pl/VC-32.pl $o='\\\\'; if ($debug)\n {\n $ssl .= 'd';\n $crypto .= 'd';\n }\n util/pl/VC-32.pl if ($debug) if ($FLAVOR =~ /WIN64/)\n {\n $out_def =~ s/32/64/;\n $tmp_def =~ s/32/64/;\n $inc_def =~ s/32/64/;\n }\n setenv /x86 /release\nperl Configure VC-WIN32 --prefix=build -DUNICODE -D_UNICODE\nms\\do_ms\nnmake -f ms\\ntdll.mak\n\nsetenv /x64 /release\nperl Configure VC-WIN64A --prefix=build\nms\\do_win64a.bat\nnmake -f ms\\ntdll.mak\n\nsetenv /x86 /debug\nperl Configure debug-VC-WIN32 --prefix=build -DUNICODE -D_UNICODE\nms\\do_ms\nmove /y ms\\libeay32.def ms\\libeay32d.def\nmove /y ms\\ssleay32.def ms\\ssleay32d.def\nnmake -f ms\\ntdll.mak\n\nsetenv /x64 /debug\nperl Configure debug-VC-WIN64A --prefix=build\nms\\do_win64a.bat\nmove /y ms\\libeay32.def ms\\libeay32d.def\nmove /y ms\\ssleay32.def ms\\ssleay32d.def\nnmake -f ms\\ntdll.mak\n" }, { "answer_id": 44318917, "author": "Alejandro PC", "author_id": 4126455, "author_profile": "https://Stackoverflow.com/users/4126455", "pm_score": 2, "selected": false, "text": "conan install OpenSSL/1.0.2g@lasote/stable -s arch=\"x86_64\" -s build_type=\"Debug\" -s compiler=\"gcc\" -s compiler.version=\"5.3\" -s os=\"Linux\" -o 386=\"False\" -o no_asm=\"False\" -o no_rsa=\"False\" -o no_cast=\"False\" -o no_hmac=\"False\" -o no_sse2=\"False\" -o no_zlib=\"False\" ..." } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
158,241
<p>What I want to do is to remove all accents and umlauts from a string, turning "lärm" into "larm" or "andré" into "andre". What I tried to do was to utf8_decode the string and then use strtr on it, but since my source file is saved as UTF-8 file, I can't enter the ISO-8859-15 characters for all umlauts - the editor inserts the UTF-8 characters.</p> <p>Obviously a solution for this would be to have an include that's an ISO-8859-15 file, but there must be a better way than to have another required include?</p> <pre><code>echo strtr(utf8_decode($input), 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); </code></pre> <p><strong>UPDATE:</strong> Maybe I was a bit inaccurate with what I try to do: I do not actually want to remove the umlauts, but to replace them with their closest "one character ASCII" equivalent.</p>
[ { "answer_id": 158247, "author": "BlaM", "author_id": 999, "author_profile": "https://Stackoverflow.com/users/999", "pm_score": 1, "selected": false, "text": "echo strtr(utf8_decode($input), \n utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),\n 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');\n" }, { "answer_id": 158265, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": true, "text": "iconv(\"utf-8\",\"ascii//TRANSLIT\",$input);\n" }, { "answer_id": 5950598, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 5, "selected": false, "text": "function Unaccent($string)\n{\n if (strpos($string = htmlentities($string, ENT_QUOTES, 'UTF-8'), '&') !== false)\n {\n $string = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_QUOTES, 'UTF-8');\n }\n\n return $string;\n}\n" }, { "answer_id": 26816858, "author": "ganji", "author_id": 2971343, "author_profile": "https://Stackoverflow.com/users/2971343", "pm_score": 0, "selected": false, "text": " $diacritics = array('َ','ِ','ً','ٌ','ٍ','ّ','ْ','ـ');\n $search_txt = str_replace($diacritics, '', $diacritics);\n" }, { "answer_id": 35178045, "author": "gabo", "author_id": 1152805, "author_profile": "https://Stackoverflow.com/users/1152805", "pm_score": 3, "selected": false, "text": "$string = \"Fóø Bår\";\n$transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;', Transliterator::FORWARD);\necho $normalized = $transliterator->transliterate($string);\n" }, { "answer_id": 39112592, "author": "jay", "author_id": 6750140, "author_profile": "https://Stackoverflow.com/users/6750140", "pm_score": 0, "selected": false, "text": "utf-8 htmlentities ( $line, ENT_SUBSTITUTE , 'utf-8' ) \n" }, { "answer_id": 50645423, "author": "youtag", "author_id": 3881472, "author_profile": "https://Stackoverflow.com/users/3881472", "pm_score": 1, "selected": false, "text": "remove_accents( $string )" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
[ { "answer_id": 158326, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": " class CRoom(object):\n person = CPerson(\"a person\")\n class CRoom(object):\n def getPerson(self): return CPerson(\"someone\")\n from CRoom import CPerson # or even import *\n #croom.py\nimport cperson\nclass CRoom(object):\n def getPerson(self): return cperson.CPerson(\"someone\")\n" }, { "answer_id": 158331, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import CRoom\n\nCPerson = CRoom.CPerson\n" }, { "answer_id": 158403, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 6, "selected": true, "text": "CRoom person.py CRoom person.py from room import CRoom import room room.CRoom Self.NextId += 1 NextId NextId CRoom.NextId += 1 Self.__class__.NextId += 1" }, { "answer_id": 158505, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "UpperCase lowerCase Room Person room.Room person.Person room.py import person\nclass Room( object ):\n def __init__( self ):\n self.nextId= 0\n self.people= {}\n def addPerson(self, firstName, secondName, gender):\n id= self.NextId\n self.nextId += 1\n\n thePerson = person.Person(firstName,secondName,gender,id)\n self.people[id] = thePerson\n return thePerson \n person.py import room\nclass Person( object ):\n def something( self, x, y ):\n aRoom= room.Room( )\n aRoom.addPerson( self.firstName, self.lastName, self.gender )\n main.py import room\nimport person\nr = room.Room( ... )\nr.addPerson( \"some\", \"name\", \"M\" )\nprint r\n" }, { "answer_id": 158620, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 0, "selected": false, "text": "from room import CRoom\nfrom person import CPerson\n\nRoom = CRoom()\n\nBen = Room.AddPerson('Ben', 'Blacker', 'Male')\nTom = Room.AddPerson('Tom', 'Smith', 'Male')\n\nBen.Leave()\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
158,279
<p>I've updated <strong>php.ini</strong> and moved <strong>php_mysql.dll</strong> as explained in <a href="https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341">steps 6 and 8 here.</a></p> <p>I get this error&hellip;</p> <pre>Fatal error: Call to undefined function mysql_connect() in C:\inetpub...</pre> <p>MySQL doesn't show up in my <strong>phpinfo;</strong> report.</p> <hr> <p>I've updated the <strong>c:\Windows\php.ini</strong> file from</p> <pre>; Directory in which the loadable extensions (modules) reside. extension_dir = "./"</pre> <p>to</p> <pre>; Directory in which the loadable extensions (modules) reside. extension_dir = ".;c:\Windows\System32"</pre> <p>Result: no change.</p> <hr> <p>I changed the <strong>php.ini</strong> value of extension_dir thusly:</p> <pre>extension_dir = "C:\Windows\System32"</pre> <p>Result: much more in the <strong>phpinfo;</strong> report, but MySQL still isn't working.</p> <hr> <p>I copied the file <strong>libmysql.dll</strong> from folder <strong>C:\php</strong> to folders <strong>C:\Windows\System32</strong> and <strong>C:\Windows</strong></p> <p>Result: no change.</p> <hr> <p>I stopped and <strong>restarted IIS</strong>.</p> <p>Result: new, different errors instead!</p> <pre>Warning: mysql_connect() [function.mysql-connect]: Access denied for user '...'@'localhost' (using password: YES) in C:\inetpub\... error in query.</pre> <pre>Fatal error: Call to a member function RecordCount() on a non-object in C:\inetpub\...</pre> <hr> <p>I found several .php files in the website where I had to set variables:</p> <pre>$db_user $db_pass</pre> <p>Result: The site works!</p>
[ { "answer_id": 158538, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 4, "selected": true, "text": "extension_dir = \"H:\\apps\\php\\ext\\\"\nextension=php_mysql.dll\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
158,283
<p>I have two vista Business machines. I have IE 7 installed on both. On my first machine (Computer1) if I go to this site (<a href="http://www.quirksmode.org/js/detect.html" rel="nofollow noreferrer">http://www.quirksmode.org/js/detect.html</a>), it says I am using "Explorer 6 on Windows". If I use Computer2 with Vista Business and IE7, it says I am using "Explorer 7 on Windows". Here is a screen <a href="http://www.rickdoes.net/blog/images/ie6.png" rel="nofollow noreferrer">capture</a>. The same version of IE is on both machines. Anyone have a solution?</p>
[ { "answer_id": 158378, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 4, "selected": true, "text": "Computer1: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MS-RTC LM 8; .NET CLR 1.1.4322) Rick Kierner (11 minutes ago)\nComputer2: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; InfoPath.2; .NET CLR 3.5.21022) Rick Kierner (10 minutes ago)\n Mozilla/4.0 (compatible...) [HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\\nInternet Settings\\5.0\\User Agent]" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11771/" ]
158,310
<p>Is there a tool (preferably free) which will translate Oracle's PL/SQL stored procedure language into Postgresql's PL/pgSQL stored procedure language?</p>
[ { "answer_id": 4037746, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "CREATE OR REPLACE FUNCTION trunc(\n parmDate DATE ,\n parmFormat VARCHAR ) \nRETURNS date \nAS $$\nDECLARE\n varPlSqlFormat VARCHAR;\n varPgSqlFormat VARCHAR;\nBEGIN\n varPgSqlFormat := lower(parmFormat);\n\n IF varPgSqlFormat IN (\n 'syyyy' ,\n 'yyyy' ,\n 'year' ,\n 'syear' ,\n 'yyy' ,\n 'yy' ,\n 'y' ) THEN\n varPgSqlFormat := 'year';\n ELSEIF varPgSqlFormat IN (\n 'month' ,\n 'mon' ,\n 'mm' ,\n 'rm' ) THEN \n varPgSqlFormat := 'month';\n ELSEIF varPgSqlFormat IN (\n 'ddd' ,\n 'dd' ,\n 'j' ) THEN \n varPgSqlFormat := 'day';\n END IF;\n\n RETURN DATE_TRUNC(varPgSqlFormat,parmDate);\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION trunc(\n parmDate DATE) \nRETURNS date \nAS $$\nDECLARE\nBEGIN\n RETURN DATE_TRUNC('day',parmDate);\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION last_day(in_date date) RETURNS date \nAS $$\nDECLARE\nBEGIN\n RETURN CAST(DATE_TRUNC('month', in_date) + '1 month'::INTERVAL AS DATE) - 1;\nEND;\n$$ LANGUAGE plpgsql;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
158,319
<p>For all major browsers (except IE), the JavaScript <code>onload</code> event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded.</p> <p>Can someone point me at some sample cross-browser code (Firefox, Opera, Safari, IE, …) that solves this problem? I’m familiar with Firefox’s <code>pageshow</code> event but unfortunately neither Opera nor Safari implement this.</p>
[ { "answer_id": 158373, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 3, "selected": false, "text": "<html>\n<head>\n <title>Test Page</title>\n <script src=\"http://code.jquery.com/jquery-latest.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function () {\n var d = new Date();\n $('#test').html( \"Hi at \" + d.toString() );\n });\n </script>\n</head>\n<body>\n <div id=\"test\"></div>\n <div>\n <a href=\"http://www.google.com\">Go!</a>\n </div>\n</body>\n</html>\n" }, { "answer_id": 158548, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<title>Untitled Document</title>\n<meta http-equiv=\"expires\" content=\"0\">\n<script src=\"jquery.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n$(document).ready( \n function(){\n alert('test');\n }\n );\n</script>\n</head>\n<body>\n<h1>Test of the page load event and the Back button using jQuery</h1>\n</body>\n</html>\n" }, { "answer_id": 170478, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 5, "selected": false, "text": "history.navigationMode = 'compatible';\n$(document).ready(function(){\n alert('test');\n});\n" }, { "answer_id": 201406, "author": "user123444555621", "author_id": 27862, "author_profile": "https://Stackoverflow.com/users/27862", "pm_score": 8, "selected": true, "text": "// http://code.jquery.com/jquery-latest.js\njQuery(window).bind(\"unload\", function() { // ...\n <body onunload=\"\"><!-- This does the trick -->\n<script type=\"text/javascript\">\n alert('first load / reload');\n window.onload = function(){alert('onload')};\n</script>\n<a href=\"http://stackoverflow.com\">click me, then press the back button</a>\n</body>\n <body><!-- Will not reload on back button -->\n<script type=\"text/javascript\">\n alert('first load / reload');\n window.onload = function(){alert('onload')};\n</script>\n<a href=\"http://stackoverflow.com\">click me, then press the back button</a>\n</body>\n" }, { "answer_id": 2218733, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 6, "selected": false, "text": "load" }, { "answer_id": 2299044, "author": "Brian Heese", "author_id": 277259, "author_profile": "https://Stackoverflow.com/users/277259", "pm_score": 5, "selected": false, "text": "|| element.readyState == 'complete' script.onreadystatechange(function(){ \n if(script.readyState == 'loaded' || script.readyState == 'complete') {\n // call code to execute here.\n } \n});\n" }, { "answer_id": 5018652, "author": "Tom", "author_id": 619967, "author_profile": "https://Stackoverflow.com/users/619967", "pm_score": 2, "selected": false, "text": "$(window).unload(function(){ alert('do unload stuff here'); }); \n" }, { "answer_id": 6972485, "author": "mallesham", "author_id": 882683, "author_profile": "https://Stackoverflow.com/users/882683", "pm_score": 1, "selected": false, "text": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\"\n pageEncoding=\"ISO-8859-1\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n<title>Insert title here</title>\n<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\">\n jQuery(window).bind(\"load\", function() {\n $(\"[name=customerName]\").val('');\n });\n</script>\n</head>\n<body>\n <h1>body.jsp</h1>\n <form action=\"success.jsp\">\n <div id=\"myDiv\">\n\n Your Full Name: <input name=\"yourName\" id=\"fullName\"\n value=\"Your Full Name\" /><br> <br> <input type=\"submit\"><br>\n\n </div>\n\n </form>\n</body>\n</html>\n" }, { "answer_id": 10842561, "author": "thorie", "author_id": 95560, "author_profile": "https://Stackoverflow.com/users/95560", "pm_score": 3, "selected": false, "text": "<input type='hidden' id='dirty'>\n\n<script>\n$(document).ready(function() {\n if ($('#dirty').val()) {\n // ... reload the page or specific divs only\n }\n // when something modifies a div that needs to be refreshed, set dirty=1\n $('#dirty').val('1');\n});\n</script>\n" }, { "answer_id": 51126506, "author": "bafsar", "author_id": 2374053, "author_profile": "https://Stackoverflow.com/users/2374053", "pm_score": 1, "selected": false, "text": " jQuery(document).ready(function($) {\n\n $(window).on('load', function() {\n //...\n });\n\n });\n jQuery(document).ready(function($) {\n //...\n });\n\n //Window Load Start\n window.addEventListener('load', function() {\n jQuery(document).ready(function($) {\n //...\n });\n });\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24190/" ]
158,324
<p>I have a basic model in which i have specified some of the fields to validate the presence of. in the create action in the controller i do the standard:</p> <pre><code>@obj = SomeObject.new(params[:some_obj]) if @obj.save flash[:notice] = "ok" redirect... else flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "&lt;br/&gt;" } redirect to new form end </code></pre> <p>however when i redirect to the new form, the errors show, but the fields are empty. is there a way to repopulate the fields with the entered values so the errors can be corrected easily?</p>
[ { "answer_id": 158499, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 4, "selected": true, "text": "render :action => :new" }, { "answer_id": 161156, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 1, "selected": false, "text": "@obj new @obj = SomeObject.new(params[:some_obj])\n\nif @obj.save\n flash[:notice] = \"ok\"\n # success\nelse\n flash[:error] = @obj.errors.full_messages.collect { |msg| msg + \"<br/>\" }\n flash[:obj] = @obj\n # redirect to new form\nend\n new @obj = flash[:obj] || MyClass.new\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
158,330
<p>I am starting a project for which we will have a thin client, sending requests and getting responses from a server.</p> <p>We are still in the planning stages, so we have a choice to settle on either an Eclipse based GUI (Eclipse plugin) or using GWT as a fromtend for the application.</p> <p>I am not very familiar with Eclipse as a GUI (Nor with GWT) but do know 'normal' Java.</p> <p>What would be the main benefits and drawbacks of either approach?</p> <p><strong>Edit:</strong> Addressing the questions posed:</p> <ul> <li>The project, if Eclipse based, would be using the core Eclipse gui (No coding tools, just bare bones) and the GUI would be packaged with it.</li> <li>I have been looking at GWT and so far seems the best choice, but still have some research to do.</li> <li>Communication method is a variant of CORBA (In house libraries)</li> </ul>
[ { "answer_id": 158499, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 4, "selected": true, "text": "render :action => :new" }, { "answer_id": 161156, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 1, "selected": false, "text": "@obj new @obj = SomeObject.new(params[:some_obj])\n\nif @obj.save\n flash[:notice] = \"ok\"\n # success\nelse\n flash[:error] = @obj.errors.full_messages.collect { |msg| msg + \"<br/>\" }\n flash[:obj] = @obj\n # redirect to new form\nend\n new @obj = flash[:obj] || MyClass.new\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ]
158,336
<p>I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml.</p> <p>Is there a way to run a method/class only on Tomcat startup?</p>
[ { "answer_id": 158358, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 7, "selected": true, "text": "ServletContextListener contextInitialized() <listener>\n <listener-class>my.Listener</listener-class>\n</listener>\n package my;\n\npublic class Listener implements javax.servlet.ServletContextListener {\n\n public void contextInitialized(ServletContext context) {\n MyOtherClass.callMe();\n }\n}\n" }, { "answer_id": 158381, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "SessonListener <servlet>\n <description>Does stuff on container startup</description>\n <display-name>StartupServlet</display-name>\n <servlet-name>StartupServlet</servlet-name>\n <servlet-class>com.foo.bar.servlets.StartupServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n</servlet> \n" }, { "answer_id": 26567732, "author": "Alexander Drobyshevsky", "author_id": 1693748, "author_profile": "https://Stackoverflow.com/users/1693748", "pm_score": 4, "selected": false, "text": " @WebListener\n public class InitializeListner implements ServletContextListener {\n\n @Override\n public final void contextInitialized(final ServletContextEvent sce) {\n\n }\n\n @Override\n public final void contextDestroyed(final ServletContextEvent sce) {\n\n }\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23968/" ]
158,341
<p>Is there a way to turn this 'feature' off? </p>
[ { "answer_id": 158351, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 4, "selected": true, "text": "Tools -> Options -> Sql Server Object Explorer -> General Scripting Options Script USE <database> -> False" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
158,359
<p>I need to know, from within Powershell, if the current drive is a mapped drive or not.</p> <p>Unfortunately, Get-PSDrive is not working "as expected":</p> <pre><code>PS:24 H:\temp &gt;get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp </code></pre> <p>but in MS-Dos "net use" shows that H: is really a mapped network drive:</p> <pre><code>New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. </code></pre> <p>What I want to do is to get the root of the drive and show it in the prompt (see: <a href="https://stackoverflow.com/questions/157923/customizing-powershell-prompt-equivalent-to-cmds-mpg">Customizing PowerShell Prompt - Equivalent to CMD&#39;s $M$P$_$+$G?</a>)</p>
[ { "answer_id": 158456, "author": "Jeff Stong", "author_id": 2459, "author_profile": "https://Stackoverflow.com/users/2459", "pm_score": 4, "selected": true, "text": "PS H:\\> $x = new-object system.io.driveinfo(\"h:\\\")\nPS H:\\> $x.drivetype\nNetwork\n" }, { "answer_id": 158518, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "Get-WMI -query \"Select ProviderName From Win32_LogicalDisk Where DeviceID='H:'\"\n" }, { "answer_id": 158541, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "get-wmiobject Win32_LogicalDisk | ? {$_.deviceid -eq \"s:\"} | % {$_.providername} get-wmiobject Win32_LogicalDisk | ? {$_.drivetype -eq 4} | % {$_.providername}" }, { "answer_id": 158758, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "get-wmiobject win32_volume | ? { $_.DriveType -eq 4 } | % { get-psdrive $_.DriveLetter[0] } \n" }, { "answer_id": 163194, "author": "Goyuix", "author_id": 243, "author_profile": "https://Stackoverflow.com/users/243", "pm_score": 2, "selected": false, "text": "[System.IO.DriveInfo](\"C\")\n" }, { "answer_id": 174599, "author": "Jeffery Hicks", "author_id": 25508, "author_profile": "https://Stackoverflow.com/users/25508", "pm_score": 1, "selected": false, "text": "([System.IO.DriveInfo](\"C\")).Drivetype\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
158,371
<p>I have recently inherited a couple of applications that run as windows services, and I am having problems providing a gui (accessible from a context menu in system tray) with both of them.</p> <p>The reason why we need a gui for a windows service is in order to be able to re-configure the behaviour of the windows service(s) without resorting to stopping/re-starting.</p> <p>My code works fine in debug mode, and I get the context menu come up, and everything behaves correctly etc.</p> <p>When I install the service via "installutil" using a named account (i.e., not Local System Account), the service runs fine, but doesn't display the icon in the system tray (I know this is normal behavior because I don't have the "interact with desktop" option).</p> <p>Here is the problem though - when I choose the "LocalSystemAccount" option, and check the "interact with desktop" option, the service takes AGES to start up for no obvious reason, and I just keep getting </p> <blockquote> <p>Could not start the ... service on Local Computer. <br/><br/> Error 1053: the service did not respond to the start or control request in a timely fashion.</p> </blockquote> <p>Incidentally, I increased the windows service timeout from the default 30 seconds to 2 minutes via a registry hack (see <a href="http://support.microsoft.com/kb/824344" rel="noreferrer">http://support.microsoft.com/kb/824344</a>, search for TimeoutPeriod in section 3), however the service start up still times out.</p> <p>My first question is - why might the "Local System Account" login takes SOOOOO MUCH LONGER than when the service logs in with the non-LocalSystemAccount, causing the windows service time-out? what's could the difference be between these two to cause such different behavior at start up?</p> <p>Secondly - taking a step back, all I'm trying to achieve, is simply a windows service that provides a gui for configuration - I'd be quite happy to run using the non-Local System Account (with named user/pwd), if I could get the service to interact with the desktop (that is, have a context menu available from the system tray). Is this possible, and if so how?</p> <p>Any pointers to the above questions would be appreciated!</p>
[ { "answer_id": 158425, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 3, "selected": false, "text": "GetMachineAccountSid()" }, { "answer_id": 158537, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 5, "selected": false, "text": "<configuration>\n <runtime>\n <generatePublisherEvidence enabled=\"false\"/>\n </runtime>\n</configuration>\n" }, { "answer_id": 158645, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 4, "selected": false, "text": "OnStart() while(!System.Diagnostics.Debugger.IsAttached) Thread.Sleep(100);\n" }, { "answer_id": 5061813, "author": "bob", "author_id": 588521, "author_profile": "https://Stackoverflow.com/users/588521", "pm_score": 0, "selected": false, "text": " private static OracleCommand cmd;\n\n static SchedTasks()\n {\n try\n {\n cmd = new OracleCommand(\"select * from change_notification\");\n }\n catch (Exception e)\n {\n Log(e.Message); \n // \"The provider is not compatible with the version of Oracle client\"\n }\n }\n" }, { "answer_id": 5338171, "author": "Eranna", "author_id": 642477, "author_profile": "https://Stackoverflow.com/users/642477", "pm_score": 3, "selected": false, "text": "protected override void OnStart(string[] args)\n{\n Thread t = new Thead(new ThreadStart(MethodName)); // e.g.\n t.Start();\n}\n" }, { "answer_id": 23417536, "author": "goamn", "author_id": 712700, "author_profile": "https://Stackoverflow.com/users/712700", "pm_score": 2, "selected": false, "text": "ServiceBase.Run(new ServiceHost());" }, { "answer_id": 24987931, "author": "savvyBrar", "author_id": 2892892, "author_profile": "https://Stackoverflow.com/users/2892892", "pm_score": 2, "selected": false, "text": "Thread.Sleep(1000) main()" }, { "answer_id": 27102808, "author": "Bulu", "author_id": 2201465, "author_profile": "https://Stackoverflow.com/users/2201465", "pm_score": 2, "selected": false, "text": "#if(!DEBUG)\nServiceBase[] ServicesToRun;\nServicesToRun = new ServiceBase[]\n{\nnew EmailService()\n};\nServiceBase.Run(ServicesToRun);\n#else\n//direct call function what you need to run\n#endif\n if (args != null && args.Length > 0)\n{\n_isDebug = args[0].ToLower().Contains(\"debug\");\n}\n" }, { "answer_id": 31353483, "author": "Masoud", "author_id": 1594487, "author_profile": "https://Stackoverflow.com/users/1594487", "pm_score": 2, "selected": false, "text": ".net framework <startup>\n <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\" />\n</startup>\n .net Framework <startup>\n <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.0\" />\n</startup>\n" }, { "answer_id": 46954990, "author": "NidhinSPradeep", "author_id": 5310594, "author_profile": "https://Stackoverflow.com/users/5310594", "pm_score": 1, "selected": false, "text": "<startup>\n<supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.6\"/>\n </startup>\n" }, { "answer_id": 55487119, "author": "Akbar Badhusha", "author_id": 6915387, "author_profile": "https://Stackoverflow.com/users/6915387", "pm_score": 1, "selected": false, "text": "Debugger.Launch() BlockingCollection.GetConsumingEnumerable()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24175/" ]
158,375
<p>I want to clear the Firebug console of the JavaScript already sent.</p> <p>Does something like <code>console.clear()</code> exist and work?</p>
[ { "answer_id": 158452, "author": "James", "author_id": 21677, "author_profile": "https://Stackoverflow.com/users/21677", "pm_score": 3, "selected": false, "text": "for(var i in console) {\n console.log(i);\n}\n" }, { "answer_id": 657368, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "console.clear();" }, { "answer_id": 7144526, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 3, "selected": false, "text": "clear();\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24197/" ]
158,382
<p>For some reason, lately the *.UDL files on many of my client systems are no longer compatible as they were once saved as ANSI files, which is no longer compatible with the expected UNICODE file format. The end result is an error dialog which states "the file is not a valid compound file". </p> <p>What is the easiest way to programatically open these files and save as a unicode file? I know I can do this by opening each one in notepad and then saving as the same file but with the "unicode" selected in the encoding section of the save as dialog, but I need to do this in the program to cut down on support calls.</p> <p>This problem is very easy to duplicate, just create a *.txt file in a directory, rename it to *.UDL, then edit it using the microsoft editor. Then open it in notepad and save as the file as an ANSI encoded file. Try to open the udl from the udl editor and it will tell you its corrupt. then save it (using notepad) as a Unicode encoded file and it will open again properly.</p>
[ { "answer_id": 158435, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": true, "text": "var\n strAnsi : TGpTextFile;\n strUnicode: TGpTextFile;\nbegin\n strAnsi := TGpTextFile.Create('c:\\0\\test.udl');\n try\n strAnsi.Reset; // you can also specify non-default 8-bit codepage here\n strUnicode := TGpTextFile.Create('c:\\0\\test-out.udl');\n try\n strUnicode.Rewrite([cfUnicode]);\n while not strAnsi.Eof do\n strUnicode.Writeln(strAnsi.Readln);\n finally FreeAndNil(strUnicode); end;\n finally FreeAndNil(strAnsi); end;\nend;\n" }, { "answer_id": 158448, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 3, "selected": false, "text": "var\n sl : TStrings;\n FileName : string;\nbegin\n FileName := fServerDir+'configuration\\hdconfig4.udl';\n sl := TStringList.Create;\n try\n sl.LoadFromFile(FileName, TEncoding.Default);\n sl.SaveToFile(FileName, TEncoding.Unicode);\n finally\n sl.Free;\n end;\nend;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217/" ]
158,384
<p>If I use mod_rewrite to control all my 301 redirects, does this happen before my page is served? so if I also have a bunch of redirect rules in a php script that runs on my page, will the .htaccess kick in first?</p>
[ { "answer_id": 2095929, "author": "DrDol", "author_id": 254234, "author_profile": "https://Stackoverflow.com/users/254234", "pm_score": 1, "selected": false, "text": "wget -S --spider http://yourdomain.com\n" }, { "answer_id": 12573644, "author": "Lucas", "author_id": 1136709, "author_profile": "https://Stackoverflow.com/users/1136709", "pm_score": 0, "selected": false, "text": ".htaccess .htaccess .htaccess" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24200/" ]
158,388
<p>I have a little program that I want to make open automatically when my mac is started up.</p> <p>Because this program accepts command line arguments, its not as simple as just going to System Prefs/Accounts/Login items and adding it there...</p> <p>From google, I read that I can create a .profile file in my user's home folder, and that will execute whatever I put in it... So I have a .profile page in ~ like this:</p> <p>-rw-r--r--@ 1 matt staff 27 27 Sep 13:36 .profile</p> <p>That contains this...</p> <p>/Applications/mousefix 3.5</p> <p>But it doesn't execute on startup! If I enter "/Applications/mousefix 3.5" manually into the terminal, it does work.</p> <p>Any ideas?</p>
[ { "answer_id": 158401, "author": "rpj", "author_id": 23498, "author_profile": "https://Stackoverflow.com/users/23498", "pm_score": 5, "selected": true, "text": "launchd .profile .bashrc" }, { "answer_id": 164204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": ".profile .bash_profile .bash_profile .profile" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24109/" ]
158,392
<p>I'm currently designing a brand new database. In school, we always learned to put a primary key in each table.</p> <p>I read a lot of articles/discussions/newsgroups posts saying that it's better to use unique constraint (aka unique index for some db) instead of PK.</p> <p>What's your point of view?</p>
[ { "answer_id": 158491, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 0, "selected": false, "text": "timestamp" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
158,431
<p>I was wondering if it is possible to not attach Excel sheet if it is empty, and maybe write a different comment in the email if empty.</p> <p>When I go to report delivery options, there's no such configuration.</p> <p><strong>Edit</strong>: I'm running SQL Server Reporting Services 2005.</p> <p>Some possible workarounds as mentioned below:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms152934(SQL.90).aspx" rel="nofollow noreferrer">MSDN: Reporting Services Extensions</a></p> <p><a href="http://technet.microsoft.com/es-es/library/microsoft.reportingservices.reportrendering.table.norows(SQL.90).aspx" rel="nofollow noreferrer">NoRows and NoRowsMessage properties</a></p> <p>I should look into these things.</p>
[ { "answer_id": 218626, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 0, "selected": false, "text": "SELECT * FROM REPORT_SUBSCRIBERS WHERE EXISTS (SELECT QUERY_FROM_YOUR_REPORT)\n SELECT 'person1@domain.com; person2@domain.com' AS RECIPIENTS,\nCASE WHEN EXISTS (REPORT_QUERY) THEN 'TRUE' ELSE 'FALSE' END AS INCLUDE_REPORT,\nCASE WHEN EXISTS (REPORT_QUERY) THEN 'The report is attached' ELSE 'There was no data in this report' END AS COMMENT\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5704/" ]
158,436
<p>I have written a small ASP.NET application. It runs fine when running it with the small IIS installation that comes with Visual Studio 2005, but not when trying with IIS. I created the virtual directory in IIS where the application is located (done it though both IIS and VS 2005), but it does not work. In the beginning I thought it might be caused by the web.config file, but after a few tests, I think that the problem lies with IIS (not certain about it).</p> <p>Some of the errors that I get are</p> <blockquote> <p>Unable to start debugging on the web server. The underlying connection was closed: An unexpected error ocurred on a receiver. Click help for more information</p> </blockquote> <p>Can anybody give me a suggestion of what to try next?</p>
[ { "answer_id": 19309204, "author": "Pramesh", "author_id": 2868435, "author_profile": "https://Stackoverflow.com/users/2868435", "pm_score": 1, "selected": false, "text": "%windir%\\Microsoft.NET\\Framework64\\v4.0.30319\\aspnet_regiis.exe -i\n %windir%\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_regiis.exe -i\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
158,438
<p>I have a website where we use Javascript to submit the login form. On Firefox it prompts the user to remember their password, when they login, but on IE7 it doesn't.</p> <p>After doing some research it looks like the user is only prompted in IE7 when the form is submitted via a Submit control. I've created some sample html to prove this is the case.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test autocomplete&lt;/title&gt; &lt;script type="text/javascript"&gt; function submitForm() { return document.forms[0].submit(); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="GET" action="test_autocomplete.html"&gt; &lt;input type="text" id="username" name="username"&gt; &lt;br&gt; &lt;input type="password" id="password" name="password"/&gt; &lt;br&gt; &lt;a href="javascript:submitForm();"&gt;Submit&lt;/a&gt; &lt;br&gt; &lt;input type="submit"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The href link doesn't get the prompt but the submit button will in IE7. Both work in Firefox.</p> <p>I can't get the style of my site to look the same with a submit button, Does anyone know how to get the remember password prompt to show up when submitting via Javascript?</p>
[ { "answer_id": 158550, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "<html>\n <head>\n <title>test autocomplete</title>\n <script type=\"text/javascript\">\n function submitForm()\n {\n return true;\n }\n </script>\n </head>\n <body>\n <form method=\"GET\" action=\"test_autocomplete.html\" onsubmit=\"return submitForm();\">\n <input type=\"text\" id=\"username\" name=\"username\">\n <br>\n <input type=\"password\" id=\"password\" name=\"password\"/>\n <br>\n <a href=\"#\" onclick=\"document.getElementById('FORMBUTTON').click();\">Submit</a>\n <br>\n <input id=\"FORMBUTTON\" type=\"submit\"/>\n </form>\n </body>\n</html>\n" }, { "answer_id": 159311, "author": "Adz", "author_id": 24232, "author_profile": "https://Stackoverflow.com/users/24232", "pm_score": 1, "selected": false, "text": "<button type=\"submit\">Submit</button>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869/" ]
158,457
<p>So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this?</p> <p>My first idea is to simply open a file and write to it.</p> <pre><code>FILE* log = fopen("logfile.log", "w"); /* daemon works...needs to write to log */ fprintf(log, "foo%s\n", (char*)bar); /* ...all done, close the file */ fclose(log); </code></pre> <p>Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux?</p>
[ { "answer_id": 158471, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "man 3 syslog\n #include <stdio.h>\n#include <unistd.h>\n#include <syslog.h>\n\nint main(void) {\n\n openlog(\"slog\", LOG_PID|LOG_CONS, LOG_USER);\n syslog(LOG_INFO, \"A different kind of Hello world ... \");\n closelog();\n\n return 0;\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12926/" ]
158,460
<p>I am looking for a C# library for getting files or directory from a directory using a complex pattern like the one used in Ant:</p> <ul> <li><code>dir1/dir2/**/SVN/*</code> --> Matches all files in SVN directories that are located anywhere in the directory tree under dir1/dir2</li> <li><code>**/test/**</code> --> Matches all files that have a test element in their path, including test as a filename.</li> <li>...</li> </ul> <p>Do I need to code it myself? extract what I want from NAnt? Or this library exists and my google skill sucks.</p> <p><code>Directory.GetFiles(String path, String searchPattern)</code> doesn't handle directory pattern and <a href="http://www.codeplex.com/FileDirectoryPath" rel="nofollow noreferrer">NDepend.Helpers.FileDirectoryPath</a> neither (it's a great library for path manipulation by the way)</p>
[ { "answer_id": 171183, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": -1, "selected": false, "text": "* -> [^\\/]*\n** -> .*\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12248/" ]
158,474
<p>Supposedly, it is possible to get this from Google Maps or some such service. (US addresses only is not good enough.)</p>
[ { "answer_id": 15645608, "author": "Nate Wildermuth", "author_id": 1535103, "author_profile": "https://Stackoverflow.com/users/1535103", "pm_score": 2, "selected": false, "text": "function get_lat_long($address) {\n $res = drupal_http_request('http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false');\n return json_decode($res->data)->results[0]->geometry->location;\n}\n" }, { "answer_id": 30210457, "author": "Selva", "author_id": 2604954, "author_profile": "https://Stackoverflow.com/users/2604954", "pm_score": 2, "selected": false, "text": "# CODE TO GET THE LATITUDE AND LONGITUDE OF A STREET ADDRESS WITH GOOGLE API\naddr <- '6th Main Rd, New Thippasandra, Bengaluru, Karnataka' # set your address here\nurl = paste('http://maps.google.com/maps/api/geocode/xml?address=', addr,'&sensor=false',sep='') # construct the URL\ndoc = xmlTreeParse(url) \nroot = xmlRoot(doc) \nlat = xmlValue(root[['result']][['geometry']][['location']][['lat']]) \nlong = xmlValue(root[['result']][['geometry']][['location']][['lng']]) \nlat\n[1] \"12.9725020\"\nlong\n[1] \"77.6510688\"\n" }, { "answer_id": 31545930, "author": "Suman", "author_id": 1203129, "author_profile": "https://Stackoverflow.com/users/1203129", "pm_score": 2, "selected": false, "text": "import json, urllib, urllib2\n\naddress = \"Your address, New York, NY\"\n\nencodedAddress = urllib.quote_plus(address)\ndata = urllib2.urlopen(\"http://maps.googleapis.com/maps/api/geocode/json?address=\" + encodedAddress + '&sensor=false').read()\nlocation = json.loads(data)['results'][0]['geometry']['location']\nlat = location['lat']\nlng = location['lng']\nprint lat, lng\n" }, { "answer_id": 40718263, "author": "Adiii", "author_id": 3288890, "author_profile": "https://Stackoverflow.com/users/3288890", "pm_score": 1, "selected": false, "text": "var geocoder = new google.maps.Geocoder();\nvar address = \"kohat\";\ngeocoder.geocode( { 'address': address}, function(results, status) {\nvar latitude = results[0].geometry.location.lat();\nvar longitude = results[0].geometry.location.lng();\nalert(latitude+\" and \"+longitude);\n } \n});\n" }, { "answer_id": 54458368, "author": "Parthiban Soundram", "author_id": 8912663, "author_profile": "https://Stackoverflow.com/users/8912663", "pm_score": 1, "selected": false, "text": "from geopy.geocoders import Nominatim\n\ngeolocator = Nominatim(user_agent=\"your-app-id\")\n\nlocation = geolocator.geocode(\"Your required address \")\n\nif location:\n print('\\n Nominatim ADDRESS :',location.address)\n print('\\n Nominatim LATLANG :',(location.latitude, location.longitude))\n print('\\n Nominatim FULL RESPONSE :',location.raw)\nelse:\n print('Cannot Find')\n import geocoder\ng = geocoder.mapquest(\"Your required address \",key='your-api-key')\n\nfor result in g:\n # print(result.address, result.latlng)\n print('\\n mapquest ADDRESS :',result.address,result.city,result.state,result.country)\n print('\\n mapquest LATLANG :', result.latlng)\n print('\\n mapquest FULL RESPONSE :',result.raw)\n" }, { "answer_id": 54800284, "author": "Mukesh Jakhar", "author_id": 7408993, "author_profile": "https://Stackoverflow.com/users/7408993", "pm_score": 0, "selected": false, "text": "<form>\n <input type=\"text\" name=\"address\" id=\"address\" style=\"width:100%;\">\n <input type=\"button\" onclick=\"return getLatLong()\" value=\"Get Lat Long\" />\n</form>\n<div id=\"latlong\">\n <p>Latitude: <input size=\"20\" type=\"text\" id=\"latbox\" name=\"lat\" ></p>\n <p>Longitude: <input size=\"20\" type=\"text\" id=\"lngbox\" name=\"lng\" ></p>\n</div>\n <script src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap\" async defer></script>\n\n <script>\n function getLatLong()\n {\n var address = document.getElementById(\"address\").value;\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n var latitude = results[0].geometry.location.lat();\n document.getElementById(\"latbox\").value=latitude;\n var longitude = results[0].geometry.location.lng();\n document.getElementById(\"lngbox\").value=longitude;\n } \n });\n }\n </script>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18651/" ]
158,479
<p>I have a PDF file, which contains data that we need to import into a database. The files seem to be pdf scans of printed alphanumeric text. Looks like 10 pt. Times New Roman. </p> <p>Are there any tools or components that can will allow me to recognize and parse this text?</p>
[ { "answer_id": 158824, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 6, "selected": true, "text": "' lifted from http://en.wikipedia.org/wiki/Microsoft_Office_Document_Imaging\nDim inputFile As String = \"C:\\test\\multipage.tif\"\nDim strRecText As String = \"\"\nDim Doc1 As MODI.Document\n\nDoc1 = New MODI.Document\nDoc1.Create(inputFile)\nDoc1.OCR() ' this will ocr all pages of a multi-page tiff file\nDoc1.Save() ' this will save the deskewed reoriented images, and the OCR text, back to the inputFile\n\nFor imageCounter As Integer = 0 To (Doc1.Images.Count - 1) ' work your way through each page of results\n strRecText &= Doc1.Images(imageCounter).Layout.Text ' this puts the ocr results into a string\nNext\n\nFile.AppendAllText(\"C:\\test\\testmodi.txt\", strRecText) ' write the OCR file out to disk\n\nDoc1.Close() ' clean up\nDoc1 = Nothing\n" }, { "answer_id": 315602, "author": "MarlonRibunal", "author_id": 10385, "author_profile": "https://Stackoverflow.com/users/10385", "pm_score": 3, "selected": false, "text": "/* Marlon Ribunal\n * Convert PDF To Text\n * *******************/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Drawing.Printing;\nusing System.IO;\nusing System.Text;\nusing System.ComponentModel.Design;\nusing System.ComponentModel;\nusing org.pdfbox.pdmodel;\nusing org.pdfbox.util;\n\nnamespace MarlonRibunal.iPdfToText\n{\n public partial class MainForm : Form\n {\n public MainForm()\n {\n InitializeComponent(); \n }\n\n void Button1Click(object sender, EventArgs e) \n { \n PDDocument doc = PDDocument.load(\"C:\\\\pdftoText\\\\myPdfTest.pdf\");\n PDFTextStripper stripper = new PDFTextStripper();\n richTextBox1.Text=(stripper.getText(doc));\n }\n\n }\n}\n" }, { "answer_id": 50221289, "author": "user1917528", "author_id": 1917528, "author_profile": "https://Stackoverflow.com/users/1917528", "pm_score": 0, "selected": false, "text": "using XpdfNet;\n\nvar pdfHelper = new XpdfHelper();\n\nstring content = pdfHelper.ToText(\"./pathToFile.pdf\");\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24204/" ]
158,482
<p>This question is based on <a href="https://stackoverflow.com/questions/150514/custom-method-in-model-to-return-an-object">another question of mine</a>(thankfully answered).</p> <p>So if in a model I have this:</p> <pre><code>def self.find_extended person = Person.find(:first) complete_name = person.firstname + ', ' + person.lastname return person end </code></pre> <p>How can I inject complete name in the person object so in my controller/view I can access it by person.complete_name?</p> <p>Thank you for your time,<br> Silviu</p>
[ { "answer_id": 158504, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 1, "selected": false, "text": "attr_accessor :complete_name\n person.complete_name= person.firstname + ', ' + person.lastname" }, { "answer_id": 158526, "author": "IDBD", "author_id": 7403, "author_profile": "https://Stackoverflow.com/users/7403", "pm_score": 4, "selected": true, "text": "def complete_name\n firstname + ', ' + lastname\nend\n" }, { "answer_id": 161103, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "def complete_name\n \"#{firstname}, #{lastname}\"\nend\n String#+ firstname 'John' lastname 'Doe' 'John' 'Doe' 'John, ' 'John, Doe' #{} 'John, '" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3718/" ]
158,492
<p>How do I perform a network login, to access a shared driver for instance, programmatically in c#? The same can be achieved by either attempting to open a share through the explorer, or by the net use shell command.</p>
[ { "answer_id": 158530, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 4, "selected": true, "text": "[DllImport(\"mpr.dll\")]\n public static extern int WNetAddConnection2A\n (\n [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,\n [MarshalAs(UnmanagedType.LPStr)] string lpPassword,\n [MarshalAs(UnmanagedType.LPStr)] string UserName, int dwFlags\n );\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13855/" ]
158,502
<p>I am trying to use the JQuery UI datepicker (latest stable version 1.5.2) on an IE6 website. But I am having the usual problems with combo boxes (selects) on IE6 where they float above other controls. I have tried adding the bgIframe plugin after declaring the datepicker with no luck.</p> <p>My guess is that the .ui-datepicker-div to which I am attaching the bgIframe doesn't exist until the calendar is shown.</p> <p>I am wondering if I can put the .bgIframe() command directly into the datepicker .js file and if so, where? (the similar control by kelvin Luck uses this approach)</p> <p>Current code</p> <p>$(".DateItem").datepicker({<br> showOn:"button",<br> ... etc ...<br> });<br> $(".ui-datepicker-div").bgIframe();</p>
[ { "answer_id": 173829, "author": "Steve Davies", "author_id": 24209, "author_profile": "https://Stackoverflow.com/users/24209", "pm_score": 0, "selected": false, "text": "if ($.browser.msie && parseInt($.browser.version, 10) < 7) // fix IE < 7 select problems\n$('iframe.ui-datepicker-cover').css({ width: inst.dpDiv.width() + 4, height: inst.dpDiv.height() + 4 });\n inst.dpDiv.empty().append(this._generateHTML(inst)).\nfind('iframe.ui-datepicker-cover').\ncss({ width: dims.width, height: dims.height });\n //if ($.browser.msie && parseInt($.browser.version, 10) < 7) // fix IE < 7 select problems\n// $('iframe.ui-datepicker-cover').css({ width: inst.dpDiv.width() + 4, height: inst.dpDiv.height() + 4 });\n\ninst.dpDiv.empty().append(this._generateHTML(inst))//. <=== note the // before the .\n//find('iframe.ui-datepicker-cover').\n//css({ width: dims.width, height: dims.height });\n" }, { "answer_id": 2404429, "author": "Ivan", "author_id": 289134, "author_profile": "https://Stackoverflow.com/users/289134", "pm_score": 0, "selected": false, "text": "bgiframe(); onBeforeShow() $('#date').DatePicker({\nformat:'Y/m/d',\ndate: $('#date').val(),\ncurrent: $('#date').val(),\nposition: 'r',\nonBeforeShow: function(){\n $('#date').DatePickerSetDate($('#date').val(), true);\n $('.datepickerContainer').bgiframe();\n},\nonChange: function(formated, dates){\n $('#date').val(formated);\n $('#date').DatePickerHide();\n}\n});\n" }, { "answer_id": 4034275, "author": "Maru", "author_id": 488929, "author_profile": "https://Stackoverflow.com/users/488929", "pm_score": 1, "selected": false, "text": "$(\".DateItem\").datepicker({\n showOn:\"button\",\n beforeShow:function(){\n $('#ui-datepicker-div').bgiframe();\n },\n ... etc ...\n});\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24209/" ]
158,508
<p>I have some formulas in my reports, and to prevent divsion by zero I do like this in the expression field:</p> <p>=IIF(Fields!F1.Value &lt;> 0, Fields!F2.Value/Fields!F1.Value, 0)</p> <p>This normally works fine, but when both F1 and F2 are zero, I get "#Error" in the report, and I get this warning: "The Value expression for the textbox ‘textbox196’ contains an error: Attempted to divide by zero."</p> <p>Why is that?</p>
[ { "answer_id": 158527, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "Fields!F2.Value/Fields!F1.Value Fields!F1.Value <> 0" }, { "answer_id": 159003, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 3, "selected": true, "text": "=IIF(Fields!F1.Value <> 0, Fields!F2.Value / \n IIF(Fields!F1.Value <> 0, Fields!F1.Value, 42), 0)\n" }, { "answer_id": 8324438, "author": "belidzs", "author_id": 733440, "author_profile": "https://Stackoverflow.com/users/733440", "pm_score": 0, "selected": false, "text": "if Fields!F1.Value <> 0 \nthen \nFields!F2.Value/Fields!F1.Value\nelse 0\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3308/" ]
158,514
<p>According to <a href="http://git-scm.com/docs/git-svn" rel="noreferrer">the manual</a>, <code>git dcommit</code> “will create a revision in SVN for each commit in git.” But is there a way to avoid multiple Subversion revisions? That is, to have git merge all changes prior to performing the <code>svn commit</code>?</p>
[ { "answer_id": 158570, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 6, "selected": true, "text": "git-merge --squash" }, { "answer_id": 163719, "author": "andy", "author_id": 21482, "author_profile": "https://Stackoverflow.com/users/21482", "pm_score": 5, "selected": false, "text": "git rebase -i git rebase -i <commit ID> git rebase -i HEAD~5 git rebase -i svn/trunk git rebase -i" }, { "answer_id": 365725, "author": "cbowns", "author_id": 774, "author_profile": "https://Stackoverflow.com/users/774", "pm_score": 3, "selected": false, "text": "git rebase -i" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446328/" ]
158,519
<p>I need advice on how to handle relatively large set of flags in my SQL2k8 table.</p> <p>Two question, bear with me please :)</p> <p>Let's say I have 20 flags I'd like to store for one record.</p> <p>For example:</p> <p>CanRead = 0x1 CanWrite = 0x2 CanModify = 0x4 ... and so on to the final flag 2^20</p> <p>Now, if i set the following combination of one record: Permissions = CanRead | CanWrite</p> <p>I can easily check whether that record has required permission by doing WHERE (Permissions &amp; CanRead) = CanRead</p> <p>That works.</p> <p>But, I would also like to retrieve all records that can either write OR modify.</p> <p>If I issue WHERE (Permissions &amp; ( CanWrite | CanModify )) = (CanWrite | CanModify) i obviously won't get my record that has permissions set to CanRead | CanWrite</p> <p>In other words, how can I find records that match ANY of the flags in my mask that i'm sending to the procedure?</p> <p>Second question, how performant is in in SQL 2008? Would it actually be better to create 20 bit fields?</p> <p>Thanks for your help</p>
[ { "answer_id": 158560, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "WHERE (Permissions & CanWrite) = CanWrite \nOR (Permissions & CanModify) = CanModify\n" }, { "answer_id": 158596, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 1, "selected": false, "text": " WHERE (Permissions & ( CanWrite | CanModify )) > 0\n" }, { "answer_id": 158608, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 2, "selected": false, "text": "WHERE (Permissions & ( CanWrite | CanModify )) > 0\n" }, { "answer_id": 158613, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": false, "text": "WHERE CanRead AND (CanWrite OR CanModify)\n" }, { "answer_id": 158685, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 4, "selected": false, "text": "Declare @Temp Table(Permission Int, PermissionType VarChar(20))\n\nDeclare @CanRead Int\nDeclare @CanWrite Int\nDeclare @CanModify Int\n\nSelect @CanRead = 1, @CanWrite = 2, @CanModify = 4\n\nInsert Into @Temp Values(@CanRead | @CanWrite, 'Read,write')\nInsert Into @Temp Values(@CanRead, 'Read')\nInsert Into @Temp Values(@CanWrite, 'Write')\nInsert Into @Temp Values(@CanModify | @CanWrite, 'Modify, write')\nInsert Into @Temp Values(@CanModify, 'Modify')\n\nSelect * \nFrom @Temp \nWhere Permission & (@CanRead | @CanWrite) > 0\n\nSelect * \nFrom @Temp \nWhere Permission & (@CanRead | @CanModify) > 0\n Modify Write Read Permissions\n------ ----- ---- -----------\n 0 0 0 Nothing\n 0 0 1 Read\n 0 1 0 Write\n 0 1 1 Read, Write\n 1 0 0 Modify\n 1 0 1 Modify, Read\n 1 1 0 Modify, Write\n 1 1 1 Modify, Write, Read\n 001 (Row from table)\n& 101 (Permissions to test)\n------\n 001 (result is greater than 0)\n 010 (Row from table)\n& 101 (Permission to test)\n------\n 000 (result = 0)\n 111 (Row from table)\n& 101 (Permission to test)\n------\n 101 (result is greater than 0)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
158,520
<p>In PowerShell, even if it's possible to know if a drive is a network drive: see <a href="https://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or">In PowerShell, how can I determine if the current drive is a networked drive or not?</a></p> <p>When I try to get the "root" of the drive, I get back the drive letter.</p> <p>The setup: MS-Dos "net use" shows that H: is really a mapped network drive:</p> <pre><code>New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. </code></pre> <p>Get-PSDrive tells us that the Root is H:</p> <pre><code>PS:24 H:\temp &gt;get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp </code></pre> <p>and using system.io.driveinfo does not give us a complete answer:</p> <pre><code>PS:13 H:\ &gt;$x = new-object system.io.driveinfo("h:\") PS:14 H:\ &gt;$x.DriveType Network PS:15 H:\ &gt;$x.RootDirectory Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 29/09/2008 16:45 h:\ </code></pre> <p>Any idea of how to get that info?</p> <p>Thanks</p>
[ { "answer_id": 158531, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": true, "text": "Get-WMIObject -query \"Select ProviderName From Win32_LogicalDisk Where DeviceID='H:'\"\n" }, { "answer_id": 36550346, "author": "Bozidar", "author_id": 6188479, "author_profile": "https://Stackoverflow.com/users/6188479", "pm_score": 3, "selected": false, "text": "(Get-PSDrive h).DisplayRoot" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
158,521
<p>I have a working LINQ to SQL model. I want to be able to use the same model but with a connection to a DataSet object, instead of SQL Server.</p> <p>I need to be able to query the model, modify fields, as well as do insert and delete operations. Is there an easy way to accomplish this?</p> <p>I noticed <a href="https://stackoverflow.com/questions/142762/is-there-a-datacontext-in-linq-to-entities-not-linq-to-sql">another question</a> mentions a similar scenario, but I'm not sure if this applies to my question.</p>
[ { "answer_id": 158545, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "DataContext.GetChangeSet()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347/" ]
158,539
<p>break line tag is not working in firefox, neither in chrome. When i see the source of my page i get: </p> <pre><code>&lt;p&gt;Zugang zu Testaccount:&lt;/br&gt;&lt;/br&gt;peter petrelli &lt;/br&gt;&lt;/br&gt;sein Standardpwd.&lt;/br&gt;&lt;/br&gt;peter.heroes.com&lt;/p&gt; </code></pre> <p>However when i do view selected source, i get: </p> <pre><code>&lt;p&gt;Zugang zu Testaccount: peter petrelli sein Standardpwd. peter.heroes.com&lt;/p&gt; </code></pre> <p>It seems firefox is filtering break line tags out. </p> <p>It works in IE7 fine. </p>
[ { "answer_id": 158549, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 7, "selected": true, "text": "<br /> </br>" }, { "answer_id": 158551, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 4, "selected": false, "text": "<br/>\n" }, { "answer_id": 158553, "author": "Dan", "author_id": 9494, "author_profile": "https://Stackoverflow.com/users/9494", "pm_score": 2, "selected": false, "text": "</br> <br />" }, { "answer_id": 158554, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 4, "selected": false, "text": "<br> <br /> </br>" }, { "answer_id": 158559, "author": "Adam Kinney", "author_id": 1973, "author_profile": "https://Stackoverflow.com/users/1973", "pm_score": 3, "selected": false, "text": "<br> </br> <br />" }, { "answer_id": 158610, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "<html>\n<head>\n<title></title>\n</head>\n<body>\n<p>\n<br />\n</p>\n</body>\n</html>\n <br />\n" }, { "answer_id": 26674004, "author": "Kunal Kumar", "author_id": 2769462, "author_profile": "https://Stackoverflow.com/users/2769462", "pm_score": 4, "selected": false, "text": "<br/> <br/> <div class=\"clear\"></div>\n .clear {\n clear: both;\n}\n" }, { "answer_id": 56392674, "author": "Thushara Buddhika", "author_id": 10517232, "author_profile": "https://Stackoverflow.com/users/10517232", "pm_score": 0, "selected": false, "text": "escapeXml=\"false\"" }, { "answer_id": 63896730, "author": "Arun Chandra", "author_id": 8494973, "author_profile": "https://Stackoverflow.com/users/8494973", "pm_score": -1, "selected": false, "text": "<br /> <br> <p></p> </p>" }, { "answer_id": 67572519, "author": "UserName Name", "author_id": 15825896, "author_profile": "https://Stackoverflow.com/users/15825896", "pm_score": 0, "selected": false, "text": "</br> <br> <br />. <!doctype html>\n<html>\n <head>\n <title></title>\n </head>\n <body>\n <p>\n Some text... </br>\n Some more text...\n </p>\n More content...\n </body>\n</html>\n <!doctype html>\n<html>\n <head>\n <title></title>\n </head>\n <body>\n <p>\n Some text... <br>\n Some more text... <br />\n </p>\n More content...\n </body>\n</html>\n" }, { "answer_id": 73467556, "author": "Ramratan Gupta", "author_id": 1589444, "author_profile": "https://Stackoverflow.com/users/1589444", "pm_score": 0, "selected": false, "text": "CSS display: none; <br>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
158,544
<p>Can you do a better code? I need to check/uncheck all childs according to parent and when an child is checked, check parent, when all childs are unchecked uncheck parent.</p> <pre><code> $(".parent").children("input").click(function() { $(this).parent().siblings("input").attr("checked", this.checked); }); $(".parent").siblings("input").click(function() { if (this.checked) { $(this).siblings("div").children("input").attr("checked", true); return; } var childs = $(this).siblings("div").siblings("input"); for (i = 0; i &lt; childs.length; i++) { if ($(childs.get(i)).attr("checked")) return; } $(this).parent().children("div").children("input").attr("checked", false); }); </code></pre>
[ { "answer_id": 159786, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 2, "selected": true, "text": "$(\".parent\").children(\"input\").click(function() {\n $(this).parent().siblings(\"input\").attr(\"checked\", this.checked);\n});\n\n$(\".parent\").siblings(\"input\").click(function() {\n $(this).siblings(\"div\").children(\"input\").attr(\"checked\",\n this.checked || $(this).siblings(\"input[checked]\").length>0\n );\n});\n" }, { "answer_id": 160624, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<div class=\"parent\">\n <input type=\"checkbox\" />\n <div>\n <input type=\"checkbox\" />\n <input type=\"checkbox\" />\n </div>\n <input type=\"checkbox\" />\n <div>\n <input type=\"checkbox\" />\n <input type=\"checkbox\" />\n </div>\n</div>\n $(\"input[type='checkbox']\").click(function() {\n // turn on or off all descendants.\n $(this) // get this checkbox\n // get the div directly after it\n .next('div')\n // get ALL the inputs in that div (not just first level children)\n .find(\"input[type='checkbox']\")\n .attr(\"checked\", this.checked)\n ;\n\n // now check if we have to turn the parent on or off.\n $(this)\n .parent() // this will be the div\n .prev('input[type=\"checkbox\"]') // this is the input\n .attr(\n \"checked\", // set checked to true if...\n this.checked // this one is checked, or...\n || $(this).siblings(\"input[type='checkbox'][checked]\").length > 0\n // any of the siblings are checked.\n )\n ;\n});\n" }, { "answer_id": 3136243, "author": "bulkhead", "author_id": 440455, "author_profile": "https://Stackoverflow.com/users/440455", "pm_score": 0, "selected": false, "text": "$(this) \n .next('div')\n .find(\"input[type='checkbox']\")\n .attr(\"checked\", this.checked)\n;\n}\n\n\n$(this)\n .parent() \n .prev('input[type=\"checkbox\"]') \n .attr(\"checked\", this.checked || $(this).siblings(\"input[type='checkbox'][checked]\").length > 0\n\n )\n;\n" }, { "answer_id": 17473348, "author": "pirs", "author_id": 2550964, "author_profile": "https://Stackoverflow.com/users/2550964", "pm_score": 0, "selected": false, "text": "$('.parent').click(function(){\n checkBox = $(this).find('input[type=checkbox]');\n checkBox.prop(\"checked\", !checkBox.prop(\"checked\")); // inverse selection\n});\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683/" ]
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.</p> <p>What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?</p>
[ { "answer_id": 158753, "author": "Rodrigo Queiro", "author_id": 20330, "author_profile": "https://Stackoverflow.com/users/20330", "pm_score": 5, "selected": true, "text": "import dictionary\n\ndictionary.words[whatever]\n words = {}\n\n# read file and add to 'words'\n" }, { "answer_id": 159441, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 1, "selected": false, "text": "a = read_dict_from_file()\nb = a\n a b def main(args):\n run_initialization_stuff()\n dictionary = read_dictionary_from_file()\n solvers = [ Solver(class=x, dictionary=dictionary) for x in len(number_of_solvers) ]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24208/" ]
158,557
<p>I've seen that it's possible to get the latitude and longitude (geocoding, like in <a href="http://code.google.com/apis/maps/documentation/services.html#Geocoding" rel="nofollow noreferrer">Google Maps API</a>) from a street address, but is it possible to do the reverse and get the street address when you know what the lat/long already is?</p> <p>The application would be an iPhone app (and why the app already knows lat/long), so anything from a web service to an iPhone API would work.</p>
[ { "answer_id": 235382, "author": "Mika Tuupola", "author_id": 24433, "author_profile": "https://Stackoverflow.com/users/24433", "pm_score": 4, "selected": false, "text": "http://maps.google.com/maps/geo?output=xml&oe=utf-8&ll=LAT,LON&key=API_KEY\n" }, { "answer_id": 2883694, "author": "Dave DeLong", "author_id": 115730, "author_profile": "https://Stackoverflow.com/users/115730", "pm_score": 2, "selected": false, "text": "MKReverseGeocoder" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5548/" ]
158,568
<p>I have a temporary file with data that's returned as part of a SOAP response via a MTOM binary attachment. I would like to trash it as soon as the method call "ends" (i.e., finishes transferring). What's the best way for me to do this? The best way I can figure out how to do this is to delete them when the session is destroyed, but I'm not sure if there's a more 'immediate' way to do this.</p> <p>FYI, I'm NOT using Axis, I'm using jax-ws, if that matters.</p> <p>UPDATE: I'm not sure the answerers are really understanding the issue. I know how to delete a file in java. My problem is this:</p> <pre><code>@javax.jws.WebService public class MyWebService { ... @javax.jws.WebMethod public MyFileResult getSomeObject() { File mytempfile = new File("tempfile.txt"); MyFileResult result = new MyFileResult(); result.setFile(mytempfile); // sets mytempfile as MTOM attachment // mytempfile.delete() iS WRONG // can't delete mytempfile because it hasn't been returned to the web service client // yet. So how do I remove it? return result; } } </code></pre>
[ { "answer_id": 158597, "author": "Steven M. Cherry", "author_id": 24193, "author_profile": "https://Stackoverflow.com/users/24193", "pm_score": 0, "selected": false, "text": "File script = File.createTempFile(\"temp\", \".tmp\", new File(\"./\"));\n... use the file ...\nscript.delete(); // delete when done.\n" }, { "answer_id": 981443, "author": "Chris Dail", "author_id": 5077, "author_profile": "https://Stackoverflow.com/users/5077", "pm_score": 5, "selected": true, "text": "private DataHandler handler;\n private class TemporaryFileInputStream extends FileInputStream {\n public TemporaryFileInputStream(File file) throws FileNotFoundException {\n super(file);\n }\n\n @Override\n public void close() throws IOException {\n super.close();\n file.delete();\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12979/" ]
158,574
<p>In several cases I want to add a toolbar to the top of the iPhone keyboard (as in iPhone Safari when you're navigating form elements, for example). </p> <p>Currently I am specifying the toolbar's rectangle with constants but because other elements of the interface are in flux - toolbars and nav bars at the top of the screen - every time we make a minor interface change, the toolbar goes out of alignment.</p> <p>Is there a way to programmatically determine the position of the keyboard in relation to the current view?</p>
[ { "answer_id": 158739, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": -1, "selected": false, "text": "#define KEYBOARD_HEIGHT 240 // example - can't remember the exact size\n#define TOOLBAR_HEIGHT 30\n\ntoolBarRect.origin.y = viewRect.size.height - KEYBOARD_HEIGHT - TOOLBAR_HEIGHT;\n\n// move toolbar either directly or with an animation\n keyboardHeight" }, { "answer_id": 159048, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 5, "selected": false, "text": "UIKeyboardWillShowNotification UIKeyboardWillHideNotification userInfo UIKeyboardBoundsUserInfoKey UIWindow" }, { "answer_id": 395882, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];\n[nc addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil];\n[nc addObserver:self selector:@selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object:nil];\n -(void) keyboardWillShow:(NSNotification *) note\n{\n CGRect r = bar.frame, t;\n [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &t];\n r.origin.y -= t.size.height;\n bar.frame = r;\n}\n [UIView beginAnimations:nil context:NULL];\n [UIView setAnimationDuration:0.3];\n//...\n [UIView commitAnimations];\n" }, { "answer_id": 2039121, "author": "David Beck", "author_id": 198514, "author_profile": "https://Stackoverflow.com/users/198514", "pm_score": 4, "selected": false, "text": "userInfo UIKeyboardWillShowNotification - (void)keyboardWillShow:(NSNotification *)notification\n{\n [UIView beginAnimations:nil context:NULL];\n [UIView setAnimationCurve:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];\n [UIView setAnimationDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];\n\n CGRect frame = self.view.frame;\n frame.size.height -= [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size.height;\n self.view.frame = frame;\n\n [UIView commitAnimations];\n}\n UIKeyboardWillHideNotification" }, { "answer_id": 3321130, "author": "tonklon", "author_id": 382190, "author_profile": "https://Stackoverflow.com/users/382190", "pm_score": 8, "selected": true, "text": "UITextFields UITextViews inputAccessoryView" }, { "answer_id": 6022567, "author": "phi", "author_id": 289501, "author_profile": "https://Stackoverflow.com/users/289501", "pm_score": 6, "selected": false, "text": "UIToolbar *toolbar = [[[UIToolbar alloc] init] autorelease];\n[toolbar setBarStyle:UIBarStyleBlackTranslucent];\n[toolbar sizeToFit];\n\nUIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];\nUIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(resignKeyboard)];\n\nNSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];\n\n[flexButton release];\n[doneButton release];\n[toolbar setItems:itemsArray];\n\n[aTextField setInputAccessoryView:toolbar];\n -resignKeyboard -(void)resignKeyboard {\n [aTextField resignFirstResponder];\n}\n" }, { "answer_id": 27427839, "author": "Juan Sebastián López", "author_id": 4006044, "author_profile": "https://Stackoverflow.com/users/4006044", "pm_score": 0, "selected": false, "text": " - (void) keyboardToolbarSetup\n{\n if(self.keyboardToolbar==nil)\n {\n self.keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];\n\n UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@\"Cancel\" style:UIBarButtonItemStylePlain target:self action:@selector(anyAction)];\n\n UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];\n\n UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@\"Done\" style:UIBarButtonItemStyleDone target:self action:@selector(anyOtherAction)];\n\n\n NSArray *toolbarButtons = [[NSArray alloc]initWithObjects:cancelButton,extraSpace,doneButton, nil];\n\n [self.keyboardToolbar setItems:toolbarButtons];\n\n self.myTextView.inputAccessoryView=self.keyboardToolbar;\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24213/" ]
158,585
<p>I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?</p> <p>I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.</p>
[ { "answer_id": 158589, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 5, "selected": false, "text": "#include <unistd.h>\nsleep(3);//sleeps for 3 second\n" }, { "answer_id": 158602, "author": "Mathias Brossard", "author_id": 5000, "author_profile": "https://Stackoverflow.com/users/5000", "pm_score": 2, "selected": false, "text": "#include <sys/select.h>\n#include <sys/time.h>\n#include <unistd.h>`\n\nint main() {\n struct timeval t;\n t.tv_sec = 1;\n t.tv_usec = 500000;\n select(0, NULL, NULL, NULL, &t);\n}\n" }, { "answer_id": 158609, "author": "Samir Talwar", "author_id": 20856, "author_profile": "https://Stackoverflow.com/users/20856", "pm_score": 5, "selected": false, "text": "#include <unistd.h>\nusleep(3000000);\n" }, { "answer_id": 158614, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 8, "selected": true, "text": "#include<windows.h>\nSleep(milliseconds);\n #include<unistd.h>\nunsigned int microsecond = 1000000;\nusleep(3 * microsecond);//sleeps for 3 second\n sleep()" }, { "answer_id": 9747668, "author": "bames53", "author_id": 365496, "author_profile": "https://Stackoverflow.com/users/365496", "pm_score": 8, "selected": false, "text": "sleep_for sleep_until #include <chrono>\n#include <thread>\n\nint main() {\n using namespace std::this_thread; // sleep_for, sleep_until\n using namespace std::chrono; // nanoseconds, system_clock, seconds\n\n sleep_for(nanoseconds(10));\n sleep_until(system_clock::now() + seconds(1));\n}\n sleep usleep nanosleep sleep_for sleep_until chrono nanoseconds seconds #include <chrono>\n#include <thread>\n\nint main() {\n using namespace std::this_thread; // sleep_for, sleep_until\n using namespace std::chrono_literals; // ns, us, ms, s, h, etc.\n using std::chrono::system_clock;\n\n sleep_for(10ns);\n sleep_until(system_clock::now() + 1s);\n}\n" }, { "answer_id": 25807983, "author": "ARoberts", "author_id": 4034723, "author_profile": "https://Stackoverflow.com/users/4034723", "pm_score": 2, "selected": false, "text": "\"_sleep(milliseconds);\" chrono #include <chrono>\n\nusing namespace std;\n\nmain\n{\n cout << \"text\" << endl;\n _sleep(10000); // pauses for 10 seconds\n}\n" }, { "answer_id": 25808322, "author": "Jayesh Rathod", "author_id": 4034752, "author_profile": "https://Stackoverflow.com/users/4034752", "pm_score": 3, "selected": false, "text": "#include<chrono>\n#include<thread>\n\nint main(){\n std::this_thread::sleep_for(std::chrono::nanoseconds(10));\n std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::seconds(1));\n}\n" }, { "answer_id": 43478283, "author": "Abhishek Rathore", "author_id": 5438060, "author_profile": "https://Stackoverflow.com/users/5438060", "pm_score": 2, "selected": false, "text": "cout<<\"Apple\\n\";\nSleep(3000);\ncout<<\"Mango\";\n" }, { "answer_id": 59760860, "author": "Milan Donhowe", "author_id": 8638218, "author_profile": "https://Stackoverflow.com/users/8638218", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\nvoid sleep(float seconds){\n clock_t startClock = clock();\n float secondsAhead = seconds * CLOCKS_PER_SEC;\n // do nothing until the elapsed time has passed.\n while(clock() < startClock+secondsAhead);\n return;\n}\nint main(){\n\n cout << \"Next string coming up in one second!\" << endl;\n sleep(1.0);\n cout << \"Hey, what did I miss?\" << endl;\n\n return 0;\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
158,628
<p>I have a function in a native DLL defined as follows:</p> <pre><code>#include &lt;string&gt; void SetPath(string path); </code></pre> <p>I tried to put this in Microsoft's P/Invoke Interop Assistant, but it chokes on the "string" class (which I think is from MFC?).</p> <p>I have tried marshaling it as a variety of different types (C# String, char[], byte[]) but every time I either get a NotSupportedException or a Native Assembly Exception (depending on what marshaling I tried).</p> <p>As anyone ever done Native/Managed Interop where the native string class is used? Is there any way to Marshal this? Am I going to have to write my own Marshaler?</p>
[ { "answer_id": 158802, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "void SetPath(__in const WCHAR* path);\n" }, { "answer_id": 16007278, "author": "xInterop", "author_id": 2278804, "author_profile": "https://Stackoverflow.com/users/2278804", "pm_score": 0, "selected": false, "text": "std::string std::wstring public class SampleClass : IDisposable\n{ \n [DllImport(\"YourDll.dll\", EntryPoint=\"ConstructorOfYourClass\", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]\n public extern static void SampleClassConstructor(IntPtr thisObject);\n\n [DllImport(\"YourDll.dll\", EntryPoint=\"DoSomething\", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]\n public extern static void DoSomething(IntPtr thisObject);\n\n [DllImport(\"YourDll.dll\", EntryPoint=\"DoSomethingElse\", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]\n public extern static void DoSomething(IntPtr thisObject, int x);\n\n IntPtr ptr;\n\n public SampleClass(int sizeOfYourCppClass)\n {\n this.ptr = Marshal.AllocHGlobal(sizeOfYourCppClass);\n SampleClassConstructor(this.ptr); \n }\n\n public void DoSomething()\n {\n DoSomething(this.ptr);\n }\n\n public void DoSomethingElse(int x)\n {\n DoSomethingElse(this.ptr, x);\n }\n\n public void Dispose()\n {\n Marshal.FreeHGlobal(this.ptr);\n }\n}\n ICustomMarshaler" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
158,633
<p>What VBA code is required to perform an HTTP POST from an Excel spreadsheet?</p>
[ { "answer_id": 158647, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "ServerXMLHTTP MSXML" }, { "answer_id": 158657, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": true, "text": "Set objHTTP = CreateObject(\"MSXML2.ServerXMLHTTP\")\nURL = \"http://www.somedomain.com\"\nobjHTTP.Open \"POST\", URL, False\nobjHTTP.setRequestHeader \"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\"\nobjHTTP.send \"\"\n WinHttp.WinHttpRequest.5.1 MSXML2.ServerXMLHTTP" }, { "answer_id": 4617566, "author": "Seamus Abshere", "author_id": 310192, "author_profile": "https://Stackoverflow.com/users/310192", "pm_score": 6, "selected": false, "text": "With ActiveSheet.QueryTables.Add(Connection:=\"URL;http://carbon.brighterplanet.com/flights.txt\", Destination:=Range(\"A2\"))\n .PostText = \"origin_airport=MSN&destination_airport=ORD\"\n .RefreshStyle = xlOverwriteCells\n .SaveData = True\n .Refresh\nEnd With\n" }, { "answer_id": 17570180, "author": "thiscode", "author_id": 2549709, "author_profile": "https://Stackoverflow.com/users/2549709", "pm_score": 6, "selected": false, "text": "$_POST \"Content-type: application/x-www-form-urlencoded\" Set objHTTP = CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nURL = \"http://www.somedomain.com\"\nobjHTTP.Open \"POST\", URL, False\nobjHTTP.setRequestHeader \"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\"\nobjHTTP.setRequestHeader \"Content-type\", \"application/x-www-form-urlencoded\"\nobjHTTP.send \"var1=value1&var2=value2&var3=value3\"\n \"$HTTP_RAW_POST_DATA\"" }, { "answer_id": 59284862, "author": "david.q", "author_id": 10986258, "author_profile": "https://Stackoverflow.com/users/10986258", "pm_score": 4, "selected": false, "text": "Dim LoginRequest As Object\nSet LoginRequest = CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nLoginRequest.Open \"POST\", \"http://...\", False\nLoginRequest.setRequestHeader \"Content-type\", \"application/x-www-form-urlencoded\"\nLoginRequest.send (\"key1=value1&key2=value2\")\n Dim TCRequestItem As Object\nSet TCRequestItem = CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nTCRequestItem.Open \"GET\", \"http://...\", False\nTCRequestItem.setRequestHeader \"Content-Type\", \"application/xml\"\nTCRequestItem.setRequestHeader \"Accept\", \"application/xml\"\nTCRequestItem.setRequestHeader \"Authorization\", \"Bearer \" & token\nTCRequestItem.send\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
158,634
<p>Is it possible to do a cast within a LINQ query (for the compiler's sake)?</p> <p>The following code isn't terrible, but it would be nice to make it into one query:</p> <pre><code>Content content = dataStore.RootControl as Controls.Content; List&lt;TabSection&gt; tabList = (from t in content.ChildControls select t).OfType&lt;TabSection&gt;().ToList(); List&lt;Paragraph&gt; paragraphList = (from t in tabList from p in t.ChildControls select p).OfType&lt;Paragraph&gt;().ToList(); List&lt;Line&gt; parentLineList = (from p in paragraphList from pl in p.ChildControls select pl).OfType&lt;Line&gt;().ToList(); </code></pre> <p>The code continues on with a few more queries, but the gist is I have to create a List out of each query in order for the compiler to know that all of the objects in <code>content.ChildControls</code> are of type <code>TabSection</code> and all of the objects in <code>t.ChildControls</code> are of type <code>Paragraph</code>...and so on and and so forth.</p> <p>Is there a way within the LINQ query to tell the compiler that <code>t</code> in <code>from t in content.ChildControls</code> is a <code>TabSection</code>?</p>
[ { "answer_id": 158675, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 6, "selected": true, "text": "from TabSection t in content.ChildControls\n" }, { "answer_id": 158676, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 1, "selected": false, "text": "List<TabSection> tabList = (from t in content.ChildControls\n where t as TabSection != null\n select t as TabSection).ToList();\n" }, { "answer_id": 158747, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 4, "selected": false, "text": "List<Line> parentLineList1 =\n (from t in content.ChildControls.OfType<TabSection>()\n from p in t.ChildControls.OfType<Paragraph>()\n from pl in p.ChildControls.OfType<Line>()\n select pl).ToList();\n\nList<Line> parentLineList2 =\n (from TabSection t in content.ChildControls\n from Paragraph p in t.ChildControls\n from Line pl in p.ChildControls\n select pl).ToList();\n" }, { "answer_id": 159464, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "List<Line> parentLineList =\n content.ChildControls.OfType<TabSections>()\n .SelectMany(t => t.ChildControls.OfType<Paragraph>())\n .SelectMany(p => p.ChildControls.OfType<Line>())\n .ToList();\n" }, { "answer_id": 164611, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 2, "selected": false, "text": "List<TabSection> tabList = (from t in content.ChildControls\n let ts = t as TabSection\n where ts != null\n select ts).ToList();\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
158,651
<p>You do you manage the same presenter working with different repositories using the MVP pattern? </p> <p>I just have multiple constructor overloads and the presenter simply uses the one that is suitable for the scenario. </p> <pre><code>AddCustomerPresenter presenter = new AddCustomerPresenter(this,customerRepository); presenter.AddCustomer(); presenter = new AddCustomerPresenter(this,archiveRepository); presenter.Archive(); </code></pre>
[ { "answer_id": 158788, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "IRepository { /* .. */ }\nCustomerRepository : IRepository { /* .. */ }\nArchiveRepository : IRepository { /* .. */ }\n AddCustomerPresenter {\nIRepository Store {get;set;}\npublic AddCustomerPresenter(IRepository store) { /*...*/ }\n/*...*/\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
158,664
<p>I have a lot of changes in a working folder, and something screwed up trying to do an update.</p> <p>Now when I issue an 'svn cleanup' I get:</p> <pre><code>&gt;svn cleanup . svn: In directory '.' svn: Error processing command 'modify-wcprop' in '.' svn: 'MemPoolTests.cpp' is not under version control </code></pre> <p>MemPoolTests.cpp is a new file another developer added and was brought down in the update. It did not exist in my working folder before.</p> <p>Is there anything I can do to try and move forward <strong>without</strong> having to checkout a fresh copy of the repository?</p> <p><strong>Clarification:</strong> Thanks for the suggestions about moving the directory out of the way and bringing down a new copy. I know that is an option, but it is one I'd like to avoid since there are many changes nested several directories deep (this should have been a branch...)</p> <p>I'm hoping for a more aggressive way of doing the cleanup, maybe someway of forcing the file SVN is having trouble with back into a known state (and I tried deleting the working copy of it ... that didn't help).</p>
[ { "answer_id": 158723, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 4, "selected": false, "text": "cd dir_above_borked\nmv borked_dir borked_dir.bak\nsvn update borked_dir\n svn checkout -N borked_dir # Non-recursive, but deprecated\n svn checkout --depth=files borked_dir\n# 'depth' is new territory to me, but do 'svn help checkout'\n" }, { "answer_id": 219194, "author": "DanJ", "author_id": 4697, "author_profile": "https://Stackoverflow.com/users/4697", "pm_score": 3, "selected": false, "text": ".svn/props .svn/prop-base" }, { "answer_id": 256283, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": ".svn .svn/props-base" }, { "answer_id": 2206556, "author": "andrej", "author_id": 146745, "author_profile": "https://Stackoverflow.com/users/146745", "pm_score": 3, "selected": false, "text": "Filename FILEname svn rename -m \"broken filename case\" http://server/repo/FILEname http://server/repo/filename" }, { "answer_id": 4402137, "author": "Chris Wade", "author_id": 502241, "author_profile": "https://Stackoverflow.com/users/502241", "pm_score": 2, "selected": false, "text": "% svn co http://[domain]/svn/mortgages mortgages\n svn: In directory 'mortgages/trunk/images/rates'\nsvn: Can't open file 'mortgages/trunk/images/rates/.svn/tmp/text-base/Header_3_nobookmark.gif.svn-base': No such file or directory\n Header_3_noBookmark.gif Header_3_nobookmark.gif % cd mortgages/trunk/images/rates/\n% svn up\nsvn: Working copy '.' locked\nsvn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)\n svn cleanup % svn cleanup\nsvn: In directory '.'\nsvn: Error processing command 'modify-wcprop' in '.'\nsvn: 'spacer.gif' is not under version control\n spacer.gif .svn % rm *; rm -rf .svn/log; svn cleanup\n% svn up Header_3_nobookmark.gif\nA Header_3_nobookmark.gif\nUpdated to revision 1087.\n% svn mv Header_3_nobookmark.gif foo\nA foo\nD Header_3_nobookmark.gif\n% svn up\nA spacer.gif\nA Header_3_noBookmark.gif\n svn up" }, { "answer_id": 4624382, "author": "ingestado", "author_id": 566711, "author_profile": "https://Stackoverflow.com/users/566711", "pm_score": 3, "selected": false, "text": "$ ls -la .svn\n$ rm -f .svn/lock\n $ svn update\n" }, { "answer_id": 4805253, "author": "Judy K", "author_id": 590670, "author_profile": "https://Stackoverflow.com/users/590670", "pm_score": 2, "selected": false, "text": ".svn svn cleanup" }, { "answer_id": 5079953, "author": "sam", "author_id": 335362, "author_profile": "https://Stackoverflow.com/users/335362", "pm_score": 0, "selected": false, "text": "#>svn st\n! my_dir\n! my_dir\\sub_dir\n svn cleanup svn revert svn update svn resolve" }, { "answer_id": 12932077, "author": "Magentron", "author_id": 832620, "author_profile": "https://Stackoverflow.com/users/832620", "pm_score": 2, "selected": false, "text": "# Go to the parent directory\ncd dir_above_borked\n\n# Rename corrupted directory\nmv borked_dir borked_dir.bak\n\n# Checkout a fresh copy\nsvn checkout svn://... borked_dir\n\n# Copy the modified files to the fresh checkout\n# - test rsync\n# (possibly use -c to verify all content and show only actually changed files)\nrsync -nav --exclude=.svn borked_dir.bak/ borked_dir/\n\n# - If all ok, run rsync for real\n# (possibly using -c again, possibly not using -v)\nrsync -av --exclude=.svn borked_dir.bak/ borked_dir/\n" }, { "answer_id": 21189668, "author": "Siva", "author_id": 930753, "author_profile": "https://Stackoverflow.com/users/930753", "pm_score": 7, "selected": false, "text": "sqlite3 .svn/wc.db \"select * from work_queue\" sqlite3 .svn/wc.db \"delete from work_queue\"" }, { "answer_id": 27746208, "author": "Nikita Bosik", "author_id": 1192987, "author_profile": "https://Stackoverflow.com/users/1192987", "pm_score": 3, "selected": false, "text": "svn cleanup svn: E720002: Can't open file '..\\.svn\\pristine\\40\\40d53d69871f4ff622a3fbb939b6a79932dc7cd4.svn-base':\nThe system cannot find the file specified.\n svn cleanup" }, { "answer_id": 30629317, "author": "ahnbizcad", "author_id": 2951835, "author_profile": "https://Stackoverflow.com/users/2951835", "pm_score": 0, "selected": false, "text": "sudo chmod 777 -R . sudo svn update" }, { "answer_id": 41445474, "author": "el-teedee", "author_id": 912046, "author_profile": "https://Stackoverflow.com/users/912046", "pm_score": 2, "selected": false, "text": "svn cleanup ~/path/to/svn-folder/$ svn cleanup\n svn cleanup" }, { "answer_id": 49220395, "author": "Hovanes Mosoyan", "author_id": 4528341, "author_profile": "https://Stackoverflow.com/users/4528341", "pm_score": 0, "selected": false, "text": "svn-xxxxxxxx ~\\.svn\\tmp xxxxxxxx" }, { "answer_id": 70356490, "author": "iosparkletree", "author_id": 3448387, "author_profile": "https://Stackoverflow.com/users/3448387", "pm_score": 1, "selected": false, "text": ".mine .r1 .r2" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3631/" ]
158,665
<p>I want to delete all directories and subdirectories under a root directory that are contain "tmp" in their names. This should include any .svn files too. My first guess is to use </p> <pre><code>&lt;delete&gt; &lt;dirset dir="${root}"&gt; &lt;include name="**/*tmp*" /&gt; &lt;/dirset&gt; &lt;/delete&gt; </code></pre> <p>This does not seem to work as you can't nest a <code>dirset</code> in a <code>delete</code> tag.</p> <p>Is this a correct approach, or should I be doing something else?</p> <ul> <li>ant version == 1.6.5.</li> <li>java version == 1.6.0_04</li> </ul>
[ { "answer_id": 158672, "author": "Blauohr", "author_id": 22176, "author_profile": "https://Stackoverflow.com/users/22176", "pm_score": 3, "selected": false, "text": "<delete includeemptydirs=\"true\">\n <fileset dir=\"${root}\">\n <include name=\"**/*tmp*/*\" />\n </fileset>\n</delete>\n" }, { "answer_id": 159711, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 6, "selected": true, "text": "<delete includeemptydirs=\"true\">\n <fileset dir=\"${root}\" defaultexcludes=\"false\">\n <include name=\"**/*tmp*/**\" />\n </fileset>\n</delete>\n .svn defaultexcludes .* includeemptydirs **" }, { "answer_id": 2336808, "author": "XORshift", "author_id": 50558, "author_profile": "https://Stackoverflow.com/users/50558", "pm_score": 3, "selected": false, "text": "/** <delete includeemptydirs=\"true\">\n <fileset dir=\"${basedir}\" includes\"**/.settings\">\n</delete>\n <delete includeemptydirs=\"true\">\n <fileset dir=\"${basedir}\" includes\"**/.settings/**\">\n</delete>\n /** /*" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737/" ]
158,673
<p>I'd like to check if the current browser supports the onbeforeunload event. The common javascript way to do this does not seem to work:</p> <pre><code>if (window.onbeforeunload) { alert('yes'); } else { alert('no'); } </code></pre> <p>Actually, it only checks whether some handler has been attached to the event. Is there a way to detect if onbeforeunload is supported without detecting the particular browser name?</p>
[ { "answer_id": 158738, "author": "rfunduk", "author_id": 210, "author_profile": "https://Stackoverflow.com/users/210", "pm_score": -1, "selected": false, "text": "if( $.browser.msie ) {\n alert( 'no' );\n}\n $.browser.msie" }, { "answer_id": 158743, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 0, "selected": false, "text": "if(typeof window.onbeforeunload == 'function')\n\n{\nalert(\"hello functionality!\");\n}\n" }, { "answer_id": 158801, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "alert('onbeforeunload' in window);\n onbeforeunload window var supportsOnbeforeunload = false;\nfor (var prop in window) {\n if (prop === 'onbeforeunload') {\n supportsOnbeforeunload = true;\n break;\n }\n}\nalert(supportsOnbeforeunload);\n alert(typeof window.onbeforeunload != 'undefined');\n typeof window.onbeforeunload null" }, { "answer_id": 3073156, "author": "Paul McLanahan", "author_id": 107114, "author_profile": "https://Stackoverflow.com/users/107114", "pm_score": 3, "selected": false, "text": "$(window).bind('unload', function(){\n alert('unload event');\n});\n\nwindow.onbeforeunload = function(){\n $(window).unbind('unload');\n return 'beforeunload event';\n}\n unload beforeunload" }, { "answer_id": 18137334, "author": "Peter V. Mørch", "author_id": 345716, "author_profile": "https://Stackoverflow.com/users/345716", "pm_score": 3, "selected": false, "text": "beforeunload beforeunload unload beforeunload beforeunload beforeunload beforeunloadSupported =\n\"yes\" unload beforeunload localStorage localStorage isBeforeunloadSupported() (function($) {\n var field = 'beforeunloadSupported';\n if (window.localStorage &&\n window.localStorage.getItem &&\n window.localStorage.setItem &&\n ! window.localStorage.getItem(field)) {\n $(window).on('beforeunload', function () {\n window.localStorage.setItem(field, 'yes');\n });\n $(window).on('unload', function () {\n // If unload fires, and beforeunload hasn't set the field,\n // then beforeunload didn't fire and is therefore not\n // supported (cough * iPad * cough)\n if (! window.localStorage.getItem(field)) {\n window.localStorage.setItem(field, 'no');\n }\n });\n }\n window.isBeforeunloadSupported = function () {\n if (window.localStorage &&\n window.localStorage.getItem &&\n window.localStorage.getItem(field) &&\n window.localStorage.getItem(field) == \"yes\" ) {\n return true;\n } else {\n return false;\n }\n }\n})(jQuery);\n iframe src isBeforeunloadSupported()" }, { "answer_id": 26110528, "author": "thetallweeks", "author_id": 1660815, "author_profile": "https://Stackoverflow.com/users/1660815", "pm_score": -1, "selected": false, "text": "if ('onbeforeunload' in window && typeof window['onbeforeunload'] === 'function') {\n // onbeforeunload is supported\n} else {\n // maybe bind to unload as a last resort\n}\n null" }, { "answer_id": 52864989, "author": "Dan Bray", "author_id": 2452680, "author_profile": "https://Stackoverflow.com/users/2452680", "pm_score": 0, "selected": false, "text": "beforeunload var isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i);\nif (isMobile)\n{\n window.addEventListener(\"visibilitychange\", function(e)\n {\n if (document.visibilityState == 'hidden')\n {\n console.log(\"beforeunload\");\n location.reload();\n }\n });\n}\nelse\n{\n window.addEventListener(\"beforeunload\", function(e)\n {\n console.log(\"beforeunload\");\n });\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12111/" ]
158,703
<p>Scott Hanselman <a href="http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx" rel="noreferrer">says yes</a>.</p> <blockquote> <p>Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though.</p> </blockquote> <p>MSDN <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx" rel="noreferrer">says no</a>.</p> <blockquote> <p>The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.</p> </blockquote> <p>So what should I think?</p>
[ { "answer_id": 158734, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "Insert() CacheItemUpdateCallback" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
158,706
<p>I'm using the Excel interop in C# (<code>ApplicationClass</code>) and have placed the following code in my finally clause:</p> <pre><code>while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } excelSheet = null; GC.Collect(); GC.WaitForPendingFinalizers(); </code></pre> <p>Although this kind of works, the <code>Excel.exe</code> process is still in the background even after I close Excel. It is only released once my application is manually closed.</p> <p>What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of?</p>
[ { "answer_id": 158751, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 6, "selected": false, "text": "excelApp.Quit();\nMarshal.ReleaseComObject (excelWB);\nMarshal.ReleaseComObject (excelApp);\nexcelApp = null;\n" }, { "answer_id": 158752, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 10, "selected": true, "text": "Worksheet sheet = excelApp.Worksheets.Open(...);\n...\nMarshal.ReleaseComObject(sheet);\n Worksheets sheets = excelApp.Worksheets; // <-- The important part\nWorksheet sheet = sheets.Open(...);\n...\nMarshal.ReleaseComObject(sheets);\nMarshal.ReleaseComObject(sheet);\n" }, { "answer_id": 158839, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 5, "selected": false, "text": "Worksheet ws = excel.WorkBooks[1].WorkSheets[1];\n Workbooks books = excel.WorkBooks;\nWorkbook book = books[1];\nSheets sheets = book.WorkSheets;\nWorksheet ws = sheets[1];\n" }, { "answer_id": 158850, "author": "bill_the_loser", "author_id": 5239, "author_profile": "https://Stackoverflow.com/users/5239", "pm_score": 1, "selected": false, "text": "objExcel = new Excel.Application();\nobjBook = (Excel.Workbook)(objExcel.Workbooks.Add(Type.Missing));\nDoSomeStuff(objBook);\nSaveTheBook(objBook);\nobjBook.Close(false, Type.Missing, Type.Missing);\nobjExcel.Quit();\n" }, { "answer_id": 159000, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "Worksheet sheet = excelApp.Worksheets(1)\n... do something with sheet\n Worksheets sheets = null;\nWorksheet sheet = null\ntry\n{ \n sheets = excelApp.Worksheets;\n sheet = sheets(1);\n ...\n}\nfinally\n{\n if (sheets != null) Marshal.ReleaseComObject(sheets);\n if (sheet != null) Marshal.ReleaseComObject(sheet);\n}\n" }, { "answer_id": 159419, "author": "Mike Rosenblum", "author_id": 10429, "author_profile": "https://Stackoverflow.com/users/10429", "pm_score": 8, "selected": false, "text": "Marshal.FinalReleaseComObject() for each GC.Collect() GC.WaitForPendingFinalizers() xlRng xlSheet xlBook xlApp // Cleanup\nGC.Collect();\nGC.WaitForPendingFinalizers();\n\nMarshal.FinalReleaseComObject(xlRng);\nMarshal.FinalReleaseComObject(xlSheet);\n\nxlBook.Close(Type.Missing, Type.Missing, Type.Missing);\nMarshal.FinalReleaseComObject(xlBook);\n\nxlApp.Quit();\nMarshal.FinalReleaseComObject(xlApp);\n GC.Collect() GC.WaitForPendingFinalizers() GC.Collect();\nGC.WaitForPendingFinalizers();\nGC.Collect();\nGC.WaitForPendingFinalizers();\n GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.Collect()" }, { "answer_id": 269083, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " CultureInfo en_US = new System.Globalization.CultureInfo(\"en-US\"); \n System.Threading.Thread.CurrentThread.CurrentCulture = en_US;\n string filePathLocal = _applicationObject.ActiveWorkbook.Path;\n System.Threading.Thread.CurrentThread.CurrentCulture = orgCulture;\n" }, { "answer_id": 349202, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 4, "selected": false, "text": "using (AutoReleaseComObject<Application> excelApplicationWrapper = new AutoReleaseComObject<Application>(new Application()))\n{\n try\n {\n using (AutoReleaseComObject<Workbook> workbookWrapper = new AutoReleaseComObject<Workbook>(excelApplicationWrapper.ComObject.Workbooks.Open(namedRangeBase.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing)))\n {\n // do something with your workbook....\n }\n }\n finally\n {\n excelApplicationWrapper.ComObject.Quit();\n } \n}\n public class AutoReleaseComObject<T> : IDisposable\n{\n private T m_comObject;\n private bool m_armed = true;\n private bool m_disposed = false;\n\n public AutoReleaseComObject(T comObject)\n {\n Debug.Assert(comObject != null);\n m_comObject = comObject;\n }\n\n#if DEBUG\n ~AutoReleaseComObject()\n {\n // We should have been disposed using Dispose().\n Debug.WriteLine(\"Finalize being called, should have been disposed\");\n\n if (this.ComObject != null)\n {\n Debug.WriteLine(string.Format(\"ComObject was not null:{0}, name:{1}.\", this.ComObject, this.ComObjectName));\n }\n\n //Debug.Assert(false);\n }\n#endif\n\n public T ComObject\n {\n get\n {\n Debug.Assert(!m_disposed);\n return m_comObject;\n }\n }\n\n private string ComObjectName\n {\n get\n {\n if(this.ComObject is Microsoft.Office.Interop.Excel.Workbook)\n {\n return ((Microsoft.Office.Interop.Excel.Workbook)this.ComObject).Name;\n }\n\n return null;\n }\n }\n\n public void Disarm()\n {\n Debug.Assert(!m_disposed);\n m_armed = false;\n }\n\n #region IDisposable Members\n\n public void Dispose()\n {\n Dispose(true);\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n }\n\n #endregion\n\n protected virtual void Dispose(bool disposing)\n {\n if (!m_disposed)\n {\n if (m_armed)\n {\n int refcnt = 0;\n do\n {\n refcnt = System.Runtime.InteropServices.Marshal.ReleaseComObject(m_comObject);\n } while (refcnt > 0);\n\n m_comObject = default(T);\n }\n\n m_disposed = true;\n }\n }\n}\n" }, { "answer_id": 1307180, "author": "joshgo", "author_id": 160146, "author_profile": "https://Stackoverflow.com/users/160146", "pm_score": 6, "selected": false, "text": "Application.Quit() Process.Kill() public enum JobObjectInfoType\n{\n AssociateCompletionPortInformation = 7,\n BasicLimitInformation = 2,\n BasicUIRestrictions = 4,\n EndOfJobTimeInformation = 6,\n ExtendedLimitInformation = 9,\n SecurityLimitInformation = 5,\n GroupInformation = 11\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct SECURITY_ATTRIBUTES\n{\n public int nLength;\n public IntPtr lpSecurityDescriptor;\n public int bInheritHandle;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct JOBOBJECT_BASIC_LIMIT_INFORMATION\n{\n public Int64 PerProcessUserTimeLimit;\n public Int64 PerJobUserTimeLimit;\n public Int16 LimitFlags;\n public UInt32 MinimumWorkingSetSize;\n public UInt32 MaximumWorkingSetSize;\n public Int16 ActiveProcessLimit;\n public Int64 Affinity;\n public Int16 PriorityClass;\n public Int16 SchedulingClass;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct IO_COUNTERS\n{\n public UInt64 ReadOperationCount;\n public UInt64 WriteOperationCount;\n public UInt64 OtherOperationCount;\n public UInt64 ReadTransferCount;\n public UInt64 WriteTransferCount;\n public UInt64 OtherTransferCount;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct JOBOBJECT_EXTENDED_LIMIT_INFORMATION\n{\n public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;\n public IO_COUNTERS IoInfo;\n public UInt32 ProcessMemoryLimit;\n public UInt32 JobMemoryLimit;\n public UInt32 PeakProcessMemoryUsed;\n public UInt32 PeakJobMemoryUsed;\n}\n\npublic class Job : IDisposable\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Unicode)]\n static extern IntPtr CreateJobObject(object a, string lpName);\n\n [DllImport(\"kernel32.dll\")]\n static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);\n\n private IntPtr m_handle;\n private bool m_disposed = false;\n\n public Job()\n {\n m_handle = CreateJobObject(null, null);\n\n JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();\n info.LimitFlags = 0x2000;\n\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();\n extendedInfo.BasicLimitInformation = info;\n\n int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));\n IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);\n Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);\n\n if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))\n throw new Exception(string.Format(\"Unable to set information. Error: {0}\", Marshal.GetLastWin32Error()));\n }\n\n #region IDisposable Members\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n\n private void Dispose(bool disposing)\n {\n if (m_disposed)\n return;\n\n if (disposing) {}\n\n Close();\n m_disposed = true;\n }\n\n public void Close()\n {\n Win32.CloseHandle(m_handle);\n m_handle = IntPtr.Zero;\n }\n\n public bool AddProcess(IntPtr handle)\n {\n return AssignProcessToJobObject(m_handle, handle);\n }\n\n}\n info.LimitFlags = 0x2000; 0x2000 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n Excel.Application app = new Excel.ApplicationClass();\n Job job = new Job();\n uint pid = 0;\n Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);\n job.AddProcess(Process.GetProcessById((int)pid).Handle);\n" }, { "answer_id": 1577441, "author": "Mohsen Afshin", "author_id": 191148, "author_profile": "https://Stackoverflow.com/users/191148", "pm_score": 4, "selected": false, "text": "Process[] prs = Process.GetProcesses();\nList<int> excelPID = new List<int>();\nforeach (Process p in prs)\n if (p.ProcessName == \"EXCEL\")\n excelPID.Add(p.Id);\n\n.... // your job \n\nprs = Process.GetProcesses();\nforeach (Process p in prs)\n if (p.ProcessName == \"EXCEL\" && !excelPID.Contains(p.Id))\n p.Kill();\n" }, { "answer_id": 1893653, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 8, "selected": false, "text": "[DllImport(\"user32.dll\")]\nprivate static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n/// <summary> Tries to find and kill process by hWnd to the main window of the process.</summary>\n/// <param name=\"hWnd\">Handle to the main window of the process.</param>\n/// <returns>True if process was found and killed. False if process was not found by hWnd or if it could not be killed.</returns>\npublic static bool TryKillProcessByMainWindowHwnd(int hWnd)\n{\n uint processID;\n GetWindowThreadProcessId((IntPtr)hWnd, out processID);\n if(processID == 0) return false;\n try\n {\n Process.GetProcessById((int)processID).Kill();\n }\n catch (ArgumentException)\n {\n return false;\n }\n catch (Win32Exception)\n {\n return false;\n }\n catch (NotSupportedException)\n {\n return false;\n }\n catch (InvalidOperationException)\n {\n return false;\n }\n return true;\n}\n\n/// <summary> Finds and kills process by hWnd to the main window of the process.</summary>\n/// <param name=\"hWnd\">Handle to the main window of the process.</param>\n/// <exception cref=\"ArgumentException\">\n/// Thrown when process is not found by the hWnd parameter (the process is not running). \n/// The identifier of the process might be expired.\n/// </exception>\n/// <exception cref=\"Win32Exception\">See Process.Kill() exceptions documentation.</exception>\n/// <exception cref=\"NotSupportedException\">See Process.Kill() exceptions documentation.</exception>\n/// <exception cref=\"InvalidOperationException\">See Process.Kill() exceptions documentation.</exception>\npublic static void KillProcessByMainWindowHwnd(int hWnd)\n{\n uint processID;\n GetWindowThreadProcessId((IntPtr)hWnd, out processID);\n if (processID == 0)\n throw new ArgumentException(\"Process has not been found by the given main window handle.\", \"hWnd\");\n Process.GetProcessById((int)processID).Kill();\n}\n int hWnd = xl.Application.Hwnd;\n// ...\n// here we try to close Excel as usual, with xl.Quit(),\n// Marshal.FinalReleaseComObject(xl) and so on\n// ...\nTryKillProcessByMainWindowHwnd(hWnd);\n void GenerateWorkbook(...)\n{\n ApplicationClass xl;\n Workbook xlWB;\n try\n {\n xl = ...\n xlWB = xl.Workbooks.Add(...);\n ...\n }\n finally\n {\n ...\n Marshal.ReleaseComObject(xlWB)\n ...\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n void GenerateWorkbook(...)\n{\n try\n {\n GenerateWorkbookInternal(...);\n }\n finally\n {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n\nprivate void GenerateWorkbookInternal(...)\n{\n ApplicationClass xl;\n Workbook xlWB;\n try\n {\n xl = ...\n xlWB = xl.Workbooks.Add(...);\n ...\n }\n finally\n {\n ...\n Marshal.ReleaseComObject(xlWB)\n ...\n }\n}\n" }, { "answer_id": 1924284, "author": "Chris McGrath", "author_id": 234088, "author_profile": "https://Stackoverflow.com/users/234088", "pm_score": 3, "selected": false, "text": "xlStyleHeader public Excel.Style xlStyleHeader = null;\n\nprivate void CreateHeaderStyle()\n{\n Excel.Styles xlStyles = null;\n Excel.Font xlFont = null;\n Excel.Interior xlInterior = null;\n Excel.Borders xlBorders = null;\n Excel.Border xlBorderBottom = null;\n\n try\n {\n xlStyles = xlWorkbook.Styles;\n xlStyleHeader = xlStyles.Add(\"Header\", Type.Missing);\n\n // Text Format\n xlStyleHeader.NumberFormat = \"@\";\n\n // Bold\n xlFont = xlStyleHeader.Font;\n xlFont.Bold = true;\n\n // Light Gray Cell Color\n xlInterior = xlStyleHeader.Interior;\n xlInterior.Color = 12632256;\n\n // Medium Bottom border\n xlBorders = xlStyleHeader.Borders;\n xlBorderBottom = xlBorders[Excel.XlBordersIndex.xlEdgeBottom];\n xlBorderBottom.Weight = Excel.XlBorderWeight.xlMedium;\n }\n catch (Exception ex)\n {\n throw ex;\n }\n finally\n {\n Release(xlBorderBottom);\n Release(xlBorders);\n Release(xlInterior);\n Release(xlFont);\n Release(xlStyles);\n }\n}\n\nprivate void Release(object obj)\n{\n // Errors are ignored per Microsoft's suggestion for this type of function:\n // http://support.microsoft.com/default.aspx/kb/317109\n try\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);\n }\n catch { } \n}\n xlBorders[Excel.XlBordersIndex.xlEdgeBottom]" }, { "answer_id": 4236321, "author": "Colin", "author_id": 514159, "author_profile": "https://Stackoverflow.com/users/514159", "pm_score": 4, "selected": false, "text": "objExcel = new Excel.Application(); \nobjBook = (Excel.Workbook)(objExcel.Workbooks.Add(Type.Missing)); \n objBook.Close(true, Type.Missing, Type.Missing); \nobjExcel.Application.Quit();\nobjExcel.Quit(); \n" }, { "answer_id": 4366693, "author": "Grimfort", "author_id": 532305, "author_profile": "https://Stackoverflow.com/users/532305", "pm_score": 3, "selected": false, "text": "For Each objWorkBook As WorkBook in objWorkBooks 'local ref, created from ExcelApp.WorkBooks to avoid the double-dot\n objWorkBook.Close 'or whatever\n FinalReleaseComObject(objWorkBook)\n objWorkBook = Nothing\nNext \n\n'The above does not work, and this is the workaround:\n\nFor intCounter As Integer = 1 To mobjExcel_WorkBooks.Count\n Dim objTempWorkBook As Workbook = mobjExcel_WorkBooks.Item(intCounter)\n objTempWorkBook.Saved = True\n objTempWorkBook.Close(False, Type.Missing, Type.Missing)\n FinalReleaseComObject(objTempWorkBook)\n objTempWorkBook = Nothing\nNext\n" }, { "answer_id": 6395865, "author": "spiderman", "author_id": 96746, "author_profile": "https://Stackoverflow.com/users/96746", "pm_score": 2, "selected": false, "text": "app.workbooks.Close();\nThread.Sleep(500); // adjust, for me it works at around 300+\napp.Quit();\n\n...\nFinalReleaseComObject(app);\n" }, { "answer_id": 6399726, "author": "quixver", "author_id": 168236, "author_profile": "https://Stackoverflow.com/users/168236", "pm_score": -1, "selected": false, "text": "Application.Run Application.Run Application.Run" }, { "answer_id": 7263538, "author": "Dave Cousineau", "author_id": 621316, "author_profile": "https://Stackoverflow.com/users/621316", "pm_score": 4, "selected": false, "text": "null GC.Collect() Quit Quit if (!mDisposed) {\n mExcel = null;\n GC.Collect();\n mDisposed = true;\n}\n Quit GC.Collect() GC.WaitForPendingFinalizers() GC.Collect()" }, { "answer_id": 9705248, "author": "Saber", "author_id": 1262198, "author_profile": "https://Stackoverflow.com/users/1262198", "pm_score": 2, "selected": false, "text": "Word.ApplicationClass.Document.Open()" }, { "answer_id": 11870990, "author": "Ned", "author_id": 1438535, "author_profile": "https://Stackoverflow.com/users/1438535", "pm_score": 2, "selected": false, "text": "Excel.Range rng = (Excel.Range)worksheet.Cells[1, 1];\nworksheet.Paste(rng, false);\nreleaseObject(rng);\n" }, { "answer_id": 14270379, "author": "Porkbutts", "author_id": 1825250, "author_profile": "https://Stackoverflow.com/users/1825250", "pm_score": 3, "selected": false, "text": "GC.Collect() GC.WaitForPendingFinalizers() public class Test {\n\n // These instance variables must be nulled or Excel will not quit\n private Excel.Application xl;\n private Excel.Workbook book;\n\n public void DoSomething()\n {\n xl = new Excel.Application();\n xl.Visible = true;\n book = xl.Workbooks.Add(Type.Missing);\n\n // These variables are locally scoped, so we need not worry about them.\n // Notice I don't care about using two dots.\n Excel.Range rng = book.Worksheets[1].UsedRange;\n }\n\n public void CleanUp()\n {\n book = null;\n xl.Quit();\n xl = null;\n\n GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n" }, { "answer_id": 15950802, "author": "Blaz Brencic", "author_id": 1009733, "author_profile": "https://Stackoverflow.com/users/1009733", "pm_score": 1, "selected": false, "text": "GC.Collect()" }, { "answer_id": 17111803, "author": "Antoine Meltzheim", "author_id": 1554443, "author_profile": "https://Stackoverflow.com/users/1554443", "pm_score": 3, "selected": false, "text": "public class MyExcelInteropClass\n{\n Excel.Application xlApp;\n Excel.Workbook xlBook;\n\n public void dothingswithExcel() \n {\n try { /* Do stuff manipulating cells sheets and workbooks ... */ }\n catch {}\n finally {KillExcelProcess(xlApp);}\n }\n\n static void KillExcelProcess(Excel.Application xlApp)\n {\n if (xlApp != null)\n {\n int excelProcessId = 0;\n GetWindowThreadProcessId(xlApp.Hwnd, out excelProcessId);\n Process p = Process.GetProcessById(excelProcessId);\n p.Kill();\n xlApp = null;\n }\n }\n\n [DllImport(\"user32.dll\")]\n static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);\n}\n" }, { "answer_id": 18462636, "author": "Shivam Srivastava", "author_id": 2731599, "author_profile": "https://Stackoverflow.com/users/2731599", "pm_score": 0, "selected": false, "text": "[DllImport(\"user32.dll\")]\nprivate static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n finally finally\n{\n GC.Collect();\n GC.WaitForPendingFinalizers();\n if (excelApp != null)\n {\n excelApp.Quit();\n int hWnd = excelApp.Application.Hwnd;\n uint processID;\n GetWindowThreadProcessId((IntPtr)hWnd, out processID);\n Process[] procs = Process.GetProcessesByName(\"EXCEL\");\n foreach (Process p in procs)\n {\n if (p.Id == processID)\n p.Kill();\n }\n Marshal.FinalReleaseComObject(excelApp);\n }\n}\n" }, { "answer_id": 20059771, "author": "D.G.", "author_id": 3006661, "author_profile": "https://Stackoverflow.com/users/3006661", "pm_score": 3, "selected": false, "text": "GC.Collect() GC.WaitForPendingFinalizers() GC.Collect();\nGC.WaitForPendingFinalizers();\n private void FunctionWrapper(string sourcePath, string targetPath)\n{\n try\n {\n FunctionThatCallsExcel(sourcePath, targetPath);\n }\n finally\n {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n" }, { "answer_id": 20555721, "author": "Hahnemann", "author_id": 77265, "author_profile": "https://Stackoverflow.com/users/77265", "pm_score": 2, "selected": false, "text": "private static void Clean()\n{\n workBook.Close();\n Marshall.ReleaseComObject(workBook);\n excel.Quit();\n CG.Collect();\n CG.WaitForPendingFinalizers();\n}\n" }, { "answer_id": 22004055, "author": "craig.tadlock", "author_id": 766616, "author_profile": "https://Stackoverflow.com/users/766616", "pm_score": 3, "selected": false, "text": "excel = new Microsoft.Office.Interop.Excel.Application();\nvar process = Process.GetProcessesByName(\"EXCEL\").OrderByDescending(p => p.StartTime).First();\n if (!process.HasExited)\n process.Kill();\n" }, { "answer_id": 24282029, "author": "Loart", "author_id": 3751812, "author_profile": "https://Stackoverflow.com/users/3751812", "pm_score": 2, "selected": false, "text": "[DllImport(\"user32.dll\")]\nstatic extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);\n\nprivate void GenerateExcel()\n{\n var excel = new Microsoft.Office.Interop.Excel.Application();\n int id;\n // Find the Excel Process Id (ath the end, you kill him\n GetWindowThreadProcessId(excel.Hwnd, out id);\n Process excelProcess = Process.GetProcessById(id);\n\ntry\n{\n // Your code\n}\nfinally\n{\n excel.Quit();\n\n // Kill him !\n excelProcess.Kill();\n}\n" }, { "answer_id": 25685147, "author": "Martin", "author_id": 559085, "author_profile": "https://Stackoverflow.com/users/559085", "pm_score": 1, "selected": false, "text": "if (xlApp != null)\n{\n xlApp.Workbooks.Close();\n xlApp.Quit();\n}\n\nSystem.Diagnostics.Process[] processArray = System.Diagnostics.Process.GetProcessesByName(\"EXCEL\");\nforeach (System.Diagnostics.Process process in processArray)\n{\n if (process.MainWindowTitle.Length == 0) { process.Kill(); }\n}\n" }, { "answer_id": 30031089, "author": "akirakonenu", "author_id": 1126174, "author_profile": "https://Stackoverflow.com/users/1126174", "pm_score": 0, "selected": false, "text": "public abstract class ReleaseContainer<T>\n{\n private readonly Action<T> actionOnT;\n\n protected ReleaseContainer(T releasible, Action<T> actionOnT)\n {\n this.actionOnT = actionOnT;\n this.Releasible = releasible;\n }\n\n ~ReleaseContainer()\n {\n Release();\n }\n\n public T Releasible { get; private set; }\n\n private void Release()\n {\n actionOnT(Releasible);\n Releasible = default(T);\n }\n}\n public class ApplicationContainer : ReleaseContainer<Application>\n{\n public ApplicationContainer()\n : base(new Application(), ActionOnExcel)\n {\n }\n\n private static void ActionOnExcel(Application application)\n {\n application.Show(); // extension method. want to make sure the app is visible.\n application.Quit();\n Marshal.FinalReleaseComObject(application);\n }\n}\n public static Application CreateExcelApplication(bool hidden = false)\n {\n var excel = new ApplicationContainer().Releasible;\n excel.Visible = !hidden;\n\n return excel;\n }\n Quit Marshal.FinalReleaseComObject" }, { "answer_id": 36476219, "author": "dicksters", "author_id": 6172080, "author_profile": "https://Stackoverflow.com/users/6172080", "pm_score": 0, "selected": false, "text": "Excel::_ApplicationPtr pXL = ...\n :\nSendMessage ( ( HWND ) m_pXL->GetHwnd ( ), WM_DESTROY, 0, 0 ) ;\n" }, { "answer_id": 38111294, "author": "Govert", "author_id": 44264, "author_profile": "https://Stackoverflow.com/users/44264", "pm_score": 5, "selected": false, "text": "Marshal.ReleaseComObject(...) Marshal.FinalReleaseComObject(...) GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() rng.Cells Sub WrapperThatCleansUp()\n\n ' NOTE: Don't call Excel objects in here... \n ' Debugger would keep alive until end, preventing GC cleanup\n\n ' Call a separate function that talks to Excel\n DoTheWork()\n\n ' Now let the GC clean up (twice, to clean up cycles too)\n GC.Collect() \n GC.WaitForPendingFinalizers()\n GC.Collect() \n GC.WaitForPendingFinalizers()\n\nEnd Sub\n\nSub DoTheWork()\n Dim app As New Microsoft.Office.Interop.Excel.Application\n Dim book As Microsoft.Office.Interop.Excel.Workbook = app.Workbooks.Add()\n Dim worksheet As Microsoft.Office.Interop.Excel.Worksheet = book.Worksheets(\"Sheet1\")\n app.Visible = True\n For i As Integer = 1 To 10\n worksheet.Cells.Range(\"A\" & i).Value = \"Hello\"\n Next\n book.Save()\n book.Close()\n app.Quit()\n\n ' NOTE: No calls the Marshal.ReleaseComObject() are ever needed\nEnd Sub\n" }, { "answer_id": 38723357, "author": "Tom Brearley", "author_id": 6668143, "author_profile": "https://Stackoverflow.com/users/6668143", "pm_score": 1, "selected": false, "text": "public static void SweepExcelProcesses()\n{ \n if (Process.GetProcessesByName(\"EXCEL\").Length != 0)\n {\n Process[] processes = Process.GetProcesses();\n foreach (Process process in processes)\n {\n if (process.ProcessName.ToString() == \"excel\")\n { \n string title = process.MainWindowTitle;\n }\n }\n }\n}\n" }, { "answer_id": 42220665, "author": "Hermes Monteiro", "author_id": 5846695, "author_profile": "https://Stackoverflow.com/users/5846695", "pm_score": -1, "selected": false, "text": " foreach (Process proc in System.Diagnostics.Process.GetProcessesByName(\"EXCEL\"))\n {\n proc.Kill();\n }\n" }, { "answer_id": 53844023, "author": "Aloha", "author_id": 9061172, "author_profile": "https://Stackoverflow.com/users/9061172", "pm_score": 0, "selected": false, "text": "private static Excel.Application GetExcelApp()\n {\n if (_excelApp == null)\n {\n var processIds = System.Diagnostics.Process.GetProcessesByName(\"EXCEL\").Select(a => a.Id).ToList();\n _excelApp = new Excel.Application();\n _excelApp.DisplayAlerts = false;\n\n _excelApp.Visible = false;\n _excelApp.ScreenUpdating = false;\n var newProcessIds = System.Diagnostics.Process.GetProcessesByName(\"EXCEL\").Select(a => a.Id).ToList();\n _excelApplicationProcessId = newProcessIds.Except(processIds).FirstOrDefault();\n }\n\n return _excelApp;\n }\n\npublic static void Dispose()\n {\n try\n {\n _excelApp.Workbooks.Close();\n _excelApp.Quit();\n System.Runtime.InteropServices.Marshal.ReleaseComObject(_excelApp);\n _excelApp = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n if (_excelApplicationProcessId != default(int))\n {\n var process = System.Diagnostics.Process.GetProcessById(_excelApplicationProcessId);\n process?.Kill();\n _excelApplicationProcessId = default(int);\n }\n }\n catch (Exception ex)\n {\n _excelApp = null;\n }\n\n }\n" }, { "answer_id": 55483021, "author": "tjarrett", "author_id": 11301945, "author_profile": "https://Stackoverflow.com/users/11301945", "pm_score": 1, "selected": false, "text": "[DllImport(\"User32.dll\")]\nstatic extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);\n...\n\nint objExcelProcessId = 0;\n\nExcel.Application objExcel = new Excel.Application();\n\nGetWindowThreadProcessId(new IntPtr(objExcel.Hwnd), out objExcelProcessId);\n\nProcess.GetProcessById(objExcelProcessId).Kill();\n" }, { "answer_id": 58152953, "author": "Dietrich Baumgarten", "author_id": 7453065, "author_profile": "https://Stackoverflow.com/users/7453065", "pm_score": 1, "selected": false, "text": "Marshal.ReleaseComObject Quit() using Excel = Microsoft.Office.Interop.Excel;\npublic delegate void WrapCom();\nnamespace GCTestOnOffice{\n class Program{\n static void DoSomethingWithExcel(){\n Excel.Application ExcelApp = new();\n Excel.Workbook Wb = ExcelApp.Workbooks.Open(@\"D:\\\\Sample.xlsx\");\n Excel.Worksheet NewWs = Wb.Worksheets.Add();\n for (int i = 1; i < 10; i++){ NewWs.Cells[i, 1] = i;}\n Wb.Save();\n ExcelApp.Quit();\n } \n\n static void TheComWrapper(WrapCom wrapCom){\n wrapCom();\n //All COM objects are out of scope, ready for the GC to gobble\n //Excel is no longer visible, but the process is still alive,\n //check out the Task-Manager in the next 6 seconds\n Thread.Sleep(6000);\n GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n GC.WaitForPendingFinalizers();\n //Check out the Task-Manager, the Excel process is gone\n }\n\n static void Main(string[] args){\n TheComWrapper(DoSomethingWithExcel);\n }\n }\n}\n" }, { "answer_id": 65117417, "author": "Anton Shepelev", "author_id": 2862241, "author_profile": "https://Stackoverflow.com/users/2862241", "pm_score": 0, "selected": false, "text": "excel Marshal.ReleaseComObject() FinalReleaseComObject() IDisposable Dispose() ReleaseComObject() WorkSheet Cells public ExcelRange XCell( int row, int col)\n{ ExcelRange anchor, res;\n using( anchor = Range( \"A1\") )\n { res = anchor.Offset( row - 1, col - 1 ); }\n return res;\n}\n" }, { "answer_id": 70030732, "author": "br3nt", "author_id": 848668, "author_profile": "https://Stackoverflow.com/users/848668", "pm_score": 0, "selected": false, "text": "Close() Quit() function void OpenCopyClose() {\n var excel = new ExcelApplication();\n var workbook1 = excel.OpenWorkbook(\"C:\\Temp\\file1.xslx\", readOnly: true);\n var readOnlysheet = workbook1.Worksheet(\"sheet1\");\n\n var workbook2 = excel.OpenWorkbook(\"C:\\Temp\\file2.xslx\");\n var writeSheet = workbook.Worksheet(\"sheet1\");\n\n // do all the excel manipulation\n\n // read from the first workbook, write to the second workbook.\n var a1 = workbook1.Cells[1, 1];\n workbook2.Cells[1, 1] = a1\n\n // explicit clean-up\n workbook1.Close(false);\n workbook2 .Close(true);\n excel.Quit();\n}\n Close() Quit() Save() DisposableComObject IDisposable using Dispose() Marshal.ReleaseComObject(ComObject) ComObjectRef ComObjectRef ComObject ComObjectAccessedAfterDisposeException Dispose() using using var Microsoft.Office.Interop.Excel Application Workbook Worksheet DisposableComObject /// <summary>\n/// References to COM objects must be explicitly released when done.\n/// Failure to do so can result in odd behavior and processes remaining running after the application has stopped.\n/// This class helps to automate the process of disposing the references to COM objects.\n/// </summary>\npublic abstract class DisposableComObject : IDisposable\n{\n public class ComObjectAccessedAfterDisposeException : Exception\n {\n public ComObjectAccessedAfterDisposeException() : base(\"COM object has been accessed after being disposed\") { }\n }\n\n /// <summary>The actual COM object</summary>\n private object ComObjectRef { get; set; }\n\n /// <summary>The COM object to be used by subclasses</summary>\n /// <exception cref=\"ComObjectAccessedAfterDisposeException\">When the COM object has been disposed</exception>\n protected object ComObject => ComObjectRef ?? throw new ComObjectAccessedAfterDisposeException();\n\n public DisposableComObject(object comObject) => ComObjectRef = comObject;\n\n /// <summary>\n /// True, if the COM object has been disposed.\n /// </summary>\n protected bool IsDisposed() => ComObjectRef is null;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this); // in case a subclass implements a finalizer\n }\n\n /// <summary>\n /// This method releases the COM object and removes the reference.\n /// This allows the garbage collector to clean up any remaining instance.\n /// </summary>\n /// <param name=\"disposing\">Set to true</param>\n protected virtual void Dispose(bool disposing)\n {\n if (!disposing || IsDisposed()) return;\n Marshal.ReleaseComObject(ComObject);\n ComObjectRef = null;\n }\n\n ~DisposableComObject()\n {\n Dispose(true);\n }\n}\n public abstract class DisposableComObject<T> : DisposableComObject\n{\n protected new T ComObject => (T)base.ComObject;\n\n public DisposableComObject(T comObject) : base(comObject) { }\n}\n DisposableComObject<T> ExcelApplication OpenWorkbook() ExcelWorkbook Dispose() Dispose() Quit() Dispose() public class ExcelApplication : DisposableComObject<Application>\n{\n public class OpenWorkbookActionCancelledException : Exception\n {\n public string Filename { get; }\n\n public OpenWorkbookActionCancelledException(string filename, COMException ex) : base($\"The workbook open action was cancelled. {ex.Message}\", ex) => Filename = filename;\n }\n\n /// <summary>The actual Application from Interop.Excel</summary>\n Application App => ComObject;\n\n public ExcelApplication() : base(new Application()) { }\n\n /// <summary>Open a workbook.</summary>\n public ExcelWorkbook OpenWorkbook(string filename, bool readOnly = false, string password = null, string writeResPassword = null)\n {\n try\n {\n var workbook = App.Workbooks.Open(Filename: filename, UpdateLinks: (XlUpdateLinks)0, ReadOnly: readOnly, Password: password, WriteResPassword: writeResPassword, );\n\n return new ExcelWorkbook(workbook);\n }\n catch (COMException ex)\n {\n // If the workbook is already open and the request mode is not read-only, the user will be presented\n // with a prompt from the Excel application asking if the workbook should be opened in read-only mode.\n // This exception is raised when when the user clicks the Cancel button in that prompt.\n throw new OpenWorkbookActionCancelledException(filename, ex);\n }\n }\n\n /// <summary>Quit the running application.</summary>\n public void Quit() => Dispose(true);\n\n /// <inheritdoc/>\n protected override void Dispose(bool disposing)\n {\n if (!disposing || IsDisposed()) return;\n App.Quit();\n base.Dispose(disposing);\n }\n}\n\n ExcelWorkbook DisposableComObject<Workbook> Worksheet() ExcelWorksheet DisposableComObject<Workbook> Dispose() Dispose() Workbook.Worksheets public class ExcelWorkbook : DisposableComObject<Workbook>\n{\n public class WorksheetNotFoundException : Exception\n {\n public WorksheetNotFoundException(string message) : base(message) { }\n }\n\n /// <summary>The actual Workbook from Interop.Excel</summary>\n Workbook Workbook => ComObject;\n\n /// <summary>The worksheets within the workbook</summary>\n public IEnumerable<ExcelWorksheet> Worksheets => worksheets ?? (worksheets = Workbook.Worksheets.AsEnumerable<Worksheet>().Select(w => new ExcelWorksheet(w)).ToList());\n private IEnumerable<ExcelWorksheet> worksheets;\n\n public ExcelWorkbook(Workbook workbook) : base(workbook) { }\n\n /// <summary>\n /// Get the worksheet matching the <paramref name=\"sheetName\"/>\n /// </summary>\n /// <param name=\"sheetName\">The name of the Worksheet</param>\n public ExcelWorksheet Worksheet(string sheetName) => Worksheet(s => s.Name == sheetName, () => $\"Worksheet not found: {sheetName}\");\n\n /// <summary>\n /// Get the worksheet matching the <paramref name=\"predicate\"/>\n /// </summary>\n /// <param name=\"predicate\">A function to test each Worksheet for a macth</param>\n public ExcelWorksheet Worksheet(Func<ExcelWorksheet, bool> predicate, Func<string> errorMessageAction) => Worksheets.FirstOrDefault(predicate) ?? throw new WorksheetNotFoundException(errorMessageAction.Invoke());\n\n /// <summary>\n /// Returns true of the workbook is read-only\n /// </summary>\n public bool IsReadOnly() => Workbook.ReadOnly;\n\n /// <summary>\n /// Save changes made to the workbook\n /// </summary>\n public void Save()\n {\n Workbook.Save();\n }\n\n /// <summary>\n /// Close the workbook and optionally save changes\n /// </summary>\n /// <param name=\"saveChanges\">True is save before close</param>\n public void Close(bool saveChanges)\n {\n if (saveChanges) Save();\n Dispose(true);\n }\n\n /// <inheritdoc/>\n protected override void Dispose(bool disposing)\n {\n if (!disposing || IsDisposed()) return;\n Workbook.Close();\n base.Dispose(disposing);\n }\n}\n ExcelWorksheet UsedRows() Microsoft.Office.Interop.Excel.Range Microsoft.Office.Interop.Excel.Worksheet Application Workbook Worksheet Dispose() public class ExcelWorksheet : DisposableComObject<Worksheet>\n{\n /// <summary>The actual Worksheet from Interop.Excel</summary>\n Worksheet Worksheet => ComObject;\n\n /// <summary>The worksheet name</summary>\n public string Name => Worksheet.Name;\n\n // <summary>The worksheets cells (Unwrapped COM object)</summary>\n public Range Cells => Worksheet.Cells;\n\n public ExcelWorksheet(Worksheet worksheet) : base(worksheet) { }\n\n /// <inheritdoc cref=\"WorksheetExtensions.UsedRows(Worksheet)\"/>\n public IEnumerable<Range> UsedRows() => Worksheet.UsedRows().ToList();\n}\n ExcelWorksheet ExcelApplication.OpenWorkbook() ExcelWorkbook.WorkSheets public static class EnumeratorExtensions\n{\n /// <summary>\n /// Converts the <paramref name=\"enumerator\"/> to an IEnumerable of type <typeparamref name=\"T\"/>\n /// </summary>\n public static IEnumerable<T> AsEnumerable<T>(this IEnumerable enumerator)\n {\n return enumerator.GetEnumerator().AsEnumerable<T>();\n }\n\n /// <summary>\n /// Converts the <paramref name=\"enumerator\"/> to an IEnumerable of type <typeparamref name=\"T\"/>\n /// </summary>\n public static IEnumerable<T> AsEnumerable<T>(this IEnumerator enumerator)\n {\n while (enumerator.MoveNext()) yield return (T)enumerator.Current;\n }\n\n /// <summary>\n /// Converts the <paramref name=\"enumerator\"/> to an IEnumerable of type <typeparamref name=\"T\"/>\n /// </summary>\n public static IEnumerable<T> AsEnumerable<T>(this IEnumerator<T> enumerator)\n {\n while (enumerator.MoveNext()) yield return enumerator.Current;\n }\n}\n\npublic static class WorksheetExtensions\n{\n /// <summary>\n /// Returns the rows within the used range of this <paramref name=\"worksheet\"/>\n /// </summary>\n /// <param name=\"worksheet\">The worksheet</param>\n public static IEnumerable<Range> UsedRows(this Worksheet worksheet) =>\n worksheet.UsedRange.Rows.AsEnumerable<Range>();\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
158,710
<p>I'm trying to use CSS (<strong>under <code>@media print</code></strong>) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option.</p> <p>To put it another way, I'm looking for proper resizing, so that, for example, "IIIII" would come out in a much larger font size than "WWWWW" because "I" is much skinnier than "W" in a variable-width font.</p> <p>The closest I've been able to get with this is using JavaScript to try various font sizes until the <code>clientWidth</code> is small enough. <strong>This works well enough for screen media, but when you switch to print media</strong>, is there any guarantee that the 90 DPI I appear to get on my system (i.e., I put the margins to 0.5in either side, and for a text resized so that it fits just within that, I get about 675 for <code>clientWidth</code>) will be the same anywhere else? How does a browser decide what DPI to use when converting from pixel measurements? Is there any way I can access this information using JavaScript?</p> <p>I would love it if this were just a CSS3 feature (<code>font-size:max-for-width(7.5in)</code>) but if it is, I haven't been able to find it.</p>
[ { "answer_id": 163931, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 1, "selected": true, "text": "function make_big(id) // must be an inline element inside a block-level element\n{\n var e = document.getElementById(id);\n e.style.whiteSpace = 'nowrap';\n e.style.textAlign = 'center';\n var max = e.parentNode.scrollWidth - 4; // a little padding\n e.style.fontSize = (max / 4) + 'px'; // make a guess, then we'll use the resulting ratio\n e.style.fontSize = (max / (e.scrollWidth / parseFloat(e.style.fontSize))) + 'px';\n e.style.display = 'block'; // so centering takes effect\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777/" ]
158,716
<p>The question gives all necessary data: what is an efficient algorithm to generate a sequence of <em>K</em> non-repeating integers within a given interval <em>[0,N-1]</em>. The trivial algorithm (generating random numbers and, before adding them to the sequence, looking them up to see if they were already there) is very expensive if <em>K</em> is large and near enough to <em>N</em>.</p> <p>The algorithm provided in <a href="https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list">Efficiently selecting a set of random elements from a linked list</a> seems more complicated than necessary, and requires some implementation. I've just found another algorithm that seems to do the job fine, as long as you know all the relevant parameters, in a single pass.</p>
[ { "answer_id": 158733, "author": "tucuxi", "author_id": 15472, "author_profile": "https://Stackoverflow.com/users/15472", "pm_score": 2, "selected": false, "text": " /* generate N sorted, non-duplicate integers in [0, max] */\n int *generate(int n, int max) {\n int i, m, a; \n int *g = (int *)calloc(n, sizeof(int));\n if (!g) return 0;\n\n m = 0;\n for (i = 0; i < max; i++) {\n a = random_in_between(0, max - i);\n if (a < n - m) {\n g[m] = i;\n m++;\n }\n }\n return g;\n }\n" }, { "answer_id": 158742, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "0...N-1 a[i] = i K J = N-1 0...J R a[R] a[J] R J 1 J K" }, { "answer_id": 158757, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": "@list = grep ($_ % I) == 0, (0..N);\n @list = grep ($_ % 3) == 0, (0..30);\n" }, { "answer_id": 158847, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 5, "selected": true, "text": "from random import sample\nprint sample(xrange(N), K)\n sample xrange" }, { "answer_id": 158901, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 0, "selected": false, "text": "my $N = 20;\nmy $k;\nmy @r;\n\nwhile(<>) {\n if(++$k <= $N) {\n push @r, $_;\n } elsif(rand(1) <= ($N/$k)) {\n $r[rand(@r)] = $_;\n }\n}\n\nprint @r;\n" }, { "answer_id": 158962, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": -1, "selected": false, "text": "/* generate N sorted, non-duplicate integers in [0, max[ in O(N))*/\n int *generate(int n, int max) {\n float step,a,v=0;\n int i; \n int *g = (int *)calloc(n, sizeof(int));\n if ( ! g) return 0;\n\n for (i=0; i<n; i++) {\n step = (max-v)/(float)(n-i);\n v+ = floating_pt_random_in_between(0.0, step*2.0);\n if ((int)v == g[i-1]){\n v=(int)v+1; //avoid collisions\n }\n g[i]=v;\n }\n while (g[i]>max) {\n g[i]=max; //fix up overflow\n max=g[i--]-1;\n }\n return g;\n }\n" }, { "answer_id": 158967, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 1, "selected": false, "text": "// Assume K is the highest number in the list\nstd::vector<int> sorted_list;\nstd::vector<int> random_list;\n\nfor(int i = 0; i < K; ++i) {\n sorted_list.push_back(i);\n}\n\n// Loop to K - 1 elements, as this will cause problems when trying to erase\n// the first element\nwhile(!sorted_list.size() > 1) {\n int rand_index = rand() % sorted_list.size();\n random_list.push_back(sorted_list.at(rand_index));\n sorted_list.erase(sorted_list.begin() + rand_index);\n} \n\n// Finally push back the last remaining element to the random list\n// The if() statement here is just a sanity check, in case K == 0\nif(!sorted_list.empty()) {\n random_list.push_back(sorted_list.at(0));\n}\n" }, { "answer_id": 187952, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 4, "selected": false, "text": "(defun sample-list (n list &optional (length (length list)) result)\n (cond ((= length 0) result)\n ((< (* length (random 1.0)) n)\n (sample-list (1- n) (cdr list) (1- length)\n (cons (car list) result)))\n (t (sample-list n (cdr list) (1- length) result))))\n (defun sample (n sequence)\n (let ((length (length sequence))\n (result (subseq sequence 0 n)))\n (loop\n with m = 0\n for i from 0 and u = (random 1.0)\n do (when (< (* (- length i) u) \n (- n m))\n (setf (elt result m) (elt sequence i))\n (incf m))\n until (= m n))\n result))\n" }, { "answer_id": 2488191, "author": "Frédéric Grosshans", "author_id": 295887, "author_profile": "https://Stackoverflow.com/users/295887", "pm_score": 0, "selected": false, "text": "/* Sampling according to [Vitter87].\n * \n * Bibliography\n * [Vitter 87]\n * Jeffrey Scott Vitter, \n * An Efficient Algorithm for Sequential Random Sampling\n * ACM Transactions on MAthematical Software, 13 (1), 58 (1987).\n */\n\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <string>\n#include <iostream>\n\n#include <iomanip>\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_real.hpp>\n\nusing namespace std;\n\n// This is a typedef for a random number generator.\n// Try boost::mt19937 or boost::ecuyer1988 instead of boost::minstd_rand\ntypedef boost::minstd_rand base_generator_type;\n\n // Define a random number generator and initialize it with a reproducible\n // seed.\n // (The seed is unsigned, otherwise the wrong overload may be selected\n // when using mt19937 as the base_generator_type.)\n base_generator_type generator(0xBB84u);\n //TODO : change the seed above !\n // Defines the suitable uniform ditribution.\n boost::uniform_real<> uni_dist(0,1);\n boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);\n\n\n\nvoid SequentialSamplesMethodA(int K, int N) \n// Outputs K sorted random integers out of 0..N, taken according to \n// [Vitter87], method A.\n {\n int top=N-K, S, curr=0, currsample=-1;\n double Nreal=N, quot=1., V;\n\n while (K>=2)\n {\n V=uni();\n S=0;\n quot=top/Nreal;\n while (quot > V)\n {\n S++; top--; Nreal--;\n quot *= top/Nreal;\n }\n currsample+=1+S;\n cout << curr << \" : \" << currsample << \"\\n\";\n Nreal--; K--;curr++;\n }\n // special case K=1 to avoid overflow\n S=floor(round(Nreal)*uni());\n currsample+=1+S;\n cout << curr << \" : \" << currsample << \"\\n\";\n }\n\nvoid SequentialSamplesMethodD(int K, int N)\n// Outputs K sorted random integers out of 0..N, taken according to \n// [Vitter87], method D. \n {\n const int negalphainv=-13; //between -20 and -7 according to [Vitter87]\n //optimized for an implementation in 1987 !!!\n int curr=0, currsample=0;\n int threshold=-negalphainv*K;\n double Kreal=K, Kinv=1./Kreal, Nreal=N;\n double Vprime=exp(log(uni())*Kinv);\n int qu1=N+1-K; double qu1real=qu1;\n double Kmin1inv, X, U, negSreal, y1, y2, top, bottom;\n int S, limit;\n while ((K>1)&&(threshold<N))\n {\n Kmin1inv=1./(Kreal-1.);\n while(1)\n {//Step D2: generate X and U\n while(1)\n {\n X=Nreal*(1-Vprime);\n S=floor(X);\n if (S<qu1) {break;}\n Vprime=exp(log(uni())*Kinv);\n }\n U=uni();\n negSreal=-S;\n //step D3: Accept ?\n y1=exp(log(U*Nreal/qu1real)*Kmin1inv);\n Vprime=y1*(1. - X/Nreal)*(qu1real/(negSreal+qu1real));\n if (Vprime <=1.) {break;} //Accept ! Test [Vitter87](2.8) is true\n //step D4 Accept ?\n y2=0; top=Nreal-1.;\n if (K-1 > S)\n {bottom=Nreal-Kreal; limit=N-S;}\n else {bottom=Nreal+negSreal-1.; limit=qu1;}\n for(int t=N-1;t>=limit;t--)\n {y2*=top/bottom;top--; bottom--;}\n if (Nreal/(Nreal-X)>=y1*exp(log(y2)*Kmin1inv))\n {//Accept !\n Vprime=exp(log(uni())*Kmin1inv);\n break;\n }\n Vprime=exp(log(uni())*Kmin1inv);\n }\n // Step D5: Select the (S+1)th record\n currsample+=1+S;\n cout << curr << \" : \" << currsample << \"\\n\";\n curr++;\n N-=S+1; Nreal+=negSreal-1.;\n K-=1; Kreal-=1; Kinv=Kmin1inv;\n qu1-=S; qu1real+=negSreal;\n threshold+=negalphainv;\n }\n if (K>1) {SequentialSamplesMethodA(K, N);}\n else {\n S=floor(N*Vprime);\n currsample+=1+S;\n cout << curr << \" : \" << currsample << \"\\n\";\n }\n }\n\n\nint main(void)\n {\n int Ntest=10000000, Ktest=Ntest/100;\n SequentialSamplesMethodD(Ktest,Ntest);\n return 0;\n }\n\n$ time ./sampling|tail\n 99990 : 9998882\n99991 : 9998885\n99992 : 9999021\n99993 : 9999058\n99994 : 9999339\n99995 : 9999359\n99996 : 9999411\n99997 : 9999427\n99998 : 9999584\n99999 : 9999745\n\nreal 0m0.075s\nuser 0m0.060s\nsys 0m0.000s\n" }, { "answer_id": 12266395, "author": "Konstantin", "author_id": 1596686, "author_profile": "https://Stackoverflow.com/users/1596686", "pm_score": 0, "selected": false, "text": "n=5 [0,N=10) t=0\nm=0\nN=10\nn=5\ns=0\ndistrib=Array.new(N,0)\nfor i in 1..500000 do\n t=0\n m=0\n s=0\n while m<n do\n\n u=rand()\n if (N-t)*u>=n-m then\n t=t+1\n else \n distrib[s]+=1\n m=m+1\n t=t+1\n end #if\n s=s+1\n end #while\n if (i % 100000)==0 then puts i.to_s + \". cycle...\" end\nend #for\nputs \"--------------\"\nputs distrib\n 100000. cycle...\n200000. cycle...\n300000. cycle...\n400000. cycle...\n500000. cycle...\n--------------\n250272\n249924\n249628\n249894\n250193\n250202\n249647\n249606\n250600\n250034\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15472/" ]
158,750
<p>I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?</p> <p><strong>Update Oct 1, 2008:</strong></p> <p>Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <code>&lt;div&gt;</code> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.</p> <p>It then got me thinking about online image editors like <a href="http://www.picnik.com/" rel="noreferrer">Picnik</a> and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?</p>
[ { "answer_id": 16028008, "author": "mikeslattery", "author_id": 1205867, "author_profile": "https://Stackoverflow.com/users/1205867", "pm_score": 5, "selected": true, "text": "<img id=\"img1\" src=\"imgfile1.png\">\n<img id=\"img2\" src=\"imgfile2.png\">\n<canvas id=\"canvas\"></canvas>\n\n<script type=\"text/javascript\">\nvar img1 = document.getElementById('img1');\nvar img2 = document.getElementById('img2');\nvar canvas = document.getElementById('canvas');\nvar context = canvas.getContext('2d');\n\ncanvas.width = img1.width;\ncanvas.height = img1.height;\n\ncontext.globalAlpha = 1.0;\ncontext.drawImage(img1, 0, 0);\ncontext.globalAlpha = 0.5; //Remove if pngs have alpha\ncontext.drawImage(img2, 0, 0);\n</script>\n <canvas id=\"canvas\"></canvas>\n<script type=\"text/javascript\">\nvar canvas = document.getElementById('canvas');\nvar context = canvas.getContext('2d');\nvar img1 = new Image();\nvar img2 = new Image();\n\nimg1.onload = function() {\n canvas.width = img1.width;\n canvas.height = img1.height;\n img2.src = 'imgfile2.png';\n};\nimg2.onload = function() {\n context.globalAlpha = 1.0;\n context.drawImage(img1, 0, 0);\n context.globalAlpha = 0.5; //Remove if pngs have alpha\n context.drawImage(img2, 0, 0);\n}; \n\nimg1.src = 'imgfile1.png';\n</script>\n" }, { "answer_id": 49632344, "author": "Gabriel Ambrósio Archanjo", "author_id": 2420599, "author_profile": "https://Stackoverflow.com/users/2420599", "pm_score": 3, "selected": false, "text": "Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);\n var canvas = document.getElementById(\"canvas\");\nimage1 = new MarvinImage();\nimage1.load(\"https://i.imgur.com/ChdMiH7.jpg\", imageLoaded);\nimage2 = new MarvinImage();\nimage2.load(\"https://i.imgur.com/h3HBUBt.png\", imageLoaded);\nimage3 = new MarvinImage();\nimage3.load(\"https://i.imgur.com/UoISVdT.png\", imageLoaded);\n\nvar loaded=0;\n\nfunction imageLoaded(){\n if(++loaded == 3){\n var image = new MarvinImage(image1.getWidth(), image1.getHeight());\n Marvin.combineByAlpha(image1, image2, image, 0, 0);\n Marvin.combineByAlpha(image, image3, image, 190, 120);\n image.draw(canvas);\n }\n} <script src=\"https://www.marvinj.org/releases/marvinj-0.8.js\"></script>\n<canvas id=\"canvas\" width=\"450\" height=\"297\"></canvas>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415/" ]
158,760
<p>I am looking for any examples or guides to using Linq over WCF (n-tier application). Please specify if you are showing something for Linq-to-SQL or Linq-to-entities. I would like to see usage examples for both. </p> <p>I am wondering how things like deffered execution works over WCF (if it works at all)? Cyclic references support and so on... </p> <p>Any information to make this a quick start guide to using Linq with WCF is helpful.</p>
[ { "answer_id": 158797, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": " static void Main(string[] args)\n {\n var context=new WebDataContext(\"http://localhost:18752/Northwind.svc\");\n\n var query = from p in context.CreateQuery<Product>(\"Products\")\n where p.UnitsInStock > 100\n select p;\n\n foreach (Product p in query)\n {\n Console.WriteLine(p.ProductName+\", UnitsInStock=\"+p.UnitsInStock);\n }\n } \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
158,772
<p>I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in <code>OnStart()</code> method). I had assumed that merely throwing an error in <code>OnStart()</code> would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?</p>
[ { "answer_id": 11870740, "author": "Sean", "author_id": 240430, "author_profile": "https://Stackoverflow.com/users/240430", "pm_score": 4, "selected": false, "text": "ExitCode protected override void OnStart(string[] args) {\n try {\n // Start your service\n }catch (Exception ex) {\n // Log exception\n this.ExitCode = 13816;\n this.Stop();\n throw;\n } \n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16487/" ]
158,778
<p>Let's say you have a function that returns a date:</p> <pre><code>Date myFunc(paramA, paramB){ //conditionally return a date? } </code></pre> <p>Is it appropriate to return <code>null</code> from this function? This seems ugly because it forces clients to check for <code>null</code>.</p> <p>The "null object" pattern is an implementation pattern that addresses this concern.<br> I'm not a huge fan of the null object pattern, but yes, it makes sense to always return a list, even if is empty, rather than to return <code>null</code>.<br> However, say in Java, a null date would be one that is cleared and has the year 1970.</p> <p>What is the best implementation pattern here?</p>
[ { "answer_id": 158803, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 0, "selected": false, "text": "if(employee.hasCustomPayday()) {\n //throws a runtime exception if no payday\n Date d = emp.customPayday();\n}\n" }, { "answer_id": 158832, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": -1, "selected": false, "text": "boolean MyFunction( a,b,Date c)\n{\n if (good) \n c.SetDate(....);\n return good;\n\n}\n Date theDate = new Date();\nif(MyFunction(a, b ,theDate ) \n{\n do stuff with C\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129162/" ]
158,780
<p>I'm trying to iterate all the controls on a form and enable ClearType font smoothing. Something like this:</p> <pre><code>procedure TForm4.UpdateControls(AParent: TWinControl); var I: Integer; ACtrl: TControl; tagLOGFONT: TLogFont; begin for I := 0 to AParent.ControlCount-1 do begin ACtrl:= AParent.Controls[I]; // if ParentFont=False, update the font here... if ACtrl is TWinControl then UpdateControls(Ctrl as TWinControl); end; end; </code></pre> <p>Now, is there a easy way to check if <code>ACtrl</code> have a <code>Font</code> property so i can pass the <code>Font.Handle</code> to somethink like:</p> <pre><code>GetObject(ACtrl.Font.Handle, SizeOf(TLogFont), @tagLOGFONT); tagLOGFONT.lfQuality := 5; ACtrl.Font.Handle := CreateFontIndirect(tagLOGFONT); </code></pre> <p>Thank you in advance.</p>
[ { "answer_id": 158841, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": true, "text": "if IsPublishedProp(ACtrl, 'Font') then\n ModifyFont(TFont(GetOrdProp(ACtrl, 'Font')))\n function ContainsNonemptyControl(controlParent: TWinControl;\n const requiredControlNamePrefix: string;\n const ignoreControls: string = ''): boolean;\nvar\n child : TControl;\n iControl: integer;\n ignored : TStringList;\n obj : TObject;\nbegin\n Result := true;\n if ignoreControls = '' then\n ignored := nil\n else begin\n ignored := TStringList.Create;\n ignored.Text := ignoreControls;\n end;\n try\n for iControl := 0 to controlParent.ControlCount-1 do begin\n child := controlParent.Controls[iControl];\n if (requiredControlNamePrefix = '') or\n SameText(requiredControlNamePrefix, Copy(child.Name, 1,\n Length(requiredControlNamePrefix))) then\n if (not assigned(ignored)) or (ignored.IndexOf(child.Name) < 0) then\n if IsPublishedProp(child, 'Text') and (GetStrProp(child, 'Text') <> '') then\n Exit\n else if IsPublishedProp(child, 'Lines') then begin\n obj := TObject(cardinal(GetOrdProp(child, 'Lines')));\n if (obj is TStrings) and (Unwrap(TStrings(obj).Text, child) <> '') then\n Exit;\n end;\n end; //for iControl\n finally FreeAndNil(ignored); end;\n Result := false;\nend; { ContainsNonemptyControl }\n" }, { "answer_id": 320155, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 3, "selected": false, "text": "type\n THackControl = class(TControl);\n\nModifyFont(THackControl(AParent.Controls[I]).Font);\n" }, { "answer_id": 22463097, "author": "Pete", "author_id": 782738, "author_profile": "https://Stackoverflow.com/users/782738", "pm_score": 0, "selected": false, "text": "struct THackControl : TControl\n{\n __fastcall virtual THackControl(Classes::TComponent* AOwner);\n TFont* Font() { return TControl::Font; };\n};\n\nfor(int ControlIdx = 0; ControlIdx < ControlCount; ++ControlIdx)\n{\n ((THackControl*)Controls[ControlIdx])->Font()->Color = clRed;\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19610/" ]
158,783
<p>I really want to be able to have a way to take an app that currently gets its settings using <strong>ConfigurationManager.AppSettings["mysettingkey"]</strong> to actually have those settings come from a centralized database instead of the app.config file. I can make a custom config section for handling this sort of thing, but I really don't want other developers on my team to have to change their code to use my new DbConfiguration custom section. I just want them to be able to call AppSettings the way they always have but have it be loaded from a central database.</p> <p>Any ideas?</p>
[ { "answer_id": 159546, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": false, "text": "ConfigurationFromDatabaseManager.AppSettings[\"key\"] instead of ConfigurationSettings[\"key\"].\n" }, { "answer_id": 160307, "author": "Pent Ploompuu", "author_id": 17122, "author_profile": "https://Stackoverflow.com/users/17122", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Collections.Specialized;\nusing System.Configuration;\nusing System.Configuration.Internal;\nusing System.Reflection;\n\nstatic class ConfigOverrideTest\n{\n sealed class ConfigProxy:IInternalConfigSystem\n {\n readonly IInternalConfigSystem baseconf;\n\n public ConfigProxy(IInternalConfigSystem baseconf)\n {\n this.baseconf = baseconf;\n }\n\n object appsettings;\n public object GetSection(string configKey)\n {\n if(configKey == \"appSettings\" && this.appsettings != null) return this.appsettings;\n object o = baseconf.GetSection(configKey);\n if(configKey == \"appSettings\" && o is NameValueCollection)\n {\n // create a new collection because the underlying collection is read-only\n var cfg = new NameValueCollection((NameValueCollection)o);\n // add or replace your settings\n cfg[\"test\"] = \"Hello world\";\n o = this.appsettings = cfg;\n }\n return o;\n }\n\n public void RefreshConfig(string sectionName)\n {\n if(sectionName == \"appSettings\") appsettings = null;\n baseconf.RefreshConfig(sectionName);\n }\n\n public bool SupportsUserConfig\n {\n get { return baseconf.SupportsUserConfig; }\n }\n }\n\n static void Main()\n {\n // initialize the ConfigurationManager\n object o = ConfigurationManager.AppSettings;\n // hack your proxy IInternalConfigSystem into the ConfigurationManager\n FieldInfo s_configSystem = typeof(ConfigurationManager).GetField(\"s_configSystem\", BindingFlags.Static | BindingFlags.NonPublic);\n s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null)));\n // test it\n Console.WriteLine(ConfigurationManager.AppSettings[\"test\"] == \"Hello world\" ? \"Success!\" : \"Failure!\");\n }\n}\n" }, { "answer_id": 42395704, "author": "Pavel Mayorov", "author_id": 4340086, "author_profile": "https://Stackoverflow.com/users/4340086", "pm_score": 0, "selected": false, "text": "AppDomain.CreateDomain(\"second\", null, new AppDomainSetup\n{\n ConfigurationFile = options.ConfigPath,\n}).DoCallBack(...);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
158,800
<p>I have an ASPX page (On server A) which is invoked using NTLM credentials. Part of that page's job is to call an HTML page (On server B) and proxy it back to the client. (The firewall allows access to A, but not to B. The user would normally be allowed access to both servers.). Server B is also not open to anonymous access, so I need to supply credentials to it.</p> <p>If I hardcode some credentials (as per the attached code), it works, but ideally I would echo the credentials that were received by the .aspx page. Is there some way to get those NetworkCredentials so I can pass them on?</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Response.Clear(); WebClient proxyFile = new WebClient(); CredentialCache cc = new CredentialCache(); cc.Add(new Uri("http://serverB/"), "NTLM", new NetworkCredential("userName", "password", "domain")); proxyFile.Credentials = cc; Stream proxyStream = proxyFile.OpenRead("http://serverB/Content/webPage.html"); int i; do { i = proxyStream.ReadByte(); if (i != -1) { Response.OutputStream.WriteByte((byte)i); } } while (i != -1); Response.End(); } </code></pre>
[ { "answer_id": 159033, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<authentication mode=\"Windows\" />\n<identity impersonate=\"true\" />\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10031/" ]
158,804
<p>I've installed .NET Framework 3.5 SP1 on web server (Server 2008 Enterprise), so running IIS 7.0.</p> <p>I want to change the version of .NET Framework used by an existing site. So I right-click on appropriate Application Pool and selected Edit Application Pool. The .NET Framework dropdown does not include an explicit entry for framework 3.5, but just 2.0.50727.</p> <p>Is this just because the version of the core RTL in 3.5 is still 2.0? Or do I need to do something additional to get IIS to see version 3.5? (Did try restarting IIS).</p>
[ { "answer_id": 158825, "author": "Brownie", "author_id": 6600, "author_profile": "https://Stackoverflow.com/users/6600", "pm_score": 5, "selected": true, "text": "c:\\windows\\assembly" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22357/" ]
158,814
<p>What does it indicate to see a query that has a low cost in the explain plan but a high consistent gets count in autotrace? In this case the cost was in the 100's and the CR's were in the millions.</p>
[ { "answer_id": 158825, "author": "Brownie", "author_id": 6600, "author_profile": "https://Stackoverflow.com/users/6600", "pm_score": 5, "selected": true, "text": "c:\\windows\\assembly" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
158,818
<p>First off, let me start off that I am not a .net developer. The reason why I am asking this question is that we rolled out our REST-API and one of our first integration partners is a .net shop.</p> <p>So basically we assumed that .net would provide some sort of wrapper to create JSON, but the developer in question created the <em>string</em> by hand. I've researched this topic a bit and I couldn't really find anything, though I believe .net provides something. :)</p> <pre><code>'current code Dim data As String data = "[hello, world]" </code></pre> <p>In PHP I would do the following (assuming ext/json is available ;):</p> <pre><code>&lt;?php $json = array('hello', 'world'); $json = json_encode($json); </code></pre> <p>I am also interested in what you use to decode the json into an array/object structure.</p> <p>Help is very appreciated. </p>
[ { "answer_id": 158838, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 3, "selected": false, "text": "Dim yourData As String() = { \"Hello\", \"World\" }\nDim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer\nDim jsonString as String = jsonSerialiser.Serialize(yourData)\n" }, { "answer_id": 865220, "author": "aleemb", "author_id": 50475, "author_profile": "https://Stackoverflow.com/users/50475", "pm_score": 2, "selected": false, "text": "Person person = new Person();\n\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nString json = serializer.Serialize(person);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2859/" ]
158,836
<p>what is a good way to select a random element from a map? C++. It is my understanding that maps don't have random access iterators. The key is a long long and the map is sparsely populated. </p>
[ { "answer_id": 158865, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 6, "selected": false, "text": "map<...> MyMap;\niterator item = MyMap.begin();\nstd::advance( item, random_0_to_n(MyMap.size()) );\n" }, { "answer_id": 158939, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 4, "selected": false, "text": "map<...> MyMap;\nvector<...> MyVecOfKeys; // <-- add keys to this when added to the map.\n\nmap<...>::key_type key = MyVecOfKeys[ random_0_to_n(MyVecOfKeys.size()) ];\nmap<...>::data_type value = MyMap[ key ];\n" }, { "answer_id": 163897, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "import random\nimport time\n\n# populate map by some stuff for testing\nm = dict((i*i, i) for i in range(3))\n# copy map to vector\nv = m.items()\n# seed PRNG \n# NOTE: this part is present only to reflect C++\nr = random.Random(time.clock()) \n# shuffle vector \nrandom.shuffle(v, r.random)\n# print randomized map elements\nfor e in v:\n print \"%s:%s\" % e, \nprint\n #include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random.hpp>\n\nint main()\n{\n using namespace std;\n using namespace boost;\n using namespace boost::posix_time;\n\n // populate map by some stuff for testing\n typedef map<long long, int> Map;\n Map m;\n for (int i = 0; i < 3; ++i)\n m[i * i] = i;\n\n // copy map to vector\n#ifndef OPERATE_ON_KEY\n typedef vector<pair<Map::key_type, Map::mapped_type> > Vector;\n Vector v(m.begin(), m.end());\n#else\n typedef vector<Map::key_type> Vector;\n Vector v;\n v.reserve(m.size());\n BOOST_FOREACH( Map::value_type p, m )\n v.push_back(p.first);\n#endif // OPERATE_ON_KEY\n\n // make PRNG\n ptime now(microsec_clock::local_time());\n ptime midnight(now.date());\n time_duration td = now - midnight;\n mt19937 gen(td.ticks()); // seed the generator with raw number of ticks\n random_number_generator<mt19937, \n Vector::iterator::difference_type> rng(gen);\n\n // shuffle vector\n // rng(n) must return a uniformly distributed integer in the range [0, n)\n random_shuffle(v.begin(), v.end(), rng);\n\n // print randomized map elements\n BOOST_FOREACH( Vector::value_type e, v )\n#ifndef OPERATE_ON_KEY\n cout << e.first << \":\" << e.second << \" \";\n#else\n cout << e << \" \";\n#endif // OPERATE_ON_KEY\n cout << endl;\n}\n" }, { "answer_id": 169254, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": false, "text": "map<K, V> const original;\n...\n\n// construct index-keyed lookup map \nmap<unsigned, map<K, V>::const_iterator> fast_random_lookup;\nmap<K, V>::const_iterator it = original.begin(), itEnd = original.end();\nfor (unsigned i = 0; it != itEnd; ++it, ++i) {\n fast_random_lookup[i] = it;\n}\n\n// lookup random value\nV v = *fast_random_lookup[random_0_to_n(original.size())];\n" }, { "answer_id": 57742495, "author": "Matheus Toniolli", "author_id": 8043030, "author_profile": "https://Stackoverflow.com/users/8043030", "pm_score": 0, "selected": false, "text": "std::random_device dev;\nstd::mt19937_64 rng(dev());\n\nstd::uniform_int_distribution<size_t> idDist(0, elements.size() - 1);\nauto elementId= elements.begin();\nstd::advance(elementId, idDist(rng));\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264/" ]
158,848
<p>I'm pulling my hair out on what should be an insanely simple problem. We are running WebSphere IHS (Apache) through an F5 BigIP. BigIP is doing the https translation for us. Our url (changed for web, not valid) is <a href="https://superniftyserver.com/lawson/portal" rel="noreferrer">https://superniftyserver.com/lawson/portal</a>.</p> <p>When someone types in just that without the slash after portal, Apache assumes "portal" to be a file and not a directory. When Apache finds out what it is, it sends the 301 Permanent Redirect. But since Apache knows only http, it sends the URL as <a href="http://superniftyserver.com/lawson/portal/" rel="noreferrer">http://superniftyserver.com/lawson/portal/</a> which then creates problems.</p> <p>So I tried a server level httpd.conf change for mod_rewrite, this is one of the dozens of combinations I've tried.</p> <p>RewriteEngine on RewriteRule ^/lawson/portal(.*) /lawson/portal/$1</p> <p>I also tried RewriteRule ^/lawson/portal$ /lawson/portal/</p> <p>Among many other things... What am I missing? </p>
[ { "answer_id": 158903, "author": "Tanj", "author_id": 4275, "author_profile": "https://Stackoverflow.com/users/4275", "pm_score": 0, "selected": false, "text": "LoadModule rewrite_module modules/mod_rewrite.so\n" }, { "answer_id": 4473740, "author": "Christoph Trautwein", "author_id": 546408, "author_profile": "https://Stackoverflow.com/users/546408", "pm_score": 2, "selected": false, "text": "# Trailing slash problem\nRewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -d\nRewriteRule ^(.+[^/])$ https://<t:sitename/>$1/ [redirect,last]\n" }, { "answer_id": 72818769, "author": "Pit", "author_id": 1392299, "author_profile": "https://Stackoverflow.com/users/1392299", "pm_score": 0, "selected": false, "text": "RewriteEngine on \nRewriteCond %{REQUEST_URI} ^/lawson/portal$ RewriteRule ^(.*)$ https://superniftyserver.com/lawson/portal/ [R=301,L]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
158,856
<p>Is there a way to have a file that is modified / touched whenever the WC is updated to a new revision? Or, as the second-best option, whenever <code>svn update</code> is executed?</p> <p>Here's the motivation: I want to have the SVN revision number inside my executable. So I have to run SubWCRev as part of the build. The output file of SubWCRev is re-created every time, even if the revision number has not changed. This means that the exe is linked on every build, even if nothing has changed. I want it to be linked only as needed.</p>
[ { "answer_id": 158899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "fc REM ***UNTESTED***\nFC temp.rev curr.rev | FIND \"FC: no dif\" > nul \nIF NOT ERRORLEVEL 1 COPY /Y temp.rev curr.rev\nDEL temp.rev\n .hg/dirstate" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7224/" ]
158,864
<p>I've read and followed <a href="http://developer.yahoo.com/yui/menu/" rel="nofollow noreferrer">YUI's tutorial</a> for subscribing to Menu events. I also looked through the API and bits of the code for Menu, MenuBar, and Custom Events, but the following <em>refuses</em> to work</p> <pre><code>// oMenuBar is a MenuBar instance with submenus var buyMenu = oMenuBar.getSubmenus()[1]; // this works buyMenu.subscribe('show', onShow, {foo: 'bar'}, false); // using the subscribe method doesn't work buyMenu.subscribe('mouseOver', onMouseOver, {foo: 'bar'}, false); // manually attaching a listener doesn't work YAHOO.util.Event.addListener(buyMenu, 'mouseOver', onMouseOver); // http://developer.yahoo.com/yui/docs/YAHOO.widget.Menu.html#event_keyPressEvent // there is a keyPress Event, but no spelling of it will trigger the handler buyMenu.subscribe('keypress', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keypressed', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keyPressed', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keyPress', onShow, {foo: 'bar'}, false); </code></pre> <p>Functionally, I'm trying to attach a keyPress listener for each submenu of the MenuBar. I do not want to add Bubbling library as a dependency.</p>
[ { "answer_id": 161550, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "oMenu.subscribe('keypress', function () { alert(\"I'm your friendly neighborhood keypress listener.\")});\n Menu keypress" }, { "answer_id": 189492, "author": "Adam Peck", "author_id": 26658, "author_profile": "https://Stackoverflow.com/users/26658", "pm_score": 0, "selected": false, "text": "var onShow = function()\n{\n alert(\"Click!\");\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13200/" ]
158,889
<p>I'm writing an application which reads large arrays of floats and performs some simple operations with them. I'm using floats, because I thought it'd be faster than doubles, but after doing some research I've found that there's some confusion about this topic. Can anyone elaborate on this?</p>
[ { "answer_id": 4610390, "author": "CReeK", "author_id": 564742, "author_profile": "https://Stackoverflow.com/users/564742", "pm_score": 2, "selected": false, "text": "double\n-----------------------------\n1 core = 990 ms\n4 cores = 340 ms\n6 cores = 282 ms\n8 cores = 250 ms\n\nfloat\n-----------------------------\n1 core = 992 ms\n4 cores = 340 ms\n6 cores = 282 ms\n8 cores = 250 ms\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
158,893
<p>How do I limit the types of HTML that a user can input into a textbox? I'm running a small forum using some custom software that I'm beta testing, but I need to know how to limit the HTML input. Any suggestions?</p>
[ { "answer_id": 158904, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "find open tag (<)\nif contents != allowed tag, remove tag (from <..>)\n" }, { "answer_id": 158916, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "img" }, { "answer_id": 269887, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 0, "selected": false, "text": "<?php\n$text = '<p>Test paragraph.</p><!-- Comment --> <a href=\"#fragment\">Other text</a>';\necho strip_tags($text);\necho \"\\n\";\n\n// Allow <p> and <a>\necho strip_tags($text, '<p><a>');\n?>\n Test paragraph. Other text\n<p>Test paragraph.</p> <a href=\"#fragment\">Other text</a>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]
158,895
<p>What needs to be done to have your .NET application show up in Window's system tray as icon?</p> <p>And how do you handle mousebutton clicks on said icon?</p>
[ { "answer_id": 158927, "author": "tom.dietrich", "author_id": 15769, "author_profile": "https://Stackoverflow.com/users/15769", "pm_score": 6, "selected": true, "text": "Private Sub frmMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize\n If Me.WindowState = FormWindowState.Minimized Then\n Me.ShowInTaskbar = False\n Else\n Me.ShowInTaskbar = True\n End If\nEnd Sub\n\nPrivate Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick\n Me.WindowState = FormWindowState.Normal\nEnd Sub\n Me.NotifyIcon1.ShowBalloonTip(3000, \"This is a notification title!!\", \"This is notification text.\", ToolTipIcon.Info)\n" }, { "answer_id": 49617320, "author": "VoteCoffee", "author_id": 848419, "author_profile": "https://Stackoverflow.com/users/848419", "pm_score": 1, "selected": false, "text": "Visible = False Private Sub Form_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize\n If Me.WindowState = FormWindowState.Minimized Then\n Hide()\n NotifyIcon1.Visible = True\n NotifyIcon1.ShowBalloonTip(3000, NotifyIcon1.Text, \"Minimized to tray\", ToolTipIcon.Info)\n End If\nEnd Sub\n\nPrivate Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick\n Show()\n Me.WindowState = FormWindowState.Normal\n Me.Activate()\n NotifyIcon1.Visible = False\nEnd Sub\n\nPrivate Sub Form_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing\n NotifyIcon1.Visible = False\n Dim index As Integer\n While index < My.Application.OpenForms.Count\n If My.Application.OpenForms(index) IsNot Me Then\n My.Application.OpenForms(index).Close()\n End If\n index += 1\n End While\nEnd Sub\n Private Sub Form_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate\n Me.Close()\nEnd Sub\n\nPrivate Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ContextMenuStrip1.Show(Cursor.Position)\n Me.Left = ContextMenuStrip1.Left + 1\n Me.Top = ContextMenuStrip1.Top + 1\nEnd Sub\n\nPrivate Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click\n MainForm.NotifyIcon1.Visible = False\n End\nEnd Sub\n TrayIconMenuForm Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick\n Select Case e.Button\n Case Windows.Forms.MouseButtons.Left\n Show()\n Me.WindowState = FormWindowState.Normal\n Me.Activate()\n NotifyIcon1.Visible = False\n Case Windows.Forms.MouseButtons.Right\n TrayIconMenuForm.Show() 'Shows the Form that is the parent of \"traymenu\"\n TrayIconMenuForm.Activate() 'Set the Form to \"Active\", that means that that will be the \"selected\" window\n TrayIconMenuForm.Width = 1 'Set the Form width to 1 pixel, that is needed because later we will set it behind the \"traymenu\"\n TrayIconMenuForm.Height = 1 'Set the Form Height to 1 pixel, for the same reason as above\n Case Else\n 'Do nothing\n End Select\nEnd Sub\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ]
158,908
<p>How would I upload a file to a webserver using c++ and MFC. We are not using .Net. Would I need to open a socket and do everything myself? If so, where is a good reference to follow?</p>
[ { "answer_id": 209505, "author": "JonDrnek", "author_id": 6701, "author_profile": "https://Stackoverflow.com/users/6701", "pm_score": 2, "selected": false, "text": "DWORD dwTotalRequestLength;\nDWORD dwChunkLength;\nDWORD dwReadLength;\nDWORD dwResponseLength;\nCHttpFile* pHTTP = NULL;\n\ndwChunkLength = 64 * 1024; \nvoid* pBuffer = malloc(dwChunkLength);\nCFile file ;\n\nCInternetSession session(\"sendFile\");\nCHttpConnection *connection = NULL;\n\ntry {\n//Create the multi-part form data that goes before and after the actual file upload.\n\nCString strHTTPBoundary = _T(\"FFF3F395A90B452BB8BEDC878DDBD152\"); \nCString strPreFileData = MakePreFileData(strHTTPBoundary, file.GetFileName());\nCString strPostFileData = MakePostFileData(strHTTPBoundary);\nCString strRequestHeaders = MakeRequestHeaders(strHTTPBoundary);\ndwTotalRequestLength = strPreFileData.GetLength() + strPostFileData.GetLength() + file.GetLength();\n\nconnection = session.GetHttpConnection(\"www.YOURSITE.com\",NULL,INTERNET_DEFAULT_HTTP_PORT);\n\npHTTP = connection->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T(\"/YOUURL/submit_file.pl\"));\npHTTP->AddRequestHeaders(strRequestHeaders);\npHTTP->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);\n\n//Write out the headers and the form variables\npHTTP->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());\n\n//upload the file.\n\ndwReadLength = -1;\nint length = file.GetLength(); //used to calculate percentage complete.\nwhile (0 != dwReadLength)\n{\n dwReadLength = file.Read(pBuffer, dwChunkLength);\n if (0 != dwReadLength)\n {\n pHTTP->Write(pBuffer, dwReadLength);\n }\n}\n\nfile.Close();\n\n//Finish the upload.\npHTTP->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());\npHTTP->EndRequest(HSR_SYNC);\n\n\n//get the response from the server.\nLPSTR szResponse;\nCString strResponse;\ndwResponseLength = pHTTP->GetLength();\nwhile (0 != dwResponseLength )\n{\n szResponse = (LPSTR)malloc(dwResponseLength + 1);\n szResponse[dwResponseLength] = '\\0';\n pHTTP->Read(szResponse, dwResponseLength);\n strResponse += szResponse;\n free(szResponse);\n dwResponseLength = pHTTP->GetLength();\n}\n\nAfxMessageBox(strResponse);\n\n//close everything up.\npHTTP->Close();\nconnection->Close();\nsession.Close();\n\nCString CHelpRequestUpload::MakeRequestHeaders(CString& strBoundary)\n{\nCString strFormat;\nCString strData;\nstrFormat = _T(\"Content-Type: multipart/form-data; boundary=%s\\r\\n\");\nstrData.Format(strFormat, strBoundary);\nreturn strData;\n}\n\nCString CHelpRequestUpload::MakePreFileData(CString& strBoundary, CString& strFileName)\n{\nCString strFormat;\nCString strData;\n\nstrFormat = _T(\"--%s\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"Content-Disposition: form-data; name=\\\"user\\\"\");\nstrFormat += _T(\"\\r\\n\\r\\n\");\nstrFormat += _T(\"%s\");\nstrFormat += _T(\"\\r\\n\");\n\nstrFormat += _T(\"--%s\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"Content-Disposition: form-data; name=\\\"email\\\"\");\nstrFormat += _T(\"\\r\\n\\r\\n\");\nstrFormat += _T(\"%s\");\nstrFormat += _T(\"\\r\\n\");\n\nstrFormat += _T(\"--%s\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"Content-Disposition: form-data; name=\\\"filename\\\"; filename=\\\"%s\\\"\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"Content-Type: audio/x-flac\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"Content-Transfer-Encoding: binary\");\nstrFormat += _T(\"\\r\\n\\r\\n\");\n\nstrData.Format(strFormat, strBoundary, m_Name, strBoundary, m_Email, strBoundary, strFileName);\n\nreturn strData;\n }\n\nCString CHelpRequestUpload::MakePostFileData(CString& strBoundary)\n{\n\nCString strFormat;\nCString strData;\n\nstrFormat = _T(\"\\r\\n\");\nstrFormat += _T(\"--%s\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"Content-Disposition: form-data; name=\\\"submitted\\\"\");\nstrFormat += _T(\"\\r\\n\\r\\n\");\nstrFormat += _T(\"\");\nstrFormat += _T(\"\\r\\n\");\nstrFormat += _T(\"--%s--\");\nstrFormat += _T(\"\\r\\n\");\n\nstrData.Format(strFormat, strBoundary, strBoundary);\n\nreturn strData;\n\n} \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6701/" ]
158,914
<p>I've got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a <code>UIImage</code> and return a small, square representation of an image, similar to what's seen in the album view of the Photos app. (I know I could use a <code>UIImageView</code> and adjust the crop mode to achieve the same results, but these images are sometimes displayed in <code>UIWebViews</code>).</p> <p>I've started to notice some crashes in this code and I'm a bit stumped. I've got two different theories and I'm wondering if either is on-base.</p> <p>Theory 1) I achieve the cropping by drawing into an offscreen image context of my target size. Since I want the center portion of the image, I set the <code>CGRect</code> argument passed to <code>drawInRect</code> to something that's larger than the bounds of my image context. I was hoping this was Kosher, but am I instead attempting to draw over other memory that I shouldn't be touching?</p> <p>Theory 2) I'm doing all of this in a background thread. I know there are portions of UIKit that are restricted to the main thread. I was assuming / hoping that drawing to an offscreen view wasn't one of these. Am I wrong?</p> <p>(Oh, how I miss <code>NSImage's drawInRect:fromRect:operation:fraction:</code> method.)</p>
[ { "answer_id": 712553, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 8, "selected": false, "text": "CGImageCreateWithImageInRect(CGImageRef, CGRect) CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);\n// or use the UIImage wherever you like\n[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; \nCGImageRelease(imageRef);\n" }, { "answer_id": 5467603, "author": "Jordan", "author_id": 640840, "author_profile": "https://Stackoverflow.com/users/640840", "pm_score": 3, "selected": false, "text": "CGSize size = [originalImage size];\nint padding = 20;\nint pictureSize = 300;\nint startCroppingPosition = 100;\nif (size.height > size.width) {\n pictureSize = size.width - (2.0 * padding);\n startCroppingPosition = (size.height - pictureSize) / 2.0; \n} else {\n pictureSize = size.height - (2.0 * padding);\n startCroppingPosition = (size.width - pictureSize) / 2.0;\n}\n// WTF: Don't forget that the CGImageCreateWithImageInRect believes that \n// the image is 180 rotated, so x and y are inverted, same for height and width.\nCGRect cropRect = CGRectMake(startCroppingPosition, padding, pictureSize, pictureSize);\nCGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);\nUIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:originalImage.imageOrientation];\n[m_photoView setImage:newImage];\nCGImageRelease(imageRef);\n" }, { "answer_id": 7704399, "author": "Vilém Kurz", "author_id": 1379833, "author_profile": "https://Stackoverflow.com/users/1379833", "pm_score": 6, "selected": false, "text": "@implementation UIImage (Crop)\n\n- (UIImage *)crop:(CGRect)rect {\n\n rect = CGRectMake(rect.origin.x*self.scale, \n rect.origin.y*self.scale, \n rect.size.width*self.scale, \n rect.size.height*self.scale); \n\n CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);\n UIImage *result = [UIImage imageWithCGImage:imageRef \n scale:self.scale \n orientation:self.imageOrientation]; \n CGImageRelease(imageRef);\n return result;\n}\n\n@end\n UIImage *imageToCrop = <yourImageToCrop>;\nCGRect cropRect = <areaYouWantToCrop>; \n\n//for example\n//CGRectMake(0, 40, 320, 100);\n\nUIImage *croppedImage = [imageToCrop crop:cropRect];\n" }, { "answer_id": 8443937, "author": "Arne", "author_id": 1089491, "author_profile": "https://Stackoverflow.com/users/1089491", "pm_score": 7, "selected": false, "text": "- (UIImage *)crop:(CGRect)rect {\n if (self.scale > 1.0f) {\n rect = CGRectMake(rect.origin.x * self.scale,\n rect.origin.y * self.scale,\n rect.size.width * self.scale,\n rect.size.height * self.scale);\n }\n\n CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);\n UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];\n CGImageRelease(imageRef);\n return result;\n}\n" }, { "answer_id": 10185736, "author": "Golden", "author_id": 1299933, "author_profile": "https://Stackoverflow.com/users/1299933", "pm_score": 1, "selected": false, "text": "- (UIImage *)getSubImage:(CGRect) rect{\n CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);\n CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));\n\n UIGraphicsBeginImageContext(smallBounds.size);\n CGContextRef context = UIGraphicsGetCurrentContext();\n CGContextDrawImage(context, smallBounds, subImageRef);\n UIImage* smallImg = [UIImage imageWithCGImage:subImageRef];\n UIGraphicsEndImageContext();\n\n return smallImg;\n}\n" }, { "answer_id": 14712184, "author": "Sergii Rudchenko", "author_id": 498067, "author_profile": "https://Stackoverflow.com/users/498067", "pm_score": 6, "selected": false, "text": "inline double rad(double deg)\n{\n return deg / 180.0 * M_PI;\n}\n\nUIImage* UIImageCrop(UIImage* img, CGRect rect)\n{\n CGAffineTransform rectTransform;\n switch (img.imageOrientation)\n {\n case UIImageOrientationLeft:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);\n break;\n case UIImageOrientationRight:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);\n break;\n case UIImageOrientationDown:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);\n break;\n default:\n rectTransform = CGAffineTransformIdentity;\n };\n rectTransform = CGAffineTransformScale(rectTransform, img.scale, img.scale);\n\n CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], CGRectApplyAffineTransform(rect, rectTransform));\n UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation:img.imageOrientation];\n CGImageRelease(imageRef);\n return result;\n}\n" }, { "answer_id": 18602671, "author": "colinta", "author_id": 138505, "author_profile": "https://Stackoverflow.com/users/138505", "pm_score": 5, "selected": false, "text": "CGImage image.CGImage UIImage CIImage CIFilter UIImage* crop(UIImage *image, rect) {\n UIGraphicsBeginImageContextWithOptions(rect.size, false, [image scale]);\n [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];\n cropped_image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n return cropped_image;\n}\n" }, { "answer_id": 21041900, "author": "Matthieu Rouif", "author_id": 984192, "author_profile": "https://Stackoverflow.com/users/984192", "pm_score": 0, "selected": false, "text": "CGFloat minimumSide = fminf(image.size.width, image.size.height);\nCGFloat finalSquareSize = 600.;\n\n//create new drawing context for right size\nCGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);\nCGFloat scalingRatio = 640.0/minimumSide;\nUIGraphicsBeginImageContext(rect.size);\n\n//draw\n[image drawInRect:CGRectMake((minimumSide - photo.size.width)*scalingRatio/2., (minimumSide - photo.size.height)*scalingRatio/2., photo.size.width*scalingRatio, photo.size.height*scalingRatio)];\n\nUIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();\n\nUIGraphicsEndImageContext();\n" }, { "answer_id": 25293588, "author": "awolf", "author_id": 160985, "author_profile": "https://Stackoverflow.com/users/160985", "pm_score": 5, "selected": false, "text": "- (UIImage *)croppedImageInRect:(CGRect)rect\n{\n double (^rad)(double) = ^(double deg) {\n return deg / 180.0 * M_PI;\n };\n\n CGAffineTransform rectTransform;\n switch (self.imageOrientation) {\n case UIImageOrientationLeft:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -self.size.height);\n break;\n case UIImageOrientationRight:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -self.size.width, 0);\n break;\n case UIImageOrientationDown:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -self.size.width, -self.size.height);\n break;\n default:\n rectTransform = CGAffineTransformIdentity;\n };\n rectTransform = CGAffineTransformScale(rectTransform, self.scale, self.scale);\n\n CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], CGRectApplyAffineTransform(rect, rectTransform));\n UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];\n CGImageRelease(imageRef);\n\n return result;\n}\n" }, { "answer_id": 25824454, "author": "Maxim Shoustin", "author_id": 1631379, "author_profile": "https://Stackoverflow.com/users/1631379", "pm_score": 6, "selected": false, "text": "func cropImage(imageToCrop:UIImage, toRect rect:CGRect) -> UIImage{\n \n let imageRef:CGImage = imageToCrop.cgImage!.cropping(to: rect)!\n let cropped:UIImage = UIImage(cgImage:imageRef)\n return cropped\n}\n\n\nlet imageTop:UIImage = UIImage(named:\"one.jpg\")! // add validation\n CGRectMake CGRect @rob mayoff func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {\n return CGRect(x: x, y: y, width: width, height: height)\n}\n if var image:UIImage = UIImage(named:\"one.jpg\"){\n let croppedImage = cropImage(imageToCrop: image, toRect: CGRectMake(\n image.size.width/4,\n 0,\n image.size.width/2,\n image.size.height)\n )\n}\n" }, { "answer_id": 28085176, "author": "Bhushan_pawar", "author_id": 2273312, "author_profile": "https://Stackoverflow.com/users/2273312", "pm_score": 1, "selected": false, "text": " (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {\n double ratio;\n double delta;\n CGPoint offset;\n\n //make a new square size, that is the resized imaged width\n CGSize sz = CGSizeMake(newSize.width, newSize.width);\n\n //figure out if the picture is landscape or portrait, then\n //calculate scale factor and offset\n if (image.size.width > image.size.height) {\n ratio = newSize.width / image.size.width;\n delta = (ratio*image.size.width - ratio*image.size.height);\n offset = CGPointMake(delta/2, 0);\n } else {\n ratio = newSize.width / image.size.height;\n delta = (ratio*image.size.height - ratio*image.size.width);\n offset = CGPointMake(0, delta/2);\n }\n\n //make the final clipping rect based on the calculated values\n CGRect clipRect = CGRectMake(-offset.x, -offset.y,\n (ratio * image.size.width) + delta,\n (ratio * image.size.height) + delta);\n\n\n //start a new context, with scale factor 0.0 so retina displays get\n //high quality image\n if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {\n UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);\n } else {\n UIGraphicsBeginImageContext(sz);\n }\n UIRectClip(clipRect);\n [image drawInRect:clipRect];\n UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n\n return newImage;\n}\n" }, { "answer_id": 29294333, "author": "King-Wizard", "author_id": 1110914, "author_profile": "https://Stackoverflow.com/users/1110914", "pm_score": 2, "selected": false, "text": "private func squareCropImageToSideLength(let sourceImage: UIImage,\n let sideLength: CGFloat) -> UIImage {\n // input size comes from image\n let inputSize: CGSize = sourceImage.size\n\n // round up side length to avoid fractional output size\n let sideLength: CGFloat = ceil(sideLength)\n\n // output size has sideLength for both dimensions\n let outputSize: CGSize = CGSizeMake(sideLength, sideLength)\n\n // calculate scale so that smaller dimension fits sideLength\n let scale: CGFloat = max(sideLength / inputSize.width,\n sideLength / inputSize.height)\n\n // scaling the image with this scale results in this output size\n let scaledInputSize: CGSize = CGSizeMake(inputSize.width * scale,\n inputSize.height * scale)\n\n // determine point in center of \"canvas\"\n let center: CGPoint = CGPointMake(outputSize.width/2.0,\n outputSize.height/2.0)\n\n // calculate drawing rect relative to output Size\n let outputRect: CGRect = CGRectMake(center.x - scaledInputSize.width/2.0,\n center.y - scaledInputSize.height/2.0,\n scaledInputSize.width,\n scaledInputSize.height)\n\n // begin a new bitmap context, scale 0 takes display scale\n UIGraphicsBeginImageContextWithOptions(outputSize, true, 0)\n\n // optional: set the interpolation quality.\n // For this you need to grab the underlying CGContext\n let ctx: CGContextRef = UIGraphicsGetCurrentContext()\n CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh)\n\n // draw the source image into the calculated rect\n sourceImage.drawInRect(outputRect)\n\n // create new image from bitmap context\n let outImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()\n\n // clean up\n UIGraphicsEndImageContext()\n\n // pass back new image\n return outImage\n}\n let image: UIImage = UIImage(named: \"Image.jpg\")!\nlet squareImage: UIImage = self.squareCropImageToSideLength(image, sideLength: 320)\nself.myUIImageView.image = squareImage\n" }, { "answer_id": 30403863, "author": "Epic Byte", "author_id": 2158465, "author_profile": "https://Stackoverflow.com/users/2158465", "pm_score": 3, "selected": false, "text": "extension UIImage {\n func crop(var rect: CGRect) -> UIImage {\n rect.origin.x*=self.scale\n rect.origin.y*=self.scale\n rect.size.width*=self.scale\n rect.size.height*=self.scale\n\n let imageRef = CGImageCreateWithImageInRect(self.CGImage, rect)\n let image = UIImage(CGImage: imageRef, scale: self.scale, orientation: self.imageOrientation)!\n return image\n }\n}\n" }, { "answer_id": 32787294, "author": "MuniekMg", "author_id": 3816679, "author_profile": "https://Stackoverflow.com/users/3816679", "pm_score": 2, "selected": false, "text": "var image:UIImage = ...\n\nlet img = CIImage(image: image)!.imageByCroppingToRect(rect)\nimage = UIImage(CIImage: img, scale: 1, orientation: image.imageOrientation)\n" }, { "answer_id": 35075745, "author": "Steven Wong", "author_id": 5176302, "author_profile": "https://Stackoverflow.com/users/5176302", "pm_score": 1, "selected": false, "text": "-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect\n{\n CGSize cropSize = rect.size;\n CGFloat widthScale = image.size.width/self.imageViewOriginal.bounds.size.width;\n CGFloat heightScale = image.size.height/self.imageViewOriginal.bounds.size.height;\n cropSize = CGSizeMake(rect.size.width*widthScale, \n rect.size.height*heightScale);\n CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale,\n rect.origin.y*heightScale);\n rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, cropSize.height);\n CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);\n UIImage *croppedImage = [UIImage imageWithCGImage:subImage];\n CGImageRelease(subImage);\n\n return croppedImage;\n}\n" }, { "answer_id": 35085214, "author": "Steven Wong", "author_id": 5176302, "author_profile": "https://Stackoverflow.com/users/5176302", "pm_score": 0, "selected": false, "text": " -(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect\n {\n CGSize cropSize = rect.size;\n CGFloat widthScale = \n image.size.width/self.imageViewOriginal.bounds.size.width;\n CGFloat heightScale = \n image.size.height/self.imageViewOriginal.bounds.size.height;\n cropSize = CGSizeMake(rect.size.width*widthScale, \n rect.size.height*heightScale);\n CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale, \n rect.origin.y*heightScale);\n rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, \n cropSize.height);\n CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);\n UIImage *croppedImage = [UIImage imageWithCGImage:subImage];\n CGImageRelease(subImage);\n return croppedImage;\n" }, { "answer_id": 38060768, "author": "NoodleOfDeath", "author_id": 409958, "author_profile": "https://Stackoverflow.com/users/409958", "pm_score": 1, "selected": false, "text": "CIImage CIImage public extension UIImage {\n func imageByCroppingToRect(rect: CGRect) -> UIImage? {\n if let image = CGImageCreateWithImageInRect(self.CGImage, rect) {\n return UIImage(CGImage: image)\n } else if let image = (self.CIImage)?.imageByCroppingToRect(rect) {\n return UIImage(CIImage: image)\n }\n return nil\n }\n}\n" }, { "answer_id": 40422054, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 4, "selected": false, "text": "extension UIImage {\n func crop(rect: CGRect) -> UIImage? {\n var scaledRect = rect\n scaledRect.origin.x *= scale\n scaledRect.origin.y *= scale\n scaledRect.size.width *= scale\n scaledRect.size.height *= scale\n guard let imageRef: CGImage = cgImage?.cropping(to: scaledRect) else {\n return nil\n }\n return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)\n }\n}\n" }, { "answer_id": 43579401, "author": "voidref", "author_id": 235808, "author_profile": "https://Stackoverflow.com/users/235808", "pm_score": 1, "selected": false, "text": "func cropping(to rect: CGRect) -> UIImage? {\n\n if let cgCrop = cgImage?.cropping(to: rect) {\n return UIImage(cgImage: cgCrop)\n }\n else if let ciCrop = ciImage?.cropping(to: rect) {\n return UIImage(ciImage: ciCrop)\n }\n\n return nil\n}\n" }, { "answer_id": 44801633, "author": "Linh Nguyen", "author_id": 1720559, "author_profile": "https://Stackoverflow.com/users/1720559", "pm_score": 1, "selected": false, "text": "-(UIImage*)cropImage:(CGRect)rect{\n\n UIGraphicsBeginImageContextWithOptions(rect.size, false, [self scale]);\n [self drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];\n UIImage* cropped_image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n return cropped_image;\n}\n" }, { "answer_id": 48110726, "author": "Mark Leonard", "author_id": 234394, "author_profile": "https://Stackoverflow.com/users/234394", "pm_score": 5, "selected": false, "text": "awolf public extension UIImage {\n func croppedImage(inRect rect: CGRect) -> UIImage {\n let rad: (Double) -> CGFloat = { deg in\n return CGFloat(deg / 180.0 * .pi)\n }\n var rectTransform: CGAffineTransform\n switch imageOrientation {\n case .left:\n let rotation = CGAffineTransform(rotationAngle: rad(90))\n rectTransform = rotation.translatedBy(x: 0, y: -size.height)\n case .right:\n let rotation = CGAffineTransform(rotationAngle: rad(-90))\n rectTransform = rotation.translatedBy(x: -size.width, y: 0)\n case .down:\n let rotation = CGAffineTransform(rotationAngle: rad(-180))\n rectTransform = rotation.translatedBy(x: -size.width, y: -size.height)\n default:\n rectTransform = .identity\n }\n rectTransform = rectTransform.scaledBy(x: scale, y: scale)\n let transformedRect = rect.applying(rectTransform)\n let imageRef = cgImage!.cropping(to: transformedRect)!\n let result = UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)\n return result\n }\n}\n" }, { "answer_id": 53079776, "author": "luhuiya", "author_id": 932672, "author_profile": "https://Stackoverflow.com/users/932672", "pm_score": 2, "selected": false, "text": "import UIKit\n\nextension UIImage {\n func cropImage(toRect rect: CGRect) -> UIImage? {\n if let imageRef = self.cgImage?.cropping(to: rect) {\n return UIImage(cgImage: imageRef)\n }\n return nil\n }\n}\n" }, { "answer_id": 56579249, "author": "huync", "author_id": 1639366, "author_profile": "https://Stackoverflow.com/users/1639366", "pm_score": 1, "selected": false, "text": "extension UIImage {\n func cropped(rect: CGRect) -> UIImage? {\n guard let cgImage = cgImage else { return nil }\n\n UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)\n let context = UIGraphicsGetCurrentContext()\n\n context?.translateBy(x: 0.0, y: self.size.height)\n context?.scaleBy(x: 1.0, y: -1.0)\n context?.draw(cgImage, in: CGRect(x: rect.minX, y: rect.minY, width: self.size.width, height: self.size.height), byTiling: false)\n\n\n let croppedImage = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n\n return croppedImage\n }\n}\n" }, { "answer_id": 70269335, "author": "jmrueda", "author_id": 1929988, "author_profile": "https://Stackoverflow.com/users/1929988", "pm_score": 0, "selected": false, "text": "public extension UIImage {\n func cropped(rect: CGRect) -> UIImage? {\n if let image = self.cgImage!.cropping(to: rect) {\n return UIImage(cgImage: image)\n } else if let image = (self.ciImage)?.cropped(to: rect) {\n return UIImage(ciImage: image)\n }\n return nil\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24168/" ]
158,933
<p>I have an array of characters that are Points and I want to take any character and be able to loop through that array and find the top 3 closest (using Point.distance) neighbors. Could anyone give me an idea of how to do this?</p>
[ { "answer_id": 159294, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "package {\n\n import flash.geom.Point;\n import flash.display.Sprite;\n\n public class TestCase extends Sprite {\n\n public function TestCase() {\n // some data to test with\n var pointList:Array = new Array();\n pointList.push(new Point(0, 0));\n pointList.push(new Point(0, 0));\n pointList.push(new Point(0, 0));\n pointList.push(new Point(1, 2));\n pointList.push(new Point(9, 9));\n\n // the point we want to test against\n var referencePoint:Point = new Point(10, 10);\n\n var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);\n\n trace(\"referencePoint is at\", referencePoint.x, referencePoint.y);\n for each(var result:Object in resultPoints) {\n trace(\"Point is at:\", result.point.x, \", \", result.point.y, \" that's \", result.distance, \" units away\");\n }\n }\n\n }\n\n}\n package {\n\n import flash.geom.Point;\n\n public class PointTester {\n\n public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{\n\n // this array will hold the results\n var resultList:Array = new Array();\n\n // loop over each point in the test data\n for each (var testPoint:Point in pointList) {\n\n // we store the distance between the two in a temporary variable\n var tempDistance:Number = getDistance(testPoint, referencePoint);\n\n // if the list is shorter than the maximum length we don't need to do any distance checking\n // if it's longer we compare the distance to the last point in the list, if it's closer we add it\n if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) {\n\n // we store the testing point and it's distance to the reference point in an object\n var tmpObject:Object = { distance : tempDistance, point : testPoint };\n // and push that onto the array\n resultList.push(tmpObject);\n\n // then we sort the array, this way we don't need to compare the distance to any other point than\n // the last one in the list\n resultList.sortOn(\"distance\", Array.NUMERIC );\n\n // and we make sure the list is kept at at the proper number of entries\n while (resultList.length > maxCount) resultList.pop();\n }\n }\n\n return resultList;\n }\n\n public static function getDistance(point1:Point, point2:Point):Number {\n var x:Number = point1.x - point2.x;\n var y:Number = point1.y - point2.y;\n return Math.sqrt(x * x + y * y);\n }\n }\n}\n" }, { "answer_id": 196098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "return x*x + y*y; return Math.sqrt( x * x + y * y );" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
158,940
<p>Is it possible to reset the alternate buffer in a vim session to what it was previously?</p> <p>By alternate buffer, I mean the one that is referred to by #, i.e. the one that is displayed when you enter cntl-^.</p> <p>Say I've got two files open main.c and other.c and :ls gives me:</p> <pre><code> 1 %a "main.c" lines 27 2 # "other.c" lines 56 </code></pre> <p>Say I open another file, e.g. refer.c, :ls will now give me:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 3 # "refer.c" lines 125 </code></pre> <p>If I delete the buffer containing refer.c, :ls now shows:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 </code></pre> <p>But if I do a cntl-^, refer.c will be displayed again!</p> <p>Is there some way to get vim to reset the alternate buffer back to what it last was automatically? A "history" of alternate buffers?</p> <p>Or am I stuck with doing a :2 b to reload other.c into the alternate buffer?</p> <p>Or maybe there is a good reason for this behaviour?</p>
[ { "answer_id": 60732165, "author": "NeilG", "author_id": 134044, "author_profile": "https://Stackoverflow.com/users/134044", "pm_score": 2, "selected": false, "text": ":bd :ls! :buffers! u :bw CTRL-^ No alternate file :b2 :buffers :buffers! :buffers :bd :buffers! :b<num>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2974/" ]
158,943
<p>I know that services like my.yahoo.com allow you to add content from RSS feeds to your personal page, but in general they are links which draw the user to the site which provided the feed. What are the legalities and implications of using RSS feeds as a data source for a site which repackages the data so as to be unrecognizable that it came from said source.</p> <hr> <p>Does credit need to be given? It is a copyright violation? What is ethical?</p> <hr> <p>What if credit is stated? Does this change your opinion? Does permission need to be granted?</p>
[ { "answer_id": 159070, "author": "AdamKG", "author_id": 16361, "author_profile": "https://Stackoverflow.com/users/16361", "pm_score": 2, "selected": false, "text": "GET /feed/ HTTP 1.0 200 OK 403 Forbidden" }, { "answer_id": 179687, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 1, "selected": false, "text": "<iframe src='www.stackoverflow.com'> </iframe>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
158,966
<p>I'm thinking floats. For the record I'm also using NHibernate.</p>
[ { "answer_id": 158972, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 6, "selected": true, "text": "decimal" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ]
158,968
<p>Could someone explain to me in simple terms the easiest way to change the indentation behavior of Vim based on the file type? For instance, if I open a Python file it should indent with 2 spaces, but if I open a Powershell script it should use 4 spaces.</p>
[ { "answer_id": 158987, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 6, "selected": false, "text": "autocmd BufRead,BufNewFile *.c,*.h,*.java set noic cin noexpandtab\nautocmd BufRead,BufNewFile *.pl syntax on\n" }, { "answer_id": 158990, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "expandtab :autocmd FileType make set noexpandtab\n" }, { "answer_id": 159065, "author": "graywh", "author_id": 18038, "author_profile": "https://Stackoverflow.com/users/18038", "pm_score": 8, "selected": false, "text": "~/.vim/ftplugin/python.vim: setlocal shiftwidth=2 softtabstop=2 expandtab\n ~/.vimrc filetype plugin indent on\n :h ftplugin ~/.vimrc autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab\n tabstop softtabstop softtabstop" }, { "answer_id": 159066, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 9, "selected": true, "text": ".vim ~/.vim/after/ftplugin/html.vim setlocal shiftwidth=2\nsetlocal tabstop=2\n noexpandtab" }, { "answer_id": 9753182, "author": "Juan Lanus", "author_id": 243303, "author_profile": "https://Stackoverflow.com/users/243303", "pm_score": 3, "selected": false, "text": ":set et :set :retab :set et\n:retab\n :set noet\n:retab\n" }, { "answer_id": 10430773, "author": "Nello", "author_id": 1372382, "author_profile": "https://Stackoverflow.com/users/1372382", "pm_score": 4, "selected": false, "text": "autocmd FileType python set tabstop=8|set shiftwidth=2|set expandtab\nautocmd FileType ruby set tabstop=8|set shiftwidth=2|set expandtab\n" }, { "answer_id": 30114038, "author": "Siwei", "author_id": 445908, "author_profile": "https://Stackoverflow.com/users/445908", "pm_score": 7, "selected": false, "text": "~/.vimrc html/rb js/coffee \" by default, the indent is 2 spaces. \nset shiftwidth=2\nset softtabstop=2\nset tabstop=2\n\n\" for html/rb files, 2 spaces\nautocmd Filetype html setlocal ts=2 sw=2 expandtab\nautocmd Filetype ruby setlocal ts=2 sw=2 expandtab\n\n\" for js/coffee/jade files, 4 spaces\nautocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab\nautocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab\nautocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab\n" }, { "answer_id": 34100528, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 1, "selected": false, "text": "autotab shiftwidth tabstop expandtab gcc -O autotab.c -o autotab" }, { "answer_id": 44338627, "author": "chengbo", "author_id": 619424, "author_profile": "https://Stackoverflow.com/users/619424", "pm_score": 2, "selected": false, "text": "# 4 space indentation for python files\n[*.py]\nindent_style = space\nindent_size = 4\n\n# 2 space indentation for pug templates\n[*.pug]\nindent_size = 2\n" }, { "answer_id": 60470085, "author": "67hz", "author_id": 957805, "author_profile": "https://Stackoverflow.com/users/957805", "pm_score": 3, "selected": false, "text": "autocmd augroup filetype_c\n autocmd!\n :autocmd FileType c setlocal tabstop=2 shiftwidth=2 softtabstop=2 expandtab\n :autocmd FileType c nnoremap <buffer> <localleader>c I/*<space><esc><s-a><space>*/<esc>\naugroup end\n .vimrc autocmd! .vimrc :help augroup" }, { "answer_id": 72359195, "author": "Dzintars", "author_id": 6651080, "author_profile": "https://Stackoverflow.com/users/6651080", "pm_score": 2, "selected": false, "text": "RUNTIMEPATH/ftplugin/*yourfiletype*.lua vim.opt_local.shiftwidth = 2\nvim.opt_local.tabstop = 2\n vim.opt_local.foldmethod = 'marker'\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
158,975
<p>I'm making a request from an <code>UpdatePanel</code> that takes more then 90 seconds. I'm getting this timeout error:</p> <blockquote> <p>Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerTimeoutException: The server request timed out.</p> </blockquote> <p>Does anyone know if there is a way to increase the amount of time before the call times out?</p>
[ { "answer_id": 159004, "author": "ctrlShiftBryan", "author_id": 6161, "author_profile": "https://Stackoverflow.com/users/6161", "pm_score": 4, "selected": false, "text": "<script type=\"text/javascript\"> \n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) { \n if (args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerTimeoutException') { \n args.set_errorHandled(true); \n } \n }); \n </script> \n" }, { "answer_id": 159019, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 8, "selected": true, "text": "AsyncPostBackTimeout=\"300\"\n" }, { "answer_id": 2456211, "author": "narayan", "author_id": 294941, "author_profile": "https://Stackoverflow.com/users/294941", "pm_score": 6, "selected": false, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n . . . \n ScriptManager _scriptMan = ScriptManager.GetCurrent(this);\n _scriptMan.AsyncPostBackTimeout = 36000;\n}\n" }, { "answer_id": 2880261, "author": "rajalingam", "author_id": 346857, "author_profile": "https://Stackoverflow.com/users/346857", "pm_score": 3, "selected": false, "text": "httpRuntime maxRequestLength=\"1024000\" executionTimeout=\"999999\" AsyncPostBackTimeout =\"360000\"" }, { "answer_id": 23948732, "author": "Pradeep atkari", "author_id": 3211873, "author_profile": "https://Stackoverflow.com/users/3211873", "pm_score": 1, "selected": false, "text": "ConnectionTimeout web.config <connectionstrings>\n <add name=\"ConnectionString\" \n connectionstring=\"Database=UKTST1;Server=BRESAWN;uid=\" system.data.sqlclient=\"/><br mode=\" hold=\" /><br mode=\" html=\"> <asp:ToolkitScriptManager runat=\" server=\" AsyncPostBackTimeOut=\" 6000=\"><br mode=\">\n </add>\n</connectionstrings>\n AsyncPostBackTimeout=\"6000\" .aspx <asp:ToolkitScriptManager runat=\"server\" AsyncPostBackTimeOut=\"6000\">\n</asp:ToolkitScriptManager>\n SqlCommand command.CommandTimeout = 30*1000;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
158,986
<p>I am <strong>very</strong> new to the entity framework, so please bear with me...</p> <p>How can I relate two objects from different contexts together?</p> <p>The example below throws the following exception:</p> <blockquote> <p>System.InvalidOperationException: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.</p> </blockquote> <pre><code>void MyFunction() { using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=&gt;p.EmployeeId == 123); er.Roles = GetDefaultRole(); model.SaveChanges(); } } private static Roles GetDefaultRole() { Roles r = null; using (TCPSEntities model = new TCPSEntities()) { r = model.Roles.First(p =&gt; p.RoleId == 1); } return r; } </code></pre> <p>Using one context is not an option because we are using the EF in an ASP.NET application.</p>
[ { "answer_id": 159042, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 5, "selected": true, "text": "void MyFunction()\n{\n using (TCPSEntities model = new TCPSEntities())\n {\n EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);\n er.Roles = GetDefaultRole(model);\n model.SaveChanges();\n }\n\n}\n\nprivate static Roles GetDefaultRole(TCPSEntities model)\n{\n Roles r = null;\n r = model.Roles.First(p => p.RoleId == 1);\n return r;\n}\n" }, { "answer_id": 660093, "author": "Ken Smith", "author_id": 68231, "author_profile": "https://Stackoverflow.com/users/68231", "pm_score": 2, "selected": false, "text": " private static PledgeManagerEntities pledgesEntities;\n public static PledgeManagerEntities PledgeManagerEntities\n {\n get \n {\n if (pledgesEntities == null)\n {\n pledgesEntities = new PledgeManagerEntities();\n }\n return pledgesEntities; \n }\n set { pledgesEntities = value; }\n }\n private PledgeManagerEntities entities = Data.PledgeManagerEntities;\n" }, { "answer_id": 1141399, "author": "Ken Smith", "author_id": 68231, "author_profile": "https://Stackoverflow.com/users/68231", "pm_score": 2, "selected": false, "text": " public void GuestUserTest()\n {\n SlideLincEntities ctx1 = new SlideLincEntities();\n GuestUser user = GuestUser.CreateGuestUser();\n user.UserName = \"Something\";\n ctx1.AddToUser(user);\n ctx1.SaveChanges();\n\n SlideLincEntities ctx2 = new SlideLincEntities();\n ctx1.Detach(user);\n user.UserName = \"Something Else\";\n ctx2.Attach(user);\n ctx2.SaveChanges();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050/" ]
158,993
<p>I need to, preferably in C# - but c++ will do, find a way to filter the list of printers in the windows print dialog for any windows printing.</p> <p>I have come across WinAPIOverride and have figured I am going to have to write my own dll which overrides the method to get the printers list, then filter it and return it. I would then have to inject the dll into all running processes.</p> <p>Can anybody assist me with something that is already developed or perhaps an easier way of accomplishing this? The only way the list of printers comes out is from the API method call and I have even considered modifying the registry, but this will slow down the response of the print dialog box to the point that it would be annoying to the user.</p>
[ { "answer_id": 436837, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 2, "selected": false, "text": " ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access\n objScope.Connect();\n\n SelectQuery selectQuery = new SelectQuery();\n selectQuery.QueryString = \"Select * from win32_Printer\";\n ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);\n ManagementObjectCollection MOC = MOS.Get();\n foreach (ManagementObject mo in MOC) {\n listBox1.Items.Add(mo[\"Name\"].ToString().ToUpper());\n }\n ConnectionOptions objConnection = new ConnectionOptions();\nobjConnection.Username = \"USERNAME\";\nobjConnection.Password = \"PASSWORD\";\nobjConnection.Authority = \"ntlmdomain:DDI\"; //Where DDI is the name of my domain\n// Make sure the user you specified have enough permission to access the resource. \n\nManagementScope objScope = new ManagementScope(@\"\\\\10.0.0.4\\root\\cimv2\",objConnection); //For the local Access\nobjScope.Connect();\n\nSelectQuery selectQuery = new SelectQuery();\nselectQuery.QueryString = \"Select * from win32_Printer\";\nManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);\nManagementObjectCollection MOC = MOS.Get();\nforeach (ManagementObject mo in MOC) {\n listBox1.Items.Add(mo[\"Name\"].ToString().ToUpper());\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
159,006
<p>Is there a way to find the maximum and minimum defined values of an enum in c++?</p>
[ { "answer_id": 159018, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 8, "selected": true, "text": "enum MyPretendEnum\n{\n Apples,\n Oranges,\n Pears,\n Bananas,\n First = Apples,\n Last = Bananas\n};\n First Last" }, { "answer_id": 159023, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 5, "selected": false, "text": "enum Name\n{\n val0,\n val1,\n val2,\n num_values\n};\n num_values" }, { "answer_id": 159081, "author": "Justsalt", "author_id": 13693, "author_profile": "https://Stackoverflow.com/users/13693", "pm_score": 3, "selected": false, "text": "enum {\n eAaa = 1,\n eBbb,\n eCccc,\n eMin = eAaaa,\n eMax = eCccc\n}\n" }, { "answer_id": 161336, "author": "Tiendil", "author_id": 23712, "author_profile": "https://Stackoverflow.com/users/23712", "pm_score": 3, "selected": false, "text": " enum My_enum\n {\n FIRST_VALUE = 0,\n\n MY_VALUE1,\n MY_VALUE2,\n ...\n MY_VALUEN,\n\n LAST_VALUE\n };\n" }, { "answer_id": 4005490, "author": "Wael", "author_id": 485228, "author_profile": "https://Stackoverflow.com/users/485228", "pm_score": -1, "selected": false, "text": "enum Name{val0,val1,val2};\n if(selectedOption>=val0 && selectedOption<=val2){\n\n //code\n}\n" }, { "answer_id": 67642152, "author": "ProXicT", "author_id": 3421618, "author_profile": "https://Stackoverflow.com/users/3421618", "pm_score": 1, "selected": false, "text": "min max enum enum class Fruits { Apples, Oranges, Pears, Bananas };\n\nint main() {\n std::cout << \"Min value for Fruits is \" << EnumMin<Fruits>::value << std::endl; // 0\n std::cout << \"Max value for Fruits is \" << EnumMax<Fruits>::value << std::endl; // 3\n std::cout << \"Name: \" << getName<Fruits, static_cast<Fruits>(0)>().cStr() << std::endl; // Apples\n std::cout << \"Name: \" << getName<Fruits, static_cast<Fruits>(3)>().cStr() << std::endl; // Bananas\n std::cout << \"Name: \" << getName<Fruits, static_cast<Fruits>(99)>().cStr() << std::endl; // (Fruits)99\n}\n" }, { "answer_id": 74377305, "author": "Andrew", "author_id": 11288621, "author_profile": "https://Stackoverflow.com/users/11288621", "pm_score": 0, "selected": false, "text": "#include <magic_enum.hpp>\n...\n \nconst size_t maxValue = static_cast<size_t>(magic_enum::enum_value<MyEnum>(magic_enum::enum_count<MyEnum>() - 1));\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
159,011
<p>Here is my question,</p> <p>Would it be possible, knowing that classic asp support server-side javascript, to be able to generate "server side HTML" to send to the client like Response.write $(page).html()</p> <p>Of course it would be great to use jQuery to do it because it's easy to parse complicated structure and manipulate them.</p> <p>The only problem I can think of that would prevent me from doing this would be that classic asp exposes only 3 objects (response, server, request) and none of them provide "dom building facilities" like the one jQuery uses all the time. How could we possibly create a blank document object?</p> <p><strong>Edit</strong> : I have to agree with you that it's definitely not a good idea performance wise. Let me explain why we would need it.</p> <p>I am actually transforming various JSON feed into complicated, sometimes nested report in HTML. Client side it works really well, even with complicated set and long report.</p> <p>However, some of our client would like to access the "formatted" report using tools like EXCEL (using webquery which are depleted of any javascript). So in that particular case, I would need to be able to response.write the .html() content of what would be the jQuery work.</p>
[ { "answer_id": 166296, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": true, "text": "function XmlWrapper(elem) { this.element = elem; }\nXmlWrapper.prototype.addChild = function(name) {\n var elem = this.element.ownerDocument.createElement(name);\n return new XmlWrapper(this.element.appendChild(elem));\n}\n var dom = Server.CreateObject(\"MSXML2.DOMDocument.3.0\");\ndom.loadXML(\"<html />\");\nvar html = XmlWapper(dom.documentElement);\n\nvar head = html.addChild(\"head\");\nvar body = html.addChild(\"body\");\n\nvar tHead = body.addChild(\"table\").addChild(\"tHead\");\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1775/" ]
159,015
<p>What is the use of a Dispatcher Object in WPF?</p>
[ { "answer_id": 72422140, "author": "user3856437", "author_id": 3856437, "author_profile": "https://Stackoverflow.com/users/3856437", "pm_score": 0, "selected": false, "text": "Dispatcher.Invoke() only the Dispatcher can update the objects in your UI from a non-UI thread public PaginatedObservableCollection<OrderItems> Orders { get; } = new PaginatedObservableCollection<OrderItems>(20);\n\n_eventAggregator.GetEvent<OrderEvent>().Subscribe(orders =>\n{\n MainDispatcher.Invoke(() => AddOrders(orders));\n});\n\nprivate void AddOrders(List<OrderItems> orders)\n{\n foreach (OrderItems item in orders)\n Orders.Add(item);\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2744/" ]
159,017
<p>Is there any way to format a string by name rather than position in C#?</p> <p>In python, I can do something like this example (shamelessly stolen from <a href="http://docs.python.org/lib/typesseq-strings.html" rel="noreferrer">here</a>):</p> <pre><code>&gt;&gt;&gt; print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2} Python has 002 quote types. </code></pre> <p>Is there any way to do this in C#? Say for instance:</p> <pre><code>String.Format("{some_variable}: {some_other_variable}", ...); </code></pre> <p>Being able to do this using a variable name would be nice, but a dictionary is acceptable too.</p>
[ { "answer_id": 159029, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "String.Format(\"{0} has {1} quote types.\", \"C#\", \"1\");\n string MyString = \"{language} has {n} quote types.\";\nMyString = MyString.Replace(\"{language}\", \"C#\").Replace(\"{n}\", \"1\");\n List<KeyValuePair<string, string>> replacements = GetFormatDictionary(); \nforeach (KeyValuePair<string, string> item in replacements)\n{\n MyString = MyString.Replace(item.Key, item.Value);\n}\n replacements.ForEach(delegate(KeyValuePair<string,string>) item) { MyString = MyString.Replace(item.Key, item.Value);});\n MyString" }, { "answer_id": 159095, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": -1, "selected": false, "text": "string language = \"Python\";\nint numquotes = 2;\nstring output = language + \" has \"+ numquotes + \" language types.\";\n" }, { "answer_id": 159126, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 8, "selected": true, "text": "string myString = \"{foo} is {bar} and {yadi} is {yada}\".Inject(o);\n Status.Text = \"{UserName} last logged in at {LastLoginDate}\".FormatWith(user);\n" }, { "answer_id": 159164, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 4, "selected": false, "text": "IFormatProvider IDictionary var Stuff = new Dictionary<string, object> {\n { \"language\", \"Python\" },\n { \"#\", 2 }\n};\nvar Formatter = new DictionaryFormatProvider();\n\n// Interpret {0:x} where {0}=IDictionary and \"x\" is hash key\nConsole.WriteLine string.Format(Formatter, \"{0:language} has {0:#} quote types\", Stuff);\n FormatProviders" }, { "answer_id": 159277, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 3, "selected": false, "text": "Person p = new Person(); \nstring foo = p.ToString(\"{Money:C} {LastName}, {ScottName} {BirthDate}\"); \nAssert.AreEqual(\"$3.43 Hanselman, {ScottName} 1/22/1974 12:00:00 AM\", foo); \n string foo = \"Top result for {Name} was {Results[0].Name}\".FormatWith(student));\n string name = ...;\nDateTime date = ...;\nstring foo = \"{Name} - {Birthday}\".FormatWith(new { Name = name, Birthday = date });\n" }, { "answer_id": 413479, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "var str = \"{foo} {bar} {baz}\".Format(foo=>\"foo\", bar=>2, baz=>new object());\n \"foo 2 System.Object" }, { "answer_id": 4077118, "author": "Doggett", "author_id": 492813, "author_profile": "https://Stackoverflow.com/users/492813", "pm_score": 5, "selected": false, "text": " public string Format(string input, object p)\n {\n foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(p))\n input = input.Replace(\"{\" + prop.Name + \"}\", (prop.GetValue(p) ?? \"(null)\").ToString());\n\n return input;\n }\n Format(\"test {first} and {another}\", new { first = \"something\", another = \"something else\" })\n" }, { "answer_id": 4838761, "author": "Steve Potter", "author_id": 574723, "author_profile": "https://Stackoverflow.com/users/574723", "pm_score": 1, "selected": false, "text": "\"The {Name} family has {Children} children\".Format(new { Children = 4, Name = \"Smith\" })\n public static class AdvancedFormatString\n{\n\n /// <summary>\n /// An advanced version of string.Format. If you pass a primitive object (string, int, etc), it acts like the regular string.Format. If you pass an anonmymous type, you can name the paramters by property name.\n /// </summary>\n /// <param name=\"formatString\"></param>\n /// <param name=\"arg\"></param>\n /// <returns></returns>\n /// <example>\n /// \"The {Name} family has {Children} children\".Format(new { Children = 4, Name = \"Smith\" })\n /// \n /// results in \n /// \"This Smith family has 4 children\n /// </example>\n public static string Format(this string formatString, object arg, IFormatProvider format = null)\n {\n if (arg == null)\n return formatString;\n\n var type = arg.GetType();\n if (Type.GetTypeCode(type) != TypeCode.Object || type.IsPrimitive)\n return string.Format(format, formatString, arg);\n\n var properties = TypeDescriptor.GetProperties(arg);\n return formatString.Format((property) =>\n {\n var value = properties[property].GetValue(arg);\n return Convert.ToString(value, format);\n });\n }\n\n\n public static string Format(this string formatString, Func<string, string> formatFragmentHandler)\n {\n if (string.IsNullOrEmpty(formatString))\n return formatString;\n Fragment[] fragments = GetParsedFragments(formatString);\n if (fragments == null || fragments.Length == 0)\n return formatString;\n\n return string.Join(string.Empty, fragments.Select(fragment =>\n {\n if (fragment.Type == FragmentType.Literal)\n return fragment.Value;\n else\n return formatFragmentHandler(fragment.Value);\n }).ToArray());\n }\n\n\n private static Fragment[] GetParsedFragments(string formatString)\n {\n Fragment[] fragments;\n if ( parsedStrings.TryGetValue(formatString, out fragments) )\n {\n return fragments;\n }\n lock (parsedStringsLock)\n {\n if ( !parsedStrings.TryGetValue(formatString, out fragments) )\n {\n fragments = Parse(formatString);\n parsedStrings.Add(formatString, fragments);\n }\n }\n return fragments;\n }\n\n private static Object parsedStringsLock = new Object();\n private static Dictionary<string,Fragment[]> parsedStrings = new Dictionary<string,Fragment[]>(StringComparer.Ordinal);\n\n const char OpeningDelimiter = '{';\n const char ClosingDelimiter = '}';\n\n /// <summary>\n /// Parses the given format string into a list of fragments.\n /// </summary>\n /// <param name=\"format\"></param>\n /// <returns></returns>\n static Fragment[] Parse(string format)\n {\n int lastCharIndex = format.Length - 1;\n int currFragEndIndex;\n Fragment currFrag = ParseFragment(format, 0, out currFragEndIndex);\n\n if (currFragEndIndex == lastCharIndex)\n {\n return new Fragment[] { currFrag };\n }\n\n List<Fragment> fragments = new List<Fragment>();\n while (true)\n {\n fragments.Add(currFrag);\n if (currFragEndIndex == lastCharIndex)\n {\n break;\n }\n currFrag = ParseFragment(format, currFragEndIndex + 1, out currFragEndIndex);\n }\n return fragments.ToArray();\n\n }\n\n /// <summary>\n /// Finds the next delimiter from the starting index.\n /// </summary>\n static Fragment ParseFragment(string format, int startIndex, out int fragmentEndIndex)\n {\n bool foundEscapedDelimiter = false;\n FragmentType type = FragmentType.Literal;\n\n int numChars = format.Length;\n for (int i = startIndex; i < numChars; i++)\n {\n char currChar = format[i];\n bool isOpenBrace = currChar == OpeningDelimiter;\n bool isCloseBrace = isOpenBrace ? false : currChar == ClosingDelimiter;\n\n if (!isOpenBrace && !isCloseBrace)\n {\n continue;\n }\n else if (i < (numChars - 1) && format[i + 1] == currChar)\n {//{{ or }}\n i++;\n foundEscapedDelimiter = true;\n }\n else if (isOpenBrace)\n {\n if (i == startIndex)\n {\n type = FragmentType.FormatItem;\n }\n else\n {\n\n if (type == FragmentType.FormatItem)\n throw new FormatException(\"Two consequtive unescaped { format item openers were found. Either close the first or escape any literals with another {.\");\n\n //curr character is the opening of a new format item. so we close this literal out\n string literal = format.Substring(startIndex, i - startIndex);\n if (foundEscapedDelimiter)\n literal = ReplaceEscapes(literal);\n\n fragmentEndIndex = i - 1;\n return new Fragment(FragmentType.Literal, literal);\n }\n }\n else\n {//close bracket\n if (i == startIndex || type == FragmentType.Literal)\n throw new FormatException(\"A } closing brace existed without an opening { brace.\");\n\n string formatItem = format.Substring(startIndex + 1, i - startIndex - 1);\n if (foundEscapedDelimiter)\n formatItem = ReplaceEscapes(formatItem);//a format item with a { or } in its name is crazy but it could be done\n fragmentEndIndex = i;\n return new Fragment(FragmentType.FormatItem, formatItem);\n }\n }\n\n if (type == FragmentType.FormatItem)\n throw new FormatException(\"A format item was opened with { but was never closed.\");\n\n fragmentEndIndex = numChars - 1;\n string literalValue = format.Substring(startIndex);\n if (foundEscapedDelimiter)\n literalValue = ReplaceEscapes(literalValue);\n\n return new Fragment(FragmentType.Literal, literalValue);\n\n }\n\n /// <summary>\n /// Replaces escaped brackets, turning '{{' and '}}' into '{' and '}', respectively.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n static string ReplaceEscapes(string value)\n {\n return value.Replace(\"{{\", \"{\").Replace(\"}}\", \"}\");\n }\n\n private enum FragmentType\n {\n Literal,\n FormatItem\n }\n\n private class Fragment\n {\n\n public Fragment(FragmentType type, string value)\n {\n Type = type;\n Value = value;\n }\n\n public FragmentType Type\n {\n get;\n private set;\n }\n\n /// <summary>\n /// The literal value, or the name of the fragment, depending on fragment type.\n /// </summary>\n public string Value\n {\n get;\n private set;\n }\n\n\n }\n\n}\n" }, { "answer_id": 5879647, "author": "wayjet", "author_id": 737437, "author_profile": "https://Stackoverflow.com/users/737437", "pm_score": 2, "selected": false, "text": "private static Regex s_NamedFormatRegex = new Regex(@\"\\{(?!\\{)(?<key>[\\w]+)(:(?<fmt>(\\{\\{|\\}\\}|[^\\{\\}])*)?)?\\}\", RegexOptions.Compiled);\n\npublic static StringBuilder AppendNamedFormat(this StringBuilder builder,IFormatProvider provider, string format, IDictionary<string, object> args)\n{\n if (builder == null) throw new ArgumentNullException(\"builder\");\n var str = s_NamedFormatRegex.Replace(format, (mt) => {\n string key = mt.Groups[\"key\"].Value;\n string fmt = mt.Groups[\"fmt\"].Value;\n object value = null;\n if (args.TryGetValue(key,out value)) {\n return string.Format(provider, \"{0:\" + fmt + \"}\", value);\n } else {\n return mt.Value;\n }\n });\n builder.Append(str);\n return builder;\n}\n\npublic static StringBuilder AppendNamedFormat(this StringBuilder builder, string format, IDictionary<string, object> args)\n{\n if (builder == null) throw new ArgumentNullException(\"builder\");\n return builder.AppendNamedFormat(null, format, args);\n}\n var builder = new StringBuilder();\nbuilder.AppendNamedFormat(\n@\"你好,{Name},今天是{Date:yyyy/MM/dd}, 这是你第{LoginTimes}次登录,积分{Score:{{ 0.00 }}}\",\nnew Dictionary<string, object>() { \n { \"Name\", \"wayjet\" },\n { \"LoginTimes\",18 },\n { \"Score\", 100.4 },\n { \"Date\",DateTime.Now }\n});\n" }, { "answer_id": 7510120, "author": "Pavlo Neiman", "author_id": 164001, "author_profile": "https://Stackoverflow.com/users/164001", "pm_score": 2, "selected": false, "text": "public static string StringFormat(string format, object source)\n{\n var matches = Regex.Matches(format, @\"\\{(.+?)\\}\");\n List<string> keys = (from Match matche in matches select matche.Groups[1].Value).ToList();\n\n return keys.Aggregate(\n format,\n (current, key) =>\n {\n int colonIndex = key.IndexOf(':');\n return current.Replace(\n \"{\" + key + \"}\",\n colonIndex > 0\n ? DataBinder.Eval(source, key.Substring(0, colonIndex), \"{0:\" + key.Substring(colonIndex + 1) + \"}\")\n : DataBinder.Eval(source, key).ToString());\n });\n}\n string format = \"{foo} is a {bar} is a {baz} is a {qux:#.#} is a really big {fizzle}\";\nvar o = new { foo = 123, bar = true, baz = \"this is a test\", qux = 123.45, fizzle = DateTime.Now };\nConsole.WriteLine(StringFormat(format, o));\n" }, { "answer_id": 9458467, "author": "Ashkan Ghodrat", "author_id": 704749, "author_profile": "https://Stackoverflow.com/users/704749", "pm_score": 1, "selected": false, "text": " using System.Text.RegularExpressions;\n using System.ComponentModel;\n\n public static string StringWithFormat(string format, object args)\n {\n Regex r = new Regex(@\"\\{([A-Za-z0-9_]+)\\}\");\n\n MatchCollection m = r.Matches(format);\n\n var properties = TypeDescriptor.GetProperties(args);\n\n foreach (Match item in m)\n {\n try\n {\n string propertyName = item.Groups[1].Value;\n format = format.Replace(item.Value, properties[propertyName].GetValue(args).ToString());\n }\n catch\n {\n throw new FormatException(\"The format string is not valid\");\n }\n }\n\n return format;\n }\n DateTime date = DateTime.Now;\n string dateString = StringWithFormat(\"{Month}/{Day}/{Year}\", date);\n" }, { "answer_id": 23173299, "author": "Ahmad Mageed", "author_id": 59111, "author_profile": "https://Stackoverflow.com/users/59111", "pm_score": 2, "selected": false, "text": "var order = new\n{\n Description = \"Widget\",\n OrderDate = DateTime.Now,\n Details = new\n {\n UnitPrice = 1500\n }\n};\n\nstring template = \"We just shipped your order of '{Description}', placed on {OrderDate:d}. Your {{credit}} card will be billed {Details.UnitPrice:C}.\";\n\nstring result = Template.Format(template, order);\n// or use the extension: template.FormatTemplate(order);\n" }, { "answer_id": 27228887, "author": "miroxlav", "author_id": 2392157, "author_profile": "https://Stackoverflow.com/users/2392157", "pm_score": 5, "selected": false, "text": "return \"\\{someVariable} and also \\{someOtherVariable}\" return $\"{someVariable} and also {someOtherVariable}\" return $\"{someVariable} and also {someOtherVariable}\" {index} {(index + 1).ToString().Trim()}" }, { "answer_id": 30247328, "author": "Serguei Fedorov", "author_id": 1260028, "author_profile": "https://Stackoverflow.com/users/1260028", "pm_score": 0, "selected": false, "text": "NamedFormatString" }, { "answer_id": 33802259, "author": "Mark Whitfeld", "author_id": 311292, "author_profile": "https://Stackoverflow.com/users/311292", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// Formats a string with named format items given a template dictionary of the items values to use.\n/// </summary>\npublic class StringTemplateFormatter\n{\n private readonly IFormatProvider _formatProvider;\n\n /// <summary>\n /// Constructs the formatter with the specified <see cref=\"IFormatProvider\"/>.\n /// This is defaulted to <see cref=\"CultureInfo.CurrentCulture\">CultureInfo.CurrentCulture</see> if none is provided.\n /// </summary>\n /// <param name=\"formatProvider\"></param>\n public StringTemplateFormatter(IFormatProvider formatProvider = null)\n {\n _formatProvider = formatProvider ?? CultureInfo.CurrentCulture;\n }\n\n /// <summary>\n /// Formats a string with named format items given a template dictionary of the items values to use.\n /// </summary>\n /// <param name=\"text\">The text template</param>\n /// <param name=\"templateValues\">The named values to use as replacements in the formatted string.</param>\n /// <returns>The resultant text string with the template values replaced.</returns>\n public string FormatTemplate(string text, Dictionary<string, object> templateValues)\n {\n var formattableString = text;\n var values = new List<object>();\n foreach (KeyValuePair<string, object> value in templateValues)\n {\n var index = values.Count;\n formattableString = ReplaceFormattableItem(formattableString, value.Key, index);\n values.Add(value.Value);\n }\n return String.Format(_formatProvider, formattableString, values.ToArray());\n }\n\n /// <summary>\n /// Convert named string template item to numbered string template item that can be accepted by <see cref=\"string.Format(string,object[])\">String.Format</see>\n /// </summary>\n /// <param name=\"formattableString\">The string containing the named format item</param>\n /// <param name=\"itemName\">The name of the format item</param>\n /// <param name=\"index\">The index to use for the item value</param>\n /// <returns>The formattable string with the named item substituted with the numbered format item.</returns>\n private static string ReplaceFormattableItem(string formattableString, string itemName, int index)\n {\n return formattableString\n .Replace(\"{\" + itemName + \"}\", \"{\" + index + \"}\")\n .Replace(\"{\" + itemName + \",\", \"{\" + index + \",\")\n .Replace(\"{\" + itemName + \":\", \"{\" + index + \":\");\n }\n}\n [Test]\n public void FormatTemplate_GivenANamedGuid_FormattedWithB_ShouldFormatCorrectly()\n {\n // Arrange\n var template = \"My guid {MyGuid:B} is awesome!\";\n var templateValues = new Dictionary<string, object> { { \"MyGuid\", new Guid(\"{A4D2A7F1-421C-4A1D-9CB2-9C2E70B05E19}\") } };\n var sut = new StringTemplateFormatter();\n // Act\n var result = sut.FormatTemplate(template, templateValues);\n //Assert\n Assert.That(result, Is.EqualTo(\"My guid {a4d2a7f1-421c-4a1d-9cb2-9c2e70b05e19} is awesome!\"));\n }\n" }, { "answer_id": 35568059, "author": "Ryan", "author_id": 2266345, "author_profile": "https://Stackoverflow.com/users/2266345", "pm_score": 0, "selected": false, "text": "StringBuilder String Dictionary<string, object> object {{{escaping}}} FormatException public static class StringExtension {\n /// <summary>\n /// Extension method that replaces keys in a string with the values of matching object properties.\n /// </summary>\n /// <param name=\"formatString\">The format string, containing keys like {foo} and {foo:SomeFormat}.</param>\n /// <param name=\"injectionObject\">The object whose properties should be injected in the string</param>\n /// <returns>A version of the formatString string with keys replaced by (formatted) key values.</returns>\n public static string FormatWith(this string formatString, object injectionObject) {\n return formatString.FormatWith(GetPropertiesDictionary(injectionObject));\n }\n\n /// <summary>\n /// Extension method that replaces keys in a string with the values of matching dictionary entries.\n /// </summary>\n /// <param name=\"formatString\">The format string, containing keys like {foo} and {foo:SomeFormat}.</param>\n /// <param name=\"dictionary\">An <see cref=\"IDictionary\"/> with keys and values to inject into the string</param>\n /// <returns>A version of the formatString string with dictionary keys replaced by (formatted) key values.</returns>\n public static string FormatWith(this string formatString, IDictionary<string, object> dictionary) {\n char openBraceChar = '{';\n char closeBraceChar = '}';\n\n return FormatWith(formatString, dictionary, openBraceChar, closeBraceChar);\n }\n /// <summary>\n /// Extension method that replaces keys in a string with the values of matching dictionary entries.\n /// </summary>\n /// <param name=\"formatString\">The format string, containing keys like {foo} and {foo:SomeFormat}.</param>\n /// <param name=\"dictionary\">An <see cref=\"IDictionary\"/> with keys and values to inject into the string</param>\n /// <returns>A version of the formatString string with dictionary keys replaced by (formatted) key values.</returns>\n public static string FormatWith(this string formatString, IDictionary<string, object> dictionary, char openBraceChar, char closeBraceChar) {\n string result = formatString;\n if (dictionary == null || formatString == null)\n return result;\n\n // start the state machine!\n\n // ballpark output string as two times the length of the input string for performance (avoids reallocating the buffer as often).\n StringBuilder outputString = new StringBuilder(formatString.Length * 2);\n StringBuilder currentKey = new StringBuilder();\n\n bool insideBraces = false;\n\n int index = 0;\n while (index < formatString.Length) {\n if (!insideBraces) {\n // currently not inside a pair of braces in the format string\n if (formatString[index] == openBraceChar) {\n // check if the brace is escaped\n if (index < formatString.Length - 1 && formatString[index + 1] == openBraceChar) {\n // add a brace to the output string\n outputString.Append(openBraceChar);\n // skip over braces\n index += 2;\n continue;\n }\n else {\n // not an escaped brace, set state to inside brace\n insideBraces = true;\n index++;\n continue;\n }\n }\n else if (formatString[index] == closeBraceChar) {\n // handle case where closing brace is encountered outside braces\n if (index < formatString.Length - 1 && formatString[index + 1] == closeBraceChar) {\n // this is an escaped closing brace, this is okay\n // add a closing brace to the output string\n outputString.Append(closeBraceChar);\n // skip over braces\n index += 2;\n continue;\n }\n else {\n // this is an unescaped closing brace outside of braces.\n // throw a format exception\n throw new FormatException($\"Unmatched closing brace at position {index}\");\n }\n }\n else {\n // the character has no special meaning, add it to the output string\n outputString.Append(formatString[index]);\n // move onto next character\n index++;\n continue;\n }\n }\n else {\n // currently inside a pair of braces in the format string\n // found an opening brace\n if (formatString[index] == openBraceChar) {\n // check if the brace is escaped\n if (index < formatString.Length - 1 && formatString[index + 1] == openBraceChar) {\n // there are escaped braces within the key\n // this is illegal, throw a format exception\n throw new FormatException($\"Illegal escaped opening braces within a parameter - index: {index}\");\n }\n else {\n // not an escaped brace, we have an unexpected opening brace within a pair of braces\n throw new FormatException($\"Unexpected opening brace inside a parameter - index: {index}\");\n }\n }\n else if (formatString[index] == closeBraceChar) {\n // handle case where closing brace is encountered inside braces\n // don't attempt to check for escaped braces here - always assume the first brace closes the braces\n // since we cannot have escaped braces within parameters.\n\n // set the state to be outside of any braces\n insideBraces = false;\n\n // jump over brace\n index++;\n\n // at this stage, a key is stored in current key that represents the text between the two braces\n // do a lookup on this key\n string key = currentKey.ToString();\n // clear the stringbuilder for the key\n currentKey.Clear();\n\n object outObject;\n\n if (!dictionary.TryGetValue(key, out outObject)) {\n // the key was not found as a possible replacement, throw exception\n throw new FormatException($\"The parameter \\\"{key}\\\" was not present in the lookup dictionary\");\n }\n\n // we now have the replacement value, add the value to the output string\n outputString.Append(outObject);\n\n // jump to next state\n continue;\n } // if }\n else {\n // character has no special meaning, add it to the current key\n currentKey.Append(formatString[index]);\n // move onto next character\n index++;\n continue;\n } // else\n } // if inside brace\n } // while\n\n // after the loop, if all braces were balanced, we should be outside all braces\n // if we're not, the input string was misformatted.\n if (insideBraces) {\n throw new FormatException(\"The format string ended before the parameter was closed.\");\n }\n\n return outputString.ToString();\n }\n\n /// <summary>\n /// Creates a Dictionary from an objects properties, with the Key being the property's\n /// name and the Value being the properties value (of type object)\n /// </summary>\n /// <param name=\"properties\">An object who's properties will be used</param>\n /// <returns>A <see cref=\"Dictionary\"/> of property values </returns>\n private static Dictionary<string, object> GetPropertiesDictionary(object properties) {\n Dictionary<string, object> values = null;\n if (properties != null) {\n values = new Dictionary<string, object>();\n PropertyDescriptorCollection props = TypeDescriptor.GetProperties(properties);\n foreach (PropertyDescriptor prop in props) {\n values.Add(prop.Name, prop.GetValue(properties));\n }\n }\n return values;\n }\n}\n StringBuffer StringBuffer StringBuffer StringBuffer StringBuffer" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]