qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
233,141
<p>I have a comma separated list of strings like the one below.</p> <pre><code>a,b ,c ,d, , , , ,e, f,g,h . </code></pre> <p>I want to write a regular expression that will replace the empty values i.e., strings that contain only white spaces to 'NA'. So the result should be</p> <pre><code>a,b ,c ,d,NA,NA,NA,NA,e, f,g,h . </code></pre> <p>I tried using ",\s+," to search but it skips the alternate empty strings and results in</p> <pre><code>a,b ,c ,d,NA, ,NA, ,e, f,g,h . </code></pre> <p>What's the correct regex to use here ?</p>
[ { "answer_id": 233160, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "(?<=,)\\s+(?=,)" }, { "answer_id": 233227, "author": "MrM", "author_id": 319803, "author_profile": "https://Stackoverflow.com/users/319803", "pm_score": 0, "selected": false, "text": "echo a,b ,c ,d, , , , ,e, f,g,h . | perl -p -e 's/, +[^a-z|A-Z]/,Na/g' echo a,b ,c ,d, , , , ,e, f,g,h . | perl -p -e 's/, +\\S/,Na/g' a-Z" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24424/" ]
233,148
<p>I keep reading that, in C, using pointer arithmetic is generally faster than subscripting for array access. Is this true even with modern (supposedly-optimizing) compilers?</p> <p>If so, is this still the case as I begin to move away from learning C into Objective-C and <a href="http://en.wikipedia.org/wiki/Cocoa_%28API%29" rel="noreferrer">Cocoa</a> on Macs?</p> <p>Which is the preferred coding style for array access, in both C and Objective-C? Which is considered (by professionals of their respective languages) more legible, more "correct" (for lack of a better term)?</p>
[ { "answer_id": 233166, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 7, "selected": true, "text": "int i;\nint a[20];\n\n// Init all values to zero\nmemset(a, 0, sizeof(a));\nfor (i = 0; i < 20; i++) {\n printf(\"Value of %d is %d\\n\", i, a[i]);\n}\n a[i] a i a a a i int i;\nint a[20];\nint * b;\n\nmemset(a, 0, sizeof(a));\nb = a;\nfor (i = 0; i < 20; i++) {\n printf(\"Value of %d is %d\\n\", i, *b);\n b++;\n}\n ++ int int i -Os -O2 -O3 _main:\n pushl %ebp\n movl %esp, %ebp\n pushl %edi\n pushl %esi\n pushl %ebx\n subl $108, %esp\n call ___i686.get_pc_thunk.bx\n\"L00000000001$pb\":\n leal -104(%ebp), %eax\n movl $80, 8(%esp)\n movl $0, 4(%esp)\n movl %eax, (%esp)\n call L_memset$stub\n xorl %esi, %esi\n leal LC0-\"L00000000001$pb\"(%ebx), %edi\nL2:\n movl -104(%ebp,%esi,4), %eax\n movl %eax, 8(%esp)\n movl %esi, 4(%esp)\n movl %edi, (%esp)\n call L_printf$stub\n addl $1, %esi\n cmpl $20, %esi\n jne L2\n addl $108, %esp\n popl %ebx\n popl %esi\n popl %edi\n popl %ebp\n ret\n _main:\n pushl %ebp\n movl %esp, %ebp\n pushl %edi\n pushl %esi\n pushl %ebx\n subl $124, %esp\n call ___i686.get_pc_thunk.bx\n\"L00000000001$pb\":\n leal -104(%ebp), %eax\n movl %eax, -108(%ebp)\n movl $80, 8(%esp)\n movl $0, 4(%esp)\n movl %eax, (%esp)\n call L_memset$stub\n xorl %esi, %esi\n leal LC0-\"L00000000001$pb\"(%ebx), %edi\nL2:\n movl -108(%ebp), %edx\n movl (%edx,%esi,4), %eax\n movl %eax, 8(%esp)\n movl %esi, 4(%esp)\n movl %edi, (%esp)\n call L_printf$stub\n addl $1, %esi\n cmpl $20, %esi\n jne L2\n addl $124, %esp\n popl %ebx\n popl %esi\n popl %edi\n popl %ebp\n ret\n b for movl -104(%ebp,%esi,4), %eax\n movl -108(%ebp), %edx\nmovl (%edx,%esi,4), %eax\n i NSArray NSMutableArray" }, { "answer_id": 233186, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 1, "selected": false, "text": "char p1[ ] = \"12345\";\nchar* p2 = \"12345\";\n\nchar *ch = p1[ 3 ]; /* 4 */\nch = *(p2 + 3); /* 4 */\n" }, { "answer_id": 233293, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef int64_t int64;\nstatic int64 nsTime() {\n struct timespec tp;\n clock_gettime(CLOCK_REALTIME, &tp);\n return tp.tv_sec*(int64)1000000000 + tp.tv_nsec;\n}\n\ntypedef int T;\nsize_t const N = 1024*1024*128;\nT data[N];\n\nint main(int, char**) {\n cout << \"starting\\n\";\n\n {\n int64 const a = nsTime();\n int sum = 0;\n for (size_t i=0; i<N; i++) {\n sum += data[i];\n }\n int64 const b = nsTime();\n cout << \"Simple loop (indexed): \" << (b-a)/1e9 << \"\\n\";\n }\n\n {\n int64 const a = nsTime();\n int sum = 0;\n T *d = data;\n for (size_t i=0; i<N; i++) {\n sum += *d++;\n }\n int64 const b = nsTime();\n cout << \"Simple loop (pointer): \" << (b-a)/1e9 << \"\\n\";\n }\n\n {\n int64 const a = nsTime();\n int sum = 0;\n for (size_t i=0; i<N; i++) {\n int a = sum+3;\n int b = 4-sum;\n int c = sum+5;\n sum += data[i] + a - b + c;\n }\n int64 const b = nsTime();\n cout << \"Loop that uses more ALUs (indexed): \" << (b-a)/1e9 << \"\\n\";\n }\n\n {\n int64 const a = nsTime();\n int sum = 0;\n T *d = data;\n for (size_t i=0; i<N; i++) {\n int a = sum+3;\n int b = 4-sum;\n int c = sum+5;\n sum += *d++ + a - b + c;\n }\n int64 const b = nsTime();\n cout << \"Loop that uses more ALUs (pointer): \" << (b-a)/1e9 << \"\\n\";\n }\n}\n" }, { "answer_id": 233314, "author": "Malkocoglu", "author_id": 31152, "author_profile": "https://Stackoverflow.com/users/31152", "pm_score": 1, "selected": false, "text": "-Os -Os Os" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
233,171
<p>What is the best way to do GUIs in <a href="http://en.wikipedia.org/wiki/Clojure" rel="noreferrer">Clojure</a>?</p> <p>Is there an example of some functional <a href="http://en.wikipedia.org/wiki/Swing_%28Java%29" rel="noreferrer">Swing</a> or <a href="http://en.wikipedia.org/wiki/Standard_Widget_Toolkit" rel="noreferrer">SWT</a> wrapper? Or some integration with <a href="http://en.wikipedia.org/wiki/JavaFX" rel="noreferrer">JavaFX</a> declarative GUI description which could be easily wrapped to <a href="http://en.wikipedia.org/wiki/S-expression" rel="noreferrer">s-expressions</a> using some macrology?</p> <p>Any tutorials?</p>
[ { "answer_id": 233271, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 4, "selected": false, "text": "(import '(javax.swing JFrame JButton JOptionPane)) ;'\n(import '(java.awt.event ActionListener)) ;'\n\n(let [frame (JFrame. \"Hello Swing\")\n button (JButton. \"Click Me\")]\n (.addActionListener button\n (proxy [ActionListener] []\n (actionPerformed [evt]\n (JOptionPane/showMessageDialog nil,\n (str \"<html>Hello from <b>Clojure</b>. Button \"\n (.getActionCommand evt) \" clicked.\")))))\n\n (.. frame getContentPane (add button))\n\n (doto frame\n (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)\n .pack\n (.setVisible true)))\n\nprint(\"code sample\");\n" }, { "answer_id": 1505404, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 2, "selected": false, "text": "; time for some swing\n(import '(javax.swing JFrame JTable JScrollPane))\n(import '(javax.swing.table DefaultTableModel))\n\n(let \n [frame (JFrame. \"Hello Swing\")\n dm (DefaultTableModel.)\n table (JTable. dm)\n scroll (JScrollPane. table)]\n (doto dm\n (.setNumRows 30)\n (.setColumnCount 5))\n (.. frame getContentPane (add scroll))\n (doto frame\n (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) \n (.pack)\n (.setVisible true)))\n" }, { "answer_id": 1505842, "author": "tomjen", "author_id": 21133, "author_profile": "https://Stackoverflow.com/users/21133", "pm_score": 2, "selected": false, "text": "(form {:title :on-close dispose :x-size 500 :y-size 450}\n [(button {:text \"Close\" :id 5 :on-click #(System/exit 0) :align :bottom})\n (text-field {:text \"\" :on-change #(.println System/out (:value %)) :align :center})\n (combo-box {:text \"Chose background colour\" :on-change background-update-function\n :items valid-colours})])\n" }, { "answer_id": 1914910, "author": "Abhijith", "author_id": 68963, "author_profile": "https://Stackoverflow.com/users/68963", "pm_score": 3, "selected": false, "text": "(ns test\n (:import (javax.swing JButton JFrame))\n (:use (clojure.contrib\n [swing-utils :only (add-action-listener)])))\n\n (defn handler\n [event]\n (JOptionPane/showMessageDialog nil,\n (str \"<html>Hello from <b>Clojure</b>. Button \"\n (.getActionCommand event) \" clicked.\")))\n\n (let [ frame (JFrame. \"Hello Swing\") \n button (JButton. \"Click Me\") ]\n (add-action-listener button handler)\n (doto frame\n (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)\n (.add button)\n (.pack)\n (.setVisible true)))\n" }, { "answer_id": 5944667, "author": "Dave Ray", "author_id": 40310, "author_profile": "https://Stackoverflow.com/users/40310", "pm_score": 8, "selected": true, "text": "(use 'seesaw.core)\n\n(-> (frame :title \"Hello\"\n :content \"Hello, Seesaw\"\n :on-close :exit)\n pack!\n show!)\n (ns seesaw-test.core\n (:use seesaw.core))\n\n(defn handler\n [event]\n (alert event\n (str \"<html>Hello from <b>Clojure</b>. Button \"\n (.getActionCommand event) \" clicked.\")))\n\n(-> (frame :title \"Hello Swing\" :on-close :exit\n :content (button :text \"Click Me\" :listen [:action handler]))\n pack!\n show!)\n" }, { "answer_id": 44462960, "author": "Bill Barnhill", "author_id": 204343, "author_profile": "https://Stackoverflow.com/users/204343", "pm_score": 2, "selected": false, "text": ":plugins [[lein-git-deps \"0.0.1-SNAPSHOT\"]]\n:git-dependencies [[\"https://github.com/halgari/fn-fx.git\"]]\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31141/" ]
233,188
<p>I have a web page that uses a scrolling div to display table information. When the window is resized (and also on page load), the display is centered and the div's scrollbar positioned to the right of the page by setting its width. For some reason, the behaviour is different under firefox than IE. IE positions/sizes the div as expected, but firefox seems to make it too wide, such that the scrollbar begins to disappear when the window client width reaches about 800px. I'm using the following methods to set the position and size: </p> <pre><code>function getWindowWidth() { var windowWidth = 0; if (typeof(window.innerWidth) == 'number') { windowWidth=window.innerWidth; } else { if (document.documentElement &amp;&amp; document.documentElement.clientWidth) { windowWidth=document.documentElement.clientWidth ; } else { if (document.body &amp;&amp; document.body.clientWidth) { windowWidth=document.body.clientWidth; } } } return windowWidth; } function findLPos(obj) { var curleft = 0; if (obj.offsetParent) { curleft = obj.offsetLeft while (obj = obj.offsetParent) { curleft += obj.offsetLeft } } return curleft; } var bdydiv; var coldiv; document.body.style.overflow="hidden"; window.onload=resizeDivs; window.onresize=resizeDivs; function resizeDivs(){ bdydiv=document.getElementById('bdydiv'); coldiv=document.getElementById('coldiv'); var winWdth=getWindowWidth(); var rghtMarg = 0; var colHdrTbl=document.getElementById('colHdrTbl'); rghtMarg = parseInt((winWdth - 766) / 2) - 8; rghtMarg = (rghtMarg &gt; 0 ? rghtMarg : 0); coldiv.style.paddingLeft = rghtMarg + "px"; bdydiv.style.paddingLeft = rghtMarg + "px"; var bdydivLft=findLPos(bdydiv); if ((winWdth - bdydivLft) &gt;= 1){ bdydiv.style.width = winWdth - bdydivLft; coldiv.style.width = bdydiv.style.width; } syncScroll(); } function syncScroll(){ if(coldiv.scrollLeft&gt;=0){ coldiv.scrollLeft=bdydiv.scrollLeft; } } </code></pre> <p>Note that I've cut out other code which sets height, and other non-relevant parts. The full page can be seen <a href="http://site1.funddata.com/mozilladivresize.html" rel="nofollow noreferrer">here</a>. If you go to the link in both IE and firefox, resize width until "800" is displayed in the green box top-right, and resize height until the scrollbar at the right is enabled, you can see the problem. If you then resize the IE width, the scrollbar stays, but if you resize the firefox width wider, the scrollbar begins to disappear. I'm at a loss as to why this is happening....</p> <p>Note that AFAIK, getWindowWidth() should be cross-browser-compatible, but I'm not so sure about findLPos().... perhaps there's an extra object in Firefox's DOM or something, which is changing the result??</p>
[ { "answer_id": 233204, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 0, "selected": false, "text": "windowWidth = document.documentElement.clientWidth;\n windowWidth = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth);\n" }, { "answer_id": 233577, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "function getPos(elm) {//jumper\n for(var zx=zy=0;elm!=null;zx+=elm.offsetLeft,zy+=elm.offsetTop,elm=elm.offsetParent);\n return {x:zx,y:zy}\n}\n" }, { "answer_id": 233998, "author": "Graza", "author_id": 11820, "author_profile": "https://Stackoverflow.com/users/11820", "pm_score": 1, "selected": false, "text": " if (__isFireFox){\n bdydiv.style.width = winWdth - bdydivLft - rghtMarg;\n } else {\n bdydiv.style.width = winWdth - bdydivLft;\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11820/" ]
233,192
<p><em>What options are there to detect web-crawlers that do not want to be detected?</em></p> <p>(I know that listing detection techniques will allow the smart stealth-crawler programmer to make a better spider, but I do not think that we will ever be able to block smart stealth-crawlers anyway, only the ones that make mistakes.)</p> <p>I'm not talking about the nice crawlers such as Googlebot and Yahoo! Slurp. I consider a bot nice if it:</p> <ol> <li>identifies itself as a bot in the user agent string</li> <li>reads <code>robots.txt</code> (and obeys it)</li> </ol> <p>I'm talking about the <em>bad</em> crawlers, hiding behind common user agents, using my bandwidth and never giving me anything in return.</p> <p>There are some trapdoors that can be constructed <em>updated list (thanks Chris, gs)</em>:</p> <ol> <li>Adding a directory only listed (marked as disallow) in the <code>robots.txt</code>,</li> <li>Adding invisible links (possibly marked as rel=&quot;nofollow&quot;?), <ul> <li>style=&quot;display: none;&quot; on link or parent container</li> <li>placed underneath another element with higher z-index</li> </ul> </li> <li>detect who doesn't understand CaPiTaLiSaTioN,</li> <li>detect who tries to post replies but always fail the Captcha.</li> <li>detect GET requests to POST-only resources</li> <li>detect interval between requests</li> <li>detect order of pages requested</li> <li>detect who (consistently) requests HTTPS resources over HTTP</li> <li>detect who does not request image file (this in combination with a list of user-agents of known image capable browsers works surprisingly nice)</li> </ol> <p>Some traps would be triggered by both 'good' and 'bad' bots. you could combine those with a whitelist:</p> <ol> <li>It trigger a trap</li> <li>It request <code>robots.txt</code>?</li> <li>It doest not trigger another trap because it obeyed <code>robots.txt</code></li> </ol> <p><em>One other important thing here is:</em> Please consider blind people using a screen readers: give people a way to contact you, or solve a (non-image) Captcha to continue browsing.</p> <p><strong>What methods are there to automatically detect the web crawlers trying to mask themselves as normal human visitors.</strong></p> <p>The question is not: <em>How do I catch every crawler.</em> The question is: <em>How can I maximize the chance of detecting a crawler.</em></p> <p>Some spiders are really good, and actually parse and understand HTML, xhtml, CSS JavaScript, VBScript etc... I have no illusions: I won't be able to beat them.</p> <p>You would however be surprised how stupid some crawlers are. With the best example of stupidity (in my opinion) being: cast all URLs to lower case before requesting them.</p> <p>And then there is a whole bunch of crawlers that are just 'not good enough' to avoid the various trapdoors.</p>
[ { "answer_id": 233541, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 3, "selected": false, "text": "<a href=\"iamabot.script\" style=\"display:none;\">Don't click me!</a>\n" }, { "answer_id": 310343, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<a href=\"//example.com/\"> = http://example.com/ on http pages.\n<a href=\"page&amp;&#x23;hash\"> = page& + #hash\n <a href=\"foo<!--bar-->\"> (comment should not be removed)\n<script>var haha = '<a href=\"bot\">'</script>\n<script>// <!-- </script> <!--><a href=\"bot\"> <!-->\n" }, { "answer_id": 3121529, "author": "Brian Armstrong", "author_id": 76486, "author_profile": "https://Stackoverflow.com/users/76486", "pm_score": 2, "selected": false, "text": "ADSARobot|ah-ha|almaden|aktuelles|Anarchie|amzn_assoc|ASPSeek|ASSORT|ATHENS|Atomz|attach|attache|autoemailspider|BackWeb|Bandit|BatchFTP|bdfetch|big.brother|BlackWidow|bmclient|Boston\\ Project|BravoBrian\\ SpiderEngine\\ MarcoPolo|Bot\\ mailto:craftbot@yahoo.com|Buddy|Bullseye|bumblebee|capture|CherryPicker|ChinaClaw|CICC|clipping|Collector|Copier|Crescent|Crescent\\ Internet\\ ToolPak|Custo|cyberalert|DA$|Deweb|diagem|Digger|Digimarc|DIIbot|DISCo|DISCo\\ Pump|DISCoFinder|Download\\ Demon|Download\\ Wonder|Downloader|Drip|DSurf15a|DTS.Agent|EasyDL|eCatch|ecollector|efp@gmx\\.net|Email\\ Extractor|EirGrabber|email|EmailCollector|EmailSiphon|EmailWolf|Express\\ WebPictures|ExtractorPro|EyeNetIE|FavOrg|fastlwspider|Favorites\\ Sweeper|Fetch|FEZhead|FileHound|FlashGet\\ WebWasher|FlickBot|fluffy|FrontPage|GalaxyBot|Generic|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go\\!Zilla|Go!Zilla|Go-Ahead-Got-It|GornKer|gotit|Grabber|GrabNet|Grafula|Green\\ Research|grub-client|Harvest|hhjhj@yahoo|hloader|HMView|HomePageSearch|http\\ generic|HTTrack|httpdown|httrack|ia_archiver|IBM_Planetwide|Image\\ Stripper|Image\\ Sucker|imagefetch|IncyWincy|Indy*Library|Indy\\ Library|informant|Ingelin|InterGET|Internet\\ Ninja|InternetLinkagent|Internet\\ Ninja|InternetSeer\\.com|Iria|Irvine|JBH*agent|JetCar|JOC|JOC\\ Web\\ Spider|JustView|KWebGet|Lachesis|larbin|LeechFTP|LexiBot|lftp|libwww|likse|Link|Link*Sleuth|LINKS\\ ARoMATIZED|LinkWalker|LWP|lwp-trivial|Mag-Net|Magnet|Mac\\ Finder|Mag-Net|Mass\\ Downloader|MCspider|Memo|Microsoft.URL|MIDown\\ tool|Mirror|Missigua\\ Locator|Mister\\ PiX|MMMtoCrawl\\/UrlDispatcherLLL|^Mozilla$|Mozilla.*Indy|Mozilla.*NEWT|Mozilla*MSIECrawler|MS\\ FrontPage*|MSFrontPage|MSIECrawler|MSProxy|multithreaddb|nationaldirectory|Navroad|NearSite|NetAnts|NetCarta|NetMechanic|netprospector|NetResearchServer|NetSpider|Net\\ Vampire|NetZIP|NetZip\\ Downloader|NetZippy|NEWT|NICErsPRO|Ninja|NPBot|Octopus|Offline\\ Explorer|Offline\\ Navigator|OpaL|Openfind|OpenTextSiteCrawler|OrangeBot|PageGrabber|Papa\\ Foto|PackRat|pavuk|pcBrowser|PersonaPilot|Ping|PingALink|Pockey|Proxy|psbot|PSurf|puf|Pump|PushSite|QRVA|RealDownload|Reaper|Recorder|ReGet|replacer|RepoMonkey|Robozilla|Rover|RPT-HTTPClient|Rsync|Scooter|SearchExpress|searchhippo|searchterms\\.it|Second\\ Street\\ Research|Seeker|Shai|Siphon|sitecheck|sitecheck.internetseer.com|SiteSnagger|SlySearch|SmartDownload|snagger|Snake|SpaceBison|Spegla|SpiderBot|sproose|SqWorm|Stripper|Sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|Szukacz|tAkeOut|tarspider|Teleport\\ Pro|Templeton|TrueRobot|TV33_Mercator|UIowaCrawler|UtilMind|URLSpiderPro|URL_Spider_Pro|Vacuum|vagabondo|vayala|visibilitygap|VoidEYE|vspider|Web\\ Downloader|w3mir|Web\\ Data\\ Extractor|Web\\ Image\\ Collector|Web\\ Sucker|Wweb|WebAuto|WebBandit|web\\.by\\.mail|Webclipping|webcollage|webcollector|WebCopier|webcraft@bea|webdevil|webdownloader|Webdup|WebEMailExtrac|WebFetch|WebGo\\ IS|WebHook|Webinator|WebLeacher|WEBMASTERS|WebMiner|WebMirror|webmole|WebReaper|WebSauger|Website|Website\\ eXtractor|Website\\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZIP|Wget|Whacker|whizbang|WhosTalking|Widow|WISEbot|WWWOFFLE|x-Tractor|^Xaldon\\ WebSpider|WUMPUS|Xenu|XGET|Zeus.*Webster|Zeus [NC]\n" }, { "answer_id": 4886720, "author": "Danubian Sailor", "author_id": 531954, "author_profile": "https://Stackoverflow.com/users/531954", "pm_score": 1, "selected": false, "text": "* style=\"display: none;\" on link or parent container\n* placed underneath another element with higher z-index\n" }, { "answer_id": 52328537, "author": "Granitosaurus", "author_id": 3737009, "author_profile": "https://Stackoverflow.com/users/3737009", "pm_score": 1, "selected": false, "text": "foo.com/cars/*.html" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22674/" ]
233,199
<p>I am trying to get data from my server, used RemoteObject to accomplish it. When I run the application on my localhost it works great but when iam using it on my server i get a Channel.Security.Error(Security Error accessing URL).</p> <p>On the server side logs there is a mention about cross domain . 77.127.194.4 - - [23/Oct/2008 21:15:11] "GET /crossdomain.xml HTTP/1.1" 501</p> <p>Any one encountered the same problem ? any idea ?</p>
[ { "answer_id": 233541, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 3, "selected": false, "text": "<a href=\"iamabot.script\" style=\"display:none;\">Don't click me!</a>\n" }, { "answer_id": 310343, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<a href=\"//example.com/\"> = http://example.com/ on http pages.\n<a href=\"page&amp;&#x23;hash\"> = page& + #hash\n <a href=\"foo<!--bar-->\"> (comment should not be removed)\n<script>var haha = '<a href=\"bot\">'</script>\n<script>// <!-- </script> <!--><a href=\"bot\"> <!-->\n" }, { "answer_id": 3121529, "author": "Brian Armstrong", "author_id": 76486, "author_profile": "https://Stackoverflow.com/users/76486", "pm_score": 2, "selected": false, "text": "ADSARobot|ah-ha|almaden|aktuelles|Anarchie|amzn_assoc|ASPSeek|ASSORT|ATHENS|Atomz|attach|attache|autoemailspider|BackWeb|Bandit|BatchFTP|bdfetch|big.brother|BlackWidow|bmclient|Boston\\ Project|BravoBrian\\ SpiderEngine\\ MarcoPolo|Bot\\ mailto:craftbot@yahoo.com|Buddy|Bullseye|bumblebee|capture|CherryPicker|ChinaClaw|CICC|clipping|Collector|Copier|Crescent|Crescent\\ Internet\\ ToolPak|Custo|cyberalert|DA$|Deweb|diagem|Digger|Digimarc|DIIbot|DISCo|DISCo\\ Pump|DISCoFinder|Download\\ Demon|Download\\ Wonder|Downloader|Drip|DSurf15a|DTS.Agent|EasyDL|eCatch|ecollector|efp@gmx\\.net|Email\\ Extractor|EirGrabber|email|EmailCollector|EmailSiphon|EmailWolf|Express\\ WebPictures|ExtractorPro|EyeNetIE|FavOrg|fastlwspider|Favorites\\ Sweeper|Fetch|FEZhead|FileHound|FlashGet\\ WebWasher|FlickBot|fluffy|FrontPage|GalaxyBot|Generic|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go\\!Zilla|Go!Zilla|Go-Ahead-Got-It|GornKer|gotit|Grabber|GrabNet|Grafula|Green\\ Research|grub-client|Harvest|hhjhj@yahoo|hloader|HMView|HomePageSearch|http\\ generic|HTTrack|httpdown|httrack|ia_archiver|IBM_Planetwide|Image\\ Stripper|Image\\ Sucker|imagefetch|IncyWincy|Indy*Library|Indy\\ Library|informant|Ingelin|InterGET|Internet\\ Ninja|InternetLinkagent|Internet\\ Ninja|InternetSeer\\.com|Iria|Irvine|JBH*agent|JetCar|JOC|JOC\\ Web\\ Spider|JustView|KWebGet|Lachesis|larbin|LeechFTP|LexiBot|lftp|libwww|likse|Link|Link*Sleuth|LINKS\\ ARoMATIZED|LinkWalker|LWP|lwp-trivial|Mag-Net|Magnet|Mac\\ Finder|Mag-Net|Mass\\ Downloader|MCspider|Memo|Microsoft.URL|MIDown\\ tool|Mirror|Missigua\\ Locator|Mister\\ PiX|MMMtoCrawl\\/UrlDispatcherLLL|^Mozilla$|Mozilla.*Indy|Mozilla.*NEWT|Mozilla*MSIECrawler|MS\\ FrontPage*|MSFrontPage|MSIECrawler|MSProxy|multithreaddb|nationaldirectory|Navroad|NearSite|NetAnts|NetCarta|NetMechanic|netprospector|NetResearchServer|NetSpider|Net\\ Vampire|NetZIP|NetZip\\ Downloader|NetZippy|NEWT|NICErsPRO|Ninja|NPBot|Octopus|Offline\\ Explorer|Offline\\ Navigator|OpaL|Openfind|OpenTextSiteCrawler|OrangeBot|PageGrabber|Papa\\ Foto|PackRat|pavuk|pcBrowser|PersonaPilot|Ping|PingALink|Pockey|Proxy|psbot|PSurf|puf|Pump|PushSite|QRVA|RealDownload|Reaper|Recorder|ReGet|replacer|RepoMonkey|Robozilla|Rover|RPT-HTTPClient|Rsync|Scooter|SearchExpress|searchhippo|searchterms\\.it|Second\\ Street\\ Research|Seeker|Shai|Siphon|sitecheck|sitecheck.internetseer.com|SiteSnagger|SlySearch|SmartDownload|snagger|Snake|SpaceBison|Spegla|SpiderBot|sproose|SqWorm|Stripper|Sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|Szukacz|tAkeOut|tarspider|Teleport\\ Pro|Templeton|TrueRobot|TV33_Mercator|UIowaCrawler|UtilMind|URLSpiderPro|URL_Spider_Pro|Vacuum|vagabondo|vayala|visibilitygap|VoidEYE|vspider|Web\\ Downloader|w3mir|Web\\ Data\\ Extractor|Web\\ Image\\ Collector|Web\\ Sucker|Wweb|WebAuto|WebBandit|web\\.by\\.mail|Webclipping|webcollage|webcollector|WebCopier|webcraft@bea|webdevil|webdownloader|Webdup|WebEMailExtrac|WebFetch|WebGo\\ IS|WebHook|Webinator|WebLeacher|WEBMASTERS|WebMiner|WebMirror|webmole|WebReaper|WebSauger|Website|Website\\ eXtractor|Website\\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZIP|Wget|Whacker|whizbang|WhosTalking|Widow|WISEbot|WWWOFFLE|x-Tractor|^Xaldon\\ WebSpider|WUMPUS|Xenu|XGET|Zeus.*Webster|Zeus [NC]\n" }, { "answer_id": 4886720, "author": "Danubian Sailor", "author_id": 531954, "author_profile": "https://Stackoverflow.com/users/531954", "pm_score": 1, "selected": false, "text": "* style=\"display: none;\" on link or parent container\n* placed underneath another element with higher z-index\n" }, { "answer_id": 52328537, "author": "Granitosaurus", "author_id": 3737009, "author_profile": "https://Stackoverflow.com/users/3737009", "pm_score": 1, "selected": false, "text": "foo.com/cars/*.html" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20955/" ]
233,207
<p>Should I always wrap external resource calls in a try-catch? (ie. calls to a database or file system) Is there a best practice for error handling when calling external resources?</p>
[ { "answer_id": 233248, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "try/finally try/finally Dispose using finally catch" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24908/" ]
233,216
<p>I have an abstract generic class <code>BLL&lt;T&gt; where T : BusinessObject</code>. I need to open an assembly that contains a set of concrete BLL classes, and return the tuples (businessObjectType, concreteBLLType) inside a Dictionary. There is the part of the method I could do until now, but I'm having problems to discover T.</p> <pre><code>protected override Dictionary&lt;Type, Type&gt; DefineBLLs() { string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"]; Type[] types = LoadAssembly(bllsAssembly); Dictionary&lt;Type, Type&gt; bllsTypes = new Dictionary&lt;Type, Type&gt;(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(BLL&lt;&gt;))) /* how to know T in the situation below? */ bllsTypes.Add(??businessObjectType (T)??, type); } return bllsTypes; } </code></pre>
[ { "answer_id": 233236, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "using System;\nusing System.Reflection;\n\npublic abstract class Base<T>\n{\n}\n\npublic class Concrete : Base<string>\n{\n}\n\nclass Test\n{\n static void Main()\n {\n Type type = typeof(Concrete);\n Type baseType = type.BaseType;\n Type typeOfT = baseType.GetGenericArguments()[0]; // Only one arg\n Console.WriteLine(typeOfT.Name); // Prints String\n }\n}\n" }, { "answer_id": 233267, "author": "Victor Rodrigues", "author_id": 21668, "author_profile": "https://Stackoverflow.com/users/21668", "pm_score": 0, "selected": false, "text": "protected override Dictionary<Type, Type> DefineBLLs()\n{\n string bllsAssembly = ConfigurationManager.AppSettings[\"BLLsAssembly\"];\n\n Type[] types = LoadAssembly(bllsAssembly);\n\n Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();\n\n foreach (Type bllType in types)\n {\n if (bllType.IsSubclassOf(typeof(BLL<>)))\n {\n Type baseType = bllType.BaseType;\n Type businessObjectType = baseType.GetGenericArguments()[0];\n bllsTypes.Add(businessObjectType, bllType);\n }\n }\n\n return bllsTypes;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21668/" ]
233,217
<p>I'm writing a C Shell program that will be doing <code>su</code> or <code>sudo</code> or <code>ssh</code>. They all want their passwords in console input (the TTY) rather than stdin or the command line.</p> <p>Does anybody know a solution?</p> <p>Setting up password-less <code>sudo</code> is not an option.</p> <p><a href="/questions/tagged/expect" class="post-tag" title="show questions tagged &#39;expect&#39;" rel="tag">expect</a> could be an option, but it's not present on my stripped-down system.</p>
[ { "answer_id": 233224, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 3, "selected": false, "text": "expect" }, { "answer_id": 351916, "author": "mlambie", "author_id": 17453, "author_profile": "https://Stackoverflow.com/users/17453", "pm_score": 5, "selected": false, "text": "echo <password> | sudo -S <command>\n" }, { "answer_id": 1607458, "author": "Shankar", "author_id": 194613, "author_profile": "https://Stackoverflow.com/users/194613", "pm_score": -1, "selected": false, "text": "su -c \"Command\" < \"Password\"\n" }, { "answer_id": 3959957, "author": "DevOz", "author_id": 479370, "author_profile": "https://Stackoverflow.com/users/479370", "pm_score": 1, "selected": false, "text": "echo <password> | su -c <command> <user> \n" }, { "answer_id": 4327123, "author": "Jesse Webb", "author_id": 346561, "author_profile": "https://Stackoverflow.com/users/346561", "pm_score": 9, "selected": true, "text": " -S The -S (stdin) option causes sudo to read the password from\n the standard input instead of the terminal device.\n echo myPassword | sudo -S ls /tmp\n" }, { "answer_id": 4627834, "author": "David Dawson", "author_id": 490129, "author_profile": "https://Stackoverflow.com/users/490129", "pm_score": 4, "selected": false, "text": "ssh user@host bash -c \"echo mypass | sudo -S mycommand\"\n" }, { "answer_id": 7437667, "author": "Martin Dorey", "author_id": 18096, "author_profile": "https://Stackoverflow.com/users/18096", "pm_score": 3, "selected": false, "text": " (sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) |\n socat - EXEC:'ssh -l user server',pty,setsid,ctty\n\n EXEC’utes an ssh session to server. Uses a pty for communication\n between socat and ssh, makes it ssh’s controlling tty (ctty),\n and makes this pty the owner of a new process group (setsid), so\n ssh accepts the password from socat.\n" }, { "answer_id": 8850586, "author": "Edward", "author_id": 1147674, "author_profile": "https://Stackoverflow.com/users/1147674", "pm_score": 5, "selected": false, "text": "ssh sshpass sshpass -p yourpassphrase ssh user@host $ apt-get install sshpass\n$ sshpass -p 'password' ssh username@server\n" }, { "answer_id": 10492509, "author": "adhown", "author_id": 1369159, "author_profile": "https://Stackoverflow.com/users/1369159", "pm_score": 4, "selected": false, "text": "expect expect -c 'spawn ssh root@your-domain.com;expect password;send \"your-password\\n\";interact\n" }, { "answer_id": 11722033, "author": "Byob ", "author_id": 1555487, "author_profile": "https://Stackoverflow.com/users/1555487", "pm_score": 3, "selected": false, "text": "ssh-keygen\nEnter file in which to save the key (/home/myuser/.ssh/id_rsa): <Hit enter for default>\nOverwrite (y/n)? y\n ssh-copy-id <remote_user>@<other_host>\nremote_user@other_host's password: <Enter remote user's password here>\n ssh remote_user@other_host" }, { "answer_id": 15586177, "author": "titus", "author_id": 2202105, "author_profile": "https://Stackoverflow.com/users/2202105", "pm_score": 0, "selected": false, "text": " dialog --inputbox \"Enter IP\" 8 78 2> /tmp/ip\n\n IP=$(cat /tmp/ip)\n\n\n dialog --inputbox \"Please enter username\" 8 78 2> /tmp/user\n\n US=$(cat /tmp/user)\n\n\n dialog --passwordbox \"enter password for \\\"$US\\\" 8 78 2> /tmp/pass\n\n PASSWORD = $(cat /tmp/pass)\n\n\n sshpass -p \"$PASSWORD\" ssh $US@$IP mkdir -p /home/$US/TARGET-FOLDER\n\n\n rm /tmp/ip\n\n rm /tmp/user\n\n rm /tmp/pass\n" }, { "answer_id": 30734581, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 4, "selected": false, "text": "sudo -S <<< \"password\" command\n" }, { "answer_id": 42299931, "author": "Ed Bishop", "author_id": 184383, "author_profile": "https://Stackoverflow.com/users/184383", "pm_score": 2, "selected": false, "text": "ssh -t -t me@myserver.io << EOF\necho SOMEPASSWORD | sudo -S do something\nsudo do something else\nexit\nEOF\n" }, { "answer_id": 42970257, "author": "Sarat Chandra", "author_id": 7121889, "author_profile": "https://Stackoverflow.com/users/7121889", "pm_score": -1, "selected": false, "text": "echo password | sudo command\n echo password | sudo apt-get update; whoami\n" }, { "answer_id": 47105629, "author": "JS.", "author_id": 310399, "author_profile": "https://Stackoverflow.com/users/310399", "pm_score": 0, "selected": false, "text": "ssh <remote_username>@<remote_server> sudo -S <<< <remote_password> cat /etc/sudoers\n" }, { "answer_id": 59699659, "author": "Badr Elmers", "author_id": 3020379, "author_profile": "https://Stackoverflow.com/users/3020379", "pm_score": 1, "selected": false, "text": "sshpass passh $ passh -p password ssh user@host\n $ passh -p password ssh user@host date\n" }, { "answer_id": 68749025, "author": "nivalderramas", "author_id": 10605742, "author_profile": "https://Stackoverflow.com/users/10605742", "pm_score": 1, "selected": false, "text": "echo password | echo y | sudo -S pacman -Syu" }, { "answer_id": 70407908, "author": "Affes Salem", "author_id": 13541620, "author_profile": "https://Stackoverflow.com/users/13541620", "pm_score": 0, "selected": false, "text": "stdin echo sudopassword | sudo -S -u username sshpass -p extsshpassword ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@ipaddress \" CMD on external machine\"\n echo password | sudo -S -u username\n sshpass -p sshpassword ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@ipaddress \" CMD on external machine\"\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23420/" ]
233,222
<p>I have 3 divs where only one is visible by default, they each contain information about a product. Below this divs is a list of 3 images which are images of the products. By default of course the 1st list item is selected and has <code>class="selected"</code>. When a different product image is clicks then <code>class="selected"</code> moves to that list item and the div above it changes to hidden and the div containing the other product information needs to appear.</p> <p>I have searched all over the place for a plugin which can do what I want, they are all limited in some way which stops me doing from doing it.</p>
[ { "answer_id": 233252, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 2, "selected": false, "text": "<img id=\"img1\" src=\"1.jpg\" desc=\"d1\" class=\"selected prodImg\" />\n<img id=\"img2\" src=\"2.jpg\" desc=\"d2\" class=\"prodImg\" />\n<img id=\"img3\" src=\"3.jpg\" desc=\"d3\" class=\"prodImg\"/>\n\n<div id=\"d1\">description 1</div>\n<div id=\"d2\" class=\"hidden\">description 2</div>\n<div id=\"d3\" class=\"hidden\">description 3</div>\n\n<script>\n\n $(\".prodImg\").click(function() {\n\n if ($(this).hasClass(\"selected\")) return;\n\n $(\"#\" + $(\".selected\").attr(\"desc\")).addClass(\"hidden\");\n $(\".selected\").removeClass(\"selected\");\n\n $(\"#\" + $(this).attr(\"desc\")).removeClass(\"hidden\");\n $(this).addClass(\"selected\");\n\n });\n\n</script>\n" }, { "answer_id": 1253712, "author": "gacon", "author_id": 86053, "author_profile": "https://Stackoverflow.com/users/86053", "pm_score": 0, "selected": false, "text": "<script>\n\n $(\".prodImg\").click(function() {\n\n if ($(this).hasClass(\"selected\")) return;\n\n\n $('.prodImg').removeClass('selected');\n\n $(this).addClass('selected');\n\n var name = $(this).attr('desc');\n\n $('.'+name).removeClass();\n $('.'+name).addClass(''); \n\n });\n\n</script>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
233,243
<p>That was an interview question that I was unable to answer:</p> <p>How to check that a string is a palindrome using regular expressions?</p> <p>p.s. There is already a question "<a href="https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome">How to check if the given string is palindrome?</a>" and it gives a lot of answers in different languages, but no answer that uses regular expressions.</p>
[ { "answer_id": 233275, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 4, "selected": false, "text": "\\(.\\)\\(.\\)\\2\\1\n \\([a-z]\\)\\([a-z]\\)[a-z]\\2\\1\n" }, { "answer_id": 233294, "author": "Dan", "author_id": 8040, "author_profile": "https://Stackoverflow.com/users/8040", "pm_score": 2, "selected": false, "text": "bool isPalindrome(String s1)\n\n{\n\n String s2 = s1.reverse;\n\n return s2 == s1;\n}\n" }, { "answer_id": 233296, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 6, "selected": false, "text": "$a = \"teststring\";\nwhile(length $a > 1)\n{\n $a =~ /(.)(.*)(.)/;\n die \"Not a palindrome: $a\" unless $1 eq $3;\n $a = $2;\n}\nprint \"Palindrome\";\n" }, { "answer_id": 233326, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 5, "selected": false, "text": "/^((.)(?1)\\2|.?)$/\n" }, { "answer_id": 260152, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "$re = qr/\n . # single letter is a palindrome\n |\n (.) # first letter\n (??{ $re })?? # apply recursivly (not interpolated yet)\n \\1 # last letter\n/x;\n\nwhile(<>) {\n chomp;\n say if /^$re$/; # print palindromes\n}\n" }, { "answer_id": 1453387, "author": "Stewart", "author_id": 85695, "author_profile": "https://Stackoverflow.com/users/85695", "pm_score": 0, "selected": false, "text": "WHILE string.length > 1\n IF /(.)(.*)\\1/ matches string\n string = \\2\n ELSE\n REJECT\nACCEPT\n" }, { "answer_id": 1453431, "author": "Stewart", "author_id": 85695, "author_profile": "https://Stackoverflow.com/users/85695", "pm_score": 3, "selected": false, "text": "(.?)(.?)(.?)(.?)(.?).?\\5\\4\\3\\2\\1\n" }, { "answer_id": 3225809, "author": "kev", "author_id": 348785, "author_profile": "https://Stackoverflow.com/users/348785", "pm_score": 4, "selected": false, "text": "(?<N>.)+.?(?<-N>\\k<N>)+(?(N)(?!))\n" }, { "answer_id": 7945076, "author": "Chris", "author_id": 839238, "author_profile": "https://Stackoverflow.com/users/839238", "pm_score": 2, "selected": false, "text": "/(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?).?\\9\\8\\7\\6\\5\\4\\3\\2\\1/\n str == str.reverse ? true : false\n" }, { "answer_id": 9639518, "author": "Lil Devil", "author_id": 262708, "author_profile": "https://Stackoverflow.com/users/262708", "pm_score": 2, "selected": false, "text": "/^((.)(?1)?\\2|.)$/" }, { "answer_id": 11246212, "author": "Taylor", "author_id": 1083057, "author_profile": "https://Stackoverflow.com/users/1083057", "pm_score": 3, "selected": false, "text": "def palindrome?(string)\n $1 if string =~ /\\A(?<p>| \\w | (?: (?<l>\\w) \\g<p> \\k<l+0> ))\\z/x\nend\n 1.9.2p290 :017 > palindrome?(\"racecar\")\n => \"racecar\" \n1.9.2p290 :018 > palindrome?(\"kayak\")\n => \"kayak\" \n1.9.2p290 :019 > palindrome?(\"woahitworks!\")\n => nil \n" }, { "answer_id": 14251184, "author": "sapam", "author_id": 1965556, "author_profile": "https://Stackoverflow.com/users/1965556", "pm_score": 2, "selected": false, "text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nprint \"Enter your string: \";\nchop(my $a = scalar(<STDIN>)); \nmy $m = (length($a)+1)/2;\nif( (length($a) % 2 != 0 ) or length($a) > 1 ) { \n my $r; \n foreach (0 ..($m - 2)){\n $r .= \"(.)\";\n }\n $r .= \".?\";\n foreach ( my $i = ($m-1); $i > 0; $i-- ) { \n $r .= \"\\\\$i\";\n } \n if ( $a =~ /(.)(.).\\2\\1/ ){\n print \"$a is a palindrome\\n\";\n }\n else {\n print \"$a not a palindrome\\n\";\n }\nexit(1);\n}\nprint \"$a not a palindrome\\n\";\n" }, { "answer_id": 22261369, "author": "Hui Liu", "author_id": 1284723, "author_profile": "https://Stackoverflow.com/users/1284723", "pm_score": 3, "selected": false, "text": "if($istr =~ /^((\\w)(?1)\\g{-1}|\\w?)$/){\n print $istr,\" is palindrome\\n\";\n}\n" }, { "answer_id": 25415318, "author": "pbatey", "author_id": 2683294, "author_profile": "https://Stackoverflow.com/users/2683294", "pm_score": 3, "selected": false, "text": "^(.)(.)(?:(.).?\\3?)?\\2\\1$\n ^(.)(.)(?:(.)(?:(.).?\\4?)?\\3?)?\\2\\1$\n" }, { "answer_id": 25721935, "author": "Melih Altıntaş", "author_id": 2740071, "author_profile": "https://Stackoverflow.com/users/2740071", "pm_score": 2, "selected": false, "text": "\\b(?'word'(?'letter'[a-z])\\g'word'\\k'letter+0'|[a-z])\\b a, dad, radar, racecar, and redivider" }, { "answer_id": 28676216, "author": "rr-", "author_id": 2016221, "author_profile": "https://Stackoverflow.com/users/2016221", "pm_score": 4, "selected": false, "text": "^(?'letter'[a-z])+[a-z]?(?:\\k'letter'(?'-letter'))+(?(letter)(?!))$\n" }, { "answer_id": 34283011, "author": "ankush", "author_id": 5466460, "author_profile": "https://Stackoverflow.com/users/5466460", "pm_score": 2, "selected": false, "text": "create or replace procedure palin_test(palin in varchar2) is\n tmp varchar2(100);\n i number := 0;\n BEGIN\n tmp := palin;\n for i in 1 .. length(palin)/2 loop\n if length(tmp) > 1 then \n if regexp_like(tmp,'^(^.).*(\\1)$') = true then \n tmp := substr(palin,i+1,length(tmp)-2);\n else \n dbms_output.put_line('not a palindrome');\n exit;\n end if;\n end if; \n if i >= length(palin)/2 then \n dbms_output.put_line('Yes ! it is a palindrome');\n end if;\n end loop; \nend palin_test;\n" }, { "answer_id": 37458487, "author": "mpugach", "author_id": 1041467, "author_profile": "https://Stackoverflow.com/users/1041467", "pm_score": 2, "selected": false, "text": "/\\A(?<a>|.|(?:(?<b>.)\\g<a>\\k<b+0>))\\z/\n" }, { "answer_id": 40792780, "author": "Casimir et Hippolyte", "author_id": 2255089, "author_profile": "https://Stackoverflow.com/users/2255089", "pm_score": 3, "selected": false, "text": "\\A(?:(.)(?=.*?((?(2)\\1\\2|\\1))\\z))*?.?\\2\\z\n \\A(?:(?:(.)(?=.*?((?(2)\\1\\2|\\1))\\z))*?.?\\2|.)\\z\n \\A(?:(.)(?=.*?(\\1\\2\\z|(?<!(?=\\2\\z).{0,1000})\\1\\z)))*?.?\\2\\z\n" }, { "answer_id": 41924373, "author": "Kanchan Sen Laskar", "author_id": 7486885, "author_profile": "https://Stackoverflow.com/users/7486885", "pm_score": 2, "selected": false, "text": "my $pal='malayalam';\n\nwhile($pal=~/((.)(.*)\\2)/){ #checking palindrome word\n $pal=$3;\n}\nif ($pal=~/^.?$/i){ #matches single letter or no letter\n print\"palindrome\\n\";\n}\nelse{\n print\"not palindrome\\n\";\n}\n" }, { "answer_id": 48080849, "author": "Josh", "author_id": 4464616, "author_profile": "https://Stackoverflow.com/users/4464616", "pm_score": 0, "selected": false, "text": "\\b([a-z])?([a-z])?([a-z])?\\2\\1\\b/gi" }, { "answer_id": 48608623, "author": "Peter Krauss", "author_id": 287948, "author_profile": "https://Stackoverflow.com/users/287948", "pm_score": 3, "selected": false, "text": " (\\w)(?:(?R)|\\w?)\\1\n $subjects=['dont','o','oo','kook','book','paper','kayak','okonoko','aaaaa','bbbb'];\n$pattern='/(\\w)(?:(?R)|\\w?)\\1/';\nforeach ($subjects as $sub) {\n echo $sub.\" \".str_repeat('-',15-strlen($sub)).\"-> \";\n if (preg_match($pattern,$sub,$m)) \n echo $m[0].(($m[0]==$sub)? \"! a palindrome!\\n\": \"\\n\");\n else \n echo \"sorry, no match\\n\";\n}\n dont ------------> sorry, no match\no ---------------> sorry, no match\noo --------------> oo! a palindrome!\nkook ------------> kook! a palindrome!\nbook ------------> oo\npaper -----------> pap\nkayak -----------> kayak! a palindrome!\nokonoko ---------> okonoko! a palindrome!\naaaaa -----------> aaaaa! a palindrome!\nbbbb ------------> bbb\n ^((\\w)(?:(?1)|\\w?)\\2)$ ^((.)(?:(?1)|.?)\\2)$ \\w ^((.)(?1)?\\2|.)$ ^((.)(?1)\\2|.?)$ ^((.)(?1)*\\2|.?)$ $subjects if (preg_match('/^((.)(?:(?1)|.?)\\2)$/',$sub)) echo \" ...reg_base($sub)!\\n\";\n if (preg_match('/^((.)(?1)?\\2|.)$/',$sub)) echo \" ...reg2($sub)!\\n\";\n if (preg_match('/^((.)(?1)\\2|.?)$/',$sub)) echo \" ...reg3($sub)!\\n\";\n if (preg_match('/^((.)(?1)*\\2|.?)$/',$sub)) echo \" ...reg4($sub)!\\n\";\n" }, { "answer_id": 50427024, "author": "Erik Rybalkin", "author_id": 7419092, "author_profile": "https://Stackoverflow.com/users/7419092", "pm_score": 0, "selected": false, "text": " function palindrome(str) {\n var symbol = /\\W|_/g;\n str = str.replace(symbol, \"\").toLowerCase();\n var palindrome = str.split(\"\").reverse(\"\").join(\"\");\n return (str === palindrome);\n}\n" }, { "answer_id": 60086224, "author": "Tony Tonev", "author_id": 512879, "author_profile": "https://Stackoverflow.com/users/512879", "pm_score": 2, "selected": false, "text": "\\b(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*(?:(\\w)[ \\t,'\"]*\\11?[ \\t,'\"]*\\10|\\10?)[ \\t,'\"]*\\9|\\9?)[ \\t,'\"]*\\8|\\8?)[ \\t,'\"]*\\7|\\7?)[ \\t,'\"]*\\6|\\6?)[ \\t,'\"]*\\5|\\5?)[ \\t,'\"]*\\4|\\4?)[ \\t,'\"]*\\3|\\3?)[ \\t,'\"]*\\2|\\2?))?[ \\t,'\"]*\\1\\b\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26276/" ]
233,251
<p>Since many years a GUI-standard are the menu-bars of applications with menus popping up, if you click or hover an entry in the menu-bar. Some websites implement this feature too, but they are using Javascript, as far as I can see. For different reasons Javascript can be a problem, so the question: Is this possible to implement without Javascript, only using HTML and CSS?</p>
[ { "answer_id": 233266, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "a:link {\n color: blue;\n}\n\na:hover {\n color: red;\n}\n" }, { "answer_id": 233269, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 5, "selected": true, "text": "<style>\n A DIV { display: none; }\n A:hover DIV { display: block; }\n</style>\n<a href=\"blah.htm\">\n Top Level Menu Text\n <div><ul>\n <li><a href=\"sub1.htm\">Sub Item 1</a></li>\n <li><a href=\"sub2.htm\">Sub Item 2</a></li>\n <li><a href=\"sub3.htm\">Sub Item 3</a></li>\n </ul></div>\n</a>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
233,255
<p>I am working on a project to enhance our production debugging capabilities. Our goal is to reliably produce a minidump on any unhandled exception, whether the exception is managed or unmanaged, and whether it occurs on a managed or unmanaged thread.</p> <p>We use the excellent <a href="http://www.debuginfo.com/tools/clrdump.html" rel="noreferrer">ClrDump</a> library for this currently, but it does not quite provide the exact features we need, and I'd like to understand the mechanisms behind exception filtering, so I set out to try this for myself.</p> <p>I started out by following this blog article to install an SEH handler myself: <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx" rel="noreferrer">http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx</a>. This technique works for console applications, but when I try the same thing from a WinForms application, my filter is not called for any variety of unmanaged exceptions.</p> <p>What can ClrDump be doing that I'm not doing? ClrDump produces dumps in all cases, so its exception filter must still be called...</p> <p>Note: I'm aware of ADPlus's capabilities, and we've also considered using the AeDebug registry keys... These are also possibilities, but also have their tradeoffs.</p> <p>Thanks, Dave</p> <pre><code>// Code adapted from &lt;http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx&gt; LONG WINAPI MyExceptionFilter(__in struct _EXCEPTION_POINTERS *ExceptionInfo) { printf("Native exception filter: %X\n",ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode); Beep(1000,1000); Sleep(500); Beep(1000,1000); if(oldFilter_ == NULL) { return EXCEPTION_CONTINUE_SEARCH; } LONG ret = oldFilter_(ExceptionInfo); printf("Other handler returned %d\n",ret); return ret; } #pragma managed namespace SEHInstaller { public ref class SEHInstall { public: static void InstallHandler() { oldFilter_ = SetUnhandledExceptionFilter(MyExceptionFilter); printf("Installed handler old=%x\n",oldFilter_); } }; } </code></pre>
[ { "answer_id": 238357, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 4, "selected": true, "text": "Application.ThreadException += new Threading.ThreadExceptionHandler(CatchFormsExceptions);\n" }, { "answer_id": 1481802, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": false, "text": "Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);\n Application.ThreadException += \n new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);\n AppDomain.CurrentDomain.UnhandledException += \n new UnhandledExceptionEventHandler(Program.CurrentDomain_UnhandledException);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6996/" ]
233,259
<p>I'm looking for ActiveX components that can easily: </p> <ul> <li>get and send emails via SMTP and POP3</li> <li>strip out and save attachments.</li> <li>Convert RTF (Outlook emails) to HTML</li> <li>Sanitize HTML.</li> </ul> <p>What components would you recommend? What components do you use?</p>
[ { "answer_id": 422437, "author": "LarryF", "author_id": 18518, "author_profile": "https://Stackoverflow.com/users/18518", "pm_score": 1, "selected": false, "text": "\n Content-Type: application/octet-stream\n Content-Transfer-Encoding: base64 \n\n http://virus.virussite.com\n JVBERi0xLjMgCiXi48/TIAo3IDAgb2JqCjw8Ci9Db250ZW50cyBbIDggMCBSIF0gCi9QYXJlbnQg\n NSAwIFIKL1Jlc291cmNlcyA2IDAgUgovVHlwZSAvUGFnZQo+PgplbmRvYmoKNiAwIG9iago8PAov" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726/" ]
233,261
<p>The strongly typed <code>SearchViewData</code> has a field called Colors that in it's turn is a <code>ColorViewData</code>. In my <code>/Colors.mvc/search</code> I populate this <code>viewData.Model.Colors</code> based on the given search criteria. Then, based on several factors, I render one of a set of user controls that are able to render itself with a <code>ColorViewData</code>.<br> So I will end up with:</p> <pre><code>&lt;%Html.RenderPartial("~/Views/Color/_ColorList.ascx", ViewData.Model.Colors);%&gt; </code></pre> <p>This used to work just fine, but since the upgrade to the beta1, my user control always ends up with <code>viewdata = null;</code></p> <p>Suggestions?</p>
[ { "answer_id": 233335, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 0, "selected": false, "text": "<% Html.RenderPartial(\"xxx\", new ViewDataDictionary(ViewData.Model.Colors)); %>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
233,264
<p>I have an ASP.NET application. Basically the delivery process is this one :</p> <ul> <li>Nant builds the application and creates a zip file on the developer's computer with the application files without SVN folders and useless files. This file is delivered with a Nant script.</li> <li>The zip and nant files are copied to the client's computer</li> <li>the Nant script replaces the current website files with the file contained in the zip file.</li> </ul> <p>My problem is that with this process I have an Unauthorized access error when I try to open the website. It seems that the files need to have a permission set for the user "<strong>IIS_WPG</strong>".</p> <p>I don't have the power to change IIS configuration so I have to manually change the permissions of each file. And each time I replace the files the permissions are removed and I need to set them again.</p> <p>So I have two questions :</p> <ul> <li>Can I change files permissions with Nant ? How to do it ?</li> <li>Is it possible to avoid this problem ? (developers don't have this user on their computers)</li> </ul>
[ { "answer_id": 233299, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 3, "selected": true, "text": "<exec program=\"cacls\">\n <arg value=\"*\" />\n <arg value=\"/G IIS_WPG:F\" />\n</exec>\n" }, { "answer_id": 233457, "author": "Julien N", "author_id": 28544, "author_profile": "https://Stackoverflow.com/users/28544", "pm_score": 3, "selected": false, "text": "cacls [full folder path] /T /E /G IIS_WPG:F\n" }, { "answer_id": 234339, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 2, "selected": false, "text": "[TaskName(\"addusertodir\")]\npublic class AddUserToDirectorySecurity : Task\n{\n [TaskAttribute(\"dir\", Required=true)]\n public string DirPath { get; set; }\n\n [TaskAttribute(\"user\", Required=true)]\n public string UserName { get; set; }\n\n protected override void ExecuteTask()\n {\n FileSystemAccessRule theRule1 = new FileSystemAccessRule(UserName, FileSystemRights.ListDirectory, AccessControlType.Allow);\n FileSystemAccessRule theRule2 = new FileSystemAccessRule(UserName, FileSystemRights.ReadAndExecute, AccessControlType.Allow);\n FileSystemAccessRule theRule3 = new FileSystemAccessRule(UserName, FileSystemRights.Read, AccessControlType.Allow);\n\n DirectorySecurity theDirSecurity = new DirectorySecurity();\n theDirSecurity.AddAccessRule(theRule1);\n theDirSecurity.AddAccessRule(theRule2);\n theDirSecurity.AddAccessRule(theRule3);\n Directory.SetAccessControl(DirPath, theDirSecurity);\n }\n}\n <loadtasks>\n <fileset>\n <include name=\"MyTask.dll\"/>\n </fileset>\n</loadtasks>\n\n<addusertodir dir=\"MyDir\" user=\"IIS_WPG\"/>\n" }, { "answer_id": 13016846, "author": "Ted Spence", "author_id": 419830, "author_profile": "https://Stackoverflow.com/users/419830", "pm_score": 2, "selected": false, "text": "${paths.myprogram.inetpub} ${upload.foldername} ${iis.upload.user} ${iis.user.permissionlevel} <exec program=\"icacls\">\n <arg value=\"${path::combine(paths.myprogram.inetpub, upload.foldername)}\" />\n <arg value=\"/grant\" />\n <arg value=\"${iis.upload.user}:${iis.user.permissionlevel}\" />\n</exec>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28544/" ]
233,283
<p>I'm starting a Wordpress Blog that will have adult content on it, so I'll need a first-time-only splash page in Wordpress. The first-time-only issue, I can fix with a cookie (although I am aware that not everyone has cookies enabled) </p> <p>What I could do is, create a script that loads another page if a cookie isn't present. Or I could make the splash page be my home page, and if the cookie is present, redirect. </p> <p>But that's not really what I'm looking for. I don't want to hassle with pages. In stead I'm looking for a lightbox-y solution, that darkens the background (the home page) and shows a panel with the choice to stay or leave. </p> <p>I haven't got a clue on how to start this. I am familiar with PHP, Javascript and CSS, so I'm not even asking for code. I just want a web programmer's view on this, and some help on how to create the splash-page the way I would like it. Or is it a stupid idea?</p>
[ { "answer_id": 9507418, "author": "Trey Copeland", "author_id": 1830549, "author_profile": "https://Stackoverflow.com/users/1830549", "pm_score": 1, "selected": false, "text": "#inline_content display: none; <script>\n\n $(document).ready(function() { \n\n if (document.cookie.indexOf('visited=true') === -1) {\n var expires = new Date();\n expires.setDate(expires.getDate()+30);\n document.cookie = \"visited=true; expires=\"+expires.toUTCString();\n $.colorbox({inline:true, width:\"40%\", height:\"450px\", href:\"#inline_content\"});\n\n }\n\n\n });\n\n </script>\n" }, { "answer_id": 12272564, "author": "Bojana Šekeljić", "author_id": 1647537, "author_profile": "https://Stackoverflow.com/users/1647537", "pm_score": 2, "selected": false, "text": "display: none $.colorbox({html:\"<div id=\\\"splash-wrapper\\\"><h1>it works</h1></div>\"});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31145/" ]
233,284
<p>I have created a .NET DLL which makes some methods COM visible.</p> <p>One method is problematic. It looks like this:</p> <pre><code>bool Foo(byte[] a, ref byte[] b, string c, ref string d) </code></pre> <p>VB6 gives a compile error when I attempt to call the method:</p> <blockquote> <p>Function or interface marked as restricted, or the function uses an Automation type not supported in Visual Basic.</p> </blockquote> <p>I read that array parameters must be passed by reference, so I altered the first parameter in the signature:</p> <pre><code>bool Foo(ref byte[] a, ref byte[] b, string c, ref string d) </code></pre> <p>VB6 still gives the same compile error.</p> <p>How might I alter the signature to be compatible with VB6?</p>
[ { "answer_id": 233451, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "[ComVisible(true)]\nbool Foo([In] ref byte[] a, [In] ref byte[] b, string c, ref string d)\n" }, { "answer_id": 233486, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 4, "selected": true, "text": "[ComVisible(true)]\npublic interface IMyInterface {\n bool Foo(ref byte[] a, ref byte[] b,string c, ref string d);\n}\n\n[ComVisible(true)]\npublic class MyClass : IMyInterface {\n public bool Foo(ref byte[] a, ref byte[] b, string c, ref string d) {\n throw new NotImplementedException();\n }\n}\n\n\n Dim obj As ClassLibrary10.IMyInterface\n Set obj = New ClassLibrary10.MyClass\n Dim binp() As Byte\n Dim bout() As Byte\n Dim sinp As String\n Dim sout As String\n Dim retval As Boolean\n retval = obj.Foo(binp, bout, sinp, sout)\n" }, { "answer_id": 1519012, "author": "Marthinus", "author_id": 101732, "author_profile": "https://Stackoverflow.com/users/101732", "pm_score": 1, "selected": false, "text": "public long ProcessWiWalletTransaction(ref IWiWalletTransaction wiWalletTransaction)\n public int ProcessWiWalletTransaction(ref IWiWalletTransaction wiWalletTransaction)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/329888/" ]
233,288
<p><strong>I have class A:</strong></p> <pre><code>public class ClassA&lt;T&gt; </code></pre> <p><strong>Class B derives from A:</strong></p> <pre><code>public class ClassB : ClassA&lt;ClassB&gt; </code></pre> <p><strong>Class C derives from class B:</strong></p> <pre><code>public class ClassC : ClassB </code></pre> <p><strong>Now I have a generic method with constraints</strong></p> <pre><code>public static T Method&lt;T&gt;() where T : ClassA&lt;T&gt; </code></pre> <p>OK, now I want to call:</p> <pre><code>ClassC c = Method&lt;ClassC&gt;(); </code></pre> <p>but I get the compile error saying: <code>Type argument 'ClassC' does not inherit from or implement the constraint type 'ClassA&lt;ClassC&gt;.</code></p> <p>Yet, the compiler will allow:</p> <pre><code>ClassB b = Method&lt;ClassB&gt;(); </code></pre> <p>My understanding is that this fails because <code>ClassC</code> inherits <code>ClassA&lt;ClassB&gt;</code> instead of <code>ClassA&lt;ClassC&gt;</code></p> <p><strong>My real question is, is it possible to create a class deriving from <code>ClassB</code> that can be used in some way with the generic method?</strong></p> <p>This may seem like generics are overused and I would agree. I am trying to create business layer objects deriving from the subsonic data objects in a separate project.</p> <p>Note: I have put the &lt; T > with extra spaces otherwise they get stripped from the question.</p>
[ { "answer_id": 233303, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "public static T Method<T,U>() where T : ClassA<U> where U : T\n" }, { "answer_id": 233425, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 1, "selected": false, "text": "public abstract class BasicClassA\n{\n}\n\npublic class ClassA<T> : BasicClassA\n{\n}\n\npublic class ClassB : ClassA<ClassB>\n{\n}\n\npublic class ClassC : ClassB\n{\n}\n\npublic static T Method<T>() where T : BasicClassA\n{\n return null;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24681/" ]
233,320
<p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a> is supposed to be preinstalled) I get:</p> <pre><code>[root@idev htdocs]# python Python 2.6 (r26:66714, Oct 23 2008, 16:25:34) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named sqlite &gt;&gt;&gt; </code></pre> <p>How do I resolve this?</p>
[ { "answer_id": 233336, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": false, "text": "import sqlite3\n .so _sqlite3 ${somewhere}/lib/python2.6/lib-dynload/_sqlite3.so\n" }, { "answer_id": 233865, "author": "razong", "author_id": 29885, "author_profile": "https://Stackoverflow.com/users/29885", "pm_score": 5, "selected": true, "text": "ImportError: No module named _sqlite3\n import sys\nprint sys.path\n sys.path.append('/your/dir/here')\n import sqlite3\n" }, { "answer_id": 233883, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 1, "selected": false, "text": "from pysqlite2 import dbapi2 as sqlite\n" }, { "answer_id": 233967, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "_sqlite3.so '/usr/lib/python2.6/lib-dynload/_sqlite3.so'\n sys.path >>> import sys; print(filter(lambda p: 'lib-dynload' in p, sys.path))\n['/usr/lib/python2.6/lib-dynload']\n" }, { "answer_id": 939030, "author": "Dickon Reed", "author_id": 22668, "author_profile": "https://Stackoverflow.com/users/22668", "pm_score": 3, "selected": false, "text": "sudo yum install sqlite-devel" }, { "answer_id": 953786, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "Python 2.5.4 (r254:67916, May 31 2009, 16:56:01)\n[GCC 4.3.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sqlite\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named sqlite\n>>> import sqlite3\n>>>\n" }, { "answer_id": 2692335, "author": "98.", "author_id": 323429, "author_profile": "https://Stackoverflow.com/users/323429", "pm_score": 0, "selected": false, "text": "\"py25-sqlite3 @2.5.4 (python, databases)\n This is a stub. sqlite3 is now built with python25\"\n python25 @2.5.5_0 $ sudo port upgrade python25\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3404/" ]
233,328
<p>I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?</p>
[ { "answer_id": 233339, "author": "John Carter", "author_id": 8331, "author_profile": "https://Stackoverflow.com/users/8331", "pm_score": 10, "selected": true, "text": "set print elements 0\n set print elements number-of-elements set print elements" }, { "answer_id": 253120, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "call (void)puts(your_string)" }, { "answer_id": 7677311, "author": "Wichert Akkerman", "author_id": 211490, "author_profile": "https://Stackoverflow.com/users/211490", "pm_score": 5, "selected": false, "text": "x/300s your_string" }, { "answer_id": 8909030, "author": "abstraktor", "author_id": 647213, "author_profile": "https://Stackoverflow.com/users/647213", "pm_score": 5, "selected": false, "text": "(gdb) p (char[10]) *($ebx)\n$87 = \"asdfasdfe\\n\"\n (gdb) p/x (char[10]) *($ebx)\n$90 = {0x61,\n 0x73,\n 0x64,\n 0x66,\n 0x61,\n 0x73,\n 0x64,\n 0x66,\n 0x65,\n 0xa}\n" }, { "answer_id": 34075827, "author": "korry", "author_id": 3882261, "author_profile": "https://Stackoverflow.com/users/3882261", "pm_score": 6, "selected": false, "text": "printf (gdb) printf \"%s\\n\", string\n" }, { "answer_id": 37984536, "author": "mrtimdog", "author_id": 309870, "author_profile": "https://Stackoverflow.com/users/309870", "pm_score": 2, "selected": false, "text": "set elements ... set string-elements ... define pstr\n ptype $arg0._M_dataplus._M_p\n printf \"[%d] = %s\\n\", $arg0._M_string_length, $arg0._M_dataplus._M_p\nend\n\ndefine pcstr\n ptype $arg0\n printf \"[%d] = %s\\n\", strlen($arg0), $arg0\nend\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8331/" ]
233,358
<p>A quick question about elf file headers, I can't seem to find anything useful on how to add/change fields in the elf header. I'd like to be able to change the magic numbers and to add a build date to the header, and probably a few other things. </p> <p>As I understand it the linker creates the header information, but I don't see anything in the LD script that refers to it (though i'm new to ld scripts).</p> <p>I'm using gcc and building for ARM.</p> <p>thanks!</p> <p>Updates:</p> <ul> <li>ok maybe my first question should be: is it possible to create/edit the header file at link time?</li> </ul>
[ { "answer_id": 47084888, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 2, "selected": false, "text": "info.c #ident #ident \"Build: 1.2.3 (Halloween)\"\n#ident \"Environment: example.org\"\n $ gcc -c info.c\n $ readelf -p .comment info.o\nString dump of section '.comment':\n [ 1] Build: 1.2.3 (Halloween)\n [ 1a] Environment: example.org\n [ 33] GCC: (GNU) 7.2.1 20170915 (Red Hat 7.2.1-2)\n objdump -s --section .comment info.o $ gcc -o main main.o info.o\n$ readelf -p .comment main \nString dump of section '.comment':\n [ 0] GCC: (GNU) 7.2.1 20170915 (Red Hat 7.2.1-2)\n [ 2c] Build: 1.2.3 (Halloween)\n [ 45] Environment: example.org\n #ident .comment $ cat info.s\n.section .comment\n.string \"Build: 1.2.3 (Halloween)\"\n.string \"Environment: example.org\"\n$ gcc -c info.s\n$ readelf -p .comment info.o\nString dump of section '.comment':\n [ 0] Build: 1.2.3 (Halloween)\n [ 19] Environment: example.org\n .section .blahblah .comment .ident #ident $ cat magic.bin \n2342\n $ objcopy -I binary -O elf64-x86-64 -B i386 \\\n --rename-section .data=.rodata,alloc,load,readonly,data,contents \\\n magic.bin magic.o\n $ nm magic.o \n0000000000000005 R _binary_magic_bin_end\n0000000000000005 A _binary_magic_bin_size\n0000000000000000 R _binary_magic_bin_start\n #include <stdio.h>\n#include <string.h>\n#include <inttypes.h>\n\nextern const char _binary_magic_bin_start[];\nextern const char _binary_magic_bin_end[];\nextern const unsigned char _binary_magic_bin_size;\nstatic const size_t magic_bin_size = (uintptr_t) &_binary_magic_bin_size;\n\nint main()\n{\n char s[23];\n memcpy(s, _binary_magic_bin_start,\n _binary_magic_bin_end - _binary_magic_bin_start);\n s[magic_bin_size] = 0;\n puts(s);\n return 0;\n}\n $ gcc -g -o main_magic main_magic.c magic.o\n $ ld -r -b binary magic.bin -o magic-ld.o\n .data .rodata objdump -h magic.o .incbin gcc -c incbin.s .section .rodata\n\n .global _binary_magic_bin_start\n .type _binary_magic_bin_start, @object\n_binary_magic_bin_start:\n .incbin \"magic.bin\"\n .size _binary_magic_bin_start, . - _binary_magic_bin_start\n\n .global _binary_magic_bin_size\n .type _binary_magic_bin_size, @object\n .set _binary_magic_bin_size, . - _binary_magic_bin_start\n\n .global _binary_magic_bin_end\n .type _binary_magic_bin_end, @object\n .set _binary_magic_bin_end, _binary_magic_bin_start + _binary_magic_bin_size\n ; an alternate way to include the size \n .global _binary_magic_bin_len\n .type _binary_magic_bin_len, @object\n .size _binary_magic_bin_len, 8\n_binary_magic_bin_len:\n .quad _binary_magic_bin_size\n $ xxd -i magic.bin | sed 's/\\(unsigned\\)/const \\1/' > magic.c\n$ gcc -c magic.c\n$ nm magic.o\n0000000000000000 R magic_bin\n0000000000000008 R magic_bin_len\n$ cat magic.c\nconst unsigned char magic_bin[] = {\n 0x32, 0x33, 0x34, 0x32, 0x0a\n};\nconst unsigned int magic_bin_len = 5;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
233,360
<p>How useful, if at all, is for the testers on a product team to know about the internal code details of a product. This does not mean they need to know every line of code but a good idea of how the code is structured, what is the object model, how the various modules are inter-linked, what are the inter-dependencies between various features etc.? This can argubaly help them in finding related issues or defects once they hit one. On the other side, this can potentially 'bias' their "user-centric" approach towards evaluating and certifying the product and can effect the testing results in the end.</p> <p>I have not heard of any specific model for such interaction. (Lets assume a product that users, potentially non-technical consume, and not a framework or API that the testers are testing - in the latter case the testers may need to understand the code to test that because the user is another programmer). </p>
[ { "answer_id": 233498, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "long long int increment(long long int l) {\n if (l == 475636294934LL) return 3;\n return l + 1;\n}\n int MyConnect(socket *sock) {\n /* socket must have been bound already, but that's OK */\n return RealConnect(sock);\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1065163/" ]
233,379
<p>We have a WinForms application which runs on a touch-screen on a bit of industrial equipment. For historical reasons which are not up for changing today, the displayed form has a normal Windows title bar. </p> <p>We would like to stop people using the mouse (i.e. touchscreen) from moving the window by dragging the title bar. We don't care if there's some other way to move the window using the keyboard.</p> <p>What's the most elegant way to achieve this? I can think of trying to subvert mouse messages if there's a mouse-down on the titlebar (though NC hit-testing doesn't at first glance seem completely obvious in Winforms), and I can think of responding to Move messages in some way which restores the window position.</p> <p>But both of these seem clunky, and I have a feeling I am missing something elegant and obvious.</p>
[ { "answer_id": 233514, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": " protected override void WndProc(ref Message msg)\n {\n const int WM_NCLBUTTONDOWN = 0xa1;\n\n switch (msg.Msg)\n {\n case WM_NCLBUTTONDOWN:\n // To prevent people moving the window with the mouse \n // unless CTRL is held\n if (!(GetKeyState((int)Keys.ControlKey) < 0))\n {\n return;\n }\n break;\n }\n base.WndProc(ref msg);\n }\n" }, { "answer_id": 4598922, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "WndProc WM_NCHITTEST base.WndProc HTCAPTION HTNONE" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987/" ]
233,382
<p>I have to override Add method of "Controls" property of myControl that is extended from a Panel control of windows. For that i extended ControlCollection class into MyControlCollection where i overriden its Add method. Now i declared a Controls property of MyControlCollection type to hide panel's Controls property. When i am accessing this.Controls.Add(control), it refers to overriden Add method. But if i drags and drops a control on myControl the behaviour is of base type's Add method. Can any body suggest the cause and remedy for this problem? Thanks in advance.</p>
[ { "answer_id": 233398, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "ControlCollection Control ControlAdded" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31159/" ]
233,411
<p>Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below.</p> <p><img src="https://i.stack.imgur.com/ss2sE.png" alt="alt text"></p>
[ { "answer_id": 233826, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 5, "selected": true, "text": "DISPLAY_DEVICE_ATTACHED_TO_DESKTOP" }, { "answer_id": 507370, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "ChangeDisplaySettingsEx DEVMODE dm = new DEVMODE();\ndm.dmSize = (short)Marshal.SizeOf(dm);\ndm.dmPelsWidth = 1680;\ndm.dmPelsHeight = 1050;\ndm.dmBitsPerPel = 32;\ndm.dmDisplayFrequency = 60;\ndm.dmFields = DevModeFields.DM_BITSPERPEL | DevModeFields.DM_PELSWIDTH | \n DevModeFields.DM_PELSHEIGHT | DevModeFields.DM_DISPLAYFREQUENCY;\nint res = ChangeDisplaySettingsEx(@\"\\\\.\\DISPLAY2\", ref dm, IntPtr.Zero, CDS_RESET | CDS_UPDATEREGISTRY, IntPtr.Zero);\nConsole.WriteLine(\"result = \" + res.ToString());\n" }, { "answer_id": 3126716, "author": "Robert Baker", "author_id": 263457, "author_profile": "https://Stackoverflow.com/users/263457", "pm_score": 4, "selected": false, "text": " private static Process DisplayChanger = new Process\n {\n StartInfo =\n {\n CreateNoWindow = true,\n WindowStyle = ProcessWindowStyle.Hidden,\n FileName = \"DisplaySwitch.exe\",\n Arguments = \"/extend\"\n }\n };\n" }, { "answer_id": 4962012, "author": "user", "author_id": 612018, "author_profile": "https://Stackoverflow.com/users/612018", "pm_score": 1, "selected": false, "text": "POINTL enabledPosition = new POINTL();\nenabledPosition.x = -1280;\nenabledPosition.y = 0;\n\ndm.dmPosition = enabledPosition;\ndm.dmFields = DM.Position;\nres = ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, (uint) DeviceFlags.CDS_UPDATEREGISTRY, IntPtr.Zero);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4500/" ]
233,421
<p>Is there currently a way to host a shared Git repository in Windows? I understand that you can configure the Git service in Linux with:</p> <pre><code>git daemon </code></pre> <p>Is there a native Windows option, short of sharing folders, to host a Git service?</p> <p>EDIT: I am currently using the cygwin install of git to store and work with git repositories in Windows, but I would like to take the next step of hosting a repository with a service that can provide access to others.</p>
[ { "answer_id": 2275844, "author": "Derek Greer", "author_id": 1219618, "author_profile": "https://Stackoverflow.com/users/1219618", "pm_score": 7, "selected": true, "text": "#!/bin/bash\n\n/usr/bin/git daemon --reuseaddr --base-path=/git --export-all --verbose --enable=receive-pack\n cygrunsrv --install gitd \\\n --path c:/cygwin64/bin/bash.exe \\\n --args c:/cygwin64/usr/local/bin/gitd \\\n --desc \"Git Daemon\" \\\n --neverexits \\\n --shutdown\n #!/bin/bash\n\necho \"Creating main git repo ...\"\nmkdir -p /git/testapp.git\ncd /git/testapp.git\ngit init --bare\ntouch git-daemon-export-ok\necho \"Creating local repo ...\"\ncd\nmkdir testapp\ncd testapp\ngit init\necho \"Creating test file ...\"\ntouch testfile\ngit add -A\ngit commit -m 'Test message'\necho \"Pushing master to main repo ...\"\ngit push git://localhost/testapp.git master\n" }, { "answer_id": 4208755, "author": "isaac", "author_id": 511283, "author_profile": "https://Stackoverflow.com/users/511283", "pm_score": 3, "selected": false, "text": "cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062: The service has not been started. cygrunsrv --start gitd\n" }, { "answer_id": 6351449, "author": "disrvptor", "author_id": 494307, "author_profile": "https://Stackoverflow.com/users/494307", "pm_score": 0, "selected": false, "text": "cygrunsrv --install gitd \\\n --path c:/cygwin/bin/bash.exe \\\n --args /usr/bin/gitd \\\n --desc \"Git Daemon\" \\\n --neverexits \\\n --shutdown\n" }, { "answer_id": 6556829, "author": "David Thomas", "author_id": 583715, "author_profile": "https://Stackoverflow.com/users/583715", "pm_score": 2, "selected": false, "text": "## GIT HTTP DAV ##\n<VirtualHost *:80>\n\n ServerName git.example.com\n DocumentRoot C:\\webroot\\htdocs\\restricted\\git\n ErrorLog C:\\webroot\\apache\\logs\\error-git-webdav.log\n\n <Location />\n DAV on\n # Restrict Access\n AuthType Basic\n AuthName \"Restricted Area\"\n AuthUserFile \"C:\\webroot\\apache\\conf\\git-htpasswd\"\n # To valid user\n Require valid-user\n # AND valid IP address\n Order Deny,Allow\n Deny from all\n # Example IP 1\n Allow from 203.22.56.67 \n # Example IP 2\n Allow from 202.12.33.44 \n # Require both authentication checks to be satisfied\n Satisfy all\n </Location>\n\n</VirtualHost>\n [core]\n repositoryformatversion = 0\n filemode = true\n bare = false\n logallrefupdates = true\n[remote \"origin\"]\n fetch = +refs/heads/*:refs/remotes/origin/*\n url = http://username:password@git.example.com/codebase.git\n[branch \"master\"]\n remote = origin\n merge = refs/heads/master\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29156/" ]
233,434
<p>I am trying to make our SQL Server Integration Services packages as portable as possible and the one thing that is preventing that is that the path to the config is always an absolute path, which makes testing and deployment a headache. Are there any suggestions for making this more manageble?</p> <p>Another issue is when another developer gets the package out of source control the path is specific to the developers machine.</p>
[ { "answer_id": 233528, "author": "Malik Daud Ahmad Khokhar", "author_id": 1688440, "author_profile": "https://Stackoverflow.com/users/1688440", "pm_score": 5, "selected": true, "text": "dtexec /File Package.dtsx /Conf configuration.dtsConfig\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12915/" ]
233,441
<p>On the SVN server, there is a file called <code>config.conf</code>. I have a local version called the same thing (in the same place). <strong>How can I make sure that my local config does not get overwritten, nor checked in?</strong> </p> <p>While I'm here, is the answer different for a directory?</p> <p>I'm using Tortoise SVN, but command line answers are cool.</p> <p>Thanks!</p> <p>[Sorry if this basic question has been asked before... I looked but didn't find it.]</p>
[ { "answer_id": 233460, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 3, "selected": true, "text": "mv config.conf config.conf.theirs && mv config.conf.mine config.conf" }, { "answer_id": 233573, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "config.default.php if (file_exists(\"config.php\")) require \"config.php\";\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
233,443
<p>I need to display a small (15x15 pixel) animation in a Flex app. I have it FLV format, but it could be converted to somthing else. I'd prefer to have the file embedded in the app (it's only 8k in size). I've seen posts about displaying animated GIFs using third-party code which would be OK, but is there a way to do this with the native Flex libs. I also realize that FLVs can be displayed in Video objects but only if they are external files.</p>
[ { "answer_id": 235296, "author": "Chetan S", "author_id": 31284, "author_profile": "https://Stackoverflow.com/users/31284", "pm_score": 1, "selected": false, "text": "Image" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15899/" ]
233,446
<p>I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.</p>
[ { "answer_id": 29435614, "author": "Bruno STEUX", "author_id": 3778294, "author_profile": "https://Stackoverflow.com/users/3778294", "pm_score": 2, "selected": false, "text": "int getBatteryLevel()\n{\n SYSTEM_POWER_STATUS status;\n GetSystemPowerStatus(&status);\n return status.BatteryLifePercent;\n}\n" }, { "answer_id": 60140012, "author": "Sahil Singh", "author_id": 981766, "author_profile": "https://Stackoverflow.com/users/981766", "pm_score": 0, "selected": false, "text": "PBT_APMPOWERSTATUSCHANGE BatteryLifePercent SYSTEM_POWER_STATUS WM_POWERBROADCAST PBT_APMPOWERSTATUSCHANGE PBT_APMPOWERSTATUSCHANGE" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9458/" ]
233,455
<p>I am making a program in C# to connect to a webcam and do some image manipulation with it.</p> <p>I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program results in null pointers.</p> <p>This is the code I use to connect the webcam:</p> <pre><code>mCapHwnd = capCreateCaptureWindowA(&quot;WebCap&quot;, 0, 0, 0, 320, 240, 1024, 0); SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0); SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0); </code></pre> <p>And this is what I use to copy the image to the clipboard:</p> <pre><code>SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0); SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0); tempObj = Clipboard.GetDataObject(); tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap); </code></pre> <p>There's some error checking which I have removed from the code to make it shorter.</p>
[ { "answer_id": 234423, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 5, "selected": true, "text": "using (var cv = new OpenCVDotNet.CVCapture(0))\n{\n var image = cv.CreateCompatibleImage();\n // ...\n cv.Release();\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31151/" ]
233,467
<p>I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).</p> <p>What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.</p> <p>I know that <code>&lt;a href="url" target="_blank"&gt;</code> is out. I also know that <code>&lt;a href="#" onclick="window.open(url);"&gt;</code> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <code>&lt;span onclick="window.open(url);"&gt;</code> and then style the SPAN to look like a link.</p> <p>One solution I'm leaning towards is <code>&lt;a href="url" rel="external"&gt;</code> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.</p> <p>Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.</p> <p>UPDATE: I say target="_blank" is a no no, because I've read in <a href="http://www.sitepoint.com/article/standards-compliant-world/3/" rel="noreferrer">several places</a> that the target attribute is going to be phased out of XHTML.</p>
[ { "answer_id": 233477, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 4, "selected": false, "text": "target=\"_blank\"" }, { "answer_id": 233495, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 1, "selected": false, "text": "<a href=\"http://www.google.com\" onclick=\"window.open(this.href); return false\">\n" }, { "answer_id": 233503, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 6, "selected": true, "text": "$(document).ready(function() {\n $('a[rel*=external]').click(function(){\n window.open($(this).attr('href'));\n return false; \n });\n});\n href" }, { "answer_id": 233658, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<a href=\"...\" target=\"_blank\" onclick=\"window.open(this.href, 'newWin'); return false;\">link</a>\n" }, { "answer_id": 236037, "author": "Fczbkk", "author_id": 22920, "author_profile": "https://Stackoverflow.com/users/22920", "pm_score": 2, "selected": false, "text": "<a href=\"http://some.website.com/\" onclick=\"return !window.open( this.href );\">link text</a>\n" }, { "answer_id": 1107714, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 3, "selected": false, "text": " (function($){ \n $.fn.newWindow = function(options) { \n var defaults = {\n titleText: 'Link opens in a new window' \n };\n\n options = $.extend(defaults, options);\n\n return this.each(function() { \n var obj = $(this);\n\n if (options.titleText) { \n if (obj.attr('title')) {\n var newTitle = obj.attr('title') + ' (' \n + options.titleText + ')';\n } else {\n var newTitle = options.titleText;\n }; \n obj.attr('title', newTitle); \n }; \n\n obj.click(function(event) {\n event.preventDefault(); \n var newBlankWindow = window.open(obj.attr('href'), '_blank');\n newBlankWindow.focus();\n }); \n }); \n }; \n })(jQuery); \n $('a[rel=external]').newWindow();\n $('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );\n $('a[rel=external]').newWindow( { titleText: '' } );\n" }, { "answer_id": 3366946, "author": "Mac", "author_id": 406196, "author_profile": "https://Stackoverflow.com/users/406196", "pm_score": 0, "selected": false, "text": "$(function() {\n $(\"a:not([href^='\"+window.location.hostname+\"'])\").click(function(){\n window.open(this.href);\n return false;\n }).attr(\"title\", \"Opens in a new window\");\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22303/" ]
233,468
<p>I have a number of custom controls that I am trying to enable designer support for. The signature looks something like the following:</p> <pre><code>[ToolboxData("&lt;{0}:MyDropDownList runat=\"server\" CustomProp="123"&gt;&lt;/{0}:MyDropDownList&gt;")] public class MyDropDownList: DropDownList { ... code here } </code></pre> <p>This works fine, but when I drag a control onto the page from the toolbox, the TagPrefix that gets added is "cc1":</p> <pre><code>&lt;%@ Register Assembly="DBMClientPortal.Controls" Namespace="DBMClientPortal.Controls" TagPrefix="cc1" %&gt; </code></pre> <p>Obviously it is somewhat irrelevant what that TagPrefix is... it works as it stands, but I figured I <em>must</em> be able to change it somehow and curiosity got the better of me...</p> <p>Anyone know how to define what the TagPrefix will be set to when dragging a custom control onto a page in visual studio?</p> <p>Thanks, Max</p>
[ { "answer_id": 233484, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 4, "selected": true, "text": "[assembly:TagPrefix(\"MyControls\",\"RequiredTextBox\")]\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29662/" ]
233,475
<p>I'm writing tests for a business method that invokes some DAO classes to perform operations over a database.</p> <p>This method, firstly retrieves a JDBC connection from a DataSource object, The same connection is passed to all DAO instances, so I can use it to control the transaction. So, if everything works properly, I must invoke commit() over the connection object.</p> <p>I would like to test if the commit() is invoked, so I've thought to create an expectation (I'm using JMock) that checks that. But since the Connection class isn't a direct neighbour from my Business class, I don't know how to do this.</p> <p>Someone knows how to overcome this? There is some JMock facility for this, or some alternative design that allows to overcome this?</p> <p>Thanks</p>
[ { "answer_id": 233492, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "DataSource Connection DataSource Connection" }, { "answer_id": 233499, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "setDataSource()" }, { "answer_id": 489050, "author": "Jan Kronquist", "author_id": 43935, "author_profile": "https://Stackoverflow.com/users/43935", "pm_score": 1, "selected": false, "text": "public void updateName(int id, String name) {\n getJdbcTemplate().update(\n \"update mytable set name = ? where id = ?\", \n new Object[] {name, new Integer(id)});\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9025/" ]
233,490
<p>I need to access a network resource on which only a given Domain Account has access. I am using the LogonUser call, but get a "User does not have required priviliege" exception, as the web application is running with the asp.net account and it does not have adequate permissions to make this call.</p> <p>Is there a way to get around it? Changing the identity or permissions of the ASP.Net account is not an option as this is a production machine with many projects running. Is there a better way to achieve this?</p> <p>Using Asp.Net 2.0, Forms Authentication.</p> <p>Kind Regards.</p>
[ { "answer_id": 233538, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "<identity impersonate=\"true\" userName=\"\"/>\n NET USE Z: \\\\SERVER\\Share password /USER:DOMAIN\\Username /PERSISTENT:YES\n" }, { "answer_id": 1327185, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<DllImport(\"advapi32.dll\", SetLastError:=True)> _\nPublic Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean\nEnd Function\n\n<DllImport(\"advapi32.dll\", EntryPoint:=\"DuplicateToken\", ExactSpelling:=False, CharSet:=CharSet.Auto, SetLastError:=True)> _\nPublic Shared Function DuplicateToken(ByVal ExistingTokenHandle As IntPtr, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Integer\nEnd Function\n\nPublic Shared Function WinLogOn(ByVal strUsuario As String, ByVal strClave As String, ByVal strDominio As String) As WindowsImpersonationContext\n Dim tokenDuplicate As New IntPtr(0)\n Dim tokenHandle As New IntPtr(0)\n If LogonUser(strUsuario, strDominio, strClave, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle) Then\n If DuplicateToken(tokenHandle, 2, tokenDuplicate) <> 0 Then\n Return (New WindowsIdentity(tokenDuplicate)).Impersonate()\n End If\n End If\n Return Nothing\nEnd Function\n Protected WithEvents File1 As HtmlInputFile\n\nDim vdestino As String = \"\\\\centappd20nd01\\uploads_avisos\"\nDim vtemporal As String = \"c:\\pdf\"\n\nProtected WithEvents boton1 As Button\nProtected WithEvents usuario As TextBox\nProtected WithEvents contra As TextBox\nProtected WithEvents dominio As TextBox\nProtected WithEvents destino As TextBox\nProtected WithEvents origen As TextBox\nProtected WithEvents temporal As TextBox\nProtected WithEvents log As TextBox\n'Render this Web Part to the output parameter specified.\nProtected Overrides Sub RenderWebPart(ByVal output As System.Web.UI.HtmlTextWriter)\n log.RenderControl(output)\n output.Write(\"<br><font>Ruta Origen</font><br>\")\n File1.RenderControl(output)\n output.Write(\"<br><font>Ruta Temporal </font><br>\")\n temporal.RenderControl(output)\n output.Write(\"<br><font>Ruta Destino </font><br>\")\n destino.RenderControl(output)\n output.Write(\"<br><font>Usuario </font><br>\")\n usuario.RenderControl(output)\n output.Write(\"<br><font>Contraseña </font><br>\")\n contra.RenderControl(output)\n output.Write(\"<br><font>Dominio </font><br>\")\n dominio.RenderControl(output)\n output.Write(\"<br><br><center>\")\n boton1.RenderControl(output)\n output.Write(\"</center>\")\nEnd Sub\nProtected Overrides Sub CreateChildControls()\n\n dominio = New TextBox\n With dominio\n .Text = \"admon-cfnavarra\"\n .Width = Unit.Pixel(\"255\")\n End With\n Controls.Add(dominio)\n\n boton1 = New Button\n With boton1\n .Text = \"Copiar Fichero\"\n End With\n Controls.Add(boton1)\n\n File1 = New HtmlInputFile\n With File1\n\n End With\n Controls.Add(File1)\n\n usuario = New TextBox\n With usuario\n .Text = \"SVCWSINCPre_SNS\"\n .Width = Unit.Pixel(\"255\")\n End With\n Controls.Add(usuario)\n\n contra = New TextBox\n With contra\n .Text = \"SVCWSINCPre_SNS\"\n .Width = Unit.Pixel(\"255\")\n End With\n Controls.Add(contra)\n\n destino = New TextBox\n With destino\n .Text = vdestino\n .Width = Unit.Pixel(\"255\")\n End With\n Controls.Add(destino)\n\n log = New TextBox\n With log\n .Width = Unit.Percentage(100)\n .BackColor = System.Drawing.Color.Black\n .ForeColor = System.Drawing.Color.White\n End With\n Controls.Add(log)\n\n temporal = New TextBox\n With temporal\n .Text = vtemporal\n .Width = Unit.Pixel(\"255\")\n End With\n Controls.Add(temporal)\nEnd Sub\nPrivate Sub boton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles boton1.Click\n If File1.PostedFile.FileName <> \"\" Then\n Dim _objContext As WindowsImpersonationContext = Nothing\n log.Text = QuienSoy()\n CopyFile(File1.PostedFile.FileName, temporal.Text)\n _objContext = Impersonalizacion.WinLogOn(usuario.Text, contra.Text, dominio.Text)\n CopyFile(temporal.Text & \"\\\" & System.IO.Path.GetFileName(File1.PostedFile.FileName), destino.Text)\n _objContext.Undo()\n Else\n log.Text = \"Se debe introducir un fichero\"\n End If\nEnd Sub\nFriend Shared Function QuienSoy() As String\n Return WindowsIdentity.GetCurrent().Name\nEnd Function\nPublic Function CopyFile(ByVal StartPath As String, ByVal EndPath As String)\n Try\n Dim fn As String = System.IO.Path.GetFileName(StartPath)\n System.IO.File.Copy(StartPath, EndPath & \"\\\" & fn, False)\n log.Text = \"Fichero Copiado Correctamente\"\n Catch ex As Exception\n log.Text = ex.Message\n End Try\nEnd Function\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21586/" ]
233,491
<p>Specifically, I currently have a JPanel with a TitledBorder. I want to customize the look of the border. In my app's current state, the title is drawn, but not the line border itself.</p> <p>If I bind an imagePainter to the panelBorder method for Panel objects, I can put a custom image around panels -- however it only shows up on those panels that I haven't explicitly set the border on in the code. Here's what that code looks like:</p> <pre><code>&lt;style id="PanelStyle"&gt; &lt;state&gt; &lt;imagePainter method="panelBorder" path="images/thick border.png" sourceInsets="3 3 3 3" /&gt; &lt;/state&gt; &lt;/style&gt; &lt;bind style="PanelStyle" type="region" key="Panel" /&gt; </code></pre> <p>How can I do the opposite -- that is, make this custom image only show up on panels I've applied a TitledBorder to?</p> <p>I have also tried using a named panel:</p> <pre><code>panel.setName("MyPanel") </code></pre> <p>and a name binding:</p> <pre><code>&lt;bind style="PanelStyle" type="name" key="MyPanel"&gt; </code></pre> <p>This allows me to change the style of only particular panels, which is good. However, it does not solve the original problem: I still can't customize my panel's NamedBorder.</p> <p>If I specify a NamedBorder, my PanelBorder painter is ignored, and just the name is printed. If I take away my NamedBorder, I <i>can</i> use my custom border graphic, but then I have to poke and prod my layout to get a JLabel in the same place that the title was previously, which is undesirable.</p> <p>Further research has uncovered that the reason there is no rendered line is that TitledBorder's constructor takes an argument of another Border, which it renders in addition to the title. I was not passing this argument, and the default depends on your selected L&amp;F. Back when I was using the System L&amp;F, the default was a LineBorder. Apparently Synth's default is an EmptyBorder. Explicitly specifying the LineBorder gets me the line back, which solves most of my problem.</p> <p>The rest of my problem involves using a custom graphic for the LineBorder. For now I'm getting by rendering my custom graphic as a second PanelBackground image -- it gets composited on top of the actual background and achieves the desired visual effect, though it's not the ideal implementation.</p>
[ { "answer_id": 279305, "author": "SpooneyDinosaur", "author_id": 22386, "author_profile": "https://Stackoverflow.com/users/22386", "pm_score": 1, "selected": false, "text": "<bind style=\"PanelStyle\" type=\"name\" key=\"mySpecialPanel\" />\n panel.setName(\"mySpecialPanel\");\n public class MySpecialPanel extends JPanel \n{ \n public MySpecialPanel(String title) \n {\n super(title);\n this.setName(\"mySpecialPanel\"); \n } \n}\n" }, { "answer_id": 1118556, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "BorderFactory.createTitledBorder(\"title\");\n Border objBorder = BorderFactory.createLineBorder(Color.black); \n//Also you can create all the rest of the borders here.\nBorderFactory.createTitledBorder(objBorder, \"title\");\n" }, { "answer_id": 1345420, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public Border getBorder() { \n Border b = border;\nif (b == null)\n b = UIManager.getBorder(\"TitledBorder.border\");\n return b; \n}\n <object id=\"TitledBorder_Color\" class=\"java.awt.Color\">\n <int>140</int>\n\n <int>125</int>\n\n <int>100</int>\n\n <int>255</int>\n </object>\n\n <object id=\"LineBorder\" class=\"javax.swing.border.LineBorder\">\n <object idref=\"TitledBorder_Color\"/>\n </object>\n\n <defaultsProperty key=\"TitledBorder.border\" type=\"idref\" value=\"LineBorder\"/>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7161/" ]
233,501
<p>For the purposes of this question, the code base is an ASP.NET website that has multiple pages written in both C# and Visual Basic .NET. The primary language is C# and the Visual Basic .NET webpages where forked into the project as the same functionality is needed. </p> <p>Should the time be taken to actually rewrite these pages, including going through the testing and debugging cycle again, or would the be considered acceptable as is?</p>
[ { "answer_id": 239817, "author": "Scriptmonkey", "author_id": 31767, "author_profile": "https://Stackoverflow.com/users/31767", "pm_score": 1, "selected": false, "text": "<configuration>\n<system.web>\n <compilation>\n <codeSubDirectories>\n <add directoryName=\"VB_Code\"/>\n <add directoryName=\"CS_Code\"/>\n </codeSubDirectories>\n </compilation>\n</system.web>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
233,504
<p>I am trying to programatically set the dpi metadata of an jpeg image in Java. The source of the image is a scanner, so I get the horizontal/vertical resolution from TWAIN, along with the image raw data. I'd like to save this info for better print results.</p> <p>Here's the code I have so far. It saves the raw image (byteArray) to a JPEG file, but it ignores the X/Ydensity information I specify via IIOMetadata. Any advice what I'm doing wrong? </p> <p>Any other solution (third-party library, etc) would be welcome too. </p> <pre><code>import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadata; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream import org.w3c.dom.Element; import com.sun.imageio.plugins.jpeg.JPEGImageWriter; public boolean saveJpeg(int[] byteArray, int width, int height, int dpi, String file) { BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster wr = bufferedImage.getRaster(); wr.setPixels(0, 0, width, height, byteArray); try { // Image writer JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file)); imageWriter.setOutput(ios); // Compression JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam(); jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); jpegParams.setCompressionQuality(0.85f); // Metadata (dpi) IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams); Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0"); Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0); jfif.setAttribute("Xdensity", Integer.toString(dpi)); jfif.setAttribute("Ydensity", Integer.toString(dpi)); jfif.setAttribute("resUnits", "1"); // density is dots per inch // Write and clean up imageWriter.write(data, new IIOImage(bufferedImage, null, null), jpegParams); ios.close(); imageWriter.dispose(); } catch (Exception e) { return false; } return true; } </code></pre> <p>Thanks!</p>
[ { "answer_id": 1276894, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "data.setFromTree(\"javax_imageio_jpeg_image_1.0\", tree);\n JPEGImageWriter#write(IIOMetaData, IIOImage, ImageWriteParam) IOMetadata IOImage imageWriter.write(null, new IIOImage(F_scaledImg, null, data), jpegParams);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31155/" ]
233,507
<p>Is it possible to log out user from a web site if he is using basic authentication?</p> <p>Killing session is not enough, since, once user is authenticated, each request contains login info, so user is automatically logged in next time he/she access the site using the same credentials.</p> <p>The only solution so far is to close browser, but that's not acceptable from the usability standpoint.</p>
[ { "answer_id": 14329930, "author": "ddotsenko", "author_id": 366864, "author_profile": "https://Stackoverflow.com/users/366864", "pm_score": 6, "selected": false, "text": "document.execCommand(\"ClearAuthenticationCache\")\n logout var p = window.location.protocol + '//'\n// current location must return 200 OK for this GET\nwindow.location = window.location.href.replace(p, p + 'logout:password@')\n logout (function(safeLocation){\n var outcome, u, m = \"You should be logged out now.\";\n // IE has a simple solution for it - API:\n try { outcome = document.execCommand(\"ClearAuthenticationCache\") }catch(e){}\n // Other browsers need a larger solution - AJAX call with special user name - 'logout'.\n if (!outcome) {\n // Let's create an xmlhttp object\n outcome = (function(x){\n if (x) {\n // the reason we use \"random\" value for password is \n // that browsers cache requests. changing\n // password effectively behaves like cache-busing.\n x.open(\"HEAD\", safeLocation || location.href, true, \"logout\", (new Date()).getTime().toString())\n x.send(\"\")\n // x.abort()\n return 1 // this is **speculative** \"We are done.\" \n } else {\n return\n }\n })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject(\"Microsoft.XMLHTTP\") : u ))\n }\n if (!outcome) {\n m = \"Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.\"\n }\n alert(m)\n // return !!outcome\n})(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)\n javascript:(function (c) {\n var a, b = \"You should be logged out now.\";\n try {\n a = document.execCommand(\"ClearAuthenticationCache\")\n } catch (d) {\n }\n a || ((a = window.XMLHttpRequest ? new window.XMLHttpRequest : window.ActiveXObject ? new ActiveXObject(\"Microsoft.XMLHTTP\") : void 0) ? (a.open(\"HEAD\", c || location.href, !0, \"logout\", (new Date).getTime().toString()), a.send(\"\"), a = 1) : a = void 0);\n a || (b = \"Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.\");\n alert(b)\n})(/*pass safeLocation here if you need*/);\n" }, { "answer_id": 16645815, "author": "Claudio", "author_id": 2401060, "author_profile": "https://Stackoverflow.com/users/2401060", "pm_score": 3, "selected": false, "text": " function ClearAuthentication(LogOffPage) \n {\n var IsInternetExplorer = false; \n\n try\n {\n var agt=navigator.userAgent.toLowerCase();\n if (agt.indexOf(\"msie\") != -1) { IsInternetExplorer = true; }\n }\n catch(e)\n {\n IsInternetExplorer = false; \n };\n\n if (IsInternetExplorer) \n {\n // Logoff Internet Explorer\n document.execCommand(\"ClearAuthenticationCache\");\n window.location = LogOffPage;\n }\n else \n {\n // Logoff every other browsers\n $.ajax({\n username: 'unknown',\n password: 'WrongPassword',\n url: './cgi-bin/PrimoCgi',\n type: 'GET',\n beforeSend: function(xhr)\n {\n xhr.setRequestHeader(\"Authorization\", \"Basic AAAAAAAAAAAAAAAAAAA=\");\n },\n\n error: function(err)\n {\n window.location = LogOffPage;\n }\n });\n }\n }\n\n\n $(document).ready(function () \n {\n $('#Btn1').click(function () \n {\n // Call Clear Authentication \n ClearAuthentication(\"force_logout.html\"); \n });\n }); \n" }, { "answer_id": 24141133, "author": "Romuald Brunet", "author_id": 286182, "author_profile": "https://Stackoverflow.com/users/286182", "pm_score": 4, "selected": false, "text": "function logout(to_url) {\n var out = window.location.href.replace(/:\\/\\//, '://log:out@');\n\n jQuery.get(out).error(function() {\n window.location = to_url;\n });\n}\n" }, { "answer_id": 28369312, "author": "Charlie", "author_id": 4232437, "author_profile": "https://Stackoverflow.com/users/4232437", "pm_score": 2, "selected": false, "text": "function logout() {\n var userAgent = navigator.userAgent.toLowerCase();\n\n if (userAgent.indexOf(\"msie\") != -1) {\n document.execCommand(\"ClearAuthenticationCache\", false);\n }\n\n xhr_objectCarte = null;\n\n if(window.XMLHttpRequest)\n xhr_object = new XMLHttpRequest();\n else if(window.ActiveXObject)\n xhr_object = new ActiveXObject(\"Microsoft.XMLHTTP\");\n else\n alert (\"Your browser doesn't support XMLHTTPREQUEST\");\n\n xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');\n xhr_object.send (\"\");\n xhr_object = null;\n\n document.location = 'http://yourserver.com'; \n return false;\n}\n" }, { "answer_id": 29037751, "author": "Sushovan Mukherjee", "author_id": 940788, "author_profile": "https://Stackoverflow.com/users/940788", "pm_score": 2, "selected": false, "text": " function logout(url){\n var str = url.replace(\"http://\", \"http://\" + new Date().getTime() + \"@\");\n var xmlhttp;\n if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();\n else xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n xmlhttp.onreadystatechange=function()\n {\n if (xmlhttp.readyState==4) location.reload();\n }\n xmlhttp.open(\"GET\",str,true);\n xmlhttp.setRequestHeader(\"Authorization\",\"Basic xxxxxxxxxx\")\n xmlhttp.send();\n return false;\n}\n" }, { "answer_id": 31530888, "author": "Amit Shah", "author_id": 5137561, "author_profile": "https://Stackoverflow.com/users/5137561", "pm_score": 1, "selected": false, "text": "//Detect Browser\nvar isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;\n // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)\nvar isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+\nvar isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;\n // At least Safari 3+: \"[object HTMLElementConstructor]\"\nvar isChrome = !!window.chrome && !isOpera; // Chrome 1+\nvar isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6\nvar Host = window.location.host;\n\n\n//Clear Basic Realm Authentication\nif(isIE){\n//IE\n document.execCommand(\"ClearAuthenticationCache\");\n window.location = '/';\n}\nelse if(isSafari)\n{//Safari. but this works mostly on all browser except chrome\n (function(safeLocation){\n var outcome, u, m = \"You should be logged out now.\";\n // IE has a simple solution for it - API:\n try { outcome = document.execCommand(\"ClearAuthenticationCache\") }catch(e){}\n // Other browsers need a larger solution - AJAX call with special user name - 'logout'.\n if (!outcome) {\n // Let's create an xmlhttp object\n outcome = (function(x){\n if (x) {\n // the reason we use \"random\" value for password is \n // that browsers cache requests. changing\n // password effectively behaves like cache-busing.\n x.open(\"HEAD\", safeLocation || location.href, true, \"logout\", (new Date()).getTime().toString())\n x.send(\"\");\n // x.abort()\n return 1 // this is **speculative** \"We are done.\" \n } else {\n return\n }\n })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject(\"Microsoft.XMLHTTP\") : u )) \n }\n if (!outcome) {\n m = \"Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.\"\n }\n alert(m);\n window.location = '/';\n // return !!outcome\n })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)\n}\nelse{\n//Firefox,Chrome\n window.location = 'http://log:out@'+Host+'/';\n}\n" }, { "answer_id": 32325848, "author": "mthoring", "author_id": 5287340, "author_profile": "https://Stackoverflow.com/users/5287340", "pm_score": 5, "selected": false, "text": "function logout(secUrl, redirUrl) {\n if (bowser.msie) {\n document.execCommand('ClearAuthenticationCache', 'false');\n } else if (bowser.gecko) {\n $.ajax({\n async: false,\n url: secUrl,\n type: 'GET',\n username: 'logout'\n });\n } else if (bowser.webkit) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", secUrl, true);\n xmlhttp.setRequestHeader(\"Authorization\", \"Basic logout\");\n xmlhttp.send();\n } else {\n alert(\"Logging out automatically is unsupported for \" + bowser.name\n + \"\\nYou must close the browser to log out.\");\n }\n setTimeout(function () {\n window.location.href = redirUrl;\n }, 200);\n}" }, { "answer_id": 32653300, "author": "Amir Mofakhar", "author_id": 4676838, "author_profile": "https://Stackoverflow.com/users/4676838", "pm_score": 2, "selected": false, "text": "@app.route('/logout')\ndef logout():\n return ('Logout', 401, {'WWW-Authenticate': 'Basic realm=\"Login required\"'})\n" }, { "answer_id": 34240806, "author": "Envek", "author_id": 338859, "author_profile": "https://Stackoverflow.com/users/338859", "pm_score": 3, "selected": false, "text": "401 Unauthorized location /logout {\n return 401;\n}\n\nerror_page 401 /errors/401.html;\n\nlocation /errors {\n auth_basic off;\n ssi on;\n ssi_types text/html;\n alias /home/user/errors;\n}\n /home/user/errors/401.html <!DOCTYPE html>\n<p>You're not authorised. <a href=\"<!--# echo var=\"scheme\" -->://<!--# echo var=\"host\" -->/\">Login</a>.</p>\n" }, { "answer_id": 41545921, "author": "Hasan Junaid Hashmi", "author_id": 2018169, "author_profile": "https://Stackoverflow.com/users/2018169", "pm_score": -1, "selected": false, "text": "\n\n function logout(secUrl, redirUrl) {\n if (bowser.msie) {\n document.execCommand('ClearAuthenticationCache', 'false');\n } else if (bowser.gecko) {\n $.ajax({\n async: false,\n url: secUrl,\n type: 'GET',\n username: 'logout'\n });\n } else if (bowser.webkit) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", secUrl, true);\n xmlhttp.setRequestHeader(\"Authorization\", \"Basic logout\");\n xmlhttp.send();\n } else {\n alert(\"Logging out automatically is unsupported for \" + bowser.name\n + \"\\nYou must close the browser to log out.\");\n }\n setTimeout(function () {\n window.location.href = redirUrl;\n }, 200);\n }\n\n\n\n function logout(secUrl, redirUrl) {\n if (bowser.msie) {\n document.execCommand('ClearAuthenticationCache', 'false');\n } else if (bowser.gecko) {\n $.ajax({\n async: false,\n url: secUrl,\n type: 'GET',\n username: 'logout'\n });\n } else if (bowser.webkit) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", secUrl, true);\n xmlhttp.setRequestHeader(\"Authorization\", \"Basic logout\");\n xmlhttp.send();\n } else {\n alert(\"Logging out automatically is unsupported for \" + bowser.name\n + \"\\nYou must close the browser to log out.\");\n }\n setTimeout(function () {\n window.location.href = redirUrl;\n }, 200);\n } ?php\n ob_start();\n session_start();\n require_once 'dbconnect.php';\n\n // if session is not set this will redirect to login page\n if( !isset($_SESSION['user']) ) {\n header(\"Location: index.php\");\n exit;\n }\n // select loggedin users detail\n $res=mysql_query(\"SELECT * FROM users WHERE userId=\".$_SESSION['user']);\n $userRow=mysql_fetch_array($res);\n?>\n<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>Welcome - <?php echo $userRow['userEmail']; ?></title>\n<link rel=\"stylesheet\" href=\"assets/css/bootstrap.min.css\" type=\"text/css\" />\n<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" />\n\n <script src=\"assets/js/bowser.min.js\"></script>\n<script>\n//function logout(secUrl, redirUrl)\n//bowser = require('bowser');\nfunction logout(secUrl, redirUrl) {\nalert(redirUrl);\n if (bowser.msie) {\n document.execCommand('ClearAuthenticationCache', 'false');\n } else if (bowser.gecko) {\n $.ajax({\n async: false,\n url: secUrl,\n type: 'GET',\n username: 'logout'\n });\n } else if (bowser.webkit) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", secUrl, true);\n xmlhttp.setRequestHeader(\"Authorization\", \"Basic logout\");\n xmlhttp.send();\n } else {\n alert(\"Logging out automatically is unsupported for \" + bowser.name\n + \"\\nYou must close the browser to log out.\");\n }\n window.location.assign(redirUrl);\n /*setTimeout(function () {\n window.location.href = redirUrl;\n }, 200);*/\n}\n\n\nfunction f1()\n {\n alert(\"f1 called\");\n //form validation that recalls the page showing with supplied inputs. \n }\n</script>\n</head>\n<body>\n\n <nav class=\"navbar navbar-default navbar-fixed-top\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"http://www.codingcage.com\">Coding Cage</a>\n </div>\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n <li class=\"active\"><a href=\"http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html\">Back to Article</a></li>\n <li><a href=\"http://www.codingcage.com/search/label/jQuery\">jQuery</a></li>\n <li><a href=\"http://www.codingcage.com/search/label/PHP\">PHP</a></li>\n </ul>\n <ul class=\"nav navbar-nav navbar-right\">\n\n <li class=\"dropdown\">\n <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\">\n <span class=\"glyphicon glyphicon-user\"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class=\"caret\"></span></a>\n <ul class=\"dropdown-menu\">\n <li><a href=\"logout.php?logout\"><span class=\"glyphicon glyphicon-log-out\"></span>&nbsp;Sign Out</a></li>\n </ul>\n </li>\n </ul>\n </div><!--/.nav-collapse -->\n </div>\n </nav> \n\n <div id=\"wrapper\">\n\n <div class=\"container\">\n\n <div class=\"page-header\">\n <h3>Coding Cage - Programming Blog</h3>\n </div>\n\n <div class=\"row\">\n <div class=\"col-lg-12\" id=\"div_logout\">\n <h1 onclick=\"logout(window.location.href, 'www.espncricinfo.com')\">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>\n </div>\n </div>\n\n </div>\n\n </div>\n\n <script src=\"assets/jquery-1.11.3-jquery.min.js\"></script>\n <script src=\"assets/js/bootstrap.min.js\"></script>\n\n\n</body>\n</html>\n<?php ob_end_flush(); ?>\n" }, { "answer_id": 42559822, "author": "Foad", "author_id": 4282984, "author_profile": "https://Stackoverflow.com/users/4282984", "pm_score": 2, "selected": false, "text": "$.ajax({\n async: false,\n url: 'http://your_login_backend',\n type: 'GET',\n username: 'logout'\n}); \n\nsetTimeout(function () {\n window.location.href = 'http://normal_index';\n}, 200);\n" }, { "answer_id": 43990171, "author": "Max", "author_id": 233871, "author_profile": "https://Stackoverflow.com/users/233871", "pm_score": 0, "selected": false, "text": "function logout(secUrl, redirUrl) {\n if (bowser.msie) {\n document.execCommand('ClearAuthenticationCache', 'false');\n } else if (bowser.gecko) {\n $.ajax({\n async: false,\n url: secUrl,\n type: 'GET',\n username: 'logout'\n });\n } else if (bowser.webkit || bowser.chrome) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\\\"GET\\\", secUrl, true);\n xmlhttp.setRequestHeader(\\\"Authorization\\\", \\\"Basic logout\\\");\\\n xmlhttp.send();\n } else {\n// http://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome\n redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');\n }\n setTimeout(function () {\n window.location.href = redirUrl;\n }, 200);\n}\n" }, { "answer_id": 55705027, "author": "Ali", "author_id": 846634, "author_profile": "https://Stackoverflow.com/users/846634", "pm_score": 1, "selected": false, "text": "chrome://restart" }, { "answer_id": 57943574, "author": "Nahuel Greco", "author_id": 392145, "author_profile": "https://Stackoverflow.com/users/392145", "pm_score": 3, "selected": false, "text": "Clear-Site-Data Clear-Site-Data: \"cookies\" Clear-Site-Data header on 'https://localhost:9443/clear': Cleared data types:\n\"cookies\". Clearing channel IDs and HTTP authentication cache is currently not\nsupported, as it breaks active network connections.\n" }, { "answer_id": 59418892, "author": "Teo Bebekis", "author_id": 1779320, "author_profile": "https://Stackoverflow.com/users/1779320", "pm_score": 2, "selected": false, "text": " <div>You have been logged out. Redirecting to home...</div> \n\n<script>\n var XHR = new XMLHttpRequest();\n XHR.open(\"GET\", \"/Home/MyProtectedPage\", true, \"no user\", \"no password\");\n XHR.send();\n\n setTimeout(function () {\n window.location.href = \"/\";\n }, 3000);\n</script>\n" }, { "answer_id": 60450491, "author": "Fogus", "author_id": 4022215, "author_profile": "https://Stackoverflow.com/users/4022215", "pm_score": 2, "selected": false, "text": "https://invalid_login@hostname https://invalid_login@hostname //It should return 401, necessary for Safari only\n const logoutUrl = 'https://example.com/logout'; \n const xmlHttp = new XMLHttpRequest();\n xmlHttp.open('POST', logoutUrl, true, 'logout');\n xmlHttp.send();\n" }, { "answer_id": 66648187, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 0, "selected": false, "text": "package main\n\nimport (\n \"crypto/subtle\"\n \"fmt\"\n \"log\"\n \"net/http\"\n)\n\nfunc BasicAuth(username, password, realm string, handlerFunc http.HandlerFunc) http.HandlerFunc {\n\n return func(w http.ResponseWriter, r *http.Request) {\n queryMap := r.URL.Query()\n if _, ok := queryMap[\"logout\"]; ok { // localhost:8080/public/?logout\n w.WriteHeader(http.StatusUnauthorized) // 401\n _, _ = w.Write([]byte(\"Success logout!\\n\"))\n return\n }\n\n user, pass, ok := r.BasicAuth()\n\n if !ok ||\n subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 ||\n subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate\n w.Header().Set(\"WWW-Authenticate\", `Basic realm=\"`+realm+`\", charset=\"UTF-8\"`)\n w.WriteHeader(http.StatusUnauthorized)\n _, _ = w.Write([]byte(\"Unauthorised.\\n\"))\n return\n }\n\n handlerFunc(w, r)\n }\n}\n\ntype UserInfo struct {\n name string\n psw string\n}\n\nfunc main() {\n\n portNumber := \"8080\"\n guest := UserInfo{\"guest\", \"123\"}\n\n // localhost:8080/public/ -> ./public/everyone\n publicHandler := http.StripPrefix(\n \"/public/\", http.FileServer(http.Dir(\"./public/everyone\")),\n )\n\n publicHandlerFunc := func(w http.ResponseWriter, r *http.Request) {\n switch r.Method {\n case http.MethodGet:\n publicHandler.ServeHTTP(w, r)\n /*\n case http.MethodPost:\n case http.MethodPut:\n case http.MethodDelete:\n */\n default:\n return\n }\n }\n\n http.HandleFunc(\"/public/\",\n BasicAuth(guest.name, guest.psw, \"Please enter your username and password for this site\",\n publicHandlerFunc),\n )\n\n log.Fatal(http.ListenAndServe(fmt.Sprintf(\":%s\", portNumber), nil))\n}\n" }, { "answer_id": 72128174, "author": "A. Morel", "author_id": 2736742, "author_profile": "https://Stackoverflow.com/users/2736742", "pm_score": 0, "selected": false, "text": "protected login(changeUser: boolean = false): Observable<AuthInfo> {\n let params = new HttpParams();\n if(changeUser) {\n let dateNow = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');\n params = params.set('changeUser', dateNow!);\n }\n const url: string = `${environment.yourAppsApiUrl}/Auth/login`;\n return this.http.get<AuthInfo>(url, { params: params });\n}\n [Route(\"api/[controller]\")]\n[ApiController]\n[Produces(\"application/json\")]\n[Authorize(AuthenticationSchemes = NegotiateDefaults.AuthenticationScheme)]\npublic class AuthController : Controller\n{\n [HttpGet(\"login\")]\n public async Task<IActionResult> Login(DateTime? changeUser = null)\n {\n if (changeUser > DateTime.Now.AddSeconds(-3))\n return Unauthorized();\n\n ...\n ... (login process)\n ...\n\n return Ok(await _authService.GetToken());\n }\n}\n return Unauthorized()" }, { "answer_id": 73612483, "author": "JPalo", "author_id": 3917638, "author_profile": "https://Stackoverflow.com/users/3917638", "pm_score": 0, "selected": false, "text": "RewriteEngine On\nAuthType Basic\nAuthName \"Login\"\nAuthUserFile /mypath/.htpasswd\nrequire user logout\n <form action=\"https://logout:logout@example.com/logout/\" method=\"post\">\n <button type=\"submit\">Logout</button>\n</form>\n <?php\necho \"LOGOUT SUCCESS\";\nheader( \"refresh:2; url=https://example.com\" );\n?>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31141/" ]
233,553
<p>I have a very simple jQuery Datepicker calendar:</p> <pre><code>$(document).ready(function(){ $("#date_pretty").datepicker({ }); }); </code></pre> <p>and of course in the HTML...</p> <pre><code>&lt;input type="text" size="10" value="" id="date_pretty"/&gt; </code></pre> <p>Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.</p>
[ { "answer_id": 233654, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 6, "selected": false, "text": "var myDate = new Date();\nvar prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +\n myDate.getFullYear();\n$(\"#date_pretty\").val(prettyDate);\n" }, { "answer_id": 233752, "author": "Marcus", "author_id": 26848, "author_profile": "https://Stackoverflow.com/users/26848", "pm_score": 3, "selected": false, "text": "$(document).ready(function(){\n $(\"#date_pretty\").datepicker({ \n });\n var myDate = new Date();\n var month = myDate.getMonth() + 1;\n var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();\n $(\"#date_pretty\").val(prettyDate);\n});\n" }, { "answer_id": 397907, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "$(function()\n{\n$('.date-pick').datePicker().val(new Date().asString()).trigger('change');\n});\n" }, { "answer_id": 2325607, "author": "CiscoIPPhone", "author_id": 70365, "author_profile": "https://Stackoverflow.com/users/70365", "pm_score": 10, "selected": true, "text": "$(\".date-pick\").datepicker('setDate', new Date());\n $(\".date-pick\").datepicker().datepicker('setDate', new Date());\n" }, { "answer_id": 3515662, "author": "Jeff Girard", "author_id": 424420, "author_profile": "https://Stackoverflow.com/users/424420", "pm_score": 3, "selected": false, "text": "$('#date-selector').datepicker('setDate', new Date());\n" }, { "answer_id": 4714808, "author": "gmail user", "author_id": 344394, "author_profile": "https://Stackoverflow.com/users/344394", "pm_score": 0, "selected": false, "text": "var prettyDate = $.datepicker.formatDate('dd-M-yy', new Date());\nalert(prettyDate);\n" }, { "answer_id": 5014025, "author": "quocnguyen", "author_id": 619263, "author_profile": "https://Stackoverflow.com/users/619263", "pm_score": 2, "selected": false, "text": "$('input[name*=\"date\"]').datepicker({\n dateFormat: 'dd-mm-yy',\n changeMonth: true,\n changeYear: true,\n beforeShow: function(input, instance) { \n $(input).datepicker('setDate', new Date());\n }\n });\n" }, { "answer_id": 8945264, "author": "Ravi Ram", "author_id": 665387, "author_profile": "https://Stackoverflow.com/users/665387", "pm_score": 8, "selected": false, "text": "$(\".date-pick\").datepicker();\n$(\".date-pick\").datepicker(\"setDate\", new Date());\n $('.date-pick').datepicker({ /* optional option parameters... */ })\n .datepicker(\"setDate\", new Date());\n $(\".date-pick\").datepicker(\"setDate\", new Date());\n" }, { "answer_id": 11172015, "author": "KirilleXXI", "author_id": 1247342, "author_profile": "https://Stackoverflow.com/users/1247342", "pm_score": 5, "selected": false, "text": "$('#date_pretty').datepicker('setDate', '+0');\n $('#date_pretty').datepicker('setDate', '-1');\n" }, { "answer_id": 11423185, "author": "maozx", "author_id": 1516208, "author_profile": "https://Stackoverflow.com/users/1516208", "pm_score": 2, "selected": false, "text": " $(function() { \n // initialize the datapicker\n $(\"#date\").datepicker();\n\n // set the time\n var currentDate = new Date();\n $(\"#date\").datepicker(\"setDate\",currentDate);\n\n // set the options for the button \n $(\"#date\").datepicker(\"option\",{\n dateFormat: 'dd/mm',\n showOn: \"button\",\n // whatever option Or event you want \n });\n });\n" }, { "answer_id": 11819375, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 6, "selected": false, "text": "setDate() $(\"#datepicker1\").datepicker({\n dateFormat: \"yy-mm-dd\"\n}).datepicker(\"setDate\", \"0\");\n setDate() defaultDate" }, { "answer_id": 13040921, "author": "Gary Medina", "author_id": 1769834, "author_profile": "https://Stackoverflow.com/users/1769834", "pm_score": 3, "selected": false, "text": "$(\".date-pick\").datepicker(); \n$(\".date-pick\").datepicker(\"setDate\", new Date()); \n $(\".date-pick\").datepicker().datepicker(\"setDate\", new Date()); \n" }, { "answer_id": 15870913, "author": "Celestz", "author_id": 2181385, "author_profile": "https://Stackoverflow.com/users/2181385", "pm_score": 3, "selected": false, "text": "$('#inputName')\n .datepicker()\n .datepicker('setDate', new Date());\n" }, { "answer_id": 20998323, "author": "Les Mizzell", "author_id": 3173655, "author_profile": "https://Stackoverflow.com/users/3173655", "pm_score": 1, "selected": false, "text": " $( \"#datepicker\" ).datepicker();\n <?php if (!empty($oneEVENT['start_ts'])): ?>\n $( \"#datepicker\" ).datepicker( \"setDate\", \"<?php echo $startDATE; ?>\" );\n <? else: ?>\n $(\"#datepicker\").datepicker('setDate', new Date()); \n <?php endif; ?>\n });\n" }, { "answer_id": 28745931, "author": "thejustv", "author_id": 2466310, "author_profile": "https://Stackoverflow.com/users/2466310", "pm_score": 0, "selected": false, "text": "$(this).datepicker(\"destroy\").datepicker({\n changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: \"dd-mm-yy\", showOn: \"focus\", yearRange: \"-5:+10\"\n }).focus();\n" }, { "answer_id": 31229651, "author": "Nadir", "author_id": 3282722, "author_profile": "https://Stackoverflow.com/users/3282722", "pm_score": 1, "selected": false, "text": "$(\"#date_pretty\").datepicker().datepicker(\"setDate\", new Date());\n" }, { "answer_id": 32376073, "author": "chispitaos", "author_id": 2271755, "author_profile": "https://Stackoverflow.com/users/2271755", "pm_score": 2, "selected": false, "text": "$('input.datepicker').datepicker(\n { \n changeMonth: false,\n changeYear: false,\n beforeShow: function(input, instance) { \n $(input).datepicker('setDate', new Date());\n }\n } \n );\n div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,\n div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active {\n background: #1ABC9C;\n border-radius: 50%;\n color: #fff;\n cursor: pointer;\n display: inline-block;\n width: 24px; height: 24px;\n }​\n" }, { "answer_id": 36155885, "author": "Alpha2k", "author_id": 3257288, "author_profile": "https://Stackoverflow.com/users/3257288", "pm_score": 0, "selected": false, "text": ".datepicker('setDate', new Date()); $(\"#myDateText\").val(moment(new Date()).format('DD/MM/YYYY'));\n" }, { "answer_id": 58394022, "author": "nikhil", "author_id": 8208024, "author_profile": "https://Stackoverflow.com/users/8208024", "pm_score": 0, "selected": false, "text": "$(\".datepicker\").datepicker({ dateFormat: 'dd-M-yy' }).datepicker('setDate', new Date());" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26848/" ]
233,560
<p>I have developed about 300 Applications which I would like to provide with multi-language capabilities independent from the Operating System. I have written a just-in-time translator, but that is too slow in applications with many components. What would you suggest I do?</p>
[ { "answer_id": 233626, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 3, "selected": true, "text": "ShowMessage('Hello'); // before\nShowMessage(_('Hello')); // after\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
233,564
<p>I have created a multi column datastore on a table that allows me to do full text indexing on the table. What I need to be able to do is weight each column different and add the scores together.</p> <p>The following query works, but is slow:</p> <pre><code>SELECT document.*, Score(1) + 2*Score(2) as Score FROM document WHERE (CONTAINS(documentContent, 'the_keyword', 1) &gt; 0 OR CONTAINS(documentTitle, 'the_keyword', 2) &gt; 0 ) ORDER BY Score DESC </code></pre> <p>After quite a bit of Googling, people have proposed the solution as:</p> <pre><code>SELECT document.*, Score(1) as Score FROM document WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))*2 OR ((the_keyword) within documentText)',1) &gt; 0) ORDER BY Score Desc </code></pre> <p>The above query is faster than its predecessor but it does not solve the actual problem. In this case, if the keyword is found in the documentTitle, it will not search the documentText (it uses the OR operator). What I really need is to ADD the two scores together so that if a keyword appears in the title AND the text it will have a higher score than if it only appears in the title. </p> <p>So, how do you add the scores for weighted columns in one CONTAINS clause? </p>
[ { "answer_id": 233761, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 0, "selected": false, "text": "select *, Score(1) + 2 * Score(2) as Score\nfrom (\n SELECT document.*, Score(1) as Score\n FROM document\n WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))\n OR ((the_keyword) within documentText)',1) > 0)\n)\nORDER BY Score Desc\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31169/" ]
233,579
<p>I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer. </p> <p>What would this syntax look like?</p> <p>I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?</p> <p>(By now we definitely know that closures not will be included in the next Java release)</p> <p>OR </p> <p><strong>edit: <a href="http://puredanger.com/tech/2009/11/18/closures-after-all/" rel="noreferrer">http://puredanger.com/tech/2009/11/18/closures-after-all/</a> :D</strong></p> <p><strong>edit2: Re-thinking JDK7: <a href="http://blogs.oracle.com/mr/entry/rethinking_jdk7" rel="noreferrer">http://blogs.oracle.com/mr/entry/rethinking_jdk7</a></strong></p> <p><strong>edit3: There’s not a moment to lose!: <a href="http://blogs.oracle.com/mr/entry/quartet" rel="noreferrer">http://blogs.oracle.com/mr/entry/quartet</a></strong></p>
[ { "answer_id": 233595, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 5, "selected": true, "text": "boolean even = { int x => x % 2 == 0 }.invoke(15);\n { int x => x % 2 == 0 }" }, { "answer_id": 234004, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "{int => boolean} evaluateInt; //declare variable of \"function\" type\nevaluateInt = {int x => x % 2 }; //assignment\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
233,593
<p>Does Eclipse have a feature that lets you search a project to find all calls to deprecated methods?</p>
[ { "answer_id": 237109, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 2, "selected": false, "text": "@deprecated" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
233,596
<p>In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect? Is there a best practice out there for doing so?</p>
[ { "answer_id": 233613, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 4, "selected": false, "text": "using" }, { "answer_id": 12527208, "author": "Morten", "author_id": 1688284, "author_profile": "https://Stackoverflow.com/users/1688284", "pm_score": 3, "selected": false, "text": "GC.Collect() Dispose() GC.Collect()" }, { "answer_id": 22460652, "author": "Vaibhav", "author_id": 1578274, "author_profile": "https://Stackoverflow.com/users/1578274", "pm_score": 3, "selected": false, "text": "class Program\n{ \n static void Main(string[] args)\n {\n SomePublisher publisher = new SomePublisher();\n\n for (int i = 0; i < 10; i++)\n {\n SomeSubscriber subscriber = new SomeSubscriber(publisher);\n subscriber = null;\n }\n\n GC.Collect();\n GC.WaitForPendingFinalizers();\n\n Console.WriteLine(SomeSubscriber.Count.ToString());\n\n\n Console.ReadLine();\n }\n }\n\n public class SomePublisher\n {\n public event EventHandler SomeEvent;\n }\n\n public class SomeSubscriber\n {\n public static int Count;\n\n public SomeSubscriber(SomePublisher publisher)\n {\n publisher.SomeEvent += new EventHandler(publisher_SomeEvent);\n }\n\n ~SomeSubscriber()\n {\n SomeSubscriber.Count++;\n }\n\n private void publisher_SomeEvent(object sender, EventArgs e)\n {\n // TODO: something\n string stub = \"\";\n }\n }\n" }, { "answer_id": 68854455, "author": "pianocomposer", "author_id": 1000008, "author_profile": "https://Stackoverflow.com/users/1000008", "pm_score": -1, "selected": false, "text": " Using con As SqlConnection = New SqlConnection(DB_CONNECTION_STRING)\n con.Open()\n\n Using command As SqlCommand = New SqlCommand(sqlStr, con)\n Using reader As SqlDataReader = command.ExecuteReader()\n\n While reader.Read()\n code_here()\n End While\n End Using\n End Using\n End Using\n Dim f1 As frmShippingLabel\n f1 = New frmShippingLabel\n f1.PrintLabel()\n f1.Dispose()\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
233,621
<p>All the PHP files in my workspace are encoded in <strong>Unicode (UTF-8, no BOM)</strong>. I often duplicate an existing source file to use as a base for a new script. Invariably (with Path Finder or the original Finder), OS X will convert the encoding of the duplicate file to <strong>Western (Mac OS Roman)</strong>.</p> <p>Is there any way to make OS X behave and not convert the text encoding when duplicating a text file? Or make it use a specific text encoding (other than Western!) by default for all files with .php extension?</p>
[ { "answer_id": 237053, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 2, "selected": false, "text": "-[NSString writeToFile:...]" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024/" ]
233,622
<p>It sounds a lot more complicated than it really is.</p> <p>So in Perl, you can do something like this:</p> <pre><code>foreach my $var (@vars) { $hash_table{$var-&gt;{'id'}} = $var-&gt;{'data'}; } </code></pre> <p>I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.</p> <p>I've tried the following:</p> <pre><code>hash_table = new Array(); $.each(data.results), function(name, result) { hash_table[result.(name).extra_info.a] = result.(name).some_dataset; }); </code></pre> <p>Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):</p> <pre><code>{ results:{ datasets_a:{ dataset_one:{ data:{ //stuff } extra_info:{ //stuff } } dataset_two:{ ... } ... } datasets_b:{ ... } } } </code></pre> <p>But every time I do this, firebug throws the following error:</p> <p>"XML filter is applied to non-xml data"</p>
[ { "answer_id": 233689, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": " d = {\n 'results':{\n 'datasets_a':{\n 'dataset_one':{\n 'data':{\n 'sample':'hello'\n },\n 'extra_info':{\n //stuff\n }\n },\n 'dataset_two':{\n ///\n }\n ///\n },\n 'datasets_b':{\n ///\n }\n }\n}\nalert(d.results.datasets_a.dataset_one.data.sample)\n d = {\n 'results':{\n 'datasets_a':{\n 'dataset_one':{\n 'data':{\n 'sample':'hello'\n },\n 'extra_info':{\n //stuff\n }\n },\n 'dataset_two':{\n ///\n }\n ///\n },\n 'datasets_b':{\n ///\n }\n }\n};\n\nalert(d.results.datasets_a.dataset_one.data.sample)\n" }, { "answer_id": 233693, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 3, "selected": true, "text": "$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];\n// Or the shorter form:\n$('result').innerHTML = data.results.dataset_a.dataset_two.data;\n $.each(data.results), function(name, result) {\n hash_table[result.(name).extra_info.a] = result.(name).some_dataset;\n});\n data.results name = \"datasets_a\" item = object item name" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22390/" ]
233,632
<p>Ok</p> <p>I'm working on a little project at the moment, the Report expects an int but the ReportParameter class only lets me have a value that's a string or a string[]</p> <p>How can I pass an int?</p> <p>thanks</p> <p>dan</p>
[ { "answer_id": 233675, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 2, "selected": false, "text": "GetReportParameters() ReportParameter[] int enum ParameterTypeEnum ParameterTypeEnum.Integer int" }, { "answer_id": 233771, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 1, "selected": false, "text": "var rp = new ReportParameter(\"IntValue\", intValue.ToString());\nreport.SetParameters(new ReportParameter[]{rp});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30861/" ]
233,643
<p>I'd like to link to some PDFs in one of my controller views. What's the best practice for accomplishing this? The CakePHP webroot folder contains a ./files/ subfolder, I am confounded by trying to link to it without using "magic" pathnames in my href (e.g. "/path/to/my/webroot/files/myfile.pdf").</p> <p>What are my options?</p> <p><strong>EDIT:</strong> I didn't adequately describe my question. I was attempting to link to files in /app/webroot/files/ in a platform-agnostic (ie. no <code>mod_rewrite</code>) way.</p> <p>I've since worked around this issue by storing such files outside the CakePHP directory structure.</p>
[ { "answer_id": 239322, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 5, "selected": true, "text": "$html->link('Pdf', '/files/myfile.pdf');\n" }, { "answer_id": 280429, "author": "Chris Hawes", "author_id": 22776, "author_profile": "https://Stackoverflow.com/users/22776", "pm_score": 0, "selected": false, "text": "<a href=\"<?php echo $html->url('/files/somefile.pdf'); ?>\">Link Text</a>\n" }, { "answer_id": 373511, "author": "user42801", "author_id": 42801, "author_profile": "https://Stackoverflow.com/users/42801", "pm_score": 1, "selected": false, "text": "<a href=\"<?php echo $this->webroot; ?>files/somefile.pdf\">Link Text</a>\n" }, { "answer_id": 3513309, "author": "James Revillini", "author_id": 336397, "author_profile": "https://Stackoverflow.com/users/336397", "pm_score": 2, "selected": false, "text": "<?php echo $html->link('pdf', '/files/test.pdf'); ?>\n <a href=\"/pathtoapp/index.php/files/test.pdf\">pdf</a>\n <a href=\"/pathtoapp/app/webroot/files/test.pdf\">pdf</a>\n" }, { "answer_id": 3591865, "author": "sotomsa", "author_id": 433847, "author_profile": "https://Stackoverflow.com/users/433847", "pm_score": 2, "selected": false, "text": "<?php echo $html->link('pdf', $this->webroot('files'.DS.'test.pdf'); ?>\n" }, { "answer_id": 4089513, "author": "zmonteca", "author_id": 186782, "author_profile": "https://Stackoverflow.com/users/186782", "pm_score": 3, "selected": false, "text": "$file = WWW_ROOT . DS . 'files' . DS;\n" }, { "answer_id": 46291489, "author": "Keila", "author_id": 8630387, "author_profile": "https://Stackoverflow.com/users/8630387", "pm_score": 0, "selected": false, "text": " <a href=\"<?php echo $this->request->webroot . 'carpetadentrodelwebroot/archivo.pdf'; ?>\" target=\"pdf-frame\" download=\"nombreParaDescarga\">Descargar Archivo</a>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5030/" ]
233,673
<p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p> <pre><code>flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) </code></pre> <p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p> <p>This equivalent Perl code does it right:</p> <pre><code>my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f-&gt;(2), "\n"; } </code></pre> <p>"0 2 4" is printed.</p> <p>Can you please explain the difference ?</p> <hr> <p>Update: </p> <p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p> <pre><code>flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) </code></pre> <p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
[ { "answer_id": 233713, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "i f >>> class f:\n... def __init__(self, multiplier): self.multiplier = multiplier\n... def __call__(self, multiplicand): return self.multiplier*multiplicand\n... \n>>> flist = [f(i) for i in range(3)]\n>>> [g(2) for g in flist]\n[0, 2, 4]\n i i kkk flist" }, { "answer_id": 233800, "author": "Null303", "author_id": 13787, "author_profile": "https://Stackoverflow.com/users/13787", "pm_score": 4, "selected": false, "text": "for f in flist:\n print f.func_closure\n\n\n(<cell at 0x00C980B0: int object at 0x009864B4>,)\n(<cell at 0x00C980B0: int object at 0x009864B4>,)\n(<cell at 0x00C980B0: int object at 0x009864B4>,)\n for i in xrange(3):\n def ffunc(i):\n def func(x): return x * i\n return func\n flist.append(ffunc(i))\n" }, { "answer_id": 233822, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 2, "selected": false, "text": "i t = [ (lambda x: lambda y : x*y)(x) for x in range(5)]\n\n>>> t[1](2)\n2\n>>> t[2](2)\n4\n" }, { "answer_id": 233835, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 8, "selected": true, "text": "flist = []\n\nfor i in xrange(3):\n def funcC(j):\n def func(x): return x * j\n return func\n flist.append(funcC(i))\n\nfor f in flist:\n print f(2)\n" }, { "answer_id": 235764, "author": "piro", "author_id": 10138, "author_profile": "https://Stackoverflow.com/users/10138", "pm_score": 7, "selected": false, "text": "i i def flist = []\n\nfor i in xrange(3):\n def func(x, i=i): # the *value* of i is copied in func() environment\n return x * i\n flist.append(func)\n\nfor f in flist:\n print f(2)\n" }, { "answer_id": 236044, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 2, "selected": false, "text": "(defvar *flist* '())\n\n(dotimes (i 3 t)\n (setf *flist* \n (cons (lambda (x) (* x i)) *flist*)))\n\n(dolist (f *flist*) \n (format t \"~a~%\" (funcall f 2)))\n (define flist '())\n\n(do ((i 1 (+ 1 i)))\n ((>= i 4))\n (set! flist \n (cons (lambda (x) (* i x)) flist)))\n\n(map \n (lambda (f)\n (printf \"~a~%\" (f 2)))\n flist)\n" }, { "answer_id": 236253, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "(let ((ii 1)) (\n (do ((i 1 (+ 1 i)))\n ((>= i 4))\n (set! flist \n (cons (lambda (x) (* ii x)) flist))\n (set! ii i))\n))\n flist = []\n\ndef loop_body(i): # extract body of the for loop to function\n def func(x): return x*i\n flist.append(func)\n\nmap(loop_body, xrange(3)) # for i in xrange(3): body\n" }, { "answer_id": 6805307, "author": "Luca Invernizzi", "author_id": 633403, "author_profile": "https://Stackoverflow.com/users/633403", "pm_score": 5, "selected": false, "text": "functools from functools import partial\n\nflist = []\n\ndef func(i, x): return x * i\n\nfor i in range(3):\n flist.append(partial(func, i))\n\nfor f in flist:\n print(f(2))\n" }, { "answer_id": 11626867, "author": "darkfeline", "author_id": 469721, "author_profile": "https://Stackoverflow.com/users/469721", "pm_score": 1, "selected": false, "text": "flist = []\n\nfor i in xrange(3):\n def func(x): return x * func.i\n func.i=i\n flist.append(func)\n\nfor f in flist:\n print f(2)\n" }, { "answer_id": 64895238, "author": "Inyoung Kim 김인영", "author_id": 8471995, "author_profile": "https://Stackoverflow.com/users/8471995", "pm_score": 1, "selected": false, "text": "wrappers flist = []\n\ndef func(i):\n return lambda x: x * i\n\nfor i in range(3):\n flist.append(func(i))\n\nfor f in flist:\n print f(2)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
233,681
<p>I have a web service using .net c# and I want to write to a text file on the server, but I cannot get this to work. I believe it's a permission problem.</p> <p>Specifically, I think the problem is I am using <code>System.IO.Directory.GetCurrentDirectory()</code>. </p> <p>Is there a better alternative?</p>
[ { "answer_id": 233743, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "'<MACHINENAME>\\ASPNET' <identity impersonate=\"true\"/>\n" }, { "answer_id": 7582879, "author": "simaglei", "author_id": 485972, "author_profile": "https://Stackoverflow.com/users/485972", "pm_score": 2, "selected": false, "text": "strFileDestination = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + strFileName;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23149/" ]
233,691
<p><strong>Scenario:</strong></p> <p>The task I have at hand is to enable a single-signon solution between different organizations/websites. I start as an authenticated user on one organization's website, convert specific information into an Xml document, encrypt the document with triple des, and send that over as a post variable to the second organizations login page.</p> <p><strong>Question:</strong></p> <p>Once I have my xml data packaged, how do I programmatically perform a post to the second website and have the user's browser redirected to the second website as well.</p> <p>This should behave just like having a form like: </p> <p><em>action="http://www.www.com/posthere" method="post"</em></p> <p>... and having a hidden text field like: </p> <p><em>input type="hidden" value="my encrypted xml"</em></p> <p>This is being written in asp.net 2.0 webforms.</p> <p>--</p> <p><strong>Edit:</strong> Nic asks why the html form I describe above will not work. Answer: I have no control over either site; I am building the "middle man" that makes all of this happen. Site 1 is forwarding a user to the page that I am making, I have to build the XML, and then forward it to site 2. Site 1 does not want the user to know about my site, the redirect should be transparent. </p> <p>The process I have described above is what both parties (site A and site B) mandate.</p>
[ { "answer_id": 234851, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "...headers left out...\n\n<script type='text/javascript'>\n\n$(document).ready( function() {\n $('form:first').submit();\n });\n</script>\n\n<body>\n <form action='othersiteurl' method='POST'>\n <input type='hidden' value='your-encrypted-xml\" />\n </form>\n</body>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5289/" ]
233,702
<p>I had a VBA project in outlook with a few email macros - but after a PC crash they are all gone and all I see is a fresh 'Project1' when I hit Alt+F11</p> <p>I'm not a VBA programmer, but had a collection of handy macros for email sorting etc. I would not like to have to code them again. Anyone know where the code files should be on the filesystem so that I might rescue the code?</p>
[ { "answer_id": 35205762, "author": "Heider Sati", "author_id": 1915577, "author_profile": "https://Stackoverflow.com/users/1915577", "pm_score": 2, "selected": false, "text": "C:\\Users\\(***Your User Name***)\\AppData\\Roaming\\Microsoft\\Outlook\\VbaProject.OTM\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3024/" ]
233,706
<p>i have a data access layer which returns data from stored procedures. If i bind this to a gridview control in asp.net 2.0, the users then have an option of filtering on that data select list where in they can choose the conditional clause of </p> <ul> <li><p>like</p></li> <li><p>=</p></li> <li><p>or</p></li> <li><p>and</p></li> </ul> <p>Once the result is returned, I do not want to hit the Db again with the filters applied.</p> <p>I have an option to use .net 3.5 if the need be. i looked at this: <a href="http://weblogs.asp.net/jgaylord/archive/2006/05/31/Filter-A-GridView-After-The-Initial-Bind.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/jgaylord/archive/2006/05/31/Filter-A-GridView-After-The-Initial-Bind.aspx</a></p> <p>and not sure of its efficiency.</p>
[ { "answer_id": 35205762, "author": "Heider Sati", "author_id": 1915577, "author_profile": "https://Stackoverflow.com/users/1915577", "pm_score": 2, "selected": false, "text": "C:\\Users\\(***Your User Name***)\\AppData\\Roaming\\Microsoft\\Outlook\\VbaProject.OTM\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
233,711
<p>I use an anonymous object to pass my Html Attributes to some helper methods. If the consumer didn't add an ID attribute, I want to add it in my helper method.</p> <p>How can I add an attribute to this anonymous object?</p>
[ { "answer_id": 233730, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "new { Name1=value1, Name2=value2} new { old.Name1, old.Name2, ID=myId }" }, { "answer_id": 233810, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": -1, "selected": false, "text": "public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}\n" }, { "answer_id": 4416536, "author": "Khaja Minhajuddin", "author_id": 24105, "author_profile": "https://Stackoverflow.com/users/24105", "pm_score": 6, "selected": false, "text": "public static class ObjectExtensions\n{\n public static IDictionary<string, object> AddProperty(this object obj, string name, object value)\n {\n var dictionary = obj.ToDictionary();\n dictionary.Add(name, value);\n return dictionary;\n }\n\n // helper\n public static IDictionary<string, object> ToDictionary(this object obj)\n {\n IDictionary<string, object> result = new Dictionary<string, object>();\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);\n foreach (PropertyDescriptor property in properties){\n result.Add(property.Name, property.GetValue(obj));\n }\n return result;\n }\n}\n" }, { "answer_id": 6753841, "author": "Levitikon", "author_id": 467339, "author_profile": "https://Stackoverflow.com/users/467339", "pm_score": 5, "selected": true, "text": "public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);\n public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)\n {\n RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);\n\n // Add more parameters\n foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)\n {\n routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);\n }\n\n return helper.ActionLink(linkText, actionName, routeValueDictionary);\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
233,718
<p>This question is about App domains and Sessions. Is it possible to have IIS run each User Session in a seperate App Domain. If Yes, Could you please let me settings in the config file that affect this.</p> <p>Regards, Anil.</p>
[ { "answer_id": 233730, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "new { Name1=value1, Name2=value2} new { old.Name1, old.Name2, ID=myId }" }, { "answer_id": 233810, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": -1, "selected": false, "text": "public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}\n" }, { "answer_id": 4416536, "author": "Khaja Minhajuddin", "author_id": 24105, "author_profile": "https://Stackoverflow.com/users/24105", "pm_score": 6, "selected": false, "text": "public static class ObjectExtensions\n{\n public static IDictionary<string, object> AddProperty(this object obj, string name, object value)\n {\n var dictionary = obj.ToDictionary();\n dictionary.Add(name, value);\n return dictionary;\n }\n\n // helper\n public static IDictionary<string, object> ToDictionary(this object obj)\n {\n IDictionary<string, object> result = new Dictionary<string, object>();\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);\n foreach (PropertyDescriptor property in properties){\n result.Add(property.Name, property.GetValue(obj));\n }\n return result;\n }\n}\n" }, { "answer_id": 6753841, "author": "Levitikon", "author_id": 467339, "author_profile": "https://Stackoverflow.com/users/467339", "pm_score": 5, "selected": true, "text": "public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);\n public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)\n {\n RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);\n\n // Add more parameters\n foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)\n {\n routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);\n }\n\n return helper.ActionLink(linkText, actionName, routeValueDictionary);\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
233,719
<p>I'm trying to read the contents of the clipboard using JavaScript. With Internet Explorer it's possible using the function</p> <pre><code>window.clipboardData.getData(&quot;Text&quot;) </code></pre> <p>Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?</p>
[ { "answer_id": 234711, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 5, "selected": true, "text": "onpaste someDomNode.onpaste = function(e) {\n var paste = e.clipboardData && e.clipboardData.getData ?\n e.clipboardData.getData('text/plain') : // Standard\n window.clipboardData && window.clipboardData.getData ?\n window.clipboardData.getData('Text') : // MS\n false;\n if(paste) {\n // ...\n }\n};\n" }, { "answer_id": 54373125, "author": "Kim", "author_id": 2396925, "author_profile": "https://Stackoverflow.com/users/2396925", "pm_score": 1, "selected": false, "text": "$(function () {\n\n $('body').prepend('<input type=\"text\" id=\"hidden_textbox\" style=\"position: absolute; width:0px; height: 0px; top: -100px; left: -100px\">');\n\n var $hiddenTextbox = $('#hidden_textbox');\n $hiddenTextbox.focus();\n\n $(document).on('paste', function () {\n setTimeout(function () {\n var val = $hiddenTextbox.val();\n\n console.log('pasted: ' + val);\n\n }, 50);\n\n });\n\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25960/" ]
233,721
<p>As per RFC1035, dns names may contain \ddd \x and quote symbol. Please explain with examples about those.</p>
[ { "answer_id": 233941, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "Although labels can contain any 8 bit values in octets that make up a\nlabel, it is strongly recommended that labels follow the preferred\nsyntax described elsewhere in this memo, which is compatible with\nexisting host naming conventions. Name servers and resolvers must\ncompare labels in a case-insensitive manner (i.e., A=a), assuming ASCII\nwith zero parity. Non-alphabetic codes must match exactly.\n The following syntax will result in\nfewer problems with many applications\nthat use domain names (e.g., mail,\nTELNET).\n\n<domain> ::= <subdomain> | \" \"\n\n<subdomain> ::= <label> | <subdomain>\n\".\" <label>\n\n<label> ::= <letter> [ [ <ldh-str> ]\n<let-dig> ]\n\n<ldh-str> ::= <let-dig-hyp> |\n<let-dig-hyp> <ldh-str>\n\n<let-dig-hyp> ::= <let-dig> | \"-\"\n\n<let-dig> ::= <letter> | <digit>\n\n<letter> ::= any one of the 52\nalphabetic characters A through Z in\nupper case and a through z in lower\ncase\n\n<digit> ::= any one of the ten digits\n0 through 9\n IHaveAn\\020EmbeddedTab IN A 172.24.3.1\n" }, { "answer_id": 1587319, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 1, "selected": false, "text": "maps-to-nonascii.rfc-test.net" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
233,749
<p>I have this loop, which I am using to get the values of all cells within all rows of a gridview and then write it to a csv file. My loop looks like this:</p> <pre><code>string filename = @"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv"; StreamWriter sWriter = new StreamWriter(filename); string Str = string.Empty; string headertext = ""; sWriter.WriteLine(headertext); for (int i = 0; i &lt;= (this.GridView3.Rows.Count - 1); i++) { for (int j = 0; j &lt;= (this.GridView3.Columns.Count - 1); j++) { Str = this.GridView3.Rows[i].Cells[j].Text.ToString(); sWriter.Write(Str); } sWriter.WriteLine(); } sWriter.Close(); </code></pre> <p>The problem with this code is that, when stepping through, the 2nd loop (the one going through the columns) does not begin as the debugger does not hit this loop and thus my file is empty.</p> <p>Any ideas on what is causing this? The code itself looks fine.</p> <p>Thanks</p>
[ { "answer_id": 233891, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 1, "selected": false, "text": " for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)\n {\n\n for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)\n {\n\n Str = this.GridView3.Rows[i].Cells[j].Text.ToString();\n\n\n sWriter.Write(Str);\n }\n }\n" }, { "answer_id": 233951, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 0, "selected": false, "text": " string filename = @\"C:\\Users\\gurdip.sira\\Documents\\Visual Studio 2008\\WebSites\\Supressions\\APP_DATA\\surpressionstest.csv\";//1\n StreamWriter sWriter = new StreamWriter(filename);//2\n string Str = string.Empty;//3\n string headertext = \"\"; //4\n sWriter.WriteLine(headertext); //5\n for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++) //6\n { //7\n for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++) //8\n { //9\n Str = this.GridView3.Rows[i].Cells[j].Text.ToString();//10\n sWriter.Write(Str);//11\n }//12\n sWriter.WriteLine();//13\n }//14\n sWriter.Close();//15\n}//16\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30004/" ]
233,756
<p>i've written a UserControl descendant that <strong>is</strong> in an assembly dll.</p> <p>How do i drop the control on a form?</p> <pre><code>namespace StackOverflowExample { public partial class MonthViewCalendar : UserControl { ... } } </code></pre> <p>i've added a reference to the assembly under the <strong>References</strong> node in the <strong>Solution Explorer</strong>, but no new control has appeared in my <strong>Toolbox</strong>.</p> <p>How do i make the control appear in the Toolbox so i can drop it on a form?</p> <hr> <p><strong>Update 1</strong>:</p> <p>i tried building the assembly while the Visual Studio option:</p> <p><strong>Tools</strong>--><strong>Options...</strong>--><strong>Windows Forms Designer</strong>--><strong>AutoToolboxPopulate</strong> = true</p> <p>The control didn't appear when in the toolbox in a new solution.</p> <p>Note: i somehow mistakenly wrote "...that is <em>not</em> in an assembly dll...". i don't know how i managed to write that, when it specifically <em>is</em> in an assembly dll. Controls have magically appeared when they're in the same project, but not now that it's a different project/solution.</p> <hr> <p><strong>Update 2: Answer</strong></p> <ol> <li>Right-click the <strong>Toolbox</strong></li> <li>Select <strong>Choose Items...</strong></li> <li><strong>.NET Framework Components</strong> tab</li> <li>Select <strong>Browse...</strong></li> <li><p>Browse to the <strong>assembly dll</strong> file that contains the control and select <strong>Open</strong></p> <p>Note: Controls in the assembly will silently be added to the list of .NET Framework Components.</p></li> <li><strong>Check</strong> each of the controls you wish to appear in the toolbox</li> <li>Select <strong>OK</strong></li> </ol>
[ { "answer_id": 233774, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "ToolboxItemAttribute ToolboxItemAttribute" }, { "answer_id": 233958, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 0, "selected": false, "text": "using System;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\nnamespace YourUIControls\n{\n [DefaultProperty(\"TextString\")]\n [DefaultEvent(\"TextClick\")]\n public partial class RoundedLabel : UserControl\n {\n public RoundedLabel()\n {\n InitializeComponent();\n }\n protected override void OnPaint(PaintEventArgs e)\n {\n //Draw your label here…\n }\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
233,759
<p>I was wondering if the C# project setting "Allow unsafe code" applies only to unsafe C# code in the project itself, or is it necessary to set this option when linking in a native C++ DLL? What about linking in a managed DLL that itself links to a native DLL? What does this option really do, under the hood?</p>
[ { "answer_id": 233763, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 3, "selected": false, "text": "unsafe(...)\n{\n}\n" }, { "answer_id": 233767, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": false, "text": "unsafe" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
233,790
<p>Is there a way to colorize parts of logs in the eclipse console. I know I could send to error and standard streams and color them differently but I'm more looking someting in the lines of ANSI escape codes (or anyother, HTML ?) where I could embed the colors in the string to have it colored in the logs.</p> <p>It sure would help making the important bits stand out without resorting to weird layout, rather keep the layout to the log4j setups </p> <p>here is an example of what I am looking for :</p> <p>[INFO ] The grid is complete ....... <strong>false</strong></p> <p>where the bold parts would be in blue, this coloring can be controlled by the application to an extent. like so (tags are conceptual and arbitrary, but you get the idea):</p> <p>log.info(String.format("The grid is complete ....... <code>&lt;blue&gt;</code>%s<code>&lt;/blue&gt;</code>", isComplete ));</p> <hr> <p>On a more general note it is the ability to embed meta information in the logs to help the presentation of these logs. Much like we tag web pages content to help the presentation of the information by CSS.</p>
[ { "answer_id": 1373290, "author": "Benjamin Seiller", "author_id": 167865, "author_profile": "https://Stackoverflow.com/users/167865", "pm_score": 7, "selected": true, "text": ".* .*ERROR.*" }, { "answer_id": 60434404, "author": "jajube", "author_id": 7915606, "author_profile": "https://Stackoverflow.com/users/7915606", "pm_score": 2, "selected": false, "text": "public static final String ANSI_RESET = \"\\u001B[0m\";\npublic static final String ANSI_RED = \"\\u001B[31m\";\n\npublic static void main(String[] args) {\n System.out.println(ANSI_RED + \"This text is red!\" + ANSI_RESET);\n}\n" }, { "answer_id": 63429576, "author": "Mojtaba Hosseini", "author_id": 5623035, "author_profile": "https://Stackoverflow.com/users/5623035", "pm_score": 0, "selected": false, "text": "⚠️ : error message\n: warning message\n: ok status message\n: action message\n: canceled status message\n: Or anything you like and want to recognize immediately by color\n Authentication Key: \nServer Error: \netc.\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25812/" ]
233,793
<p>I'm trying to dynamically add some textboxes (input type=text) to a page in javascript and prefill them. The textboxes are coming up, but they are coming up empty. What is the proper way to pre-fill a textbox. Ideally I'd love to use the trick of creating a child div, setting the innerhtml property, and then adding that div to the parent main div but that didn't work. Then I thought I'd use the dom but setting textboxname.value before or after insertion won't work and doing txttextbox.setattribute('value','somevalue') won't work either. Works fine in firefox. What gives? This has to be possible? Here is my code. I know I'm only using string literals, but these will be replaced with the results of a web service call eventually. Below is some code. Oh and how do you format code to show up as you type it? I thought it said to indent four spaces, and I did that but the code is still on one line. Sorry about that.</p> <pre><code>var table=document.createElement('table'); var tbody=document.createElement('tbody'); var row=document.createElement('tr'); row.appendChild(document.createElement('td').appendChild(document.createTextNode('E-mail'))); var txtEmail=document.createElement('input'); row.appendChild(document.createElement('td').appendChild(txtEmail)); tbody.appendChild(row); table.appendChild(tbody); //document.getElementById('additionalEmails').innerHTML=""; document.getElementById('additionalEmails').appendChild(table); </code></pre>
[ { "answer_id": 233815, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "txtEmail.value = 'my text'\n" }, { "answer_id": 233853, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "document.body.insert(new Element(\"input\", { type: \"text\", size:20, value:'hello world' })) \n" }, { "answer_id": 233893, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 0, "selected": false, "text": "\nvar txtEmail=document.createElement('input');\n\ndocument.getElementById('someElementThatAlreadyExists').appendChild(txtEmail);\n\ntxtEmail.value = 'sample text';\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
233,802
<p>I am trying to detect Blackberry user agents in my app, which works fine in my development version. But nothing happens when I redeploy the app in production.</p> <p>application_helper.rb</p> <pre><code> def blackberry_user_agent? request.env["HTTP_USER_AGENT"] &amp;&amp; request.env["HTTP_USER_AGENT"][/(Blackberry)/] end </code></pre> <p>application.html.erb</p> <pre><code>&lt;% if blackberry_user_agent? -%&gt; &lt;div class="message"&gt; &lt;p&gt;Using a Blackberry? &lt;a href="http://mobile.site.ca/"&gt;Use the mobile optimized version&lt;/a&gt;.&lt;/p&gt; &lt;/div&gt; </code></pre> <p>I've tried clearing the cache using rake tmp:cache:clear and restarted mongrel a few times. Apparently the HTTP_USER_AGENT is coming back nil in production. I am using Nginx with a mongrel cluster.</p>
[ { "answer_id": 233986, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 3, "selected": true, "text": "log_format main '$remote_addr - $remote_user [$time_local] $request '\n '\"$status\" $body_bytes_sent \"$http_referer\" '\n '\"$http_user_agent\" \"http_x_forwarded_for\"';\n" }, { "answer_id": 248115, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 5, "selected": false, "text": "request.user_agent\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10258/" ]
233,828
<p>Let's say you have a aspx page that does not rely on session, but does rely on viewstate for persistance between postbacks. </p> <p>If a user is accessing this page, and leaves for a long lunch, will viewstate still be valid when he returns?</p>
[ { "answer_id": 5377527, "author": "AareP", "author_id": 11741, "author_profile": "https://Stackoverflow.com/users/11741", "pm_score": 3, "selected": false, "text": "<sessionPageState historySize=\"9\"/>" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21155/" ]
233,842
<p>I am using VB.Net WinForms. I would like to call the Adobe Reader 9 ActiveX control to print some PDFs. I have added the ActiveX control to the VS toolbox (the dll is AcroPDF.dll, the COM name "Adobe PDF Reader". After some experiment the following code works.</p> <pre><code>Dim files As String() = Directory.GetFiles(TextBoxPath.Text, "*.pdf", SearchOption.TopDirectoryOnly) Using ActiveXPDF As New AxAcroPDFLib.AxAcroPDF Me.Controls.Add(ActiveXPDF) ActiveXPDF.Hide() For Each filename As String In files ActiveXPDF.LoadFile(filename) ActiveXPDF.printAll() 'Begin Yukky Hack ' Dim endTime As Date = DateAdd(DateInterval.Second, 20, Now) Do While Now &lt; endTime My.Application.DoEvents() Loop 'End Yuk ' Next End Using </code></pre> <p>Without the Yuk bit this will only print some of the PDFs, it seems that the End Using statement is calling dispose on the control before it has finished printing.</p> <p>Therefore it seems the call to printAll is non-blocking but I can't find a callback or status property I can query to see if the print spooling has been completed. I am missing a property/method or is there a more elegant (and more responsive) work around?</p>
[ { "answer_id": 1862454, "author": "Ed Zenker", "author_id": 226624, "author_profile": "https://Stackoverflow.com/users/226624", "pm_score": -1, "selected": false, "text": "Sub Show_Document(ByVal FILENAME As String)\n Dim p As Process = Nothing\n Try\n If My.Computer.FileSystem.FileExists(FILENAME) Then\n p = Process.Start(FILENAME)\n p.Dispose()\n End If\n\n Catch ex As Exception\n\n Finally\n\n End Try\n\nEnd Sub\n" }, { "answer_id": 9227853, "author": "Anderson", "author_id": 1202042, "author_profile": "https://Stackoverflow.com/users/1202042", "pm_score": 1, "selected": false, "text": "var\n formModal : TFormModal;\nbegin\n formModal := TFormModal.Create(self);\n //PrintMethodHere \n frmPecas.CarregarDocumentoParaImpressao();\n formModal.ShowModal;\nend;\n unit FModal;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, ExtCtrls, Animate, GIFCtrl;\n\ntype\n TFormModal = class(TForm)\n Timer: TTimer;\n imgGif: TRxGIFAnimator;\n procedure TimerTimer(Sender: TObject);\n procedure FormShow(Sender: TObject);\n procedure FormClose(Sender: TObject; var Action: TCloseAction);\n procedure FormCreate(Sender: TObject);\n procedure FormKeyDown(Sender: TObject; var Key: Word;\n Shift: TShiftState);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n FormModal: TFormModal;\n\nimplementation\n\n{$R *.dfm}\n// Author: Anderson Mello Date: 09-fev-2012\n// DEscription: Using TTimer after 5 seconds I close this form\nprocedure TFormModal.TimerTimer(Sender: TObject);\nbegin\n close;\nend;\n\n// Author: Anderson Mello Date: 09-fev-2012\n// Description: Enable the timer only when the form is shown\nprocedure TFormModal.FormShow(Sender: TObject);\nbegin\n Timer.Enabled := true;\nend;\n\n// Description: disable when close\nprocedure TFormModal.FormClose(Sender: TObject; var Action: TCloseAction);\nbegin\n Timer.Enabled := false;\nend;\n\n// Author: Anderson Mello Date: 09-fev-2012\n// Description: disable close button \"X\", so the user can't close \nprocedure TFormModal.FormCreate(Sender: TObject);\nvar\n hSysMenu:HMENU;\nbegin\n hSysMenu:=GetSystemMenu(Self.Handle,False);\n if hSysMenu <> 0 then begin\n EnableMenuItem(hSysMenu,SC_CLOSE,MF_BYCOMMAND or MF_GRAYED);\n DrawMenuBar(Self.Handle);\n end;\n KeyPreview:=True;\nend;\n\n// Author: Anderson Mello Date: 09-fev-2012\n// Description: disable shortcuts to close\nprocedure TFormModal.FormKeyDown(Sender: TObject; var Key: Word;\n Shift: TShiftState);\nbegin\n if (Key = VK_F4) and (ssAlt in Shift) then\n Key:=0;\nend;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29411/" ]
233,850
<p>What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game? I always find the piece rotation and representation schemes confusing.</p> <p>Most tetris games seem to use a naive "remake the array of blocks" at each rotation:</p> <p><a href="http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris" rel="noreferrer">http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris</a></p> <p>However, some use pre-built encoded numbers and bit shifting to represent each piece:</p> <p><a href="http://www.codeplex.com/wintris" rel="noreferrer">http://www.codeplex.com/wintris</a></p> <p>Is there a method to do this using mathematics (not sure that would work on a cell based board)?</p>
[ { "answer_id": 233882, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 5, "selected": false, "text": "[ 0 1 ]\n[ -1 0 ]\n [ 0 -1 ]\n[ 1 0 ]\n" }, { "answer_id": 233894, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "class Shape\n{\n Color color;\n ShapeRotation[] rotations;\n}\n\nclass ShapeRotation\n{\n Point[4] points;\n}\n\nclass Point\n{\n int x, y;\n}\n" }, { "answer_id": 233985, "author": "Dave Cluderay", "author_id": 30933, "author_profile": "https://Stackoverflow.com/users/30933", "pm_score": 4, "selected": false, "text": "x2 = (y1 + px - py)\n\ny2 = (px + py - x1 - q)\n x2 = (px + py - y1 - q)\n\ny2 = (x1 + py - px)\n" }, { "answer_id": 1740038, "author": "BeMasher", "author_id": 211769, "author_profile": "https://Stackoverflow.com/users/211769", "pm_score": 2, "selected": false, "text": "rotate = lambda tetrad: zip(*tetrad[::-1])\n\n# S Tetrad\ntetrad = rotate([[0,0,0,0], [0,0,0,0], [0,1,1,0], [1,1,0,0]])\n" }, { "answer_id": 1996601, "author": "mdm", "author_id": 25318, "author_profile": "https://Stackoverflow.com/users/25318", "pm_score": 2, "selected": false, "text": " 0123 012\n0.... 0.#.\n1#### or 1###\n2.... 2...\n3....\n x_new = y_old\ny_new = 1 - (x_old - (me - 2))\n x_new = 1 - (y_old - (me - 2))\ny_new = x_old\n me 4 2 3" }, { "answer_id": 2753376, "author": "Ricardo Sousa", "author_id": 330791, "author_profile": "https://Stackoverflow.com/users/330791", "pm_score": 3, "selected": false, "text": "Mat A = [1,1,1]\n [0,0,1]\n [0,0,0]\n IHM(A) = [0,0,1]\n [0,1,0]\n [1,0,0]\n Mat Rotation = Trn(A)*IHM(A) = [1,0,0]*[0,0,1] = [0,0,1]\n [1,0,0] [0,1,0] = [0,0,1]\n [1,1,0] [1,0,0] = [0,1,1]\n" }, { "answer_id": 8131337, "author": "Jason Rae", "author_id": 680565, "author_profile": "https://Stackoverflow.com/users/680565", "pm_score": 5, "selected": false, "text": "public synchronized void rotateLeft(){\n\n Point[] rotatedCoordinates = new Point[MAX_COORDINATES];\n\n for(int i = 0; i < MAX_COORDINATES; i++){\n\n // Translates current coordinate to be relative to (0,0)\n Point translationCoordinate = new Point(coordinates[i].x - origin.x, coordinates[i].y - origin.y);\n\n // Java coordinates start at 0 and increase as a point moves down, so\n // multiply by -1 to reverse\n translationCoordinate.y *= -1;\n\n // Clone coordinates, so I can use translation coordinates\n // in upcoming calculation\n rotatedCoordinates[i] = (Point)translationCoordinate.clone();\n\n // May need to round results after rotation\n rotatedCoordinates[i].x = (int)Math.round(translationCoordinate.x * Math.cos(Math.PI/2) - translationCoordinate.y * Math.sin(Math.PI/2)); \n rotatedCoordinates[i].y = (int)Math.round(translationCoordinate.x * Math.sin(Math.PI/2) + translationCoordinate.y * Math.cos(Math.PI/2));\n\n // Multiply y-coordinate by -1 again\n rotatedCoordinates[i].y *= -1;\n\n // Translate to get new coordinates relative to\n // original origin\n rotatedCoordinates[i].x += origin.x;\n rotatedCoordinates[i].y += origin.y;\n\n // Erase the old coordinates by making them black\n matrix.fillCell(coordinates[i].x, coordinates[i].y, Color.black);\n\n }\n // Set new coordinates to be drawn on screen\n setCoordinates(rotatedCoordinates.clone());\n}\n" }, { "answer_id": 12767925, "author": "Mickey Tin", "author_id": 1649615, "author_profile": "https://Stackoverflow.com/users/1649615", "pm_score": 0, "selected": false, "text": "oldShapeMap[3][3] = {{1,1,0},\n {0,1,0},\n {0,1,1}};\n\nbool newShapeMap[3][3] = {0};\nint gridSize = 3;\n\nfor(int i=0;i<gridSize;i++)\n for(int j=0;j<gridSize;j++)\n newShapeMap[i][j] = oldShapeMap[j][(gridSize-1) - i];\n/*newShapeMap now contain: \n {{0,0,1},\n {1,1,1},\n {1,0,0}};\n\n*/ \n" }, { "answer_id": 14926239, "author": "Andrew Fader", "author_id": 962968, "author_profile": "https://Stackoverflow.com/users/962968", "pm_score": 0, "selected": false, "text": "require 'matrix'\nshape = shape.map{|arr|(Matrix[arr] * Matrix[[0,-1],[1,0]]).to_a.flatten}\n" }, { "answer_id": 27721888, "author": "Playmen Paychek", "author_id": 4408437, "author_profile": "https://Stackoverflow.com/users/4408437", "pm_score": 2, "selected": false, "text": "private void rotateClockwise()\n{\n if(rotatable > 0) //We don't rotate tetromino O. It doesn't have central square.\n {\n int i = y1 - y0;\n y1 = (y0 + x1) - x0;\n x1 = x0 - i;\n i = y2 - y0;\n y2 = (y0 + x2) - x0;\n x2 = x0 - i;\n i = y3 - y0;\n y3 = (y0 + x3) - x0;\n x3 = x0 - i; \n }\n}\n\nprivate void rotateCounterClockwise()\n{\n if(rotatable > 0)\n {\n int i = y1 - y0;\n y1 = (y0 - x1) + x0;\n x1 = x0 + i;\n i = y2 - y0;\n y2 = (y0 - x2) + x0;\n x2 = x0 + i;\n i = y3 - y0;\n y3 = (y0 - x3) + x0;\n x3 = x0 + i;\n }\n}\n" }, { "answer_id": 34164786, "author": "Ferit", "author_id": 1079908, "author_profile": "https://Stackoverflow.com/users/1079908", "pm_score": 3, "selected": false, "text": "originalMatrix = \n[0, 0, 1]\n[1, 1, 1]\n clockwise90DegreesRotatedMatrix = reverseTheOrderOfColumns(Transpose(originalMatrix))\n\nanticlockwise90DegreesRotatedMatrix = reverseTheOrderOfRows(Transpose(originalMatrix))\n originalMatrix = \n x y z\na[0, 0, 1]\nb[1, 1, 1]\n transposed = transpose(originalMatrix)\n a b\nx[0, 1]\ny[0, 1]\nz[1, 1]\n counterClockwise90DegreesRotated = reverseTheOrderOfRows(transposed)\n a b\nz[1, 1]\ny[0, 1]\nx[0, 1]\n clockwise90DegreesRotated = reverseTheOrderOfColumns(transposed)\n b a\nx[1, 0]\ny[1, 0]\nz[1, 1]\n" }, { "answer_id": 47006916, "author": "Vincent", "author_id": 270663, "author_profile": "https://Stackoverflow.com/users/270663", "pm_score": 0, "selected": false, "text": "pieces = [\n [(0,0),(0,1),(0,2),(0,3)],\n [(0,0),(0,1),(1,0),(1,1)],\n [(1,0),(0,1),(1,1),(1,2)],\n [(0,0),(0,1),(1,0),(2,0)],\n [(0,0),(0,1),(1,1),(2,1)],\n [(0,1),(1,0),(1,1),(2,0)]\n]\n\ndef get_piece_dimensions(piece):\n max_r = max_c = 0\n for point in piece:\n max_r = max(max_r, point[0])\n max_c = max(max_c, point[1])\n return max_r, max_c\n\ndef rotate_piece(piece):\n max_r, max_c = get_piece_dimensions(piece)\n new_piece = []\n for r in range(max_r+1):\n for c in range(max_c+1):\n if (r,c) in piece:\n new_piece.append((c, max_r-r))\n return new_piece\n" }, { "answer_id": 66210899, "author": "vadimv", "author_id": 417174, "author_profile": "https://Stackoverflow.com/users/417174", "pm_score": 0, "selected": false, "text": "private static char[][] rotateMatrix(char[][] m) {\n final int h = m.length;\n final int w = m[0].length;\n final char[][] t = new char[h][w];\n\n for(int y = 0; y < h; y++) {\n for(int x = 0; x < w; x++) {\n t[w - x - 1][y] = m[y][x];\n }\n }\n return t;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21826/" ]
233,870
<p>I know the statement:</p> <pre><code>create table xyz_new as select * from xyz; </code></pre> <p>Which copies the structure and the data, but what if I just want the structure?</p>
[ { "answer_id": 233890, "author": "Jim Hudson", "author_id": 8051, "author_profile": "https://Stackoverflow.com/users/8051", "pm_score": 10, "selected": true, "text": "create table xyz_new as select * from xyz where 1=0;\n" }, { "answer_id": 240371, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 6, "selected": false, "text": "SET LONG 5000\nSELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL;\n SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME', 'OTHER_SCHEMA_NAME' ) FROM DUAL;\n" }, { "answer_id": 5101313, "author": "Digo", "author_id": 631805, "author_profile": "https://Stackoverflow.com/users/631805", "pm_score": 0, "selected": false, "text": "create table abc_new as select * from abc; \n abc_new" }, { "answer_id": 12166768, "author": "Donkha", "author_id": 1631369, "author_profile": "https://Stackoverflow.com/users/1631369", "pm_score": -1, "selected": false, "text": "CREATE table new_table_name AS(Select * from old_table_name);\n query DELETE * FROM new_table_name.\n" }, { "answer_id": 20721832, "author": "sunleo", "author_id": 1755242, "author_profile": "https://Stackoverflow.com/users/1755242", "pm_score": 4, "selected": false, "text": "create table xyz_new as select * from xyz where rownum = -1;\n" }, { "answer_id": 21630355, "author": "user3284249", "author_id": 3284249, "author_profile": "https://Stackoverflow.com/users/3284249", "pm_score": 1, "selected": false, "text": "create table new_table as select * from old_table where 1=2;\n new_table old_table" }, { "answer_id": 29763613, "author": "Prashant Mishra", "author_id": 4534585, "author_profile": "https://Stackoverflow.com/users/4534585", "pm_score": -1, "selected": false, "text": "Create table target_table \nAs\nSelect * \nfrom source_table \nwhere 1=2;\n" }, { "answer_id": 32097825, "author": "Diogo Maschio", "author_id": 3961267, "author_profile": "https://Stackoverflow.com/users/3961267", "pm_score": 0, "selected": false, "text": "SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL \n TYPE TABLE PROCEDURE" }, { "answer_id": 34213500, "author": "Mohsen Molaei", "author_id": 1939606, "author_profile": "https://Stackoverflow.com/users/1939606", "pm_score": 3, "selected": false, "text": "Create table New_table as select * from Old_table where 1=2 ;" }, { "answer_id": 40981693, "author": "Brian Leach", "author_id": 2800402, "author_profile": "https://Stackoverflow.com/users/2800402", "pm_score": 2, "selected": false, "text": " DECLARE\n l_ddl VARCHAR2 (32767);\nBEGIN\n l_ddl := REPLACE (\n REPLACE (\n DBMS_LOB.SUBSTR (DBMS_METADATA.get_ddl ('TABLE', 'ACTIVITY_LOG', 'OLDSCHEMA'))\n , q'[\"OLDSCHEMA\"]'\n , q'[\"NEWSCHEMA\"]'\n )\n , q'[\"OLDTABLSPACE\"]'\n , q'[\"NEWTABLESPACE\"]'\n );\n\n EXECUTE IMMEDIATE l_ddl;\nEND; \n" }, { "answer_id": 43438077, "author": "Alok", "author_id": 7867894, "author_profile": "https://Stackoverflow.com/users/7867894", "pm_score": 0, "selected": false, "text": "create table <target_table> as select * from <source_table> where 1=2;\n create table <target_table> as select * from <source_table>;\n" }, { "answer_id": 45991389, "author": "guesswho", "author_id": 7026895, "author_profile": "https://Stackoverflow.com/users/7026895", "pm_score": 1, "selected": false, "text": "SELECT * INTO newtable\nFROM oldtable\nWHERE 1 = 0;\n" }, { "answer_id": 48831620, "author": "Dima Korobskiy", "author_id": 534217, "author_profile": "https://Stackoverflow.com/users/534217", "pm_score": 1, "selected": false, "text": "WHERE 1 = 0 \nCREATE TABLE bar AS\n SELECT *\n FROM foo\n FETCH FIRST 0 ROWS ONLY;\n" }, { "answer_id": 64233045, "author": "pahariayogi", "author_id": 2316223, "author_profile": "https://Stackoverflow.com/users/2316223", "pm_score": 1, "selected": false, "text": "CREATE TABLE t1_temp FOR EXCHANGE WITH TABLE t1;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
233,905
<p>Is is better to do a joined query like this:</p> <pre><code>var employer = (from person in db.People join employer in db.Employers on person.EmployerID equals employer.EmployerID where person.PersonID == idPerson select employer).FirstOrDefault(); </code></pre> <p>Or is it just as good to do the easy thing and do this (with null checks):</p> <pre><code>var employer = (from person in db.People where person.PersonID == idPerson select person).FirstOrDefault().Employer; </code></pre> <p>Obviously, in this one I would actually have to do it in 2 statements to get in the null check.</p> <p>Is there any sort of best practice here for either readability or performance issues?</p>
[ { "answer_id": 233943, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "var employer = (from person in db.People\n where person.PersonID == idPerson\n select person.Employer).FirstOrDefault();\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4797/" ]
233,908
<p>I need to replace some 2- and 3-digit numbers with the same number plus 10000. So</p> <pre><code>Photo.123.aspx </code></pre> <p>needs to become</p> <pre><code>Photo.10123.aspx </code></pre> <p>and also</p> <pre><code>Photo.12.aspx </code></pre> <p>needs to become</p> <pre><code>Photo.10012.aspx </code></pre> <p>I know that in .NET I can delegate the replacement to a function and just add 10000 to the number, but I'd rather stick to garden-variety RegEx if I can. Any ideas?</p>
[ { "answer_id": 233977, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 1, "selected": false, "text": "Photo\\.{\\d\\d\\d}\\.aspx Photo.10\\1.aspx Photo\\.{\\d\\d}\\.aspx Photo.100\\1.aspx" }, { "answer_id": 234026, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "static public string Evaluator(Match match) \n{\n return \"Photo.1\" \n + match.Groups[1].Captures[0].Value.PadLeft(4, '0')\n + \".aspx\";\n}\n\npublic void Code(params string[] args)\n{\n string pattern = @\"Photo\\.([\\d]+)\\.aspx\";\n string test = \"Photo.123.aspx\";\n Regex regex = new Regex(pattern);\n string converted = regex.Replace(test, Evaluator) \n Console.WriteLine(converted);\n}\n" }, { "answer_id": 234050, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 3, "selected": false, "text": "VB.NET s(\n Photo\\. (\\d{2,3}) \\.aspx\n){\n \"Photo.\" . ($1 + 10000) . \".aspx\"\n}xe\n" }, { "answer_id": 234055, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 1, "selected": false, "text": " Regex regex = new Regex(@\"(\\d\\d\\d?)\", RegexOptions.None);\n string result = regex.Replace(@\"Photo.123.asp\", delegate(Match m) \n {\n return \"Photo.1\"\n + m.Groups[1].Captures[0].Value.PadLeft(4, '0')\n + \".aspx\";\n }\n );\n" }, { "answer_id": 234063, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "\"Photo\\./d\\.aspx\" and replace with \"Photo.1000$1.aspx\"\n\"Photo\\./d/d\\.aspx\" and replace with \"Photo.100$1.aspx\"\n\"Photo\\./d/d/d\\.aspx\" and replace with \"Photo.10$1.aspx\"\n" }, { "answer_id": 234085, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "[^\\d][\\d]{2,3}[^\\d]\n" }, { "answer_id": 234166, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 4, "selected": true, "text": "using System;\nusing System.Text.RegularExpressions;\n\nnamespace RenameAspxFile\n{\n sealed class Program\n {\n private static readonly Regex _aspxFileNameRegex = new Regex(@\"(\\S+\\.)(\\d+)(\\.aspx)\", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);\n private static readonly string[] _aspxFileNames= {\"Photo.123.aspx\", \"Photo.456.aspx\", \"BigPhoto.789.aspx\"};\n\n static void Main(string[] args)\n {\n Program program = new Program();\n program.Run();\n }\n\n void Run()\n {\n foreach (string aspxFileName in _aspxFileNames)\n {\n Console.WriteLine(\"Renamed '{0}' to '{1}'\", aspxFileName, AddTenThousandToPhotoNumber(aspxFileName));\n }\n }\n\n string AddTenThousandToPhotoNumber(string aspxFileName)\n {\n return _aspxFileNameRegex.Replace(aspxFileName, match => String.Format(\"{0}{1}{2}\", match.Result(\"$1\"), Int32.Parse(match.Result(\"$2\")) + 10000, match.Result(\"$3\")));\n }\n }\n}\n" }, { "answer_id": 3389244, "author": "Niall Murphy", "author_id": 188397, "author_profile": "https://Stackoverflow.com/users/188397", "pm_score": 0, "selected": false, "text": ":s/Photo\\.\\d\\+\\.aspx/\\=Photo\\.submatch(0)+10000\\.aspx/g\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
233,911
<p>Im currently using ie as an active x com thing on wxWidgets and was wanting to know if there is any easy way to change the user agent that will always work.</p> <p>Atm im changing the header but this only works when i manually load the link (i.e. call setUrl)</p>
[ { "answer_id": 235713, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 3, "selected": true, "text": "DISPID_AMBIENT_USERAGENT DISPID_AMBIENT_USERAGENT" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23339/" ]
233,916
<p>I have a WinForms app with an input textbox, button, and a multiline output textbox. A root path is entered in the textbox. Button click calls a function to recursively check all subdirectories for some proper directory naming validation check. The results are output into the multiline textbox.</p> <p>If the recursive work is done in a separate class, I have two options:</p> <ol> <li><p>Keep track of improper directories in a class property(e.g. ArrayList),return the ArrayList when done, and update the output textbox with all results.</p></li> <li><p>Pass in ByRef the output textbox and update/refresh it for each improper directory. Even though 1 &amp; 2 are single-threaded, with 2, I would at least get my results updated per directory.</p></li> </ol> <p>If the recursive work is done in the presentation layer and the validation is done in a separate class, I can multithread.</p> <p>Which is a cleaner way?</p>
[ { "answer_id": 233974, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "List<string>" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
233,919
<p>I have been working with T-SQL in MS SQL for some time now and somehow whenever I have to insert data into a table I tend to use syntax:</p> <pre><code>INSERT INTO myTable &lt;something here&gt; </code></pre> <p>I understand that keyword <code>INTO</code> is optional here and I do not have to use it but somehow it grew into habit in my case.</p> <p>My question is: </p> <ul> <li>Are there any implications of using <code>INSERT</code> syntax versus <code>INSERT INTO</code>?</li> <li>Which one complies fully with the standard?</li> <li>Are they both valid in other implementations of SQL standard?</li> </ul>
[ { "answer_id": 233945, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": true, "text": "INSERT INTO INTO" }, { "answer_id": 233962, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": false, "text": "INTO INTO INSERT INTO Customer INSERT Customer" }, { "answer_id": 233965, "author": "AgentThirteen", "author_id": 26199, "author_profile": "https://Stackoverflow.com/users/26199", "pm_score": 0, "selected": false, "text": "group BY order BY" }, { "answer_id": 73897741, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "INSERT INTO INSERT INTO DELETE FROM DELETE FROM" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ]
233,922
<p>I have this code to give me a rollover on submit buttons, and I'm trying to make it more generic:</p> <pre><code>$('.rollover').hover( function(){ // Change the input image's source when we "roll on" srcPath = $(this).attr("src"); srcPathOver = ??????? /*need to manipulate srcPath to change from img/content/go-button.gif into img/content/go-button-over.gif */ $(this).attr({ src : srcPathOver}); }, function(){ // Change the input image's source back to the default on "roll off" $(this).attr({ src : srcPath}); } ); </code></pre> <p>Two things really,</p> <p>I want to learn how manipulate the <code>srcPath</code> variable to append the text '-over' onto the gif filename, to give a new image for the rollover. Can anyone suggest a way to do this?</p> <p>Also, can someone tell me if this code could be refined at all? I'm a bit new to jQuery and wondered if the syntax could be improved upon.</p> <p>Many thanks.</p>
[ { "answer_id": 234025, "author": "Matt Ephraim", "author_id": 22291, "author_profile": "https://Stackoverflow.com/users/22291", "pm_score": 2, "selected": false, "text": "srcPathOver = srcPath.replace(/([^.]*)\\.(.*)/, \"$1-over.$2\");\n var srcPath;\n$('.rollover').hover(...\n" }, { "answer_id": 234028, "author": "LorenzCK", "author_id": 3118, "author_profile": "https://Stackoverflow.com/users/3118", "pm_score": 3, "selected": false, "text": "function appendOver(srcPath){\n var index = s.indexOf('.');\n\n var before = s.substr(0, index);\n var after = s.substr(index);\n\n return before + \"-over\" + after;\n}\n" }, { "answer_id": 234042, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 5, "selected": true, "text": "$('.rollover').hover(\n function(){ // Change the input image's source when we \"roll on\"\n var t = $(this);\n t.attr('src',t.attr('src').replace(/([^.]*)\\.(.*)/, \"$1-over.$2\"));\n },\n function(){ \n var t= $(this);\n t.attr('src',t.attr('src').replace('-over',''));\n }\n );\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
233,936
<p>Ok let me make an example:</p> <pre><code>&lt;head&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $("#options_2").hide(); $("#options_3").hide(); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="options_1"&gt;option 1&lt;/div&gt; &lt;div id="options_2"&gt;option 2&lt;/div&gt; &lt;div id="options_3"&gt;option 3&lt;/div&gt; &lt;a href="" class="selected"&gt;choose option 1&lt;/a&gt; &lt;a href=""&gt;choose option 2&lt;/a&gt; &lt;a href=""&gt;choose option 3&lt;/a&gt; &lt;/body&gt; </code></pre> <p>As you can see only option 1 is visible by default, and the link you click to show option 1 has the class="selected" by default, showing the user that that option is currently selected. I basically want it so that when they click "choose option 2" the options 1 div hides itself and the options 2 div shows itself, and then gives the second link the selected class and removes the class from the image link.</p> <p>It basically just tabs using links and divs but due to the format I have to display it in I cannot use any of the tabs plugins I have found online.</p>
[ { "answer_id": 234009, "author": "Wayne Austin", "author_id": 31109, "author_profile": "https://Stackoverflow.com/users/31109", "pm_score": 2, "selected": false, "text": "$('a#link_1').click(function() {\n $(this).attr(\"class\", \"selected\");\n $(this).siblings('a').removeClass(\"selected\");\n $('div#option_1').show();\n $('div#option_1').siblings('div').hide();\n});\n $('a#link_2').click(function() {\n $(this).attr(\"class\", \"selected\");\n $(this).siblings('a').removeClass(\"selected\");\n $('div#option_2').show();\n $('div#option_2').siblings('div').hide();\n});\n $('a#link_3').click(function() {\n $(this).attr(\"class\", \"selected\");\n $(this).siblings('a').removeClass(\"selected\");\n $('div#option_3').show();\n $('div#option_3').siblings('div').hide();\n});\n" }, { "answer_id": 234022, "author": "Matt Goddard", "author_id": 5185, "author_profile": "https://Stackoverflow.com/users/5185", "pm_score": 5, "selected": true, "text": "<div id=\"options_1\" class=\"tab\" >option 1</div>\n<div id=\"options_2\" class=\"tab\">option 2</div>\n<div id=\"options_3\" class=\"tab\">option 3</div>\n\n$(document).ready(function () {\n\n var clickHandler = function (link) {\n $('.tab').hide();\n $('#option_' + link.data.id).show();\n $('.selected').removeClass('selected');\n $(this).attr('class','selected');\n }\n\n $('.link1').bind('click', {id:'1'} ,clickHandler);\n $('.link2').bind('click', {id:'2'} ,clickHandler);\n $('.link3').bind('click', {id:'3'} ,clickHandler);\n})\n" }, { "answer_id": 234041, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 1, "selected": false, "text": "$('a.opener').click(function() {\n // mark current link as selected and unmark all others\n $(this)\n .addClass('selected')\n .siblings('a').removeClass('selected');\n\n // find a div to show, and hide its siblings\n $('#' + $(this).attr('id').substring(0, 9))\n .show()\n .siblings('div').hide();\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
233,966
<p>I have a great deal of data to keep synchronized over 4 or 5 sites around the world, around half a terabyte at each site. This changes (either adds or changes) by around 1.4 Gigabytes per day, and the data can change at any of the four sites.</p> <p>A large percentage (30%) of the data is duplicate packages (Perhaps packaged-up JDKs), so the solution would have to include a way of picking up the fact that there are such things lying aruond on the local machine and grab them instead of downloading from another site.</p> <p>The control of versioning is not an issue, this is not a codebase per-se.</p> <p>I'm just interested if there are any solutions out there (preferably open-source) that get close to such a thing? </p> <p>My baby script using rsync doesn't cut the mustard any more, I'd like to do more complex, intelligent synchronization.</p> <p>Thanks</p> <p>Edit : This should be UNIX based :)</p>
[ { "answer_id": 236271, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "detect-renamed" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31161/" ]
233,979
<p>I am trying to link to a file that has the '#' character in via a window.open() call. The file does exist and can be linked to just fine using a normal anchor tag.</p> <p>I have tried escaping the '#' character with '%23' but when the window.open(myurl) gets processed, the '%23' becomes '%2523'. This tells me that my url string is being escapped by the window.open call changing the '%' to the '%25'.</p> <p>Are there ways to work around this extra escaping.</p> <p>Sample code:</p> <pre><code>&lt;script language="javascript"&gt; function escapePound(url) { // original attempt newUrl = url.replace("#", "%23"); // first answer attempt - doesn't work // newUrl = url.replace("#", "\\#"); return newUrl; } &lt;/script&gt; &lt;a href="#top" onclick="url = '\\\\MyUNCPath\\PropertyRushRefi-Add#1-ABCDEF.RTF'; window.open(escapePound(url)); return true;"&gt;Some Doc&lt;/a&gt; </code></pre> <p>URL that yells says "file://MyUNCPath/PropertyRushRefi-Add%25231-ABCDEF.RTF" cannot be found</p>
[ { "answer_id": 234002, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "\\#\n" }, { "answer_id": 234031, "author": "Rahul", "author_id": 16308, "author_profile": "https://Stackoverflow.com/users/16308", "pm_score": 4, "selected": true, "text": "window.open(\"http://your-url.com/\" + encodeURIComponent(\"foo#123.jpg\"));\n" }, { "answer_id": 234061, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 0, "selected": false, "text": "<a href=\"#top onclick=\"url = '\\\\\\\\MyUNCPath\\\\PropertyRushRefi-Add#1-ABCDEF.RTF'; window.open(url); return true;\">Some Doc</a>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18284/" ]
234,008
<p>I need to create at runtime instances of a class that uses generics, like <code>class&lt;T&gt;</code>, without knowing previously the type T they will have, I would like to do something like that:</p> <pre><code>public Dictionary&lt;Type, object&gt; GenerateLists(List&lt;Type&gt; types) { Dictionary&lt;Type, object&gt; lists = new Dictionary&lt;Type, object&gt;(); foreach (Type type in types) { lists.Add(type, new List&lt;type&gt;()); /* this new List&lt;type&gt;() doesn't work */ } return lists; } </code></pre> <p>...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?</p>
[ { "answer_id": 234016, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "public Dictionary<Type, object> GenerateLists(List<Type> types)\n{\n Dictionary<Type, object> lists = new Dictionary<Type, object>();\n\n foreach (Type type in types)\n {\n Type genericList = typeof(List<>).MakeGenericType(type);\n lists.Add(type, Activator.CreateInstance(genericList));\n }\n\n return lists;\n}\n" }, { "answer_id": 234082, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": " public Dictionary<Type, object> GenerateLists(List<Type> types)\n {\n Dictionary<Type, object> lists = new Dictionary<Type, object>();\n\n foreach (Type type in types)\n {\n if (!delegates.ContainsKey(type))\n delegates.Add(type, CreateListDelegate(type));\n lists.Add(type, delegates[type]());\n }\n\n return lists;\n }\n\n private Func<object> CreateListDelegate(Type type)\n {\n MethodInfo createListMethod = GetType().GetMethod(\"CreateList\");\n MethodInfo genericCreateListMethod = createListMethod.MakeGenericMethod(type);\n return Delegate.CreateDelegate(typeof(Func<object>), this, genericCreateListMethod) as Func<object>;\n }\n\n public object CreateList<T>()\n {\n return new List<T>();\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21668/" ]
234,024
<p>I have an array I've created in JavaScript. The end result comes out to element1,element2,,,element5,element6,,,element9.... etc</p> <p>Once passed to ColdFusion, it removes the null elements, I end up with element1,element2,element5,element6,element9</p> <p>I need to maintain these spaces, any ideas? My problem may begin before this, to explain in more detail...</p> <p>I have a form with 13 elements that are acting as a search/filter type function. I want to "post" with AJAX, in essence, i'm using a button to call a jQuery function and want to pass the fields to a ColdFusion page, then have the results passed back. The JavaScript array may not even be my best option.</p> <p>Any ideas?</p>
[ { "answer_id": 452284, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<cfset jsList = \"item1,item2,,item4,item5,,item6\">\n<cfset jsArray = jsList.split(\",\")>\n<cfdump var=\"#jsArray#\">\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
234,027
<p>How can I find the index in a string that matches a boost regex?</p>
[ { "answer_id": 234248, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 3, "selected": false, "text": "position match_results int find_match_offset(std::string const& string_to_search,\n boost::regex const& expression)\n{\n boost::smatch results;\n if(boost::regex_match(string_to_search,results,expression))\n {\n return results.position()\n }\n return -1;\n}\n" }, { "answer_id": 234277, "author": "Paolo Tedesco", "author_id": 15622, "author_profile": "https://Stackoverflow.com/users/15622", "pm_score": 4, "selected": true, "text": "void index(boost::regex& re,const std::string& input){\n boost::match_results<std::string::const_iterator> what;\n boost::match_flag_type flags = boost::match_default;\n std::string::const_iterator s = input.begin();\n std::string::const_iterator e = input.end();\n while (boost::regex_search(s,e,what,re,flags)){\n std::cout << what.position() << std::endl;\n std::string::difference_type l = what.length();\n std::string::difference_type p = what.position();\n s += p + l;\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
234,056
<p>Anyone got a ready made function that will take an XML string and return a correctly indented string?</p> <p>eg</p> <pre><code>&lt;XML&gt;&lt;TAG1&gt;A&lt;/TAG1&gt;&lt;TAG2&gt;&lt;Tag3&gt;&lt;/Tag3&gt;&lt;/TAG2&gt;&lt;/XML&gt; </code></pre> <p>and will return nicely formatted String in return after inserting linebreaks and tabs or spaces?</p>
[ { "answer_id": 234101, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "program TestIndentXML;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n OmniXML,\n OmniXMLUtils;\n\nfunction IndentXML(const xml: string): string;\nvar\n xmlDoc: IXMLDocument;\nbegin\n Result := '';\n xmlDoc := CreateXMLDoc;\n if not XMLLoadFromAnsiString(xmlDoc, xml) then\n Exit;\n Result := XMLSaveToAnsiString(xmlDoc, ofIndent);\nend;\n\nbegin\n Writeln(IndentXML('<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>'));\n Readln;\nend.\n" }, { "answer_id": 234105, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"xml\" indent=\"yes\" />\n <xsl:template match=\"/\">\n <xsl:copy-of select=\".\"/>\n </xsl:template>\n</xsl:stylesheet>\n" }, { "answer_id": 249291, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 2, "selected": false, "text": "function TForm1.DoTidy(const Source: string): string;\nvar\n Tidy : TLibTidy;\nbegin\n if not TidyGlobal.LoadTidyLibrary('libtidy.dll') then\n begin\n // Application.MessageBox('TidyLib is not available.', 'Error', 16);\n // exit;\n raise Exception.Create('Cannot load TidyLib.dll');\n end;\n Tidy := TLibTidy.Create(Self);\n try\n Tidy.LoadConfigFile(ExtractFilePath(Application.ExeName) +\n 'tidyconfig.txt');\n // Tidy.Configuration.IndentContent := tsYes;\n // Tidy.Configuration.IndentSpaces := 5;\n // Tidy.Configuration.UpperCaseTags := False;\n // Tidy.Configuration.NumEntities := True;\n // Tidy.Configuration.AccessibilityCheckLevel := 2;\n // Tidy.Configuration.InlineTags := 'foo,bar';\n // Tidy.Configuration.XmlDecl := True;\n // Tidy.Configuration.XmlTags := True;\n // Tidy.Configuration.CharEncoding := TidyUTF8;\n // Tidy.Configuration.WrapLen := 0;\n // Tidy.SaveConfigFile('tidyconfig.txt');\n Tidy.ParseString(Source);\n Result := Tidy.RunDiagnosticsAndRepair;\n finally\n Tidy.Free;\n end;\nend;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6244/" ]
234,059
<p>I have the following code:</p> <pre><code>MemoryStream foo(){ MemoryStream ms = new MemoryStream(); // write stuff to ms return ms; } void bar(){ MemoryStream ms2 = foo(); // do stuff with ms2 return; } </code></pre> <p>Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later? </p> <p>I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.</p>
[ { "answer_id": 234071, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 7, "selected": true, "text": "using bar() ms2" }, { "answer_id": 234080, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 3, "selected": false, "text": ".Dispose() Using .Dispose()" }, { "answer_id": 312299, "author": "Chris R. Donnelly", "author_id": 17152, "author_profile": "https://Stackoverflow.com/users/17152", "pm_score": 2, "selected": false, "text": "bar() using .Dispose() foo() return MemoryStream x = new MemoryStream();\ntry\n{\n // ... other code goes here ...\n return x;\n}\ncatch\n{\n // \"other code\" failed, dispose the stream before throwing out the Exception\n x.Dispose();\n throw;\n}\n" }, { "answer_id": 870605, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "MemoryStream foo()\n{ \n MemoryStream ms = new MemoryStream(); \n // write stuff to ms \n return ms;\n}\n Stream foo()\n{ \n ...\n}\n void bar()\n{ \n using (Stream s = foo())\n {\n // do stuff with s\n return;\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
234,064
<p>Using data binding, how do you bind a new object that uses value types? </p> <p>Simple example:</p> <pre><code>public class Person() { private string _firstName; private DateTime _birthdate; private int _favoriteNumber; //Properties } </code></pre> <p>If I create a new Person() and bind it to a form with text boxes. Birth Date displays as 01/01/0001 and Favorite Number as 0. These fields are required, but I would like these boxes to be empty and have the user fill them in.</p> <p>The solution also needs to be able to default fields. In our example, I may want the Favorite Number to default to 42.</p> <p>I'm specifically asking about Silverlight, but I assume WPF and WinForms probably have the same issue.</p> <p><b>EDIT:</b></p> <p>I thought of Nullable types, however we are currently using the same domain objects on client and server and I don't want to have required fields be Nullable. I'm hoping the databinding engine exposes a way to know it is binding a new object?</p>
[ { "answer_id": 234155, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 2, "selected": false, "text": "public class Person() {\n private string? _firstName;\n private DateTime? _birthdate;\n private int? _favoriteNumber;\n //Properties\n}\n public class Person() {\n private Nullable<string> _firstName;\n private Nullable<DateTime> _birthdate;\n private Nullable<int> _favoriteNumber;\n //Properties\n}\n" }, { "answer_id": 237273, "author": "Senkwe", "author_id": 6419, "author_profile": "https://Stackoverflow.com/users/6419", "pm_score": 0, "selected": false, "text": "public class Person\n {\n private int _favoriteNumber = 0;\n public string FavoriteNumber\n {\n get\n {\n return _favoriteNumber > 0 ? _favoriteNumber.ToString() : string.Empty;\n }\n set\n {\n _favoriteNumber = Convert.ToInt32(value);\n }\n }\n\n private DateTime _birthDate = DateTime.MinValue;\n private string BirthDate \n {\n get\n {\n return _birthDate == DateTime.MinValue ? string.Empty : _birthDate.ToString(); //or _birthDate.ToShortDateString() etc etc\n }\n set\n {\n _birthDate = DateTime.Parse(value);\n }\n }\n }\n" }, { "answer_id": 237419, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 1, "selected": false, "text": "public class DefaultValueToNullConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n object result = value;\n Type valueType = parameter as Type;\n\n if (value != null && valueType != null && value.Equals(defautValue(valueType)))\n {\n result = null;\n }\n\n return result;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n object result = value;\n Type valueType = parameter as Type;\n\n if (value == null && valueType != null )\n {\n result = defautValue(valueType);\n }\n return result;\n }\n\n private object defautValue(Type type)\n {\n object result = null;\n if (type == typeof(int))\n {\n result = 0;\n }\n else if (type == typeof(DateTime))\n {\n result = DateTime.MinValue;\n }\n return result;\n }\n}\n <Page.Resources>\n <local:DefaultValueToNullConverter x:Key=\"DefaultValueToNullConverter\"/>\n</Page.Resources>\n\n<TextBox \n Text=\"{Binding \n Path=BirthDate, \n Converter={StaticResource DefaultValueToNullConverter},\n ConverterParameter={x:Type sys:DateTime}}\" \n />\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4231/" ]
234,076
<p>I have a "Login" button that I want to be disabled until 3 text boxes on the same WPF form are populated with text (user, password, server). </p> <p>I have a backing object with a boolean property called IsLoginEnabled which returns True if and only if all 3 controls have data. However, when should I be checking this property? Should it be on the LostFocus event of each of the 3 dependent controls?</p> <p>Thanks!</p> <p>vg1890</p>
[ { "answer_id": 234158, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 2, "selected": true, "text": "IsLoginEnabled Public Event IsLoginEnabledChanged As EventHandler\n\nPublic Property User() As String\nGet.. ' snipped for brevity\nSet(ByVal value As String)\n mUser = value\n RaiseEvent IsLoginEnabledChanged(Me, New EventArgs())\nEnd Set\n\n' do the same in the Set for Password() and Server() properties\n [PropertyName]Changed IsLogonEnabledChanged" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
234,090
<p>How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:</p> <pre><code>&lt;input name = "deleteGameButton" type = "submit" value = "Delete" onclick = "submitToServlet('DeleteGameServlet');"&gt; </code></pre> <p>Here is the corresponding javascript:</p> <pre><code> function submitToServlet(newAction) { document.userGameForm.action = newAction; } </code></pre> <p>I'd like the servlet to have access to userBean</p> <pre><code> &lt;jsp:useBean id = "userBean" scope = "session" class = "org.project.User" /&gt; </code></pre>
[ { "answer_id": 234127, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 0, "selected": false, "text": "<jsp:useBean id = \"userBean\" scope = \"session\" class = \"org.project.User\"/>\n <jsp:setProperty name=\"beanName\" property=\"propertyname\" value=\"value\"/>\n</jsp:useBean>\n" }, { "answer_id": 234826, "author": "mtruesdell", "author_id": 6479, "author_profile": "https://Stackoverflow.com/users/6479", "pm_score": 2, "selected": false, "text": "<jsp:useBean id = \"userBean\" scope = \"session\" class = \"org.project.User\" /> User user = (User)request.getSession().getAttribute(\"userBean\");\n" }, { "answer_id": 5337181, "author": "Naveen kumar HR", "author_id": 664042, "author_profile": "https://Stackoverflow.com/users/664042", "pm_score": 1, "selected": false, "text": " getServletConfig().getServletContext().getRequestDispatcher(\"servlet path & name\"); \n dispatcher.forward (request, response);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25280/" ]
234,091
<p>We have a highly specialized DAL which sits over our DB. Our apps need to use this DAL to correctly operate against this DB.</p> <p>The generated DAL (which sits on some custom base classes) has various 'Rec' classes (Table1Rec, Table2Rec) each of which represents the record structure of a given table.</p> <p>Here is a sample Pseudo-class...</p> <pre><code>Public Class SomeTableRec Private mField1 As String Private mField1isNull As Boolean Private mField2 As Integer Private mField2isNull As Boolean Public Sub New() mField1isNull = True mField2isNull = True End Sub Public Property Field1() As String Get Return mField1 End Get Set(ByVal value As String) mField1 = value mField1isNull = False End Set End Property Public ReadOnly Property Field1isNull() As Boolean Get Return mField1isNull End Get End Property Public Property Field2() As Integer Get Return mField2 End Get Set(ByVal value As Integer) mField2 = value mField2isNull = False End Set End Property Public ReadOnly Property Field2isNull() As Boolean Get Return mField2isNull End Get End Property End Class </code></pre> <p>Each class has properties for each of the fields... Thus I can write...</p> <pre><code>Dim Rec as New Table1Rec Table1Rec.Field1 = "SomeString" Table2Rec.Field2 = 500 </code></pre> <p>Where a field can accept a NULL value, there is an additional property which indicates if the value is currently null.</p> <p>Thus....</p> <pre><code>Dim Rec as New Table1Rec Table1Rec.Field1 = "SomeString" If Table1Rec.Field1Null then ' This clearly is not true End If If Table1Rec.Field2Null then ' This will be true End If </code></pre> <p>This works because the constructor of the class sets all NULLproperties to True and the setting of any FieldProperty will cause the equivalent NullProperty to be set to false.</p> <p>I have recently had the need to expose my DAL over the web through a web service (which I of course intend to secure) and have discovered that while the structure of the 'Rec' class remains intact over the web... All logic is lost..</p> <p>If someone were to run the previous piece of code remotely they would notice that neither condition would prove true as there is no client side code which sets null to true.</p> <p><strong>I get the feeling I have architected this all wrong, but cannot see how I should improve it.</strong></p> <p><strong>What is the correct way to architect this?</strong></p>
[ { "answer_id": 614630, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 2, "selected": true, "text": "Imports System.Web\nImports System.Web.Services\nImports System.Web.Services.Protocols\n\n<WebService(Namespace:=\"http://tempuri.org/\")> _\n<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _\n<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _\nPublic Class Testing\n Inherits System.Web.Services.WebService\n\n <WebMethod()> _\n Public Function GetObjects() As Generic.List(Of TestObject)\n Dim list As New Generic.List(Of TestObject)\n list.Add(New TestObject(Nothing, \"Empty ID Object\"))\n list.Add(New TestObject(1, \"Full ID Object\"))\n list.Add(New TestObject(2, Nothing))\n Return list\n End Function\n\n Public Class TestObject\n Public Sub New()\n _name = String.Empty\n _id = Nothing\n End Sub\n Public Sub New(ByVal id As Nullable(Of Integer), ByVal name As String)\n _name = name\n _id = id\n End Sub\n Private _name As String\n Public Property Name() As String\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n End Set\n End Property\n\n Private _id As Nullable(Of Integer)\n Public Property ID() As Nullable(Of Integer)\n Get\n Return _id\n End Get\n Set(ByVal value As Nullable(Of Integer))\n _id = value\n End Set\n End Property\n End Class\n\nEnd Class\n <?xml version=\"1.0\" encoding=\"utf-8\" ?> \n<ArrayOfTestObject xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://tempuri.org/\">\n <TestObject>\n <Name>Empty ID Object</Name> \n <ID xsi:nil=\"true\" /> \n </TestObject>\n <TestObject>\n <Name>Full ID Object</Name> \n <ID>1</ID> \n </TestObject>\n <TestObject>\n <ID>2</ID> \n </TestObject>\n</ArrayOfTestObject>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
234,131
<p>I did this tests and the results seems the count function scale linearly. I have another function relying strongly in the efficiency to know if there are any data, so I would like to know how to replace this select count(*) with another more efficient (maybe constant?) query or data structure.</p> <blockquote> <p>psql -d testdb -U postgres -f truncate_and_insert_1000_rows.sql > NUL</p> <p>psql -d testdb -U postgres -f count_data.sql</p> </blockquote> <h2>--------------------------------------------------------------------------------</h2> <p>Aggregate (cost=36.75..36.76 rows=1 width=0) (actual time=0.762..0.763 rows=1 loops=1) -> Seq Scan on datos (cost=0.00..31.40 rows=2140 width=0) (actual time=0.02 8..0.468 rows=1000 loops=1) Total runtime: <strong>0.846 ms</strong> (3 filas)</p> <blockquote> <p>psql -d testdb -U postgres -f truncate_and_insert_10000_rows.sql > NUL</p> <p>psql -d testdb -U postgres -f count_data.sql</p> </blockquote> <h2>--------------------------------------------------------------------------------</h2> <p>Aggregate (cost=197.84..197.85 rows=1 width=0) (actual time=6.191..6.191 rows= 1 loops=1) -> Seq Scan on datos (cost=0.00..173.07 rows=9907 width=0) (actual time=0.0 09..3.407 rows=10000 loops=1) Total runtime: <strong>6.271 ms</strong> (3 filas)</p> <blockquote> <p>psql -d testdb -U postgres -f truncate_and_insert_100000_rows.sql > NUL</p> <p>psql -d testdb -U postgres -f count_data.sql</p> </blockquote> <h2>--------------------------------------------------------------------------------</h2> <p>Aggregate (cost=2051.60..2051.61 rows=1 width=0) (actual time=74.075..74.076 r ows=1 loops=1) -> Seq Scan on datos (cost=0.00..1788.48 rows=105248 width=0) (actual time= 0.032..46.024 rows=100000 loops=1) Total runtime: <strong>74.164 ms</strong> (3 filas)</p> <blockquote> <p>psql -d prueba -U postgres -f truncate_and_insert_1000000_rows.sql > NUL</p> <p>psql -d testdb -U postgres -f count_data.sql</p> </blockquote> <h2>--------------------------------------------------------------------------------</h2> <p>Aggregate (cost=19720.00..19720.01 rows=1 width=0) (actual time=637.486..637.4 87 rows=1 loops=1) -> Seq Scan on datos (cost=0.00..17246.60 rows=989360 width=0) (actual time =0.028..358.831 rows=1000000 loops=1) Total runtime: <strong>637.582 ms</strong> (3 filas)</p> <p>the definition of data is</p> <pre><code>CREATE TABLE data ( id INTEGER NOT NULL, text VARCHAR(100), CONSTRAINT pk3 PRIMARY KEY (id) ); </code></pre>
[ { "answer_id": 234561, "author": "Patryk Kordylewski", "author_id": 30927, "author_profile": "https://Stackoverflow.com/users/30927", "pm_score": 2, "selected": false, "text": "SELECT t.primary_key IS NOT NULL FROM table t LIMIT 1;\n" }, { "answer_id": 1691576, "author": "Michael Buen", "author_id": 11432, "author_profile": "https://Stackoverflow.com/users/11432", "pm_score": 3, "selected": false, "text": "select exists(select * from your_table_here) as has_row\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
234,171
<p>I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of <a href="http://msdn.microsoft.com/en-us/library/ms776293(VS.85).aspx" rel="nofollow noreferrer">GetDateFormat()</a>.</p>
[ { "answer_id": 234183, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": true, "text": "sscanf SYSTEMTIME" }, { "answer_id": 234202, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 2, "selected": false, "text": "COleDateTime::ParseDateTime" }, { "answer_id": 234213, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 0, "selected": false, "text": "bool kGUIDate::Setz(const char *datestring)\n /* formats excepted are: */\n/* yyyy-mm-dd */\n/* Wdy, DD-Mon-YY HH:MM:SS GMT */\n/* Wdy, D Mon YY HH:MM:SS GMT */\n" }, { "answer_id": 234223, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "strptime()" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3857/" ]
234,177
<p>As usual, some background information first:</p> <p>Database A (Access database) - Holds a table that has information I need from only two columns. The information from these two columns is needed for an application that will be used by people that cannot access database A.</p> <p>Database B (Access database) - Holds a table that contains only two columns (mirrors to what we need from table A). Database B is accessible to all users of the application. One issue is that on of the column names is not the same as it is in the table from Database A.</p> <p>What I need to do is transfer the necessary data via a utility that will run automatically, say once a week (the two databases don't need to be totally in sync, just close). The transfer utility will be run from a user account that has access to both databases (obviously).</p> <p>Here's the approach I've taken (again if there is a better way, please suggest away):</p> <ol> <li><p>Grab the data from database A. It is only the two columns from the necessary table.</p></li> <li><p>Write the data out to [tablename].txt file using a DataReader object and WriterStream object. I've done this so I can use a schema.ini file and force the data columns to have the same name as they will be in Database B.</p></li> <li><p>Create a DataSet object, containing a DataTable that mirrors the table from Database B.</p></li> <li><p>Suck the information from the .txt file into the DataTable using the Microsoft.Jet.OLEDB.4.0 provider with extended properties of text, hdr=yes and fmt=delimited (to match how I have the schema.ini file setup and the .txt file setup). I'm using a DataAdapter to fill the DataTable.</p></li> <li><p>Create another DataSet object, containing a DataTable that mirrors the table from Database B. </p></li> <li><p>Suck in the information from Database B so that it contains all the current data found in the table that needs to be updated from Database A. Again I'm using a DataAdapter to fill this DataTable (a different one from Step 5, since they are both using different data sources).</p></li> <li><p>Merge the DataTable that holds the data from Database A (or the .txt file, technically).</p></li> <li><p>Update Database B's table with the changes.</p></li> </ol> <p>I've written update, delete and insert commands manually for the DataAdapter that is repsonsible for talking to Database B. However, this logic is never used because the DataSet-From-Database-B.Merge(Dataset-From-TxtFile[tableName]) doesn't flip the HasChanges flag. This means the DataSet-From-Database-B.Update doesn't fire any of the commands.</p> <p>So is there any way I can get the data from DataSet-From-TxtFile to merge and apply to Database B using the method I'm using? Am I missing a crucial step here?</p> <p>I know I could always delete all the records from Database B's table and then just insert all the records from the text file (even if I had to loop through each record in the DataSet and apply row.SetAdded to ensure it triggers the HasChanges flag), but I'd rather have it apply ONLY the changes each time.</p> <p>I'm using c# and the 2.0 Framework (which I realize means I can use DataTables and TableAdapters instead of DataSets and DataAdapters since I'm only dealing with a single table, but anyway).</p> <p>TIA</p>
[ { "answer_id": 234415, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "DataTable A = load table from A\nDataTable B = load table from B\n\nforeach row in A\n col1 = row[col1]\n col2 = row[col2]\n matchRow = B.select( \"col1 = \" + col1 + \" and col2 = \" + col2)\n if not matchRow exists\n add new row to B with col1,col2\n end\nend\n\nforeach row in B\n col1 = row[col1]\n col2 = row[col2]\n matchRow = A.select( \"col1 = \" + col1 + \" and col2 = \" + col2)\n if not matchRow exists\n remove row from B\n end\nend\n\nupdate B\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9732/" ]
234,181
<p>I have a sorted collection of objects (it can be either SortedList or SortedDictionary, I will use it mainly for reading so add performance is not that important). How can I get the i-th value?</p> <p>So e.g. when I have numbers 1, 2, 3, 4, 5 in the collection and I want the median (so 3 in this example), how can I do it?</p>
[ { "answer_id": 234259, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 5, "selected": false, "text": "list.Values[index] \n dict.ElementAt(index).Value\n" }, { "answer_id": 42473025, "author": "mudrak patel", "author_id": 6452486, "author_profile": "https://Stackoverflow.com/users/6452486", "pm_score": 3, "selected": false, "text": "sortedDictionaryName.ElementAt(index);\n sortedDictionaryName.ElementAt(index).Key //For only Key\nsortedDictionaryName.ElementAt(index).Value //For only Value\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ]
234,210
<p>I'm trying to write a web application using SpringMVC. Normally I'd just map some made-up file extension to Spring's front controller and live happily, but this time I'm going for REST-like URLs, with no file-name extensions.</p> <p>Mapping everything under my context path to the front controller (let's call it "<strong>app</strong>") means I should take care of static files also, something I'd rather not do (why reinvent yet another weel?), so some combination with tomcat's default servlet (let's call it "<strong>tomcat</strong>") appears to be the way to go.</p> <p>I got the thing to work doing something like </p> <pre class="lang-xml prettyprint-override"><code>&lt;servlet-mapping&gt; &lt;servlet-name&gt;app&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;tomcat&lt;/servlet-name&gt; &lt;url-pattern&gt;*.ext&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>and repeating the latter for each one of the file extensions of my static content. I'm just wondering why the following setups, which to me are equivalent to the one above, don't work.</p> <pre class="lang-xml prettyprint-override"><code>&lt;!-- failed attempt #1 --&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;app&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;tomcat&lt;/servlet-name&gt; &lt;url-pattern&gt;*.ext&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- failed attempt #2 --&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;app&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;tomcat&lt;/servlet-name&gt; &lt;url-pattern&gt;/some-static-content-folder/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>Can anyone shed some light?</p>
[ { "answer_id": 245143, "author": "Philip Tinney", "author_id": 14930, "author_profile": "https://Stackoverflow.com/users/14930", "pm_score": 6, "selected": true, "text": "/some-static-content-folder/ test.png /some-static-content-folder/test.png\n /some-static-content-folder/some-static-content-folder/test.png\n" }, { "answer_id": 26670813, "author": "PragmaCoder", "author_id": 231896, "author_profile": "https://Stackoverflow.com/users/231896", "pm_score": 2, "selected": false, "text": "<!-- Correct for Tomcat >= 6.0.29 or other Servlet containers -->\n<servlet-mapping>\n <servlet-name>app</servlet-name>\n <url-pattern>/</url-pattern>\n</servlet-mapping>\n\n<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>/some-static-content-folder/*</url-pattern>\n</servlet-mapping>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
234,215
<p>I am creating a WordML document from an xml file whose elements sometimes contain html-formatted text. </p> <pre><code>&lt;w:p&gt; &lt;w:r&gt; &lt;w:t&gt; html formatted content is in here taken from xml file! &lt;/w:t&gt; &lt;/w:r&gt; &lt;/w:p&gt; </code></pre> <p>This is how my templates are sort of set up. I have a recursive call-template function that does text replacement against the source xml content. When it comes across a "<code>&lt;b&gt;</code>" tag, I output a string in CDATA containing "<code>&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:r&gt;&lt;w:rPr&gt;&lt;w:b/&gt;&lt;/w:rPr&gt;&lt;w:t&gt;</code>" to close the current run and start up a new run with bold formatting enabled. when it gets to a "<code>&lt;/b&gt;</code>" tag, it replaces it with the following CDATA string "<code>&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:r&gt;&lt;w:t&gt;</code>".</p> <p>What I'd like to do is use XSL to close the run tag and start a new run without using CDATA string inserts. Is this possible?</p>
[ { "answer_id": 239235, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 0, "selected": false, "text": "b w:t w:r <doc xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n<w:p>\n <w:r>\n <w:t>before<b>bold</b>after</w:t>\n </w:r>\n</w:p>\n</doc>\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n\n<xsl:template match=\"/doc/w:p/w:r/w:t//b\">\n <xsl:value-of select=\"'&lt;/w:t>&lt;/w:r>&lt;w:r>&lt;w:rPr>&lt;w:b/>&lt;/w:rPr>&lt;w:t>'\" disable-output-escaping=\"yes\" />\n <xsl:apply-templates select=\"@*|node()\"/>\n <xsl:value-of select=\"'&lt;/w:t>&lt;/w:r>&lt;w:r>&lt;w:t>'\" disable-output-escaping=\"yes\" />\n</xsl:template>\n xalan input.xml convert_html.xsl\n <?xml version=\"1.0\" encoding=\"UTF-8\"?><doc xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n<w:p>\n <w:r>\n <w:t>before</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>bold</w:t></w:r><w:r><w:t>after</w:t>\n </w:r>\n</w:p>\n</doc>\n" }, { "answer_id": 240076, "author": "Andrew Cowenhoven", "author_id": 12281, "author_profile": "https://Stackoverflow.com/users/12281", "pm_score": 0, "selected": false, "text": "<text>\n <para>\n Test for paragraph 1\n </para>\n <para>\n Test for <b>paragraph 2</b>\n </para>\n</text>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:w=\"http://foo\">\n<xsl:template match=\"/\">\n <w:p>\n <w:r>\n <xsl:apply-templates/>\n </w:r> \n </w:p>\n</xsl:template>\n <xsl:template match=\"para\">\n <w:t>\n <xsl:apply-templates/>\n </w:t>\n </xsl:template>\n\n <xsl:template match=\"b\">\n <w:rPr>\n <w:b/>\n </w:rPr>\n <xsl:value-of select=\".\"/>\n </xsl:template>\n</xsl:stylesheet> \n <w:p xmlns:w=\"http://foo\">\n <w:r>\n <w:t>\n Test for paragraph 1\n </w:t>\n <w:t>\n Test for <w:rPr><w:b /></w:rPr>paragraph 2\n </w:t>\n </w:r>\n</w:p>\n" }, { "answer_id": 251078, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 2, "selected": false, "text": " <xsl:template match=\"text()\" priority=\"1\">\n <w:r>\n <w:t>\n <xsl:value-of select=\".\"/>\n </w:t>\n </w:r> \n </xsl:template>\n\n <xsl:template match=\"@*|node()\">\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:template>\n\n <xsl:template match=\"para\">\n <w:p>\n <xsl:apply-templates select=\"text() | *\" />\n </w:p>\n </xsl:template>\n\n <xsl:template match=\"b\">\n <w:r>\n <w:rPr>\n <w:b />\n </w:rPr>\n <w:t><xsl:apply-templates /></w:t>\n </w:r>\n </xsl:template>\n" }, { "answer_id": 1189335, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<xsl:template match=\"Body\"><xsl:apply-templates select=\"p\"/></xsl:template>\n\n<xsl:template match=\"text()\" priority=\"1\"><w:r><w:t><xsl:value-of select=\".\"/></w:t></w:r></xsl:template>\n\n<xsl:template match=\"@*|node()\"><xsl:apply-templates select=\"@*|node()\"/></xsl:template>\n\n<xsl:template match=\"p\"><w:p><xsl:apply-templates select=\"text() | *\" /></w:p></xsl:template>\n\n<xsl:template match=\"b\"><w:r><w:rPr><w:b /></w:rPr><xsl:apply-templates /></w:r></xsl:template>\n<xsl:template match=\"i\"><w:r><w:rPr><w:i /></w:rPr><xsl:apply-templates /></w:r></xsl:template>\n<xsl:template match=\"u\"><w:r><w:rPr><w:u w:val=\"single\" /></w:rPr><xsl:apply-templates /></w:r></xsl:template>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31229/" ]
234,217
<p><strong>Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET.</strong> That being said...</p> <p>I would like to allow the user to enter any equation, like the following, into a text box:</p> <pre><code>x = x / 2 * 0.07914 x = x^2 / 5 </code></pre> <p>And have that equation applied to incoming data points. The incoming data points are represented by <strong>x</strong> and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:</p> <pre><code>float ApplyEquation (string equation, float dataPoint) { // parse the equation string and figure out how to do the math // lots of messy code here... } </code></pre> <p>When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:</p> <pre><code>FunctionPointer foo = ConvertEquationToCode(equation); .... x = foo(x); // I could then apply the equation to my incoming data like this </code></pre> <p>Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.</p> <p>The app would basically be writing new code at run time. Is this possible with .NET?</p>
[ { "answer_id": 234236, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "ConvertEquationToCode" }, { "answer_id": 234303, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": false, "text": "MathEvaluator eval = new MathEvaluator();\n//basic math\ndouble result = eval.Evaluate(\"(2 + 1) * (1 + 2)\");\n//calling a function\nresult = eval.Evaluate(\"sqrt(4)\");\n//evaluate trigonometric \nresult = eval.Evaluate(\"cos(pi * 45 / 180.0)\");\n//convert inches to feet\nresult = eval.Evaluate(\"12 [in->ft]\");\n//use variable\nresult = eval.Evaluate(\"answer * 10\");\n//add variable\neval.Variables.Add(\"x\", 10); \nresult = eval.Evaluate(\"x * 10\");\n" }, { "answer_id": 234698, "author": "baretta", "author_id": 30052, "author_profile": "https://Stackoverflow.com/users/30052", "pm_score": 3, "selected": false, "text": "static object Evaluate ( string xp )\n{\n return _nav.Evaluate ( xp );\n}\nstatic readonly System.Xml.XPath.XPathNavigator _nav\n = new System.Xml.XPath.XPathDocument (\n new StringReader ( \"<r/>\" ) ).CreateNavigator ( );\n <context>\n <x>2.151</x>\n <y>231.2</y>\n</context>\n object result = Evaluate ( \"my:func(234) * $myvar\" );\n" }, { "answer_id": 375737, "author": "pyon", "author_id": 46571, "author_profile": "https://Stackoverflow.com/users/46571", "pm_score": -1, "selected": false, "text": "ConvertEquationToCode" }, { "answer_id": 2196645, "author": "Hannoun Yassir", "author_id": 72443, "author_profile": "https://Stackoverflow.com/users/72443", "pm_score": -1, "selected": false, "text": "system.CodeDom" }, { "answer_id": 7013086, "author": "GreyCloud", "author_id": 397268, "author_profile": "https://Stackoverflow.com/users/397268", "pm_score": 2, "selected": false, "text": "Expression e = new Expression(\"Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)\"); \n\n e.Parameters[\"Pi2\"] = new Expression(\"Pi * Pi\"); \n e.Parameters[\"X\"] = 10; \n\n e.EvaluateParameter += delegate(string name, ParameterArgs args) \n { \n if (name == \"Pi\") \n args.Result = 3.14; \n }; \n\n Debug.Assert(117.07 == e.Evaluate()); \n" }, { "answer_id": 10457244, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 5, "selected": true, "text": "using Microsoft.CSharp;\nusing System;\nusing System.CodeDom.Compiler;\nusing System.Reflection;\n\nnamespace RuntimeCompilationTest {\n class Program\n {\n static void Main(string[] args) {\n string sourceCode = @\"\n public class SomeClass {\n public int Add42 (int parameter) {\n return parameter += 42;\n }\n }\";\n var compParms = new CompilerParameters{\n GenerateExecutable = false, \n GenerateInMemory = true\n };\n var csProvider = new CSharpCodeProvider();\n CompilerResults compilerResults = \n csProvider.CompileAssemblyFromSource(compParms, sourceCode);\n object typeInstance = \n compilerResults.CompiledAssembly.CreateInstance(\"SomeClass\");\n MethodInfo mi = typeInstance.GetType().GetMethod(\"Add42\");\n int methodOutput = \n (int)mi.Invoke(typeInstance, new object[] { 1 }); \n Console.WriteLine(methodOutput);\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 50430964, "author": "Kent", "author_id": 1583763, "author_profile": "https://Stackoverflow.com/users/1583763", "pm_score": 1, "selected": false, "text": " string sExpression = \"(a == 0) ? 5 : 10\";\n ExpressionEvaluator<int> exec = new ExpressionEvaluator<int>(sExpression);\n exec.AddParameter(\"a\", 0);\n int n0 = exec.Invoke();\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
234,231
<p>How do you create an application shortcut (.lnk file) in C# or using the .NET framework?</p> <p>The result would be a .lnk file to the specified application or URL.</p>
[ { "answer_id": 234543, "author": "Charley Rathkopf", "author_id": 10119, "author_profile": "https://Stackoverflow.com/users/10119", "pm_score": 7, "selected": true, "text": "private static void configStep_addShortcutToStartupGroup()\n{\n using (ShellLink shortcut = new ShellLink())\n {\n shortcut.Target = Application.ExecutablePath;\n shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);\n shortcut.Description = \"My Shorcut Name Here\";\n shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;\n shortcut.Save(STARTUP_SHORTCUT_FILEPATH);\n }\n}\n" }, { "answer_id": 2736786, "author": "Anuraj", "author_id": 38024, "author_profile": "https://Stackoverflow.com/users/38024", "pm_score": 4, "selected": false, "text": "private void appShortcutToDesktop(string linkName)\n{\n string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);\n\n using (StreamWriter writer = new StreamWriter(deskDir + \"\\\\\" + linkName + \".url\"))\n {\n string app = System.Reflection.Assembly.GetExecutingAssembly().Location;\n writer.WriteLine(\"[InternetShortcut]\");\n writer.WriteLine(\"URL=file:///\" + app);\n writer.WriteLine(\"IconIndex=0\");\n string icon = app.Replace('\\\\', '/');\n writer.WriteLine(\"IconFile=\" + icon);\n writer.Flush();\n }\n}\n" }, { "answer_id": 19914018, "author": "IS4", "author_id": 1424244, "author_profile": "https://Stackoverflow.com/users/1424244", "pm_score": 6, "selected": false, "text": "Type t = Type.GetTypeFromCLSID(new Guid(\"72C24DD5-D70A-438B-8A42-98424B88AFB8\")); //Windows Script Host Shell Object\ndynamic shell = Activator.CreateInstance(t);\ntry{\n var lnk = shell.CreateShortcut(\"sc.lnk\");\n try{\n lnk.TargetPath = @\"C:\\something\";\n lnk.IconLocation = \"shell32.dll, 1\";\n lnk.Save();\n }finally{\n Marshal.FinalReleaseComObject(lnk);\n }\n}finally{\n Marshal.FinalReleaseComObject(shell);\n}\n Type t = Type.GetTypeFromCLSID(new Guid(\"72C24DD5-D70A-438B-8A42-98424B88AFB8\")); //Windows Script Host Shell Object\nobject shell = Activator.CreateInstance(t);\ntry{\n object lnk = t.InvokeMember(\"CreateShortcut\", BindingFlags.InvokeMethod, null, shell, new object[]{\"sc.lnk\"});\n try{\n t.InvokeMember(\"TargetPath\", BindingFlags.SetProperty, null, lnk, new object[]{@\"C:\\whatever\"});\n t.InvokeMember(\"IconLocation\", BindingFlags.SetProperty, null, lnk, new object[]{\"shell32.dll, 5\"});\n t.InvokeMember(\"Save\", BindingFlags.InvokeMethod, null, lnk, null);\n }finally{\n Marshal.FinalReleaseComObject(lnk);\n }\n}finally{\n Marshal.FinalReleaseComObject(shell);\n}\n" }, { "answer_id": 20695964, "author": "AZ_", "author_id": 185022, "author_profile": "https://Stackoverflow.com/users/185022", "pm_score": 1, "selected": false, "text": "IWshRuntimeLibrary private void createShortcutOnDesktop(String executablePath)\n{\n // Create a new instance of WshShellClass\n\n WshShell lib = new WshShellClass();\n // Create the shortcut\n\n IWshRuntimeLibrary.IWshShortcut MyShortcut;\n\n\n // Choose the path for the shortcut\n string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);\n MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+\"\\\\AZ.lnk\");\n\n\n // Where the shortcut should point to\n\n //MyShortcut.TargetPath = Application.ExecutablePath;\n MyShortcut.TargetPath = @executablePath;\n\n\n // Description for the shortcut\n\n MyShortcut.Description = \"Launch AZ Client\";\n\n StreamWriter writer = new StreamWriter(@\"D:\\AZ\\logo.ico\");\n Properties.Resources.system.Save(writer.BaseStream);\n writer.Flush();\n writer.Close();\n // Location for the shortcut's icon \n\n MyShortcut.IconLocation = @\"D:\\AZ\\logo.ico\";\n\n\n // Create the shortcut at the given path\n\n MyShortcut.Save();\n\n}\n" }, { "answer_id": 23848146, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 1, "selected": false, "text": "//Create new shortcut\nusing (var shellShortcut = new ShellShortcut(newShortcutPath)\n{\n Path = path\n WorkingDirectory = workingDir,\n Arguments = args,\n IconPath = iconPath,\n IconIndex = iconIndex,\n Description = description,\n})\n{\n shellShortcut.Save();\n}\n\n//Read existing shortcut\nusing (var shellShortcut = new ShellShortcut(existingShortcut))\n{\n path = shellShortcut.Path;\n args = shellShortcut.Arguments;\n workingDir = shellShortcut.WorkingDirectory;\n ...\n}\n" }, { "answer_id": 28417360, "author": "Steven Jeuris", "author_id": 590790, "author_profile": "https://Stackoverflow.com/users/590790", "pm_score": 0, "selected": false, "text": "References->Add Reference... COM->Type Libraries IWshRuntimeLibrary WshShell shell = new WshShell();\nIWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);\nlink.TargetPath=TargetPathName;\nlink.Save();\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10119/" ]
234,233
<p>I have two machines... a development machine and a production machine. When I first brought my rails app onto the production server, I had no problem. I simply imported schema.rb by running rake db:schema:load RAILS_ENV=production. All was well.</p> <p>So, then on my development machine, I made some more changes and another migration, and then copy the new application over to the production machine. I then tried to update the database by running rake db:migrate RAILS_ENV=production. I get the following error: "There is already an object named 'schema_migrations' in the database."</p> <p>I'm thinking to myself, ya no kidding Rake... you created it! I ran trace on rake and it seems as if rake thinks it's the first time it's ever ran. However, by analyzing my 'schema_migrations' table on my development machine and my production machine you can see that there is a difference of one migration, namely the one that I want to migrate.</p> <p>I have also tried to explicitly define the version number, but that doesn't work either.</p> <p>Any ideas on how I can bring my production server up to date?</p> <p><strong>Update:</strong></p> <p>Let me start off by saying that I can't just 'drop' the database. It's a production server with a little over 100k records already in it. What happens if a similar problem occurs in the future? Am, I to just drop the table every time a database problem occurs? It might work this time, but it doesn't seem like a practical long term solution to every database problem. I doubt the problem I'm having now is unique to me.</p> <ol> <li><p>It sounds like the 'schema_info' table and the 'schema_migrations' table are the same. In my setup, I only have 'schema_migrations'. As stated previously, the difference between the 'schema_migrations' table on the production server and the development machine is just one record. That is, the record containing the version number of the change I want to migrate.</p></li> <li><p>From the book I read, 'Simply Rails 2', it states that when first moving to a production server, instead of running rake db:migrate, one should just run rake:db:schema:load.</p></li> <li><p>If it matters, I'm using Rails version 2.1.</p></li> </ol>
[ { "answer_id": 235845, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": -1, "selected": false, "text": "rake db:migrate RAILS_ENV=production\n db:schema:load" }, { "answer_id": 241846, "author": "Brad", "author_id": 31352, "author_profile": "https://Stackoverflow.com/users/31352", "pm_score": 1, "selected": false, "text": "ActiveRecord::Base.connection.execute(\"INSERT schema_migrations (version) VALUES(#{my version number that production is supposedly on})\") ActiveRecord::Base.connection.execute(\"DROP TABLE schema_migrations\") rake db:migrate RAILS_ENV=production MyMigrationClass.up" }, { "answer_id": 707295, "author": "Marc L", "author_id": 79144, "author_profile": "https://Stackoverflow.com/users/79144", "pm_score": 1, "selected": false, "text": "rake db:migrate RAILS_ENV=production\n RAILS_ENV=production rake db:migrate\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
234,239
<p>C# .NET 3.5. I'm trying to understand the intrinsic limitation of the C# Action object. Within the lamda (are those, in fact, lamdas?), we can perform assignments, call functions, even execute a ternary operation, but we can't execute a multi-statement operation.</p> <p>Is this because the single-statement execution is just syntactic sugar for wrapping it in a delegate? Why does the first example below not work?</p> <pre><code>public class MyClass { private int m_Count = 0; public void Test() { int value = 0; // Does not work, throws compile error Action action = () =&gt; { if(m_Count &lt; 10) m_Count++; value = m_Count; } // Works Action action2 = () =&gt; value = delegate(){ if(m_Count &lt; 10) m_Count++; return m_Count; }; // Works Action action3 = () =&gt; value = m_Count; // Works Action action4 = () =&gt; value = m_Count &lt; 10 ? m_Count++ : 0; // Works Action action5 = () =&gt; value = Increment(); } public int Increment() { if (m_Count &lt; 10) m_Count++; return m_Count; } } </code></pre> <p>EDIT: Grr, sorry for the noise. Originally, I had </p> <pre><code>Action action = () =&gt; if(m_Count &lt; 10) m_Count++; value = m_Count; </code></pre> <p>Which threw a compile error, but then right before the post I thought I'd try wrapping it in braces</p> <pre><code>Action action = () =&gt; { if(m_Count &lt; 10) m_Count++; value = m_Count; } </code></pre> <p>Which also threw a compile error, so I jumped to conclusions that it was the same problem. It works, though, if I toss in a semi-colon after the braces</p> <pre><code>Action action = () =&gt; { if(m_Count &lt; 10) m_Count++; value = m_Count; }; </code></pre> <p>Sorry for the noise!</p> <p>EDIT 2: Thanks cfeduke, you posted that at the same time as my edit above - went ahead and marked as answer. </p>
[ { "answer_id": 234266, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 5, "selected": true, "text": " Action action = () => { if (m_Count < 10) m_Count++; value = m_Count; };\n type name = statement;" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
234,241
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo">Reference: Comparing PHP&#39;s print and echo</a> </p> </blockquote> <p>Is there any major and fundamental difference between these two functions in PHP?</p>
[ { "answer_id": 234255, "author": "dl__", "author_id": 28565, "author_profile": "https://Stackoverflow.com/users/28565", "pm_score": 9, "selected": true, "text": "print() $ret = print \"Hello World\" $ret 1 $b ? print \"true\" : print \"false\";\n , AND OR XOR echo expression [, expression[,\nexpression] ... ] echo ( expression, expression ) echo (\"howdy\"),(\"partner\") echo\n\"howdy\",\"partner\" echo \"and a \", 1, 2, 3; // comma-separated without parentheses\n echo (\"and a 123\"); // just one parameter with parentheses\n print() print (\"and a 123\");\n print \"and a 123\";\n" }, { "answer_id": 234258, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "echo echo 'foo', 'bar'; // Concatenates the 2 strings\nprint('foo', 'bar'); // Fatal error\n print echo $res = print('test');\nvar_dump($res); //bool(true)\n" }, { "answer_id": 447548, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "$count = 5;\n\nprint \"This is \" . $count . \" values in \" . $count/5 . \" parameter\";\n" }, { "answer_id": 663347, "author": "grilix", "author_id": 74814, "author_profile": "https://Stackoverflow.com/users/74814", "pm_score": 3, "selected": false, "text": "print() echo print() echo 'Doing some stuff... ';\n foo() and print(\"ok.\\n\") or print(\"error: \" . getError() . \".\\n\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
234,249
<p>I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".</p> <p>I've written the following test program</p> <pre><code>public static void main(String[] args) { Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z"); boolean one = fileExtensionPattern.matcher("foo.bar").matches(); boolean two = fileExtensionPattern.matcher("foo.b").matches(); boolean three = fileExtensionPattern.matcher("foo.").matches(); boolean four = fileExtensionPattern.matcher("foo").matches(); System.out.println(one + " " + two + " " + three + " " + four); } </code></pre> <p>I expect this to print "true true false false", but instead it prints false for all 4 cases. Where am I going wrong?</p> <p>Cheers, Don</p>
[ { "answer_id": 234283, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": true, "text": ".* \\\\Z" }, { "answer_id": 234427, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "public boolean isFilename(String filename) {\n int i=filename.lastInstanceOf(\".\");\n return(i != -1 && i != filename.length - 1)\n}\n" }, { "answer_id": 11826665, "author": "hanisa", "author_id": 1578951, "author_profile": "https://Stackoverflow.com/users/1578951", "pm_score": 0, "selected": false, "text": "package regularexpression;\n\nimport java.io.File;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegularFile {\n public static void main(String[] args) {\n new RegularFile();\n }\n\n public RegularFile() {\n\n String fileName = null;\n boolean bName = false;\n int iCount = 0;\n File dir = new File(\"C:/regularfolder\");\n File[] files = dir.listFiles();\n System.out.println(\"List Of Files ::\");\n\n for (File f : files) {\n\n fileName = f.getName();\n System.out.println(fileName);\n\n Pattern uName = Pattern.compile(\".*l.zip.*\");\n Matcher mUname = uName.matcher(fileName);\n bName = mUname.matches();\n if (bName) {\n iCount++;\n\n }\n }\n System.out.println(\"File Count In Folder ::\" + iCount);\n\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
234,265
<p>I'm using Chris Pederick's Firefox addon <a href="http://chrispederick.com/work/web-developer/" rel="nofollow noreferrer">"Web Developer 1.1.6"</a>. I get this warning when hitting a certain web page on my site: </p> <blockquote> <p>Unknown property 'MozOpacity'. Declaration dropped.</p> </blockquote> <p>What does this mean and how can I fix this on my site?</p>
[ { "answer_id": 234271, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 1, "selected": false, "text": "mozopacity -moz-opacity" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8088/" ]