qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
137,314
<p>I've got a CAkePHP 1.2 site. I've got three related Models/tables: A Comment has exactly one Touch, a Touch has exactly one Touchtype.</p> <p>In each model, I have a belongs to, so I have Comments belongs to Touch, Touch belongs to Touchtype.</p> <p>I'm trying to get a list of comments that includes information about the touch stored in the touchtype table. </p> <pre><code>$this-&gt;Comment-&gt;find(...) </code></pre> <p>I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help.</p>
[ { "answer_id": 137323, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 5, "selected": true, "text": "cut -b 1-LIMIT\n" }, { "answer_id": 137642, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 2, "selected": false, "text": "$ perl -pe's/(?<=.{25}).*//' filename\n" }, { "answer_id": 138192, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "perl -wlne'print substr($_,0,80)'\n perl -nE'say/(.{0,80})/'\n" }, { "answer_id": 141112, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 0, "selected": false, "text": "typeset -L70 line\nwhile read line\ndo\n print $line\ndone\n" }, { "answer_id": 142098, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 0, "selected": false, "text": "#! /usr/bin/perl -w\n\nuse strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n" }, { "answer_id": 848356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "use strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n" }, { "answer_id": 12899735, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 0, "selected": false, "text": "$ cat file\nthe quick brown fox jumped over the lazy dog's back\n\n$ fold -w20 file\nthe quick brown fox\njumped over the lazy\n dog's back\n\n$ fold -w10 file\nthe quick\nbrown fox\njumped ove\nr the lazy\n dog's bac\nk\n\n$ fold -s -w10 file\nthe quick\nbrown fox\njumped\nover the\nlazy\ndog's back\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43/" ]
137,326
<p>How do you embed a SWF file in an HTML page?</p>
[ { "answer_id": 137332, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 7, "selected": false, "text": "<object width=\"100\" height=\"100\">\n <param name=\"movie\" value=\"file.swf\">\n <embed src=\"file.swf\" width=\"100\" height=\"100\">\n </embed>\n</object>\n" }, { "answer_id": 137349, "author": "Ronnie Liew", "author_id": 1987, "author_profile": "https://Stackoverflow.com/users/1987", "pm_score": 8, "selected": true, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n <head>\n <title>SWFObject dynamic embed - step 3</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n <script type=\"text/javascript\" src=\"swfobject.js\"></script>\n\n <script type=\"text/javascript\">\n swfobject.embedSWF(\"myContent.swf\", \"myContent\", \"300\", \"120\", \"9.0.0\");\n </script>\n\n </head>\n <body>\n <div id=\"myContent\">\n <p>Alternative content</p>\n </div>\n </body>\n</html>\n" }, { "answer_id": 142304, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 3, "selected": false, "text": "<noscript/>" }, { "answer_id": 12847276, "author": "Spooky", "author_id": 1739270, "author_profile": "https://Stackoverflow.com/users/1739270", "pm_score": 3, "selected": false, "text": "<object type=\"application/x-shockwave-flash\" data=\"http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01\" \nstyle=\"width:640px;height:480px;margin:10px 36px;\">\n\n<param name=\"movie\" value=\"http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01\" />\n<param name=\"allowfullscreen\" value=\"true\" />\n<param name=\"allowscriptaccess\" value=\"always\" />\n<param name=\"wmode\" value=\"opaque\" />\n<param name=\"quality\" value=\"high\" />\n<param name=\"menu\" value=\"false\" />\n\n</object>\n" }, { "answer_id": 12847491, "author": "Spooky", "author_id": 1739270, "author_profile": "https://Stackoverflow.com/users/1739270", "pm_score": 4, "selected": false, "text": "<object type=\"application/x-shockwave-flash\" data=\"/dir/application.swf\" \nid=\"applicationID\" style=\"margin:0 10px;width:auto;height:auto;\">\n\n<param name=\"movie\" value=\"/dir/application.swf\" />\n<param name=\"wmode\" value=\"transparent\" /> <!-- Or opaque, etc. -->\n\n<!-- ↓ Required paramter or not, depends on application -->\n<param name=\"FlashVars\" value=\"\" />\n\n<param name=\"quality\" value=\"high\" />\n<param name=\"menu\" value=\"false\" />\n\n</object>\n" }, { "answer_id": 20752959, "author": "Syed", "author_id": 2228691, "author_profile": "https://Stackoverflow.com/users/2228691", "pm_score": 1, "selected": false, "text": "www.YourDomain.com/YourFlashFile.swf <iframe src=\"//www.YourDomain.com/YourFlashFile.swf\" width=\"500\" height=\"500\"></iframe>\n" }, { "answer_id": 21070366, "author": "Allan", "author_id": 2289327, "author_profile": "https://Stackoverflow.com/users/2289327", "pm_score": -1, "selected": false, "text": "swfobject.embedSWF(\"filename.swf\", \"Title\", \"width\", \"height\", \"9.0.0\");\n <object>" }, { "answer_id": 25805669, "author": "gtb", "author_id": 3009025, "author_profile": "https://Stackoverflow.com/users/3009025", "pm_score": 0, "selected": false, "text": " <a target=\"_blank\" href=\"{{ entity.link }}\">\n <object type=\"application/x-shockwave-flash\" data=\"{{ entity.file.path }}?clickTAG={{ entity.link }}\" width=\"120\" height=\"600\" style=\"visibility: visible;\">\n <param name=\"quality\" value=\"high\">\n <param name=\"play\" value=\"true\">\n <param name=\"LOOP\" value=\"false\">\n <param name=\"wmode\" value=\"transparent\">\n <param name=\"allowScriptAccess\" value=\"true\">\n </object>\n </a>\n" }, { "answer_id": 30406612, "author": "Jan Desta", "author_id": 2942035, "author_profile": "https://Stackoverflow.com/users/2942035", "pm_score": 4, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<body>\n\n<embed src=\"anim.swf\">\n\n</body>\n</html>\n" }, { "answer_id": 31627369, "author": "Stefan Đorđević", "author_id": 4722777, "author_profile": "https://Stackoverflow.com/users/4722777", "pm_score": 2, "selected": false, "text": "<embed src=\"application.swf\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getfashplayer\" type=\"application/x-shockwave-flash\" width=\"690\" height=\"430\">\n" }, { "answer_id": 48910563, "author": "Isuru Dilshan", "author_id": 7877099, "author_profile": "https://Stackoverflow.com/users/7877099", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <title>histo2</title>\n <style type=\"text/css\" media=\"screen\">\n html, body { height:100%; background-color: #ffff99;}\n body { margin:0; padding:0; overflow:hidden; }\n #flashContent { width:100%; height:100%; }\n </style>\n </head>\n <body>\n <div id=\"flashContent\">\n <object type=\"application/x-shockwave-flash\" data=\"histo2.swf\" width=\"822\" height=\"550\" id=\"histo2\" style=\"float: none; vertical-align:middle\">\n <param name=\"movie\" value=\"histo2.swf\" />\n <param name=\"quality\" value=\"high\" />\n <param name=\"bgcolor\" value=\"#ffff99\" />\n <param name=\"play\" value=\"true\" />\n <param name=\"loop\" value=\"true\" />\n <param name=\"wmode\" value=\"window\" />\n <param name=\"scale\" value=\"showall\" />\n <param name=\"menu\" value=\"true\" />\n <param name=\"devicefont\" value=\"false\" />\n <param name=\"salign\" value=\"\" />\n <param name=\"allowScriptAccess\" value=\"sameDomain\" />\n <a href=\"http://www.adobe.com/go/getflash\">\n <img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" />\n </a>\n </object>\n </div>\n </body>\n</html>\n" }, { "answer_id": 54138706, "author": "xxnull", "author_id": 6273068, "author_profile": "https://Stackoverflow.com/users/6273068", "pm_score": 1, "selected": false, "text": "<object type=\"application/x-shockwave-flash\" data=\"movie.swf\" width=\"720\" height=\"480\">\n <param name=\"movie\" value=\"movie.swf\" />\n <param name=\"quality\" value=\"high\" />\n <param name=\"bgcolor\" value=\"#000000\" />\n <param name=\"play\" value=\"true\" />\n <param name=\"loop\" value=\"true\" />\n <param name=\"wmode\" value=\"window\" />\n <param name=\"scale\" value=\"showall\" />\n <param name=\"menu\" value=\"true\" />\n <param name=\"devicefont\" value=\"false\" />\n <param name=\"salign\" value=\"\" />\n <param name=\"allowScriptAccess\" value=\"sameDomain\" />\n <a href=\"http://www.adobe.com/go/getflash\">\n <img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" />\n </a>\n</object>\n" }, { "answer_id": 61020637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<embed> <embed src=\"file.swf\" width=\"854\" height=\"480\"></embed>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
137,336
<p>PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.</p> <p>Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument.</p> <p>Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, <strong><em>I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.</em></strong> </p> <p>How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages? </p> <p>Also, how can you do all this while accounting for inheritance in Php? Consider:</p> <pre><code>&lt;?php class InterfaceClass { #... } class UsesInterfaceClass { function SetObject(&amp;$obj) { // What do I put here to make sure that $obj either // is of type InterfaceObject or inherits from it } } ?&gt; </code></pre> <p>Then a user of this code implements the interface with their own concrete class:</p> <pre><code>&lt;?php class ConcreteClass extends InterfaceClass { } ?&gt; </code></pre> <p>I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?</p>
[ { "answer_id": 137342, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 5, "selected": true, "text": " <?php\n class UsesBaseClass\n {\n function SetObject(InterfaceObject $obj) \n {\n }\n }\n ?>\n" }, { "answer_id": 137351, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 2, "selected": false, "text": "<?php\nclass MyCoolClass {\n public function passMeAnArray(array $array = array()) {\n // do something with the array \n } \n } \n ?>\n ::passMeAnArray() array" }, { "answer_id": 170242, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 2, "selected": false, "text": "public function Add($a, $b)\n{\n if (!is_int($a) || !is_int($b))\n throw new InvalidArgumentException();\n return $a + $b;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
137,340
<p>The question posed came about during a 2nd Year Comp Science lecture while discussing the impossibility of generating numbers in a deterministic computational device.</p> <p>This was the only suggestion which didn't depend on non-commodity-class hardware.</p> <p>Subsequently nobody would put their reputation on the line to argue definitively for or against it. </p> <p>Anyone care to make a stand for or against. If so, how about a mention as to a possible implementation?</p>
[ { "answer_id": 137401, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "@ips : list = getIpAddresses();\n@rnd = PseudorandomNumberGenerator(0 to (ips.count - 1));\n\n@getTrueRandomNumber() { ping(ips[rnd.nextNumber()]).averageTime }\n" }, { "answer_id": 153045, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 0, "selected": false, "text": " I MADE U A RANDOM NUMBER\n BUT I EATED IT\n" }, { "answer_id": 625038, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 4, "selected": false, "text": "/etc/init.d/networking stop" }, { "answer_id": 1218649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <stdio.h>\n#include <cstdio>\n#include <stdlib.h>\n#include <vector>\n#include <fstream>\n\nusing namespace std;\n\nint main()\n{\nsystem(\"traceroute -w 5 www.google.com >> trace.txt\");\n\nstring fname = \"trace.txt\";\nifstream in;\nstring temp;\n\nvector<string> tracer;\nvector<string> numbers;\n\nin.open(fname.c_str());\nwhile(in>>temp)\ntracer.push_back(temp);\n\nsystem(\"rm trace.txt\");\n\nunsigned index = 0;\n\nstring a = \"ms\";\nwhile(index<tracer.size())\n{\nif(tracer[index]== a)\nnumbers.push_back(tracer[index-1]);\n++index;\n}\n\n\nstd::string rand;\n\nfor(unsigned i = 0 ; i < numbers.size() ; ++i)\n{\nstd::string temp = numbers[i];\nint index = temp.size();\nrand += temp[index - 1];\n}\n\ncout<<rand<<endl;\n\nreturn 0;\n\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
137,359
<p>I produce a report as an CSV file. When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly.</p> <p>For example, if the CSV file contains</p> <pre><code>...,005,... </code></pre> <p>Then Excel shows it as 5. Is there a way to override this and display 005?</p> <p>I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it.</p> <p>I use Excel 2003.</p>
[ { "answer_id": 3259242, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 0, "selected": false, "text": "...,`005,...\n" }, { "answer_id": 4597545, "author": "personaelit", "author_id": 42574, "author_profile": "https://Stackoverflow.com/users/42574", "pm_score": 1, "selected": false, "text": ", 005," }, { "answer_id": 19274257, "author": "Kloe2378231", "author_id": 2378231, "author_profile": "https://Stackoverflow.com/users/2378231", "pm_score": 2, "selected": false, "text": "\"firstvalue\";\"secondvalue\";\"005 \";\"othervalue\"" }, { "answer_id": 23666382, "author": "Ellen", "author_id": 3499045, "author_profile": "https://Stackoverflow.com/users/3499045", "pm_score": 1, "selected": false, "text": " 'Convert .csv file to .txt file.\n FileName = ConvertToText(FileName)\n\n Dim ColumnTypes(,) As Integer = New Integer(,) {{1, xlTextFormat}, _\n {2, xlTextFormat}, _\n {3, xlGeneralFormat}, _\n {4, xlGeneralFormat}, _\n {5, xlGeneralFormat}, _\n {6, xlGeneralFormat}}\n\n 'We are using OpenText() in order to specify the column types.\n mxlApp.Workbooks.OpenText(FileName, , , Excel.XlTextParsingType.xlDelimited, , , True, , True, , , , ColumnTypes)\n mxlWorkBook = mxlApp.ActiveWorkbook\n mxlWorkSheet = CType(mxlApp.ActiveSheet, Excel.Worksheet)\n\n\nPrivate Function ConvertToText(ByVal FileName As String) As String\n 'Convert the .csv file to a .txt file.\n 'If the file is a text file, we can specify the column types.\n 'Otherwise, the Codes are first converted to numbers, which loses trailing zeros.\n\n Try\n Dim MyReader As New StreamReader(FileName)\n Dim NewFileName As String = FileName.Replace(\".CSV\", \".TXT\")\n Dim MyWriter As New StreamWriter(NewFileName, False)\n Dim strLine As String\n\n Do While Not MyReader.EndOfStream\n strLine = MyReader.ReadLine\n MyWriter.WriteLine(strLine)\n Loop\n\n MyReader.Close()\n MyReader.Dispose()\n MyWriter.Close()\n MyWriter.Dispose()\n\n Return NewFileName\n Catch ex As Exception\n MsgBox(ex.Message)\n Return \"\"\n End Try\n\nEnd Function\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10557/" ]
137,375
<p>I'm teaching/helping a student to program.</p> <p>I remember the following process always helped me when I started; It looks pretty intuitive and I wonder if someone else have had a similar approach.</p> <ol> <li>Read the problem and understand it ( of course ) .</li> <li>Identify possible "functions" and variables.</li> <li>Write how would I do it step by step ( algorithm ) </li> <li>Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.</li> </ol> <p>With the time and practice I seem to have forgotten how hard it was to pass from problem description to a coding solution, but, by applying this method I managed to learn how to program.</p> <p>So for a project description like: </p> <blockquote> <p><em>A system has to calculate the price of an Item based on the following rules ( a description of the rules... client, discounts, availability etc.. etc.etc. )</em></p> </blockquote> <p>I first step is to understand what the problem is.</p> <p>Then identify the item, the rules the variables etc.</p> <p>pseudo code something like:</p> <pre><code>function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int if( hourOfDay &gt; 18 ) then discount = 5% if( quantity &gt; 10 ) then discount = 5% if( clientAge &gt; 60 or &lt; 18 ) then discount = 5% return item_price - discounts... end </code></pre> <p>And then pass it to the programming language..</p> <pre><code>public class Problem1{ public int getPrice( int itemPrice, int quantity,hourOdDay ) { int discount = 0; if( hourOfDay &gt; 10 ) { // uh uh.. U don't know how to calculate percentage... // create a function and move on. discount += percentOf( 5, itemPriece ); . . . you get the idea.. } } public int percentOf( int percent, int i ) { // .... } } </code></pre> <p>Did you went on a similar approach?.. Did some one teach you a similar approach or did you discovered your self ( as I did :( ) </p>
[ { "answer_id": 137485, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": false, "text": "- simple calculations (no discounts and concessions) with:\n - single item\n - two items\n - maximum number of items that doesn't have a discount\n- calculate for discounts based on number of items\n - buying 10 items gives you a 5% discount\n - buying 15 items gives you a 7% discount\n - etc.\n- calculate based on hourly rates\n - calculate morning rates\n - calculate afternoon rates\n - calculate evening rates\n - calculate midnight rates\n- calculate based on buyer's age\n - children\n - adults\n - seniors\n- calculate based on combinations\n - buying 10 items in the afternoon\n [Test] public void SingleItems()\n{\n Assert.AreEqual(5, GetPrice(5, 1));\n}\n public decimal GetPrice(decimal amount, int quantity)\n{\n return amount * quantity; // easy!\n}\n [Test]\npublic void TwoItemsItems()\n{\n Assert.AreEqual(10, GetPrice(5, 2));\n}\n" }, { "answer_id": 137632, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "(display (- (sum-of-squares (list-to 10))\n (square-of-sums (list-to 10))))\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
137,380
<p>Does anyone have a suggestion for where to find archives or collections of everyday English text for use in a small corpus? I have been using Gutenberg Project books for a working prototype, and would like to incorporate more contemporary language. A <a href="https://stackoverflow.com/questions/122595/nlp-qualitatively-positive-vs-negative-sentence#126378">recent answer</a> here pointed indirectly to a great <a href="http://us.imdb.com/Reviews/" rel="nofollow noreferrer">archive of usenet movie reviews</a>, which hadn't occurred to me, and is very good. For this particular program technical usenet archives or programming mailing lists would tilt the results and be hard to analyze, but any kind of general blog text, or chat transcripts, or anything that may have been useful to others, would be very helpful. Also, a partial or downloadable research corpus that isn't too marked-up, or some heuristic for finding an appropriate subset of wikipedia articles, or any other idea, is very appreciated.</p> <p>(BTW, I am being a good citizen w/r/t downloading, using a deliberately slow script that is not demanding on servers hosting such material, in case you perceive a moral hazard in pointing me to something enormous.)</p> <p><strong>UPDATE</strong>: User S0rin points out that wikipedia requests no crawling and provides <a href="http://en.wikipedia.org/wiki/Special:Export" rel="nofollow noreferrer">this export tool</a> instead. Project Gutenberg has a policy specified <a href="http://www.gutenberg.org/wiki/Gutenberg:Information_About_Robot_Access_to_our_Pages" rel="nofollow noreferrer">here</a>, bottom line, try not to crawl, but if you need to: "Configure your robot to wait at least 2 seconds between requests."</p> <p><strong>UPDATE 2</strong> The wikpedia dumps are the way to go, thanks to the answerers who pointed them out. I ended up using the English version from here: <a href="http://download.wikimedia.org/enwiki/20090306/" rel="nofollow noreferrer">http://download.wikimedia.org/enwiki/20090306/</a> , and a Spanish dump about half the size. They are some work to clean up, but well worth it, and they contain a lot of useful data in the links.</p> <hr>
[ { "answer_id": 138242, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 2, "selected": false, "text": "wget" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11596/" ]
137,387
<p>I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library:</p> <pre><code>Set fso = CreateObject("Scripting.FileSystemObject") Set folderObject = fso.GetFolder(folder) size = folderObject.Size </code></pre> <p>There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes.</p> <p>To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes?</p> <p>Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal.</p>
[ { "answer_id": 137393, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "public static long DirSize(DirectoryInfo d) \n{ \n long Size = 0; \n // Add file sizes.\n FileInfo[] fis = d.GetFiles();\n foreach (FileInfo fi in fis) \n { \n Size += fi.Length; \n }\n // Add subdirectory sizes.\n DirectoryInfo[] dis = d.GetDirectories();\n foreach (DirectoryInfo di in dis) \n {\n Size += DirSize(di); \n }\n return(Size); \n}\n" }, { "answer_id": 137424, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 0, "selected": false, "text": "private double size = 0;\n\nprivate double GetDirectorySize(string directory)\n{\n foreach (string dir in Directory.GetDirectories(directory))\n {\n GetDirectorySize(dir);\n }\n\n foreach (FileInfo file in new DirectoryInfo(directory).GetFiles())\n {\n size += file.Length;\n }\n\n return size;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
137,392
<p>I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/" rel="nofollow noreferrer">password composer</a> which lets you generate passwords base on the <strong>hostname</strong> and a secret <strong>master password</strong>. But I don't want to use a website or installing software to generate my passwords.</p> <p>So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the <a href="http://en.wikipedia.org/wiki/Solitaire_(cipher)" rel="nofollow noreferrer">solitare cipher</a> without the need for cards.</p> <p>Using a PW store is not an option.</p>
[ { "answer_id": 137421, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "Master Password: kaboom\nMachine Name: hal9000\nShuffle: khaablo9o0m00\nTransposition table: shift 5 left\nabcdefghijklmnopqrstuvwxyz 1234567890\nvwxyzabcdefghijklmnopqrstu 6789012345 \n\nResult: fcvvwgj4j5h55\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
137,398
<p>I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:</p> <pre><code>SELECT Column1, Column2, Column3+Column4 AS [Added Values] FROM Table </code></pre> <p>where Column3 or Column4 may be null. In this case, I want null to be considered zero (so <code>4 + null = 4, null + null = 0</code>).</p> <p>Any suggestions as to how to accomplish this?</p>
[ { "answer_id": 137410, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 5, "selected": true, "text": "SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]\nFROM Table\n" }, { "answer_id": 137413, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 1, "selected": false, "text": " SELECT Column1, Column2, ISNULL(Column3, 0) + ISNULL(Column4, 0) AS [Added Values]FROM Table\n" }, { "answer_id": 139117, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": -1, "selected": false, "text": "SELECT \n Column1, \n Column2, \n COALESCE(Column3, 0) + COALESCE(Column4, 0) AS [Added Values]\nFROM Table\n" }, { "answer_id": 140546, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 2, "selected": false, "text": "nz (column3, 0)\n" }, { "answer_id": 143092, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 1, "selected": false, "text": "SELECT Column1, Column2, Nz(Column3, 0) + Nz(Column4, 0) AS [Added Values]\nFROM Table\n" }, { "answer_id": 5461079, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 2, "selected": false, "text": "IIF(Column3 is Null; 0; Column3) NZ() ISNULL()" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14902/" ]
137,399
<p>Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed.</p> <p>I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it.</p> <p>Just wondering what people's views on this are?</p>
[ { "answer_id": 137438, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 5, "selected": true, "text": "// Act\nException ex = Record.Exception(() => someCode());\n\n// Assert\nAssert.Null(ex);\n" }, { "answer_id": 137441, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 3, "selected": false, "text": "try\n{\n unitUnderTest.DoWork()\n}\ncatch\n{\n Assert.Fail(\"code should never throw exceptions but failed with ...\")\n}\n" }, { "answer_id": 137470, "author": "codeLes", "author_id": 3030, "author_profile": "https://Stackoverflow.com/users/3030", "pm_score": 1, "selected": false, "text": "Class Controller {\n private Validator validator;\n\n public void control(){\n validator.validate;\n }\n\n public setValidator(Validator validator){ this.validator = validator; }\n}\n public void testControlShouldCallValidate(){\n mockValidator.expects(once()).method(\"validate\");\n controller.control;\n}\n" }, { "answer_id": 1070862, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 1, "selected": false, "text": "void TestLogDoesNotThrowException(void) {\n log(\"blah blah\");\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
137,448
<p>Take the following snippet:</p> <pre><code>List&lt;int&gt; distances = new List&lt;int&gt;(); </code></pre> <p>Was the redundancy intended by the language designers? If so, why?</p>
[ { "answer_id": 137455, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 4, "selected": false, "text": " var distances = new List<int>();\n" }, { "answer_id": 137459, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 1, "selected": false, "text": "distances = []\n" }, { "answer_id": 137475, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "List<int> listOfInts = new List<int>():\n var listOfInts = new List<int>();\n" }, { "answer_id": 137476, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 2, "selected": false, "text": "var distances = new List<int>();\n" }, { "answer_id": 137492, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 0, "selected": false, "text": "int i;\n Dim i as Integer\n" }, { "answer_id": 137514, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 2, "selected": false, "text": "List<int> foo; \n" }, { "answer_id": 137537, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 7, "selected": true, "text": "List<int> List<int> Person[] coworkers = new Employee[20];\n" }, { "answer_id": 137543, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "IEnumerable<int> distances = new List<int>();\n// or more likely...\nIEnumerable<int> distances = GetList();\n" }, { "answer_id": 137545, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "var x = new {Foo = Bar, Number = 1};\n" }, { "answer_id": 139067, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "var" }, { "answer_id": 147200, "author": "trampster", "author_id": 78561, "author_profile": "https://Stackoverflow.com/users/78561", "pm_score": 1, "selected": false, "text": "//Use var here\nvar names = new List<string>();\n\n//but not here\nList<string> names = GetNames();\n" }, { "answer_id": 421926, "author": "Joan Venge", "author_id": 51816, "author_profile": "https://Stackoverflow.com/users/51816", "pm_score": 2, "selected": false, "text": "var distances = new List<int>();\n" }, { "answer_id": 423619, "author": "Oliver Friedrich", "author_id": 44532, "author_profile": "https://Stackoverflow.com/users/44532", "pm_score": 0, "selected": false, "text": "var names = new List<string>();\n List<string>, List<T>. IList<string> = new List<string>();\nICollection<string> = new List<string>();\nIEnumerable<string> = new List<string>();\n" }, { "answer_id": 2767703, "author": "Greg Bacon", "author_id": 123109, "author_profile": "https://Stackoverflow.com/users/123109", "pm_score": 0, "selected": false, "text": "foo.Foo* myFoo = new(foo.Foo) :=" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
137,449
<p>I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled.</p> <pre><code>&lt;div class="app_setting"&gt; &lt;label"&gt;Name&lt;/label&gt; &lt;input type="text" name="name"/&gt; &lt;/div&gt; .app_setting:hover { cursor:move; } </code></pre> <p>Any ideas how to get the hover to apply also to the child elements?</p>
[ { "answer_id": 137466, "author": "garrow", "author_id": 21095, "author_profile": "https://Stackoverflow.com/users/21095", "pm_score": 6, "selected": true, "text": ".app_setting *:hover { cursor:move }\n" }, { "answer_id": 137496, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 5, "selected": false, "text": "* .class *:hover .class:hover *" }, { "answer_id": 137603, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 2, "selected": false, "text": "$(\".appsetting\").hover(hoverInFunc,hoverOutFunc); $()" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14971/" ]
137,452
<p>I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries?</p>
[ { "answer_id": 137505, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 4, "selected": true, "text": "ALTER DATABASE database_name COLLATE collation_name\n" }, { "answer_id": 289842, "author": "nickd", "author_id": 2373, "author_profile": "https://Stackoverflow.com/users/2373", "pm_score": 1, "selected": false, "text": "select temp.A, table.B\nfrom #TEMPORARY_TABLE temp inner join table\non temp.X COLLATE database_default = table.Y\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
137,454
<p>Considering "private" is the default access modifier for class Members, why is the keyword even needed?</p>
[ { "answer_id": 137686, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "private int x;\npublic string y;\nprotected float z;\n int x;\n\npublic string y;\nprotected float z;\n" }, { "answer_id": 137962, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 3, "selected": false, "text": "public bool CanAccessTheMissileCodes\n{\n get { return canAccessTheMissileCodes; }\n private set { canAccessTheMissileCodes = value; }\n}\n" }, { "answer_id": 138005, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 1, "selected": false, "text": "private internal" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
137,487
<p>I am told that good developers can spot/utilize the difference between <code>Null</code> and <code>False</code> and <code>0</code> and all the other good "nothing" entities.<br> What <em>is</em> the difference, specifically in PHP? Does it have something to do with <code>===</code>?</p>
[ { "answer_id": 137539, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 3, "selected": false, "text": "NULL False 0 null NULL 0 NULL 0" }, { "answer_id": 137553, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 1, "selected": false, "text": "( \n ( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&\n ( false !== null ) && ( false == null ) \n)\n 0x00 ( null == 0x00 ) && ( null !== 0x00 ) 0" }, { "answer_id": 137575, "author": "Chad", "author_id": 17382, "author_profile": "https://Stackoverflow.com/users/17382", "pm_score": 1, "selected": false, "text": "// On error GetChar returns -1\nint GetChar()\n char GetChar()\n // On success return 1\n// on failure return 0\nbool GetChar(int &char)\n" }, { "answer_id": 137701, "author": "Javier Constanzo", "author_id": 21996, "author_profile": "https://Stackoverflow.com/users/21996", "pm_score": 2, "selected": false, "text": "FALSE 0.0 \"0\" NULL TRUE === == $a == $b //Equal. TRUE if $a is equal to $b.\n$a === $b //Identical. TRUE if $a is equal to $b, and they are of the same type. \n" }, { "answer_id": 137715, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "NULL NULL unset() NULL false 0 0 \"0\" \"\" false" }, { "answer_id": 137776, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 0, "selected": false, "text": "x + 0 = x\n x || False = x\n" }, { "answer_id": 138020, "author": "inkredibl", "author_id": 22129, "author_profile": "https://Stackoverflow.com/users/22129", "pm_score": 3, "selected": false, "text": "0 == false true 0 === false false != !== null 0 false === strpos() strpos() false" }, { "answer_id": 138954, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 9, "selected": true, "text": "Null False 0 int False == === strrpos() <?php\n// pitfall :\nif (strrpos(\"Hello World\", \"Hello\")) { \n // never exectuted\n}\n\n// smart move :\nif (strrpos(\"Hello World\", \"Hello\") !== False) {\n // that works !\n}\n?>\n DebugMode = False DebugMode = True DebugMode = Null" }, { "answer_id": 5700831, "author": "gcb", "author_id": 183132, "author_profile": "https://Stackoverflow.com/users/183132", "pm_score": 6, "selected": false, "text": "null null false false false null filter_input() ===false ===null ===null ===false var_dump( 0<0 ); #bool(false)\nvar_dump( 1<0 ); #bool(false)\nvar_dump( -1<0 ); #bool(true)\nvar_dump( false<0 ); #bool(false)\nvar_dump( null<0 ); #bool(false)\nvar_dump( ''<0 ); #bool(false)\nvar_dump( 'a'<0 ); #bool(false)\necho \"\\n\";\nvar_dump( !0 ); #bool(true)\nvar_dump( !1 ); #bool(false)\nvar_dump( !-1 ); #bool(false)\nvar_dump( !false ); #bool(true)\nvar_dump( !null ); #bool(true)\nvar_dump( !'' ); #bool(true)\nvar_dump( !'a' ); #bool(false)\necho \"\\n\";\nvar_dump( false == 0 ); #bool(true)\nvar_dump( false == 1 ); #bool(false)\nvar_dump( false == -1 ); #bool(false)\nvar_dump( false == false ); #bool(true)\nvar_dump( false == null ); #bool(true)\nvar_dump( false == '' ); #bool(true)\nvar_dump( false == 'a' ); #bool(false)\necho \"\\n\";\nvar_dump( null == 0 ); #bool(true)\nvar_dump( null == 1 ); #bool(false)\nvar_dump( null == -1 ); #bool(false)\nvar_dump( null == false ); #bool(true)\nvar_dump( null == null ); #bool(true)\nvar_dump( null == '' ); #bool(true)\nvar_dump( null == 'a' ); #bool(false)\necho \"\\n\";\n$a=0; var_dump( empty($a) ); #bool(true)\n$a=1; var_dump( empty($a) ); #bool(false)\n$a=-1; var_dump( empty($a) ); #bool(false)\n$a=false; var_dump( empty($a) ); #bool(true)\n$a=null; var_dump( empty($a) ); #bool(true)\n$a=''; var_dump( empty($a) ); #bool(true)\n$a='a'; var_dump( empty($a)); # bool(false)\necho \"\\n\"; #new block suggested by @thehpi\nvar_dump( null < -1 ); #bool(true)\nvar_dump( null < 0 ); #bool(false)\nvar_dump( null < 1 ); #bool(true)\nvar_dump( -1 > true ); #bool(false)\nvar_dump( 0 > true ); #bool(false)\nvar_dump( 1 > true ); #bool(true)\nvar_dump( -1 > false ); #bool(true)\nvar_dump( 0 > false ); #bool(false)\nvar_dump( 1 > true ); #bool(true)\n" }, { "answer_id": 27606553, "author": "madesignUK", "author_id": 3037182, "author_profile": "https://Stackoverflow.com/users/3037182", "pm_score": 2, "selected": false, "text": "0 null false strops if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ()) \n{ \n do this \n} else {\n or that\n}\n\n{\necho strpos(mydomain.co.uk, mydomain); \n\nif ( strpos(mydomain, xmas) == null ) \n {\n echo \"\\n1 is null\"; \n }\n\nif ( (strpos(mydomain.co.uk, mydomain)) == 0 ) \n {\n echo \"\\n2 is 0\"; \n } else {\n echo \"\\n2 Something is WRONG\"; \n }\n\nif ( (mydomain.co.uk, mydomain)) != 0 ) \n {\n echo \"\\n3 is 0\"; \n } else {\n echo \"\\n3 it is not 0\"; \n }\n\nif ( (mydomain.co.uk, mydomain)) == null ) \n {\n echo \"\\n4 is null\"; \n } else {\n echo \"\\n4 Something is WRONG\"; \n }\n}\n {\nif ((mydomain.co.uk, mydomain)) !== false ) \n {\n echo \"\\n5 is True\"; \n } else {\n echo \"\\n5 is False\"; \n }\n}\n false NULL False NULL 0 True or False or NULL" }, { "answer_id": 33293119, "author": "kriscondev", "author_id": 5159914, "author_profile": "https://Stackoverflow.com/users/5159914", "pm_score": 5, "selected": false, "text": " Comparisons of $x with PHP functions\n\nExpression gettype() empty() is_null() isset() boolean : if($x)\n$x = \"\"; string TRUE FALSE TRUE FALSE\n$x = null; NULL TRUE TRUE FALSE FALSE\nvar $x; NULL TRUE TRUE FALSE FALSE\n$x is undefined NULL TRUE TRUE FALSE FALSE\n$x = array(); array TRUE FALSE TRUE FALSE\n$x = false; boolean TRUE FALSE TRUE FALSE\n$x = true; boolean FALSE FALSE TRUE TRUE\n$x = 1; integer FALSE FALSE TRUE TRUE\n$x = 42; integer FALSE FALSE TRUE TRUE\n$x = 0; integer TRUE FALSE TRUE FALSE\n$x = -1; integer FALSE FALSE TRUE TRUE\n$x = \"1\"; string FALSE FALSE TRUE TRUE\n$x = \"0\"; string TRUE FALSE TRUE FALSE\n$x = \"-1\"; string FALSE FALSE TRUE TRUE\n$x = \"php\"; string FALSE FALSE TRUE TRUE\n$x = \"true\"; string FALSE FALSE TRUE TRUE\n$x = \"false\"; string FALSE FALSE TRUE TRUE\n" }, { "answer_id": 53140612, "author": "adrian", "author_id": 10603435, "author_profile": "https://Stackoverflow.com/users/10603435", "pm_score": -1, "selected": false, "text": "'*' == true -> true (string match)\n'*' === true -> false (numberic match)\n\n(int)'*' == true -> false\n(string)'*' == true -> true\n" }, { "answer_id": 54472049, "author": "vladzur", "author_id": 797716, "author_profile": "https://Stackoverflow.com/users/797716", "pm_score": 0, "selected": false, "text": "$x = 0;\nvar_dump($x == 'NULL'); # TRUE !!!WTF!!!\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
137,497
<p>In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables?</p>
[ { "answer_id": 137750, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": 2, "selected": false, "text": "SELECT text FROM dba_views\nWHERE owner = 'the-owner' AND view_name = 'the-view-name';\n" }, { "answer_id": 138751, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "create or replace view london_dept as\nselect * from dept\nwhere loc = 'LONDON';\n create or replace view london_mgr as\nselect * from emp \nwhere job='MANAGER'\nand deptno in (select deptno from london_dept);\n select * from emp \nwhere job='MANAGER'\nand deptno in (select deptno from (select * from dept\nwhere loc = 'LONDON'));\n select * from emp \nwhere job='MANAGER'\nand deptno in (select deptno from dept where loc = 'LONDON');\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
137,521
<p>My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class:</p> <pre><code>invoice.address_id = 1 invoice.address = some_address </code></pre> <p>Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling</p> <pre><code>attr_protected :address_id </code></pre> <p>is most likely not the solution since based on the documentation it only prevents mass assignments.</p> <p>Thanks!</p>
[ { "answer_id": 137538, "author": "ryw", "author_id": 2477, "author_profile": "https://Stackoverflow.com/users/2477", "pm_score": 2, "selected": false, "text": "def address_id=(id)\n if new_record?\n write_attribute(:address_id, id)\n else\n raise 'address is immutable!'\n end\nend \n" }, { "answer_id": 137551, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 5, "selected": true, "text": "attr_readonly" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082/" ]
137,523
<p>I'd like to learn assembler. However, there are very few resources for doing assembler with OS X.</p> <p>Is there anyone out there who has programmed in assembly on a Mac? Where did you learn?</p> <p>And, is there any reason I shouldn't be doing assembly? Do I risk (significantly) crashing my computer irreparably?</p>
[ { "answer_id": 137680, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 3, "selected": false, "text": "gcc -S hello.c -o hello.asm\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
137,526
<p>On some systems it is UTF-8, on others latin-1. How do you set this? Is it something in php.ini?</p> <p>(I know you can set the encoding/charset for a given page by setting HTTP headers, but this is not what I am looking for.)</p> <p>Alex</p>
[ { "answer_id": 137680, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 3, "selected": false, "text": "gcc -S hello.c -o hello.asm\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
137,530
<p>Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as <code>null</code>, even though it's definitely being sent <code>1</code>.</p> <p>The Delphi code uses a TADOQuery to execute the stored procedure (anonymized):</p> <pre><code> ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy"; ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction()); // other parameters all set similarly ADOQuery1.ExecSQL; </code></pre> <p><code>Integer(SomeFunction())</code> currently always returns 1 - I checked with the debugger.</p> <p>However, in my stored proc ( altered for debug purposes ):</p> <pre><code>create procedure MyStoredProcedure ( @Foo int, @Bar int, @Baz int, @Qux int, @Smang int, @Jimmy varchar(20) ) as begin -- temp debug if ( @Foo is null ) begin insert into TempLog values ( "oh crap" ) end -- do the rest of the stuff here.. end </code></pre> <p><code>TempLog</code> does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?).</p> <p>Here's an example trace from profiler:</p> <pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p3 int set @p3=NULL exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int', @p3 output,1,1,1,0,200 select @p3 </code></pre> <p>This looks a little strange to me. Notice that it's using @p3 <em>and</em> @P3 - could this be causing my issue? </p> <p>The other strange thing is that it seems to depend on which TADOConnection I use. </p> <p>The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection.</p> <p>If instead of using this connection, I first do this:</p> <pre><code>ConnectionNew := TADOQuery.Create(ConnectionOld.Owner); ConnectionNew.ConnectionString := ConnectionOld.ConnectionString; TADOQuery1.Connection := ConnectionNew; </code></pre> <p>Then the issue does not occur! The trace from this situation is this:</p> <pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p1 int set @p1=64 exec sp_prepare @p1 output, N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', 1 select @p1 SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF exec sp_unprepare 64 SET NO_BROWSETABLE OFF exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', 1,1,1,3,0,'400.00' </code></pre> <p>Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this?</p> <p>Does anyone have any ideas?</p> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/137530/why-is-my-stored-procedure-receiving-a-null-parameter#177214">Update below</a> (didn't want to make this question any longer :P)</p>
[ { "answer_id": 152251, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 0, "selected": false, "text": " ADOQuery1.Parameters.Refresh;\n ADOQuery1.Parameters.Clear;\n ADOQuery1.Parameters.CreateParameter('Foo', ftInteger, pdInput, 0, 1);\n [...]\n" }, { "answer_id": 152265, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": " ADOQuery1.Parameters.ParamByName(\"Foo\").Value = Integer(someFunction()); \n :=" }, { "answer_id": 177214, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": true, "text": "pdInput TParameters.InternalRefresh.RefreshFromOleDB function TParameters.InternalRefresh: Boolean;\n procedure RefreshFromOleDB;\n // ..\n if OLEDBParameters.GetParameterInfo(ParamCount, PDBPARAMINFO(ParamInfo), @NamesBuffer) = S_OK then\n for I := 0 to ParamCount - 1 do\n with ParamInfo[I] do\n begin\n // ..\n Direction := dwFlags and $F; // here's where the wrong value comes from\n // ..\n end;\n // ..\n end;\n // ..\nend;\n OLEDBParameters.GetParameterInfo (dwFlags and $F) 2 DBPARAMFLAGS_ISOUTPUT 1 DBPARAMFLAGS_ISINPUT pdInput" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
137,534
<p>I was reading about output buffering in JavaScript <strong><a href="http://www.webreference.com/programming/javascript/jkm3/4.html" rel="nofollow noreferrer">here</a>,</strong> and was trying to get my head around the script the author says was the fastest at printing 1 to 1,000,000 to a web page. (Scroll down to the header "The winning one million number script".) After studying it a bit, I have a few questions: </p> <ul> <li>What makes this script so efficient compared to other approaches? </li> <li>Why does buffering speed things up? </li> <li>How do you determine the proper buffer size to use?</li> <li>Does anyone here have any tricks up her/his sleeve that could optimize this script further?</li> </ul> <p>(I realize this is probably CS101, but I'm one of those blasted, self-taught hackers and I was hoping to benefit from the wisdom of the collective on this one. Thanks!)</p>
[ { "answer_id": 137898, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 1, "selected": false, "text": "<html>\n<head>\n<script type=\"text/javascript\">\n function printAllNumberBuffered(n, bufferSize)\n {\n var startTime = new Date();\n\n var oRuntime = document.getElementById(\"divRuntime\");\n var oNumbers = document.getElementById(\"divNumbers\");\n\n var i = 0;\n var currentNumber;\n var pass = 0;\n var numArray = new Array(bufferSize);\n\n for(currentNumber = 1; currentNumber <= n; currentNumber++)\n {\n numArray[i] = currentNumber;\n\n if(currentNumber % bufferSize == 0 && currentNumber > 0)\n {\n oNumbers.textContent += numArray.join(' ');\n i = 0;\n }\n else\n {\n i++;\n }\n }\n\n if(i > 0)\n {\n numArray.splice(i - 1, bufferSize - 1);\n oNumbers.textContent += numArray.join(' ');\n }\n\n var endTime = new Date();\n\n oRuntime.innerHTML += \"<div>Number: \" + n + \" Buffer Size: \" + bufferSize + \" Runtime: \" + (endTime - startTime) + \"</div>\";\n }\n\n function PrintNumbers()\n {\n var oNumbers = document.getElementById(\"divNumbers\");\n var tbNumber = document.getElementById(\"tbNumber\");\n var tbBufferSize = document.getElementById(\"tbBufferSize\");\n\n var n = parseInt(tbNumber.value);\n var bufferSize = parseInt(tbBufferSize.value);\n\n oNumbers.textContent = \"\";\n\n printAllNumberBuffered(n, bufferSize);\n }\n</script>\n</head>\n<body>\n<table border=\"1\">\n <tr>\n <td colspan=\"2\">\n <div>Number:&nbsp;<input id=\"tbNumber\" type=\"text\" />Buffer Size:&nbsp;<input id=\"tbBufferSize\" type=\"text\" /><input type=\"button\" value=\"Run\" onclick=\"PrintNumbers();\" /></div>\n </td>\n </tr>\n <tr>\n <td style=\"vertical-align:top\" width=\"30%\">\n <div id=\"divRuntime\"></div>\n </td>\n <td width=\"90%\">\n <div id=\"divNumbers\"></div>\n </td>\n </tr>\n</table>\n</body>\n</html>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
137,580
<p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p> <p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p> <p>Any suggestions how I could accomplish this?</p>
[ { "answer_id": 137624, "author": "Michał Kwiatkowski", "author_id": 21998, "author_profile": "https://Stackoverflow.com/users/21998", "pm_score": 4, "selected": true, "text": "import mechanize\n\nclass HeadRequest(mechanize.Request):\n def get_method(self):\n return \"HEAD\"\n\nrequest = HeadRequest(\"http://www.example.com/\")\nresponse = mechanize.urlopen(request)\n\nprint response.info()\n" }, { "answer_id": 12680334, "author": "Nuncjo", "author_id": 977337, "author_profile": "https://Stackoverflow.com/users/977337", "pm_score": 0, "selected": false, "text": "\nimport mechanize\n\nbr = mechanize.Browser()\n\nr = br.open(\"http://www.example.com/\")\n\nprint r.info()\n\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
137,605
<p>I have been looking at XML and HTML libraries on rubyforge for a simple way to pull data out of a web page. For example if I want to parse a user page on stackoverflow how can I get the data into a usable format?</p> <p>Say I want to parse my own user page for my current reputation score and badge listing. I tried to convert the source retrieved from my user page into xml but the conversion failed due to a missing div. I know I could do a string compare and find the text I'm looking for, but there has to be a much better way of doing this.</p> <p>I want to incorporate this into a simple script that spits out my user data at the command line, and possibly expand it into a GUI application.</p>
[ { "answer_id": 137639, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": false, "text": "require 'hpricot'\nrequire 'open-uri'\n\ndoc = Hpricot(open(\"http://stackoverflow.com/users/19990/armin-ronacher\"))\nreputation = (doc / \"td.summaryinfo div.summarycount\").text.gsub(/[^\\d]+/, \"\").to_i\n" }, { "answer_id": 16040777, "author": "deadfish", "author_id": 619673, "author_profile": "https://Stackoverflow.com/users/619673", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env ruby\n\nrequire 'rubygems'\nrequire 'hpricot'\nrequire 'open-uri'\n\nuser = \"619673/100kg\"\nhtml = \"http://stackoverflow.com/users/%s?tab=reputation\"\n\npage = html % user\nputs page\n\ndoc = Hpricot(open(page))\npars = Array.new\ndoc.search(\"div[@class='subheader user-full-tab-header']/h1/span[@class='count']\").text.each do |p|\n pars << p\nend\n\nputs \"reputation \" + pars[0]\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22423/" ]
137,621
<p>I can't find a reference to it but I remember reading that it wasn't a good idea to call virtual (polymorphic) methods within a destructor or the Dispose() method of IDisposable.</p> <p>Is this true and if so can someone explain why?</p>
[ { "answer_id": 137947, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 4, "selected": true, "text": "Dispose virtual Dispose(bool disposing) class C : IDisposable {\n private IDisposable.Dispose() {\n this.Dispose(true);\n }\n protected virtual Dispose(bool disposing) {\n this.DoSomething();\n }\n\n protected virtual void DoSomething() { }\n}\nclass D : C {\n IDisposable X;\n\n protected override Dispose(bool disposing) {\n X.Dispose();\n base.Dispose(disposing);\n }\n\n protected override void DoSomething() {\n X.Whatever();\n }\n}\n D d ((IDisposable)d).Dispose() C.IDisposable.Dispose() D.Dispose(bool) D.Dispose(bool) D.X D.Dispose(bool) C.Dispose(bool) C.Dispose(bool) D.DoSomething() D.DoSomething D.X.Whatever() D.X base.Dispose(dispose) C D base.Dispose(disposing) C" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ]
137,623
<p>Expanding this question on how I learnt to pass from <a href="https://stackoverflow.com/questions/137375/"> problem description to code </a> Two people mentioned TDD.</p> <p>Would it be good for a starter to get into TDD ( and avoid bad habits in the future ? ) Or would it be too complex for a stage when understand what a programming language is?</p>
[ { "answer_id": 137662, "author": "ryw", "author_id": 2477, "author_profile": "https://Stackoverflow.com/users/2477", "pm_score": 2, "selected": false, "text": "def self.learn_tdd_and_programming_together?\n if you_have_tdd_mentor_sitting_next_to_you?\n \"go for it\"\n else\n if language.ruby?\n \"it's possible, there is quite a bit of good stuff out \n there that could give you a chance of learning programming \n with TDD from the start. It's sort of in the ruby culture\"\n elsif language.dot_net?\n \"learn TDD after you learn the basics of .NET\" \n end\n end\nend\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
137,629
<p>How do you render primitives as wireframes in OpenGL?</p>
[ { "answer_id": 137644, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": false, "text": "// Turn on wireframe mode\nglPolygonMode(GL_FRONT, GL_LINE);\nglPolygonMode(GL_BACK, GL_LINE);\n\n// Draw the box\nDrawBox();\n\n// Turn off wireframe mode\nglPolygonMode(GL_FRONT, GL_FILL);\nglPolygonMode(GL_BACK, GL_FILL);\n" }, { "answer_id": 137649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );\n glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );\n" }, { "answer_id": 22497914, "author": "Hochester", "author_id": 3436093, "author_profile": "https://Stackoverflow.com/users/3436093", "pm_score": 2, "selected": false, "text": "GL_LINE_STRIP glBegin(GL_LINE_STRIP);\n/* Draw vertices here */\nglEnd();\n" }, { "answer_id": 33004265, "author": "the swine", "author_id": 1140976, "author_profile": "https://Stackoverflow.com/users/1140976", "pm_score": 5, "selected": false, "text": "glPolygonMode GL_LINES in vec3 v_barycentric; // barycentric coordinate inside the triangle\nuniform float f_thickness; // thickness of the rendered lines\n\nvoid main()\n{\n float f_closest_edge = min(v_barycentric.x,\n min(v_barycentric.y, v_barycentric.z)); // see to which edge this pixel is the closest\n float f_width = fwidth(f_closest_edge); // calculate derivative (divide f_thickness by this to have the line width constant in screen-space)\n float f_alpha = smoothstep(f_thickness, f_thickness + f_width, f_closest_edge); // calculate alpha\n gl_FragColor = vec4(vec3(.0), f_alpha);\n}\n in vec4 v_pos; // position of the vertices\nin vec3 v_bc; // barycentric coordinate inside the triangle\n\nout vec3 v_barycentric; // barycentric coordinate inside the triangle\n\nuniform mat4 t_mvp; // modeview-projection matrix\n\nvoid main()\n{\n gl_Position = t_mvp * v_pos;\n v_barycentric = v_bc; // just pass it on\n}\n (1, 0, 0) (0, 1, 0) (0, 0, 1)" }, { "answer_id": 43410404, "author": "H.Mohcen", "author_id": 7258877, "author_profile": "https://Stackoverflow.com/users/7258877", "pm_score": 1, "selected": false, "text": "glutWireSphere(radius,20,20);\n GLUquadric *quadratic = gluNewQuadric();\ngluQuadricDrawStyle(quadratic,GLU_LINE);\ngluCylinder(quadratic,1,1,1,12,1);\n glutWireCube(1.5);\n" }, { "answer_id": 47037419, "author": "LMD", "author_id": 7185318, "author_profile": "https://Stackoverflow.com/users/7185318", "pm_score": 3, "selected": false, "text": "#version 330\n\nlayout (triangles) in;\nlayout (line_strip /*for lines, use \"points\" for points*/, max_vertices=3) out;\n\nin vec2 texcoords_pass[]; //Texcoords from Vertex Shader\nin vec3 normals_pass[]; //Normals from Vertex Shader\n\nout vec3 normals; //Normals for Fragment Shader\nout vec2 texcoords; //Texcoords for Fragment Shader\n\nvoid main(void)\n{\n int i;\n for (i = 0; i < gl_in.length(); i++)\n {\n texcoords=texcoords_pass[i]; //Pass through\n normals=normals_pass[i]; //Pass through\n gl_Position = gl_in[i].gl_Position; //Pass through\n EmitVertex();\n }\n EndPrimitive();\n}\n layout (line_strip, max_vertices=3) out; layout (points, max_vertices=3) out;" }, { "answer_id": 47054000, "author": "Victor", "author_id": 789999, "author_profile": "https://Stackoverflow.com/users/789999", "pm_score": 0, "selected": false, "text": "GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, GL_POINTS GL_TRIANGLE_STRIP GL_TRIANGLE_FAN GL_TRIANGLES glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)\n glDrawArrays(GLenum mode, GLint first, GLsizei count)" }, { "answer_id": 47064476, "author": "Zaphyk", "author_id": 3430546, "author_profile": "https://Stackoverflow.com/users/3430546", "pm_score": 3, "selected": false, "text": "//Turn on wireframe mode\nglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\n//Draw the scene with polygons as lines (wireframe)\nrenderScene();\n\n//Turn off wireframe mode\nglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n" }, { "answer_id": 59473781, "author": "Omar Ghannou", "author_id": 11969743, "author_profile": "https://Stackoverflow.com/users/11969743", "pm_score": 1, "selected": false, "text": "void glPolygonMode(GLenum face, GLenum mode);\n face GL_FRONT GL_BACK GL_FRONT_AND_BACK mode GL_POINT GL_LINE GL_FILL glPolygonMode" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,630
<p>I was wondering if there was a way to use "find_by_sql" within a named_scope. I'd like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently.</p>
[ { "answer_id": 180440, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "find_by_sql class Item\n # Anything you can put in an sql WHERE you can put here\n named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1'\nend\n Item.mine.find :all\n=> SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1)\n Items.mine.find_by_sql 'select * from items limit 1'\n=> select * from items limit 1\n select joins conditions with_scope named_scope find_by_sql" }, { "answer_id": 927136, "author": "jdwyah", "author_id": 53387, "author_profile": "https://Stackoverflow.com/users/53387", "pm_score": 1, "selected": false, "text": "named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1'\nnamed_scope :additional {\n :condtions => mine.send(:construct_finder_sql,{}) + \" additional = 'foo'\"\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
137,659
<p>Do you know any easy or simple way to make a map object (from the STL library) persistent (i.e. write it to a file) so that you can recover its state later when the program in run later ??</p> <p>Thanks for your help</p>
[ { "answer_id": 137696, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": false, "text": "outputFile.Write(thisMap.size());\nfor (map<...>::const_iterator i = thisMap.begin(); i != thisMap.end(); ++iMap)\n{\n outputFile.Write(i->first);\n outputFile.Write(i->second);\n}\n size_t mapSize = inputFile.Read();\nfor (size_t i = 0; i < mapSize; ++i)\n{\n keyType key = inputFile.Read();\n valueType value = inputFile.Read();\n thisMap[key] = value;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876/" ]
137,660
<p>In a J2EE application (like one running in WebSphere), when I use <code>System.out.println()</code>, my text goes to standard out, which is mapped to a file by the WebSphere admin console.</p> <p>In an ASP.NET application (like one running in IIS), where does the output of <code>Console.WriteLine()</code> go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here?</p> <p>I'm <strong>not asking</strong> if I should log there (I use log4net), but where does the output go? My best info came from this <a href="http://www.velocityreviews.com/forums/t91075-where-does-consolewriteline-goto.html" rel="noreferrer">discussion</a> where they say <code>Console.SetOut()</code> can change the <code>TextWriter</code>, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code.</p>
[ { "answer_id": 879928, "author": "Greg Bernhardt", "author_id": 24387, "author_profile": "https://Stackoverflow.com/users/24387", "pm_score": 10, "selected": false, "text": "System.Diagnostics.Debug.WriteLine(...) Console.WriteLine()" }, { "answer_id": 1432088, "author": "Ruben", "author_id": 143854, "author_profile": "https://Stackoverflow.com/users/143854", "pm_score": 9, "selected": true, "text": "Console Console.Out Console.Error Stream.Null TextWriter Stream /dev/null SetOut stdoutLogEnabled stdoutLogFile <system.webServer>\n <aspNetCore processPath=\"dotnet\"\n arguments=\".\\MyApp.dll\"\n hostingModel=\"inprocess\"\n stdoutLogEnabled=\"true\"\n stdoutLogFile=\".\\logs\\stdout\" />\n<system.webServer>\n" }, { "answer_id": 3896183, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 5, "selected": false, "text": "class DebugTextWriter : System.IO.TextWriter {\n public override void Write(char[] buffer, int index, int count) {\n System.Diagnostics.Debug.Write(new String(buffer, index, count));\n }\n\n public override void Write(string value) {\n System.Diagnostics.Debug.Write(value);\n }\n\n public override Encoding Encoding {\n get { return System.Text.Encoding.Default; }\n }\n}\n" }, { "answer_id": 9541047, "author": "Brian Griffin", "author_id": 1246074, "author_profile": "https://Stackoverflow.com/users/1246074", "pm_score": 2, "selected": false, "text": "TraceContext DefaultTraceListener Console.Write() Trace.Write System.Diagnostics.Process OutputDataRecieved" }, { "answer_id": 18887673, "author": "Nik", "author_id": 2228791, "author_profile": "https://Stackoverflow.com/users/2228791", "pm_score": 4, "selected": false, "text": "System.Diagnostics.Debug.WriteLine(...);" }, { "answer_id": 19523569, "author": "Chris", "author_id": 945840, "author_profile": "https://Stackoverflow.com/users/945840", "pm_score": 4, "selected": false, "text": "Console.Write \"C:\\Program Files (x86)\\IIS Express\\iisexpress\" /path:C:\\Projects\\Website1 /port:1655\n <%@ Page Language=\"C#\" %>\n<html>\n<body>\n <form id=\"form1\" runat=\"server\">\n Hello!\n\n <% for(int i = 0; i < 6; i++) %>\n <% { Console.WriteLine(i.ToString()); }%>\n\n </form>\n</body>\n</html>\n http://localhost:1655/ Request started: \"GET\" http://localhost:1655/\n0\n1\n2\n3\n4\n5\nRequest ended: http://localhost:1655/default.aspx with HTTP status 200.0\n" }, { "answer_id": 53953125, "author": "mickey", "author_id": 529059, "author_profile": "https://Stackoverflow.com/users/529059", "pm_score": 1, "selected": false, "text": "<targets>\n <target name=\"debugger\" xsi:type=\"Debugger\"\n layout=\"${date:format=HH\\:mm\\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} \"/>\n <rules>\n <logger name=\"*\" minlevel=\"Trace\" writeTo=\"debugger\" />\n" }, { "answer_id": 70324600, "author": "Shoaib Khalil", "author_id": 11966556, "author_profile": "https://Stackoverflow.com/users/11966556", "pm_score": 1, "selected": false, "text": "System.Diagnostics.Debug.WriteLine(\"Message\" + variable) Console.WriteLine()" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22514/" ]
137,661
<p>In C#, I can do this:</p> <pre><code>class Program { static void Main(string[] args) { List&lt;Animal&gt; animals = new List&lt;Animal&gt;(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } } } public class Animal { public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); } } public class Dog : Animal { public override string MakeNoise() { return "Woof!"; } } public class Cat : Animal { public override string MakeNoise() { return "Meow!"; } } </code></pre> <p>Obviously, the output is (Slightly paraphrased):</p> <ul> <li>Woof</li> <li>Dog is Sleeping</li> <li>Meow</li> <li>Cat is Sleeping</li> </ul> <p>Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?</p>
[ { "answer_id": 137675, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "class Animal\n def MakeNoise\n return \"\"\n end\n def Sleep\n print self.class.name + \" is sleeping.\\n\"\n end\nend\n\nclass Dog < Animal\n def MakeNoise\n return \"Woof!\"\n end\nend\n\nclass Cat < Animal\n def MakeNoise\n return \"Meow!\"\n end\nend\n\nanimals = [Dog.new, Cat.new]\nanimals.each {|a|\n print a.MakeNoise + \"\\n\"\n a.Sleep\n}\n" }, { "answer_id": 137716, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 2, "selected": false, "text": "class Animal\n def MakeNoise\n raise NotImplementedError # I don't remember the exact error class\n end\n def Sleep\n puts self.class.to_s + \" is sleeping.\"\n end\nend\n\nclass Dog < Animal\n def MakeNoise\n return \"Woof!\"\n end\nend\n\nclass Cat < Animal\n def MakeNoise\n return \"Meow!\"\n end\nend\n\nanimals = [Dog.new, Cat.new]\nanimals.each {|a|\n puts a.MakeNoise\n a.Sleep\n}\n" }, { "answer_id": 137916, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 3, "selected": false, "text": "class Animal\n def sleep\n puts \"#{self.class} is sleeping\"\n end\nend\n\nclass Dog < Animal\n def make_noise\n \"Woof!\"\n end\nend\n\nclass Cat < Animal\n def make_noise\n \"Meow!\"\n end\nend\n\n[Dog, Cat].each do |clazz|\n animal = clazz.new\n puts animal.make_noise\n animal.sleep\nend\n" }, { "answer_id": 138131, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 0, "selected": false, "text": "class Animal\n def make_noise; '' end\n def sleep; puts \"#{self.class.name} is sleeping.\" end\nend\n\nclass Dog < Animal; def make_noise; 'Woof!' end end\nclass Cat < Animal; def make_noise; 'Meow!' end end\n\n[Dog.new, Cat.new].each do |animal|\n puts animal.make_noise\n animal.sleep\nend\n" }, { "answer_id": 141457, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 5, "selected": false, "text": "module Animal\n def sleep\n puts self.class.name + \" sleeps\"\n end\nend\n\nclass Dog\n include Animal\n def make_noise\n puts \"Woof\"\n end\nend\n\nclass Cat\n include Animal\n def make_noise\n puts \"Meow\"\n end\nend\n" }, { "answer_id": 144185, "author": "zimbatm", "author_id": 17533, "author_profile": "https://Stackoverflow.com/users/17533", "pm_score": 1, "selected": false, "text": "module Sleeping\n def sleep; puts \"#{self} sleeps\"\nend\n\ndog = \"Dog\"\ndog.extend Sleeping\nclass << dog\n def make_noise; puts \"Woof!\" end\nend\n\nclass Cat\n include Sleeping\n def to_s; \"Cat\" end\n def make_noise; puts \"Meow!\" end\nend\n\n[dog, Cat.new].each do |a|\n a.sleep\n a.make_noise\nend\n" }, { "answer_id": 3121417, "author": "bitTnkr", "author_id": 376528, "author_profile": "https://Stackoverflow.com/users/376528", "pm_score": 1, "selected": false, "text": "Species = [Dog, Cat]\n\nSpecies.each do |specie|\n animal = specie.new # this will create a different specie on each call of new\n print animal.MakeNoise + \"\\n\"\n animal.Sleep\nend\n" }, { "answer_id": 37137558, "author": "itsnikolay", "author_id": 1117851, "author_profile": "https://Stackoverflow.com/users/1117851", "pm_score": 0, "selected": false, "text": "becomes class Animal\n attr_reader :name\n\n def initialize(name = nil)\n @name = name\n end\n\n def make_noise\n ''\n end\n\n def becomes(klass)\n became = klass.new\n became.instance_variables.each do |instance_variable|\n value = self.instance_variable_get(instance_variable)\n became.instance_variable_set(instance_variable, value)\n end\n\n became\n end\nend\n\nclass Dog < Animal\n def make_noise\n 'Woof'\n end\nend\n\nclass Cat < Animal\n def make_noise\n 'Meow'\n end\nend\n\nanimals = [Dog.new('Spot'), Cat.new('Tom')]\n\nanimals.each do |animal|\n new_animal = animal.becomes(Cat)\n puts \"#{animal.class} with name #{animal.name} becomes #{new_animal.class}\"\n puts \"and makes a noise: #{new_animal.make_noise}\"\n puts '----'\nend\n Dog with name Spot becomes Cat\nand makes a noise: Meow\n----\nCat with name Tom becomes Cat\nand makes a noise: Meow\n----\n if RubyOnRails becomes becomes" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
137,679
<p>I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working:</p> <pre><code>RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1 </code></pre>
[ { "answer_id": 137692, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "RewriteCond %{SERVER_PORT} 80\nRewriteCond %{QUERY_STRING} (.+)\nRewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1\n RewriteCond %{SERVER_PORT} 80\nRewriteCond %{QUERY_STRING} (.+)\nRewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1\n" }, { "answer_id": 438964, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 0, "selected": false, "text": "RewriteCond %{SERVER_PORT} 80 80 openid/index.php ." } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
137,721
<p>As title but would like the flexibility to specify how the output xml file will look like. Any free tool available on windows platform that I can use to achieve that? Thanks</p>
[ { "answer_id": 164065, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "import java.io.ByteArrayOutputStream;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport org.dbunit.dataset.DataSetException;\nimport org.dbunit.dataset.IDataSet;\nimport org.dbunit.dataset.excel.XlsDataSet;\nimport org.dbunit.dataset.xml.FlatXmlDataSet;\n\npublic class XlsToXml {\n public static void main(String[] args) { \n try {\n FileInputStream stream = new FileInputStream(args[0]);\n IDataSet dataset = new XlsDataSet(stream);\n OutputStream out = new ByteArrayOutputStream();\n FlatXmlDataSet.write(dataset, out);\n System.out.println(out);\n } catch (Exception e) { \n e.printStackTrace();\n }\n } \n}\n" }, { "answer_id": 11525792, "author": "bassim", "author_id": 403750, "author_profile": "https://Stackoverflow.com/users/403750", "pm_score": 1, "selected": false, "text": "header1;header2;header3\ndata1;data2;data3\ndata4;data5;data6\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n <row>\n <header1>data1</header1>\n <header2>data2</header2>\n <header3>data3</header3>\n </row>\n <row>\n <header1>data4</header1>\n <header2>data5</header2>\n <header3>data6</header3>\n </row>\n</root>\n" }, { "answer_id": 70184442, "author": "Raos", "author_id": 13192320, "author_profile": "https://Stackoverflow.com/users/13192320", "pm_score": 0, "selected": false, "text": "id,name\n1,Roberta\n2,Oliver\n3,Shayna\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<root>\n <row><id>1</id><name>Roberta</name></row>\n <row><id>2</id><name>Oliver</name></row>\n <row><id>3</id><name>Shayna</name></row>\n</root>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14790/" ]
137,730
<p>How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax.</p>
[ { "answer_id": 137751, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "$_FILES move_uploaded_file() $_POST" }, { "answer_id": 137907, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 4, "selected": true, "text": "move_uploaded_file <html>\n<body>\n <form action=\"processStuff.php\" enctype=\"multipart/form-data\" method=\"POST\">\n username: <input type=\"text\" name=\"username\" />\n password: <input type=\"password\" name=\"password\" />\n\n <p>\n <input type=\"file\" name=\"uploadFile[]\" /><br />\n <input type=\"file\" name=\"uploadFile[]\" /><br />\n <input type=\"file\" name=\"uploadFile[]\" /><br />\n <!-- Add as many of these as you want -->\n </p>\n\n <p>\n <input type=\"submit\" />\n </p>\n </form>\n</body>\n</html>\n <pre>\n<?php\n\n echo '<h2>Username & password</h2>'\n echo \"Username: {$_POST['username']}\\nPassword: {$_POST['password']}\";\n echo '<hr />';\n\n echo '<h2>Uploaded files</h2>' \n foreach($_FILES['uploadFile']['tmp_name'] as $i => $tempUploadPath) {\n if (empty($tempUploadPath)) {\n // this <input type=\"file\" /> was \"blank\"... no file selected\n } else {\n // a file was uploaded\n echo '<strong>A file named \"', $_FILES['uploadFile']['name'][$i], \"\\\" was uploaded</strong>\\n\";\n echo \"\\ttemporarily stored at: \", $tempUploadPath, \"\\n\"; \n echo \"\\tmime type: \", $_FILES['uploadFile']['type'][$i], \"\\n\";\n echo \"\\tsize: \", $_FILES['uploadFile']['size'][$i], \" bytes\\n\"; \n echo \"\\terror code\", \n ((empty($_FILES['uploadFile']['size'][$i]) \n ? '<em>no errror</em>' \n : $_FILES['uploadFile']['size'][$i])), \n \"\\n\\n\";\n\n // do something useful with the uploaded file \n // access it via $tempUploadPath and use move_uploaded_file() to move \n // it out of the temp path before you manipulate it in any way!!!!!\n // see http://us3.php.net/features.file-upload\n // and http://us3.php.net/manual/en/function.move-uploaded-file.php\n } \n }\n\n?>\n</pre>\n enctype <form>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
137,753
<p>I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas?</p>
[ { "answer_id": 137762, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "List<KeyValuePair<K,V>>\n" }, { "answer_id": 137772, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "class IndexableDictionary<TItem> : KeyedCollection<string, TItem>\n { Dictionary<TItem, string> keys = new Dictionary<TItem, string>();\n\n protected override string GetKeyForItem(TItem item) { return keys[item];}\n\n public void Add(string key, TItem item) \n { keys[item] = key;\n this.Add(item);\n }\n }\n" }, { "answer_id": 137883, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": " OrderedDictionary od = new OrderedDictionary(); \n od.Add(\"abc\", 1); \n od.Add(\"def\", 2); \n od.Add(\"ghi\", 3); \n od.Add(\"jkl\", 4); \n\n // Can access via index or key value: \n Console.WriteLine(od[1]); \n Console.WriteLine(od[\"def\"]);\n" }, { "answer_id": 138259, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "OrderedDictionary SortedList SortedDictionary ElementAt List<KeyValuePair<TKey, TValue>>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
137,773
<p>In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs:</p> <pre><code>./authpam: /lib/libpam.so.0: no version information available (required by authpam) </code></pre> <p>The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning.</p> <p>I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :(</p> <p>Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem?</p> <p>Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc?</p>
[ { "answer_id": 3387789, "author": "Dieter_be", "author_id": 408644, "author_profile": "https://Stackoverflow.com/users/408644", "pm_score": 2, "selected": false, "text": "root@monitoring:$ echo $LD_LIBRARY_PATH\n\nsu - zenoss\nzenoss@monitoring:/root$ echo $LD_LIBRARY_PATH\n/usr/local/zenoss/python/lib:/usr/local/zenoss/mysql/lib:/usr/local/zenoss/zenoss/lib:/usr/local/zenoss/common/lib::\nzenoss@monitoring:/root$ /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq\n/usr/lib/nagios/plugins/check_nrpe: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libssl.so.0.9.8)\n(...)\nzenoss@monitoring:/root$ LD_LIBRARY_PATH= /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq\n(...)\n" }, { "answer_id": 38851073, "author": "Roman Khimov", "author_id": 165063, "author_profile": "https://Stackoverflow.com/users/165063", "pm_score": 5, "selected": false, "text": "/lib/libpam.so.0 VERDEF authpam VERNEED libpam.so.0 readelf .gnu.version_d .gnu.version_r VERNEED VERDEF" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,775
<p>I've wanted this for fluent interfaces. See, for example <a href="http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/" rel="nofollow noreferrer">this</a> Channel9 discussion. Would probably <a href="http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx" rel="nofollow noreferrer">require</a> also adding indexed properties.</p> <p>What are your thoughts? Would the advantages outweigh the "language clutter"?</p>
[ { "answer_id": 137891, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": -1, "selected": false, "text": "public string MyProperty { get; set; }\n public string get_MyProperty(){ return <some generated variable>; }\npublic string set_MyProperty(string value) { <some generated variable> = value; }\n" }, { "answer_id": 1884696, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 4, "selected": true, "text": "public bool IsInTransaction\n{\n get { return _session.Is().Not.Null && _session.Is().InTransaction; }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22528/" ]
137,783
<p>Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.</p>
[ { "answer_id": 137807, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 4, "selected": false, "text": "function rnd7() {\n do {\n r1 = rnd5() - 1;\n do {\n r2=rnd5() - 1;\n } while (r2 > 1);\n result = r2 * 5 + r1;\n } while (result > 6);\n return result + 1;\n}\n" }, { "answer_id": 137809, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 9, "selected": false, "text": "\nint i;\ndo\n{\n i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25\n} while(i > 21);\n// i is now uniformly random between 1 and 21\nreturn i % 7 + 1; // result is now uniformly random between 1 and 7\n" }, { "answer_id": 137823, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 4, "selected": false, "text": "int ans = 0;\nwhile (ans == 0) \n{\n for (int i=0; i<3; i++) \n {\n while ((r = rand5()) == 3){};\n ans += (r < 3) >> i\n }\n}\n" }, { "answer_id": 137833, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 4, "selected": false, "text": "rand7() = (rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5())%7+1\n value Count Error%\n1 11158 -0.0035\n2 11144 -0.0214\n3 11144 -0.0214\n4 11158 -0.0035\n5 11172 +0.0144\n6 11177 +0.0208\n7 11172 +0.0144\n n Error%\n10 +/- 1e-3,\n12 +/- 1e-4,\n14 +/- 1e-5,\n16 +/- 1e-6,\n...\n28 +/- 3e-11\n p[x,n] output=x n rand5 p[1,1] ... p[5,1] = 1\n p[6,1] ... p[7,1] = 0\n\n p[1,n] = p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1]\n p[2,n] = p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1]\n p[3,n] = p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1]\n p[4,n] = p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1]\n p[5,n] = p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1]\n p[6,n] = p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1]\n p[7,n] = p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1]\n" }, { "answer_id": 137862, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "int randbit( void )\n{\n while( 1 )\n {\n int r = rand5();\n if( r <= 4 ) return(r & 1);\n }\n}\n\nint randint( int nbits )\n{\n int result = 0;\n while( nbits-- )\n {\n result = (result<<1) | randbit();\n }\n return( result );\n}\n\nint rand7( void )\n{\n while( 1 )\n {\n int r = randint( 3 ) + 1;\n if( r <= 7 ) return( r );\n }\n}\n" }, { "answer_id": 324595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<?php\nfunction random_5(){\n return rand(1,5);\n}\n\n\nfunction random_7(){\n $total = 0;\n\n for($i=0;$i<7;$i++){\n $total += random_5();\n }\n\n return ($total%7)+1; \n}\n\necho random_7();\n?>\n" }, { "answer_id": 445623, "author": "jason", "author_id": 45914, "author_profile": "https://Stackoverflow.com/users/45914", "pm_score": 4, "selected": false, "text": "public static int random_7(Random rg) {\n int returnValue = 0;\n while (returnValue == 0) {\n for (int i = 1; i <= 3; i++) {\n returnValue = (returnValue << 1) + SimulateFairCoin(rg);\n }\n }\n return returnValue;\n}\n\nprivate static int SimulateFairCoin(Random rg) {\n while (true) {\n int flipOne = random_5_mod_2(rg);\n int flipTwo = random_5_mod_2(rg);\n\n if (flipOne == 0 && flipTwo == 1) {\n return 0;\n }\n else if (flipOne == 1 && flipTwo == 0) {\n return 1;\n }\n }\n}\n\nprivate static int random_5_mod_2(Random rg) {\n return random_5(rg) % 2;\n}\n\nprivate static int random_5(Random rg) {\n return rg.Next(5) + 1;\n} \n" }, { "answer_id": 806137, "author": "Joshua Fox", "author_id": 39242, "author_profile": "https://Stackoverflow.com/users/39242", "pm_score": 3, "selected": false, "text": "from random import randint\nsum = 7\nwhile sum >= 7:\n first = randint(0,5) \n toadd = 9999\n while toadd>1:\n toadd = randint(0,5)\n if toadd:\n sum = first+5\n else:\n sum = first\n\nassert 7>sum>=0 \nprint sum\n" }, { "answer_id": 807033, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 5, "selected": false, "text": "int rand7() {\n i = 5 * rand5() + rand5();\n max = 25;\n //i is uniform among {0 ... max-1}\n while(i < max%7) {\n //i is uniform among {0 ... (max%7 - 1)}\n i *= 5;\n i += rand5(); //i is uniform {0 ... (((max%7)*5) - 1)}\n max %= 7;\n max *= 5; //once again, i is uniform among {0 ... max-1}\n }\n return(i%7);\n}\n max x = 2 * 21/25\n + 3 * 4/25 * 14/20\n + 4 * 4/25 * 6/20 * 28/30\n + 5 * 4/25 * 6/20 * 2/30 * 7/10\n + 6 * 4/25 * 6/20 * 2/30 * 3/10 * 14/15\n + (6+x) * 4/25 * 6/20 * 2/30 * 3/10 * 1/15\nx = about 2.21 calls to rand5()\n" }, { "answer_id": 807434, "author": "Patrick Hogan", "author_id": 4065, "author_profile": "https://Stackoverflow.com/users/4065", "pm_score": -1, "selected": false, "text": "int rand5()\n{\n return (rand() % 5) + 1;\n}\n\nint rand25()\n{ \n return (5 * (rand5() - 1) + rand5());\n}\n\nint rand625()\n{\n return (25 * (rand25() - 1) + rand25());\n}\n\nint rand7()\n{\n return ((625 * (rand625() - 1) + rand625()) - 1) % 7 + 1;\n}\n" }, { "answer_id": 808183, "author": "mangokun", "author_id": 59389, "author_profile": "https://Stackoverflow.com/users/59389", "pm_score": -1, "selected": false, "text": "int rand7()\n{\n int zero_one_or_two = ( rand5() + rand5() - 1 ) % 3 ;\n return rand5() + zero_one_or_two ;\n}\n" }, { "answer_id": 808199, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": -1, "selected": false, "text": "int random1_to_7()\n{\n return (random1_to_5() * 7) / 5; \n}\n" }, { "answer_id": 808267, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": -1, "selected": false, "text": "#!/usr/bin/env ruby\nclass Integer\n def rand7\n rand(6)+1\n end\nend\n\ndef rand5\n rand(4)+1\nend\n\nx = rand5() # x => int between 1 and 5\n\ny = x.rand7() # y => int between 1 and 7\n" }, { "answer_id": 816738, "author": "Peter Stegnar", "author_id": 99422, "author_profile": "https://Stackoverflow.com/users/99422", "pm_score": -1, "selected": false, "text": "return (Rand5() + Rand5()) % 7 + 1;\n private static int Rand7WithRand5()\n{\n //PUT YOU FAVOURITE ALGORITHM HERE//\n\n //1. Stackoverflow winner\n int i;\n do\n {\n i = 5 * (Rand5() - 1) + Rand5(); // i is now uniformly random between 1 and 25\n } while (i > 21);\n // i is now uniformly random between 1 and 21\n return i % 7 + 1;\n\n //My 2 cents\n //return (Rand5() + Rand5()) % 7 + 1;\n}\n random.Next(1, 8)" }, { "answer_id": 818817, "author": "James McMahon", "author_id": 20774, "author_profile": "https://Stackoverflow.com/users/20774", "pm_score": 3, "selected": false, "text": "import random\n\ndef rand5():\n return random.randint(1, 5)\n\ndef rand7():\n while True:\n r = 5 * (rand5() - 1) + rand5()\n #r is now uniformly random between 1 and 25\n if (r <= 21):\n break\n #result is now uniformly random between 1 and 7\n return r % 7 + 1\n" }, { "answer_id": 832809, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "rand(5)+rand(5)... import random\nx = []\nfor i in range (0,7):\n x.append (0)\nt = 0\ntt = 0\nfor i in range (0,700000):\n ########################################\n ##### qq.py #####\n r = int (random.random () * 5)\n t = (t + r) % 7\n ########################################\n ##### qq_notsogood.py #####\n #r = 20\n #while r > 6:\n #r = int (random.random () * 5)\n #r = r + int (random.random () * 5)\n #t = r\n ########################################\n x[t] = x[t] + 1\n tt = tt + 1\nhigh = x[0]\nlow = x[0]\nfor i in range (0,7):\n print \"%d: %7d %.5f\" % (i, x[i], 100.0 * x[i] / tt)\n if x[i] < low:\n low = x[i]\n if x[i] > high:\n high = x[i]\ndiff = high - low\nprint \"Variation = %d (%.5f%%)\" % (diff, 100.0 * diff / tt)\n pax$ python qq.py\n0: 99908 14.27257\n1: 100029 14.28986\n2: 100327 14.33243\n3: 100395 14.34214\n4: 99104 14.15771\n5: 99829 14.26129\n6: 100408 14.34400\nVariation = 1304 (0.18629%)\n\npax$ python qq.py\n0: 99547 14.22100\n1: 100229 14.31843\n2: 100078 14.29686\n3: 99451 14.20729\n4: 100284 14.32629\n5: 100038 14.29114\n6: 100373 14.33900\nVariation = 922 (0.13171%)\n\npax$ python qq.py\n0: 100481 14.35443\n1: 99188 14.16971\n2: 100284 14.32629\n3: 100222 14.31743\n4: 99960 14.28000\n5: 99426 14.20371\n6: 100439 14.34843\nVariation = 1293 (0.18471%)\n rand(5)+rand(5) pax$ python qq_notsogood.py\n0: 31756 4.53657\n1: 63304 9.04343\n2: 95507 13.64386\n3: 127825 18.26071\n4: 158851 22.69300\n5: 127567 18.22386\n6: 95190 13.59857\nVariation = 127095 (18.15643%)\n\npax$ python qq_notsogood.py\n0: 31792 4.54171\n1: 63637 9.09100\n2: 95641 13.66300\n3: 127627 18.23243\n4: 158751 22.67871\n5: 126782 18.11171\n6: 95770 13.68143\nVariation = 126959 (18.13700%)\n\npax$ python qq_notsogood.py\n0: 31955 4.56500\n1: 63485 9.06929\n2: 94849 13.54986\n3: 127737 18.24814\n4: 159687 22.81243\n5: 127391 18.19871\n6: 94896 13.55657\nVariation = 127732 (18.24743%)\n rand7... import random\n\n# rand5() returns 0 through 4 inclusive.\n\ndef rand5():\n return int (random.random () * 5)\n\n# rand7() generator returns 0 through 6 inclusive (using rand5()).\n\ndef rand7():\n rand7ret = 0\n while True:\n rand7ret = (rand7ret + rand5()) % 7\n yield rand7ret\n\n# Number of test runs.\n\ncount = 700000\n\n# Work out distribution.\n\ndistrib = [0,0,0,0,0,0,0]\nrgen =rand7()\nfor i in range (0,count):\n r = rgen.next()\n distrib[r] = distrib[r] + 1\n\n# Print distributions and calculate variation.\n\nhigh = distrib[0]\nlow = distrib[0]\nfor i in range (0,7):\n print \"%d: %7d %.5f\" % (i, distrib[i], 100.0 * distrib[i] / count)\n if distrib[i] < low:\n low = distrib[i]\n if distrib[i] > high:\n high = distrib[i]\ndiff = high - low\nprint \"Variation = %d (%.5f%%)\" % (diff, 100.0 * diff / count)\n" }, { "answer_id": 842183, "author": "Rob McAfee", "author_id": 103834, "author_profile": "https://Stackoverflow.com/users/103834", "pm_score": 9, "selected": false, "text": "int rand7()\n{\n int vals[5][5] = {\n { 1, 2, 3, 4, 5 },\n { 6, 7, 1, 2, 3 },\n { 4, 5, 6, 7, 1 },\n { 2, 3, 4, 5, 6 },\n { 7, 0, 0, 0, 0 }\n };\n\n int result = 0;\n while (result == 0)\n {\n int i = rand5();\n int j = rand5();\n result = vals[i-1][j-1];\n }\n return result;\n}\n" }, { "answer_id": 842343, "author": "Ivan", "author_id": 103673, "author_profile": "https://Stackoverflow.com/users/103673", "pm_score": 4, "selected": false, "text": "I m O m L(m) O a1, a2, a3,... -> a1+5*a2+5^2*a3+.. O m choose n s.t. 5^m-7^n=c c>0 1 5^m 7^n 7^n L(m) m (log5/log7) .82m 5^m-7^n=c 1 5^m 7^n 5^m-7^n=c 0 (5^m)-1 7^n 5^m-7^n T7(X) random(1-7) X 5^m=7^n0+7^n1+7^n2+...+7^nr+s, s<7 T7(5^m)=n0x7^n0/5^m + ((5^m-7^n0)/5^m) T7(5^m-7^n0) 5^m-7^n0 (5^m-7^n0)/5^m) T7(5^m) = n0x7^n0/5^m + n1x7^n1/5^m + ... + nrx7^nr/5^m = (n0x7^n0 + n1x7^n1 + ... + nrx7^nr)/5^m\n L(m)=T7(5^m)=(n0x7^n0 + n1x7^n1 + ... + nrx7^nr)/(7^n0+7^n1+7^n2+...+7^nr+s)\n If 5^m has 7-ary representation `a0+a1*7 + a2*7^2 + a3*7^3+...+ar*7^r\nThen L(m) = (a1*7 + 2a2*7^2 + 3a3*7^3+...+rar*7^r)/(a0+a1*7 + a2*7^2 + a3*7^3+...+ar*7^r)\n 5^m=7^n+s s<7 T7(5^m) = nx(7^n)/(7^n+s) = n+o(1) = m (Log5/Log7)+o(1) Then T7(5^m) = 1x(k.7)/(k.7+s) = 1+o(1)\n T7(5^m) = m (Log5/Log7)+e(m)\n e(m) = o(1) e(m)=o(m) 5^m m" }, { "answer_id": 859341, "author": "ShuggyCoUk", "author_id": 12748, "author_profile": "https://Stackoverflow.com/users/12748", "pm_score": 2, "selected": false, "text": "public class SevenFromFive\n{\n public SevenFromFive()\n {\n // this outputs a uniform ditribution but for some reason including it \n // screws up the output distribution\n // open question Why?\n this.fifth = new ProbabilityCondensor(5, b => {});\n this.eigth = new ProbabilityCondensor(8, AddEntropy);\n } \n\n private static Random r = new Random();\n private static uint Rand5()\n {\n return (uint)r.Next(0,5);\n }\n\n private class ProbabilityCondensor\n {\n private readonly int samples;\n private int counter;\n private int store;\n private readonly Action<bool> output;\n\n public ProbabilityCondensor(int chanceOfTrueReciprocal,\n Action<bool> output)\n {\n this.output = output;\n this.samples = chanceOfTrueReciprocal - 1; \n }\n\n public void Add(bool bit)\n {\n this.counter++;\n if (bit)\n this.store++; \n if (counter == samples)\n {\n bool? e;\n if (store == 0)\n e = false;\n else if (store == 1)\n e = true;\n else\n e = null;// discard for now \n counter = 0;\n store = 0;\n if (e.HasValue)\n output(e.Value);\n }\n }\n }\n\n ulong buffer = 0;\n const ulong Mask = 7UL;\n int bitsAvail = 0;\n private readonly ProbabilityCondensor fifth;\n private readonly ProbabilityCondensor eigth;\n\n private void AddEntropy(bool bit)\n {\n buffer <<= 1;\n if (bit)\n buffer |= 1; \n bitsAvail++;\n }\n\n private void AddTwoBitsEntropy(uint u)\n {\n buffer <<= 2;\n buffer |= (u & 3UL); \n bitsAvail += 2;\n }\n\n public uint Rand7()\n {\n uint selection; \n do\n {\n while (bitsAvail < 3)\n {\n var x = Rand5();\n if (x < 4)\n {\n // put the two low order bits straight in\n AddTwoBitsEntropy(x);\n fifth.Add(false);\n }\n else\n { \n fifth.Add(true);\n }\n }\n // read 3 bits\n selection = (uint)((buffer & Mask));\n bitsAvail -= 3; \n buffer >>= 3;\n if (selection == 7)\n eigth.Add(true);\n else\n eigth.Add(false);\n }\n while (selection == 7); \n return selection;\n }\n}\n" }, { "answer_id": 891304, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 7, "selected": false, "text": "rand5() rand7() rand5() rand7() rand5() rand7() rand5() rand7() rand5() rand7() a a a i rand5() i i a b b - a rand7() rand7() rand5() rand5() rand5() k k k rand7() rand5() import random\n\nrand5_calls = 0\ndef rand5():\n global rand5_calls\n rand5_calls += 1\n return random.randint(0, 4)\n\ndef rand7_gen():\n state = 0\n pow5 = 1\n pow7 = 7\n while True:\n if state / pow5 == (state + pow7) / pow5:\n result = state / pow5\n state = (state - result * pow5) * 7\n pow7 *= 7\n yield result\n else:\n state = 5 * state + pow7 * rand5()\n pow5 *= 5\n\nif __name__ == '__main__':\n r7 = rand7_gen()\n N = 10000\n x = list(next(r7) for i in range(N))\n distr = [x.count(i) for i in range(7)]\n expmean = N / 7.0\n expstddev = math.sqrt(N * (1.0/7.0) * (6.0/7.0))\n\n print '%d TRIALS' % N\n print 'Expected mean: %.1f' % expmean\n print 'Expected standard deviation: %.1f' % expstddev\n print\n print 'DISTRIBUTION:'\n for i in range(7):\n print '%d: %d (%+.3f stddevs)' % (i, distr[i], (distr[i] - expmean) / expstddev)\n print\n print 'Calls to rand5: %d (average of %f per call to rand7)' % (rand5_calls, float(rand5_calls) / N)\n rand7_gen() next(r7) rand5() rand7() pow5 pow7 rand5() rand7()" }, { "answer_id": 1397428, "author": "Chris Suter", "author_id": 116931, "author_profile": "https://Stackoverflow.com/users/116931", "pm_score": 3, "selected": false, "text": "static struct rand_buffer {\n unsigned v, count;\n} buf2, buf3;\n\nvoid push (struct rand_buffer *buf, unsigned n, unsigned v)\n{\n buf->v = buf->v * n + v;\n ++buf->count;\n}\n\n#define PUSH(n, v) push (&buf##n, n, v)\n\nint rand16 (void)\n{\n int v = buf2.v & 0xf;\n buf2.v >>= 4;\n buf2.count -= 4;\n return v;\n}\n\nint rand9 (void)\n{\n int v = buf3.v % 9;\n buf3.v /= 9;\n buf3.count -= 2;\n return v;\n}\n\nint rand7 (void)\n{\n if (buf3.count >= 2) {\n int v = rand9 ();\n\n if (v < 7)\n return v % 7 + 1;\n\n PUSH (2, v - 7);\n }\n\n for (;;) {\n if (buf2.count >= 4) {\n int v = rand16 ();\n\n if (v < 14) {\n PUSH (2, v / 7);\n return v % 7 + 1;\n }\n\n PUSH (2, v - 14);\n }\n\n // Get a number between 0 & 25\n int v = 5 * (rand5 () - 1) + rand5 () - 1;\n\n if (v < 21) {\n PUSH (3, v / 7);\n return v % 7 + 1;\n }\n\n v -= 21;\n PUSH (2, v & 1);\n PUSH (2, v >> 1);\n }\n}\n" }, { "answer_id": 1441828, "author": "Ashwin", "author_id": 174553, "author_profile": "https://Stackoverflow.com/users/174553", "pm_score": 2, "selected": false, "text": "int R7() {\n do {\n x = R8();\n } while (x > 6)\n return x;\n}\n" }, { "answer_id": 1700617, "author": "Ante", "author_id": 206844, "author_profile": "https://Stackoverflow.com/users/206844", "pm_score": 3, "selected": false, "text": "int random7() {\n return random5() + (random5() % 3);\n}\n" }, { "answer_id": 1850414, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "$num = 0;\n$possibilities = 1;\n\nsub rand7\n{\n while( $possibilities < 7 )\n {\n $num = $num * 5 + int(rand(5));\n $possibilities *= 5;\n }\n my $result = $num % 7;\n $num = int( $num / 7 );\n $possibilities /= 7;\n return $result;\n}\n" }, { "answer_id": 1851459, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 2, "selected": false, "text": "import numpy\ndef rand1_5():\n return numpy.random.randint(5)+1\n\ndef rand1_7():\n q = 0\n for i in xrange(7): q+= rand1_5()\n return q%7 + 1\n" }, { "answer_id": 1972518, "author": "Kugel", "author_id": 177591, "author_profile": "https://Stackoverflow.com/users/177591", "pm_score": 2, "selected": false, "text": "def rand7:\n seed += 1\n if seed >= 7:\n seed = 0\n yield seed\n" }, { "answer_id": 2420737, "author": "Rex Kerr", "author_id": 247533, "author_profile": "https://Stackoverflow.com/users/247533", "pm_score": 2, "selected": false, "text": "abstract class RNG {\n def apply(): Int\n}\n\nclass Random5 extends RNG {\n val rng = new scala.util.Random\n var count = 0\n def apply() = { count += 1 ; rng.nextInt(5) }\n}\n\nclass FiveSevener(five: RNG) {\n val sevens = new Array[Int](9)\n var nsevens = 0\n val to9 = 40353607;\n val to8 = 5764801;\n val to7 = 823543;\n def loadSevens(value: Int, count: Int) {\n nsevens = 0;\n var remaining = value;\n while (nsevens < count) {\n sevens(nsevens) = remaining % 7\n remaining /= 7\n nsevens += 1\n }\n }\n def loadSevens {\n var fivepow11 = 0;\n var i=0\n while (i<11) { i+=1 ; fivepow11 = five() + fivepow11*5 }\n if (fivepow11 < to9) { loadSevens(fivepow11 , 9) ; return }\n fivepow11 -= to9\n if (fivepow11 < to8) { loadSevens(fivepow11 , 8) ; return }\n fivepow11 -= to8\n if (fivepow11 < 3*to7) loadSevens(fivepow11 % to7 , 7)\n else loadSevens\n }\n def apply() = {\n if (nsevens==0) loadSevens\n nsevens -= 1\n sevens(nsevens)\n }\n}\n scala> val five = new Random5\nfive: Random5 = Random5@e9c592\n\nscala> val seven = new FiveSevener(five)\nseven: FiveSevener = FiveSevener@143c423\n\nscala> val counts = new Array[Int](7)\ncounts: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0)\n\nscala> var i=0 ; while (i < 100000000) { counts( seven() ) += 1 ; i += 1 }\ni: Int = 100000000\n\nscala> counts\nres0: Array[Int] = Array(14280662, 14293012, 14281286, 14284836, 14287188,\n14289332, 14283684)\n\nscala> five.count\nres1: Int = 125902876\n" }, { "answer_id": 2667241, "author": "philcolbourn", "author_id": 275052, "author_profile": "https://Stackoverflow.com/users/275052", "pm_score": 3, "selected": false, "text": "(5a + rand5) % 7 = (k*7 + (5a%7) + rand5) % 7 = ( (5a%7) + rand5) % 7\n int rand7(){\n static int a=0;\n static int e=0;\n int r;\n a = a * 5 + rand5();\n e = e + 5; // added 5/7ths of a rand7 number\n if ( e<7 ){\n a = a * 5 + rand5();\n e = e + 5; // another 5/7ths\n }\n r = a % 7;\n e = e - 7; // removed a rand7 number\n a = a % 7;\n return r;\n}\n" }, { "answer_id": 2919491, "author": "cartonn", "author_id": 350668, "author_profile": "https://Stackoverflow.com/users/350668", "pm_score": 2, "selected": false, "text": "0) you have a number in range 1-5\n1) subtract 1 to make it in range 0-4\n2) multiply by (7-1)/(5-1) to make it in range 0-6\n3) add 1 to increment the range: Now your result is in between 1-7\n" }, { "answer_id": 3547853, "author": "chiccodoro", "author_id": 55787, "author_profile": "https://Stackoverflow.com/users/55787", "pm_score": 3, "selected": false, "text": "int rand7 ( void )\n{\n return 4; // this number has been calculated using\n // rand5() and is in the range 1..7\n}\n" }, { "answer_id": 3761993, "author": "fredoverflow", "author_id": 252000, "author_profile": "https://Stackoverflow.com/users/252000", "pm_score": 3, "selected": false, "text": "unsigned rand5()\n{\n return rand() % 5;\n}\n\nunsigned rand7()\n{\n int r;\n\n do\n {\n r = rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n } while (r > 15623);\n\n return r / 2232;\n}\n" }, { "answer_id": 3895983, "author": "user470894", "author_id": 470894, "author_profile": "https://Stackoverflow.com/users/470894", "pm_score": 2, "selected": false, "text": "function Rand7\n put 200 into x\n repeat while x > 118\n put ((random(5)-1) * 25) + ((random(5)-1) * 5) + (random(5)-1) into x\n end repeat\n return (x mod 7) + 1\nend Rand7\n" }, { "answer_id": 4179748, "author": "Anand", "author_id": 507613, "author_profile": "https://Stackoverflow.com/users/507613", "pm_score": 5, "selected": false, "text": "public static int random_7() {\n int returnValue = 0;\n while (returnValue == 0) {\n for (int i = 1; i <= 3; i++) {\n returnValue = (returnValue << 1) + random_5_output_2();\n }\n }\n return returnValue;\n}\n\nprivate static int random_5_output_2() {\n while (true) {\n int flip = random_5();\n\n if (flip < 3) {\n return 0;\n }\n else if (flip > 3) {\n return 1;\n }\n }\n}\n" }, { "answer_id": 4316537, "author": "pas1311", "author_id": 525505, "author_profile": "https://Stackoverflow.com/users/525505", "pm_score": 2, "selected": false, "text": "int getOneToSeven(){\n int added = 0;\n for(int i = 1; i<=7; i++){\n added += getOneToFive();\n }\n return (added)%7+1;\n}\n" }, { "answer_id": 4327883, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 2, "selected": false, "text": "def r5tor7():\n while True:\n cand = (5 * r5()) + r5()\n if cand < 27:\n return cand\n cand from collections import defaultdict\n\ndef r5_outcome(n):\n if not n:\n yield []\n else:\n for i in range(1, 6):\n for j in r5_outcome(n-1):\n yield [i] + j\n\ndef test_r7():\n d = defaultdict(int)\n for x in r5_outcome(2):\n s = sum([x[i] * 5**i for i in range(len(x))])\n if s < 27:\n d[s] += 1\n print len(d), d\n r5_outcome(2)" }, { "answer_id": 4341713, "author": "maxchengcn", "author_id": 528789, "author_profile": "https://Stackoverflow.com/users/528789", "pm_score": 2, "selected": false, "text": "extern int r5();\n\nint r7() {\n return ((r5() & 0x01) << 2 ) | ((r5() & 0x01) << 1 ) | (r5() & 0x01);\n}\n" }, { "answer_id": 4720026, "author": "DeWan", "author_id": 579349, "author_profile": "https://Stackoverflow.com/users/579349", "pm_score": 2, "selected": false, "text": "package CareerCup;\n\npublic class RangeTransform {\n static int counter = (int)(Math.random() * 5 + 1);\n\n private int func() {\n return (int) (Math.random() * 5 + 1);\n }\n\n private int getMultiplier() {\n return counter % 5 + 1;\n }\n\n public int rangeTransform() {\n counter++;\n int count = getMultiplier();\n int mult = func() + 5 * count;\n System.out.println(\"Mult is : \" + 5 * count);\n return (mult) % 7 + 1;\n }\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n RangeTransform rangeTransform = new RangeTransform();\n for (int i = 0; i < 35; i++)\n System.out.println(\"Val is : \" + rangeTransform.rangeTransform());\n }\n}\n" }, { "answer_id": 4813754, "author": "Sam", "author_id": 591809, "author_profile": "https://Stackoverflow.com/users/591809", "pm_score": 2, "selected": false, "text": "i = rand5() + rand5() + (rand5() - 1) //Random number between 1 and 14\n\ni = i % 7 + 1;\n" }, { "answer_id": 5328966, "author": "Rob Leclerc", "author_id": 606612, "author_profile": "https://Stackoverflow.com/users/606612", "pm_score": 2, "selected": false, "text": "0 000\n1 001\n2 010\n3 011\n4 100\n5 101\n6 110\n7 111\n" }, { "answer_id": 5354261, "author": "ekr", "author_id": 666278, "author_profile": "https://Stackoverflow.com/users/666278", "pm_score": 2, "selected": false, "text": "rand25() =5*(rand5()-1) + rand5()\n\nrand7() { \n while(true) {\n int r = rand25();\n if (r < 21) return r%3; \n }\n}\n" }, { "answer_id": 5508688, "author": "Eric Rowell", "author_id": 686858, "author_profile": "https://Stackoverflow.com/users/686858", "pm_score": 1, "selected": false, "text": "function rand7() {\n\n var returnVal = 4;\n\n for (var n=0; n<3; n++) {\n var rand = rand5();\n\n if (rand==1||rand==2){\n returnVal+=1;\n }\n else if (rand==3||rand==4) {\n returnVal-=1;\n }\n }\n\n return returnVal;\n}\n" }, { "answer_id": 5509037, "author": "dqhendricks", "author_id": 512922, "author_profile": "https://Stackoverflow.com/users/512922", "pm_score": 2, "selected": false, "text": "function rand1to7() {\n do {\n $output_value = 0;\n for ($i = 0; $i < 28; $i++) {\n $output_value += rand1to5();\n }\n while ($output_value != 140);\n $output_value -= 12;\n return floor($output_value / 16);\n}\n" }, { "answer_id": 5537186, "author": "Ben", "author_id": 690910, "author_profile": "https://Stackoverflow.com/users/690910", "pm_score": 2, "selected": false, "text": "rand int i = rand(5) ^ (rand(5) & 2);\n rand(5) 1b 10b 11b 100b 101b" }, { "answer_id": 10035519, "author": "Yatharth Agarwal", "author_id": 1292652, "author_profile": "https://Stackoverflow.com/users/1292652", "pm_score": 0, "selected": false, "text": "def ranndomNo7():\n import random\n rand5 = random.randint(4) # Produces range: [0, 4]\n rand7 = int(rand5 / 5 * 7) # /5, *7, +0.5 and floor()\n return rand7\n" }, { "answer_id": 12585928, "author": "coder", "author_id": 1122689, "author_profile": "https://Stackoverflow.com/users/1122689", "pm_score": 0, "selected": false, "text": "int rand7()\n{\n return ( rand5() + (rand5()%3) );\n}\n" }, { "answer_id": 14528515, "author": "leonbloy", "author_id": 277304, "author_profile": "https://Stackoverflow.com/users/277304", "pm_score": 1, "selected": false, "text": "public class RandomUnif {\n\n public static final int BASE_NUMBER = 5;\n\n private static Random rand = new Random();\n\n /** given generator, returns uniform integer in the range 0.. BASE_NUMBER-1\n public static int randomBASE() {\n return rand.nextInt(BASE_NUMBER);\n }\n\n /** returns uniform integer in the range 0..n-1 using randomBASE() */\n public static int randomUnif(int n) {\n int rand, factor;\n if( n <= 1 ) return 0;\n else if( n == BASE_NUMBER ) return randomBASE();\n if( n < BASE_NUMBER ) {\n factor = BASE_NUMBER / n;\n do\n rand = randomBASE() / factor;\n while(rand >= n);\n return rand;\n } else {\n factor = (n - 1) / BASE_NUMBER + 1;\n do {\n rand = factor * randomBASE() + randomUnif(factor);\n } while(rand >= n);\n return rand;\n }\n }\n}\n n calls\n 2 1.250 \n 3 1.644 \n 4 1.252 \n 5 1.000 \n 6 3.763 \n 7 3.185 \n 8 2.821 \n 9 2.495 \n10 2.250 \n11 3.646 \n12 3.316 \n13 3.060 \n14 2.853 \n15 2.650 \n16 2.814 \n17 2.644 \n18 2.502 \n19 2.361 \n20 2.248 \n21 2.382 \n22 2.277 \n23 2.175 \n24 2.082 \n25 2.000 \n26 5.472 \n27 5.280 \n28 5.119 \n29 4.899 \n" }, { "answer_id": 14630267, "author": "bernard paulus", "author_id": 1610553, "author_profile": "https://Stackoverflow.com/users/1610553", "pm_score": 2, "selected": false, "text": "rand(n) -> [0, n - 1] [0-6] ran5() p(x) = 5 / 35 = 1 / 7 for all x in [0, 6]\n ran5() [0-6] def rand_range_transform(rands):\n \"\"\"\n returns a uniform random number in [0, len(rands) - 1]\n if all r in rands are independent random numbers from the same uniform distribution\n \"\"\"\n return sum((x + i) for i, x in enumerate(rands)) % len(rands) # a single modulo outside the sum is enough in modulo arithmetic\n rand5 = lambda : random.randrange(5)\n\ndef rand7():\n return rand_range_transform([rand5() for _ in range(7)])\n rand7() max: 6 min: 0 mean: 2.99711428571 std: 2.00194697049\n0: 10019\n1: 10016\n2: 10071\n3: 10044\n4: 9775\n5: 10042\n6: 10033\n rand5() rand7()" }, { "answer_id": 15148624, "author": "William Pursell", "author_id": 140750, "author_profile": "https://Stackoverflow.com/users/140750", "pm_score": 1, "selected": false, "text": "int rand_7() { return rand_5(); }\n 1) examine the rand_5 function\n2) understand how it works\n3) profit\n" }, { "answer_id": 18573436, "author": "user2713461", "author_id": 2713461, "author_profile": "https://Stackoverflow.com/users/2713461", "pm_score": 0, "selected": false, "text": "int j = ( rand5()*2 + 4 ) % 7 + 1;\n" }, { "answer_id": 20668588, "author": "dansalmo", "author_id": 1355221, "author_profile": "https://Stackoverflow.com/users/1355221", "pm_score": 1, "selected": false, "text": "function rand7() {\n while (true) { //lowest base 5 random number > 7 reduces memory\n int num = (rand5()-1)*5 + rand5()-1;\n if (num < 21) // improves performance\n return 1 + num%7;\n }\n}\n from random import randint\ndef rand7():\n while(True):\n num = (randint(1, 5)-1)*5 + randint(1, 5)-1\n if num < 21:\n return 1 + num%7\n >>> rnums = []\n>>> for _ in range(100000):\n rnums.append(rand7())\n>>> {n:rnums.count(n) for n in set(rnums)}\n{1: 15648, 2: 15741, 3: 15681, 4: 15847, 5: 15642, 6: 15806, 7: 15635}\n" }, { "answer_id": 20957658, "author": "invisal", "author_id": 1332934, "author_profile": "https://Stackoverflow.com/users/1332934", "pm_score": 1, "selected": false, "text": "int rand7() {\n int m = 1203068;\n int r = (m >> (rand5() - 1) * 5 + rand5() - 1) & 7;\n\n return (r > 0) ? r : rand7();\n}\n" }, { "answer_id": 21252243, "author": "Martin", "author_id": 2306145, "author_profile": "https://Stackoverflow.com/users/2306145", "pm_score": 2, "selected": false, "text": "int random7() {\n range = 1;\n remainder = 0;\n\n while (1) {\n remainder = remainder * 5 + random5() - 1;\n range = range * 5;\n\n limit = range - (range % 7);\n if (remainder < limit) return (remainder % 7) + 1;\n\n remainder = remainder % 7;\n range = range % 7;\n }\n}\n r5=5;\nnum=random5()-1;\nwhile (1) {\n num=num*5+random5()-1;\n r5=r5*5;\n r7=r5-r5%7;\n if (num<r7) return num%7+1;\n}\n" }, { "answer_id": 22467753, "author": "jantimon", "author_id": 159319, "author_profile": "https://Stackoverflow.com/users/159319", "pm_score": 1, "selected": false, "text": "// Returns 1-5\nvar rnd5 = function(){\n return parseInt(Math.random() * 5, 10) + 1;\n}\n// Helper\nvar lastEdge = 0;\n// Returns 1-7\nvar rnd7 = function () {\n var map = [\n [ 1, 2, 3, 4, 5 ],\n [ 6, 7, 1, 2, 3 ],\n [ 4, 5, 6, 7, 1 ],\n [ 2, 3, 4, 5, 6 ],\n [ 7, 0, 0, 0, 0 ]\n ];\n var result = map[rnd5() - 1][rnd5() - 1];\n if (result > 0) {\n return result;\n }\n lastEdge++;\n if (lastEdge > 7 ) {\n lastEdge = 1;\n }\n return lastEdge;\n};\n\n// Test the a uniform distribution\nresults = {}; for(i=0; i < 700000;i++) { var rand = rnd7(); results[rand] = results[rand] ? results[rand] + 1 : 1;} \nconsole.log(results)\n [1: 99560, 2: 99932, 3: 100355, 4: 100262, 5: 99603, 6: 100062, 7: 100226]" }, { "answer_id": 22722546, "author": "Graham Toal", "author_id": 210830, "author_profile": "https://Stackoverflow.com/users/210830", "pm_score": 1, "selected": false, "text": "int rand7(void)\n{\n static int startpos = 0;\n startpos = (startpos+5) % (5*7);\n return (((startpos + rand5()-1)%7)+1);\n}\n" }, { "answer_id": 23854520, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": 1, "selected": false, "text": "rand5() rand7() rand5 float rand7()\n{\n return (rand5() * 7.0) / 5.0 ;\n}\n rand5 int rand7()\n{\n static int prev = 1;\n\n int cur = rand5();\n\n int r = cur * prev; // 1-25\n\n float f = r / 4.0; // 0.25-6.25\n\n f = f - 0.25; // 0-6\n\n f = f + 1.0; // 1-7\n\n prev = cur;\n\n return (int)f;\n}\n rand7(i) ~ rand5(i) * rand5(i-1) rand7(0) ~ rand5(0) * 1" }, { "answer_id": 25703358, "author": "user515430", "author_id": 515430, "author_profile": "https://Stackoverflow.com/users/515430", "pm_score": 1, "selected": false, "text": "#include <functional>\n#include <iostream>\n#include <ostream>\n#include <random>\n\nint main()\n{\n std::random_device rd;\n unsigned long seed = rd();\n std::cout << \"seed = \" << seed << std::endl;\n\n std::mt19937 engine(seed);\n\n std::uniform_int_distribution<> dist(1, 5);\n auto rand5 = std::bind(dist, engine);\n\n const int n = 20;\n for (int i = 0; i != n; ++i)\n {\n std::cout << rand5() << \" \";\n }\n std::cout << std::endl;\n\n // Use a lambda expression to define rand7\n auto rand7 = [&rand5]()->int\n {\n for (int result = 0; ; result = 0)\n {\n // Take advantage of the fact that\n // 5**6 = 15625 = 15624 + 1 = 7 * (2232) + 1.\n // So we only have to discard one out of every 15625 numbers generated.\n\n // Generate a 6-digit number in base 5\n for (int i = 0; i != 6; ++i)\n {\n result = 5 * result + (rand5() - 1);\n }\n\n // result is in the range [0, 15625)\n if (result == 15625 - 1)\n {\n // Discard this number\n continue;\n }\n\n // We now know that result is in the range [0, 15624), a range that can\n // be divided evenly into 7 buckets guaranteeing uniformity\n result /= 2232;\n return 1 + result;\n }\n };\n\n for (int i = 0; i != n; ++i)\n {\n std::cout << rand7() << \" \";\n }\n std::cout << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 26373727, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "random5 random7 random5 random5 random7 random5 random7 random5 random7 def random5():\n return random.randint(1, 5)\n\ndef random7gen(n):\n count = 0\n while n > 0:\n samples = 6 * 7**9\n while samples >= 6 * 7**9:\n samples = 0\n for i in range(12):\n samples = samples * 5 + random5() - 1\n count += 1\n samples //= 6\n for outputs in range(9):\n yield samples % 7 + 1, count\n samples //= 7\n count = 0\n n -= 1\n if n == 0: break\n\n>>> from collections import Counter\n>>> Counter(x for x,i in random7gen(10000000))\nCounter({2: 1430293, 4: 1429298, 1: 1428832, 7: 1428571, 3: 1428204, 5: 1428134, 6: 1426668})\n>>> sum(i for x,i in random7gen(10000000)) / 10000000.0\n1.344606\n" }, { "answer_id": 26405409, "author": "Martin", "author_id": 2215617, "author_profile": "https://Stackoverflow.com/users/2215617", "pm_score": 1, "selected": false, "text": "package random;\n\nimport java.util.Random;\n\nimport org.junit.Test;\n\npublic class RandomTest {\n\n\n @Test\n public void testName() throws Exception {\n long times = 100000000;\n int indexes[] = new int[7];\n for(int i = 0; i < times; i++) {\n int rand7 = rand7();\n indexes[rand7]++;\n }\n\n for(int i = 0; i < 7; i++)\n System.out.println(\"Value \" + i + \": \" + indexes[i]);\n }\n\n\n public int rand7() {\n return (rand5() + rand5() + rand5() + rand5() + rand5() + rand5() + rand5()) % 7;\n }\n\n\n public int rand5() {\n return new Random().nextInt(5);\n }\n\n\n}\n Value 0: 14308087\nValue 1: 14298303\nValue 2: 14279731\nValue 3: 14262533\nValue 4: 14269749\nValue 5: 14277560\nValue 6: 14304037\n rand5() Value 0: 15199685\nValue 1: 14402429\nValue 2: 12795649\nValue 3: 12796957\nValue 4: 14402252\nValue 5: 15202778\nValue 6: 15200250\n public int rand(int range) {\n int randomValue = 0;\n for(int i = 0; i < range; i++) {\n randomValue += rand5();\n }\n return randomValue % range;\n\n}\n public static final int ORIGN_RANGE = 5;\npublic static final int DEST_RANGE = 7;\n\n@Test\npublic void testName() throws Exception {\n long times = 100000000;\n int indexes[] = new int[DEST_RANGE];\n for(int i = 0; i < times; i++) {\n int rand7 = convertRand(DEST_RANGE, ORIGN_RANGE);\n indexes[rand7]++;\n }\n\n for(int i = 0; i < DEST_RANGE; i++)\n System.out.println(\"Value \" + i + \": \" + indexes[i]);\n}\n\n\npublic int convertRand(int destRange, int originRange) {\n int randomValue = 0;\n for(int i = 0; i < destRange; i++) {\n randomValue += rand(originRange);\n }\n return randomValue % destRange;\n\n}\n\n\npublic int rand(int range) {\n return new Random().nextInt(range);\n}\n Value 0: 7713763\nValue 1: 7706552\nValue 2: 7694697\nValue 3: 7695319\nValue 4: 7688617\nValue 5: 7681691\nValue 6: 7674798\nValue 7: 7680348\nValue 8: 7685286\nValue 9: 7683943\nValue 10: 7690283\nValue 11: 7699142\nValue 12: 7705561\n" }, { "answer_id": 26538543, "author": "Michael Katkov", "author_id": 955321, "author_profile": "https://Stackoverflow.com/users/955321", "pm_score": 0, "selected": false, "text": "public int random7(){\n Random random = new Random();\n //function (1 + random.nextInt(5)) is given\n int random1_5 = 1 + random.nextInt(5); // 1,2,3,4,5\n int random2_6 = 2 + random.nextInt(5); // 2,3,4,5,6\n int random3_7 = 3 + random.nextInt(5); // 3,4,5,6,7\n int random4_8 = 4 + random.nextInt(5); // 4,5,6,7,8\n int random5_9 = 5 + random.nextInt(5); // 5,6,7,8,9\n int random6_10 = 6 + random.nextInt(5); //6,7,8,9,10\n int random7_11 = 7 + random.nextInt(5); //7,8,9,10,11\n\n //sumOfRandoms is between 28 and 56\n int sumOfRandoms = random1_5 + random2_6 + random3_7 + \n random4_8 + random5_9 + random6_10 + random7_11;\n //result is number between 0 and 6, and\n //equals 0 if sumOfRandoms = 28 or 35 or 42 or 49 or 56 , 5 options\n //equals 1 if sumOfRandoms = 29 or 36 or 43 or 50, 4 options\n //equals 2 if sumOfRandoms = 30 or 37 or 44 or 51, 4 options\n //equals 3 if sumOfRandoms = 31 or 38 or 45 or 52, 4 options\n //equals 4 if sumOfRandoms = 32 or 39 or 46 or 53, 4 options\n //equals 5 if sumOfRandoms = 33 or 40 or 47 or 54, 4 options\n //equals 6 if sumOfRandoms = 34 or 41 or 48 or 55, 4 options\n //It means that the probabilities of getting numbers between 0 and 6 are almost equal.\n int result = sumOfRandoms % 7;\n //we should add 1 to move the interval [0,6] to the interval [1,7]\n return 1 + result;\n}\n" }, { "answer_id": 26539070, "author": "jongo45", "author_id": 1447749, "author_profile": "https://Stackoverflow.com/users/1447749", "pm_score": 0, "selected": false, "text": "Math.random() rand5() Math.random() function rand5(){\n return Math.floor(Math.random()*5)+1;\n}\nfunction rand7(){\n var uiRandom=0;\n var div=1;\n for(var i=0; i<7; i++){\n div*=5;\n var term=(rand5()-1)/div;\n uiRandom+=term;\n }\n //return uiRandom;\n return Math.floor(uiRandom*7)+1; \n}\n rand5()-1 function rand5(){\n return Math.floor(Math.random()*5)+1;\n}\nfunction rand7(){\n var buffer=[];\n var div=1;\n for (var i=0; i<7; i++){\n buffer.push((rand5()-1).toString(5));\n div*=5;\n }\n var n=parseInt(buffer.join(\"\"),5);\n var uiRandom=n/div;\n //return uiRandom;\n return Math.floor(uiRandom*7)+1; \n}\n" }, { "answer_id": 29886312, "author": "Colin Su", "author_id": 492611, "author_profile": "https://Stackoverflow.com/users/492611", "pm_score": 0, "selected": false, "text": "rand5() def rand7():\n # twoway = 0 or 1 in the same probability\n twoway = None\n while not twoway in (1, 2):\n twoway = rand5()\n twoway -= 1\n\n ans = rand5() + twoway * 5\n\n return ans if ans in range(1,8) else rand7()\n twoway ans rand5() + twoway * 5 rand10() twoway result = [ rand7() for x in xrange(777777) ]\n\nans = {\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n}\n\nfor i in result:\n ans[i] += 1\n\nprint ans\n {1: 111170, 2: 110693, 3: 110651, 4: 111260, 5: 111197, 6: 111502, 7: 111304}\n def rand7():\n ans = rand5() + (rand5()-1) * 5\n return ans if ans < 8 else rand7()\n" }, { "answer_id": 30189285, "author": "user2622350", "author_id": 2622350, "author_profile": "https://Stackoverflow.com/users/2622350", "pm_score": -1, "selected": false, "text": "def rand5():\n return random.randint(1,5) #return random integers from 1 to 5\n\ndef rand7():\n rand = rand5()+rand5()-1\n if rand > 7: #if numbers > 7, call rand7() again\n return rand7()\n print rand%7 + 1\n 5*rand5() + rand5() - 5 rand5()+rand5()-1" }, { "answer_id": 30567290, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 1, "selected": false, "text": "int rand7(void) {\n static int m = 1;\n static int r = 0;\n\n for (;;) {\n while (m <= INT_MAX / 5) {\n r = r + m * (rand5() - 1);\n m = m * 5;\n }\n int q = m / 7;\n if (r < q * 7) {\n int i = r % 7;\n r = r / 7;\n m = q;\n return i + 1;\n }\n r = r - q * 7;\n m = m - q * 7;\n }\n}\n 0 m-1 m INT_MAX int r r rand5()" }, { "answer_id": 30569344, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 2, "selected": false, "text": "int rand7() {\n int r = 7 / 2;\n for (int i = 0; i < 28; i++)\n r = ((rand5() - 1) * 7 + r) / 5;\n return r + 1;\n}\n r r r = 3 rand5() int rand7() {\n return rand5();\n}\n" }, { "answer_id": 31949527, "author": "robermorales", "author_id": 887427, "author_profile": "https://Stackoverflow.com/users/887427", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env ruby\n\n# random integer from 1 to 5\ndef rand5\n STDERR.putc '.'\n 1 + rand( 5 )\nend\n\n@bucket = 0\n@bucket_size = 0\n\n# random integer from 1 to 7\ndef rand7\n if @bucket_size == 0\n @bucket = 7.times.collect{ |d| rand5 * 5**d }.reduce( &:+ )\n @bucket_size = 5\n end\n\n next_rand7 = @bucket%7 + 1\n\n @bucket /= 7\n @bucket_size -= 1\n\n return next_rand7\nend\n\n35.times.each{ putc rand7.to_s }\n" }, { "answer_id": 33795768, "author": "Thirlan", "author_id": 590059, "author_profile": "https://Stackoverflow.com/users/590059", "pm_score": 4, "selected": false, "text": "int rand7() {\n int value = rand5()\n + rand5() * 2\n + rand5() * 3\n + rand5() * 4\n + rand5() * 5\n + rand5() * 6;\n return value%7;\n}\n rand5 * 5^5 + rand5 * 5^4 + rand5 * 5^3 + rand5 * 5^2 + rand5 * 5 + rand5\n 5^5 = 3 mod 7\n5^4 = 2 mod 7\n5^3 = 6 mod 7\n5^2 = 4 mod 7\n5^1 = 5 mod 7\n rand5 * 5^5 + rand5 * 5^4 + rand5 * 5^3 + rand5 * 5^2 + rand5 * 5 + rand5\n rand5 * 3 + rand5 * 2 + rand5 * 6 + rand5 * 4 + rand5 * 5 + rand5\n a^(p-1) = 1 mod p\n (5^6)-1 = 0 mod 7\n 4 * 5^5 + 4 * 5^4 + 4 * 5^3 + 4 * 5^2 + 4 * 5 + 4\n def getRandomconverted(frm, to):\n s = 0\n for i in range(to):\n s += getRandomUniform(frm)*frm**i\n mx = 0\n for i in range(to):\n mx = (to-1)*frm**i \n mx = int(mx/to)*to # maximum value till which we can take mod\n if s < mx:\n return s%to\n else:\n return getRandomconverted(frm, to)\n" }, { "answer_id": 43161105, "author": "Devendra Lattu", "author_id": 2889297, "author_profile": "https://Stackoverflow.com/users/2889297", "pm_score": 1, "selected": false, "text": "(rand5() + rand5()) % 7 + 1 Yes, this is effective as it calls rand5() only twice and have O(1) space complexity rand5()" }, { "answer_id": 47603332, "author": "Shambho", "author_id": 3547167, "author_profile": "https://Stackoverflow.com/users/3547167", "pm_score": 2, "selected": false, "text": "rand5 rand5 rand5 <- function() sample(1:5,1)\n\nrand7 <- function() (sum(sapply(0:6, function(i) i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6)) %% 7) + 1\n rand7 = function(){\n r = 0 \n for(i in 0:6){\n r = r + i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6\n }\n return r %% 7 + 1\n}\n rand5 (7 * 5^6) %% 7 = 0 table(apply(expand.grid(c(outer(1:5,0:6,\"+\")),(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1)\n\n 1 2 3 4 5 6 7 \n15625 15625 15625 15625 15625 15625 15625 \n rand5 (4/25)^21 ~ 10^(-17) rand5 rand7 <- function() (sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1\n rand7 = function(){\n r = 0 \n for(i in 1:6){\n r = r + i*rand5()\n }\n return r %% 7 + 1\n}\n table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1)\n\n 1 2 3 4 5 6 7 \n2233 2232 2232 2232 2232 2232 2232\n 5^6 = 15625 rand5 rand5 <- function() sample(1:5,1)\n\nrand7 <- function() (sum(sapply(1:7, function(i) i * rand5())) %% 7) + 1\n rand7 = function(){\n r = 0 \n for(i in 1:7){\n r = r + i * rand5()\n }\n return r %% 7 + 1\n}\n rand5 (7 * 5) %% 7 = 0 table(apply(expand.grid(0:6,(1:5)),1,sum) %% 7 + 1)\n\n1 2 3 4 5 6 7 \n5 5 5 5 5 5 5 \n rand5 (4/25)^3 ~ 0.004 rand5 rand7 <- function() (rand5() + sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1\n rand7 = function(){\n r = 0 \n for(i in 1:6){\n r = r + i*rand5()\n }\n return (r+rand5()) %% 7 + 1\n}\n table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6,1:5),1,sum) %% 7 + 1)\n\n 1 2 3 4 5 6 7 \n11160 11161 11161 11161 11161 11161 11160\n 5^7 = 78125" }, { "answer_id": 51996385, "author": "Hassan", "author_id": 9798613, "author_profile": "https://Stackoverflow.com/users/9798613", "pm_score": -1, "selected": false, "text": "import random\n\ndef rand5():\n return float(random.randint(0,5))\n\ndef rand7():\n random_val = rand5()\n return float(random.randint((random_val-random_val),7))\n\nprint rand7()\n" }, { "answer_id": 52253512, "author": "ibrahim tanyalcin", "author_id": 9410412, "author_profile": "https://Stackoverflow.com/users/9410412", "pm_score": 1, "selected": false, "text": "f (b^0 * f() + b^1 * f() + b^2 * f() .... b^p * f()) / (b^(p+1) - 1) * (b-1)\n b p p rand5 rand7 function rand4(){\n return Math.random() * 5 | 0;\n}\n rand4 rand5()-1 function toFloat(f,b,p){\n b = b || 2;\n p = p || 3;\n return (Array.apply(null,Array(p))\n .map(function(d,i){return f()})\n .map(function(d,i){return Math.pow(b,i)*d})\n .reduce(function(ac,d,i){return ac += d;}))\n /\n (\n (Math.pow(b,p) - 1)\n /(b-1)\n )\n}\n toFloat(rand4) //1.4285714285714286 base = 2, precision = 3\ntoFloat(rand4,3,4) //0.75 base = 3, precision = 4\ntoFloat(rand4,4,5) //3.7507331378299122 base = 4, precision = 5\ntoFloat(rand4,5,6) //0.2012288786482335 base = 5, precision =6\n...\n 4 rand4 b=5 ((toFloat(rand4,5,6)/4 * 7) | 0) + 1 ---> occasionally you'll get 8 with 1/4^6 probability.\nMath.round((toFloat(rand4,5,6)/4 * 7) - 0.5) + 1 --> between 1 and 7\n" }, { "answer_id": 56184907, "author": "Ishpreet", "author_id": 5811973, "author_profile": "https://Stackoverflow.com/users/5811973", "pm_score": -1, "selected": false, "text": "// returns random number between 0-5 with equal probability\nfunction rand5() {\n return Math.floor(Math.random() * 6);\n}\n\n// returns random number between 0-7 with equal probability\nfunction rand7() {\n if(rand5() % 2 == 0 && rand5() % 2 == 0) { \n return 6 + rand5() % 2;\n } else {\n return rand5();\n }\n}\n\nconsole.log(rand7());" }, { "answer_id": 57677538, "author": "Emil Jeřábek", "author_id": 516539, "author_profile": "https://Stackoverflow.com/users/516539", "pm_score": 0, "selected": false, "text": "uint_fast64_t pool;\n\nint capacity = 0;\n\nvoid new_batch (void)\n{\n uint_fast64_t r;\n int i;\n\n do {\n r = 0;\n for (i = 0; i < 23; i++)\n r = 5 * r + (rand5() - 1);\n } while (r >= 11398895185373143ULL); /* 7**19, a bit less than 5**23 */\n\n pool = r;\n capacity = 19;\n}\n\nint rand7 (void)\n{\n int r;\n\n if (capacity == 0)\n new_batch();\n\n r = pool % 7;\n pool /= 7;\n capacity--;\n\n return r + 1;\n}\n" }, { "answer_id": 71476397, "author": "ldmtwo", "author_id": 3746632, "author_profile": "https://Stackoverflow.com/users/3746632", "pm_score": 0, "selected": false, "text": "Knowing that 5*7=35 and 7/5 = 1 remainder 2. How to guarantee that sum of remainders is always 0? 5*[7/5 = 1 remainder 2] --> 35/5 = 7 remainder 0 len=[1...5] import numpy as np\nimport pandas as pd\n# display is a notebook function FYI\ndef rand5(): ## random uniform int [1...5]\n return np.random.randint(1,6)\n\nn_trials = 1000\nsamples = [rand5() for _ in range(n_trials)]\n\ndisplay(pd.Series(samples).value_counts(normalize=True))\n# 4 0.2042\n# 5 0.2041\n# 2 0.2010\n# 1 0.1981\n# 3 0.1926\n# dtype: float64\n \ndef rand7(): # magic algebra\n x = sum(rand5() for _ in range(7))\n return x%7 + 1\n\nsamples = [rand7() for _ in range(n_trials)]\n\ndisplay(pd.Series(samples).value_counts(normalize=False))\n# 6 1475\n# 2 1475\n# 3 1456\n# 1 1423\n# 7 1419\n# 4 1393\n# 5 1359\n# dtype: int64\n \ndf = pd.DataFrame([\n pd.Series([rand7() for _ in range(n_trials)]).value_counts(normalize=True)\n for _ in range(1000)\n])\ndf.describe()\n# 1 2 3 4 5 6 7\n# count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000\n# mean 0.142885 0.142928 0.142523 0.142266 0.142704 0.143048 0.143646\n# std 0.010807 0.011526 0.010966 0.011223 0.011052 0.010983 0.011153\n# min 0.112000 0.108000 0.101000 0.110000 0.100000 0.109000 0.110000\n# 25% 0.135000 0.135000 0.135000 0.135000 0.135000 0.135000 0.136000\n# 50% 0.143000 0.142000 0.143000 0.142000 0.143000 0.142000 0.143000\n# 75% 0.151000 0.151000 0.150000 0.150000 0.150000 0.150000 0.151000\n# max 0.174000 0.181000 0.175000 0.178000 0.189000 0.176000 0.179000\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22535/" ]
137,784
<p>I have a report in SSRS 2005 that's based on a query that's similar to this one: </p> <pre><code>SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND col2 LIKE '%XYZ%' </code></pre> <p>I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!</p>
[ { "answer_id": 137856, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 1, "selected": false, "text": "if @checked = 1\n select * from mytable (nolock) where col = 'ABC'\nelse\n select * from mytable (nolock) where col = 'ABC' AND colw Like '%XYZ%'\n" }, { "answer_id": 137913, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 0, "selected": false, "text": "DECLARE @CommonSelectText varchar(2000) \nDECLARE @CompleteSelectText varchar(2000) \nSELECT @CommonSelectText = 'SELECT * FROM MyTable (nolock) Where Col = ''ABC'' ' \n\nIF @checked = 1 \n SELECT @CompleteSelectText = @CommonSelectText + ' AND ColW LIKE ''%XYZ%'' ' \nELSE \n SELECT @CompleteSelectText = @CommonSelectText \n\nEXEC (@CompleteSelectText) \n\nGO \n '" }, { "answer_id": 137924, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\nAND (@checked <> 0 and col2 LIKE '%XYZ%')\n" }, { "answer_id": 137969, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 1, "selected": false, "text": "SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\nAND col2 LIKE CASE @checked WHEN 1 THEN '%XYZ%' ELSE col2 END\n" }, { "answer_id": 138008, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "=\"SELECT * FROM MyTable (NOLOCK)\nWHERE col1 = 'ABC'\"+\niff(condition,true,\"AND col2 LIKE '%XYZ%'\",\"\")\n" }, { "answer_id": 138172, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "=\"SELECT * FROM MyTable WITH (NOLOCK) WHERE col1 = 'ABC'\" +\n Iif(Parameters!Checked.Value = true,\" AND col2 LIKE '%XYZ%'\",\"\")\n" }, { "answer_id": 138193, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": true, "text": "SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\n AND (@checked = 0 OR col2 LIKE '%XYZ%')\n @checked = 0 col1 = 'ABC' OR @checked = 1 OR col1 = 'ABC' AND col2 LIKE '%XYZ%' SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\n AND (@checked1 = 0 OR col2 LIKE '%XYZ%')\n AND (@checked2 = 0 OR col3 LIKE '%MNO%')\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11507/" ]
137,803
<p>Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.</p>
[ { "answer_id": 137818, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 5, "selected": true, "text": "SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1\n" }, { "answer_id": 138524, "author": "Andy Jones", "author_id": 5096, "author_profile": "https://Stackoverflow.com/users/5096", "pm_score": 1, "selected": false, "text": "--Check for existance \nif exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1) \ndrop table dbo.t\ngo\n\n--create dummy table and insert data \ncreate table dbo.t(x char(1) not null primary key, y char(1) not null) \ngo \nset nocount on \ninsert dbo.t (x,y) values ('A','B') \ninsert dbo.t (x,y) values ('C','D') \ninsert dbo.t (x,y) values ('E','F')\n\n--create temp table to add an identity column \ncreate table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null) \n\n--populate the temporary table \ninsert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t\n\n--return the data \nselect i,x,y from dbo.#TempWithIdentity\n\n--clean up \ndrop table dbo.#TempWithIdentity\n" }, { "answer_id": 140666, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 0, "selected": false, "text": " select rank=count(*), a1.au_lname, a1.au_fname\n from authors a1, authors a2\n where a1.au_lname + a1.au_fname >= a2.au_lname + a2.au_fname\n group by a1.au_lname, a1.au_fname\n order by rank\n" }, { "answer_id": 380821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Select (Select count(y.au_lname) from dbo.authors y\nwhere y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,\nx.au_lname,x.au_fname from authors x group by au_lname,au_fname\norder by Counterid --Alternatively that can be done which is equivalent as above..\n" }, { "answer_id": 9781014, "author": "codezombie", "author_id": 1279958, "author_profile": "https://Stackoverflow.com/users/1279958", "pm_score": 4, "selected": false, "text": "select top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp\n" }, { "answer_id": 25076734, "author": "Martin Widlund", "author_id": 3898763, "author_profile": "https://Stackoverflow.com/users/3898763", "pm_score": 4, "selected": false, "text": "ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber.\n" }, { "answer_id": 73395865, "author": "Leonardo Camargo", "author_id": 16308905, "author_profile": "https://Stackoverflow.com/users/16308905", "pm_score": 0, "selected": false, "text": " SELECT \n ROW_NUMBER() OVER (ORDER BY newId())\n FROM anyTbl\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396/" ]
137,812
<p>As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the <a href="http://open-std.org/JTC1/SC22/WG21/" rel="noreferrer">committee website</a>. All sorts of new features are being added, the biggest being concepts and lambdas. There is a very comprehensive <a href="http://en.wikipedia.org/wiki/C++0x" rel="noreferrer">Wikipedia article</a> with many of the new features. GCC 4.3 and later implement <a href="http://gcc.gnu.org/projects/cxx0x.html" rel="noreferrer">some C++0x features</a>.</p> <p>As far as new features go, I really like type traits (and the appropriate concepts), but my definite leader is variadic templates. Until 0x, long template lists have involved Boost Preprocessor usually, and are very unpleasant to write. This makes things a lot easier and allows C++0x templates to be treated like a perfectly functional language using variadic templates. I've already written some very cool code with them already, and I can't wait to use them more often!</p> <p>So what features are you most eagerly anticipating?</p>
[ { "answer_id": 237819, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "constexpr obj.bitmask |= 00001010B; \n" }, { "answer_id": 3117365, "author": "lornova", "author_id": 297373, "author_profile": "https://Stackoverflow.com/users/297373", "pm_score": 2, "selected": false, "text": "std::vector<std::vector<int>> a;\n std::vector<std::vector<int> > a;\n" }, { "answer_id": 4051812, "author": "Stephane Rolland", "author_id": 356440, "author_profile": "https://Stackoverflow.com/users/356440", "pm_score": 0, "selected": false, "text": "<regexp>" }, { "answer_id": 4192350, "author": "snogglethorpe", "author_id": 284969, "author_profile": "https://Stackoverflow.com/users/284969", "pm_score": 3, "selected": false, "text": "for (auto x : collection) *i i->... x" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16855/" ]
137,817
<p>I'm interested in building a PC for a car that will boot off of a USB flash drive. I'm planning on using <a href="http://en.wikipedia.org/wiki/Windows_Preinstallation_Environment" rel="nofollow noreferrer">Windows PE</a> 2.0 for it with the GUI being written in C# or VB.NET.</p> <p>Obviously, for this to work, I'd need to have <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> 2.0 or later installed. Understanding that .NET is not included by default, is there a way to package .NET 2.0 with Windows PE 2.0 in such a way as to allow my <a href="http://en.wikipedia.org/wiki/Graphical_user_interface" rel="nofollow noreferrer">GUI</a> application to work?</p>
[ { "answer_id": 237819, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "constexpr obj.bitmask |= 00001010B; \n" }, { "answer_id": 3117365, "author": "lornova", "author_id": 297373, "author_profile": "https://Stackoverflow.com/users/297373", "pm_score": 2, "selected": false, "text": "std::vector<std::vector<int>> a;\n std::vector<std::vector<int> > a;\n" }, { "answer_id": 4051812, "author": "Stephane Rolland", "author_id": 356440, "author_profile": "https://Stackoverflow.com/users/356440", "pm_score": 0, "selected": false, "text": "<regexp>" }, { "answer_id": 4192350, "author": "snogglethorpe", "author_id": 284969, "author_profile": "https://Stackoverflow.com/users/284969", "pm_score": 3, "selected": false, "text": "for (auto x : collection) *i i->... x" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,837
<p>Does your software handle newline characters from other systems?</p> <pre><code>Linux/BSD linefeed ^J 10 x0A Windows/IBM return linefeed ^M^J 13 10 x0D x0A old Macs return ^M 13 x0D others? </code></pre> <p>For reasons of insanity, I am going with using the Linux version of the newline character in my text files. But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text. How would you deal with this?</p>
[ { "answer_id": 137841, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "fopen(..., \"r\")" }, { "answer_id": 137842, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": -1, "selected": false, "text": "string convertLineBreaks(String line, String lineBreakYouWant) {\n replace all ^M^J or ^M or ^J in line with lineBreakYouWant\n\n return line\n}\n" }, { "answer_id": 137848, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "Environment.NewLine" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19737/" ]
137,845
<p>How do I determine whether an object is a member of a collection in VBA?</p> <p>Specifically, I need to find out whether a table definition is a member of the <code>TableDefs</code> collection.</p>
[ { "answer_id": 218727, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 5, "selected": false, "text": "Public Function InCollection(col As Collection, key As String) As Boolean\n Dim var As Variant\n Dim errNumber As Long\n\n InCollection = False\n Set var = Nothing\n\n Err.Clear\n On Error Resume Next\n var = col.Item(key)\n errNumber = CLng(Err.Number)\n On Error GoTo 0\n\n '5 is not in, 0 and 438 represent incollection\n If errNumber = 5 Then ' it is 5 if not in collection\n InCollection = False\n Else\n InCollection = True\n End If\n\nEnd Function\n" }, { "answer_id": 991900, "author": "Vadim", "author_id": 122609, "author_profile": "https://Stackoverflow.com/users/122609", "pm_score": 6, "selected": false, "text": "Public Function Contains(col As Collection, key As Variant) As Boolean\nDim obj As Variant\nOn Error GoTo err\n Contains = True\n obj = col(key)\n Exit Function\nerr:\n\n Contains = False\nEnd Function\n" }, { "answer_id": 9497469, "author": "muscailie", "author_id": 418367, "author_profile": "https://Stackoverflow.com/users/418367", "pm_score": 1, "selected": false, "text": "Public Function CheckExists(vntIndexKey As Variant) As Boolean\n On Error Resume Next\n Dim cObj As Object\n\n ' just get the object\n Set cObj = mCol(vntIndexKey)\n\n ' here's the key! Trap the Error Code\n ' when the error code is 5 then the Object is Not Exists\n CheckExists = (Err <> 5)\n\n ' just to clear the error\n If Err <> 0 Then Call Err.Clear\n Set cObj = Nothing\nEnd Function\n" }, { "answer_id": 13532878, "author": "Gov_Programmer", "author_id": 1631272, "author_profile": "https://Stackoverflow.com/users/1631272", "pm_score": 2, "selected": false, "text": "Public Function InCollection(col As Collection, Optional vItem, Optional vKey) As Boolean\nOn Error Resume Next\n\nDim vColItem As Variant\n\nInCollection = False\n\nIf Not IsMissing(vKey) Then\n col.item vKey\n\n '5 if not in collection, it is 91 if no collection exists\n If Err.Number <> 5 And Err.Number <> 91 Then\n InCollection = True\n End If\nElseIf Not IsMissing(vItem) Then\n For Each vColItem In col\n If vColItem = vItem Then\n InCollection = True\n GoTo Exit_Proc\n End If\n Next vColItem\nEnd If\n\nExit_Proc:\nExit Function\nErr_Handle:\nResume Exit_Proc\nEnd Function\n" }, { "answer_id": 21599578, "author": "TmTron", "author_id": 1041641, "author_profile": "https://Stackoverflow.com/users/1041641", "pm_score": 1, "selected": false, "text": "' TODO: change this to the name of your module\nPrivate Const sMODULE As String = \"MVbaUtils\"\n\nPublic Function ExistsInCollection(oCollection As Collection, sKey As String) As Boolean\n Const scSOURCE As String = \"ExistsInCollection\"\n\n Dim lErrNumber As Long\n Dim sErrDescription As String\n\n lErrNumber = 0\n sErrDescription = \"unknown error occurred\"\n Err.Clear\n On Error Resume Next\n ' note: just access the item - no need to assign it to a dummy value\n ' and this would not be so easy, because we would need different\n ' code depending on the type of object\n ' e.g.\n ' Dim vItem as Variant\n ' If VarType(oCollection.Item(sKey)) = vbObject Then\n ' Set vItem = oCollection.Item(sKey)\n ' Else\n ' vItem = oCollection.Item(sKey)\n ' End If\n oCollection.Item sKey\n lErrNumber = CLng(Err.Number)\n sErrDescription = Err.Description\n On Error GoTo 0\n\n If lErrNumber = 5 Then ' 5 = not in collection\n ExistsInCollection = False\n ElseIf (lErrNumber = 0) Then\n ExistsInCollection = True\n Else\n ' Re-raise error\n Err.Raise lErrNumber, mscMODULE & \":\" & scSOURCE, sErrDescription\n End If\nEnd Function\n\nPrivate Sub Test_ExistsInCollection()\n Dim asTest As New Collection\n\n Debug.Assert Not ExistsInCollection(asTest, \"\")\n Debug.Assert Not ExistsInCollection(asTest, \"xx\")\n\n asTest.Add \"item1\", \"key1\"\n asTest.Add \"item2\", \"key2\"\n asTest.Add New Collection, \"key3\"\n asTest.Add Nothing, \"key4\"\n Debug.Assert ExistsInCollection(asTest, \"key1\")\n Debug.Assert ExistsInCollection(asTest, \"key2\")\n Debug.Assert ExistsInCollection(asTest, \"key3\")\n Debug.Assert ExistsInCollection(asTest, \"key4\")\n Debug.Assert Not ExistsInCollection(asTest, \"abcx\")\n\n Debug.Print \"ExistsInCollection is okay\"\nEnd Sub\n" }, { "answer_id": 24041939, "author": "KthProg", "author_id": 3707806, "author_profile": "https://Stackoverflow.com/users/3707806", "pm_score": 2, "selected": false, "text": "Public Function InCollection(col As Collection, key As String) As Boolean\n\n On Error GoTo incol\n col.Item key\n\nincol:\n InCollection = (Err.Number = 0)\n\nEnd Function\n" }, { "answer_id": 27759431, "author": "Levent", "author_id": 4415934, "author_profile": "https://Stackoverflow.com/users/4415934", "pm_score": 2, "selected": false, "text": "Public Function Contains(col As collection, key As Variant) As Boolean\n Dim obj As Object\n On Error GoTo err\n Contains = True\n Set obj = col.Item(key)\n Exit Function\n \nerr:\n Contains = False\nEnd Function" }, { "answer_id": 31457677, "author": "DrBuck", "author_id": 5037322, "author_profile": "https://Stackoverflow.com/users/5037322", "pm_score": -1, "selected": false, "text": "' Returns TRUE if item is already contained in collection, otherwise FALSE\n\nPublic Function Contains(col As Collection, item As String) As Boolean\n\n Dim i As Integer\n\n For i = 1 To col.Count\n\n If col.item(i) = item Then\n Contains = True\n Exit Function\n End If\n\n Next i\n\n Contains = False\n\nEnd Function\n" }, { "answer_id": 31834936, "author": "Joao Louzada", "author_id": 4298248, "author_profile": "https://Stackoverflow.com/users/4298248", "pm_score": -1, "selected": false, "text": "Public Function VerifyCollection()\n For i = 1 To 10 Step 1\n MyKey = \"A\"\n On Error GoTo KillError:\n Dispersao.Add 1, MyKey\n GoTo KeepInForLoop\nKillError: 'If My collection already has the key A Then...\n count = Dispersao(MyKey)\n Dispersao.Remove (MyKey)\n Dispersao.Add count + 1, MyKey 'Increase the amount in relationship with my Key\n count = Dispersao(MyKey) 'count = new amount\n On Error GoTo -1\nKeepInForLoop:\n Next\nEnd Function\n" }, { "answer_id": 39464809, "author": "Sharunas Bielskis", "author_id": 4403269, "author_profile": "https://Stackoverflow.com/users/4403269", "pm_score": 2, "selected": false, "text": "Public Function Contains(col As Collection, thisItem As Variant) As Boolean\n\n Dim item As Variant\n\n Contains = False\n For Each item In col\n If item = thisItem Then\n Contains = True\n Exit Function\n End If\n Next\nEnd Function\n" }, { "answer_id": 48375276, "author": "ZygD", "author_id": 2753501, "author_profile": "https://Stackoverflow.com/users/2753501", "pm_score": 4, "selected": false, "text": "Public Function ExistsInCollection(col As Collection, key As Variant) As Boolean\n On Error GoTo err\n ExistsInCollection = True\n IsObject(col.item(key))\n Exit Function\nerr:\n ExistsInCollection = False\nEnd Function\n col As Collection col As ListColumns" }, { "answer_id": 48703732, "author": "Ister", "author_id": 6340948, "author_profile": "https://Stackoverflow.com/users/6340948", "pm_score": 0, "selected": false, "text": "'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'INPUT : Kollection, the collection we would like to examine\n' : (Optional) Key, the Key we want to find in the collection\n' : (Optional) Item, the Item we want to find in the collection\n'OUTPUT : True if Key or Item is found, False if not\n'SPECIAL CASE: If both Key and Item are missing, return False\nOption Explicit\nPublic Function CollectionContains(Kollection As Collection, Optional Key As Variant, Optional Item As Variant) As Boolean\n Dim strKey As String\n Dim var As Variant\n\n 'First, investigate assuming a Key was provided\n If Not IsMissing(Key) Then\n\n strKey = CStr(Key)\n\n 'Handling errors is the strategy here\n On Error Resume Next\n CollectionContains = True\n var = Kollection(strKey) '<~ this is where our (potential) error will occur\n If Err.Number = 91 Then GoTo CheckForObject\n If Err.Number = 5 Then GoTo NotFound\n On Error GoTo 0\n Exit Function\n\nCheckForObject:\n If IsObject(Kollection(strKey)) Then\n CollectionContains = True\n On Error GoTo 0\n Exit Function\n End If\n\nNotFound:\n CollectionContains = False\n On Error GoTo 0\n Exit Function\n\n 'If the Item was provided but the Key was not, then...\n ElseIf Not IsMissing(Item) Then\n\n CollectionContains = False '<~ assume that we will not find the item\n\n 'We have to loop through the collection and check each item against the passed-in Item\n For Each var In Kollection\n If var = Item Then\n CollectionContains = True\n Exit Function\n End If\n Next var\n\n 'Otherwise, no Key OR Item was provided, so we default to False\n Else\n CollectionContains = False\n End If\n\nEnd Function\n" }, { "answer_id": 62281203, "author": "nir", "author_id": 4342378, "author_profile": "https://Stackoverflow.com/users/4342378", "pm_score": 0, "selected": false, "text": "Function ArrayRemoveDups(MyArray As Variant) As Variant\nDim nFirst As Long, nLast As Long, i As Long\nDim item As Variant, outputArray() As Variant\nDim Coll As New Collection\n\n'Get First and Last Array Positions\nnFirst = LBound(MyArray)\nnLast = UBound(MyArray)\nReDim arrTemp(nFirst To nLast)\ni = nFirst\n'convert to collection\nFor Each item In MyArray\n skipitem = False\n For Each key In Coll\n If key = item Then skipitem = True\n Next\n If skipitem = False Then Coll.Add (item)\nNext item\n'convert back to array\nReDim outputArray(0 To Coll.Count - 1)\nFor i = 1 To Coll.Count\n outputArray(i - 1) = Coll.item(i)\nNext\nArrayRemoveDups = outputArray\nEnd Function\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
137,868
<p>In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.</p> <p>Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.</p> <p>What are your thoughts on this and what do you follow?</p>
[ { "answer_id": 137875, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 4, "selected": false, "text": "public String doSomething() {\n final String first = someReallyComplicatedExpressionToGetTheString();\n final String second = anotherReallyComplicatedExpressionToGetAnother();\n\n return first+second;\n}\n" }, { "answer_id": 137895, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 0, "selected": false, "text": "public/private static final type SOME_CONSTANT;" }, { "answer_id": 137946, "author": "Johan Pelgrim", "author_id": 9707, "author_profile": "https://Stackoverflow.com/users/9707", "pm_score": 9, "selected": true, "text": "final final final final" }, { "answer_id": 137964, "author": "Hans Sjunnesson", "author_id": 8683, "author_profile": "https://Stackoverflow.com/users/8683", "pm_score": 0, "selected": false, "text": "public void doSomething(int i, int j) {\n final int n = i + j; // must be declared final\n\n Comparator comp = new Comparator() {\n public int compare(Object left, Object right) {\n return n; // return copy of a local variable\n }\n };\n}\n" }, { "answer_id": 138137, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": false, "text": "final NullPointerException final FileInputStream in;\nif(test)\n in = new FileInputStream(\"foo.txt\");\nelse\n System.out.println(\"test failed\");\nin.read(); // Compiler error because variable 'in' might be unassigned\n String msg = null;\n for(int i = 0; i < 10; i++) {\n msg = \"We are at position \" + i;\n System.out.println(msg);\n }\n msg = null;\n for(int i = 0; i < 10; i++) {\n final String msg = \"We are at position \" + i;\n System.out.println(msg);\n }\n" }, { "answer_id": 138440, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 3, "selected": false, "text": "final final this final" }, { "answer_id": 142122, "author": "David Leppik", "author_id": 18078, "author_profile": "https://Stackoverflow.com/users/18078", "pm_score": 3, "selected": false, "text": "final int foo;\nif (a)\n foo = 1;\nelse if (b)\n foo = 2;\nelse if (c)\n foo = 3;\nif (d) // Compile error: forgot the 'else'\n foo = 4;\nelse\n foo = -1;\n" }, { "answer_id": 142406, "author": "Eugene", "author_id": 22876, "author_profile": "https://Stackoverflow.com/users/22876", "pm_score": 0, "selected": false, "text": "class A {\n void foo() {\n //do something\n }\n}\nfinal class B extends A {\n void foo() {\n }\n}\nclass Test {\n public void t(A v1, B v2) {\n v1.foo();\n v2.foo();\n }\n}\n" }, { "answer_id": 144988, "author": "Ryan Ransford", "author_id": 12604, "author_profile": "https://Stackoverflow.com/users/12604", "pm_score": 4, "selected": false, "text": "final final" }, { "answer_id": 12207465, "author": "Oleg Mikheev", "author_id": 513342, "author_profile": "https://Stackoverflow.com/users/513342", "pm_score": 2, "selected": false, "text": "final" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15321/" ]
137,870
<p>I'd like to change the security attribute of a directory that InstallShield creates under the <code>CSIDL_COMMON_APPDATA</code> - can someone please advise on how to do that during the installation process?</p> <p>It's a script-defined folder.</p> <p>Thank you.</p>
[ { "answer_id": 147122, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 2, "selected": false, "text": "Installation Designer > Components > [somecomponent] > Destination Permissions\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
137,872
<p>I am using the JQuery form plugin (<a href="http://malsup.com/jquery/form/" rel="noreferrer">http://malsup.com/jquery/form/</a>) to handle the ajax submission of a form. I also have JQuery.Validate (<a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">http://docs.jquery.com/Plugins/Validation</a>) plugged in for my client side validation.</p> <p>What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.</p> <p>I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.</p> <p>So what I am I missing that is preventing my desired behaviour? Sample code below....</p> <pre><code>&lt;form id="searchForm" method="post" action="/User/GetDetails"&gt; &lt;input id="username" name="username" type="text" value="user.name" /&gt; &lt;input id="submit" name="submit" type="submit" value="Search" /&gt; &lt;/form&gt; &lt;div id="detailsView"&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; var options = { target: '#detailsView' }; $('#searchForm').ajaxForm(options); $('#searchForm').validate({ rules: { username: {required:true}}, messages: { username: {required:"Username is a required field."}} }); &lt;/script&gt; </code></pre>
[ { "answer_id": 137881, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 1, "selected": false, "text": "$(\"form\").validate({\n" }, { "answer_id": 139336, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<form id=\"searchForm\" method=\"post\" action=\"/User/GetDetails\" onSubmit=\"return false;\">\n" }, { "answer_id": 844582, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 4, "selected": false, "text": "var options = {\n beforeSubmit: function() {\n return $('#searchForm').validate().form();\n },\n target: '#detailsView'\n };\n" }, { "answer_id": 2069996, "author": "berko", "author_id": 4884, "author_profile": "https://Stackoverflow.com/users/4884", "pm_score": 2, "selected": false, "text": "var v = jQuery(\"#form\").validate({\n submitHandler: function(form) {\n jQuery(form).ajaxSubmit({target: \"#result\"});\n }\n});\n" }, { "answer_id": 5007286, "author": "duggi", "author_id": 262942, "author_profile": "https://Stackoverflow.com/users/262942", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\n var options = {\n target: '#detailsView'\n };\n\n// -- \"solution\" --\n$('#searchForm').submit(function(event) {\n this.preventDefault(event); // our env actually monkey patches preventDefault\n // impl your own prevent default here\n // basically the idea is to bind a prevent default\n // stopper on the form's submit event\n});\n// -- end --\n\n $('#searchForm').ajaxForm(options);\n\n $('#searchForm').validate({\n rules: {\n username: {required:true}},\n messages: {\n username: {required:\"Username is a required field.\"}}\n });\n</script>\n" }, { "answer_id": 11282333, "author": "Manjula Srinath", "author_id": 1494295, "author_profile": "https://Stackoverflow.com/users/1494295", "pm_score": 2, "selected": false, "text": "$('#contactform').ajaxForm({\n success : FormSendResponse, \n beforeSubmit: function(){\n return $(\"#contactform\").valid();\n }\n});\n\n\n$(\"#contactform\").validate(); \n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4884/" ]
137,880
<p>Start with the simplest task of capturing the URL in Firefox from a C# application. It appears using user32.dll Windows API functions will not work as is the approach for capturing the URL within IE. </p>
[ { "answer_id": 21419194, "author": "Victor D. Castillo", "author_id": 1996777, "author_profile": "https://Stackoverflow.com/users/1996777", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Interactions;\nusing OpenQA.Selenium.Interactions.Internal;\nusing OpenQA.Selenium.Support.UI;\nusing OpenQA.Selenium.IE;\nusing NUnit.Framework;\nusing System.Text.RegularExpressions;\n\nnamespace sae_test\n{ class Program\n { private static string baseURL;\n private static StringBuilder verificationErrors;\n\n static void Main(string[] args)\n { // test with firefox\n IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();\n // test with IE\n //InternetExplorerOptions options = new InternetExplorerOptions();\n //options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;\n //IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);\n SetupTest();\n driver.Navigate().GoToUrl(baseURL + \"Account/Login.aspx\");\n IWebElement inputTextUser = driver.FindElement(By.Id(\"MainContent_LoginUser_UserName\"));\n inputTextUser.Clear();\n driver.FindElement(By.Id(\"MainContent_LoginUser_UserName\")).Clear();\n driver.FindElement(By.Id(\"MainContent_LoginUser_UserName\")).SendKeys(\"usuario\");\n driver.FindElement(By.Id(\"MainContent_LoginUser_Password\")).Clear();\n driver.FindElement(By.Id(\"MainContent_LoginUser_Password\")).SendKeys(\"123\");\n driver.FindElement(By.Id(\"MainContent_LoginUser_LoginButton\")).Click();\n driver.Navigate().GoToUrl(baseURL + \"finanzas/consulta.aspx\");\n // view combo element\n IWebElement comboBoxSistema = driver.FindElement(By.Id(\"MainContent_rcbSistema_Arrow\"));\n //Then click when menu option is visible \n comboBoxSistema.Click();\n System.Threading.Thread.Sleep(500);\n // container of elements systems combo\n IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id(\"MainContent_rcbSistema_DropDown\"));\n listaDesplegableComboSistemas.FindElement(By.XPath(\"//li[text()='BOMBEO MECANICO']\")).Click();\n System.Threading.Thread.Sleep(500);\n IWebElement comboBoxEquipo = driver.FindElement(By.Id(\"MainContent_rcbEquipo_Arrow\"));\n //Then click when menu option is visible \n comboBoxEquipo.Click();\n System.Threading.Thread.Sleep(500);\n // container of elements equipment combo\n IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id(\"MainContent_rcbEquipo_DropDown\"));\n\n listaDesplegableComboEquipos.FindElement(By.XPath(\"//li[text()='MINI-V']\")).Click();\n System.Threading.Thread.Sleep(500);\n\n driver.FindElement(By.Id(\"MainContent_Button1\")).Click(); \n try\n { Assert.AreEqual(\"BOMBEO MECANICO_22\", driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\\\"]\")).Text);\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n // verify coin format $1,234,567.89 usd\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n // verify number format 1,234,567.89\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\\\"]\")).Text, \"((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})?\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n System.Console.WriteLine(\"errores: \" + verificationErrors);\n System.Threading.Thread.Sleep(20000);\n driver.Quit();\n }\n\n public static void SetupTest()\n { baseURL = \"http://127.0.0.1:8081/ver.rel.1.2/\";\n verificationErrors = new StringBuilder();\n }\n\n protected static void mouseOver(IWebDriver driver, IWebElement element)\n { Actions builder = new Actions(driver);\n builder.MoveToElement(element);\n builder.Perform();\n }\n\n public static void highlightElement(IWebDriver driver, IWebElement element)\n { for (int i = 0; i < 2; i++)\n { IJavaScriptExecutor js = (IJavaScriptExecutor)driver;\n js.ExecuteScript(\"arguments[0].setAttribute('style', arguments[1]);\",\n element, \"color: yellow; border: 2px solid yellow;\");\n js.ExecuteScript(\"arguments[0].setAttribute('style', arguments[1]);\",\n element, \"\");\n }\n }\n}\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391678/" ]
137,893
<p>I'm using code that I found on the <a href="http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx" rel="nofollow noreferrer">CodeProject.com for a low-level keyboard hook</a>. The only problem is it uses external DLL calls that don't work in mono. I was wondering if anyone knew of a way to accomplish the same thing as that code, but will run in both Windows using .net, and Linux using mono?</p> <p>Edit: Clarifying what I'm trying to do: I'm making a <a href="http://joel-llamaduck.blogspot.com/" rel="nofollow noreferrer">Dashboard like application</a>. The program sits in the system tray and when the user presses the hot-key, it will pop up all the gadgets. So the program doesn't have focus, so typically it won't catch any keystrokes, so I'm using the low-level keyboard hook and I hook the two keys that the user defines as the hot-keys. But I'm using a Windows DLL call for that, which doesn't work in Linux using mono. So I'm wondering if there's a way to do the same thing, but will run in Linux using mono?</p>
[ { "answer_id": 21419194, "author": "Victor D. Castillo", "author_id": 1996777, "author_profile": "https://Stackoverflow.com/users/1996777", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Interactions;\nusing OpenQA.Selenium.Interactions.Internal;\nusing OpenQA.Selenium.Support.UI;\nusing OpenQA.Selenium.IE;\nusing NUnit.Framework;\nusing System.Text.RegularExpressions;\n\nnamespace sae_test\n{ class Program\n { private static string baseURL;\n private static StringBuilder verificationErrors;\n\n static void Main(string[] args)\n { // test with firefox\n IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();\n // test with IE\n //InternetExplorerOptions options = new InternetExplorerOptions();\n //options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;\n //IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);\n SetupTest();\n driver.Navigate().GoToUrl(baseURL + \"Account/Login.aspx\");\n IWebElement inputTextUser = driver.FindElement(By.Id(\"MainContent_LoginUser_UserName\"));\n inputTextUser.Clear();\n driver.FindElement(By.Id(\"MainContent_LoginUser_UserName\")).Clear();\n driver.FindElement(By.Id(\"MainContent_LoginUser_UserName\")).SendKeys(\"usuario\");\n driver.FindElement(By.Id(\"MainContent_LoginUser_Password\")).Clear();\n driver.FindElement(By.Id(\"MainContent_LoginUser_Password\")).SendKeys(\"123\");\n driver.FindElement(By.Id(\"MainContent_LoginUser_LoginButton\")).Click();\n driver.Navigate().GoToUrl(baseURL + \"finanzas/consulta.aspx\");\n // view combo element\n IWebElement comboBoxSistema = driver.FindElement(By.Id(\"MainContent_rcbSistema_Arrow\"));\n //Then click when menu option is visible \n comboBoxSistema.Click();\n System.Threading.Thread.Sleep(500);\n // container of elements systems combo\n IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id(\"MainContent_rcbSistema_DropDown\"));\n listaDesplegableComboSistemas.FindElement(By.XPath(\"//li[text()='BOMBEO MECANICO']\")).Click();\n System.Threading.Thread.Sleep(500);\n IWebElement comboBoxEquipo = driver.FindElement(By.Id(\"MainContent_rcbEquipo_Arrow\"));\n //Then click when menu option is visible \n comboBoxEquipo.Click();\n System.Threading.Thread.Sleep(500);\n // container of elements equipment combo\n IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id(\"MainContent_rcbEquipo_DropDown\"));\n\n listaDesplegableComboEquipos.FindElement(By.XPath(\"//li[text()='MINI-V']\")).Click();\n System.Threading.Thread.Sleep(500);\n\n driver.FindElement(By.Id(\"MainContent_Button1\")).Click(); \n try\n { Assert.AreEqual(\"BOMBEO MECANICO_22\", driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\\\"]\")).Text);\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n // verify coin format $1,234,567.89 usd\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\\\"]\")).Text, \"\\\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})? usd\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n // verify number format 1,234,567.89\n try\n { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath(\"//*[@id=\\\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\\\"]\")).Text, \"((,)*[0-9]*[0-9]*[0-9]+)+(\\\\.[0-9]{2})?\"));\n }\n catch (AssertionException e)\n { verificationErrors.Append(e.Message);\n }\n System.Console.WriteLine(\"errores: \" + verificationErrors);\n System.Threading.Thread.Sleep(20000);\n driver.Quit();\n }\n\n public static void SetupTest()\n { baseURL = \"http://127.0.0.1:8081/ver.rel.1.2/\";\n verificationErrors = new StringBuilder();\n }\n\n protected static void mouseOver(IWebDriver driver, IWebElement element)\n { Actions builder = new Actions(driver);\n builder.MoveToElement(element);\n builder.Perform();\n }\n\n public static void highlightElement(IWebDriver driver, IWebElement element)\n { for (int i = 0; i < 2; i++)\n { IJavaScriptExecutor js = (IJavaScriptExecutor)driver;\n js.ExecuteScript(\"arguments[0].setAttribute('style', arguments[1]);\",\n element, \"color: yellow; border: 2px solid yellow;\");\n js.ExecuteScript(\"arguments[0].setAttribute('style', arguments[1]);\",\n element, \"\");\n }\n }\n}\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ]
137,911
<p>I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone?</p> <p>I understand that filling the head_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main_template.pt, which is my current solution, with it's huge drawbacks).</p>
[ { "answer_id": 147805, "author": "michaeljoseph", "author_id": 5549, "author_profile": "https://Stackoverflow.com/users/5549", "pm_score": 3, "selected": false, "text": "head_slot main_template.pt <head>\n <metal:block metal:fill-slot=\"head_slot\">\n <link rel=\"openid.server\" href=\"http://your.provider\">\n <link rel=\"openid.delegate\" href=\"http://your.url\">\n </metal:block>\n</head>\n" }, { "answer_id": 197777, "author": "Reinout van Rees", "author_id": 27401, "author_profile": "https://Stackoverflow.com/users/27401", "pm_score": 1, "selected": false, "text": " <metal:myopenid fill-slot=\"style_slot\">\n <link rel=\"openid.server\" href=\"http://www.myopenid.com/server\" />\n <link rel=\"openid.delegate\" href=\"http://reinout.myopenid.com/\" />\n </metal:myopenid>\n" }, { "answer_id": 438254, "author": "pupeno", "author_id": 6068, "author_profile": "https://Stackoverflow.com/users/6068", "pm_score": 1, "selected": true, "text": "<head>\n ...\n <link rel=\"openid.server\" href=\"http://www.myopenid.com/server\" />\n <link rel=\"openid.delegate\" href=\"http://pupeno.myopenid.com/\" />\n <link rel=\"openid2.local_id\" href=\"http://pupeno.myopenid.com\" />\n <link rel=\"openid2.provider\" href=\"http://www.myopenid.com/server\" />\n <meta http-equiv=\"X-XRDS-Location\" content=\"http://www.myopenid.com/xrds?username=pupeno.myopenid.com\" />\n</head>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
137,933
<p>We are writing a complex rich desktop application and need to offer flexibility in reporting formats so we thought we would just expose our object model to a scripting langauge. Time was when that meant VBA (which is still an option), but the managed code derivative VSTA (I think) seems to have withered on the vine.</p> <p>What is now the best choice for an embedded scripting language on Windows .NET?</p>
[ { "answer_id": 596097, "author": "Grant Peters", "author_id": 68241, "author_profile": "https://Stackoverflow.com/users/68241", "pm_score": 7, "selected": false, "text": "\nusing System;\nusing System.Windows.Forms;\nusing System.Reflection;\nusing System.CodeDom.Compiler;\n\nnamespace ScriptingInterface\n{\n public interface IScriptType1\n {\n string RunScript(int value);\n }\n}\n\nnamespace ScriptingExample\n{\n static class Program\n {\n /// \n /// The main entry point for the application.\n /// \n [STAThread]\n static void Main()\n {\n\n // Lets compile some code (I'm lazy, so I'll just hardcode it all, i'm sure you can work out how to read from a file/text box instead\n Assembly compiledScript = CompileCode(\n \"namespace SimpleScripts\" +\n \"{\" +\n \" public class MyScriptMul5 : ScriptingInterface.IScriptType1\" +\n \" {\" +\n \" public string RunScript(int value)\" +\n \" {\" +\n \" return this.ToString() + \\\" just ran! Result: \\\" + (value*5).ToString();\" +\n \" }\" +\n \" }\" +\n \" public class MyScriptNegate : ScriptingInterface.IScriptType1\" +\n \" {\" +\n \" public string RunScript(int value)\" +\n \" {\" +\n \" return this.ToString() + \\\" just ran! Result: \\\" + (-value).ToString();\" +\n \" }\" +\n \" }\" +\n \"}\");\n\n if (compiledScript != null)\n {\n RunScript(compiledScript);\n }\n }\n\n static Assembly CompileCode(string code)\n {\n // Create a code provider\n // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones)\n // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that\n // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?)\n Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();\n\n // Setup our options\n CompilerParameters options = new CompilerParameters();\n options.GenerateExecutable = false; // we want a Dll (or \"Class Library\" as its called in .Net)\n options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile\n // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best!\n\n // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow\n // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows\n // thus they can only do the things you want them to.\n // (though things like \"System.Xml.dll\" can be useful, just need to provide a way users can read a file to pass in to it)\n // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another\n // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to\n // the \"script\"\n options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);\n\n // Compile our code\n CompilerResults result;\n result = csProvider.CompileAssemblyFromSource(options, code);\n\n if (result.Errors.HasErrors)\n {\n // TODO: report back to the user that the script has errored\n return null;\n }\n\n if (result.Errors.HasWarnings)\n {\n // TODO: tell the user about the warnings, might want to prompt them if they want to continue\n // runnning the \"script\"\n }\n\n return result.CompiledAssembly;\n }\n\n static void RunScript(Assembly script)\n {\n // Now that we have a compiled script, lets run them\n foreach (Type type in script.GetExportedTypes())\n {\n foreach (Type iface in type.GetInterfaces())\n {\n if (iface == typeof(ScriptingInterface.IScriptType1))\n {\n // yay, we found a script interface, lets create it and run it!\n\n // Get the constructor for the current type\n // you can also specify what creation parameter types you want to pass to it,\n // so you could possibly pass in data it might need, or a class that it can use to query the host application\n ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes);\n if (constructor != null && constructor.IsPublic)\n {\n // lets be friendly and only do things legitimitely by only using valid constructors\n\n // we specified that we wanted a constructor that doesn't take parameters, so don't pass parameters\n ScriptingInterface.IScriptType1 scriptObject = constructor.Invoke(null) as ScriptingInterface.IScriptType1;\n if (scriptObject != null)\n {\n //Lets run our script and display its results\n MessageBox.Show(scriptObject.RunScript(50));\n }\n else\n {\n // hmmm, for some reason it didn't create the object\n // this shouldn't happen, as we have been doing checks all along, but we should\n // inform the user something bad has happened, and possibly request them to send\n // you the script so you can debug this problem\n }\n }\n else\n {\n // and even more friendly and explain that there was no valid constructor\n // found and thats why this script object wasn't run\n }\n }\n }\n }\n }\n }\n}\n" }, { "answer_id": 16969754, "author": "lukebuehler", "author_id": 408710, "author_profile": "https://Stackoverflow.com/users/408710", "pm_score": 0, "selected": false, "text": "Mono.CSharp.dll" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
137,935
<p>In Vim editor I opted <code>]I</code> on a function (in C++ code). This presented a list, which says <em>'Press ENTER or type command to continue'</em>.</p> <p>Now to jump to an occurrence say 6, I type <code>6</code> - but this is not working.</p> <p>What commands can I type in such a case, and how do I jump to Nth occurrence from this list?</p> <p><strong>Update:</strong></p> <p>Actually I tried <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> (eg :6) - but the moment I type <code>:</code> Vim enters Insert mode, and the colon gets inserted in the code instead.</p> <p><strong>Update</strong></p> <p>Assuming <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing <code>:</code> does not switch Vim to insert mode.</p>
[ { "answer_id": 137942, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "1: 345 my_func (int var)\n2: 4523 my_func (int var)\n3: 10032 my_func (3);\n" }, { "answer_id": 137956, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 0, "selected": false, "text": " :tag getfirst\n # pri kind tag file\n 1 F m getfirst /home/sthorne/work/.../FormData.py\n class:FakeFieldStorage\n def getfirst(self, k, default):\n ....\n 8 F m getfirst /home/sthorne/work/.../CGIForm.py\n class:CGIForm\n def getfirst(self, name):\nChoice number (<Enter> cancels):\n" }, { "answer_id": 138007, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": -1, "selected": false, "text": "123G :h G" }, { "answer_id": 142348, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 1, "selected": false, "text": "1: 345 my_func (int var)\n2: 4523 my_func (int var)\n3: 10032 my_func (3);\n" }, { "answer_id": 258108, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 0, "selected": false, "text": "[I [ CTRL+I" }, { "answer_id": 1062547, "author": "thoughton", "author_id": 128264, "author_profile": "https://Stackoverflow.com/users/128264", "pm_score": 1, "selected": false, "text": "[I // gives list of matches for word under cursor, potentially some matches are in headers. remember the number of the match you're interested in, eg. the 3rd\nq // quits the list of matches\n3[Ctrl-i // (with cursor in same position) jumps to third match\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14803/" ]
137,951
<p>I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it?</p>
[ { "answer_id": 137993, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 2, "selected": false, "text": " $('#client_id_of_datagrid input, #client_id_of_datagrid select')\n.each(function() {val = this.value; /* Do Stuff */})\n" }, { "answer_id": 138093, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": true, "text": "var txts = $get('client_id_of_datagrid').getElementsByTagName('input');\nvar ddls = $get('client_id_of_datagrid').getElementsByTagName('select');\n\nfor(var i=0;i<txts.length;i++){\n if(txts[i].type==='text'){\n /* do stuff */\n }\n}\n\nfor(var i=0;i<ddls.length;i++){\n /* do stuff */\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,952
<p>I decide to learn more about vim and its syntax highlighting. Using examples for others, I am creating my own syntax file for Markdown. I have seen <a href="http://www.vim.org/scripts/script.php?script_id=1242" rel="noreferrer">mkd.vim</a> and it has this problem too. My issue is between list items and code block highlighting.</p> <p>Code Block <a href="http://daringfireball.net/projects/markdown/syntax#precode" rel="noreferrer">definition</a>:</p> <ul> <li>first line is blank</li> <li>second line begins with at least 4 spaces or 1 tab</li> <li>block is finished with a blank line</li> </ul> <p>Example:</p> <pre><code>Regular text this is code, monospaced and left untouched by markdown another line of code Regular Text </code></pre> <p>My Vim syntax for code block:</p> <pre><code>syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock hi link mkdCodeBlock comment </code></pre> <p>Unorder List item <a href="http://daringfireball.net/projects/markdown/syntax#list" rel="noreferrer">definition</a>:</p> <ul> <li>first line is blank</li> <li>second line begins with a [-+*] followed by a space</li> <li>the list is finished with a blank line then a normal (non-list) line</li> <li>in between line items any number of blank lines can be added</li> <li>a sub list is specified by indenting (4 space or 1 tab)</li> <li>a line of normal text after a list item is include as a continuation of that list item</li> </ul> <p>Example:</p> <pre><code>Regular text - item 1 - sub item 1 - sub item 2 - item 2 this is part of item 2 so is this - item 3, still in the same list - sub item 1 - sub item 2 Regular text, list ends above </code></pre> <p>My Vim syntax for unorder list item definition (I only highlight <code>[-+*]</code>):</p> <pre><code>syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl hi link mkdListItem operator </code></pre> <p>I cannot get the highlighting to work with the last two rule for list and with a code block.</p> <p>This is an example that breaks my syntax highlighting:</p> <pre><code>Regular text - Item 1 - Item 2 part of item 2 - these 2 line should be highlighted as a list item - but they are highlighted as a code block </code></pre> <p>I currently cannot figure out how to get the highlighting to work the way I want it too</p> <hr> <p>Forgot to add a "global" syntax rule used in both rules listed below. It is to ensure a that they start with a blank line.</p> <pre><code>syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent </code></pre> <hr> <p>Another Note: I should have been more clear. In my syntax file, the List rules appear before the Blockquote Rules</p> <hr>
[ { "answer_id": 138186, "author": "hcs42", "author_id": 17916, "author_profile": "https://Stackoverflow.com/users/17916", "pm_score": 4, "selected": true, "text": "syn match mkdCodeBlock /\\(\\s\\{4,}\\|\\t\\{1,}\\).*\\n/ contained nextgroup=mkdCodeBlock \nhi link mkdCodeBlock comment\n\nsyn region mkdListItem start=/\\s*[-*+]\\s\\+/ matchgroup=pdcListText end=\".*\" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl \nsyn match mkdListSkipNL /\\s*\\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl\nhi link mkdListItem operator\n\nsyn match mkdBlankLine /^\\s*\\n/ nextgroup=mkdCodeBlock,mkdListItem transparent\n :help :syn-define" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873/" ]
137,975
<p>The <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton pattern</a> is a fully paid up member of the <a href="https://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer">GoF</a>'s <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">patterns book</a>, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for <a href="https://en.wikipedia.org/wiki/Factory_method_pattern" rel="noreferrer">factory classes</a>, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.</p> <p>Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?</p> <p>Please support your answers with "<em>facts, references, or specific expertise</em>"</p>
[ { "answer_id": 138017, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 6, "selected": false, "text": "public MyConstructor(Singleton singleton) {\n this.singleton = singleton;\n}\n public MyConstructor() {\n this.singleton = Singleton.getInstance();\n}\n" }, { "answer_id": 138021, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 3, "selected": false, "text": "void some_class::some_function(parameters, service_provider& srv)\n{\n srv.get<error_logger>().log(\"Hi there!\");\n this->another_function(some_other_parameters, srv);\n}\n" }, { "answer_id": 795871, "author": "mP.", "author_id": 56524, "author_profile": "https://Stackoverflow.com/users/56524", "pm_score": 3, "selected": false, "text": "Singleton.getInstance()" }, { "answer_id": 1115505, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 2, "selected": false, "text": "kill" }, { "answer_id": 2953477, "author": "Volodymyr Frolov", "author_id": 276773, "author_profile": "https://Stackoverflow.com/users/276773", "pm_score": 3, "selected": false, "text": "@Singleton" }, { "answer_id": 15026525, "author": "Uooo", "author_id": 1328300, "author_profile": "https://Stackoverflow.com/users/1328300", "pm_score": 6, "selected": false, "text": "SingletonDao public class SingletonDao {\n // songleton's static variable and getInstance() method etc. omitted\n public void writeXYZ(...){\n synchronized(...){\n // some database writing operations...\n }\n }\n}\n SingletonDao" }, { "answer_id": 33595283, "author": "Ilya Gazman", "author_id": 1129332, "author_profile": "https://Stackoverflow.com/users/1129332", "pm_score": 5, "selected": false, "text": "\n MyModel TestMyModel MyModel TestMyModel" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
138,000
<p>When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP.</p> <p>But when sent over HTTPS, different browsers gave different results:</p> <p>On Firefox 3.0.2: - The GET request doesn't reach the web server.</p> <p>On IE 7: - The GET request reached the web server.</p> <p>Does this have something to do with Firefox 3 getting stricter with untrusted certificates? Is there a way around this?</p> <p>I've already added the URL as an exception in Firefox's Certificate Manager. The error console doesn't report any error. I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown.</p> <p>Using both absolute and relative URL path doesn't work.</p> <p>Here's the code snippet:</p> <pre><code> var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); xmlHttp.send(null); } catch (e) { alert('Error sending HTTP GET request!'); return false; } </code></pre> <p>Thanks, Kenneth</p>
[ { "answer_id": 161889, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 1, "selected": false, "text": "// send HTTP GET request\ntry\n{\n xmlHttp.open(\"GET\", \"/[relative path to request]\", true);\n}\ncatch (e)\n{\n alert('Error sending HTTP GET request!');\n return false;\n}\n// we won't be handling any HTTP response\nxmlHttp.onreadystatechange=function()\n{\n // do nothing..\n}\n\n// Then send it.\nxmlHttp.send(null);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
138,028
<p>Is it possible to call a COM API from Java (specifically the HP/Mercury Quality Center OTA API)? If so, what's the best way?</p> <p>Is something like JACOB appropriate?</p> <p>Code fragments would be helpful for the basics :-)</p>
[ { "answer_id": 43658568, "author": "user2228895", "author_id": 2228895, "author_profile": "https://Stackoverflow.com/users/2228895", "pm_score": 2, "selected": false, "text": "MsWordApp comObj = this.factory.createObject(MsWordApp.class);\n\nDocuments documents = comObj.getDocuments();\n_Document myDocument = documents.Add();\n\nString path = new File(\".\").getAbsolutePath();\nmyDocument.SaveAs(path + \"\\\\abcdefg\", WdSaveFormat.wdFormatPDF);\ncomObj.Quit();\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
138,029
<p>After a bind a method to an event of a Tkinter element is there a way to get the method back?</p> <pre><code>&gt;&gt;&gt; root = Tkinter.Tk() &gt;&gt;&gt; frame = Tkinter.Frame(root, width=100, height=100) &gt;&gt;&gt; frame.bind('&lt;Button-1&gt;', lambda e: pprint('Click')) # function needed &gt;&gt;&gt; frame.pack() &gt;&gt;&gt; bound_event_method = frame.??? </code></pre>
[ { "answer_id": 138039, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 0, "selected": false, "text": "lambda print print()" }, { "answer_id": 226141, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": "bind .b <Button-1> doSomething\nputs \"the function is [bind .b <Button-1>]\"\n=> the function is doSomething\n e1.bind(\"<Button-1>\",doSomething)\ne1.bind(\"<Button-1>\")\n=> 'if {\"[-1208974516doSomething %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]\" == \"break\"} break\\n'\n def bindWidget(widget,event,func=None):\n '''Set or retrieve the binding for an event on a widget'''\n\n if not widget.__dict__.has_key(\"bindings\"): widget.bindings=dict()\n\n if func:\n widget.bind(event,func)\n widget.bindings[event] = func\n else:\n return(widget.bindings.setdefault(event,None))\n e1=Entry()\nprint \"before, binding for <Button-1>: %s\" % bindWidget(e1,\"<Button-1>\")\nbindWidget(e1,\"<Button-1>\",doSomething)\nprint \" after, binding for <Button-1>: %s\" % bindWidget(e1,\"<Button-1>\")\n before, binding for <Button-1>: None\n after, binding for <Button-1>: <function doSomething at 0xb7f2e79c>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
138,040
<p>I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs?</p>
[ { "answer_id": 138062, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 6, "selected": true, "text": "IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201\nSTYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU\n IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201\nSTYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME\n" }, { "answer_id": 5739386, "author": "steinybot", "author_id": 367796, "author_profile": "https://Stackoverflow.com/users/367796", "pm_score": 2, "selected": false, "text": "cs.style |= WS_POPUP | WS_THICKFRAME;\n" }, { "answer_id": 5739620, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "WS_THICKFRAME InitDialog AutoMove #if !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_)\n#define AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_\n\n#if _MSC_VER > 1000\n#pragma once\n#endif // _MSC_VER > 1000\n\n#include <vector>\n\nclass CBaseDialog : public CDialog\n{\n// Construction\npublic:\n CBaseDialog(UINT nIDTemplate, CWnd* pParent = NULL); // standard constructor\n\n void AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct);\n\n// Overrides\n // ClassWizard generated virtual function overrides\n //{{AFX_VIRTUAL(CBaseDialog)\nprotected:\n //}}AFX_VIRTUAL\n\nprotected:\n //{{AFX_MSG(CBaseDialog)\n virtual BOOL OnInitDialog();\n afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI);\n afx_msg void OnSize(UINT nType, int cx, int cy);\n //}}AFX_MSG\n DECLARE_MESSAGE_MAP()\n\npublic:\n bool m_bShowGripper; // ignored if not WS_THICKFRAME\n\nprivate:\n struct SMovingChild\n {\n HWND m_hWnd;\n double m_dXMoveFrac;\n double m_dYMoveFrac;\n double m_dXSizeFrac;\n double m_dYSizeFrac;\n CRect m_rcInitial;\n };\n typedef std::vector<SMovingChild> MovingChildren;\n\n MovingChildren m_MovingChildren;\n CSize m_szInitial;\n CSize m_szMinimum;\n HWND m_hGripper;\n};\n\n//{{AFX_INSERT_LOCATION}}\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\n\n#endif // !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_)\n #include \"stdafx.h\"\n#include \"BaseDialog.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\nCBaseDialog::CBaseDialog(UINT nIDTemplate, CWnd* pParent /*=NULL*/)\n : CDialog(nIDTemplate, pParent),\n m_bShowGripper(true),\n m_szMinimum(0, 0),\n m_hGripper(NULL)\n{\n}\n\n\nBEGIN_MESSAGE_MAP(CBaseDialog, CDialog)\n //{{AFX_MSG_MAP(CBaseDialog)\n ON_WM_GETMINMAXINFO()\n ON_WM_SIZE()\n //}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\nvoid CBaseDialog::AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct)\n{\n ASSERT((dXMovePct + dXSizePct) <= 100.0); // can't use more than 100% of the resize for the child\n ASSERT((dYMovePct + dYSizePct) <= 100.0); // can't use more than 100% of the resize for the child\n SMovingChild s;\n GetDlgItem(iID, &s.m_hWnd);\n ASSERT(s.m_hWnd != NULL);\n s.m_dXMoveFrac = dXMovePct / 100.0;\n s.m_dYMoveFrac = dYMovePct / 100.0;\n s.m_dXSizeFrac = dXSizePct / 100.0;\n s.m_dYSizeFrac = dYSizePct / 100.0;\n ::GetWindowRect(s.m_hWnd, &s.m_rcInitial);\n ScreenToClient(s.m_rcInitial);\n m_MovingChildren.push_back(s);\n}\n\nBOOL CBaseDialog::OnInitDialog()\n{\n CDialog::OnInitDialog();\n\n // use the initial dialog size as the default minimum\n if ((m_szMinimum.cx == 0) && (m_szMinimum.cy == 0))\n {\n CRect rcWindow;\n GetWindowRect(rcWindow);\n m_szMinimum = rcWindow.Size();\n }\n\n // keep the initial size of the client area as a baseline for moving/sizing controls\n CRect rcClient;\n GetClientRect(rcClient);\n m_szInitial = rcClient.Size();\n\n // create a gripper in the bottom-right corner\n if (m_bShowGripper && ((GetStyle() & WS_THICKFRAME) != 0))\n {\n SMovingChild s;\n s.m_rcInitial.SetRect(-GetSystemMetrics(SM_CXVSCROLL), -GetSystemMetrics(SM_CYHSCROLL), 0, 0);\n s.m_rcInitial.OffsetRect(rcClient.BottomRight());\n m_hGripper = CreateWindow(_T(\"Scrollbar\"), _T(\"size\"), WS_CHILD | WS_VISIBLE | SBS_SIZEGRIP,\n s.m_rcInitial.left, s.m_rcInitial.top, s.m_rcInitial.Width(), s.m_rcInitial.Height(),\n m_hWnd, NULL, AfxGetInstanceHandle(), NULL);\n ASSERT(m_hGripper != NULL);\n if (m_hGripper != NULL)\n {\n s.m_hWnd = m_hGripper;\n s.m_dXMoveFrac = 1.0;\n s.m_dYMoveFrac = 1.0;\n s.m_dXSizeFrac = 0.0;\n s.m_dYSizeFrac = 0.0;\n m_MovingChildren.push_back(s);\n\n // put the gripper first in the z-order so it paints first and doesn't obscure other controls\n ::SetWindowPos(m_hGripper, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);\n }\n }\n\n return TRUE; // return TRUE unless you set the focus to a control\n}\n\nvoid CBaseDialog::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) \n{\n CDialog::OnGetMinMaxInfo(lpMMI);\n\n if (lpMMI->ptMinTrackSize.x < m_szMinimum.cx)\n lpMMI->ptMinTrackSize.x = m_szMinimum.cx;\n if (lpMMI->ptMinTrackSize.y < m_szMinimum.cy)\n lpMMI->ptMinTrackSize.y = m_szMinimum.cy;\n}\n\nvoid CBaseDialog::OnSize(UINT nType, int cx, int cy) \n{\n CDialog::OnSize(nType, cx, cy);\n\n int iXDelta = cx - m_szInitial.cx;\n int iYDelta = cy - m_szInitial.cy;\n HDWP hDefer = NULL;\n for (MovingChildren::iterator p = m_MovingChildren.begin(); p != m_MovingChildren.end(); ++p)\n {\n if (p->m_hWnd != NULL)\n {\n CRect rcNew(p->m_rcInitial);\n rcNew.OffsetRect(int(iXDelta * p->m_dXMoveFrac), int(iYDelta * p->m_dYMoveFrac));\n rcNew.right += int(iXDelta * p->m_dXSizeFrac);\n rcNew.bottom += int(iYDelta * p->m_dYSizeFrac);\n if (hDefer == NULL)\n hDefer = BeginDeferWindowPos(m_MovingChildren.size());\n UINT uFlags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER;\n if ((p->m_dXSizeFrac != 0.0) || (p->m_dYSizeFrac != 0.0))\n uFlags |= SWP_NOCOPYBITS;\n DeferWindowPos(hDefer, p->m_hWnd, NULL, rcNew.left, rcNew.top, rcNew.Width(), rcNew.Height(), uFlags);\n }\n }\n if (hDefer != NULL)\n EndDeferWindowPos(hDefer);\n\n if (m_hGripper != NULL)\n ::ShowWindow(m_hGripper, (nType == SIZE_MAXIMIZED) ? SW_HIDE : SW_SHOW);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
138,043
<p>I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.</p> <p>I know that TcpClient will assign a new client side port when I open a connection to a given server.</p> <p>Is there a simple way to find the next open TCP port in .NET?</p> <p>I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.</p>
[ { "answer_id": 150974, "author": "TheSeeker", "author_id": 4829, "author_profile": "https://Stackoverflow.com/users/4829", "pm_score": 8, "selected": true, "text": "static int FreeTcpPort()\n{\n TcpListener l = new TcpListener(IPAddress.Loopback, 0);\n l.Start();\n int port = ((IPEndPoint)l.LocalEndpoint).Port;\n l.Stop();\n return port;\n}\n" }, { "answer_id": 38969868, "author": "yoavs", "author_id": 6313865, "author_profile": "https://Stackoverflow.com/users/6313865", "pm_score": 1, "selected": false, "text": "private int GetFreePortInRange(int PortStartIndex, int PortEndIndex)\n{\n DevUtils.LogDebugMessage(string.Format(\"GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}\", PortStartIndex, PortEndIndex));\n try\n {\n IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();\n\n IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners();\n List<int> usedServerTCpPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();\n\n IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners();\n List<int> usedServerUdpPorts = udpEndPoints.Select(p => p.Port).ToList<int>();\n\n TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();\n List<int> usedPorts = tcpConnInfoArray.Where(p=> p.State != TcpState.Closed).Select(p => p.LocalEndPoint.Port).ToList<int>();\n\n usedPorts.AddRange(usedServerTCpPorts.ToArray());\n usedPorts.AddRange(usedServerUdpPorts.ToArray());\n\n int unusedPort = 0;\n\n for (int port = PortStartIndex; port < PortEndIndex; port++)\n {\n if (!usedPorts.Contains(port))\n {\n unusedPort = port;\n break;\n }\n }\n DevUtils.LogDebugMessage(string.Format(\"Local unused Port:{0}\", unusedPort.ToString()));\n\n if (unusedPort == 0)\n {\n DevUtils.LogErrorMessage(\"Out of ports\");\n throw new ApplicationException(\"GetFreePortInRange, Out of ports\");\n }\n\n return unusedPort;\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message;\n DevUtils.LogErrorMessage(errorMessage);\n throw;\n }\n}\n\n\nprivate int GetLocalFreePort()\n{\n int hemoStartLocalPort = int.Parse(DBConfig.GetField(\"Site.Config.hemoStartLocalPort\"));\n int hemoEndLocalPort = int.Parse(DBConfig.GetField(\"Site.Config.hemoEndLocalPort\"));\n int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort);\n DevUtils.LogDebugMessage(string.Format(\"Local Free Port:{0}\", localPort.ToString()));\n return localPort;\n}\n\n\npublic void Connect(string host, int port)\n{\n try\n {\n // Create socket\n Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);\n\n var localPort = GetLocalFreePort();\n // Create an endpoint for the specified IP on any port\n IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);\n\n // Bind the socket to the endpoint\n socket.Bind(bindEndPoint);\n\n // Connect to host\n socket.Connect(IPAddress.Parse(host), port);\n\n socket.Dispose();\n }\n catch (SocketException ex)\n {\n // Get the error message\n string errorMessage = ex.Message;\n DevUtils.LogErrorMessage(errorMessage);\n }\n}\n\n\npublic void Connect2(string host, int port)\n{\n try\n {\n // Create socket\n\n var localPort = GetLocalFreePort();\n\n // Create an endpoint for the specified IP on any port\n IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);\n\n var client = new TcpClient(bindEndPoint);\n //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done\n\n // Connect to the host\n client.Connect(IPAddress.Parse(host), port);\n\n client.Close();\n }\n catch (SocketException ex)\n {\n // Get the error message\n string errorMessage = ex.Message;\n DevUtils.LogErrorMessage(errorMessage);\n }\n}\n" }, { "answer_id": 45384984, "author": "zumalifeguard", "author_id": 75129, "author_profile": "https://Stackoverflow.com/users/75129", "pm_score": 4, "selected": false, "text": "public static int GetAvailablePort(int startingPort)\n{\n var portArray = new List<int>();\n\n var properties = IPGlobalProperties.GetIPGlobalProperties();\n\n // Ignore active connections\n var connections = properties.GetActiveTcpConnections();\n portArray.AddRange(from n in connections\n where n.LocalEndPoint.Port >= startingPort\n select n.LocalEndPoint.Port);\n\n // Ignore active tcp listners\n var endPoints = properties.GetActiveTcpListeners();\n portArray.AddRange(from n in endPoints\n where n.Port >= startingPort\n select n.Port);\n\n // Ignore active UDP listeners\n endPoints = properties.GetActiveUdpListeners();\n portArray.AddRange(from n in endPoints\n where n.Port >= startingPort\n select n.Port);\n\n portArray.Sort();\n\n for (var i = startingPort; i < UInt16.MaxValue; i++)\n if (!portArray.Contains(i))\n return i;\n\n return 0;\n}\n" }, { "answer_id": 49408267, "author": "Eric Boumendil", "author_id": 249742, "author_profile": "https://Stackoverflow.com/users/249742", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Net;\nusing System.Net.Sockets;\n\n private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0);\n\n public static int GetAvailablePort()\n {\n using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n {\n socket.Bind(DefaultLoopbackEndpoint);\n return ((IPEndPoint)socket.LocalEndPoint).Port;\n }\n }\n" }, { "answer_id": 58526893, "author": "Daniel Rosenberg", "author_id": 6275530, "author_profile": "https://Stackoverflow.com/users/6275530", "pm_score": 2, "selected": false, "text": "private int GetNextUnusedPort(int min, int max)\n{\n if (max < min)\n throw new ArgumentException(\"Max cannot be less than min.\");\n\n var ipProperties = IPGlobalProperties.GetIPGlobalProperties();\n\n var usedPorts =\n ipProperties.GetActiveTcpConnections()\n .Where(connection => connection.State != TcpState.Closed)\n .Select(connection => connection.LocalEndPoint)\n .Concat(ipProperties.GetActiveTcpListeners())\n .Concat(ipProperties.GetActiveUdpListeners())\n .Select(endpoint => endpoint.Port)\n .ToArray();\n\n var firstUnused =\n Enumerable.Range(min, max - min)\n .Where(port => !usedPorts.Contains(port))\n .Select(port => new int?(port))\n .FirstOrDefault();\n\n if (!firstUnused.HasValue)\n throw new Exception($\"All local TCP ports between {min} and {max} are currently in use.\");\n\n return firstUnused.Value;\n}\n" }, { "answer_id": 58924521, "author": "Fatih TAN", "author_id": 6322573, "author_profile": "https://Stackoverflow.com/users/6322573", "pm_score": 4, "selected": false, "text": "public static int FindFreePort()\n{\n int port = 0;\n Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n try\n {\n IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);\n socket.Bind(localEP);\n localEP = (IPEndPoint)socket.LocalEndPoint;\n port = localEP.Port;\n }\n finally\n {\n socket.Close();\n }\n return port;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
138,045
<p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm" rel="noreferrer">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
[ { "answer_id": 138053, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 3, "selected": false, "text": "Type.GetProperty() Type.GetProperties() PropertyInfo var result = typeof(DateTime).GetProperty(\"Year\").GetValue(dt, null)\n Type.GetMethod() Type.GetMethods() MethodInfo var result = typeof(DateTime).GetMethod(\"ToLongDateString\").Invoke(dt, null);\n var result = dt.GetType().GetProperty(\"Year\").Invoke(dt, null);\n" }, { "answer_id": 138054, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 1, "selected": false, "text": "typeof(YourObjectType).GetProperty(\"PropertyName\").GetValue(instanceObjectToGetPropFrom, null);\n" }, { "answer_id": 138079, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": true, "text": "public static class ReflectionExt\n{\n public static object GetAttr(this object obj, string name)\n {\n Type type = obj.GetType();\n BindingFlags flags = BindingFlags.Instance | \n BindingFlags.Public | \n BindingFlags.GetProperty;\n\n return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);\n }\n}\n object value = ReflectionExt.GetAttr(obj, \"PropertyName\");\n object value = obj.GetAttr(\"PropertyName\");\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22562/" ]
138,071
<p>The questions says everything, take this example code: </p> <pre><code>&lt;ul id="css-id"&gt; &lt;li&gt; &lt;something:CustomControl ID="SomeThingElse" runat="server" /&gt; &lt;something:OtherCustomControl runat="server" /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?</p>
[ { "answer_id": 138082, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 4, "selected": true, "text": "protected void Application_Error(Object sender, EventArgs e)\n" }, { "answer_id": 138092, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 1, "selected": false, "text": "Error HttpApplication" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
138,073
<p><strong>Scenario:</strong> C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented. </p> <p><strong>Q:</strong> How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error &lt;> 0' does fire. I try to store the @@Error number, but it is always 0.</p> <p>Please help.</p>
[ { "answer_id": 138111, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 2, "selected": false, "text": "RAISERROR ... WITH LOG\n xp_logevent {error_number, 'message'} [, 'severity']\n" }, { "answer_id": 138114, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "@@ERROR IF @@ERROR <> 0 ...\n @@ERROR @@ERROR DECLARE @ErrorCode INT\n\nINSERT INTO Table ...\n\nSET @ErrorCode = @@ERROR\nIF @ErrorCode <> 0\nBEGIN\n INSERT INTO ErrorLog (ErrorCode, Message)\n VALUES (@ErrorCode, 'The INSERT operation failed.')\nEND\n" }, { "answer_id": 5868727, "author": "Sai Sherlekar", "author_id": 730593, "author_profile": "https://Stackoverflow.com/users/730593", "pm_score": 1, "selected": false, "text": "ALTER PROCEDURE [dbo].[StoreProcedureName] \n(\nparameters \n)\nAS\nBEGIN\n SET NOCOUNT On\n BEGIN TRY \n --type your query \n\n End Try\n BEGIN CATCH\n SELECT\n ERROR_NUMBER() AS ErrorNumber,\n ERROR_SEVERITY() AS ErrorSeverity,\n ERROR_STATE() AS ErrorState,\n ERROR_PROCEDURE() AS ErrorProcedure,\n ERROR_LINE() AS ErrorLine,\n ERROR_MESSAGE() AS ErrorMessage\n RETURN -1\n END CATCH\nEnd\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
138,096
<p>I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame.</p> <p>Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this. </p> <p>I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (<a href="http://dnrtv.com/default.aspx?showID=115" rel="noreferrer">http://dnrtv.com/default.aspx?showID=115</a>). </p>
[ { "answer_id": 138315, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 5, "selected": true, "text": "myFrame.Navigate(myPageObject);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ]
138,097
<p>I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.</p> <p>Is there another way to obtain the PID?</p>
[ { "answer_id": 138098, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 6, "selected": true, "text": "String pid = new File(\"/proc/self\").getCanonicalFile().getName();\n pid = java.io.File.new(\"/proc/self\").canonical_file.name\n" }, { "answer_id": 138332, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 3, "selected": false, "text": "String pid = ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0];\n" }, { "answer_id": 11396935, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 2, "selected": false, "text": "POSIX.java import java.util.*;\n\nclass POSIX\n{\n static { System.loadLibrary (\"POSIX\"); }\n native static int getpid ();\n}\n $ javac POSIX.java\n POSIX.h $ javah -jni POSIX\n POSIX.c #include \"POSIX.h\"\n\n#include <sys/types.h>\n#include <unistd.h>\n\nJNIEXPORT jint JNICALL Java_POSIX_getpid (JNIEnv *env, jclass cls)\n{\n return getpid ();\n}\n $ gcc -Wall -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include/linux -o libPOSIX.so -shared -Wl,-soname,libPOSIX.so POSIX.c -static -lc\n public class getpid\n{\n public static void main (String argv[])\n {\n System.out.println (POSIX.getpid ());\n }\n}\n javac getpid.java $ java getpid &\n[1] 21983\n$ 21983\n" }, { "answer_id": 12886699, "author": "Jarekczek", "author_id": 772981, "author_profile": "https://Stackoverflow.com/users/772981", "pm_score": 2, "selected": false, "text": "import java.io.*;\nimport java.util.Scanner;\n\npublic class Pid2\n{\n public static void main(String sArgs[])\n throws java.io.IOException, InterruptedException\n {\n Process p = Runtime.getRuntime().exec(\n new String[] { \"sh\", \"-c\", \"ps h -o ppid $$\" });\n p.waitFor();\n Scanner sc = new Scanner(p.getInputStream());\n System.out.println(\"My pid: \" + sc.nextInt()); \n Thread.sleep(5000);\n }\n}\n nice `ps h -o ppid $$`\n exec" }, { "answer_id": 52526755, "author": "Xavier Guihot", "author_id": 9297144, "author_profile": "https://Stackoverflow.com/users/9297144", "pm_score": 1, "selected": false, "text": "Java 9 ProcessHandle.current().pid();\n ProcessHandle pid ProcessHandle java.lang" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
138,099
<p>GWT's serializer has limited <code>java.io.Serializable</code> support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example <a href="http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable" rel="noreferrer">this FAQ entry</a> says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist.</p> <p>The generated list contains a number of types that are part of the standard library, such as <code>java.lang.String</code> and <code>java.util.HashMap</code>. I get an error when trying to serialize <code>java.sql.Date</code>, which implements the <code>Serializable</code> interface, but is not on the whitelist. How can I add this type to the list?</p>
[ { "answer_id": 144894, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 5, "selected": true, "text": "public String getStringForDates(ArrayList<java.util.Date> dates);\n public Object getObjectForString(String str);\n" }, { "answer_id": 992745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "Dummy Dummy dummy(Dummy d);\n Dummy dummy(Dummy d) { return d; }\n void dummy(Dummy d, AsyncCallback< Dummy> callback);\n Dummy Dummy public class Dummy implements IsSerializable {\n private java.sql.Date d;\n}\n" }, { "answer_id": 1230180, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class SerializableWhitelist implements IsSerializable {\n String[] dummy1;\n SomeOtherThingsIWishToSerialize dummy2;\n}\n .client" }, { "answer_id": 1533719, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "war/<app>/gwt/*.gwt.rpc" }, { "answer_id": 1627181, "author": "Domchi", "author_id": 29192, "author_profile": "https://Stackoverflow.com/users/29192", "pm_score": 0, "selected": false, "text": "/**\n * Used to instantiate GWT server in Spring context.\n *\n * Original version from <a href=\"http://docs.google.com/Doc?docid=dw2zgx2_25492p5qxfq&hl=en\">this tutorial</a>.\n * \n * ...fixed to work as explained <a href=\"http://blog.js-development.com/2009/09/gwt-meets-spring.html\">in this tutorial</a>.\n * \n * ...and then fixed to use StandardSerializationPolicy as explained in\n * <a href=\"http://markmail.org/message/k5j2vni6yzcokjsw\">this message</a> to allow\n * using Serializable instead of IsSerializable in model.\n */\npublic class GWTController extends RemoteServiceServlet implements Controller, ServletContextAware {\n\n // Instance fields\n\n private RemoteService remoteService;\n\n private Class<? extends RemoteService> remoteServiceClass;\n\n private ServletContext servletContext;\n\n // Public methods\n\n /**\n * Call GWT's RemoteService doPost() method and return null.\n * \n * @param request\n * The current HTTP request\n * @param response\n * The current HTTP response\n * @return A ModelAndView to render, or null if handled directly\n * @throws Exception\n * In case of errors\n */\n public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {\n doPost(request, response);\n return null; // response handled by GWT RPC over XmlHttpRequest\n }\n\n /**\n * Process the RPC request encoded into the payload string and return a string that encodes either the method return\n * or an exception thrown by it.\n * \n * @param payload\n * The RPC payload\n */\n public String processCall(String payload) throws SerializationException {\n try {\n RPCRequest rpcRequest = RPC.decodeRequest(payload, this.remoteServiceClass, this);\n\n // delegate work to the spring injected service\n return RPC.invokeAndEncodeResponse(this.remoteService, rpcRequest.getMethod(), rpcRequest.getParameters(), rpcRequest.getSerializationPolicy());\n } catch (IncompatibleRemoteServiceException e) {\n return RPC.encodeResponseForFailure(null, e);\n }\n }\n\n /**\n * Setter for Spring injection of the GWT RemoteService object.\n * \n * @param RemoteService\n * The GWT RemoteService implementation that will be delegated to by the {@code GWTController}.\n */\n public void setRemoteService(RemoteService remoteService) {\n this.remoteService = remoteService;\n this.remoteServiceClass = this.remoteService.getClass();\n }\n\n @Override\n public ServletContext getServletContext() {\n return servletContext;\n }\n\n public void setServletContext(ServletContext servletContext) {\n this.servletContext = servletContext;\n }\n}\n" }, { "answer_id": 7532213, "author": "Glenn", "author_id": 924369, "author_profile": "https://Stackoverflow.com/users/924369", "pm_score": 0, "selected": false, "text": "public class GWTSerializableTypes extends SomeTypeInServiceInterface implements IsSerializable {\n Long l;\n Double d;\n private GWTSerializableTypes() {}\n}\n" }, { "answer_id": 14733419, "author": "Dominic Tracey", "author_id": 1211550, "author_profile": "https://Stackoverflow.com/users/1211550", "pm_score": 0, "selected": false, "text": "Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO, \"Foo\");\n @Override\n protected void serialize(Object instance, String typeSignature)\n throws SerializationException {\n assert (instance != null);\n\n Class<?> clazz = getClassForSerialization(instance);\n\n try {\n serializationPolicy.validateSerialize(clazz);\n } catch (SerializationException e) {\n throw new SerializationException(e.getMessage() + \": instance = \" + instance);\n }\n serializeImpl(instance, clazz);\n }\n com.google.gwt.user.client.rpc.SerializationException: Type 'net.your.class' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = net.your.class@9c7edce\n at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:619)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3562/" ]
138,105
<p>Is there a way in Delphi 7 to find out if a pop-up menu is visible (shown on the screen) or not, since it lacks a Visible property.</p>
[ { "answer_id": 139161, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 2, "selected": false, "text": "procedure TForm1.WMContextMenu(var Message: TWMContextMenu);\nbegin\n FPopupActive := True;\n try\n OutputDebugString(PChar(Format('popup opening', [])));\n inherited;\n finally\n FPopupActive := False;\n OutputDebugString(PChar(Format('popup closed', [])));\n end;\nend;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6482/" ]
138,117
<p>how to send rich text message in system.net.mail need code for send a mail as html</p>
[ { "answer_id": 138128, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 2, "selected": false, "text": "System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();\nmm.Body = \"<html>...</html>\";\nmm.IsBodyHtml = true;\n" }, { "answer_id": 138134, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": true, "text": "//create the mail message\n MailMessage mail = new MailMessage();\n\n //set the addresses\n mail.From = new MailAddress(\"me@mycompany.com\");\n mail.To.Add(\"you@yourcompany.com\");\n\n //set the content\n mail.Subject = \"This is an email\";\n mail.Body = \"<b>This is bold</b> <font color=#336699>This is blue</font>\";\n mail.IsBodyHtml = true;\n\n //send the message\n SmtpClient smtp = new SmtpClient(\"127.0.0.1\");\n smtp.Send(mail);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
138,122
<p>I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.</p> <p>I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information.</p> <p>The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render.</p> <p>I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique.</p> <p>any thoughts?</p>
[ { "answer_id": 138143, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 3, "selected": true, "text": "BITMAPINFOHEADER bmi = { sizeof(bmi) };\nbmi.biWidth = 20000;\nbmi.biHeight = 20000;\nbmi.biPlanes = 1;\nbmi.biBitCount = 16;\nHDC hdc = CreateCompatibleDC(NULL);\nBYTE* pbData = 0;\nHBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pbData, NULL, 0);\nDeleteObject(SelectObject(hdc, hbm));\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22564/" ]
138,132
<p><strong>Here's the situation</strong>: I'm trying my hand at some MySpace page customisations. If you've <a href="https://stackoverflow.com/questions/116610/myspace-dom">ever tried</a> [stackoverflow], I'm sure you understand how frustrating it can be.<br> Basically it can be all customised via CSS, within a certain set of rules (e.g. the '#' character is not allowed...how useful!).<br> Have a look at this <a href="http://www.mikeindustries.com/blog/archive/2006/04/hacking-myspace-layouts" rel="nofollow noreferrer">blog</a> if you want more info, I used it as the basis for my customisations</p> <p>So the only problem is with the comments section, where 'friends' post whatever they feel like. It already has...</p> <pre><code>max-width:423px; </code></pre> <p>...set on the table, but I've discovered if long URLs are posted in the comment section, it blows out the table width, regardless of the max setting!</p> <p><strong>Question</strong>: Is there a way to manage text that is going to push the width of the table?<br> Perhaps splitting/chopping the string? Or is there more I should be doing..?<br> The URLs are posted as text, not hrefs.</p> <p>Using Firefox and Firebug btw.</p> <p><strong>Edit</strong>: Also javascript is not allowed ;)</p> <p><strong>Another edit</strong> Just checked with IE7, and it seems to work.. so firefox is being the hassle in this case..</p>
[ { "answer_id": 138151, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 0, "selected": false, "text": " overflow: hidden\n" }, { "answer_id": 138154, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<div style=\"width: 50px; word-wrap: break-word\">insertsuperlongwordhereplease</div>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
138,133
<p>Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes?</p>
[ { "answer_id": 1438327, "author": "Christian", "author_id": 54193, "author_profile": "https://Stackoverflow.com/users/54193", "pm_score": 3, "selected": true, "text": "public Rational(int numerator, int denominator)\n{\n Contract.Requires(denominator ! = 0);\n \n this.numerator = numerator;\n this.denominator = denominator;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
138,144
<p>What essential things (functions, aliases, start up scripts) do you have in your profile?</p>
[ { "answer_id": 138224, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 2, "selected": false, "text": "############################################################################## \n# Get an XPath Navigator object based on the input string containing xml\nfunction get-xpn ($text) { \n $rdr = [System.IO.StringReader] $text\n $trdr = [system.io.textreader]$rdr\n $xpdoc = [System.XML.XPath.XPathDocument] $trdr\n $xpdoc.CreateNavigator()\n}\n" }, { "answer_id": 138229, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 3, "selected": false, "text": "############################################################################## \n## Search the PowerShell help documentation for a given keyword or regular \n## expression.\n## \n## Example:\n## Get-HelpMatch hashtable\n## Get-HelpMatch \"(datetime|ticks)\"\n############################################################################## \nfunction apropos {\n\n param($searchWord = $(throw \"Please specify content to search for\"))\n\n $helpNames = $(get-help *)\n\n foreach($helpTopic in $helpNames)\n {\n $content = get-help -Full $helpTopic.Name | out-string\n if($content -match $searchWord)\n { \n $helpTopic | select Name,Synopsis\n }\n }\n}\n" }, { "answer_id": 139102, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 1, "selected": false, "text": "$MaximumHistoryCount=1024 \nfunction hist {get-history -count 256 | %{$_.commandline}}\n\nNew-Alias which get-command\n\nfunction guidConverter([byte[]] $gross){ $GUID = \"{\" + $gross[3].ToString(\"X2\") + `\n$gross[2].ToString(\"X2\") + $gross[1].ToString(\"X2\") + $gross[0].ToString(\"X2\") + \"-\" + `\n$gross[5].ToString(\"X2\") + $gross[4].ToString(\"X2\") + \"-\" + $gross[7].ToString(\"X2\") + `\n$gross[6].ToString(\"X2\") + \"-\" + $gross[8].ToString(\"X2\") + $gross[9].ToString(\"X2\") + \"-\" +` \n$gross[10].ToString(\"X2\") + $gross[11].ToString(\"X2\") + $gross[12].ToString(\"X2\") + `\n$gross[13].ToString(\"X2\") + $gross[14].ToString(\"X2\") + $gross[15].ToString(\"X2\") + \"}\" $GUID }\n" }, { "answer_id": 145882, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 3, "selected": false, "text": "prompt() $HOME" }, { "answer_id": 145893, "author": "user15071", "author_id": 15071, "author_profile": "https://Stackoverflow.com/users/15071", "pm_score": 3, "selected": false, "text": "# ----------------------------------------------------------\n# msdn search for win32 APIs.\n# ----------------------------------------------------------\n\nfunction Search-MSDNWin32\n{\n\n $url = 'http://search.msdn.microsoft.com/?query=';\n\n $url += $args[0];\n\n for ($i = 1; $i -lt $args.count; $i++) {\n $url += '+';\n $url += $args[$i];\n }\n\n $url += '&locale=en-us&refinement=86&ac=3';\n\n Open-IE($url);\n}\n\n# ----------------------------------------------------------\n# Open Internet Explorer given the url.\n# ----------------------------------------------------------\n\nfunction Open-IE ($url)\n{ \n $ie = new-object -comobject internetexplorer.application;\n\n $ie.Navigate($url);\n\n $ie.Visible = $true;\n}\n" }, { "answer_id": 146937, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 4, "selected": false, "text": "### ---------------------------------------------------------------------------\n### Load function / filter definition library\n### ---------------------------------------------------------------------------\n\n Get-ChildItem scripts:\\lib-*.ps1 | % { \n . $_\n write-host \"Loading library file:`t$($_.name)\"\n }\n" }, { "answer_id": 146945, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "$env:path += \";$profiledir\\scripts\"\nNew-PSDrive -Name Scripts -PSProvider FileSystem -Root $profiledir\\scripts\n" }, { "answer_id": 146952, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "$snapins = @(\n \"Quest.ActiveRoles.ADManagement\",\n \"PowerGadgets\",\n \"VMware.VimAutomation.Core\",\n \"NetCmdlets\"\n)\n$snapins | ForEach-Object { \n if ( Get-PSSnapin -Registered $_ -ErrorAction SilentlyContinue ) {\n Add-PSSnapin $_\n }\n}\n" }, { "answer_id": 158779, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "\n #==============================================================================\n# Jared Parsons PowerShell Profile (jaredp@rantpack.org) \n#==============================================================================\n\n#==============================================================================\n# Common Variables Start\n#==============================================================================\n$global:Jsh = new-object psobject \n$Jsh | add-member NoteProperty \"ScriptPath\" $(split-path -parent $MyInvocation.MyCommand.Definition) \n$Jsh | add-member NoteProperty \"ConfigPath\" $(split-path -parent $Jsh.ScriptPath)\n$Jsh | add-member NoteProperty \"UtilsRawPath\" $(join-path $Jsh.ConfigPath \"Utils\")\n$Jsh | add-member NoteProperty \"UtilsPath\" $(join-path $Jsh.UtilsRawPath $env:PROCESSOR_ARCHITECTURE)\n$Jsh | add-member NoteProperty \"GoMap\" @{}\n$Jsh | add-member NoteProperty \"ScriptMap\" @{}\n\n#==============================================================================\n\n#==============================================================================\n# Functions \n#==============================================================================\n\n# Load snapin's if they are available\nfunction Jsh.Load-Snapin([string]$name) {\n $list = @( get-pssnapin | ? { $_.Name -eq $name })\n if ( $list.Length -gt 0 ) {\n return; \n }\n\n $snapin = get-pssnapin -registered | ? { $_.Name -eq $name }\n if ( $snapin -ne $null ) {\n add-pssnapin $name\n }\n}\n\n# Update the configuration from the source code server\nfunction Jsh.Update-WinConfig([bool]$force=$false) {\n\n # First see if we've updated in the last day \n $target = join-path $env:temp \"Jsh.Update.txt\"\n $update = $false\n if ( test-path $target ) {\n $last = [datetime] (gc $target)\n if ( ([DateTime]::Now - $last).Days -gt 1) {\n $update = $true\n }\n } else {\n $update = $true;\n }\n\n if ( $update -or $force ) {\n write-host \"Checking for winconfig updates\"\n pushd $Jsh.ConfigPath\n $output = @(& svn update)\n if ( $output.Length -gt 1 ) {\n write-host \"WinConfig updated. Re-running configuration\"\n cd $Jsh.ScriptPath\n & .\\ConfigureAll.ps1\n . .\\Profile.ps1\n }\n\n sc $target $([DateTime]::Now)\n popd\n }\n}\n\nfunction Jsh.Push-Path([string] $location) { \n go $location $true \n}\nfunction Jsh.Go-Path([string] $location, [bool]$push = $false) {\n if ( $location -eq \"\" ) {\n write-output $Jsh.GoMap\n } elseif ( $Jsh.GoMap.ContainsKey($location) ) {\n if ( $push ) {\n push-location $Jsh.GoMap[$location]\n } else {\n set-location $Jsh.GoMap[$location]\n }\n } elseif ( test-path $location ) {\n if ( $push ) {\n push-location $location\n } else {\n set-location $location\n }\n } else {\n write-output \"$loctaion is not a valid go location\"\n write-output \"Current defined locations\"\n write-output $Jsh.GoMap\n }\n}\n\nfunction Jsh.Run-Script([string] $name) {\n if ( $Jsh.ScriptMap.ContainsKey($name) ) {\n . $Jsh.ScriptMap[$name]\n } else {\n write-output \"$name is not a valid script location\"\n write-output $Jsh.ScriptMap\n }\n}\n\n\n# Set the prompt\nfunction prompt() {\n if ( Test-Admin ) { \n write-host -NoNewLine -f red \"Admin \"\n }\n write-host -NoNewLine -ForegroundColor Green $(get-location)\n foreach ( $entry in (get-location -stack)) {\n write-host -NoNewLine -ForegroundColor Red '+';\n }\n write-host -NoNewLine -ForegroundColor Green '>'\n ' '\n}\n\n#==============================================================================\n\n#==============================================================================\n# Alias \n#==============================================================================\nset-alias gcid Get-ChildItemDirectory\nset-alias wget Get-WebItem\nset-alias ss select-string\nset-alias ssr Select-StringRecurse \nset-alias go Jsh.Go-Path\nset-alias gop Jsh.Push-Path\nset-alias script Jsh.Run-Script\nset-alias ia Invoke-Admin\nset-alias ica Invoke-CommandAdmin\nset-alias isa Invoke-ScriptAdmin\n#==============================================================================\n\npushd $Jsh.ScriptPath\n\n# Setup the go locations\n$Jsh.GoMap[\"ps\"] = $Jsh.ScriptPath\n$Jsh.GoMap[\"config\"] = $Jsh.ConfigPath\n$Jsh.GoMap[\"~\"] = \"~\"\n\n# Setup load locations\n$Jsh.ScriptMap[\"profile\"] = join-path $Jsh.ScriptPath \"Profile.ps1\"\n$Jsh.ScriptMap[\"common\"] = $(join-path $Jsh.ScriptPath \"LibraryCommon.ps1\")\n$Jsh.ScriptMap[\"svn\"] = $(join-path $Jsh.ScriptPath \"LibrarySubversion.ps1\")\n$Jsh.ScriptMap[\"subversion\"] = $(join-path $Jsh.ScriptPath \"LibrarySubversion.ps1\")\n$Jsh.ScriptMap[\"favorites\"] = $(join-path $Jsh.ScriptPath \"LibraryFavorites.ps1\")\n$Jsh.ScriptMap[\"registry\"] = $(join-path $Jsh.ScriptPath \"LibraryRegistry.ps1\")\n$Jsh.ScriptMap[\"reg\"] = $(join-path $Jsh.ScriptPath \"LibraryRegistry.ps1\")\n$Jsh.ScriptMap[\"token\"] = $(join-path $Jsh.ScriptPath \"LibraryTokenize.ps1\")\n$Jsh.ScriptMap[\"unit\"] = $(join-path $Jsh.ScriptPath \"LibraryUnitTest.ps1\")\n$Jsh.ScriptMap[\"tfs\"] = $(join-path $Jsh.ScriptPath \"LibraryTfs.ps1\")\n$Jsh.ScriptMap[\"tab\"] = $(join-path $Jsh.ScriptPath \"TabExpansion.ps1\")\n\n# Load the common functions\n. script common\n. script tab\n$global:libCommonCertPath = (join-path $Jsh.ConfigPath \"Data\\Certs\\jaredp_code.pfx\")\n\n# Load the snapin's we want\nJsh.Load-Snapin \"pscx\"\nJsh.Load-Snapin \"JshCmdlet\" \n\n# Setup the Console look and feel\n$host.UI.RawUI.ForegroundColor = \"Yellow\"\nif ( Test-Admin ) {\n $title = \"Administrator Shell - {0}\" -f $host.UI.RawUI.WindowTitle\n $host.UI.RawUI.WindowTitle = $title;\n}\n\n# Call the computer specific profile\n$compProfile = join-path \"Computers\" ($env:ComputerName + \"_Profile.ps1\")\nif ( -not (test-path $compProfile)) { ni $compProfile -type File | out-null }\nwrite-host \"Computer profile: $compProfile\"\n. \".\\$compProfile\"\n$Jsh.ScriptMap[\"cprofile\"] = resolve-path ($compProfile)\n\n# If the computer name is the same as the domain then we are not \n# joined to active directory\nif ($env:UserDomain -ne $env:ComputerName ) {\n # Call the domain specific profile data\n write-host \"Domain $env:UserDomain\"\n $domainProfile = join-path $env:UserDomain \"Profile.ps1\"\n if ( -not (test-path $domainProfile)) { ni $domainProfile -type File | out-null }\n . \".\\$domainProfile\"\n}\n\n# Run the get-fortune command if JshCmdlet was loaded\nif ( get-command \"get-fortune\" -ea SilentlyContinue ) {\n get-fortune -timeout 1000\n}\n\n# Finished with the profile, go back to the original directory\npopd\n\n# Look for updates\nJsh.Update-WinConfig\n\n# Because this profile is run in the same context, we need to remove any \n# variables manually that we don't want exposed outside this script\n" }, { "answer_id": 255709, "author": "Alex", "author_id": 19081, "author_profile": "https://Stackoverflow.com/users/19081", "pm_score": 2, "selected": false, "text": "function ha {\n Get-History -count $MaximumHistoryCount\n}\n" }, { "answer_id": 385718, "author": "nabiy", "author_id": 48286, "author_profile": "https://Stackoverflow.com/users/48286", "pm_score": 3, "selected": false, "text": "function df {\n $colItems = Get-wmiObject -class \"Win32_LogicalDisk\" -namespace \"root\\CIMV2\" `\n -computername localhost\n\n foreach ($objItem in $colItems) {\n write $objItem.DeviceID $objItem.Description $objItem.FileSystem `\n ($objItem.Size / 1GB).ToString(\"f3\") ($objItem.FreeSpace / 1GB).ToString(\"f3\")\n\n }\n}\n" }, { "answer_id": 394187, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "$width = ($Host.UI.RawUI.WindowSize.Width - 2 - $(Get-Location).ToString().Length)\n$hr = New-Object System.String @('-',$width)\nWrite-Host -ForegroundColor Red $(Get-Location) $hr\n" }, { "answer_id": 1435515, "author": "Precipitous", "author_id": 77784, "author_profile": "https://Stackoverflow.com/users/77784", "pm_score": 1, "selected": false, "text": "PS > . .\\DotSourceThisToLoadSomeHandyEventLogMonitoringFunctions.ps1\n # Using a target web service that requires SSL, but server is self-signed. \n# Without this, we'll fail unable to establish trust relationship. \nfunction Set-CertificateValidationCallback\n{\n try\n {\n Add-Type @'\n using System;\n\n public static class CertificateAcceptor{\n\n public static void SetAccept()\n {\n System.Net.ServicePointManager.ServerCertificateValidationCallback = AcceptCertificate;\n }\n\n private static bool AcceptCertificate(Object sender,\n System.Security.Cryptography.X509Certificates.X509Certificate certificate,\n System.Security.Cryptography.X509Certificates.X509Chain chain,\n System.Net.Security.SslPolicyErrors policyErrors)\n {\n Console.WriteLine(\"Accepting certificate and ignoring any SSL errors.\");\n return true;\n }\n }\n'@\n }\n catch {} # Already exists? Find a better way to check.\n\n [CertificateAcceptor]::SetAccept()\n}\n" }, { "answer_id": 1913201, "author": "icnivad", "author_id": 232756, "author_profile": "https://Stackoverflow.com/users/232756", "pm_score": 2, "selected": false, "text": "Set-PSDebug -Strict \n" }, { "answer_id": 1995576, "author": "Raoul Supercopter", "author_id": 57123, "author_profile": "https://Stackoverflow.com/users/57123", "pm_score": 5, "selected": false, "text": "#\n# useful agregate\n#\nfunction count\n{\n BEGIN { $x = 0 }\n PROCESS { $x += 1 }\n END { $x }\n}\n\nfunction product\n{\n BEGIN { $x = 1 }\n PROCESS { $x *= $_ }\n END { $x }\n}\n\nfunction sum\n{\n BEGIN { $x = 0 }\n PROCESS { $x += $_ }\n END { $x }\n}\n\nfunction average\n{\n BEGIN { $max = 0; $curr = 0 }\n PROCESS { $max += $_; $curr += 1 }\n END { $max / $curr }\n}\n function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) }\nfunction prompt\n{\n # Write the time \n write-host \"[\" -noNewLine\n write-host $(Get-Time) -foreground yellow -noNewLine\n write-host \"] \" -noNewLine\n # Write the path\n write-host $($(Get-Location).Path.replace($home,\"~\").replace(\"\\\",\"/\")) -foreground green -noNewLine\n write-host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine\n return \"> \"\n}\n # LS.MSH \n# Colorized LS function replacement \n# /\\/\\o\\/\\/ 2006 \n# http://mow001.blogspot.com \nfunction LL\n{\n param ($dir = \".\", $all = $false) \n\n $origFg = $host.ui.rawui.foregroundColor \n if ( $all ) { $toList = ls -force $dir }\n else { $toList = ls $dir }\n\n foreach ($Item in $toList) \n { \n Switch ($Item.Extension) \n { \n \".Exe\" {$host.ui.rawui.foregroundColor = \"Yellow\"} \n \".cmd\" {$host.ui.rawui.foregroundColor = \"Red\"} \n \".msh\" {$host.ui.rawui.foregroundColor = \"Red\"} \n \".vbs\" {$host.ui.rawui.foregroundColor = \"Red\"} \n Default {$host.ui.rawui.foregroundColor = $origFg} \n } \n if ($item.Mode.StartsWith(\"d\")) {$host.ui.rawui.foregroundColor = \"Green\"}\n $item \n } \n $host.ui.rawui.foregroundColor = $origFg \n}\n\nfunction lla\n{\n param ( $dir=\".\")\n ll $dir $true\n}\n\nfunction la { ls -force }\n # behave like a grep command\n# but work on objects, used\n# to be still be allowed to use grep\nfilter match( $reg )\n{\n if ($_.tostring() -match $reg)\n { $_ }\n}\n\n# behave like a grep -v command\n# but work on objects\nfilter exclude( $reg )\n{\n if (-not ($_.tostring() -match $reg))\n { $_ }\n}\n\n# behave like match but use only -like\nfilter like( $glob )\n{\n if ($_.toString() -like $glob)\n { $_ }\n}\n\nfilter unlike( $glob )\n{\n if (-not ($_.tostring() -like $glob))\n { $_ }\n}\n" }, { "answer_id": 2191475, "author": "JMS", "author_id": 56876, "author_profile": "https://Stackoverflow.com/users/56876", "pm_score": 2, "selected": false, "text": "profile.ps1 Addons PSDrive go go vsp C:\\Visual Studio 2008\\Projects Set-Location Set-Location Get-ChildItem mkdir Set-Location xyz New-Item xyz -Type Directory" }, { "answer_id": 7668105, "author": "Stisfa", "author_id": 595317, "author_profile": "https://Stackoverflow.com/users/595317", "pm_score": 2, "selected": false, "text": "Function funcOpenPowerShellProfile\n{\n Notepad $PROFILE\n}\n\nSet-Alias fop funcOpenPowerShellProfile\n fop Notepad $PROFILE Function funcOpenPowerShellProfile\n{\n $fileProfileBackup = $PROFILE + '.bak'\n cp $PROFILE $fileProfileBackup\n PowerShell_ISE $PROFILE # Replace with Desired IDE/ISE for Syntax Highlighting\n}\n\nSet-Alias fop funcOpenPowerShellProfile\n Function funcOpenPowerShellProfile\n{\n $fileProfilePathParts = @($PROFILE.Split('\\'))\n $fileProfileName = $fileProfilePathParts[-1]\n $fileProfilePathPartNum = 0\n $fileProfileHostPath = $fileProfilePathParts[$fileProfilePathPartNum] + '\\'\n $fileProfileHostPathPartsCount = $fileProfilePathParts.Count - 2\n # Arrays start at 0, but the Count starts at 1; if both started at 0 or 1, \n # then a -1 would be fine, but the realized discrepancy is 2\n Do\n {\n $fileProfilePathPartNum++\n $fileProfileHostPath = $fileProfileHostPath + `\n $fileProfilePathParts[$fileProfilePathPartNum] + '\\'\n }\n While\n (\n $fileProfilePathPartNum -LT $fileProfileHostPathPartsCount\n )\n $fileProfileBackupTime = [string](date -format u) -replace \":\", \"\"\n $fileProfileBackup = $fileProfileHostPath + `\n $fileProfileBackupTime + ' - ' + $fileProfileName + '.bak'\n cp $PROFILE $fileProfileBackup\n\n cd $fileProfileHostPath\n $fileProfileBackupNamePattern = $fileProfileName + '.bak'\n $fileProfileBackups = @(ls | Where {$_.Name -Match $fileProfileBackupNamePattern} | `\n Sort Name)\n $fileProfileBackupsCount = $fileProfileBackups.Count\n $fileProfileBackupThreshold = 5 # Change as Desired\n If\n (\n $fileProfileBackupsCount -GT $fileProfileBackupThreshold\n )\n {\n $fileProfileBackupsDeleteNum = $fileProfileBackupsCount - `\n $fileProfileBackupThreshold\n $fileProfileBackupsIndexNum = 0\n Do\n {\n\n rm $fileProfileBackups[$fileProfileBackupsIndexNum]\n $fileProfileBackupsIndexNum++;\n $fileProfileBackupsDeleteNum--\n }\n While\n (\n $fileProfileBackupsDeleteNum -NE 0\n )\n }\n\n PowerShell_ISE $PROFILE\n # Replace 'PowerShell_ISE' with Desired IDE (IDE's path may be needed in \n # '$Env:PATH' for this to work; if you can start it from the \"Run\" window, \n # you should be fine)\n}\n\nSet-Alias fop funcOpenPowerShellProfile\n" }, { "answer_id": 10337172, "author": "Bill Barry", "author_id": 108993, "author_profile": "https://Stackoverflow.com/users/108993", "pm_score": 2, "selected": false, "text": "function w {\n explorer .\n}\n function startover {\n iisreset /restart\n iisreset /stop\n\n rm \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files\\*.*\" -recurse -force -Verbose\n\n iisreset /start\n}\n function edit($x) {\n . 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe' $x\n}\n" }, { "answer_id": 15710210, "author": "Christopher Douglas", "author_id": 1304390, "author_profile": "https://Stackoverflow.com/users/1304390", "pm_score": 3, "selected": false, "text": "write-host \"Your modules are...\" -ForegroundColor Red\nGet-module -li\n function prompt\n{\n $host.UI.RawUI.WindowTitle = \"ShellPower\"\n # Need to still show the working directory.\n #Write-Host \"You landed in $PWD\"\n\n # Nerd up, yo.\n $Str = \"Root@The Matrix\"\n \"$str> \"\n}\n # Explorer command\nfunction Explore\n{\n param\n (\n [Parameter(\n Position = 0,\n ValueFromPipeline = $true,\n Mandatory = $true,\n HelpMessage = \"This is the path to explore...\"\n )]\n [ValidateNotNullOrEmpty()]\n [string]\n # First parameter is the path you're going to explore.\n $Target\n )\n $exploration = New-Object -ComObject shell.application\n $exploration.Explore($Target)\n}\n Function RDP\n{\n param\n (\n [Parameter(\n Position = 0,\n ValueFromPipeline = $true,\n Mandatory = $true,\n HelpMessage = \"Server Friendly name\"\n )]\n [ValidateNotNullOrEmpty()]\n [string]\n $server\n )\n\n cmdkey /generic:TERMSRV/$server /user:$UserName /pass:($Password.GetNetworkCredential().Password)\n mstsc /v:$Server /f /admin\n Wait-Event -Timeout 5\n cmdkey /Delete:TERMSRV/$server\n}\n # Restarts explorer as the user in $UserName\nfunction New-Explorer\n{\n # CLI prompt for password\n\n taskkill /f /IM Explorer.exe\n runas /noprofile /netonly /user:$UserName explorer\n}\n Function Lock-RemoteWorkstation\n{\n param(\n $Computername,\n $Credential\n )\n\n if(!(get-module taskscheduler))\n {\n Import-Module TaskScheduler\n }\n New-task -ComputerName $Computername -credential:$Credential |\n Add-TaskTrigger -In (New-TimeSpan -Seconds 30) |\n Add-TaskAction -Script `\n {\n $signature = @\"\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern bool LockWorkStation();\n \"@\n $LockWorkStation = Add-Type -memberDefinition $signature -name \"Win32LockWorkStation\" -namespace Win32Functions -passthru\n $LockWorkStation::LockWorkStation() | Out-Null\n } | Register-ScheduledTask TestTask -ComputerName $Computername -credential:$Credential\n}\n Function llm # Lock Local machine\n{\n $signature = @\"\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern bool LockWorkStation();\n \"@\n $LockWorkStation = Add-Type -memberDefinition $signature -name \"Win32LockWorkStation\" -namespace Win32Functions -passthru\n\n $LockWorkStation::LockWorkStation() | Out-Null\n}\n filter FileSizeBelow($size){if($_.length -le $size){ $_ }}\n filter FileSizeAbove($size){if($_.Length -ge $size){$_}}\n" }, { "answer_id": 24091871, "author": "noam", "author_id": 1751302, "author_profile": "https://Stackoverflow.com/users/1751302", "pm_score": 2, "selected": false, "text": "function Get-FolderSizes { # poor man's du\n [cmdletBinding()]\n param(\n [parameter(mandatory=$true)]$Path,\n [parameter(mandatory=$false)]$SizeMB,\n [parameter(mandatory=$false)]$ExcludeFolders,\n [parameter(mandatory=$false)][switch]$AsObject\n ) #close param\n # http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/05/weekend-scripter-sorting-folders-by-size.aspx\n # uses Christoph Schneegans' Find-Files https://schneegans.de/windows/find-files/ because \"gci -rec\" follows junctions in \"special\" folders\n $pathCheck = test-path $path\n if (!$pathcheck) { Write-Error \"Invalid path. Wants gci's -path parameter.\"; return }\n if (!(Get-Command Find-Files)) { Write-Error \"Required function Find-Files not found\"; return }\n $fso = New-Object -ComObject scripting.filesystemobject\n $parents = Get-ChildItem $path -Force | where { $_.PSisContainer -and $ExcludeFolders -notContains $_.name -and !$_.LinkType }\n $folders = Foreach ($folder in $parents)\n {\n $getFolder = $fso.getFolder( $folder.fullname.tostring() )\n if (!$getFolder.Size)\n { \n #for \"special folders\" like appdata\n # maybe \"-Attributes !ReparsePoint\" works in v6? https://stackoverflow.com/a/59952913/\n # what about https://superuser.com/a/650476/ ?\n # abandoned because it follows junctions, distorting results # $length = gci $folder.FullName -Recurse -Force -EA SilentlyContinue | Measure -Property Length -Sum\n $length = Find-Files $folder.FullName -EA SilentlyContinue | Measure -Property Length -Sum -EA SilentlyContinue\n $sizeMBs = \"{0:N0}\" -f ($length.Sum /1mb)\n } #close if size property is null\n else { $sizeMBs = \"{0:N0}\" -f ($getFolder.size /1mb) }\n New-Object -TypeName psobject -Property @{\n Name = $getFolder.Path\n SizeMB = $sizeMBs\n } #close new obj property\n } #close foreach folder\n #here's the output\n $foldersObj = $folders | Sort @{E={[decimal]$_.SizeMB}} -Descending | ? {[Decimal]$_.SizeMB -gt $SizeMB}\n if (!$AsObject) { $foldersObj | Format-Table -AutoSize } else { $foldersObj }\n #calculate the total including contents\n $sum = $folders | Select -Expand SizeMB | Measure -Sum | Select -Expand Sum\n $sum += ( gci $path | where {!$_.psIsContainer} | Measure -Property Length -Sum | Select -Expand Sum ) / 1mb\n $sumString = \"{0:n2}\" -f ($sum /1kb)\n $sumString + \" GB total\" \n} #end function\nSet-Alias gfs Get-FolderSizes\n\nfunction Find-Files\n{\n <# by Christoph Schneegans https://schneegans.de/windows/find-files/ - used in Get-FolderSizes aka gfs\n .SYNOPSIS\n Lists the contents of a directory. Unlike Get-ChildItem, this function does not recurse into symbolic links or junctions in order to avoid infinite loops.\n #>\n\n param (\n [Parameter( Mandatory=$false )]\n [string]\n # Specifies the path to the directory whose contents are to be listed. By default, the current working directory is used.\n $LiteralPath = (Get-Location),\n\n [Parameter( Mandatory=$false )]\n # Specifies a filter that is applied to each file or directory. Wildcards ? and * are supported.\n $Filter,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if file objects should be returned. By default, all file system objects are returned.\n $File = $true,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if directory objects should be returned. By default, all file system objects are returned.\n $Directory = $true,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if reparse point objects should be returned. By default, all file system objects are returned.\n $ReparsePoint = $true,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if the top directory should be returned. By default, all file system objects are returned.\n $Self = $true\n )\n\n function Enumerate( [System.IO.FileSystemInfo] $Item ) {\n $Item;\n if ( $Item.GetType() -eq [System.IO.DirectoryInfo] -and ! $Item.Attributes.HasFlag( [System.IO.FileAttributes]::ReparsePoint ) ) {\n foreach ($ChildItem in $Item.EnumerateFileSystemInfos() ) {\n Enumerate $ChildItem;\n }\n }\n }\n\n function FilterByName {\n process {\n if ( ( $Filter -eq $null ) -or ( $_.Name -ilike $Filter ) ) {\n $_;\n }\n }\n }\n\n function FilterByType {\n process {\n if ( $_.GetType() -eq [System.IO.FileInfo] ) {\n if ( $File ) { $_; }\n } elseif ( $_.Attributes.HasFlag( [System.IO.FileAttributes]::ReparsePoint ) ) {\n if ( $ReparsePoint ) { $_; }\n } else {\n if ( $Directory ) { $_; }\n }\n }\n }\n \n $Skip = if ($Self) { 0 } else { 1 };\n Enumerate ( Get-Item -LiteralPath $LiteralPath -Force ) | Select-Object -Skip $Skip | FilterByName | FilterByType;\n} # end function find-files\n Find-Files function New-URLfile {\n param( [parameter(mandatory=$true)]$Target, [parameter(mandatory=$true)]$Link )\n if ($target -match \"^\\.\" -or $link -match \"^\\.\") {\"Full paths plz.\"; break}\n $content = @()\n $header = '[InternetShortcut]'\n $content += $header\n $content += \"URL=\" + $target\n $content | out-file $link \n ii $link\n} #end function\n\nfunction New-LNKFile {\n param( [parameter(mandatory=$true)]$Target, [parameter(mandatory=$true)]$Link )\n if ($target -match \"^\\.\" -or $link -match \"^\\.\") {\"Full paths plz.\"; break}\n $WshShell = New-Object -comObject WScript.Shell\n $Shortcut = $WshShell.CreateShortcut($link)\n $Shortcut.TargetPath = $target\n $shortCut.save()\n} #end function new-lnkfile\n function Search-TextFile {\n param( \n [parameter(mandatory=$true)]$File,\n [parameter(mandatory=$true)]$SearchText\n ) #close param\n if ( !(Test-path $File) )\n { \n Write-Error \"File not found: $file\" \n return\n }\n $fullPath = Resolve-Path $file | select -Expand ProviderPath\n $lines = [System.IO.File]::ReadLines($fullPath)\n foreach ($line in $lines) { if ($line -match $SearchText) {$line} }\n} #end function Search-TextFile\nSet-Alias stf Search-TextFile\n function Get-InstalledProgram { [cmdletBinding()] #http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/13/use-powershell-to-quickly-find-installed-software.aspx\n param( [parameter(mandatory=$true)]$Comp,[parameter(mandatory=$false)]$Name )\n $keys = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall','SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall'\n TRY { $RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Comp) }\n CATCH {\n $rrSvc = gwmi win32_service -comp $comp -Filter {name='RemoteRegistry'}\n if (!$rrSvc) {\"Unable to connect. Make sure that this computer is on the network, has remote administration enabled, `nand that both computers are running the remote registry service.\"; break}\n #Enable and start RemoteRegistry service\n if ($rrSvc.State -ne 'Running') {\n if ($rrSvc.StartMode -eq 'Disabled') { $null = $rrSvc.ChangeStartMode('Manual'); $undoMe2 = $true }\n $null = $rrSvc.StartService() ; $undoMe = $true \n } #close if rrsvc not running\n else {\"Unable to connect. Make sure that this computer is on the network, has remote administration enabled, `nand that both computers are running the remote registry service.\"; break}\n $RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Comp) \n } #close if failed to connect regbase\n $out = @()\n foreach ($key in $keys) {\n if ( $RegBase.OpenSubKey($Key) ) { #avoids errors on 32bit OS\n foreach ( $entry in $RegBase.OpenSubKey($Key).GetSubkeyNames() ) {\n $sub = $RegBase.OpenSubKey( ($key + '\\' + $entry) )\n if ($sub) { $row = $null\n $row = [pscustomobject]@{\n Name = $RegBase.OpenSubKey( ($key + '\\' + $entry) ).GetValue('DisplayName')\n InstallDate = $RegBase.OpenSubKey( ($key + '\\' + $entry) ).GetValue('InstallDate')\n Version = $RegBase.OpenSubKey( ($key + '\\' + $entry) ).GetValue('DisplayVersion')\n } #close row\n $out += $row\n } #close if sub\n } #close foreach entry\n } #close if key exists\n } #close foreach key\n $out | where {$_.name -and $_.name -match $Name}\n if ($undoMe) { $null = $rrSvc.StopService() }\n if ($undoMe2) { $null = $rrSvc.ChangeStartMode('Disabled') }\n } #end function\n function Copy-ProfilePS1 ($Comp,$User) {\n if (!$User) {$User = $env:USERNAME}\n $targ = \"\\\\$comp\\c$\\users\\$User\\Documents\\WindowsPowershell\\\"\n if (Test-Path $targ)\n {\n $cmd = \"copy /-Y $profile $targ\"\n cmd /c $cmd\n } else {\"Path not found! $targ\"}\n} #end function CopyProfilePS1\n" }, { "answer_id": 24871440, "author": "Burt_Harris", "author_id": 3776535, "author_profile": "https://Stackoverflow.com/users/3776535", "pm_score": 0, "selected": false, "text": "profile.ps1 if ($PSVersionTable.PsVersion.Major -ge 3) {\n Write-Host \"Executing $PSCommandPath\"\n}\n Microsoft.PowerShellIse_profile.ps1 if ($PSVersionTable.PsVersion.Major -ge 3) {\n Write-Host \"Executing $PSCommandPath\"\n}\n\nif ( New-PSDrive -ErrorAction Ignore One FileSystem `\n (Get-ItemProperty hkcu:\\Software\\Microsoft\\SkyDrive UserFolder).UserFolder) { \n Write-Host -ForegroundColor Green \"PSDrive One: mapped to local OneDrive/SkyDrive folder\"\n }\n\nImport-Module PSCX\n\n$PSCX:TextEditor = (get-command Powershell_ISE).Path\n\n$PSDefaultParameterValues = @{\n \"Get-Help:ShowWindow\" = $true\n \"Help:ShowWindow\" = $true\n \"Out-Default:OutVariable\" = \"0\"\n}\n\n\n#Script Browser Begin\n#Version: 1.2.1\nAdd-Type -Path 'C:\\Program Files (x86)\\Microsoft Corporation\\Microsoft Script Browser\\System.Windows.Interactivity.dll'\nAdd-Type -Path 'C:\\Program Files (x86)\\Microsoft Corporation\\Microsoft Script Browser\\ScriptBrowser.dll'\nAdd-Type -Path 'C:\\Program Files (x86)\\Microsoft Corporation\\Microsoft Script Browser\\BestPractices.dll'\n$scriptBrowser = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Script Browser', [ScriptExplorer.Views.MainView], $true)\n$scriptAnalyzer = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Script Analyzer', [BestPractices.Views.BestPracticesView], $true)\n$psISE.CurrentPowerShellTab.VisibleVerticalAddOnTools.SelectedAddOnTool = $scriptBrowser\n#Script Browser End\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20911/" ]
138,153
<p>Are there any ncurses libraries in C/C++ for Windows that emulate ncurses in native resizable Win32 windows (<em>not</em> in console mode)?</p>
[ { "answer_id": 1517788, "author": "Adam Batkin", "author_id": 120808, "author_profile": "https://Stackoverflow.com/users/120808", "pm_score": 4, "selected": false, "text": "CMD.EXE ncurses" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6619/" ]
138,157
<p>Hey, I've been developing an application in the windows console with Java, and want to put it online in all of its console-graphics-glory.</p> <p>Is there a simple web applet API I can use to port my app over?</p> <p>I'm just using basic System.out and System.in functionality, but I'm happy to rebuild my I/O wrappers.</p> <p>I think something along these lines would be a great asset to any beginning Java developers who want to put their work online.</p>
[ { "answer_id": 144467, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 2, "selected": false, "text": "prompt() stdin stdout stderr" }, { "answer_id": 187056, "author": "Dean Rather", "author_id": 14966, "author_profile": "https://Stackoverflow.com/users/14966", "pm_score": 2, "selected": false, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport java.io.*;\nimport java.awt.Font;\n\npublic class Applet extends JFrame {\n static final long serialVersionUID = 1;\n\n /** Text area for console output. */\n protected JTextArea textArea;\n\n /** Text box for user input. */\n protected JTextField textBox;\n\n /** \"GO\" button, in case they don't know to hit enter. */\n protected JButton goButton;\n\n protected PrintStream printStream;\n protected BufferedReader bufferedReader;\n\n /**\n * This function is called when they hit ENTER or click GO.\n */\n ActionListener actionListener = new ActionListener() {\n public void actionPerformed(ActionEvent actionEvent) {\n goButton.setEnabled(false);\n SwingUtilities.invokeLater(\n new Thread() {\n public void run() {\n String userInput = textBox.getText();\n printStream.println(\"> \"+userInput);\n Input.inString = userInput;\n textBox.setText(\"\");\n goButton.setEnabled(true);\n }\n } \n );\n }\n };\n\n public void println(final String string) {\n SwingUtilities.invokeLater(\n new Thread() {\n public void run() {\n printStream.println(string);\n }\n } \n );\n }\n\n public void printmsg(final String string) {\n SwingUtilities.invokeLater(\n new Thread() {\n public void run() {\n printStream.print(string);\n }\n } \n );\n }\n\n public Applet() throws IOException {\n super(\"My Applet Title\");\n\n Container contentPane = getContentPane();\n\n textArea = new JTextArea(30, 60);\n JScrollPane jScrollPane = new JScrollPane(textArea);\n final JScrollBar jScrollBar = jScrollPane.getVerticalScrollBar();\n contentPane.add(BorderLayout.NORTH, jScrollPane);\n textArea.setFocusable(false);\n textArea.setAutoscrolls(true);\n textArea.setFont(new Font(\"Comic Sans MS\", Font.TRUETYPE_FONT, 14));\n\n // TODO This might be overkill\n new Thread() {\n public void run() {\n while(true) {\n jScrollBar.setValue(jScrollBar.getMaximum());\n try{\n Thread.sleep(100);\n } catch (Exception e) {}\n }\n }\n }.start();\n\n JPanel panel;\n contentPane.add(BorderLayout.CENTER, panel = new JPanel());\n\n panel.add(textBox = new JTextField(55));\n textBox.addActionListener(actionListener);\n\n panel.add(goButton = new JButton(\"GO\"));\n goButton.addActionListener(actionListener);\n\n pack();\n\n // End of GUI stuff\n\n PipedInputStream inputStream;\n PipedOutputStream outputStream;\n\n inputStream = new PipedInputStream();\n outputStream = new PipedOutputStream(inputStream);\n\n bufferedReader = new BufferedReader(new InputStreamReader(inputStream, \"ISO8859_1\"));\n printStream = new PrintStream(outputStream);\n\n new Thread() {\n public void run() {\n try {\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n textArea.append(line+\"\\n\");\n }\n } catch (IOException ioException) {\n textArea.append(\"ERROR\");\n }\n }\n }.start();\n }\n}\n public static String getString() {\n inString = \"\";\n\n // Wait for input\n while (inString == \"\") {\n try{\n Thread.sleep(100);\n } catch (Exception e) {}\n }\n\n return inString;\n }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14966/" ]
138,159
<p>I'm new to PHP and I'm confused seeing some examples calling a function with a @ prefix like @mysql_ping().</p> <p>What is it for? Googling / searching is not much of a help since @ gets discarded and 'alias' is not good enough keyword.</p>
[ { "answer_id": 138183, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "$test = @file_get_contents('nonexistant.file');\nif(!$test)\n{\n die('Failed');\n}\n display_errors" }, { "answer_id": 2778372, "author": "Doug", "author_id": 334069, "author_profile": "https://Stackoverflow.com/users/334069", "pm_score": 0, "selected": false, "text": ".$foutDate = @filemtime($keyring); /* Don't care, as we've already established file */\n\n$f[\"date\"] = $foutDate;\n\n$f[\"fullDate\"] = date(\"r\", $foutDate);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
138,162
<p>I want to setup my local development machine so that any requests for <code>*.local</code> are redirected to <code>localhost</code>. The idea is that as I develop multiple sites, I can just add vhosts to Apache called <code>site1.local</code>, <code>site2.local</code> etc, and have them all resolve to <code>localhost</code>, while Apache serves a different site accordingly.</p> <p>I am on Windows XP.</p> <p>I tried adding </p> <pre><code>127.0.0.1 *.local </code></pre> <p>to my <code>c:\windows\system32\drivers\etc\hosts</code> file, also tried:</p> <pre><code>127.0.0.1 .local </code></pre> <p>Neither of which seem to work.</p> <p>I know I can set them up on different port numbers, but that is a pain since it is hard to remember which port is which.</p> <p>I don't want to have to setup a local DNS server or anything hard, any suggestions?</p>
[ { "answer_id": 272092, "author": "jeremyasnyder", "author_id": 33143, "author_profile": "https://Stackoverflow.com/users/33143", "pm_score": 6, "selected": false, "text": " LoadModule vhost_alias_module modules/mod_vhost_alias.so\n\n NameVirtualHost *:80\n\n <Directory \"/xampp/sites\">\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all \n </Directory>\n\n <VirtualHost *:80>\n VirtualDocumentRoot c:/xampp/sites/%-1/%-2+/\n </VirtualHost>\n 127.0.0.1 test.dev\n <Directory>" }, { "answer_id": 342562, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "DESCRIPTION\n The hosts file contains information regarding the known hosts on the net-\n work. For each host a single line should be present with the following\n information:\n\n Internet address\n Official host name\n Aliases\n Host names may contain any printable character other than a field delim-\n iter, newline, or comment character.\n" }, { "answer_id": 9695861, "author": "Petah", "author_id": 268074, "author_profile": "https://Stackoverflow.com/users/268074", "pm_score": 10, "selected": true, "text": "127.0.0.1 *.localhost\n127.0.0.1 *.local\n127.0.0.1 *.lc\n Preferred DNS Server: 127.0.0.1\n VirtualDocumentRoot" }, { "answer_id": 17812067, "author": "Matthew Skelton", "author_id": 1253233, "author_profile": "https://Stackoverflow.com/users/1253233", "pm_score": 2, "selected": false, "text": "A *.local -> 127.0.0.1 .local .int .localhost.int *.localhost.int 127.0.0.1 site1.localhost.int site2.localhost.int" }, { "answer_id": 21153552, "author": "oucil", "author_id": 1058733, "author_profile": "https://Stackoverflow.com/users/1058733", "pm_score": 1, "selected": false, "text": "virtualhost ServerAlias ServerAlias *.foo.local\n" }, { "answer_id": 22097400, "author": "casivaagustin", "author_id": 1582216, "author_profile": "https://Stackoverflow.com/users/1582216", "pm_score": 2, "selected": false, "text": "[A]\n*.google.com=192.0.2.1\n*.local=127.0.0.1\n*.devServer1.com=192.0.2.3\n sudo python dnschef.py --file myfile.ini -q\n runas dnschef.exe --file myfile.ini -q\n" }, { "answer_id": 25391952, "author": "Daniel Jordi", "author_id": 3765399, "author_profile": "https://Stackoverflow.com/users/3765399", "pm_score": 1, "selected": false, "text": "127.0.0.1 example.local\n # Virtual hosts\nInclude etc\\extra\\httpd-vhosts.conf\n <VirtualHost *:80>\n ServerAdmin admin@example.local\n DocumentRoot \"\\path_to_XAMPP\\htdocs\"\n ServerName example.local\n ServerAlias *.example.local\n# SetEnv APP_ENVIRONMENT development\n# ErrorLog \"logs\\example.local-error_log\"\n# CustomLog \"logs\\example.local-access_log\" common\n</VirtualHost>\n function FindProxyForURL(url, host) {\n if (shExpMatch(host, \"*example.local\")) {\n return \"PROXY example.local\";\n }\n return \"DIRECT\";\n}\n" }, { "answer_id": 27858259, "author": "arva", "author_id": 2659230, "author_profile": "https://Stackoverflow.com/users/2659230", "pm_score": 1, "selected": false, "text": "echoipdns local" }, { "answer_id": 28846477, "author": "Stackia", "author_id": 3542546, "author_profile": "https://Stackoverflow.com/users/3542546", "pm_score": 2, "selected": false, "text": "[\n {\n \"Pattern\": \"^.*$\",\n \"NameServer\": \"8.8.8.8\"\n },\n {\n \"Pattern\": \"^(.*\\\\.googlevideo\\\\.com)|((.*\\\\.)?(youtube|ytimg)\\\\.com)$\",\n \"Address\": \"203.66.168.119\"\n },\n {\n \"Pattern\": \"^.*\\\\.cn$\",\n \"NameServer\": \"114.114.114.114\"\n },\n {\n \"Pattern\": \"baidu.com$\",\n \"Address\": \"127.0.0.1\"\n }\n]\n" }, { "answer_id": 29159000, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 3, "selected": false, "text": " myproject.127.0.0.1.xip.io -- resolves to --> 127.0.0.1\n other.project.127.0.0.1.xip.io -- resolves to --> 127.0.0.1\n other.machine.10.0.0.1.xip.io -- resolves to --> 10.0.0.1\n" }, { "answer_id": 54423117, "author": "Davron Achilov", "author_id": 8182972, "author_profile": "https://Stackoverflow.com/users/8182972", "pm_score": 0, "selected": false, "text": "server {\n listen 80;\n server_name ~^(?<branch>.*)\\.example\\.com;\n root /var/www/html/$branch/public; \n\n index index.html index.htm index.php;\n\n charset utf-8;\n\n location / {\n try_files $uri $uri/ /index.php$is_args$args;\n }\n\n location = /favicon.ico { access_log off; log_not_found off; }\n location = /robots.txt { access_log off; log_not_found off; }\n\n error_log /var/log/nginx/$branch.error.log error;\n\n sendfile off;\n\n client_max_body_size 100m;\n\n location ~ \\.php$ {\n try_files $uri /index.php =404;\n fastcgi_pass php-fpm:9000;\n fastcgi_index index.php;\n fastcgi_buffers 16 16k;\n fastcgi_buffer_size 32k;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n include fastcgi_params;\n }\n\n location ~ /\\.ht {\n deny all;\n }\n}\n 127.0.0.1 example.com *.example.com" }, { "answer_id": 58622224, "author": "davidjimenez75", "author_id": 8208892, "author_profile": "https://Stackoverflow.com/users/8208892", "pm_score": 0, "selected": false, "text": "nano /etc/hosts\npihole restartdns\n 127.0.1.1 raspberrypi\n192.168.1.1 w1.dev.net\n192.168.1.2 w2.dev.net\n192.168.1.3 w3.dev.net\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
138,174
<p>I'm considering supporting both <strong><a href="http://textism.com/tools/textile/" rel="nofollow noreferrer">Textile</a></strong> and <strong><a href="http://daringfireball.net/projects/markdown/" rel="nofollow noreferrer">Markdown</a></strong> on a current project. I would prefer not forcing users to choose one or the other. Is there a way to auto-detect which the user is using? How would you go about this? I'd like to find / develop both a JavaScript and a PHP solution so I can provide live previews as well as process the user input on the server-side.</p>
[ { "answer_id": 138491, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": 2, "selected": false, "text": "h1. Header\n\np. Paragraph\n if (preg_match('/^(p|h[1-6])\\. /m', $subject)) \n{\n // Successful match\n} else \n{\n // Match attempt failed\n}\n" }, { "answer_id": 138537, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 4, "selected": true, "text": "*this* <em>this</em> <strong>this</strong>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
138,177
<p>I use several referenced tables with integer primary keys. Now I want to change ints to GUIDs leaving all references intact. What is the easiest way to do it?</p> <p>Thank you!</p> <p><strong>Addition</strong></p> <p>I do understand the process in general, so I need more detailed advices, for example, how to fill new GUID column. Using default value newid() is correct, but what for already existing rows?</p>
[ { "answer_id": 138185, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 3, "selected": false, "text": "UPDATE foreignTable f\nSET f.guidCol = p.guidCol\nFROM primaryTable p\nWHERE p.intCol = f.intCol\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
138,194
<p>In the Flex framework a custom preloader can be used while the site is loading.</p> <p>In the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=app_container_4.html" rel="nofollow noreferrer">Adobe docs</a> it specifies that '<strong>the progress bar [preloader] is displayed if less than half of the application is downloaded after 700 milliseconds of downloading.</strong>'</p> <p>However I ALWAYS want the preloader to appear instantly since I know that 95% of our users are first time visitors and the site is over 500kb. I dont want people to have to wait .7 seconds for the preloader animation to appear.</p> <p>I would think in theory that it is possible to 'monkey patch' the framework to remove this .7 second limitation. I dont have time to figure out how, and I've never done it before.</p> <p>Anybody help?</p>
[ { "answer_id": 138247, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 1, "selected": false, "text": "showDisplayForDownloading showDisplayForDownloading" }, { "answer_id": 138373, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "package{\nimport flash.display.MovieClip;\nimport flash.display.Sprite;\nimport flash.events.Event;\nimport flash.events.ProgressEvent;\n\nimport mx.events.FlexEvent;\nimport mx.preloaders.DownloadProgressBar;\n\npublic class Preloader extends DownloadProgressBar\n{\n\n /**\n * The Flash 8 MovieClip embedded as a Class.\n */ \n [Embed(source=\"yourPreloaderFile.swf\")]\n private var FlashPreloaderSymbol:Class;\n\n private var clip:MovieClip;\n\n public function Preloader()\n {\n super();\n clip = new FlashPreloaderSymbol();\n addChild(clip);\n }\n\n public override function set preloader(preloader:Sprite):void \n { \n preloader.addEventListener( FlexEvent.INIT_COMPLETE , onFlexInitComplete );\n\n centerPreloader();\n }\n\n private function centerPreloader():void\n {\n x = (stageWidth / 2) - (clip.width / 2);\n y = (stageHeight / 2) - (clip.height / 2);\n }\n\n private function onFlexInitComplete( event:FlexEvent ):void \n {\n dispatchEvent( new Event( Event.COMPLETE ) ); \n }\n\n\n protected override function showDisplayForDownloading(time : int, event : ProgressEvent) : Boolean {\n return true;\n }\n\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
138,203
<p>Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control? </p> <p>The report definition should be embedded in the executable and should not use the Reporting Services web service.</p>
[ { "answer_id": 138222, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "ReportViewer rv = new ReportViewer();\nrv.LocalReport.ReportPath = \"templatepath\";\n// or use file from resource with rv.LocalReport.ReportEmbeddedResource\n\n// add parameters, datasource, etc.\n\nWarning[] warnings;\nstring[] streamids;\nstring mimeType;\nstring encoding;\nstring filenameExtension;\n\nbyte[] bytes;\nbytes = rv.LocalReport.Render(\"PDF\", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);\n\n// save byte[] to file with FileStream or something else\n" }, { "answer_id": 138339, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 4, "selected": true, "text": "LocalReport report = new LocalReport();\nreport.ReportPath = \"templatepath\";\n// or use file from resource with report.ReportEmbeddedResource\n\n// add parameters, datasource, etc.\n\nWarning[] warnings;\nstring[] streamids;\nstring mimeType;\nstring encoding;\nstring filenameExtension;\n\nbyte[] bytes;\nbytes =report.Render(\"PDF\", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);\n\n// save byte[] to file with FileStream or something else\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966/" ]
138,250
<p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?</p> <p>Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p> <p>I would prefer if I didn't have to download any additional libraries.</p>
[ { "answer_id": 138260, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 9, "selected": true, "text": "from PIL import Image\n\nim = Image.open('dead_parrot.jpg') # Can be many different formats.\npix = im.load()\nprint im.size # Get the width and hight of the image for iterating over\nprint pix[x,y] # Get the RGBA Value of the a pixel of an image\npix[x,y] = value # Set the RGBA Value of the image (tuple)\nim.save('alive_parrot.png') # Save the modified pixels as .png\n" }, { "answer_id": 139070, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 5, "selected": false, "text": "import png, array\n\npoint = (2, 10) # coordinates of pixel to be painted red\n\nreader = png.Reader(filename='image.png')\nw, h, pixels, metadata = reader.read_flat()\npixel_byte_width = 4 if metadata['alpha'] else 3\npixel_position = point[0] + point[1] * w\nnew_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)\npixels[\n pixel_position * pixel_byte_width :\n (pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)\n\noutput = open('image-with-red-dot.png', 'wb')\nwriter = png.Writer(w, h, **metadata)\nwriter.write_array(output, pixels)\noutput.close()\n" }, { "answer_id": 663861, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "from pygame import surfarray, image, display\nimport pygame\nimport numpy #important to import\n\npygame.init()\nimage = image.load(\"myimagefile.jpg\") #surface to render\nresolution = (image.get_width(),image.get_height())\nscreen = display.set_mode(resolution) #create space for display\nscreen.blit(image, (0,0)) #superpose image on screen\ndisplay.flip()\nsurfarray.use_arraytype(\"numpy\") #important!\nscreenpix = surfarray.pixels3d(image) #pixels in 3d array:\n#[x][y][rgb]\nfor y in range(resolution[1]):\n for x in range(resolution[0]):\n for color in range(3):\n screenpix[x][y][color] += 128\n #reverting colors\nscreen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen\ndisplay.flip() #update display\nwhile 1:\n print finished\n" }, { "answer_id": 5365853, "author": "Lachlan Phillips", "author_id": 667814, "author_profile": "https://Stackoverflow.com/users/667814", "pm_score": 4, "selected": false, "text": "import os, sys\nimport Image\n\nim = Image.open(\"image.jpg\")\nx = 3\ny = 4\n\npix = im.load()\nprint pix[x,y]\n" }, { "answer_id": 22877878, "author": "user3423024", "author_id": 3423024, "author_profile": "https://Stackoverflow.com/users/3423024", "pm_score": 2, "selected": false, "text": "import PIL\nimport Image\nFILENAME='fn.gif' #image can be in gif jpeg or png format \nim=Image.open(FILENAME).convert('RGB')\npix=im.load()\nw=im.size[0]\nh=im.size[1]\nfor i in range(w):\n for j in range(h):\n print pix[i,j]\n" }, { "answer_id": 27370477, "author": "chenlian", "author_id": 4268078, "author_profile": "https://Stackoverflow.com/users/4268078", "pm_score": 2, "selected": false, "text": "#from http://tkinter.unpythonic.net/wiki/PhotoImage\nfrom Tkinter import *\n\nroot = Tk()\n\ndef pixel(image, pos, color):\n \"\"\"Place pixel at pos=(x,y) on image, with color=(r,g,b).\"\"\"\n r,g,b = color\n x,y = pos\n image.put(\"#%02x%02x%02x\" % (r,g,b), (y, x))\n\nphoto = PhotoImage(width=32, height=32)\n\npixel(photo, (16,16), (255,0,0)) # One lone pixel in the middle...\n\nlabel = Label(root, image=photo)\nlabel.grid()\nroot.mainloop()\n #from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py\ndef getRGB(image, x, y):\n value = image.get(x, y)\n return tuple(map(int, value.split(\" \")))\n" }, { "answer_id": 27960627, "author": "Martin Thoma", "author_id": 562769, "author_profile": "https://Stackoverflow.com/users/562769", "pm_score": 6, "selected": false, "text": "from PIL import Image\nim = Image.open('image.jpg', 'r')\nwidth, height = im.size\npixel_values = list(im.getdata())\n im.mode (x, y) pixel_values[width*y+x]\n >>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))\n>>> x, y = 0, 1\n>>> pixel_values[x][y]\n[ 18 18 12]\n # Third party modules\nimport numpy\nfrom PIL import Image\n\n\ndef get_image(image_path):\n \"\"\"Get a numpy array of an image so that one can access values[x][y].\"\"\"\n image = Image.open(image_path, \"r\")\n width, height = image.size\n pixel_values = list(image.getdata())\n if image.mode == \"RGB\":\n channels = 3\n elif image.mode == \"L\":\n channels = 1\n else:\n print(\"Unknown mode: %s\" % image.mode)\n return None\n pixel_values = numpy.array(pixel_values).reshape((width, height, channels))\n return pixel_values\n\n\nimage = get_image(\"gradient.png\")\n\nprint(image[0])\nprint(image.shape)\n #ffaa00 #ffffff [[255 172 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 172 4]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 172 5]]\n(100, 26, 3)\n image[0]" }, { "answer_id": 33630650, "author": "Peter V", "author_id": 916859, "author_profile": "https://Stackoverflow.com/users/916859", "pm_score": 3, "selected": false, "text": "photo = Image.open('IN.jpg') #your image\nphoto = photo.convert('RGB')\n\nwidth = photo.size[0] #define W and H\nheight = photo.size[1]\n\nfor y in range(0, height): #each pixel has coordinates\n row = \"\"\n for x in range(0, width):\n\n RGB = photo.getpixel((x,y))\n R,G,B = RGB #now you can use the RGB value\n" }, { "answer_id": 45342958, "author": "user8374199", "author_id": 8374199, "author_profile": "https://Stackoverflow.com/users/8374199", "pm_score": 1, "selected": false, "text": "import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimg=mpimg.imread('Cricket_ACT_official_logo.png')\nimgplot = plt.imshow(img)\n" }, { "answer_id": 49242185, "author": "Anupam Hayat Shawon", "author_id": 6760464, "author_profile": "https://Stackoverflow.com/users/6760464", "pm_score": 1, "selected": false, "text": "i = Image.open(path)\npixels = i.load() # this is not a list, nor is it list()'able\nwidth, height = i.size\n\nall_pixels = []\nfor x in range(width):\n for y in range(height):\n cpixel = pixels[x, y]\n all_pixels.append(cpixel)\n" }, { "answer_id": 50894365, "author": "Idan Rotbart", "author_id": 6941443, "author_profile": "https://Stackoverflow.com/users/6941443", "pm_score": 3, "selected": false, "text": "from PIL import Image\ndef rgb_of_pixel(img_path, x, y):\n im = Image.open(img_path).convert('RGB')\n r, g, b = im.getpixel((x, y))\n a = (r, g, b)\n return a\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
138,251
<p>I am trying to access a Windows Media Player library from ASP.NET.</p> <p>The following code:</p> <p>WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer();</p> <p>WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio");</p> <p>Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS.</p> <p>Setting impersonation with:</p> <p>System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();</p> <p>Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library. </p> <p>Is there a way to get around this?</p>
[ { "answer_id": 140939, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 1, "selected": false, "text": "<system.web>\n<identity impersonate=\"true\" userName=\"MYDOMAIN\\myuser\" password=\"p@ssw0rd\" />\n</system.web>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22590/" ]
138,261
<p>I am having a table Table1 with columns id1, id2, id3 all the columns are nullable</p> <p>I may enter null or value to all columns in rows.</p> <p>My question is I need to select the rows whose all the column values should not be null.</p> <p>Thanks</p> <hr> <p>There are totally around 300 columns in the table. I can't do the <code>is null</code> property for all the columns in <code>where</code> condition.</p>
[ { "answer_id": 138276, "author": "James", "author_id": 7837, "author_profile": "https://Stackoverflow.com/users/7837", "pm_score": 1, "selected": false, "text": " \n\nSELECT id1, id2, id3 \nFROM Table1 \nWHERE id1 IS NOT NULL AND id2 IS NOT NULL AND id3 IS NOT NULL\n\n\n " }, { "answer_id": 138792, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": true, "text": "SELECT *\nFROM yourtable\nWHERE\n column1 IS NOT NULL\nAND column2 IS NOT NULL\nAND column3 IS NOT NULL\nAND ....\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
138,273
<p>I have recently run across these terms few times but I am quite confused how they work and when they are usualy implemented?</p>
[ { "answer_id": 138472, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 6, "selected": false, "text": "put(key,value) get(key) contains(key) remove(key) ID => student studentToClassRegistration LinkedHashMap" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515/" ]
138,302
<p>When using SQLBulkCopy on a table with a GUID primary key and default newsequentialid()</p> <p>e.g</p> <pre><code>CREATE TABLE [dbo].[MyTable]( [MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()), [Status] [int] NULL, [Priority] [int] NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED ( [MyPrimaryKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] </code></pre> <p>wIth the C# code</p> <pre><code> tran = connection.BeginTransaction(); SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran); sqlCopy.DestinationTableName = "MyTable"; sqlCopy.WriteToServer(dataTable); </code></pre> <p>Gives you an error...</p> <p>Column 'MyPrimaryKey' does not allow DBNull.Value</p> <p>I've tried fiddling the the SqlBulkCopyOptions. The only thing that works is setting the MyPrimaryKey field to allow nulls and removing the primary key.</p> <p>Anyone know if there is a workaround for this issue? Or can you verify that there is no workaround (other than changing the table structure)?</p>
[ { "answer_id": 139850, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "sqlCopy.ColumnMappings.Clear();\n sqlBulkCopy.ColumnMappings.Add(\"Status\", \"Status\");\nsqlBulkCopy.ColumnMappings.Add(\"Priority\", \"Priority\");\n" }, { "answer_id": 30249522, "author": "DCShannon", "author_id": 2449863, "author_profile": "https://Stackoverflow.com/users/2449863", "pm_score": 0, "selected": false, "text": "BulkInsertAll<> SqlBulkCopy ColumnAttribute IsDbGenerated=\"true\" public void BulkInsertAll<T>( IEnumerable<T> entities ) {\n entities = entities.ToArray();\n\n string cs = Connection.ConnectionString;\n var conn = new SqlConnection( cs );\n conn.Open();\n\n Type t = typeof( T );\n\n var tableAttribute = (TableAttribute) t.GetCustomAttributes(\n typeof( TableAttribute ), false\n ).Single();\n\n var bulkCopy = new SqlBulkCopy( conn ) {\n DestinationTableName = tableAttribute.Name\n };\n\n var properties = t.GetProperties().Where( EventTypeFilter );\n\n // This will prevent the bulk insert from attempting to update DBGenerated columns\n // Without, inserts with a guid pk will fail to get the generated sequential id\n // If uninitialized guids are passed to the DB, it will throw duplicate key exceptions\n properties = properties.Where( \n x => !x.GetCustomAttributes( typeof( ColumnAttribute ), false )\n .Cast<ColumnAttribute>().Any( attr => attr.IsDbGenerated )\n );\n\n var table = new DataTable();\n\n foreach( var property in properties ) {\n Type propertyType = property.PropertyType;\n if( propertyType.IsGenericType &&\n propertyType.GetGenericTypeDefinition() == typeof( Nullable<> ) ) {\n propertyType = Nullable.GetUnderlyingType( propertyType );\n }\n\n table.Columns.Add( new DataColumn( property.Name, propertyType ) );\n }\n\n foreach( var entity in entities ) {\n table.Rows.Add( \n properties.Select( \n property => GetPropertyValue( property.GetValue( entity, null ) ) \n ).ToArray()\n );\n }\n\n //specify the mapping for SqlBulk Upload\n foreach( var col in properties ) {\n bulkCopy.ColumnMappings.Add( col.Name, col.Name );\n }\n\n bulkCopy.WriteToServer( table );\n\n conn.Close();\n}\n\n\nprivate bool EventTypeFilter( System.Reflection.PropertyInfo p ) {\n var attribute = Attribute.GetCustomAttribute( p,\n typeof( AssociationAttribute ) ) as AssociationAttribute;\n\n if( attribute == null ) return true;\n if( attribute.IsForeignKey == false ) return true;\n\n return false;\n}\n\nprivate object GetPropertyValue( object o ) {\n if( o == null )\n return DBNull.Value;\n return o;\n}\n .Where" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
138,309
<p>I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.</p> <p>Example:</p> <pre><code>&lt;object id="img" data="image.svg" width="500" height="300"/&gt; &lt;script&gt;document.getElementById("img").addData([1,23,4]);&lt;/script&gt; </code></pre> <p>Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?</p>
[ { "answer_id": 138358, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 5, "selected": true, "text": "<script>document.method = function() {}</script>\n <script>$(\"img\").observe(\"load\", function() {$(\"img\").contentDocument.method()});\n element.contentDocument" }, { "answer_id": 144236, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 3, "selected": false, "text": "/****************** Track and handle SVG object movement *************/\nvar svgDoc;\nvar svgRoot;\nvar mover=''; //keeps track of what I'm dragging\n\n///start function////\n//do this onload\nfunction start(evt){\n //set up the svg document elements\n svgDoc=evt.target.ownerDocument;\n svgRoot=svgDoc.documentElement;\n //add the mousemove event to the whole thing\n svgRoot.addEventListener('mousemove',go,false);\n //do this when the mouse is released\n svgRoot.addEventListener('mouseup',releaseMouse,false); \n}\n\n// set the id of the target to drag\nfunction setMove(id){ mover=id; }\n\n// clear the id of the dragging object\nfunction releaseMouse(){ \n if(allowMoves == true){ sendMove(mover); }\n mover=''; \n}\n\n// this is launched every mousemove on the doc\n// if we are dragging something, move it\nfunction go(evt){\n if(mover != '' && allowMoves != false) {\n //init it\n var me=document.getElementById(mover);\n\n //actually change the location\n moveX = evt.clientX-135; //css positioning minus 1/2 the width of the piece\n moveY = evt.clientY-65;\n me.setAttributeNS(null, 'x', evt.clientX-135);\n me.setAttributeNS(null, 'y', evt.clientY-65);\n }\n}\n\nfunction moveThis(pieceID, x, y) {\n $(pieceID).setAttributeNS(null, 'x', x);\n $(pieceID).setAttributeNS(null, 'y', y);\n}\n" }, { "answer_id": 7183632, "author": "Temperage", "author_id": 657087, "author_profile": "https://Stackoverflow.com/users/657087", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\nfunction change(){\n var s=document.getElementById(\"cube\");\n s.setAttribute(\"stroke\",\"0000FF\");\n}\n</script>\n <svg width=100 height=100 style='float: left;'>\n <rect x=\"10\" y=\"10\" width=\"60\" height=\"60\" id=\"cube\" onclick=\"change()\" stroke=#F53F0C stroke-width=10 fill=#F5C60C />\n</svg>\n <button onclick=\"change()\">Click</button>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
138,311
<p>The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?</p>
[ { "answer_id": 138372, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 6, "selected": true, "text": "#I go in application.rb\nself.allow_forgery_protection = false\n Application self #I still go in application.rb\nself.allow_forgery_protection = false unless ENV[\"RAILS_ENV\"] == \"production\"\n" }, { "answer_id": 7564903, "author": "Jeff Dickey", "author_id": 43055, "author_profile": "https://Stackoverflow.com/users/43055", "pm_score": 2, "selected": false, "text": "protect_from_forgery app/controllers/application_controller.rb" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
138,313
<p>I would like to create a page where all images which reside on my website are listed with title and alternative representation.</p> <p>I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract <code>src</code>, <code>title</code> and <code>alt</code> from this HTML:</p> <pre><code>&lt;img <b>src</b>="/image/fluffybunny.jpg" <b>title</b>="Harvey the bunny" <b>alt</b>="a cute little fluffy bunny" /></code></pre> <p>I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).</p>
[ { "answer_id": 138614, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 6, "selected": false, "text": "$doc=new DOMDocument();\n$doc->loadHTML(\"<html><body>Test<br><img src=\\\"myimage.jpg\\\" title=\\\"title\\\" alt=\\\"alt\\\"></body></html>\");\n$xml=simplexml_import_dom($doc); // just to make xpath more simple\n$images=$xml->xpath('//img');\nforeach ($images as $img) {\n echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];\n}\n DOMDocument::loadHTML() SimpleXMLElement" }, { "answer_id": 138649, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 3, "selected": false, "text": "<?php\n$input = '<img src=\"/image/fluffybunny.jpg\" title=\"Harvey the bunny\" alt=\"a cute little fluffy bunny\"/>';\n$sx = simplexml_load_string($input);\nvar_dump($sx);\n?>\n object(SimpleXMLElement)#1 (1) {\n [\"@attributes\"]=>\n array(3) {\n [\"src\"]=>\n string(22) \"/image/fluffybunny.jpg\"\n [\"title\"]=>\n string(16) \"Harvey the bunny\"\n [\"alt\"]=>\n string(26) \"a cute little fluffy bunny\"\n }\n}\n" }, { "answer_id": 143455, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 9, "selected": true, "text": "/* preg_match_all match the regexp in all the $html string and output everything as \nan array in $result. \"i\" option is used to make it case insensitive */\n\npreg_match_all('/<img[^>]+>/i',$html, $result); \n\nprint_r($result);\nArray\n(\n [0] => Array\n (\n [0] => <img src=\"/Content/Img/stackoverflow-logo-250.png\" width=\"250\" height=\"70\" alt=\"logo link to homepage\" />\n [1] => <img class=\"vote-up\" src=\"/content/img/vote-arrow-up.png\" alt=\"vote up\" title=\"This was helpful (click again to undo)\" />\n [2] => <img class=\"vote-down\" src=\"/content/img/vote-arrow-down.png\" alt=\"vote down\" title=\"This was not helpful (click again to undo)\" />\n [3] => <img src=\"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG\" height=32 width=32 alt=\"gravatar image\" />\n [4] => <img class=\"vote-up\" src=\"/content/img/vote-arrow-up.png\" alt=\"vote up\" title=\"This was helpful (click again to undo)\" />\n\n[...]\n )\n\n)\n $img = array();\nforeach( $result as $img_tag)\n{\n preg_match_all('/(alt|title|src)=(\"[^\"]*\")/i',$img_tag, $img[$img_tag]);\n}\n\nprint_r($img);\n\nArray\n(\n [<img src=\"/Content/Img/stackoverflow-logo-250.png\" width=\"250\" height=\"70\" alt=\"logo link to homepage\" />] => Array\n (\n [0] => Array\n (\n [0] => src=\"/Content/Img/stackoverflow-logo-250.png\"\n [1] => alt=\"logo link to homepage\"\n )\n\n [1] => Array\n (\n [0] => src\n [1] => alt\n )\n\n [2] => Array\n (\n [0] => \"/Content/Img/stackoverflow-logo-250.png\"\n [1] => \"logo link to homepage\"\n )\n\n )\n\n [<img class=\"vote-up\" src=\"/content/img/vote-arrow-up.png\" alt=\"vote up\" title=\"This was helpful (click again to undo)\" />] => Array\n (\n [0] => Array\n (\n [0] => src=\"/content/img/vote-arrow-up.png\"\n [1] => alt=\"vote up\"\n [2] => title=\"This was helpful (click again to undo)\"\n )\n\n [1] => Array\n (\n [0] => src\n [1] => alt\n [2] => title\n )\n\n [2] => Array\n (\n [0] => \"/content/img/vote-arrow-up.png\"\n [1] => \"vote up\"\n [2] => \"This was helpful (click again to undo)\"\n )\n\n )\n\n [<img class=\"vote-down\" src=\"/content/img/vote-arrow-down.png\" alt=\"vote down\" title=\"This was not helpful (click again to undo)\" />] => Array\n (\n [0] => Array\n (\n [0] => src=\"/content/img/vote-arrow-down.png\"\n [1] => alt=\"vote down\"\n [2] => title=\"This was not helpful (click again to undo)\"\n )\n\n [1] => Array\n (\n [0] => src\n [1] => alt\n [2] => title\n )\n\n [2] => Array\n (\n [0] => \"/content/img/vote-arrow-down.png\"\n [1] => \"vote down\"\n [2] => \"This was not helpful (click again to undo)\"\n )\n\n )\n\n [<img src=\"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG\" height=32 width=32 alt=\"gravatar image\" />] => Array\n (\n [0] => Array\n (\n [0] => src=\"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG\"\n [1] => alt=\"gravatar image\"\n )\n\n [1] => Array\n (\n [0] => src\n [1] => alt\n )\n\n [2] => Array\n (\n [0] => \"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG\"\n [1] => \"gravatar image\"\n )\n\n )\n\n [..]\n )\n\n)\n <img[^>]+>\n <img (alt|title|src)=(\"[^\"]*\")\n" }, { "answer_id": 1482842, "author": "Bakudan", "author_id": 179669, "author_profile": "https://Stackoverflow.com/users/179669", "pm_score": 3, "selected": false, "text": "foreach( $result[0] as $img_tag)" }, { "answer_id": 2937682, "author": "karim", "author_id": 353868, "author_profile": "https://Stackoverflow.com/users/353868", "pm_score": 8, "selected": false, "text": "$url=\"http://example.com\";\n\n$html = file_get_contents($url);\n\n$doc = new DOMDocument();\n@$doc->loadHTML($html);\n\n$tags = $doc->getElementsByTagName('img');\n\nforeach ($tags as $tag) {\n echo $tag->getAttribute('src');\n}\n" }, { "answer_id": 3815188, "author": "WNRosenberg", "author_id": 332472, "author_profile": "https://Stackoverflow.com/users/332472", "pm_score": 3, "selected": false, "text": "<img> src // get the featured image\n$image = get_the_post_thumbnail($photos[$i]->ID);\n\n// get the src for that image\n$pattern = '/src=\"([^\"]*)\"/';\npreg_match($pattern, $image, $matches);\n$src = $matches[1];\nunset($matches);\n $pattern = '/title=\"([^\"]*)\"/'; $pattern = '/title=\"([^\"]*)\"/';" }, { "answer_id": 4172834, "author": "Xavier", "author_id": 506742, "author_profile": "https://Stackoverflow.com/users/506742", "pm_score": -1, "selected": false, "text": "$doc= qp($myHtmlDoc);\n\nforeach($doc->xpath('//img') as $img) {\n\n $src= $img->attr('src');\n $title= $img->attr('title');\n $alt= $img->attr('alt');\n\n}\n" }, { "answer_id": 8061770, "author": "John Daliani", "author_id": 1037139, "author_profile": "https://Stackoverflow.com/users/1037139", "pm_score": 1, "selected": false, "text": "function ReSizeImagesInHTML($HTMLContent,$MaximumWidth,$MaximumHeight) {\n\n// find image tags\npreg_match_all('/<img[^>]+>/i',$HTMLContent, $rawimagearray,PREG_SET_ORDER); \n\n// put image tags in a simpler array\n$imagearray = array();\nfor ($i = 0; $i < count($rawimagearray); $i++) {\n array_push($imagearray, $rawimagearray[$i][0]);\n}\n\n// put image attributes in another array\n$imageinfo = array();\nforeach($imagearray as $img_tag) {\n\n preg_match_all('/(src|width|height)=(\"[^\"]*\")/i',$img_tag, $imageinfo[$img_tag]);\n}\n\n// combine everything into one array\n$AllImageInfo = array();\nforeach($imagearray as $img_tag) {\n\n $ImageSource = str_replace('\"', '', $imageinfo[$img_tag][2][0]);\n $OrignialWidth = str_replace('\"', '', $imageinfo[$img_tag][2][1]);\n $OrignialHeight = str_replace('\"', '', $imageinfo[$img_tag][2][2]);\n\n $NewWidth = $OrignialWidth; \n $NewHeight = $OrignialHeight;\n $AdjustDimensions = \"F\";\n\n if($OrignialWidth > $MaximumWidth) { \n $diff = $OrignialWidth-$MaximumHeight; \n $percnt_reduced = (($diff/$OrignialWidth)*100); \n $NewHeight = floor($OrignialHeight-(($percnt_reduced*$OrignialHeight)/100)); \n $NewWidth = floor($OrignialWidth-$diff); \n $AdjustDimensions = \"T\";\n }\n\n if($OrignialHeight > $MaximumHeight) { \n $diff = $OrignialHeight-$MaximumWidth; \n $percnt_reduced = (($diff/$OrignialHeight)*100); \n $NewWidth = floor($OrignialWidth-(($percnt_reduced*$OrignialWidth)/100)); \n $NewHeight= floor($OrignialHeight-$diff); \n $AdjustDimensions = \"T\";\n } \n\n $thisImageInfo = array('OriginalImageTag' => $img_tag , 'ImageSource' => $ImageSource , 'OrignialWidth' => $OrignialWidth , 'OrignialHeight' => $OrignialHeight , 'NewWidth' => $NewWidth , 'NewHeight' => $NewHeight, 'AdjustDimensions' => $AdjustDimensions);\n array_push($AllImageInfo, $thisImageInfo);\n}\n\n// build array of before and after tags\n$ImageBeforeAndAfter = array();\nfor ($i = 0; $i < count($AllImageInfo); $i++) {\n\n if($AllImageInfo[$i]['AdjustDimensions'] == \"T\") {\n $NewImageTag = str_ireplace('width=\"' . $AllImageInfo[$i]['OrignialWidth'] . '\"', 'width=\"' . $AllImageInfo[$i]['NewWidth'] . '\"', $AllImageInfo[$i]['OriginalImageTag']);\n $NewImageTag = str_ireplace('height=\"' . $AllImageInfo[$i]['OrignialHeight'] . '\"', 'height=\"' . $AllImageInfo[$i]['NewHeight'] . '\"', $NewImageTag);\n\n $thisImageBeforeAndAfter = array('OriginalImageTag' => $AllImageInfo[$i]['OriginalImageTag'] , 'NewImageTag' => $NewImageTag);\n array_push($ImageBeforeAndAfter, $thisImageBeforeAndAfter);\n }\n}\n\n// execute search and replace\nfor ($i = 0; $i < count($ImageBeforeAndAfter); $i++) {\n $HTMLContent = str_ireplace($ImageBeforeAndAfter[$i]['OriginalImageTag'],$ImageBeforeAndAfter[$i]['NewImageTag'], $HTMLContent);\n}\n\nreturn $HTMLContent;\n\n}\n" }, { "answer_id": 21375115, "author": "Nauphal", "author_id": 932319, "author_profile": "https://Stackoverflow.com/users/932319", "pm_score": 3, "selected": false, "text": "// Create DOM from URL or file\n$html = file_get_html('http://www.google.com/');\n\n// Find all images\nforeach($html->find('img') as $element)\n echo $element->src . '<br>';\n\n// Find all links\nforeach($html->find('a') as $element)\n echo $element->href . '<br>'; \n" }, { "answer_id": 56151147, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "$test = <<<HTML\n<img src=\"/image/fluffybunny.jpg\" title=\"Harvey the bunny\" alt=\"a cute little fluffy bunny\" />\n<img src='/image/pricklycactus.jpg' title='Roger the cactus' alt='a big green prickly cactus' />\n<p>This is irrelevant text.</p>\n<img alt=\"an annoying white cockatoo\" title=\"Polly the cockatoo\" src=\"/image/noisycockatoo.jpg\">\n<img title=something src=somethingelse>\nHTML;\n\nlibxml_use_internal_errors(true); // silences/forgives complaints from the parser (remove to see what is generated)\n$dom = new DOMDocument();\n$dom->loadHTML($test);\nforeach ($dom->getElementsByTagName('img') as $i => $img) {\n echo \"IMG#{$i}:\\n\";\n echo \"\\tsrc = \" , $img->getAttribute('src') , \"\\n\";\n echo \"\\ttitle = \" , $img->getAttribute('title') , \"\\n\";\n echo \"\\talt = \" , $img->getAttribute('alt') , \"\\n\";\n echo \"---\\n\";\n}\n IMG#0:\n src = /image/fluffybunny.jpg\n title = Harvey the bunny\n alt = a cute little fluffy bunny\n---\nIMG#1:\n src = /image/pricklycactus.jpg\n title = Roger the cactus\n alt = a big green prickly cactus\n---\nIMG#2:\n src = /image/noisycockatoo.jpg\n title = Polly the cockatoo\n alt = an annoying white cockatoo\n---\nIMG#3:\n src = somethingelse\n title = something\n alt = \n---\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
138,318
<p>here is my directory structure.</p> <p>/user/a /user/b /user/b</p> <p>inside folder a,b,c there is a file person.java (it is the Same file, just a one line modification.</p> <p>now, on my shell, im on my /user/ directory and i try to do </p> <pre><code> javac */person.java </code></pre> <p>the shell returns the following error,</p> <p>person.java:14: duplicate class: person</p> <p>Is there anything to resolve this?</p>
[ { "answer_id": 138329, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 4, "selected": true, "text": "find . -name '*.java' -exec javac {} \\; find . -name 'person.java' -maxdepth 2 -exec javac {} \\;" }, { "answer_id": 138354, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "for f in */person.java; do\n javac $file\ndone\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085/" ]
138,321
<p>I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree?</p> <p>(I'm on a Windows system, but have Cygwin installed.)</p>
[ { "answer_id": 138325, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 2, "selected": false, "text": "clearfsimport –recurse /usr/src/projectx /vobs/projectx/src\n" }, { "answer_id": 144310, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "clearfsimport -preview -rec -nset c:\\sourceDir\\* m:\\MyView\\MyVob\\MyDestinationDirectory\n" }, { "answer_id": 147899, "author": "Markus Schnell", "author_id": 20668, "author_profile": "https://Stackoverflow.com/users/20668", "pm_score": 5, "selected": false, "text": "Search... * Ctrl-A ClearCase Add to source control..." }, { "answer_id": 36550173, "author": "Amit Kumar", "author_id": 2123715, "author_profile": "https://Stackoverflow.com/users/2123715", "pm_score": 3, "selected": false, "text": "find . ! -path . -type d | xargs cleartool mkelem -mkpath -nc find ./ -type f | xargs cleartool mkelem -nc" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668/" ]
138,353
<p>In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?</p> <p>For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.</p> <p>However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.</p> <p>I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.</p> <pre><code> class Job(wiz.WizardPageSimple): """Character's job class.""" def __init__(self, parent, title, attribs): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) self.charAttribs = attribs #---Create widgets self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"] box1_title = wx.StaticBox( self, -1, "" ) box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL ) grid1 = wx.BoxSizer(wx.VERTICAL) for item in self.Job_list: radio = wx.RadioButton(self, -1, item) grid1.Add(radio) ##Debugging self.btn = wx.Button(self, -1, "click") self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn) #---Place widgets self.sizer.Add(self.Job_intro) self.sizer.Add(self.btn) box1.Add(grid1) self.sizer.Add(box1) def eligibleJob(self, event): """Determine which Jobs a character is eligible for.""" if self.charAttribs.intelligence &gt;= 12: skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"] for skill in skillList: self.Job_list.append(skill) print self.Job_list ##Debugging #return self.Job_list </code></pre>
[ { "answer_id": 139009, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 2, "selected": true, "text": "def addNewSkills(self, newSkillList):\n '''newSkillList is a list of skill names you want to add'''\n for skillName in newSkillList:\n newRadioButton = wx.RadioButton(self, -1, skillName)\n self.grid1.Add(newRadioButton) # appears in top-left corner of the panel\n self.Layout() # all newly added radio buttons appear where they should be\n self.Fit() # if you need to resize the panel to fit new items, this will help\n self.grid1" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
138,355
<p>I have a third party .NET Assembly and a large Java application. I need to call mothods provided by the .NET class library from the Java application. The assembly is not COM-enabled. I have searched the net and so far i have the following:</p> <p>C# code (cslib.cs):</p> <pre><code>using System; namespace CSLib { public class CSClass { public static void SayHi() { System.Console.WriteLine("Hi"); } } } </code></pre> <p>compiled with (using .net 3.5, but the same happens when 2.0 is used):</p> <pre><code>csc /target:library cslib.cs </code></pre> <p>C++ code (clib.cpp):</p> <pre><code>#include &lt;jni.h&gt; #using &lt;CSLib.dll&gt; using namespace CSLib; extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) { CSLib::CSClass::SayHi(); } </code></pre> <p>compiled with (using VC 2008 tools, but the same happens when 2003 tools are used):</p> <pre><code>cl /clr /LD clib.cpp mt -manifest clib.dll.manifest -outputresource:clib.dll;2 </code></pre> <p>Java code (CallCS.java):</p> <pre><code>class CallCS { static { System.loadLibrary("clib"); } private static native void callCS(); public static void main(String[] args) { callCS(); } } </code></pre> <p>When I try to run the java class, the Java VM crashes while invoking the method (it is able to load the library):</p> <pre> # # An unexpected error has been detected by Java Runtime Environment: # # Internal Error (0xe0434f4d), pid=3144, tid=3484 # # Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing windows-x86) # Problematic frame: # C [kernel32.dll+0x22366] # ... Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j CallCS.callCS()V+0 j CallCS.main([Ljava/lang/String;)V+0 v ~StubRoutines::call_stub </pre> <p>However, if I create a plain cpp application that loads clib.dll and calls the exported function Java_CallCS_callCS, everything is OK. I have tried this on both x86 and x64 environments and the result is the same. I have not tried other versions of Java, but I need the code to run on 1.5.0.</p> <p>Moreover, if I modify clib.cpp to call only System methods everything works fine even from Java:</p> <pre><code>#include &lt;jni.h&gt; #using &lt;mscorlib.dll&gt; using namespace System; extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) { System::Console::WriteLine("It works"); } </code></pre> <p>To wrap up:</p> <ol> <li>I am ABLE to call System methods from Java -> clib.dll -> mscorlib.dll</li> <li>I am ABLE to call any methods from CPPApp -> clib.dll -> cslib.dll</li> <li>I am UNABLE to call any methods from Java -> clib.dll -> cslib.dll</li> </ol> <p>I am aware of a workaround that uses 1. above - I can use reflection to load the assmebly and invoke desired methods using only System calls, but the code gets messy and I am hoping for a better solution. </p> <p>I know about dotnetfromjava project, which uses the reflection method, but prefer not to add more complexity than needed. I'll use something like this if there is no other way, however.</p> <p>I have looked at ikvm.net also, but my understanding is that it uses its own JVM (written in C#) to do the magic. However, running the entire Java application under its VM is no option for me.</p> <p>Thanks.</p>
[ { "answer_id": 17556542, "author": "dusselduck22", "author_id": 2565905, "author_profile": "https://Stackoverflow.com/users/2565905", "pm_score": 0, "selected": false, "text": " //C# code\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Security.Permissions;\nusing System.Runtime.InteropServices;\n\nnamespace JNIBridge\n{\n public class Temperature\n {\n\n [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution)]\n [ReflectionPermission(SecurityAction.Assert, Unrestricted = true)]\n [FileIOPermission(SecurityAction.Assert, Unrestricted = true)]\n\n public static double toFahrenheit(double value)\n {\n return (value * 9) / 5 + 32;\n }\n\n [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution)]\n [ReflectionPermission(SecurityAction.Assert, Unrestricted = true)]\n [FileIOPermission(SecurityAction.Assert, Unrestricted = true)]\n\n public static double toCelsius(double value)\n {\n return (value - 32) * 5 / 9; \n }\n\n\n }\n}\n // C++ Code\n\n#include \"stdafx.h\"\n\n#include \"JNIMapper.h\"\n#include \"DotNet.h\"\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/*\n * Class: DotNet\n * Method: toFahrenheit\n * Signature: (D)D\n */\n\nstatic bool initialized = false;\nusing namespace System;\nusing namespace System::Reflection;\n\n/*** \n This is procedure is always needed when the .NET dll's arent in the actual directory of the calling exe!!!\n It loads the needed assembly from a predefined path, if found in the directory and returns the assembly.\n*/\n\nAssembly ^OnAssemblyResolve(Object ^obj, ResolveEventArgs ^args)\n{\n //System::Console::WriteLine(\"In OnAssemblyResolve\");\n#ifdef _DEBUG\n /// Change to your .NET DLL paths here\n String ^path = gcnew String(\"d:\\\\WORK\\\\JNIBridge\\\\x64\\\\Debug\");\n#else\n String ^path = gcnew String(_T(\"d:\\\\WORK\\\\JNIBridge\\\\x64\\\\Release\"));\n#endif\n array<String^>^ assemblies =\n System::IO::Directory::GetFiles(path, \"*.dll\");\n for (long ii = 0; ii < assemblies->Length; ii++) {\n AssemblyName ^name = AssemblyName::GetAssemblyName(assemblies[ii]);\n if (AssemblyName::ReferenceMatchesDefinition(gcnew AssemblyName(args->Name), name)) {\n // System::Console::WriteLine(\"Try to resolve \"+ name);\n Assembly ^a = Assembly::Load(name);\n //System::Console::WriteLine(\"Resolved \"+ name);\n return a;\n }\n }\n return nullptr;\n}\n\n/**\n This procedure adds the Assembly resolve event handler\n*/\nvoid AddResolveEvent()\n{\n AppDomain::CurrentDomain->AssemblyResolve +=\n gcnew ResolveEventHandler(OnAssemblyResolve);\n}\n/*\n * Class: DotNet\n * Method: init\n * Signature: ()Z\n */\nJNIEXPORT jboolean JNICALL Java_DotNet_init\n (JNIEnv *, jobject)\n\n{\n printf(\"In init\\n\"); \n AddResolveEvent(); \n printf(\"init - done.\\n\"); \n return true;\n\n}\n\n/*\n * Class: DotNet\n * Method: toFahrenheit\n * Signature: (D)D\n */\n\nJNIEXPORT jdouble JNICALL Java_DotNet_toFahrenheit\n (JNIEnv * je, jobject jo, jdouble value)\n{\n printf(\"In Java_DotNet_toFahrenheit\\n\"); \n\n double result = 47;\n\n try{ \n result = JNIBridge::Temperature::toFahrenheit(value);\n } catch (...){\n printf(\"Error caught\");\n }\n return result;\n}\n\n/*\n * Class: DotNet\n * Method: toCelsius\n * Signature: (D)D\n */\nJNIEXPORT jdouble JNICALL Java_DotNet_toCelsius\n (JNIEnv * je, jobject jo , jdouble value){\n\n printf(\"In Java_DotNet_toCelsius\\n\");\n\n double result = 11;\n\n try{\n\n result = JNIBridge::Temperature::toCelsius(value);\n } catch (...){\n printf(\"Error caught\");\n }\n\n return result;\n}\n\n\n#ifdef __cplusplus\n\n}\n /***\n ** Java class file\n **/\npublic class DotNet { \n public native double toFahrenheit (double d);\n public native double toCelsius (double d);\n public native boolean init();\n\n static {\n try{ \n System.loadLibrary(\"JNIMapper\");\n } catch(Exception ex){\n ex.printStackTrace();\n }\n } \n\n public DotNet(){\n init();\n }\n\n public double fahrenheit (double v) {\n return toFahrenheit(v);\n }\n\n public double celsius (double v) {\n return toCelsius(v);\n }\n\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22602/" ]
138,361
<p>Or is it now the other way around?</p> <p>From what I've heard there are some areas in which C# proves to be faster than C++, but I've never had the guts to test it by myself.</p> <p>Thought any of you could explain these differences in detail or point me to the right place for information on this.</p>
[ { "answer_id": 2553416, "author": "rks", "author_id": 306058, "author_profile": "https://Stackoverflow.com/users/306058", "pm_score": -1, "selected": false, "text": "for (int i=0; i<1000; i++)\n{\n StreamReader str = new StreamReader(\"file.csv\");\n StreamWriter stw = new StreamWriter(\"examp.csv\");\n string strL = \"\";\n while((strL = str.ReadLine()) != null)\n {\n ArrayList al = new ArrayList();\n string[] strline = strL.Split(',');\n al.AddRange(strline);\n foreach(string str1 in strline)\n {\n stw.Write(str1 + \",\");\n }\n stw.Write(\"\\n\");\n }\n str.Close();\n stw.Close();\n}\n for (int i = 0; i<1000; i++)\n{\n std::fstream file(\"file.csv\", ios::in);\n if (!file.is_open())\n {\n std::cout << \"File not found!\\n\";\n return 1;\n }\n\n ofstream myfile;\n myfile.open (\"example.txt\");\n std::string csvLine;\n\n while (std::getline(file, csvLine))\n {\n std::istringstream csvStream(csvLine);\n std::vector csvColumn;\n std::string csvElement;\n\n while( std::getline(csvStream, csvElement, ‘,’) )\n {\n csvColumn.push_back(csvElement);\n }\n\n for (std::vector::iterator j = csvColumn.begin(); j != csvColumn.end(); ++j)\n {\n myfile << *j << \", \";\n }\n\n csvColumn.clear();\n csvElement.clear();\n csvLine.clear();\n myfile << \"\\n\";\n }\n myfile.close();\n file.close();\n}\n" }, { "answer_id": 5952642, "author": "Wiory", "author_id": 736258, "author_profile": "https://Stackoverflow.com/users/736258", "pm_score": 2, "selected": false, "text": "vector List new static void TestVector()\n{\n clock_t start,finish;\n start=clock();\n vector<vector<double>> myList=vector<vector<double>>();\n int i=0;\n for( i=0; i<500; i++)\n {\n myList.push_back(vector<double>());\n for(int j=0;j<50000;j++)\n myList[i].push_back(j+i);\n }\n finish=clock();\n cout<<(finish-start)<<endl;\n cout<<(double(finish - start)/CLOCKS_PER_SEC);\n}\n private static void TestVector()\n{\n\n DateTime t1 = System.DateTime.Now;\n List<List<double>> myList = new List<List<double>>();\n int i = 0;\n for (i = 0; i < 500; i++)\n {\n myList.Add(new List<double>());\n for (int j = 0; j < 50000; j++)\n myList[i].Add(j *i);\n }\n DateTime t2 = System.DateTime.Now;\n Console.WriteLine(t2 - t1);\n}\n static void TestArray()\n{\n cout << \"Normal array test:\" << endl;\n const int rows = 5000;\n const int columns = 9000;\n clock_t start, finish;\n\n start = clock();\n double** arr = new double*[rows];\n for (int i = 0; i < rows; i++)\n arr[i] = new double[columns];\n finish = clock();\n\n cout << (finish - start) << endl;\n\n start = clock();\n for (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n arr[i][j] = i * j;\n finish = clock();\n\n cout << (finish - start) << endl;\n}\n private static void TestArray()\n{\n const int rows = 5000;\n const int columns = 9000;\n DateTime t1 = System.DateTime.Now;\n double[][] arr = new double[rows][];\n for (int i = 0; i < rows; i++)\n arr[i] = new double[columns];\n DateTime t2 = System.DateTime.Now;\n\n Console.WriteLine(t2 - t1);\n\n t1 = System.DateTime.Now;\n for (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n arr[i][j] = i * j;\n t2 = System.DateTime.Now;\n\n Console.WriteLine(t2 - t1);\n\n}\n" }, { "answer_id": 34502915, "author": "Special Sauce", "author_id": 1911540, "author_profile": "https://Stackoverflow.com/users/1911540", "pm_score": 4, "selected": false, "text": "std::vector inline new T[] delete[] std::unique_ptr unsafe Calendar" }, { "answer_id": 39387531, "author": "U007D", "author_id": 1541330, "author_profile": "https://Stackoverflow.com/users/1541330", "pm_score": 7, "selected": false, "text": "private static void TestArray()\n{\n const int rows = 5000;\n const int columns = 9000;\n DateTime t1 = System.DateTime.Now;\n double[][] arr = new double[rows][];\n for (int i = 0; i < rows; i++)\n arr[i] = new double[columns];\n DateTime t2 = System.DateTime.Now;\n\n Console.WriteLine(t2 - t1);\n\n t1 = System.DateTime.Now;\n for (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n arr[i][j] = i;\n t2 = System.DateTime.Now;\n\n Console.WriteLine(t2 - t1);\n}\n #include <iostream>\n#include <vector>\n\nauto TestSuite::ColMajorArray()\n{\n constexpr size_t ROWS = 5000;\n constexpr size_t COLS = 9000;\n\n auto initStart = std::chrono::steady_clock::now();\n\n auto arr = std::vector<double>();\n arr.reserve(ROWS * COLS);\n\n auto initFinish = std::chrono::steady_clock::now();\n auto initTime = std::chrono::duration_cast<std::chrono::microseconds>(initFinish - initStart);\n\n auto fillStart = std::chrono::steady_clock::now();\n\n for(auto i = 0, r = 0; r < ROWS; ++r)\n {\n for (auto c = 0; c < COLS; ++c)\n {\n arr[i++] = static_cast<double>(r * c);\n }\n }\n\n auto fillFinish = std::chrono::steady_clock::now();\n auto fillTime = std::chrono::duration_cast<std::chrono::milliseconds>(fillFinish - fillStart);\n\n return std::make_pair(initTime, fillTime);\n}\n" }, { "answer_id": 49704653, "author": "Charles Owen", "author_id": 4151175, "author_profile": "https://Stackoverflow.com/users/4151175", "pm_score": 1, "selected": false, "text": "#include \"stdafx.h\"\n\nusing namespace System;\nusing namespace System::Diagnostics;\n\nbool EqualMe(String^ first, String^ second)\n{\n return first->Equals(second);\n}\nint main(array<String ^> ^args)\n{\n Stopwatch^ sw = gcnew Stopwatch();\n sw->Start();\n for (int i = 0; i < 100000; i++)\n {\n EqualMe(L\"one\", L\"two\");\n }\n sw->Stop();\n Console::WriteLine(sw->ElapsedTicks);\n return 0;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
138,371
<p>What are (if any)the implied assumptions or restrictions and the differences of designing like:</p> <p>A) this:</p> <pre><code>class SampleClass1 { IWorker workerA; IWorker workerB; void setWorkerA(IWorker w); void setWorkerB(IWorker w); WorkResult doWork(); } </code></pre> <p>B) versus this:</p> <pre><code>class SampleClass2 { WorkResult doWork(IWorker workerA, IWorker workerB); } </code></pre> <p>I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called.</p> <p>Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks.</p>
[ { "answer_id": 138403, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "WorkDelegate doWork WorkResult" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11906/" ]
138,374
<p>I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.</p> <p>I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?</p> <pre><code>&lt;?php echo( "We'll email you as soon as this is done." ); header( "Connection: Close" ); // do some stuff that will take a while mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' ); ?&gt; </code></pre>
[ { "answer_id": 138750, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 2, "selected": false, "text": "mkdir test\nchmod -R 777 test\ncd test\n bgping echo starting bgping\nping -c 15 www.google.com > dump.txt &\necho ending bgping\n & chmod 777 bgping\n bgtest.php <?php\n\necho \"start bgtest.php\\n\";\nexec('./bgping', $output, $result).\"\\n\";\necho \"output:\".print_r($output,true).\"\\n\";\necho \"result:\".print_r($result,true).\"\\n\";\necho \"end bgtest.php\\n\";\n\n?>\n start bgtest.php\noutput:Array\n(\n [0] => starting bgping\n [1] => ending bgping\n)\n\nresult:0\nend bgtest.php\n php -n -f largejob.php > dump.txt &\n" }, { "answer_id": 139306, "author": "Morgan ARR Allen", "author_id": 22474, "author_profile": "https://Stackoverflow.com/users/22474", "pm_score": 0, "selected": false, "text": "<?php\n function wrap($str)\n {\n return \"<script>{$str}</script>\";\n };\n\n ob_start(); // begin buffering output\n echo wrap(\"console.log('test1');\");\n ob_flush(); // push current buffer\n flush(); // this flush actually pushed to the browser\n $t = time();\n while($t > (time() - 3)) {} // wait 3 seconds\n echo wrap(\"console.log('test2');\");\n?>\n\n<html>\n <body>\n <iframe src=\"ob.php\"></iframe>\n </body>\n</html>\n" }, { "answer_id": 141026, "author": "Joeri Sebrechts", "author_id": 20980, "author_profile": "https://Stackoverflow.com/users/20980", "pm_score": 8, "selected": true, "text": "register_shutdown_function() <?php\nheader(\"Connection: close\");\nob_start();\nphpinfo();\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush();\nflush();\nsleep(13);\nerror_log(\"do something in the background\");\n?>\n phpinfo() echo('text I want user to see'); <?php\nob_end_clean();\nheader(\"Connection: close\");\nignore_user_abort(true); // just to be safe\nob_start();\necho('Text the user will see');\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush(); // Strange behaviour, will not work\nflush(); // Unless both are called !\n// Do processing here \nsleep(30);\necho('Text user will never see');\n?>\n" }, { "answer_id": 1773248, "author": "Timbo White", "author_id": 215773, "author_profile": "https://Stackoverflow.com/users/215773", "pm_score": 6, "selected": false, "text": "Connection: close\nContent-Length: n (n = size of output in bytes )\n // buffer all upcoming output\nob_start();\necho 'We\\'ll email you as soon as this is done.';\n\n// get the size of the output\n$size = ob_get_length();\n\n// send headers to tell the browser to close the connection\nheader('Content-Length: '.$size);\nheader('Connection: close');\n\n// flush all output\nob_end_flush();\nob_flush();\nflush();\n\n// if you're using sessions, this prevents subsequent requests\n// from hanging while the background process executes\nif (session_id()) {session_write_close();}\n\n/******** background process starts here ********/\n" }, { "answer_id": 7120170, "author": "diyism", "author_id": 264181, "author_profile": "https://Stackoverflow.com/users/264181", "pm_score": 4, "selected": false, "text": "ignore_user_abort(true);//avoid apache to kill the php running\nob_start();//start buffer output\n\necho \"show something to user\";\nsession_write_close();//close session file on server side to avoid blocking other requests\n\nheader(\"Content-Encoding: none\");//send header to avoid the browser side to take content as gzip format\nheader(\"Content-Length: \".ob_get_length());//send length header\nheader(\"Connection: close\");//or redirect to some url: header('Location: http://www.google.com');\nob_end_flush();flush();//really send content, can't change the order:1.ob buffer to normal buffer, 2.normal buffer to output\n\n//continue do something on server side\nob_start();\nsleep(5);//the user won't wait for the 5 seconds\necho 'for diyism';//user can't see this\nfile_put_contents('/tmp/process.log', ob_get_contents());\nob_end_clean();\n" }, { "answer_id": 10101623, "author": "Jorrit Schippers", "author_id": 261747, "author_profile": "https://Stackoverflow.com/users/261747", "pm_score": 5, "selected": false, "text": "fastcgi_end_request() fastcgi_finish_request() fastcgi_finish_request() fastcgi_finish_request() flush print echo ignore_user_abort(true) fastcgi_finish_request ignore_user_abort(true);\nfastcgi_finish_request();\n" }, { "answer_id": 10465055, "author": "Nir O.", "author_id": 582821, "author_profile": "https://Stackoverflow.com/users/582821", "pm_score": 0, "selected": false, "text": "flush() output_buffering = Off \nzlib.output_compression = Off \n" }, { "answer_id": 14950738, "author": "Andrew Winter", "author_id": 206001, "author_profile": "https://Stackoverflow.com/users/206001", "pm_score": 2, "selected": false, "text": "// buffer all upcoming output\nif(!ob_start(\"ob_gzhandler\")){\n define('NO_GZ_BUFFER', true);\n ob_start();\n}\necho \"We'll email you as soon as this is done.\";\n\n//Flush here before getting content length if ob_gzhandler was used.\nif(!defined('NO_GZ_BUFFER')){\n ob_end_flush();\n}\n\n// get the size of the output\n$size = ob_get_length();\n\n// send headers to tell the browser to close the connection\nheader(\"Content-Length: $size\");\nheader('Connection: close');\n\n// flush all output\nob_end_flush();\nob_flush();\nflush();\n\n// if you're using sessions, this prevents subsequent requests\n// from hanging while the background process executes\nif (session_id()) session_write_close();\n\n/******** background process starts here ********/\n" }, { "answer_id": 21037399, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 1, "selected": false, "text": "ignore_user_abort function disconnect_continue_processing($time_limit = null) {\n ignore_user_abort(true);\n session_write_close();\n set_time_limit((int) $time_limit);//defaults to no limit\n while (ob_get_level() > 1) {//only keep the last buffer if nested\n ob_end_flush();\n }\n $last_buffer = ob_get_level();\n $length = $last_buffer ? ob_get_length() : 0;\n header(\"Content-Length: $length\");\n header('Connection: close');\n if ($last_buffer) {\n ob_end_flush();\n }\n flush();\n}\n" }, { "answer_id": 26892012, "author": "skibulk", "author_id": 1017480, "author_profile": "https://Stackoverflow.com/users/1017480", "pm_score": 2, "selected": false, "text": "fastcgi_finish_request connection: close Transfer-Encoding: cunked 0\\r\\n\\r\\n // Disable automatic compression\n// @ini_set('zlib.output_compression', 'Off');\n// @ini_set('output_buffering', 'Off');\n// @ini_set('output_handler', '');\n// @apache_setenv('no-gzip', 1);\n\n// Chunked Transfer-Encoding & Gzip Content-Encoding\nfunction ob_chunked_gzhandler($buffer, $phase) {\n if (!headers_sent()) header('Transfer-Encoding: chunked');\n $buffer = ob_gzhandler($buffer, $phase);\n return dechex(strlen($buffer)).\"\\r\\n$buffer\\r\\n\";\n}\n\nob_start('ob_chunked_gzhandler');\n\n// First Chunk\necho \"Hello World\";\nob_flush();\n\n// Second Chunk\necho \", Grand World\";\nob_flush();\n\nob_end_clean();\n\n// Terminating Chunk\necho \"\\x30\\r\\n\\r\\n\";\nob_flush();\nflush();\n\n// Post Processing should not be displayed\nfor($i=0; $i<10; $i++) {\n print(\"Post-Processing\");\n sleep(1);\n}\n" }, { "answer_id": 26996177, "author": "Tasos", "author_id": 1127070, "author_profile": "https://Stackoverflow.com/users/1127070", "pm_score": 1, "selected": false, "text": "FcgidOutputBufferSize FcgidOutputBufferSize 0\n FcgidOutputBufferSize <?php\n ob_end_clean();\n header(\"Connection: close\");\n ignore_user_abort(true); // just to be safe\n ob_start();\n echo('Text the user will see');\n\n echo(str_repeat(' ', 65537)); // [+] Line added: Fill up mod_fcgi's buffer.\n\n $size = ob_get_length();\n header(\"Content-Length: $size\");\n ob_end_flush(); // Strange behaviour, will not work\n flush(); // Unless both are called !\n // Do processing here \n sleep(30);\n echo('Text user will never see');\n?>\n FcgidOutputBufferSize <VirtualHost *:80>\n DocumentRoot \"d:/wamp/www/example\"\n ServerName example.local\n\n FcgidOutputBufferSize 0\n\n <Directory \"d:/wamp/www/example\">\n Require all granted\n </Directory>\n</VirtualHost>\n" }, { "answer_id": 28299471, "author": "Williem", "author_id": 3091630, "author_profile": "https://Stackoverflow.com/users/3091630", "pm_score": 1, "selected": false, "text": "//avoid apache to kill the php running\nignore_user_abort(true);\n//start buffer output\nob_start();\n\necho \"show something to user1\";\n//close session file on server side to avoid blocking other requests\nsession_write_close();\n\n//send length header\nheader(\"Content-Length: \".ob_get_length());\nheader(\"Connection: close\");\n//really send content, can't change the order:\n//1.ob buffer to normal buffer,\n//2.normal buffer to output\nob_end_flush();\nflush();\n//continue do something on server side\nob_start();\n//replace it with the background task\nsleep(20);\n" }, { "answer_id": 40041923, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 3, "selected": false, "text": "<?php\necho \"We'll email you as soon as this is done.\";\nsystem(\"php somestuff.php dude@thatplace.com >/dev/null &\");\n?>\n" }, { "answer_id": 43113409, "author": "FluorescentGreen5", "author_id": 3881189, "author_profile": "https://Stackoverflow.com/users/3881189", "pm_score": 2, "selected": false, "text": "ignore_user_abort(true); //Safety measure so that the user doesn't stop the script too early.\n\n$content = 'Hello World!'; //The content that will be sent to the browser.\n\nheader('Content-Length: ' . strlen($content)); //The browser will close the connection when the size of the content reaches \"Content-Length\", in this case, immediately.\n\nob_start(); //Content past this point...\n\necho $content;\n\n//...will be sent to the browser (the output buffer gets flushed) when this code executes.\nob_end_flush();\nob_flush();\nflush();\n\nif(session_id())\n{\n session_write_close(); //Closes writing to the output buffer.\n}\n\n//Anything past this point will be ran without involving the browser.\n ignore_user_abort(true);\n\nfunction sendAndAbort($content)\n{\n header('Content-Length: ' . strlen($content));\n\n ob_start();\n\n echo $content;\n\n ob_end_flush();\n ob_flush();\n flush();\n}\n\nsendAndAbort('Hello World!');\n\n//Anything past this point will be ran without involving the browser.\n" }, { "answer_id": 43327373, "author": "Sudharshana S L Srihari", "author_id": 5232157, "author_profile": "https://Stackoverflow.com/users/5232157", "pm_score": 0, "selected": false, "text": " // client can see outputs if any\n ignore_user_abort(true);\n ob_start();\n echo \"success\";\n $buffer_size = ob_get_length();\n session_write_close();\n header(\"Content-Encoding: none\");\n header(\"Content-Length: $buffer_size\");\n header(\"Connection: close\");\n ob_end_flush();\n ob_flush();\n flush();\n\n sleep(2);\n ob_start();\n // client cannot see the result of code below\n" }, { "answer_id": 49208805, "author": "WhiteAngel", "author_id": 1291512, "author_profile": "https://Stackoverflow.com/users/1291512", "pm_score": 0, "selected": false, "text": "function sendResponse($response) {\n ob_end_clean();\n header(\"Connection: close\\r\\n\");\n header(\"Content-Encoding: none\\r\\n\");\n ignore_user_abort(true);\n ob_start();\n\n echo $response; // Actual response that will be sent to the user\n\n $size = ob_get_length();\n header(\"Content-Length: $size\");\n ob_end_flush();\n flush();\n if (ob_get_contents()) {\n ob_end_clean();\n }\n}\n" }, { "answer_id": 72672603, "author": "Teson", "author_id": 247245, "author_profile": "https://Stackoverflow.com/users/247245", "pm_score": 0, "selected": false, "text": "//limit of length required!\n<?php\n$s = file_get_contents('http://127.0.0.1:8080/test.php',false,null,0,10);\necho $s;\n ob_end_clean();\nheader(\"Connection: close\");\nignore_user_abort(true);\nob_start();\necho 'Text the user will see';\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush(); // All output buffers must be flushed here\nflush(); // Force output to client\n// Do processing here \nsleep(5);\nfile_put_contents('ts.txt',date('H:i:s',time()));\n//echo('Text user will never see');\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82944/" ]
138,379
<p>What happens if I use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx" rel="nofollow noreferrer">SHGetFolderPath</a> api call in a 32 bit system with CSIDL_PROGRAM_FILESx86 folder id instead of the CSIDL_PROGRAM_FILES id?</p> <p>Theoretically CSIDL_PROGRAM_FILESx86 should map to <code>C:\program files (x86)</code> in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist?</p>
[ { "answer_id": 138473, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 4, "selected": true, "text": "The interpretation of certain KNOWNFOLDERID values depends on whether the folder is part of a 32-bit or 64-bit application and whether that application is running on a 32-bit or 64-bit operating system. If your application needs to distinguish between, for example, Program Files and Program Files (x86), you must use the right KNOWNFOLDERID for the situation.\n\nThe following tables summarize the KNOWNFOLDERID use in those cases.\n\nFOLDERID_ProgramFiles\nOS Application KNOWNFOLDERID Default Path CSIDL Equivalent\n32 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\\Program Files CSIDL_PROGRAM_FILES\n32 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\\Program Files CSIDL_PROGRAM_FILESX86\n32 bit 32 bit FOLDERID_ProgramFilesX64 (undefined) Not applicable Not applicable\n64 bit 64 bit FOLDERID_ProgramFiles %SystemDrive%\\Program Files CSIDL_PROGRAM_FILES\n64 bit 64 bit FOLDERID_ProgramFilesX86 %SystemDrive%\\Program Files (x86) CSIDL_PROGRAM_FILESX86\n64 bit 64 bit FOLDERID_ProgramFilesX64 %SystemDrive%\\Program Files None\n64 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\\Program Files (x86) CSIDL_PROGRAM_FILES\n64 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\\Program Files (x86) CSIDL_PROGRAM_FILESX86\n64 bit 32 bit FOLDERID_ProgramFilesX64 %SystemDrive%\\Program Files None\n" }, { "answer_id": 6204863, "author": "Stlopus", "author_id": 779843, "author_profile": "https://Stackoverflow.com/users/779843", "pm_score": 1, "selected": false, "text": "GetEnvironmentVariable(\"ProgramW6432\", szBuffer, nBufferSize);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14587/" ]
138,383
<p>Sometimes coloring a logfile or other gives a good overview when looking for <em>stuff</em> and <em>behaviors</em></p> <p>I just saw that grep have a coloring feature</p> <pre><code>grep -C 99999 --color &lt;regexp&gt; &lt;filename&gt; </code></pre> <p>What other methods are there?</p>
[ { "answer_id": 138528, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 4, "selected": false, "text": "#include <stdio.h>\n#include <regex.h>\n\n#define MAX_LINE 4096\n\n#define RESET \"\\033[0m\"\n#define BLACK \"\\033[30m\" /* Black */\n#define RED \"\\033[31m\" /* Red */\n#define GREEN \"\\033[32m\" /* Green */\n#define YELLOW \"\\033[33m\" /* Yellow */\n#define BLUE \"\\033[34m\" /* Blue */\n#define MAGENTA \"\\033[35m\" /* Magenta */\n#define CYAN \"\\033[36m\" /* Cyan */\n#define WHITE \"\\033[37m\" /* White */\n#define BOLDBLACK \"\\033[1m\\033[30m\" /* Bold Black */\n#define BOLDRED \"\\033[1m\\033[31m\" /* Bold Red */\n#define BOLDGREEN \"\\033[1m\\033[32m\" /* Bold Green */\n#define BOLDYELLOW \"\\033[1m\\033[33m\" /* Bold Yellow */\n#define BOLDBLUE \"\\033[1m\\033[34m\" /* Bold Blue */\n#define BOLDMAGENTA \"\\033[1m\\033[35m\" /* Bold Magenta */\n#define BOLDCYAN \"\\033[1m\\033[36m\" /* Bold Cyan */\n#define BOLDWHITE \"\\033[1m\\033[37m\" /* Bold White */\n\nstatic int selected_color = 0;\nstatic char *colors[] = {\n \"-green\", GREEN,\n \"-black\", BLACK,\n \"-red\", RED,\n \"-yellow\", YELLOW,\n \"-blue\", BLUE,\n \"-magenta\", MAGENTA,\n \"-cyan\", CYAN,\n \"-white\", WHITE,\n \"-boldgreen\", BOLDGREEN,\n \"-boldblack\", BOLDBLACK,\n \"-boldred\", BOLDRED,\n \"-boldyellow\", BOLDYELLOW,\n \"-boldblue\", BOLDBLUE,\n \"-boldmagenta\", BOLDMAGENTA,\n \"-boldcyan\", BOLDCYAN,\n \"-boldwhite\", BOLDWHITE,\n NULL\n};\n\n/*----------------------------------------------------------------------*/\n\nint main(int argc, char *argv[]) {\n char buf[MAX_LINE];\n int has_re = 0;\n regex_t re;\n\n if (argc > 1) {\n if (argc > 2) {\n int idx = 0;\n while (colors[idx*2]) {\n if (!strcmp(colors[idx*2], argv[1])) {\n selected_color = idx;\n break;\n }\n idx++;\n }\n if (regcomp(&re, argv[2], REG_EXTENDED | REG_NEWLINE)) {\n printf(\"regcomp() failed!\\n\");\n return -1;\n }\n } else if (regcomp(&re, argv[1], REG_EXTENDED | REG_NEWLINE)) {\n printf(\"regcomp() failed!\\n\");\n return -1;\n }\n has_re = 1;\n } else {\n printf(\"Usage: %s [ -red | -blue | -cyan | -white | -black | \"\n \"-yellow | -magenta ] <regexp>\\n\", argv[0]);\n return -1; \n }\n\n while (fgets(buf, MAX_LINE, stdin) == buf) {\n char *bbuf = buf;\n while (1) {\n if (has_re) {\n regmatch_t match[10];\n if (regexec(&re, bbuf, re.re_nsub + 1, match, 0)) {\n printf(\"%s\", bbuf);\n break;\n } else {\n int i, idx;\n for (i=idx=0; i<1; i++) {\n if (match[0].rm_so < 0) {\n break;\n } else {\n printf(\"%.*s\", \n (int)(match[i].rm_so-idx), \n bbuf+idx);\n printf( \"%s%.*s\" RESET, \n colors[selected_color*2+1],\n (int)(match[i].rm_eo-match[i].rm_so), \n bbuf+(int)match[i].rm_so);\n idx = match[i].rm_eo;\n bbuf += idx;\n }\n }\n }\n }\n fflush(stdout);\n }\n }\n\n if (has_re) {\n regfree(&re);\n }\n\n return 0;\n}\n" }, { "answer_id": 50229165, "author": "merlin2011", "author_id": 391161, "author_profile": "https://Stackoverflow.com/users/391161", "pm_score": 1, "selected": false, "text": "colorize docopt colorize.py -f 'This is an interesting line=Blue' -f 'Different topic=Red' Input.log\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842/" ]
138,394
<p>I'm trying to fix a non-responsive USB device that's masquerading as a virtual COM port. Manual replugging works, but there may be up to 12 of these units. Is there an API command to do the programmatic equivalent of the unplug/replug cycle?</p>
[ { "answer_id": 14216048, "author": "shahar_m", "author_id": 662770, "author_profile": "https://Stackoverflow.com/users/662770", "pm_score": 2, "selected": false, "text": "public bool ResetDevice( IntPtr hDevInfo, IntPtr devInfoData ) \n// Need to add \n// public const int DICS_PROPCHANGE = ((0x00000003)); \n// at the public class Native under //PARMS \nint szOfPcp; \nIntPtr ptrToPcp; \nint szDevInfoData; \nIntPtr ptrToDevInfoData; \n\nNative.SP_PROPCHANGE_PARAMS pcp = new Native.SP_PROPCHANGE_PARAMS(); \npcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(Native.SP_CLASSINSTALL_HEADER)); \npcp.ClassInstallHeader.InstallFunction = Native.DIF_PROPERTYCHANGE; \npcp.StateChange = Native.DICS_PROPCHANGE; // for reset \npcp.Scope = Native.DICS_FLAG_CONFIGSPECIFIC; \npcp.HwProfile = 0; \n\nszOfPcp = Marshal.SizeOf(pcp); \nptrToPcp = Marshal.AllocHGlobal(szOfPcp); \nMarshal.StructureToPtr(pcp, ptrToPcp, true); \nszDevInfoData = Marshal.SizeOf(devInfoData); \nptrToDevInfoData = Marshal.AllocHGlobal(szDevInfoData); \nMarshal.StructureToPtr(devInfoData, ptrToDevInfoData, true); \n\nbool rslt1 = Native.SetupDiSetClassInstallParams(hDevInfo, ptrToDevInfoData, ptrToPcp, Marshal.SizeOf(typeof(Native.SP_PROPCHANGE_PARAMS))); \nbool rstl2 = Native.SetupDiCallClassInstaller(Native.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData); \n\nif (rslt1 && rstl2) \n{ \n return true; \n} \nreturn false; \n} \n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
138,411
<p>Is there any way of knowing if the user closes a tab in a web browser? Specifically IE7, but also FireFox and others as well. I would like to be able to handle this situation from our asp code if the current tab containing our web site closes.</p>
[ { "answer_id": 146826, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 0, "selected": false, "text": "XMLHttpRequest" }, { "answer_id": 193727, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "onbeforeunload" }, { "answer_id": 4208431, "author": "Tyler", "author_id": 65977, "author_profile": "https://Stackoverflow.com/users/65977", "pm_score": 0, "selected": false, "text": "TabClose" }, { "answer_id": 4319352, "author": "Santosh", "author_id": 525816, "author_profile": "https://Stackoverflow.com/users/525816", "pm_score": 3, "selected": false, "text": "* Close the current browser window.\n* Navigate to another location by entering a new address or selecting a Favorite.\n* Click the Back, Forward, Refresh, or Home button.\n* Click an anchor that refers the browser to another Web page.\n* Invoke the anchor.click method.\n* Invoke the document.write method.\n* Invoke the document.open method.\n* Invoke the document.close method.\n* Invoke the window.close method.\n* Invoke the window.open method, providing the possible value _self for the window name.\n* Invoke the window.navigate or NavigateAndFind method.\n* Invoke the location.replace method.\n* Invoke the location.reload method.\n* Specify a new value for the location.href property.\n* Submit a form to the address specified in the ACTION attribute via the INPUT type=submit control, or invoke the form.submit method.\n" }, { "answer_id": 9920612, "author": "ThdK", "author_id": 681803, "author_profile": "https://Stackoverflow.com/users/681803", "pm_score": 0, "selected": false, "text": " $(function () { \n window.onbeforeunload = OnBeforeUnload;\n $(window).data('beforeunload', window.onbeforeunload);\n $('body').delegate('a', 'hover', function (event) {\n if (event.type === 'mouseenter' || event.type === \"mouseover\")\n window.onbeforeunload = null;\n else\n window.onbeforeunload = $(window).data('beforeunload');\n });\n });\n window.onbeforeunload = null;\n function OnBeforeUnload(oEvent) { \n // return a string to show the warning message (not every browser will use this string in the dialog)\n // or run the code you need when the user closes your page \n return \"Are you sure you want to close this window?\"; \n }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20315/" ]
138,412
<p>I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.</p> <p>I have a GridView in which the code in the ASP reference to it in the HTML is minimal:</p> <pre><code>&lt;asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True"&gt; &lt;/asp:GridView&gt; </code></pre> <p>In the code-behind I attach a dynamically-created SqlDataSource (the columns it contains are not always the same so the SQL used to create it is constructed at runtime). For example:</p> <p>I set up the columns...</p> <pre><code>BoundField column = new BoundField(); column.DataField = columnName; column.HeaderText = "Heading"; column.SortExpression = columnName; grid.Columns.Add(column); </code></pre> <p>the data source...</p> <pre><code>SqlDataSource dataSource = new SqlDataSource( "System.Data.SqlClient", connectionString, generatedSelectCommand); </code></pre> <p>then the gridview...</p> <pre><code>grid.DataSource = dataSource; grid.DataKeyNames = mylistOfKeys; grid.DataBind(); </code></pre> <p>At the moment nothing happens when a user clicks on a column heading when I'd expect it to sort the column data. Anyone any ideas what I'm missing?</p> <p>If there's a nicer way of doing this that would be helpful too as this looks messy to me!</p>
[ { "answer_id": 138492, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": true, "text": "<asp:GridView AllowSorting=\"True\" OnSorting=\"gvName_Sorting\" ...\n protected void gvName_Sorting( object sender, GridViewSortEventArgs e )\n{\n ...\n //rebind gridview\n}\n" }, { "answer_id": 2965130, "author": "Martin", "author_id": 355272, "author_profile": "https://Stackoverflow.com/users/355272", "pm_score": 0, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\n If Not IsPostBack Then\n\n Me.gridView.Sort(Request.QueryString(\"sortExpression\"), Request.QueryString(\"sortDirection\"))\n\n End If\n\nEnd Sub\n Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gridView.Sorting\n If IsPostBack Then\n e.Cancel = True\n Dim sortDir As SortDirection = SortDirection.Ascending\n If e.SortExpression = Me.Q_SortExpression And Me.Q_SortDirection = SortDirection.Ascending Then\n sortDir = SortDirection.Descending\n End If\n RedirectMe(e.SortExpression, sortDir)\n Else\n Dim sortExpr As String = e.SortExpression + \" \" + IIf(e.SortDirection = SortDirection.Ascending, \"ASC\", \"DESC\")\n Dim dv As System.Data.DataView = Me.dsrcView.Select(New DataSourceSelectArguments(sortExpr))\n Me.gridView.DataSource = dv\n Me.gridView.DataBind()\n End If\nEnd Sub\n" }, { "answer_id": 4430230, "author": "Mike", "author_id": 540688, "author_profile": "https://Stackoverflow.com/users/540688", "pm_score": 3, "selected": false, "text": "protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)\n{\n GridView gv = (GridView)sender;\n SqlDataSource ds = (SqlDataSource)gv.DataSource;\n ds.SelectCommand = ds.SelectCommand + \" order by \" \n + e.SortExpression + \" \" + GetSortDirection(e.SortDirection);\n gvItems.DataSource = ds;\n gvItems.DataBind();\n}\n\nstring GetSortDirection(string sSortDirCmd)\n{\n string sSortDir;\n if ((SortDirection.Ascending == sSortDirCmd))\n {\n sSortDir = \"asc\";\n }\n else\n {\n sSortDir = \"desc\";\n }\n return sSortDir;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22185/" ]