qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
171,400
<p>I'd like to know if anyone has any first-hand experience with this dichotomy. A few blogs say the mysql extension is faster than mysqli. Is this true?</p> <p>And I'm only asking about speed. I know mysqli has features that are not present in the older extension.</p>
[ { "answer_id": 17254568, "author": "Donovanr", "author_id": 2047064, "author_profile": "https://Stackoverflow.com/users/2047064", "pm_score": -1, "selected": false, "text": "SELECT * FROM users WHERE ID=$user_id $user_id SELECT * FROM users WHERE ID=? E_DEPRECATED" }, { "answer_id": 20766308, "author": "Josh", "author_id": 3133345, "author_profile": "https://Stackoverflow.com/users/3133345", "pm_score": 0, "selected": false, "text": "<?php\n$start = microtime();\n$c = new mysqli('localhost', 'username', 'userpass', 'username_dbname');\n$c -> select_db('username_dbname');\n\n\n$q = $c -> query(\"SELECT * FROM example\");\n\nwhile ($r = $q -> fetch_array(MYSQLI_ASSOC))\n {\n echo $r['col1'] . \"<br/>\\n\";\n }\n\n$me = $c -> query(\"SELECT col1 FROM example WHERE id='11'\") -> fetch_array(MYSQLI_ASSOC);\n\necho $me['col1'];\necho (microtime() - $start);\n?>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3351/" ]
171,407
<p>Has anyone implemented Mozilla's Object.toSource() method for Internet Explorer and other non-Gecko browsers? I'm looking for a lightweight way to serialize simple objects into strings.</p>
[ { "answer_id": 171421, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "Object.prototype.getSource = function() {\n var output = [], temp;\n for (var i in this) {\n if (this.hasOwnProperty(i)) {\n temp = i + \":\";\n switch (typeof this[i]) {\n case \"object\" :\n temp += this[i].getSource();\n break;\n case \"string\" :\n temp += \"\\\"\" + this[i] + \"\\\"\"; // add in some code to escape quotes\n break;\n default :\n temp += this[i];\n }\n output.push(temp);\n }\n }\n return \"{\" + output.join() + \"}\";\n}\n" }, { "answer_id": 171698, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "function SerializeObject(obj, indentValue)\n{\n var hexDigits = \"0123456789ABCDEF\";\n function ToHex(d)\n {\n return hexDigits[d >> 8] + hexDigits[d & 0x0F];\n }\n function Escape(string)\n {\n return string.replace(/[\\x00-\\x1F'\\\\]/g,\n function (x)\n {\n if (x == \"'\" || x == \"\\\\\") return \"\\\\\" + x;\n return \"\\\\x\" + ToHex(String.charCodeAt(x, 0));\n })\n }\n\n var indent;\n if (indentValue == null)\n {\n indentValue = \"\";\n indent = \"\"; // or \" \"\n }\n else\n {\n indent = \"\\n\";\n }\n return GetObject(obj, indent).replace(/,$/, \"\");\n\n function GetObject(obj, indent)\n {\n if (typeof obj == 'string')\n {\n return \"'\" + Escape(obj) + \"',\";\n }\n if (obj instanceof Array)\n {\n result = indent + \"[\";\n for (var i = 0; i < obj.length; i++)\n {\n result += indent + indentValue +\n GetObject(obj[i], indent + indentValue);\n }\n result += indent + \"],\";\n return result;\n }\n var result = \"\";\n if (typeof obj == 'object')\n {\n result += indent + \"{\";\n for (var property in obj)\n {\n result += indent + indentValue + \"'\" +\n Escape(property) + \"' : \" +\n GetObject(obj[property], indent + indentValue);\n }\n result += indent + \"},\";\n }\n else\n {\n result += obj + \",\";\n }\n return result.replace(/,(\\n?\\s*)([\\]}])/g, \"$1$2\");\n }\n}\n" }, { "answer_id": 5628008, "author": "Ekim", "author_id": 703011, "author_profile": "https://Stackoverflow.com/users/703011", "pm_score": 3, "selected": false, "text": "javascript:\n x=function(){alert('caveat compter')};\n alert(['JSON:\\t',JSON.stringify(x),'\\n\\ntoSource():\\t',x.toSource()].join(''));\n javascript:\nx=[];x[3]=x;\nalert('toSource():\\t'+x.toSource());\nalert('JSON can not handle this at all and goes \"infinite\".');\nalert('JSON:\\n'+JSON.stringify(x));\n javascript:\nfunction render(title,src){ (function(objRA){\n alert([ title, src,\n '\\ntoSource():',objRA.toSource(),\n '\\nJSON:',JSON.stringify(objRA) ].join('\\n'));\n })(eval(src));\n}\nrender('Simple Raw Object source code:',\n '[new Array, new Object, new Number, new String, ' +\n 'new Boolean, new Date, new RegExp, new Function]' );\n\nrender( 'Literal Instances source code:',\n '[ [], 1, true, {}, \"\", /./, new Date(), function(){} ]' );\n\nrender( 'some predefined entities:',\n '[JSON, Math, null, Infinity, NaN, ' +\n 'void(0), Function, Array, Object, undefined]' );\n" }, { "answer_id": 15184817, "author": "Eliran Malka", "author_id": 547020, "author_profile": "https://Stackoverflow.com/users/547020", "pm_score": 0, "selected": false, "text": "toSource() function#toString() var serialized = function () {\n return {\n n: 8,\n o: null,\n b: true,\n s: 'text',\n a: ['a', 'b', 'c'],\n f: function () {\n alert('!')\n }\n }\n};\nserialized.toString();\n" }, { "answer_id": 25701797, "author": "dragon", "author_id": 4014779, "author_profile": "https://Stackoverflow.com/users/4014779", "pm_score": 1, "selected": false, "text": "// SENDER IS WRAPPING OBJECT TO BE SENT AS STRING\n// object to serialize\nvar s1 = function (str) {\n return {\n n: 8,\n o: null,\n b: true,\n s: 'text',\n a: ['a', 'b', 'c'],\n f: function () {\n alert(str)\n }\n }\n};\n// test\ns1(\"this function call works!\").f();\n// serialized object; for newbies: object is now a string and can be sent ;)\nvar code = s1.toString();\n\n// RECEIVER KNOWS A WRAPPED OBJECT IS COMING IN\n// you have to assign your wrapped object to somevar\neval('var s2 = ' + code);\n// and then you can test somevar again\ns2(\"this also works!\").f();\n eval" }, { "answer_id": 39154926, "author": "max pleaner", "author_id": 2981429, "author_profile": "https://Stackoverflow.com/users/2981429", "pm_score": 0, "selected": false, "text": "Object.toSource" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
171,412
<p>I basically have an xml column, and I need to find and replace one tag value in each record.</p>
[ { "answer_id": 171429, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 4, "selected": false, "text": "SELECT * FROM Table\nWHERE XMLColumn.exist('/Root/MyElement') = 1\n SET XMLColumn.modify('\n replace value of (/Root/MyElement/text())[1]\n with \"new value\"\n')\n" }, { "answer_id": 171430, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": -1, "selected": false, "text": "update my_table\nset xml_column = replace(xml_column, \"old value\", \"new value\")\n" }, { "answer_id": 6451344, "author": "Cory Mawhorter", "author_id": 670023, "author_profile": "https://Stackoverflow.com/users/670023", "pm_score": 6, "selected": true, "text": "UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]') SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%' CAST( xmlCol as nvarchar(max) )" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
171,435
<p>I know that the #warning directive is not standard <strong>C</strong>/C++, but several compilers support it, including gcc/g++. But for those that don't support it, will they silently ignore it or will it result in a compile failure? In other words, can I safely use it in my project without breaking the build for compilers that don't support it?</p>
[ { "answer_id": 40147989, "author": "Fantastory", "author_id": 621706, "author_profile": "https://Stackoverflow.com/users/621706", "pm_score": 2, "selected": false, "text": "#ifdef __GNUC__\n//from https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html\n//Instead of put such pragma in code:\n//#pragma GCC diagnostic ignored \"-Wformat\"\n//use:\n//PRAGMA_GCC(diagnostic ignored \"-Wformat\")\n#define DO_PRAGMA(x) _Pragma (#x)\n#define PRAGMA_GCC(x) DO_PRAGMA(GCC #x)\n\n#define PRAGMA_MESSAGE(x) DO_PRAGMA(message #x)\n#define PRAGMA_WARNING(x) DO_PRAGMA(warning #x)\n#endif //__GNUC__\n#ifdef _MSC_VER\n/*\n#define PRAGMA_OPTIMIZE_OFF __pragma(optimize(\"\", off))\n// These two lines are equivalent\n#pragma optimize(\"\", off)\nPRAGMA_OPTIMIZE_OFF\n*/\n#define PRAGMA_GCC(x)\n// https://support2.microsoft.com/kb/155196?wa=wsignin1.0\n#define __STR2__(x) #x\n#define __STR1__(x) __STR2__(x)\n#define __PRAGMA_LOC__ __FILE__ \"(\"__STR1__(__LINE__)\") \"\n#define PRAGMA_WARNING(x) __pragma(message(__PRAGMA_LOC__ \": warning: \" #x))\n#define PRAGMA_MESSAGE(x) __pragma(message(__PRAGMA_LOC__ \": message : \" #x))\n\n#endif\n\n//#pragma message \"message quoted\"\n//#pragma message message unquoted\n\n//#warning warning unquoted\n//#warning \"warning quoted\"\n\nPRAGMA_MESSAGE(PRAGMA_MESSAGE unquoted)\nPRAGMA_MESSAGE(\"PRAGMA_MESSAGE quoted\")\n\n#warning \"#pragma warning quoted\"\n\nPRAGMA_WARNING(PRAGMA_WARNING unquoted)\nPRAGMA_WARNING(\"PRAGMA_WARNING quoted\")\n #pragma warning #pragma warning\" #warning" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78437/" ]
171,452
<p>I've got an app that my client wants to open a kiosk window to ie on startup that goes to their corporate internet. Vb isn't my thing but they wanted it integrated into their current program and I figured it would be easy so I've got</p> <pre><code>Shell ("explorer.exe http://www.corporateintranet.com") </code></pre> <p>and command line thing that needs to be passed is -k</p> <p>Can't figure out where in the hell to drop this to make it work. Thanks in advance! :)</p>
[ { "answer_id": 171459, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "iexplore.exe explorer.exe" }, { "answer_id": 171465, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Shell (\"C:\\Program Files\\Internet Explorer\\iexplore.exe -k http://www.corporateintranet.com\")\n" }, { "answer_id": 27620668, "author": "Julien Dumoulin", "author_id": 4388605, "author_profile": "https://Stackoverflow.com/users/4388605", "pm_score": 0, "selected": false, "text": "ShellExecute(Application.hwnd, \"open\", \"http://www.corporateintranet.com\", vbNullString, vbNullString, SW_SHOWNORMAL)\n Public Declare Function ShellExecute Lib \"shell32.dll\" Alias \"ShellExecuteA\" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long\nPublic Const SW_SHOW = 5\nPublic Const SW_SHOWDEFAULT = 10\nPublic Const SW_SHOWNORMAL = 1\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
171,474
<p>I'm curious what tools people have found useful for building flowcharts. Obviously MS Visio and OmniGraffle come to mind but they both feel so bloated and also tend to emphasize the document formatting/printing side and less on helping to organize the actual logic. Is there anything else out there that fellow developers would recommend?</p> <p>I'm hoping to find something fairly simple that would let me throw together flowcharts on the fly when I'm working through complex logic. I don't care about formatting or fonts or the like, just something that would help me keep my logic organized as I work through it. Even something that would arrange the chart itself and simply allow me to specify where to branch and what to check, etc.</p> <p>Any OS would be fine, though I personally lean towards OS X apps as this has recently been my primary work environment.</p>
[ { "answer_id": 173034, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "digraph finite_state_machine {\n rankdir=LR;\n size=\"8,5\"\n node [shape = doublecircle]; LR_0 LR_3 LR_4 LR_8;\n node [shape = circle];\n LR_0 -> LR_2 [ label = \"SS(B)\" ];\n LR_0 -> LR_1 [ label = \"SS(S)\" ];\n LR_1 -> LR_3 [ label = \"S($end)\" ];\n LR_2 -> LR_6 [ label = \"SS(b)\" ];\n LR_2 -> LR_5 [ label = \"SS(a)\" ];\n LR_2 -> LR_4 [ label = \"S(A)\" ];\n LR_5 -> LR_7 [ label = \"S(b)\" ];\n LR_5 -> LR_5 [ label = \"S(a)\" ];\n LR_6 -> LR_6 [ label = \"S(b)\" ];\n LR_6 -> LR_5 [ label = \"S(a)\" ];\n LR_7 -> LR_8 [ label = \"S(b)\" ];\n LR_7 -> LR_5 [ label = \"S(a)\" ];\n LR_8 -> LR_6 [ label = \"S(b)\" ];\n LR_8 -> LR_5 [ label = \"S(a)\" ];\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
171,480
<p>I have a value like this:</p> <pre class="lang-none prettyprint-override"><code>"Foo Bar" "Another Value" something else </code></pre> <p>What regex will return the values enclosed in the quotation marks (e.g. <code>Foo Bar</code> and <code>Another Value</code>)?</p>
[ { "answer_id": 171483, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": false, "text": "\"(.*?)\"\n >>> import re\n>>> string = '\"Foo Bar\" \"Another Value\"'\n>>> print re.findall(r'\"(.*?)\"', string)\n['Foo Bar', 'Another Value']\n" }, { "answer_id": 171492, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": false, "text": "\"([^\"]*)\"\n" }, { "answer_id": 171499, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 10, "selected": true, "text": "([\"'])(?:(?=(\\\\?))\\2.)*?\\1\n ([\"\"']) ((?=(\\\\?))\\2.) *? \\1" }, { "answer_id": 171914, "author": "amo-ej1", "author_id": 15791, "author_profile": "https://Stackoverflow.com/users/15791", "pm_score": 2, "selected": false, "text": "echo 'junk \"Foo Bar\" not empty one \"\" this \"but this\" and this neither' | sed 's/[^\\\"]*\\\"\\([^\\\"]*\\)\\\"[^\\\"]*/>\\1</g'\n" }, { "answer_id": 172996, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 3, "selected": false, "text": "/([\"'])((?:(?!\\1)[^\\\\]|(?:\\\\\\\\)*\\\\[^\\\\])*)\\1/\n" }, { "answer_id": 7627772, "author": "Alexandru Furculita", "author_id": 841146, "author_profile": "https://Stackoverflow.com/users/841146", "pm_score": 1, "selected": false, "text": "|([\\'\"])(.*?)\\1|i\n preg_match_all('|([\\'\"])(.*?)\\1|i', $cont, $matches);\n" }, { "answer_id": 8313796, "author": "motoprog", "author_id": 808760, "author_profile": "https://Stackoverflow.com/users/808760", "pm_score": 2, "selected": false, "text": "reg = r\"\"\"(['\"])(%s)\\1\"\"\"\nif re.search(reg%(needle), haystack, re.IGNORECASE):\n print \"winning...\"\n" }, { "answer_id": 19124525, "author": "miracle2k", "author_id": 15677, "author_profile": "https://Stackoverflow.com/users/15677", "pm_score": 3, "selected": false, "text": "foo \"string \\\\ string\" bar\n foo \"string1\" bar \"string2\"\n # opening quote\n([\"'])\n (\n # repeat (non-greedy, so we don't span multiple strings)\n (?:\n # anything, except not the opening quote, and not \n # a backslash, which are handled separately.\n (?!\\1)[^\\\\]\n |\n # consume any double backslash (unnecessary?)\n (?:\\\\\\\\)* \n |\n # Allow backslash to escape characters\n \\\\.\n )*?\n )\n# same character as opening quote\n\\1\n" }, { "answer_id": 21721356, "author": "mobman", "author_id": 3288462, "author_profile": "https://Stackoverflow.com/users/3288462", "pm_score": 3, "selected": false, "text": "string = \"\\\" foo bar\\\" \\\"loloo\\\"\"\nprint re.findall(r'\"(.*?)\"',string)\n \\" }, { "answer_id": 26634133, "author": "Suganthan Madhavan Pillai", "author_id": 2534236, "author_profile": "https://Stackoverflow.com/users/2534236", "pm_score": 4, "selected": false, "text": "(\\\"[\\w\\s]+\\\")\n" }, { "answer_id": 29452781, "author": "Casimir et Hippolyte", "author_id": 2255089, "author_profile": "https://Stackoverflow.com/users/2255089", "pm_score": 5, "selected": false, "text": "[^\"\\\\]*(?:\\\\.[^\"\\\\]*)* [^\"\\\\]*+(?:\\\\.[^\"\\\\]*)*+ [^\"]*(?:\"\"[^\"]*)* ([\"']).....\\1 [\"'] [\"'](?:(?<=\")[^\"\\\\]*(?s:\\\\.[^\"\\\\]*)*\"|(?<=')[^'\\\\]*(?s:\\\\.[^'\\\\]*)*')\n (?s:...) [\\s\\S] (?=[\"'])(?:\"[^\"\\\\]*(?:\\\\[\\s\\S][^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\[\\s\\S][^'\\\\]*)*')\n \"[^\"\\\\]*(\\\\(.|\\n)[^\"\\\\]*)*\"|'[^'\\\\]*(\\\\(.|\\n)[^'\\\\]*)*'\n \"([^\"\\\\]|\\\\.|\\\\\\n)*\"|'([^'\\\\]|\\\\.|\\\\\\n)*'\n" }, { "answer_id": 34198968, "author": "Eugen Mihailescu", "author_id": 327614, "author_profile": "https://Stackoverflow.com/users/327614", "pm_score": 3, "selected": false, "text": "([\"'])(?:(?=(\\\\?))\\2.)*?\\1 \"(.*?)\" \\' /(['\"])((\\\\\\1|.)*?)\\1/gm" }, { "answer_id": 39486685, "author": "Martin Schneider", "author_id": 1951524, "author_profile": "https://Stackoverflow.com/users/1951524", "pm_score": 5, "selected": false, "text": "\"Foo Bar\" \"Another Value\" \"(.*?[^\\\\])\" '(.*?[^\\\\])' ([\"'])(.*?[^\\\\])\\1" }, { "answer_id": 40519361, "author": "James Harrington", "author_id": 1456666, "author_profile": "https://Stackoverflow.com/users/1456666", "pm_score": 3, "selected": false, "text": "\\\"([^\\\"]*?icon[^\\\"]*?)\\\" id=\"fb-icon\" id=\"icon-close\" id=\"large-icon-close\" \" \" icon \" \"" }, { "answer_id": 47214303, "author": "IrishDubGuy", "author_id": 1669024, "author_profile": "https://Stackoverflow.com/users/1669024", "pm_score": 5, "selected": false, "text": "(?<=([\"']\\b))(?:(?=(\\\\?))\\2.)*?(?=\\1)\n ?<= ?= [\"'] (?=\\1) [\"']\\b" }, { "answer_id": 49073714, "author": "OffensivelyBad", "author_id": 6199526, "author_profile": "https://Stackoverflow.com/users/6199526", "pm_score": 2, "selected": false, "text": "\\\"([^\\\"]*?[^\\\"]*?)\\\".localized .localized print(\"this is something I need to return\".localized + \"so is this\".localized + \"but this is not\") \"this is something I need to return\".localized \"so is this\".localized \"but this is not\"" }, { "answer_id": 50176237, "author": "S Meaden", "author_id": 3607273, "author_profile": "https://Stackoverflow.com/users/3607273", "pm_score": 2, "selected": false, "text": "Microsoft VBScript Regular Expressions 5.5 Sub TestRegularExpression()\n\n Dim oRE As VBScript_RegExp_55.RegExp '* Tools->References: Microsoft VBScript Regular Expressions 5.5\n Set oRE = New VBScript_RegExp_55.RegExp\n\n oRE.Pattern = \"\"\"([^\"\"]*)\"\"\"\n\n\n oRE.Global = True\n\n Dim sTest As String\n sTest = \"\"\"Foo Bar\"\" \"\"Another Value\"\" something else\"\n\n Debug.Assert oRE.test(sTest)\n\n Dim oMatchCol As VBScript_RegExp_55.MatchCollection\n Set oMatchCol = oRE.Execute(sTest)\n Debug.Assert oMatchCol.Count = 2\n\n Dim oMatch As Match\n For Each oMatch In oMatchCol\n Debug.Print oMatch.SubMatches(0)\n\n Next oMatch\n\nEnd Sub\n" }, { "answer_id": 50196016, "author": "lon", "author_id": 5379564, "author_profile": "https://Stackoverflow.com/users/5379564", "pm_score": 2, "selected": false, "text": "([\"'])(?:\\\\\\1|.)*?\\1\n ([\"'])((?:\\\\\\1|.)*?)\\1\n $1 $2" }, { "answer_id": 50320848, "author": "wp78de", "author_id": 8291949, "author_profile": "https://Stackoverflow.com/users/8291949", "pm_score": 4, "selected": false, "text": "(['\"])(?:(?!\\1|\\\\).|\\\\.)*\\1\n $0 (?<=(['\"])\\b)(?:(?!\\1|\\\\).|\\\\.)*(?=\\1)\n \\b $2 (['\"])((?:(?!\\1|\\\\).|\\\\.)*)\\1\n" }, { "answer_id": 61985732, "author": "Donovan P", "author_id": 9895070, "author_profile": "https://Stackoverflow.com/users/9895070", "pm_score": 2, "selected": false, "text": "/(?<=((?<=[\\s,.:;\"']|^)[\"']))(?:(?=(\\\\?))\\2.)*?(?=\\1)/gmu\n" }, { "answer_id": 72615025, "author": "novice", "author_id": 13836083, "author_profile": "https://Stackoverflow.com/users/13836083", "pm_score": 2, "selected": false, "text": "([\"']).*\\1(?![^\\s]) ([\"']) ' \" \\1 .* ' \" \\1 (?![^\\s])" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4646/" ]
171,506
<p>I've been unsuccessfully searching for a way to install <code>make</code> utility on my CentOS 5.2. I've looked through some RPM repositories and online, with no avail. Installing <code>gcc</code>, <code>gcc-c++</code> didn't help! Package <code>build-essential</code> is not made for CentOS/RHEL. I have RPMFORGE repo enabled in YUM.</p>
[ { "answer_id": 1539224, "author": "Daniel Von Fange", "author_id": 62621, "author_profile": "https://Stackoverflow.com/users/62621", "pm_score": 5, "selected": false, "text": "yum install make\n" }, { "answer_id": 3523405, "author": "CagedMantis", "author_id": 71002, "author_profile": "https://Stackoverflow.com/users/71002", "pm_score": 6, "selected": false, "text": "yum groupinstall \"Development Tools\"\n yum install gcc gcc-c++ kernel-devel\n" }, { "answer_id": 45987742, "author": "Lionel", "author_id": 335185, "author_profile": "https://Stackoverflow.com/users/335185", "pm_score": 2, "selected": false, "text": "yum install -y gcc-c++ make" }, { "answer_id": 61944751, "author": "Bruno Spolavori", "author_id": 10095914, "author_profile": "https://Stackoverflow.com/users/10095914", "pm_score": 0, "selected": false, "text": "yum groupinstall \"Development Tools\" -y \n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406/" ]
171,512
<p>I wish to implement a 2d bit map class in Python. The class would have the following requirements:</p> <ol> <li><p>Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like:</p> <pre><code>bitmap = Bitmap(8,8) </code></pre></li> <li><p>provide an API to access the bits in this 2d map as boolean or even integer values, i.e.:</p> <pre><code>if bitmap[1, 2] or bitmap.get(0, 1) </code></pre></li> <li><p>Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar.</p> <pre><code>bitmap.data() </code></pre></li> <li><p>Be able to create new maps from the binary data retrieved:</p> <pre><code>new_bitmap = Bitmap(8, 8, bitmap.data()) </code></pre></li> </ol> <p>I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.</p>
[ { "answer_id": 171672, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": true, "text": ">>> a = np.array([[[1,0,1],\n... [0,1,0]],\n... [[1,1,0],\n... [0,0,1]]])\n>>> b = np.packbits(a,axis=-1)\n>>> b\narray([[[160],[64]],[[192],[32]]], dtype=uint8)\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
171,516
<p>In my ASP.NET application using InProc sessions, Session_End calls a static method in another object to do session-specific clean up. This clean up uses a shared database connection that I am storing in application state.</p> <p>The problem is that I cannot see how to access the application state without passing it (or rather the database connection) as a parameter to the clean up method. Since I am not in a request I have no current HttpContext, and I cannot find any other static method to access the state.</p> <p>Am I missing something?</p> <p><strong>UPDATE</strong>: It appears that my question needs further clarification, so let me try the following code sample. What I want to be able to do is:</p> <pre><code>// in Global.asax void Session_End(object sender, EventArgs e) { NeedsCleanup nc = Session["NeedsCleanup"] as NeedsCleanup; nc.CleanUp(); } </code></pre> <p>But the problem is that the <code>CleanUp</code> method in turn needs information that is stored in application state. I am already doing the following, but it is exactly what I was hoping to avoid; this is what I meant by "...without passing it... as a parameter to the clean up method" above.</p> <pre><code>// in Global.asax void Session_End(object sender, EventArgs e) { NeedsCleanup nc = Session["NeedsCleanup"] as NeedsCleanup; nc.CleanUp(this.Application); } </code></pre> <p>I just do not like the idea that <code>Global.asax</code> <em>has</em> to know where the <code>NeedsCleanup</code> object gets its information. That sort of thing that makes more sense as self-contained within the class.</p>
[ { "answer_id": 171538, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 1, "selected": false, "text": "void Session_End(object sender, EventArgs e) \n{\n HttpSessionState session = this.Session;\n}\n" }, { "answer_id": 173245, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 2, "selected": false, "text": "void Session_End(object sender, EventArgs e) \n{\n HttpApplicationState state = this.Application;\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6234/" ]
171,519
<p>I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 (<a href="http://adldap.sourceforge.net/" rel="noreferrer">adLDAP</a> does it on Apache). Anyone had done anything similar, with success?</p> <ul> <li>Edit: I'd prefer a library/class with code that's ready to go... It'd be silly to invent the wheel when someone has already done so.</li> </ul>
[ { "answer_id": 172042, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 8, "selected": true, "text": "$ldap = ldap_connect(\"ldap.example.com\");\nif ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {\n // log them in!\n} else {\n // error message\n}\n" }, { "answer_id": 36522599, "author": "ChadSikorra", "author_id": 2242593, "author_profile": "https://Stackoverflow.com/users/2242593", "pm_score": 4, "selected": false, "text": "use LdapTools\\Configuration;\nuse LdapTools\\DomainConfiguration;\nuse LdapTools\\LdapManager;\n\n$domain = (new DomainConfiguration('example.com'))\n ->setUsername('username') # A separate AD service account used by your app\n ->setPassword('password')\n ->setServers(['dc1', 'dc2', 'dc3'])\n ->setUseTls(true);\n$config = new Configuration($domain);\n$ldap = new LdapManager($config);\n\nif (!$ldap->authenticate($username, $password, $message)) {\n echo \"Error: $message\";\n} else {\n // Do something...\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406/" ]
171,529
<p>I have this Task model:</p> <pre><code>class Task &lt; ActiveRecord::Base acts_as_tree :order =&gt; 'sort_order' end </code></pre> <p>And I have this test</p> <pre><code>class TaskTest &lt; Test::Unit::TestCase def setup @root = create_root end def test_destroying_a_task_should_destroy_all_of_its_descendants d1 = create_task(:parent_id =&gt; @root.id, :sort_order =&gt; 2) d2 = create_task(:parent_id =&gt; d1.id, :sort_order =&gt; 3) d3 = create_task(:parent_id =&gt; d2.id, :sort_order =&gt; 4) d4 = create_task(:parent_id =&gt; d1.id, :sort_order =&gt; 5) assert_equal 5, Task.count d1.destroy assert_equal @root, Task.find(:first) assert_equal 1, Task.count end end </code></pre> <p>The test is successful: when I destroy d1, it destroys all the descendants of d1. Thus, after the destroy only the root is left.</p> <p>However, this test is now failing after I have added a before_save callback to the Task. This is the code I added to Task:</p> <pre><code>before_save :update_descendants_if_necessary def update_descendants_if_necessary handle_parent_id_change if self.parent_id_changed? return true end def handle_parent_id_change self.children.each do |sub_task| #the code within the loop is deliberately commented out end end </code></pre> <p>When I added this code, <code>assert_equal 1, Task.count</code> fails, with <code>Task.count == 4</code>. I think <code>self.children</code> under <code>handled_parent_id_change</code> is the culprit, because when I comment out the <code>self.children.each do |sub_task|</code> block, the test passes again.</p> <p>Any ideas?</p>
[ { "answer_id": 172553, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "children .children Task.count d1.children.count" }, { "answer_id": 173169, "author": "gsmendoza", "author_id": 11082, "author_profile": "https://Stackoverflow.com/users/11082", "pm_score": 3, "selected": true, "text": "d1 = create_task(:parent_id => @root.id, :sort_order => 2)\n before_save self.children @root.children << (d1 = new_task(:sort_order => 2))\n@root.save!\n d1.reload self.children(true)" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082/" ]
171,541
<p>I have a service app that creates AppDomain's during the course of its use for long running tasks. I've been tracking these by storing them in a Hashtable with a unique ID.</p> <p>After a task is completed the service app then unloads the AppDomain allocated to that task and then it's removed it from the appdomain Hashtable.</p> <p>Purely from a sanity checking point of view, is there a way I can query the CLR to see what app domains are still loaded by the creating app domain (i.e. so I can compare the tracking Hashtable against what the CLR actually sees)?</p>
[ { "answer_id": 172553, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "children .children Task.count d1.children.count" }, { "answer_id": 173169, "author": "gsmendoza", "author_id": 11082, "author_profile": "https://Stackoverflow.com/users/11082", "pm_score": 3, "selected": true, "text": "d1 = create_task(:parent_id => @root.id, :sort_order => 2)\n before_save self.children @root.children << (d1 = new_task(:sort_order => 2))\n@root.save!\n d1.reload self.children(true)" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
171,542
<p>I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using <pre>document.body.clientHeight</pre> but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big. </p> <p>Now, I really don't want to use browser specific logic and substract a pixel or 2 from each dimension just for IE6. Also, I am not using CSS (width: 100% etc.) for this because I need the pixel amounts.</p> <p>Does anyone know a better way to fill the viewport with an element in IE6+ (obviously all good browsers, too)?</p> <p>Edit: Thanks Owen for the suggestion, I'm sure jQuery will work. I should have specified that I need a toolkit-agnostic solution. </p>
[ { "answer_id": 171544, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n<!--\n\n var viewportwidth;\n var viewportheight;\n\n // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight\n\n if (typeof window.innerWidth != 'undefined')\n {\n viewportwidth = window.innerWidth,\n viewportheight = window.innerHeight\n }\n\n// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)\n\n else if (typeof document.documentElement != 'undefined'\n && typeof document.documentElement.clientWidth !=\n 'undefined' && document.documentElement.clientWidth != 0)\n {\n viewportwidth = document.documentElement.clientWidth,\n viewportheight = document.documentElement.clientHeight\n }\n\n // older versions of IE\n\n else\n {\n viewportwidth = document.getElementsByTagName('body')[0].clientWidth,\n viewportheight = document.getElementsByTagName('body')[0].clientHeight\n }\ndocument.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');\n//-->\n</script>\n" }, { "answer_id": 171632, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "var width = $(document).width();\nvar height = $(document.height();\n\n$('#mySpecialElement').width(width).height(height);\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25066/" ]
171,548
<p>I have always been for documenting code, but when it comes to AJAX + PHP, it's not always easy: the code is really spread out! Logic, data, presentation - you name it - are split and mixed between server-side and client-side code. Sometimes there's also database-side code (stored procedures, views, etc) doing part of the work.</p> <p>This challenges me to come up with an efficient way to document such code. I usually provide a list of .js files inside .php file as well as list of .php files inside .js file. I also do in-line comments and function descriptions, where I list what function is used by what file and what output is expected. I do similar tasks for database procedures. Maybe there's a better method?</p> <p>Any ideas or experiences?</p> <p>Note: This question applies to any client+server-side applications, not just Javascript+PHP.</p>
[ { "answer_id": 191907, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 1, "selected": false, "text": "function OutputJs($Content) {\n ob_start();\n echo $Content;\n $expires = DAY_IN_S;\n header(\"Content-type: x-javascript\");\n header('Content-Length: ' . ob_get_length());\n header('Cache-Control: max-age='.$expires.', must-revalidate');\n header('Pragma: public');\n header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');\n ob_end_flush(); \n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406/" ]
171,550
<blockquote> <p><strong>See also:</strong> <br/> <em><a href="https://stackoverflow.com/questions/4950725">How can I see which Git branches are tracking which remote / upstream branch?</a></em></p> </blockquote> <p>How can I find out which remote branch a local branch is tracking?</p> <p>Do I need to parse <code>git config</code> output, or is there a command that would do this for me?</p>
[ { "answer_id": 7251377, "author": "Aaron Wells", "author_id": 468642, "author_profile": "https://Stackoverflow.com/users/468642", "pm_score": 7, "selected": false, "text": "@{u} git log remotename/branchname..HEAD LOCAL_BRANCH=`git name-rev --name-only HEAD`\nTRACKING_BRANCH=`git config branch.$LOCAL_BRANCH.merge`\nTRACKING_REMOTE=`git config branch.$LOCAL_BRANCH.remote`\nREMOTE_URL=`git config remote.$TRACKING_REMOTE.url`\n git config branch.`git name-rev --name-only HEAD`.remote\n" }, { "answer_id": 7733266, "author": "Ajit George", "author_id": 36661, "author_profile": "https://Stackoverflow.com/users/36661", "pm_score": 8, "selected": false, "text": "git branch -av git remote show origin abranch $ git branch -av\n* abranch d875bf4 initial commit\n master d875bf4 initial commit\n remotes/origin/HEAD -> origin/master\n remotes/origin/abranch d875bf4 initial commit\n remotes/origin/master d875bf4 initial commit\n $ git remote show origin\n* remote origin\n Fetch URL: /home/ageorge/tmp/d/../exrepo/\n Push URL: /home/ageorge/tmp/d/../exrepo/\n HEAD branch (remote HEAD is ambiguous, may be one of the following):\n abranch\n master\n Remote branches:\n abranch tracked\n master tracked\n Local branches configured for 'git pull':\n abranch merges with remote abranch\n master merges with remote master\n Local refs configured for 'git push':\n abranch pushes to abranch (up to date)\n master pushes to master (up to date)\n" }, { "answer_id": 9753364, "author": "cdunn2001", "author_id": 263998, "author_profile": "https://Stackoverflow.com/users/263998", "pm_score": 9, "selected": false, "text": "% git rev-parse --abbrev-ref --symbolic-full-name @{u}\norigin/mainline\n % git for-each-ref --format='%(upstream:short)' \"$(git symbolic-ref -q HEAD)\"\norigin/mainline\n" }, { "answer_id": 10014285, "author": "Olivier Refalo", "author_id": 258689, "author_profile": "https://Stackoverflow.com/users/258689", "pm_score": 1, "selected": false, "text": "git config --global alias.track '!sh -c \"\nif [ \\$# -eq 2 ]\n then\n echo \\\"Setting tracking for branch \\\" \\$1 \\\" -> \\\" \\$2;\n git branch --set-upstream \\$1 \\$2;\n else\n git for-each-ref --format=\\\"local: %(refname:short) <--sync--> remote: %(upstream:short)\\\" refs/heads && echo --URLs && git remote -v;\nfi \n\" -'\n git track\n" }, { "answer_id": 12538667, "author": "jdsumsion", "author_id": 1667497, "author_profile": "https://Stackoverflow.com/users/1667497", "pm_score": 10, "selected": false, "text": "$ git branch -vv\n main aaf02f0 [main/master: ahead 25] Some other commit\n* master add0a03 [jdsumsion/master] Some commit\n git remote show origin git status git status -sb" }, { "answer_id": 26526119, "author": "Eugene Yarmash", "author_id": 244297, "author_profile": "https://Stackoverflow.com/users/244297", "pm_score": 5, "selected": false, "text": "git checkout $ git checkout \nYour branch is up-to-date with 'origin/master'.\n" }, { "answer_id": 27395297, "author": "Trickmaster", "author_id": 2652482, "author_profile": "https://Stackoverflow.com/users/2652482", "pm_score": 4, "selected": false, "text": "cat .git/config" }, { "answer_id": 32255813, "author": "Wayne Walker", "author_id": 448831, "author_profile": "https://Stackoverflow.com/users/448831", "pm_score": 3, "selected": false, "text": "if git rev-parse @{u} > /dev/null 2>&1\nthen\n printf \"has an upstream\\n\"\nelse\n printf \"has no upstream\\n\"\nfi\n" }, { "answer_id": 32613805, "author": "FragLegs", "author_id": 912374, "author_profile": "https://Stackoverflow.com/users/912374", "pm_score": 4, "selected": false, "text": "git status -b --porcelain\n ## BRANCH(...REMOTE)\nmodified and untracked files\n" }, { "answer_id": 35835293, "author": "Ranushka Goonesekere", "author_id": 3234426, "author_profile": "https://Stackoverflow.com/users/3234426", "pm_score": 3, "selected": false, "text": "git branch -r -vv\n" }, { "answer_id": 38406646, "author": "nikkypx", "author_id": 1395009, "author_profile": "https://Stackoverflow.com/users/1395009", "pm_score": 6, "selected": false, "text": "git branch -vv \n git branch -a -vv\n git remote show {remote_name}\n" }, { "answer_id": 39456421, "author": "ravikanth", "author_id": 1030360, "author_profile": "https://Stackoverflow.com/users/1030360", "pm_score": 0, "selected": false, "text": "def gitHash = new ByteArrayOutputStream()\n project.exec {\n commandLine 'git', 'rev-parse', '--short', 'HEAD'\n standardOutput = gitHash\n }\n\ndef gitBranch = new ByteArrayOutputStream()\n project.exec {\n def gitCmd = \"git symbolic-ref --short -q HEAD || git branch -rq --contains \"+getGitHash()+\" | sed -e '2,\\$d' -e 's/\\\\(.*\\\\)\\\\/\\\\(.*\\\\)\\$/\\\\2/' || echo 'master'\"\n commandLine \"bash\", \"-c\", \"${gitCmd}\"\n standardOutput = gitBranch\n }\n" }, { "answer_id": 40630957, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": 5, "selected": false, "text": "$ git branch -vv\n $ git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)\n myremote/mybranch\n $ git remote get-url $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)|cut -d/ -f1)\n https://github.com/someone/somerepo.git\n" }, { "answer_id": 52896538, "author": "Tom Hale", "author_id": 5353461, "author_profile": "https://Stackoverflow.com/users/5353461", "pm_score": 2, "selected": false, "text": ".gitconfig branch-name = \"symbolic-ref --short HEAD\"\nbranch-remote-fetch = !\"branch=$(git branch-name) && git config branch.\\\"$branch\\\".remote || echo origin #\"\nbranch-remote-push = !\"branch=$(git branch-name) && git config branch.\\\"$branch\\\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #\"\nbranch-url-fetch = !\"remote=$(git branch-remote-fetch) && git remote get-url \\\"$remote\\\" #\" # cognizant of insteadOf\nbranch-url-push = !\"remote=$(git branch-remote-push ) && git remote get-url --push \\\"$remote\\\" #\" # cognizant of pushInsteadOf\n" }, { "answer_id": 52930908, "author": "Jeremy Thomerson", "author_id": 1011988, "author_profile": "https://Stackoverflow.com/users/1011988", "pm_score": 3, "selected": false, "text": "git rev-parse --abbrev-ref --symbolic-full-name YOUR_LOCAL_BRANCH_NAME@{upstream} YOUR_LOCAL_BRANCH_NAME" }, { "answer_id": 55698562, "author": "joseluisq", "author_id": 2510591, "author_profile": "https://Stackoverflow.com/users/2510591", "pm_score": 3, "selected": false, "text": "$ git branch -ra\n feature/feature1\n feature/feature2\n hotfix/hotfix1\n* master\n remotes/origin/HEAD -> origin/master\n remotes/origin/develop\n remotes/origin/master\n" }, { "answer_id": 55968741, "author": "xpioneer", "author_id": 3729270, "author_profile": "https://Stackoverflow.com/users/3729270", "pm_score": 3, "selected": false, "text": "git remote show origin | grep \"branch_name\"\n branch_name" }, { "answer_id": 58872860, "author": "Sabyasachi Ghosh", "author_id": 11169852, "author_profile": "https://Stackoverflow.com/users/11169852", "pm_score": 5, "selected": false, "text": "git branch -vv | grep 'BRANCH_NAME' git branch -vv grep 'BRANCH_NAME'" }, { "answer_id": 60297250, "author": "AndiDog", "author_id": 245706, "author_profile": "https://Stackoverflow.com/users/245706", "pm_score": 4, "selected": false, "text": "$ git status -b --porcelain=v2\n# branch.oid d0de00da833720abb1cefe7356493d773140b460\n# branch.head the-branch-name\n# branch.upstream gitlab/the-branch-name\n# branch.ab +2 -2\n $ git status -b --porcelain=v2 | grep -m 1 \"^# branch.upstream \" | cut -d \" \" -f 3-\ngitlab/the-branch-name\n set -o pipefail" }, { "answer_id": 63585578, "author": "Erik Aronesty", "author_id": 627042, "author_profile": "https://Stackoverflow.com/users/627042", "pm_score": 2, "selected": false, "text": "git branch -a --contains HEAD --list --format='%(refname:short)'\n / (" }, { "answer_id": 71040132, "author": "Fred Yang", "author_id": 98563, "author_profile": "https://Stackoverflow.com/users/98563", "pm_score": 0, "selected": false, "text": "git branch -vv | grep 'hardcode-branch-name'\n# \"git rev-parse --abbrev-ref head\" will get your current branch name\n# $(git rev-parse --abbrev-ref head) save it as string\n# find the tracking branch by grep filtering the current branch \ngit branch -vv | grep $(git rev-parse --abbrev-ref head)\n" }, { "answer_id": 72717025, "author": "PhillipMcCubbin", "author_id": 13977551, "author_profile": "https://Stackoverflow.com/users/13977551", "pm_score": 1, "selected": false, "text": "grep git branch -vv --contains\n git branch -vv --contains HEAD\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
171,565
<p>Is there a tool/plugin/function for Firefox that'll dump out a memory usage of Javascript objects that you create in a page/script? I know about Firebug's profiler but I'd like something more than just times. Something akin to what Yourkit has for Java profiling of memory usage.</p> <p>Reason is that a co-worker is using id's for "keys" in an array and is creating 1000's of empty slots when he does this. He's of the opinion that this is harmless whereas my opinion differs. I'd like to offer some proof to prove whether I'm right or not.</p>
[ { "answer_id": 172105, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 3, "selected": false, "text": "Array Object" }, { "answer_id": 22458462, "author": "Jan Wrobel", "author_id": 1031601, "author_profile": "https://Stackoverflow.com/users/1031601", "pm_score": 3, "selected": false, "text": "about:memory" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8590/" ]
171,566
<p>Im using delphi's ttreeview as an 'options' menu. how would i go upon selecting the next node at runtime like a previous and next button? i tried the getprev and getnext methods but no luck.</p>
[ { "answer_id": 171722, "author": "John Thomas", "author_id": 22599, "author_profile": "https://Stackoverflow.com/users/22599", "pm_score": 3, "selected": false, "text": "procedure TForm8.btn1Click(Sender: TObject); \nvar \n crt: TTreeNode;\n\nbegin\n with tv1 do //this is our tree\n begin\n if Selected=nil then\n crt:=Items[0] //the first one\n else\n crt:=Selected.GetNext; //for previous you'll have 'GetPrev' \n\n if crt<>nil then //can be 'nil' if we reached to the end\n Selected:=crt;\n end;\nend;\n" }, { "answer_id": 2968900, "author": "Remus Rigo", "author_id": 184401, "author_profile": "https://Stackoverflow.com/users/184401", "pm_score": 0, "selected": false, "text": "type TfrmMain = class(TForm)\n...\n public\n DLLHandle : THandle;\n function GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\n\n...\n\nfunction TfrmMain.GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\nbegin\n Result:='';\n while Assigned(node) do\n begin\n Result:=delimiter+node.Text+Result;\n node:=node.Parent;\n end;\n if Result <> '' then\n Delete(Result, 1, 1);\nend;\n\n...\n ...\nvar\n path : String;\nbegin\n path:=GetNodePath(yourTreeView.Selected);\n ShowMessage(path);\n...\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
171,569
<p>Actually I will want to use that JeOS for our webserver. Is it a good choice?</p>
[ { "answer_id": 171722, "author": "John Thomas", "author_id": 22599, "author_profile": "https://Stackoverflow.com/users/22599", "pm_score": 3, "selected": false, "text": "procedure TForm8.btn1Click(Sender: TObject); \nvar \n crt: TTreeNode;\n\nbegin\n with tv1 do //this is our tree\n begin\n if Selected=nil then\n crt:=Items[0] //the first one\n else\n crt:=Selected.GetNext; //for previous you'll have 'GetPrev' \n\n if crt<>nil then //can be 'nil' if we reached to the end\n Selected:=crt;\n end;\nend;\n" }, { "answer_id": 2968900, "author": "Remus Rigo", "author_id": 184401, "author_profile": "https://Stackoverflow.com/users/184401", "pm_score": 0, "selected": false, "text": "type TfrmMain = class(TForm)\n...\n public\n DLLHandle : THandle;\n function GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\n\n...\n\nfunction TfrmMain.GetNodePath(node: TTreeNode; delimiter: string = '\\') : String;\nbegin\n Result:='';\n while Assigned(node) do\n begin\n Result:=delimiter+node.Text+Result;\n node:=node.Parent;\n end;\n if Result <> '' then\n Delete(Result, 1, 1);\nend;\n\n...\n ...\nvar\n path : String;\nbegin\n path:=GetNodePath(yourTreeView.Selected);\n ShowMessage(path);\n...\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
171,588
<p>If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?</p>
[ { "answer_id": 171737, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 8, "selected": true, "text": "resetvars.vbs Set oShell = WScript.CreateObject(\"WScript.Shell\")\nfilename = oShell.ExpandEnvironmentStrings(\"%TEMP%\\resetvars.bat\")\nSet objFileSystem = CreateObject(\"Scripting.fileSystemObject\")\nSet oFile = objFileSystem.CreateTextFile(filename, TRUE)\n\nset oEnv=oShell.Environment(\"System\")\nfor each sitem in oEnv \n oFile.WriteLine(\"SET \" & sitem)\nnext\npath = oEnv(\"PATH\")\n\nset oEnv=oShell.Environment(\"User\")\nfor each sitem in oEnv \n oFile.WriteLine(\"SET \" & sitem)\nnext\n\npath = path & \";\" & oEnv(\"PATH\")\noFile.WriteLine(\"SET PATH=\" & path)\noFile.Close\n @echo off\n%~dp0resetvars.vbs\ncall \"%TEMP%\\resetvars.bat\"\n resetvars.bat exportvars.vbs Set oShell = WScript.CreateObject(\"WScript.Shell\")\nfilename = oShell.ExpandEnvironmentStrings(\"%TEMP%\\resetvars.bat\")\nSet objFileSystem = CreateObject(\"Scripting.fileSystemObject\")\nSet oFile = objFileSystem.CreateTextFile(filename, TRUE)\n\nset oEnv=oShell.Environment(\"Process\")\nfor each sitem in oEnv \n oFile.WriteLine(\"SET \" & sitem)\nnext\noFile.Close\n exportvars.vbs \"%TEMP%\\resetvars.bat\"\n" }, { "answer_id": 2479615, "author": "Brian Weed", "author_id": 297617, "author_profile": "https://Stackoverflow.com/users/297617", "pm_score": 4, "selected": false, "text": "VOID Win32ForceSettingsChange()\n{\n DWORD dwReturnValue;\n ::SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) \"Environment\", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);\n}\n" }, { "answer_id": 5111086, "author": "Algonaut", "author_id": 472554, "author_profile": "https://Stackoverflow.com/users/472554", "pm_score": 3, "selected": false, "text": "REGEDIT /E &lt;filename&gt; \"HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment\" REGEDIT /E &lt;filename&gt; \"HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment\" type <filename> | findstr -c:\\\"Path\\\"" }, { "answer_id": 9016150, "author": "kristofer månsson", "author_id": 1170948, "author_profile": "https://Stackoverflow.com/users/1170948", "pm_score": 5, "selected": false, "text": "SET PATH=%PATH%;C:\\CmdShortcuts" }, { "answer_id": 11147132, "author": "Christopher Holmes", "author_id": 1473406, "author_profile": "https://Stackoverflow.com/users/1473406", "pm_score": 4, "selected": false, "text": "@ECHO OFF\nsetlocal ENABLEEXTENSIONS\nset keyname=HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\nset value=%1\nSET ERRKEY=0\n\nREG QUERY \"%KEYNAME%\" /v \"%VALUE%\" 2>NUL| FIND /I \"%VALUE%\"\nIF %ERRORLEVEL% EQU 0 (\nECHO The Registry Key Exists \n) ELSE (\nSET ERRKEY=1\nEcho The Registry Key Does not Exist\n)\n\nEcho %ERRKEY%\nIF %ERRKEY% EQU 1 GOTO :ERROR\n\nFOR /F \"tokens=1-7\" %%A IN ('REG QUERY \"%KEYNAME%\" /v \"%VALUE%\" 2^>NUL^| FIND /I \"%VALUE%\"') DO (\nECHO %%A\nECHO %%B\nECHO %%C\nECHO %%D\nECHO %%E\nECHO %%F\nECHO %%G\nSET ValueName=%%A\nSET ValueType=%%B\nSET C1=%%C\nSET C2=%%D\nSET C3=%%E\nSET C4=%%F\nSET C5=%%G\n)\n\nSET VALUE1=%C1% %C2% %C3% %C4% %C5%\necho The Value of %VALUE% is %C1% %C2% %C3% %C4% %C5%\ncd /d \"%VALUE1%\"\npause\nREM **RUN Extra Commands here**\nGOTO :EOF\n\n:ERROR\nEcho The the Enviroment Variable does not exist.\npause\nGOTO :EOF\n @ECHO OFF\nSETLOCAL ENABLEEXTENSIONS\nset org=%PATH%\nfor /f \"tokens=2*\" %%A in ('REG QUERY \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v Path ^|FIND /I \"Path\"') DO (\nSET path=%%B\n)\nSET PATH=%org%;%PATH%\nset path\n" }, { "answer_id": 11955920, "author": "Jens A. Koch", "author_id": 1163786, "author_profile": "https://Stackoverflow.com/users/1163786", "pm_score": 5, "selected": false, "text": "setx" }, { "answer_id": 14289383, "author": "wardies", "author_id": 1970593, "author_profile": "https://Stackoverflow.com/users/1970593", "pm_score": 0, "selected": false, "text": "SETLOCAL ENDLOCAL SETLOCAL ENDLOCAL ENDLOCAL & (\n SET RESULT1=%RESULT1%\n SET RESULT2=%RESULT2%\n)\n" }, { "answer_id": 18257168, "author": "josh poley", "author_id": 858968, "author_profile": "https://Stackoverflow.com/users/858968", "pm_score": 3, "selected": false, "text": "typedef DWORD (__stdcall *NtQueryInformationProcessPtr)(HANDLE, DWORD, PVOID, ULONG, PULONG);\n\nint __cdecl main(int argc, char* argv[])\n{\n HMODULE hNtDll = GetModuleHandleA(\"ntdll.dll\");\n NtQueryInformationProcessPtr NtQueryInformationProcess = (NtQueryInformationProcessPtr)GetProcAddress(hNtDll, \"NtQueryInformationProcess\");\n\n int processId = atoi(argv[1]);\n printf(\"Target PID: %u\\n\", processId);\n\n // open the process with read+write access\n HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, 0, processId);\n if(hProcess == NULL)\n {\n printf(\"Error opening process (%u)\\n\", GetLastError());\n return 0;\n }\n\n // find the location of the PEB\n PROCESS_BASIC_INFORMATION pbi = {0};\n NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);\n if(status != 0)\n {\n printf(\"Error ProcessBasicInformation (0x%8X)\\n\", status);\n }\n printf(\"PEB: %p\\n\", pbi.PebBaseAddress);\n\n // find the process parameters\n char *processParamsOffset = (char*)pbi.PebBaseAddress + 0x20; // hard coded offset for x64 apps\n char *processParameters = NULL;\n if(ReadProcessMemory(hProcess, processParamsOffset, &processParameters, sizeof(processParameters), NULL))\n {\n printf(\"UserProcessParameters: %p\\n\", processParameters);\n }\n else\n {\n printf(\"Error ReadProcessMemory (%u)\\n\", GetLastError());\n }\n\n // find the address to the environment table\n char *environmentOffset = processParameters + 0x80; // hard coded offset for x64 apps\n char *environment = NULL;\n ReadProcessMemory(hProcess, environmentOffset, &environment, sizeof(environment), NULL);\n printf(\"environment: %p\\n\", environment);\n\n // copy the environment table into our own memory for scanning\n wchar_t *localEnvBlock = new wchar_t[64*1024];\n ReadProcessMemory(hProcess, environment, localEnvBlock, sizeof(wchar_t)*64*1024, NULL);\n\n // find the variable to edit\n wchar_t *found = NULL;\n wchar_t *varOffset = localEnvBlock;\n while(varOffset < localEnvBlock + 64*1024)\n {\n if(varOffset[0] == '\\0')\n {\n // we reached the end\n break;\n }\n if(wcsncmp(varOffset, L\"ENVTEST=\", 8) == 0)\n {\n found = varOffset;\n break;\n }\n varOffset += wcslen(varOffset)+1;\n }\n\n // check to see if we found one\n if(found)\n {\n size_t offset = (found - localEnvBlock) * sizeof(wchar_t);\n printf(\"Offset: %Iu\\n\", offset);\n\n // write a new version (if the size of the value changes then we have to rewrite the entire block)\n if(!WriteProcessMemory(hProcess, environment + offset, L\"ENVTEST=def\", 12*sizeof(wchar_t), NULL))\n {\n printf(\"Error WriteProcessMemory (%u)\\n\", GetLastError());\n }\n }\n\n // cleanup\n delete[] localEnvBlock;\n CloseHandle(hProcess);\n\n return 0;\n}\n >set ENVTEST=abc\n\n>cppTest.exe 13796\nTarget PID: 13796\nPEB: 000007FFFFFD3000\nUserProcessParameters: 00000000004B2F30\nenvironment: 000000000052E700\nOffset: 1528\n\n>set ENVTEST\nENVTEST=def\n dt _PEB dt _RTL_USER_PROCESS_PARAMETERS" }, { "answer_id": 22027353, "author": "wharding28", "author_id": 2132305, "author_profile": "https://Stackoverflow.com/users/2132305", "pm_score": 6, "selected": false, "text": "explorer.exe" }, { "answer_id": 23777960, "author": "Sebastian", "author_id": 3032994, "author_profile": "https://Stackoverflow.com/users/3032994", "pm_score": 2, "selected": false, "text": "if not defined MY_ENV_VAR (\n setx MY_ENV_VAR \"VALUE\" > nul\n set MY_ENV_VAR=VALUE\n)\necho %MY_ENV_VAR%\n" }, { "answer_id": 29891036, "author": "Jens Hykkelbjerg", "author_id": 2298901, "author_profile": "https://Stackoverflow.com/users/2298901", "pm_score": 0, "selected": false, "text": "setx /M ENVVAR \"NEWVALUE\"\nset ENVVAR=\"NEWVALUE\"\n\ntaskkill /f /IM explorer.exe\nstart explorer.exe >nul\nexit\n" }, { "answer_id": 32420542, "author": "anonymous coward", "author_id": 5305271, "author_profile": "https://Stackoverflow.com/users/5305271", "pm_score": 7, "selected": false, "text": "@echo off\n::\n:: RefreshEnv.cmd\n::\n:: Batch file to read environment variables from registry and\n:: set session variables to these values.\n::\n:: With this batch file, there should be no need to reload command\n:: environment every time you want environment changes to propagate\n\n::echo \"RefreshEnv.cmd only works from cmd.exe, please install the Chocolatey Profile to take advantage of refreshenv from PowerShell\"\necho | set /p dummy=\"Refreshing environment variables from registry for cmd.exe. Please wait...\"\n\ngoto main\n\n:: Set one environment variable from registry key\n:SetFromReg\n \"%WinDir%\\System32\\Reg\" QUERY \"%~1\" /v \"%~2\" > \"%TEMP%\\_envset.tmp\" 2>NUL\n for /f \"usebackq skip=2 tokens=2,*\" %%A IN (\"%TEMP%\\_envset.tmp\") do (\n echo/set \"%~3=%%B\"\n )\n goto :EOF\n\n:: Get a list of environment variables from registry\n:GetRegEnv\n \"%WinDir%\\System32\\Reg\" QUERY \"%~1\" > \"%TEMP%\\_envget.tmp\"\n for /f \"usebackq skip=2\" %%A IN (\"%TEMP%\\_envget.tmp\") do (\n if /I not \"%%~A\"==\"Path\" (\n call :SetFromReg \"%~1\" \"%%~A\" \"%%~A\"\n )\n )\n goto :EOF\n\n:main\n echo/@echo off >\"%TEMP%\\_env.cmd\"\n\n :: Slowly generating final file\n call :GetRegEnv \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" >> \"%TEMP%\\_env.cmd\"\n call :GetRegEnv \"HKCU\\Environment\">>\"%TEMP%\\_env.cmd\" >> \"%TEMP%\\_env.cmd\"\n\n :: Special handling for PATH - mix both User and System\n call :SetFromReg \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" Path Path_HKLM >> \"%TEMP%\\_env.cmd\"\n call :SetFromReg \"HKCU\\Environment\" Path Path_HKCU >> \"%TEMP%\\_env.cmd\"\n\n :: Caution: do not insert space-chars before >> redirection sign\n echo/set \"Path=%%Path_HKLM%%;%%Path_HKCU%%\" >> \"%TEMP%\\_env.cmd\"\n\n :: Cleanup\n del /f /q \"%TEMP%\\_envset.tmp\" 2>nul\n del /f /q \"%TEMP%\\_envget.tmp\" 2>nul\n\n :: capture user / architecture\n SET \"OriginalUserName=%USERNAME%\"\n SET \"OriginalArchitecture=%PROCESSOR_ARCHITECTURE%\"\n\n :: Set these variables\n call \"%TEMP%\\_env.cmd\"\n\n :: Cleanup\n del /f /q \"%TEMP%\\_env.cmd\" 2>nul\n\n :: reset user / architecture\n SET \"USERNAME=%OriginalUserName%\"\n SET \"PROCESSOR_ARCHITECTURE=%OriginalArchitecture%\"\n\n echo | set /p dummy=\"Finished.\"\n echo .\n" }, { "answer_id": 37357801, "author": "DieterDP", "author_id": 1436932, "author_profile": "https://Stackoverflow.com/users/1436932", "pm_score": 2, "selected": false, "text": "refreshEnv.bat PATH refreshEnv @ECHO OFF\nREM Source found on https://github.com/DieterDePaepe/windows-scripts\nREM Please share any improvements made!\n\nREM Code inspired by http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w\n\nIF [%1]==[/?] GOTO :help\nIF [%1]==[/help] GOTO :help\nIF [%1]==[--help] GOTO :help\nIF [%1]==[] GOTO :main\n\nECHO Unknown command: %1\nEXIT /b 1 \n\n:help\nECHO Refresh the environment variables in the console.\nECHO.\nECHO refreshEnv Refresh all environment variables.\nECHO refreshEnv /? Display this help.\nGOTO :EOF\n\n:main\nREM Because the environment variables may refer to other variables, we need a 2-step approach.\nREM One option is to use delayed variable evaluation, but this forces use of SETLOCAL and\nREM may pose problems for files with an '!' in the name.\nREM The option used here is to create a temporary batch file that will define all the variables.\n\nREM Check to make sure we don't overwrite an actual file.\nIF EXIST %TEMP%\\__refreshEnvironment.bat (\n ECHO Environment refresh failed!\n ECHO.\n ECHO This script uses a temporary file \"%TEMP%\\__refreshEnvironment.bat\", which already exists. The script was aborted in order to prevent accidental data loss. Delete this file to enable this script.\n EXIT /b 1\n)\n\nREM Read the system environment variables from the registry.\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\"`) DO (\n REM /I -> ignore casing, since PATH may also be called Path\n IF /I NOT [%%I]==[PATH] (\n ECHO SET %%I=%%K>>%TEMP%\\__refreshEnvironment.bat\n )\n)\n\nREM Read the user environment variables from the registry.\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY HKCU\\Environment`) DO (\n REM /I -> ignore casing, since PATH may also be called Path\n IF /I NOT [%%I]==[PATH] (\n ECHO SET %%I=%%K>>%TEMP%\\__refreshEnvironment.bat\n )\n)\n\nREM PATH is a special variable: it is automatically merged based on the values in the\nREM system and user variables.\nREM Read the PATH variable from the system and user environment variables.\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v PATH`) DO (\n ECHO SET PATH=%%K>>%TEMP%\\__refreshEnvironment.bat\n)\nFOR /F \"usebackq tokens=1,2,* skip=2\" %%I IN (`REG QUERY HKCU\\Environment /v PATH`) DO (\n ECHO SET PATH=%%PATH%%;%%K>>%TEMP%\\__refreshEnvironment.bat\n)\n\nREM Load the variable definitions from our temporary file.\nCALL %TEMP%\\__refreshEnvironment.bat\n\nREM Clean up after ourselves.\nDEL /Q %TEMP%\\__refreshEnvironment.bat\n\nECHO Environment successfully refreshed.\n" }, { "answer_id": 38087205, "author": "Richard Woodruff", "author_id": 6525677, "author_profile": "https://Stackoverflow.com/users/6525677", "pm_score": 3, "selected": false, "text": "PATH=(VARIABLE);%path%\n PATH\n" }, { "answer_id": 41612026, "author": "noname", "author_id": 1365722, "author_profile": "https://Stackoverflow.com/users/1365722", "pm_score": 1, "selected": false, "text": "#REQUIRES -Version 3.0\n\nif (-not (\"win32.nativemethods\" -as [type])) {\n # import sendmessagetimeout from win32\n add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @\"\n[DllImport(\"user32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\npublic static extern IntPtr SendMessageTimeout(\n IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,\n uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);\n\"@\n}\n\n$HWND_BROADCAST = [intptr]0xffff;\n$WM_SETTINGCHANGE = 0x1a;\n$result = [uintptr]::zero\n\nfunction global:ADD-PATH\n{\n [Cmdletbinding()]\n param ( \n [parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)] \n [string] $Folder\n )\n\n # See if a folder variable has been supplied.\n if (!$Folder -or $Folder -eq \"\" -or $Folder -eq $null) { \n throw 'No Folder Supplied. $ENV:PATH Unchanged'\n }\n\n # Get the current search path from the environment keys in the registry.\n $oldPath=$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH).Path\n\n # See if the new Folder is already in the path.\n if ($oldPath | Select-String -SimpleMatch $Folder){ \n return 'Folder already within $ENV:PATH' \n }\n\n # Set the New Path and add the ; in front\n $newPath=$oldPath+';'+$Folder\n Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH -Value $newPath -ErrorAction Stop\n\n # Show our results back to the world\n return 'This is the new PATH content: '+$newPath\n\n # notify all windows of environment block change\n [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, \"Environment\", 2, 5000, [ref]$result)\n}\n\nfunction global:REMOVE-PATH {\n [Cmdletbinding()]\n param ( \n [parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)]\n [String] $Folder\n )\n\n # See if a folder variable has been supplied.\n if (!$Folder -or $Folder -eq \"\" -or $Folder -eq $NULL) { \n throw 'No Folder Supplied. $ENV:PATH Unchanged'\n }\n\n # add a leading \";\" if missing\n if ($Folder[0] -ne \";\") {\n $Folder = \";\" + $Folder;\n }\n\n # Get the Current Search Path from the environment keys in the registry\n $newPath=$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH).Path\n\n # Find the value to remove, replace it with $NULL. If it's not found, nothing will change and you get a message.\n if ($newPath -match [regex]::Escape($Folder)) { \n $newPath=$newPath -replace [regex]::Escape($Folder),$NULL \n } else { \n return \"The folder you mentioned does not exist in the PATH environment\" \n }\n\n # Update the Environment Path\n Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH -Value $newPath -ErrorAction Stop\n\n # Show what we just did\n return 'This is the new PATH content: '+$newPath\n\n # notify all windows of environment block change\n [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, \"Environment\", 2, 5000, [ref]$result)\n}\n\n\n# Use ADD-PATH or REMOVE-PATH accordingly.\n\n#Anything to Add?\n\n#Anything to Remove?\n\nREMOVE-PATH \"%_installpath_bin%\"\n" }, { "answer_id": 42116634, "author": "Vince", "author_id": 6574586, "author_profile": "https://Stackoverflow.com/users/6574586", "pm_score": 4, "selected": false, "text": "taskkill /f /im explorer.exe && explorer.exe\n" }, { "answer_id": 44669930, "author": "Jeroen van Dijk-Jun", "author_id": 4336408, "author_profile": "https://Stackoverflow.com/users/4336408", "pm_score": 2, "selected": false, "text": "@echo off\nset JAVA_HOME=%JAVA_HOME_8%\nsetx JAVA_HOME \"%JAVA_HOME_8%\"\n" }, { "answer_id": 44807922, "author": "jolly", "author_id": 2583495, "author_profile": "https://Stackoverflow.com/users/2583495", "pm_score": 8, "selected": false, "text": "RefreshEnv.cmd" }, { "answer_id": 56562186, "author": "Andy McRae", "author_id": 2299775, "author_profile": "https://Stackoverflow.com/users/2299775", "pm_score": 2, "selected": false, "text": "> powershell.exe -executionpolicy unrestricted -File C:\\path_here\\refresh.ps1 function Update-Environment {\n $locations = 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',\n 'HKCU:\\Environment'\n $locations | ForEach-Object {\n $k = Get-Item $_\n $k.GetValueNames() | ForEach-Object {\n $name = $_\n $value = $k.GetValue($_)\n\n if ($userLocation -and $name -ieq 'PATH') {\n $env:Path += \";$value\"\n } else {\n\n Set-Item -Path Env:\\$name -Value $value\n }\n }\n $userLocation = $true\n }\n}\nUpdate-Environment\n#Here we can use newly added environment variables like for example npm install.. \nnpm install -g create-react-app serve\n" }, { "answer_id": 59065248, "author": "Charles Grunwald", "author_id": 1017636, "author_profile": "https://Stackoverflow.com/users/1017636", "pm_score": 2, "selected": false, "text": "@echo off\nrem Refresh PATH from registry.\nsetlocal\nset USR_PATH=\nset SYS_PATH=\nfor /F \"tokens=3* skip=2\" %%P in ('%SystemRoot%\\system32\\reg.exe query \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v PATH') do @set \"SYS_PATH=%%P %%Q\"\nfor /F \"tokens=3* skip=2\" %%P in ('%SystemRoot%\\system32\\reg.exe query \"HKCU\\Environment\" /v PATH') do @set \"USR_PATH=%%P %%Q\"\nif \"%SYS_PATH:~-1%\"==\" \" set \"SYS_PATH=%SYS_PATH:~0,-1%\"\nif \"%USR_PATH:~-1%\"==\" \" set \"USR_PATH=%USR_PATH:~0,-1%\"\nendlocal & call set \"PATH=%SYS_PATH%;%USR_PATH%\"\ngoto :EOF\n" }, { "answer_id": 69408975, "author": "Badr Elmers", "author_id": 3020379, "author_profile": "https://Stackoverflow.com/users/3020379", "pm_score": 3, "selected": false, "text": "test & echo baaaaaaaaaad refreshenv baaaaaaaaaad ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \\ / \" : ? * = . - _ & echo baaaad\n call refrenv.bat <!-- : Begin batch script\n@echo off\nREM PUSHD \"%~dp0\"\n\n\nREM author: Badr Elmers 2021\nREM description: refrenv = refresh environment. this is a better alternative to the chocolatey refreshenv for cmd\nREM https://github.com/badrelmers/RefrEnv\nREM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w\n\nREM ___USAGE_____________________________________________________________\nREM usage: \nREM call refrenv.bat full refresh. refresh all non critical variables*, and refresh the PATH\n\nREM debug:\nREM to debug what this script do create this variable in your parent script like that\nREM set debugme=yes\nREM then the folder containing the files used to set the variables will be open. Then see\nREM _NewEnv.cmd this is the file which run inside your script to setup the new variables, you\nREM can also revise the intermediate files _NewEnv.cmd_temp_.cmd and _NewEnv.cmd_temp2_.cmd \nREM (those two contains all the variables before removing the duplicates and the unwanted variables)\n\n\nREM you can also put this script in windows\\systems32 or another place in your %PATH% then call it from an interactive console by writing refrenv\n\nREM *critical variables: are variables which belong to cmd/windows and should not be refreshed normally like:\nREM - windows vars:\nREM ALLUSERSPROFILE APPDATA CommonProgramFiles CommonProgramFiles(x86) CommonProgramW6432 COMPUTERNAME ComSpec HOMEDRIVE HOMEPATH LOCALAPPDATA LOGONSERVER NUMBER_OF_PROCESSORS OS PATHEXT PROCESSOR_ARCHITECTURE PROCESSOR_ARCHITEW6432 PROCESSOR_IDENTIFIER PROCESSOR_LEVEL PROCESSOR_REVISION ProgramData ProgramFiles ProgramFiles(x86) ProgramW6432 PUBLIC SystemDrive SystemRoot TEMP TMP USERDOMAIN USERDOMAIN_ROAMINGPROFILE USERNAME USERPROFILE windir SESSIONNAME\n\n\nREM ___INFO_____________________________________________________________\nREM :: this script reload environment variables inside cmd every time you want environment changes to propagate, so you do not need to restart cmd after setting a new variable with setx or when installing new apps which add new variables ...etc\n\n\nREM This is a better alternative to the chocolatey refreshenv for cmd, which solves a lot of problems like:\n\nREM The Chocolatey refreshenv is so bad if the variable have some cmd meta-characters, see this test:\n REM add this to the path in HKCU\\Environment: test & echo baaaaaaaaaad, and run the chocolatey refreshenv you will see that it prints baaaaaaaaaad which is very bad, and the new path is not added to your path variable.\n REM This script solve this and you can test it with any meta-character, even something so bad like:\n REM ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \\ / \" : ? * = . - _ & echo baaaad\n \nREM refreshenv adds only system and user environment variables, but CMD adds volatile variables too (HKCU\\Volatile Environment). This script will merge all the three and remove any duplicates.\n\nREM refreshenv reset your PATH. This script append the new path to the old path of the parent script which called this script. It is better than overwriting the old path, otherwise it will delete any newly added path by the parent script.\n\nREM This script solve this problem described in a comment by @Gene Mayevsky: refreshenv modifies env variables TEMP and TMP replacing them with values stored in HKCU\\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\\AppData\\Local\\Temp instead of C:\\Windows\\Temp. This breaks build because linker cannot open system profile's Temp folder.\n\nREM ________\nREM this script solve things like that too:\nREM The confusing thing might be that there are a few places to start the cmd from. In my case I run cmd from windows explorer and the environment variables did not change while when starting cmd from the \"run\" (windows key + r) the environment variables were changed.\n\nREM In my case I just had to kill the windows explorer process from the task manager and then restart it again from the task manager.\nREM Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.\n\nREM my conclusion:\nREM if I add a new variable with setx, i can access it in cmd only if i run cmd as admin, without admin right i have to restart explorer to see that new variable. but running this script inside my script (who sets the variable with setx) solve this problem and i do not have to restart explorer\n\n\nREM ________\nREM windows recreate the path using three places at less:\nREM the User namespace: HKCU\\Environment\nREM the System namespace: HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\nREM the Session namespace: HKCU\\Volatile Environment\nREM but the original chocolatey script did not add the volatile path. This script will merge all the three and remove any duplicates. this is what windows do by default too\n\nREM there is this too which cmd seems to read when first running, but it contains only TEMP and TMP,so i will not use it\nREM HKEY_USERS\\.DEFAULT\\Environment\n\n\nREM ___TESTING_____________________________________________________________\nREM to test this script with extreme cases do\n REM :: Set a bad variable\n REM add a var in reg HKCU\\Environment as the following, and see that echo is not executed. if you use refreshenv of chocolatey you will see that echo is executed which is so bad!\n REM so save this in reg:\n REM all 32 characters: & % ' ( ) ~ + @ # $ { } [ ] ; , ` ! ^ | > < \\ / \" : ? * = . - _ & echo baaaad\n REM and this:\n REM (^.*)(Form Product=\")([^\"]*\") FormType=\"[^\"]*\" FormID=\"([0-9][0-9]*)\".*$\n REM and use set to print those variables and see if they are saved without change ; refreshenv fail dramatically with those variables\n \n \nREM invalid characters (illegal characters in file names) in Windows using NTFS\nREM \\ / : * ? \" < > | and ^ in FAT \n\n\n\nREM __________________________________________________________________________________________\nREM __________________________________________________________________________________________\nREM __________________________________________________________________________________________\nREM this is a hybrid script which call vbs from cmd directly\nREM :: The only restriction is the batch code cannot contain - - > (without space between - - > of course)\nREM :: The only restriction is the VBS code cannot contain </script>.\nREM :: The only risk is the undocumented use of \"%~f0?.wsf\" as the script to load. Somehow the parser properly finds and loads the running .BAT script \"%~f0\", and the ?.wsf suffix mysteriously instructs CSCRIPT to interpret the script as WSF. Hopefully MicroSoft will never disable that \"feature\".\nREM :: https://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a\n\nif \"%debugme%\"==\"yes\" (\n echo RefrEnv - Refresh the Environment for CMD - ^(Debug enabled^)\n) else (\n echo RefrEnv - Refresh the Environment for CMD\n)\n\nset \"TEMPDir=%TEMP%\\refrenv\"\nIF NOT EXIST \"%TEMPDir%\" mkdir \"%TEMPDir%\"\nset \"outputfile=%TEMPDir%\\_NewEnv.cmd\"\n\n\nREM detect if DelayedExpansion is enabled\nREM It relies on the fact, that the last caret will be removed only in delayed mode.\nREM https://www.dostips.com/forum/viewtopic.php?t=6496\nset \"DelayedExpansionState=IsDisabled\"\nIF \"^!\" == \"^!^\" (\n REM echo DelayedExpansion is enabled\n set \"DelayedExpansionState=IsEnabled\"\n)\n\n\nREM :: generate %outputfile% which contain all the new variables\nREM cscript //nologo \"%~f0?.wsf\" %1\ncscript //nologo \"%~f0?.wsf\" \"%outputfile%\" %DelayedExpansionState%\n\n\nREM ::set the new variables generated with vbscript script above\nREM for this to work always it is necessary to use DisableDelayedExpansion or escape ! and ^ when using EnableDelayedExpansion, but this script already solve this, so no worry about that now, thanks to God\nREM test it with some bad var like:\nREM all 32 characters: ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \\ / \" : ? * = . - _ & echo baaaad\nREM For /f delims^=^ eol^= %%a in (%outputfile%) do %%a\nREM for /f \"delims== tokens=1,2\" %%G in (%outputfile%) do set \"%%G=%%H\"\nFor /f delims^=^ eol^= %%a in (%outputfile%) do set %%a\n\n\nREM for safely print a variable with bad charachters do:\nREM SETLOCAL EnableDelayedExpansion\nREM echo \"!z9!\"\nREM or\nREM set z9\nREM but generally paths and environment variables should not have bad metacharacters, but it is not a rule!\n\n\nif \"%debugme%\"==\"yes\" (\n explorer \"%TEMPDir%\"\n) else (\n rmdir /Q /S \"%TEMPDir%\"\n)\n\nREM cleanup\nset \"TEMPDir=\"\nset \"outputfile=\"\nset \"DelayedExpansionState=\"\nset \"debugme=\"\n\n\nREM pause\nexit /b\n\n\n\nREM #############################################################################\nREM :: to run jscript you have to put <script language=\"JScript\"> directly after ----- Begin wsf script --->\n----- Begin wsf script --->\n<job><script language=\"VBScript\">\nREM #############################################################################\nREM ### put you code here #######################################################\nREM #############################################################################\n\nREM based on itsadok script from here\nREM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w\n\nREM and it is faster as stated by this comment\nREM While I prefer the Chocolatey code-wise for being pure batch code, overall I decided to use this one, since it's faster. (~0.3 seconds instead of ~1 second -- which is nice, since I use it frequently in my Explorer \"start cmd here\" entry) – \n\nREM and it is safer based on my tests, the Chocolatey refreshenv is so bad if the variable have some cmd metacharacters\n\n\nConst ForReading = 1 \nConst ForWriting = 2\nConst ForAppending = 8 \n\nSet WshShell = WScript.CreateObject(\"WScript.Shell\")\nfilename=WScript.Arguments.Item(0)\nDelayedExpansionState=WScript.Arguments.Item(1)\n\nTMPfilename=filename & \"_temp_.cmd\"\nSet fso = CreateObject(\"Scripting.fileSystemObject\")\nSet tmpF = fso.CreateTextFile(TMPfilename, TRUE)\n\n\nset oEnvS=WshShell.Environment(\"System\")\nfor each sitem in oEnvS\n tmpF.WriteLine(sitem)\nnext\nSystemPath = oEnvS(\"PATH\")\n\nset oEnvU=WshShell.Environment(\"User\")\nfor each sitem in oEnvU\n tmpF.WriteLine(sitem)\nnext\nUserPath = oEnvU(\"PATH\")\n\nset oEnvV=WshShell.Environment(\"Volatile\")\nfor each sitem in oEnvV\n tmpF.WriteLine(sitem)\nnext\nVolatilePath = oEnvV(\"PATH\")\n\nset oEnvP=WshShell.Environment(\"Process\")\nREM i will not save the process env but only its path, because it have strange variables like =::=::\\ and =F:=.... which seems to be added by vbscript\nREM for each sitem in oEnvP\n REM tmpF.WriteLine(sitem)\nREM next\nREM here we add the actual session path, so we do not reset the original path, because maybe the parent script added some folders to the path, If we need to reset the path then comment the following line\nProcessPath = oEnvP(\"PATH\")\n\nREM merge System, User, Volatile, and process PATHs\nNewPath = SystemPath & \";\" & UserPath & \";\" & VolatilePath & \";\" & ProcessPath\n\n\nREM ________________________________________________________________\nREM :: remove duplicates from path\nREM :: expand variables so they become like windows do when he read reg and create path, then Remove duplicates without sorting \n REM why i will clean the path from duplicates? because:\n REM the maximum string length in cmd is 8191 characters. But string length doesnt mean that you can save 8191 characters in a variable because also the assignment belongs to the string. you can save 8189 characters because the remaining 2 characters are needed for \"a=\"\n \n REM based on my tests: \n REM when i open cmd as user , windows does not remove any duplicates from the path, and merge system+user+volatil path\n REM when i open cmd as admin, windows do: system+user path (here windows do not remove duplicates which is stupid!) , then it adds volatil path after removing from it any duplicates \n\nREM ' https://www.rosettacode.org/wiki/Remove_duplicate_elements#VBScript\nFunction remove_duplicates(list)\n arr = Split(list,\";\")\n Set dict = CreateObject(\"Scripting.Dictionary\")\n REM ' force dictionary compare to be case-insensitive , uncomment to force case-sensitive\n dict.CompareMode = 1\n\n For i = 0 To UBound(arr)\n If dict.Exists(arr(i)) = False Then\n dict.Add arr(i),\"\"\n End If\n Next\n For Each key In dict.Keys\n tmp = tmp & key & \";\"\n Next\n remove_duplicates = Left(tmp,Len(tmp)-1)\nEnd Function\n \nREM expand variables\nNewPath = WshShell.ExpandEnvironmentStrings(NewPath)\nREM remove duplicates\nNewPath=remove_duplicates(NewPath)\n\nREM remove_duplicates() will add a ; to the end so lets remove it if the last letter is ;\nIf Right(NewPath, 1) = \";\" Then \n NewPath = Left(NewPath, Len(NewPath) - 1) \nEnd If\n \ntmpF.WriteLine(\"PATH=\" & NewPath)\ntmpF.Close\n\nREM ________________________________________________________________\nREM :: exclude setting variables which may be dangerous to change\n\n REM when i run a script from task scheduler using SYSTEM user the following variables are the differences between the scheduler env and a normal cmd script, so i will not override those variables\n REM APPDATA=D:\\Users\\LLED2\\AppData\\Roaming\n REM APPDATA=D:\\Windows\\system32\\config\\systemprofile\\AppData\\Roaming\n\n REM LOCALAPPDATA=D:\\Users\\LLED2\\AppData\\Local\n REM LOCALAPPDATA=D:\\Windows\\system32\\config\\systemprofile\\AppData\\Local\n\n REM TEMP=D:\\Users\\LLED2\\AppData\\Local\\Temp\n REM TEMP=D:\\Windows\\TEMP\n\n REM TMP=D:\\Users\\LLED2\\AppData\\Local\\Temp\n REM TMP=D:\\Windows\\TEMP\n\n REM USERDOMAIN=LLED2-PC\n REM USERDOMAIN=WORKGROUP\n\n REM USERNAME=LLED2\n REM USERNAME=LLED2-PC$\n\n REM USERPROFILE=D:\\Users\\LLED2\n REM USERPROFILE=D:\\Windows\\system32\\config\\systemprofile\n\n REM i know this thanks to this comment\n REM The solution is good but it modifies env variables TEMP and TMP replacing them with values stored in HKCU\\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\\AppData\\Local\\Temp instead of C:\\Windows\\Temp. This breaks build because linker cannot open system profile's Temp folder. – Gene Mayevsky Sep 26 '19 at 20:51\n\n\nREM Delete Lines of a Text File Beginning with a Specified String\nREM those are the variables which should not be changed by this script \narrBlackList = Array(\"ALLUSERSPROFILE=\", \"APPDATA=\", \"CommonProgramFiles=\", \"CommonProgramFiles(x86)=\", \"CommonProgramW6432=\", \"COMPUTERNAME=\", \"ComSpec=\", \"HOMEDRIVE=\", \"HOMEPATH=\", \"LOCALAPPDATA=\", \"LOGONSERVER=\", \"NUMBER_OF_PROCESSORS=\", \"OS=\", \"PATHEXT=\", \"PROCESSOR_ARCHITECTURE=\", \"PROCESSOR_ARCHITEW6432=\", \"PROCESSOR_IDENTIFIER=\", \"PROCESSOR_LEVEL=\", \"PROCESSOR_REVISION=\", \"ProgramData=\", \"ProgramFiles=\", \"ProgramFiles(x86)=\", \"ProgramW6432=\", \"PUBLIC=\", \"SystemDrive=\", \"SystemRoot=\", \"TEMP=\", \"TMP=\", \"USERDOMAIN=\", \"USERDOMAIN_ROAMINGPROFILE=\", \"USERNAME=\", \"USERPROFILE=\", \"windir=\", \"SESSIONNAME=\")\n\nSet objFS = CreateObject(\"Scripting.FileSystemObject\")\nSet objTS = objFS.OpenTextFile(TMPfilename, ForReading)\nstrContents = objTS.ReadAll\nobjTS.Close\n\nTMPfilename2= filename & \"_temp2_.cmd\"\narrLines = Split(strContents, vbNewLine)\nSet objTS = objFS.OpenTextFile(TMPfilename2, ForWriting, True)\n\nREM this is the equivalent of findstr /V /I /L or grep -i -v , i don t know a better way to do it, but it works fine\nFor Each strLine In arrLines\n bypassThisLine=False\n For Each BlackWord In arrBlackList\n If Left(UCase(LTrim(strLine)),Len(BlackWord)) = UCase(BlackWord) Then\n bypassThisLine=True\n End If\n Next\n If bypassThisLine=False Then\n objTS.WriteLine strLine\n End If\nNext\n\nREM ____________________________________________________________\nREM :: expand variables because registry save some variables as unexpanded %....%\nREM :: and escape ! and ^ for cmd EnableDelayedExpansion mode\n\nset f=fso.OpenTextFile(TMPfilename2,ForReading)\nREM Write file: ForAppending = 8 ForReading = 1 ForWriting = 2 , True=create file if not exist\nset fW=fso.OpenTextFile(filename,ForWriting,True)\nDo Until f.AtEndOfStream\n LineContent = f.ReadLine\n REM expand variables\n LineContent = WshShell.ExpandEnvironmentStrings(LineContent)\n \n REM _____this part is so important_____\n REM if cmd delayedexpansion is enabled in the parent script which calls this script then bad thing happen to variables saved in the registry if they contain ! . if var have ! then ! and ^ are removed; if var do not have ! then ^ is not removed . to understand what happens read this :\n REM how cmd delayed expansion parse things\n REM https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912\n REM For each parsed token, first check if it contains any !. If not, then the token is not parsed - important for ^ characters. If the token does contain !, then scan each character from left to right:\n REM - If it is a caret (^) the next character has no special meaning, the caret itself is removed\n REM - If it is an exclamation mark, search for the next exclamation mark (carets are not observed anymore), expand to the value of the variable.\n REM - Consecutive opening ! are collapsed into a single !\n REM - Any remaining unpaired ! is removed\n REM ...\n REM Look at next string of characters, breaking before !, :, or <LF>, and call them VAR\n\n REM conclusion:\n REM when delayedexpansion is enabled and var have ! then i have to escape ^ and ! ,BUT IF VAR DO NOT HAVE ! THEN DO NOT ESCAPE ^ .this made me crazy to discover\n REM when delayedexpansion is disabled then i do not have to escape anything\n \n If DelayedExpansionState=\"IsEnabled\" Then\n If InStr(LineContent, \"!\") > 0 Then\n LineContent=Replace(LineContent,\"^\",\"^^\")\n LineContent=Replace(LineContent,\"!\",\"^!\")\n End If\n End If\n REM __________\n \n fW.WriteLine(LineContent)\nLoop\n\nf.Close\nfW.Close\n\nREM #############################################################################\nREM ### end of vbscript code ####################################################\nREM #############################################################################\nREM this must be at the end for the hybrid trick, do not remove it\n</script></job>\n\n\n source refrenv.sh . .\\refrenv.ps1" }, { "answer_id": 70504233, "author": "Amey Mahajan", "author_id": 15311773, "author_profile": "https://Stackoverflow.com/users/15311773", "pm_score": 0, "selected": false, "text": "Refreshenv" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
171,596
<p>After having implemented the strategy pattern, I wanted to make an array of the interface-type, to which I can then add any concrete type. </p> <p>For those who don't know the strategy pattern: <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Strategy_pattern</a> In this particular example I would want to make a StrategyInterface array, which I can then fill with concrete type's A, B and C. However, because this is an abstract class, I can't get it done. Is there a way to do this, or is it completely impossible, without removing the abstract method?</p>
[ { "answer_id": 171605, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "typedef std::vector<Interface *> Array;\nArray myArray;\nmyArray.push_back(new A());\n typedef boost::ptr_vector<Interface> Array;\n// the rest is the same\n" }, { "answer_id": 171679, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "#include <list>\n#include <boost/any.hpp>\n\nusing boost::any_cast;\ntypedef std::list<boost::any> many;\n\nvoid append_int(many & values, int value)\n{\n boost::any to_append = value;\n values.push_back(to_append);\n}\n\nvoid append_string(many & values, const std::string & value)\n{\n values.push_back(value);\n}\n\nvoid append_char_ptr(many & values, const char * value)\n{\n values.push_back(value);\n}\n\nvoid append_any(many & values, const boost::any & value)\n{\n values.push_back(value);\n}\n\nvoid append_nothing(many & values)\n{\n values.push_back(boost::any());\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23163/" ]
171,601
<p>WPF WebBrowser control looks great but knowledge accumlated over time about WinForms WebBrowser is substantial and it's hard to ignore work like csExWB. It would be nice to know what functional shortcomings or advantages exists in .NET 3.5's WPF WebBrowser control over WinForms WebBrowser control. In particular, is it possible to build csExWB-like functionality on top of WPF WebBrowser?</p>
[ { "answer_id": 1152092, "author": "Marco Luglio", "author_id": 14263, "author_profile": "https://Stackoverflow.com/users/14263", "pm_score": 3, "selected": false, "text": "IsWebBrowserContextMenuEnabled ActiveXInstance document System.Windows.Forms.HtmlDocument PointToClient GetElementFromPoint Object mshtml.HtmlDocument" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406313/" ]
171,633
<p>When using one's own iPhone for development it's easy enough to access any crash logs via XCode->Organizer->Crash Logs.</p> <p>How does one access crash logs on another person's phone if they don't have it set up for development in XCode, as would likely be the case if you were distributing your app to them via ad hoc distribution for beta testing?</p>
[ { "answer_id": 4504889, "author": "Simon Whitaker", "author_id": 263871, "author_profile": "https://Stackoverflow.com/users/263871", "pm_score": 4, "selected": false, "text": "~/Library/Logs/CrashReporter/MobileDevice/<DEVICE_NAME> C:\\Documents and Settings\\<USERNAME>\\Application Data\\Apple Computer\\Logs\\CrashReporter\\MobileDevice\\<DEVICE_NAME> C:\\Users\\<USERNAME>\\AppData\\Roaming\\Apple Computer\\Logs\\CrashReporter\\MobileDevice\\<DEVICE_NAME> <USERNAME> <DEVICE_NAME> <DEVICE_NAME>" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
171,640
<p>In multi-threaded code, when an instance may be read or written by multiple threads, they need to be locked on to perform these operations safely.</p> <p>To avoid the repetition of creating an object to lock on and writing a bunch of lock statements through code, I've created a generic class to handle the locking. </p> <p>Am I missing anything, conceptually? This should work, right?</p> <pre><code>public class Locked&lt;T&gt; where T : new() { private readonly object locker = new object(); private T value; public Locked() : this(default(T)) { } public Locked(T value) { this.value = value; } public T Get() { lock (this.locker) { return this.value; } } public void Set(T value) { lock (this.locker) { this.value = value; } } } </code></pre> <p>And an example of it being used in a class:</p> <pre><code>private Locked&lt;bool&gt; stopWorkerThread = new Locked&lt;bool&gt;(); public void WorkerThreadEntryPoint() { while (true) { if (this.stopWorkerThread.Get()) { break; } </code></pre> <p>Also, how would I test something like this, in an automated way (e.g. create a unit test)?</p> <p>Lastly, what can I do to implement a ++ and -- operator, to avoid this:</p> <pre><code> this.runningThreads.Set(this.runningThreads.Get() + 1); </code></pre>
[ { "answer_id": 171665, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "this.runningThreads.Set(this.runningThreads.Get() + 1);\n Get() Get Set using (Locked<T> lock = Locked<T>(instance))\n{\n // write value\n instance++;\n}\n\n// read value\nprint instance;\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
171,641
<p>When maintaining a <code>COM</code> interface should an empty <code>BSTR</code> be treated the same way as <code>NULL</code>? In other words should these two function calls produce the same result?</p> <pre><code> // Empty BSTR CComBSTR empty(L""); // Or SysAllocString(L"") someObj-&gt;Foo(empty); // NULL BSTR someObj-&gt;Foo(NULL); </code></pre>
[ { "answer_id": 171644, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 5, "selected": true, "text": "strlen std::string" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
171,662
<p>I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into "normal text" is by using the <strong>string.join</strong> method. However, it only takes 2 arguments so I can only make a single column using "\n". I thought trying to make a loop that would simply add a tab between columns would do it but the logic didn't work correctly.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/" rel="noreferrer">ActiveState page</a> that has a fairly complicated way of doing it but it's from 4 years ago. Is there an easy way to do it nowadays?</p> <hr> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology", "CBE:Combat Engineer", "CHM:Chemistry", "CMP:Computers", "CRM:Combat Rifeman", "CVE:Civil Engineer", "DIS:Disguise", "ELC:Electronics","EQ:Equestrian", "FO:Forward Observer", "FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing", "GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire", "INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow", "LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language", "LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic", "MED:Medical", "MET:Meterology", "MNE:Mining Engineer", "MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead", "PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot", "SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging", "SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver", "WVD:Wheeled Vehicle Driver"] </code></pre> <p>I just want to output this list into a simple, 2 column format to reduce space. Ideally there should be a standard amount of space between the columns but I can work with it.</p> <pre><code>ACM:Aircraft Mechanic BC:Body Combat BIO:Biology CBE:Combat Engineer CHM:Chemistry CMP:Computers CRM:Combat Rifeman CVE:Civil Engineer DIS:Disguise ELC:Electronics EQ:Equestrian FO:Forward Observer FOR:Forage FRG:Forgery FRM:Farming FSH:Fishing GEO:Geology GS:Gunsmith HW:Heavy Weapons IF:Indirect Fire INS:Instruction INT:Interrogation JP:Jet Pilot LB:Longbow LAP:Light Aircraft Pilot LCG:Large Caliber Gun LNG:Language LP:Lockpick MC:Melee Combat MCY:Motorcycle MEC:Mechanic MED:Medical MET:Meterology MNE:Mining Engineer MTL:Metallurgy MTN:Mountaineering NWH:Nuclear Warhead PAR:Parachute PST:Pistol RCN:Recon RWP:Rotary Wing Pilot SBH:Small Boat Handling SCD:Scuba Diving SCR:Scrounging SWM:Swimming TW:Thrown Weapon TVD:Tracked Vehicle Driver WVD:Wheeled Vehicle Driver </code></pre>
[ { "answer_id": 171686, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 0, "selected": false, "text": "data = [ (\"1\",\"2\"),(\"3\",\"4\") ]\nprint \"\\n\".join(map(\"\\t\".join,data))\n" }, { "answer_id": 171707, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "import string\ndef fmtpairs(mylist):\n pairs = zip(mylist[::2],mylist[1::2])\n return '\\n'.join('\\t'.join(i) for i in pairs)\n\nprint fmtpairs(list(string.ascii_uppercase))\n\nA B\nC D\nE F\nG H\nI J\n...\n def fmtcols(mylist, cols):\n lines = (\"\\t\".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))\n return '\\n'.join(lines)\n" }, { "answer_id": 173823, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "def columns( skills_defs, cols=2 ):\n pairs = [ \"\\t\".join(skills_defs[i:i+cols]) for i in range(0,len(skills_defs),cols) ]\n return \"\\n\".join( pairs )\n" }, { "answer_id": 173933, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "format_columns from __future__ import generators\ntry: import itertools\nexcept ImportError: mymap, myzip= map, zip\nelse: mymap, myzip= itertools.imap, itertools.izip\n\ndef format_columns(string_list, columns, separator=\" \"):\n \"Produce equal-width columns from string_list\"\n sublists= []\n\n # empty_str based on item 0 of string_list\n try:\n empty_str= type(string_list[0])()\n except IndexError: # string_list is empty\n return\n\n # create a sublist for every column\n for column in xrange(columns):\n sublists.append(string_list[column::columns])\n\n # find maximum length of a column\n max_sublist_len= max(mymap(len, sublists))\n\n # make all columns same length\n for sublist in sublists:\n if len(sublist) < max_sublist_len:\n sublist.append(empty_str)\n\n # calculate a format string for the output lines\n format_str= separator.join(\n \"%%-%ds\" % max(mymap(len, sublist))\n for sublist in sublists)\n\n for line_items in myzip(*sublists):\n yield format_str % line_items\n\nif __name__ == \"__main__\":\n skills_defs = [\"ACM:Aircraft Mechanic\", \"BC:Body Combat\", \"BIO:Biology\",\n \"CBE:Combat Engineer\", \"CHM:Chemistry\", \"CMP:Computers\",\n \"CRM:Combat Rifeman\", \"CVE:Civil Engineer\", \"DIS:Disguise\",\n \"ELC:Electronics\",\"EQ:Equestrian\", \"FO:Forward Observer\",\n \"FOR:Forage\", \"FRG:Forgery\", \"FRM:Farming\", \"FSH:Fishing\",\n \"GEO:Geology\", \"GS:Gunsmith\", \"HW:Heavy Weapons\", \"IF:Indirect Fire\",\n \"INS:Instruction\", \"INT:Interrogation\", \"JP:Jet Pilot\", \"LB:Longbow\",\n \"LAP:Light Aircraft Pilot\", \"LCG:Large Caliber Gun\", \"LNG:Language\",\n \"LP:Lockpick\", \"MC:Melee Combat\", \"MCY:Motorcycle\", \"MEC:Mechanic\",\n \"MED:Medical\", \"MET:Meterology\", \"MNE:Mining Engineer\",\n \"MTL:Metallurgy\", \"MTN:Mountaineering\", \"NWH:Nuclear Warhead\",\n \"PAR:Parachute\", \"PST:Pistol\", \"RCN:Recon\", \"RWP:Rotary Wing Pilot\",\n \"SBH:Small Boat Handling\",\"SCD:Scuba Diving\", \"SCR:Scrounging\",\n \"SWM:Swimming\", \"TW:Thrown Weapon\", \"TVD:Tracked Vehicle Driver\",\n \"WVD:Wheeled Vehicle Driver\"]\n\n for line in format_columns(skills_defs, 2):\n print line\n" }, { "answer_id": 12721559, "author": "ruwan800", "author_id": 1511978, "author_profile": "https://Stackoverflow.com/users/1511978", "pm_score": 2, "selected": false, "text": "it = iter(skills_defs)\nfor i in it:\n print('{:<60}{}'.format(i, next(it, \"\")))\n" }, { "answer_id": 24876899, "author": "masat", "author_id": 1913361, "author_profile": "https://Stackoverflow.com/users/1913361", "pm_score": 2, "selected": false, "text": "def fmtcols(mylist, cols):\n maxwidth = max(map(lambda x: len(x), mylist))\n justifyList = map(lambda x: x.ljust(maxwidth), mylist)\n lines = (' '.join(justifyList[i:i+cols]) \n for i in xrange(0,len(justifyList),cols))\n print \"\\n\".join(lines)\n ACM:Aircraft Mechanic BC:Body Combat BIO:Biology CBE:Combat Engineer CHM:Chemistry CMP:Computers CRM:Combat Rifeman CVE:Civil Engineer DIS:Disguise ELC:Electronics" }, { "answer_id": 27027373, "author": "sidewinderguy", "author_id": 214974, "author_profile": "https://Stackoverflow.com/users/214974", "pm_score": 0, "selected": false, "text": "import sys\n\nskills_defs = [\"ACM:Aircraft Mechanic\", \"BC:Body Combat\", \"BIO:Biology\",\n\"CBE:Combat Engineer\", \"CHM:Chemistry\", \"CMP:Computers\",\n\"CRM:Combat Rifeman\", \"CVE:Civil Engineer\", \"DIS:Disguise\",\n\"ELC:Electronics\",\"EQ:Equestrian\", \"FO:Forward Observer\",\n\"FOR:Forage\", \"FRG:Forgery\", \"FRM:Farming\", \"FSH:Fishing\",\n\"GEO:Geology\", \"GS:Gunsmith\", \"HW:Heavy Weapons\", \"IF:Indirect Fire\",\n\"INS:Instruction\", \"INT:Interrogation\", \"JP:Jet Pilot\", \"LB:Longbow\",\n\"LAP:Light Aircraft Pilot\", \"LCG:Large Caliber Gun\", \"LNG:Language\",\n\"LP:Lockpick\", \"MC:Melee Combat\", \"MCY:Motorcycle\", \"MEC:Mechanic\",\n\"MED:Medical\", \"MET:Meterology\", \"MNE:Mining Engineer\",\n\"MTL:Metallurgy\", \"MTN:Mountaineering\", \"NWH:Nuclear Warhead\",\n\"PAR:Parachute\", \"PST:Pistol\", \"RCN:Recon\", \"RWP:Rotary Wing Pilot\",\n\"SBH:Small Boat Handling\",\"SCD:Scuba Diving\", \"SCR:Scrounging\",\n\"SWM:Swimming\", \"TW:Thrown Weapon\", \"TVD:Tracked Vehicle Driver\",\n\"WVD:Wheeled Vehicle Driver\"]\n\n# The only thing \"colform\" does is return a modified version of \"txt\" that is\n# ensured to be exactly \"width\" characters long. It truncates or adds spaces\n# on the end as needed.\ndef colform(txt, width):\n if len(txt) > width:\n txt = txt[:width]\n elif len(txt) < width:\n txt = txt + (\" \" * (width - len(txt)))\n return txt\n\n# Now that you have colform you can use it to print out columns any way you wish.\n# Here's one brain-dead way to print in two columns:\nfor i in xrange(len(skills_defs)):\n sys.stdout.write(colform(skills_defs[i], 30))\n if i % 2 == 1:\n sys.stdout.write('\\n')\n" }, { "answer_id": 62495173, "author": "Ayush Jain", "author_id": 13779749, "author_profile": "https://Stackoverflow.com/users/13779749", "pm_score": 0, "selected": false, "text": "for i in skills_defs:\nif skills_defs.index(i)%2 ==0:\n print(i.ljust(30),end = \" \")\nelse:\n print(i.ljust(30))\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
171,664
<p>I have not used generics much and so cannot figure out if it is possible to turn the following three methods into one using generics to reduce duplication. Actually my code currently has six methods but if you can solve it for the three then the rest should just work anyway with the same solution.</p> <pre><code> private object EvaluateUInt64(UInt64 x, UInt64 y) { switch (Operation) { case BinaryOp.Add: return x + y; case BinaryOp.Subtract: return x - y; case BinaryOp.Multiply: return x * y; case BinaryOp.Divide: return x / y; case BinaryOp.Remainder: return x % y; default: throw new ApplicationException("error"); } } private object EvaluateFloat(float x, float y) { switch(Operation) { case BinaryOp.Add: return x + y; case BinaryOp.Subtract: return x - y; case BinaryOp.Multiply: return x * y; case BinaryOp.Divide: return x / y; case BinaryOp.Remainder: return x % y; default: throw new ApplicationException("error"); } } private object EvaluateDouble(double x, double y) { switch (Operation) { case BinaryOp.Add: return x + y; case BinaryOp.Subtract: return x - y; case BinaryOp.Multiply: return x * y; case BinaryOp.Divide: return x / y; case BinaryOp.Remainder: return x % y; default: throw new ApplicationException("error"); } } </code></pre> <p>I am building a simple expression parser that then needs to evaluate the simple binary operations such as addition/subtraction etc. I use the above methods to get the actual maths performed using the relevant types. But there has got to be a better answer!</p>
[ { "answer_id": 171668, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": " public T Evaluate<T>(T x, T y) {\n switch (Operation)\n {\n case BinaryOp.Add:\n return Operator.Add(x, y);\n case BinaryOp.Subtract:\n return Operator.Subtract(x, y);\n ... etc\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
171,673
<p>I've been trying to create a Windows Media Player plugin in Visual Studio 2008, and am having great difficulty finding the correct template. MSDN provides advice <a href="http://msdn.microsoft.com/en-us/library/bb262076(VS.85).aspx" rel="nofollow noreferrer">here</a>, but it does not appear to be relevant to VS2008.</p> <p>Can anyone suggest how to start a WMP plugin in Visual Studio?</p> <p>EDIT: Ive accepted this answer because it worked for me, but I'm afraid it isn't the most elegant of solutions. If anyone has a better idea, please add it!</p>
[ { "answer_id": 171668, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": " public T Evaluate<T>(T x, T y) {\n switch (Operation)\n {\n case BinaryOp.Add:\n return Operator.Add(x, y);\n case BinaryOp.Subtract:\n return Operator.Subtract(x, y);\n ... etc\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11484/" ]
171,694
<p>Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a <code>SetFont()</code> call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and wxPython In Action book don't discuss this.</p> <p>Is there a way to easily apply the same <code>SetFont()</code> method to all these text objects without making separate calls each time?</p>
[ { "answer_id": 171702, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 1, "selected": false, "text": "__init__ def f(C):\n x = C()\n x.SetFont(font) # where font is defined somewhere else\n return x\n text = f(wx.StaticText)\n StaticText f" }, { "answer_id": 182923, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 0, "selected": false, "text": "SetFont def changeFontInChildren(win, font):\n '''\n Set font in given window and all its descendants.\n @type win: L{wx.Window}\n @type font: L{wx.Font}\n '''\n try:\n win.SetFont(font)\n except:\n pass # don't require all objects to support SetFont\n for child in win.GetChildren():\n changeFontInChildren(child, font)\n frame newFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\nnewFont.SetStyle(wx.FONTSTYLE_ITALIC)\nchangeFontInChildren(frame, newFont)\n" }, { "answer_id": 54486363, "author": "Jorge Moraleda", "author_id": 3981273, "author_profile": "https://Stackoverflow.com/users/3981273", "pm_score": 0, "selected": false, "text": "AuiManager def change_font_in_children(win, font):\n '''\n Set font in given window and all its descendants.\n @type win: L{wx.Window}\n @type font: L{wx.Font}\n '''\n for child in win.GetChildren():\n change_font_in_children(child, font)\n try:\n win.SetFont(font)\n win.Update()\n except:\n pass # don't require all objects to support SetFont\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
171,699
<p>I'm developing and application that runs as a Windows service. There are other components which include a few WCF services, a client GUI and so on - but it is the Windows service that access the database.</p> <p>So, the application is a long-running server, and I'd like to improve its performance and scalability, I was looking to improve data access among other things. I posted in another thread about second-level caching.</p> <p>This post is about session management for the long-running thread that accesses the database. Should I be using a thread-static context? If so, is there any example of how that would be implemented. </p> <p>Every one around the net who is using NHibernate seem to be heavily focussed on web-application style architectures. There seems to be a great lack of documentation / discussion for non-web app designs.</p> <p>At the moment, my long running thread does this:</p> <ol> <li>Call 3 or 4 DAO methods</li> <li>Verify the state of the detached objects returned.</li> <li>Update the state if needed.</li> <li>Call a couple of DAO methods to persist the updated instances. (pass in the id of the object and the instance itself - the DAO will retrieve the object from the DB again, and set the updated values and session.SaveOrUpdate() before committing the transaction.</li> <li>Sleep for 'n' seconds</li> <li>Repeat all over again!</li> </ol> <p>So, the following is a common pattern we use for each of the DAO methods:</p> <ul> <li>Open session using sessionFactory.OpenSession()</li> <li>Begin transaction</li> <li>Do db work. retrieve / update etc</li> <li>Commit trans</li> <li>(Rollback in case of exceptions)</li> <li>Finally always dispose transaction and session.Close()</li> </ul> <p>This happens for <em>every</em> method call to a DAO class. I suspect this is some sort of an anti-pattern the way we are doing it.</p> <p>However, I'm not able to find enough direction anywhere as to how we could improve it.</p> <p>Pls note, while this thread is running in the background, doing its stuff, there are requests coming in from the WCF clients each of which could make 2-3 DAO calls themselves - sometimes querying/updating the same objects the long running thread deals with.</p> <p>Any ideas / suggestions / pointers to improve our design will be greatly appreciated. If we can get some good discussion going, we could make this a community wiki, and possbily link to here from <a href="http://nhibernate.info" rel="nofollow noreferrer">http://nhibernate.info</a></p> <p>Krishna</p>
[ { "answer_id": 324185, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private void BeginTransaction(object sender, EventArgs e) {\n NHibernateSessionManager.Instance.BeginTransaction();\n}\nprivate void CommitAndCloseSession(object sender, EventArgs e) {\n try {\n NHibernateSessionManager.Instance.CommitTransaction();\n }\n finally {\n NHibernateSessionManager.Instance.CloseSession();\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6995/" ]
171,727
<p>How do i delete all the tables in the schema on Apache Derby DB using JDBC?</p>
[ { "answer_id": 171773, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 2, "selected": false, "text": "DROP TABLE [tablename]\n tablename SELECT tablename FROM SYSTABLES\n" }, { "answer_id": 13928594, "author": "gregn", "author_id": 266387, "author_profile": "https://Stackoverflow.com/users/266387", "pm_score": 0, "selected": false, "text": "SELECT 'DROP TABLE ' || schemaname ||'.' || tablename || ';'\nFROM SYS.SYSTABLES\nINNER JOIN SYS.SYSSCHEMAS ON SYS.SYSTABLES.SCHEMAID = SYS.SYSSCHEMAS.SCHEMAID\n;\n" }, { "answer_id": 22890176, "author": "Sym-Sym", "author_id": 1725975, "author_profile": "https://Stackoverflow.com/users/1725975", "pm_score": 3, "selected": false, "text": "SELECT\n'ALTER TABLE '||S.SCHEMANAME||'.'||T.TABLENAME||' DROP CONSTRAINT '||C.CONSTRAINTNAME||';'\nFROM\n SYS.SYSCONSTRAINTS C,\n SYS.SYSSCHEMAS S,\n SYS.SYSTABLES T\nWHERE\n C.SCHEMAID = S.SCHEMAID\nAND\n C.TABLEID = T.TABLEID\nAND\nS.SCHEMANAME = 'APP'\nUNION\nSELECT 'DROP TABLE ' || schemaname ||'.' || tablename || ';'\nFROM SYS.SYSTABLES\nINNER JOIN SYS.SYSSCHEMAS ON SYS.SYSTABLES.SCHEMAID = SYS.SYSSCHEMAS.SCHEMAID\nwhere schemaname='APP';\n" }, { "answer_id": 70706017, "author": "keithphw", "author_id": 1126250, "author_profile": "https://Stackoverflow.com/users/1126250", "pm_score": 0, "selected": false, "text": "public static void dropAllSchemas(Connection conn) throws SQLException {\n DatabaseMetaData dmd = conn.getMetaData();\n SQLException sqle = null;\n // Loop a number of arbitary times to catch cases\n // where objects are dependent on objects in\n // different schemas.\n for (int count = 0; count < 5; count++) {\n // Fetch all the user schemas into a list\n List<String> schemas = new ArrayList<String>();\n ResultSet rs = dmd.getSchemas();\n while (rs.next()) {\n String schema = rs.getString(\"TABLE_SCHEM\");\n if (schema.startsWith(\"SYS\"))\n continue;\n if (schema.equals(\"SQLJ\"))\n continue;\n if (schema.equals(\"NULLID\"))\n continue;\n schemas.add(schema);\n }\n rs.close();\n // DROP all the user schemas.\n sqle = null;\n for (String schema : schemas) {\n try {\n dropSchema(dmd, schema);\n } catch (SQLException e) {\n sqle = e;\n }\n }\n // No errors means all the schemas we wanted to\n // drop were dropped, so nothing more to do.\n if (sqle == null)\n return;\n }\n throw sqle;\n}\n\n\n/**\n * Constant to pass to DatabaseMetaData.getTables() to fetch\n * just tables.\n */\npublic static final String[] GET_TABLES_TABLE = new String[] {\"TABLE\"};\n/**\n * Constant to pass to DatabaseMetaData.getTables() to fetch\n * just views.\n */\npublic static final String[] GET_TABLES_VIEW = new String[] {\"VIEW\"};\n/**\n * Constant to pass to DatabaseMetaData.getTables() to fetch\n * just synonyms.\n */\npublic static final String[] GET_TABLES_SYNONYM =\n new String[] {\"SYNONYM\"};\n/**\n * Drop a database schema by dropping all objects in it\n * and then executing DROP SCHEMA. If the schema is\n * APP it is cleaned but DROP SCHEMA is not executed.\n * \n * TODO: Handle dependencies by looping in some intelligent\n * way until everything can be dropped.\n * \n\n * \n * @param dmd DatabaseMetaData object for database\n * @param schema Name of the schema\n * @throws SQLException database error\n */\npublic static void dropSchema(DatabaseMetaData dmd, String schema) throws SQLException{ \n Connection conn = dmd.getConnection();\n Statement s = dmd.getConnection().createStatement();\n\n // Triggers\n PreparedStatement pstr = conn.prepareStatement(\n \"SELECT TRIGGERNAME FROM SYS.SYSSCHEMAS S, SYS.SYSTRIGGERS T \"\n + \"WHERE S.SCHEMAID = T.SCHEMAID AND SCHEMANAME = ?\");\n pstr.setString(1, schema);\n ResultSet trrs = pstr.executeQuery();\n while (trrs.next()) {\n String trigger = trrs.getString(1);\n s.execute(\"DROP TRIGGER \" + escape(schema, trigger));\n }\n trrs.close();\n pstr.close();\n\n // Functions - not supported by JDBC meta data until JDBC 4\n // Need to use the CHAR() function on A.ALIASTYPE\n // so that the compare will work in any schema.\n PreparedStatement psf = conn.prepareStatement(\n \"SELECT ALIAS FROM SYS.SYSALIASES A, SYS.SYSSCHEMAS S\" +\n \" WHERE A.SCHEMAID = S.SCHEMAID \" +\n \" AND CHAR(A.ALIASTYPE) = ? \" +\n \" AND S.SCHEMANAME = ?\");\n psf.setString(1, \"F\" );\n psf.setString(2, schema);\n ResultSet rs = psf.executeQuery();\n dropUsingDMD(s, rs, schema, \"ALIAS\", \"FUNCTION\"); \n\n // Procedures\n rs = dmd.getProcedures((String) null,\n schema, (String) null);\n \n dropUsingDMD(s, rs, schema, \"PROCEDURE_NAME\", \"PROCEDURE\");\n \n // Views\n rs = dmd.getTables((String) null, schema, (String) null,\n GET_TABLES_VIEW);\n \n dropUsingDMD(s, rs, schema, \"TABLE_NAME\", \"VIEW\");\n \n // Tables\n rs = dmd.getTables((String) null, schema, (String) null,\n GET_TABLES_TABLE);\n \n dropUsingDMD(s, rs, schema, \"TABLE_NAME\", \"TABLE\");\n \n // At this point there may be tables left due to\n // foreign key constraints leading to a dependency loop.\n // Drop any constraints that remain and then drop the tables.\n // If there are no tables then this should be a quick no-op.\n ResultSet table_rs = dmd.getTables((String) null, schema, (String) null,\n GET_TABLES_TABLE);\n\n while (table_rs.next()) {\n String tablename = table_rs.getString(\"TABLE_NAME\");\n rs = dmd.getExportedKeys((String) null, schema, tablename);\n while (rs.next()) {\n short keyPosition = rs.getShort(\"KEY_SEQ\");\n if (keyPosition != 1)\n continue;\n String fkName = rs.getString(\"FK_NAME\");\n // No name, probably can't happen but couldn't drop it anyway.\n if (fkName == null)\n continue;\n String fkSchema = rs.getString(\"FKTABLE_SCHEM\");\n String fkTable = rs.getString(\"FKTABLE_NAME\");\n\n String ddl = \"ALTER TABLE \" +\n escape(fkSchema, fkTable) +\n \" DROP FOREIGN KEY \" +\n escape(fkName);\n s.executeUpdate(ddl);\n }\n rs.close();\n }\n table_rs.close();\n conn.commit();\n \n // Tables (again)\n rs = dmd.getTables((String) null, schema, (String) null,\n GET_TABLES_TABLE); \n dropUsingDMD(s, rs, schema, \"TABLE_NAME\", \"TABLE\");\n\n // drop UDTs\n psf.setString(1, \"A\" );\n psf.setString(2, schema);\n rs = psf.executeQuery();\n dropUsingDMD(s, rs, schema, \"ALIAS\", \"TYPE\"); \n\n // drop aggregates\n psf.setString(1, \"G\" );\n psf.setString(2, schema);\n rs = psf.executeQuery();\n dropUsingDMD(s, rs, schema, \"ALIAS\", \"DERBY AGGREGATE\"); \n psf.close();\n\n // Synonyms - need work around for DERBY-1790 where\n // passing a table type of SYNONYM fails.\n rs = dmd.getTables((String) null, schema, (String) null,\n GET_TABLES_SYNONYM);\n \n dropUsingDMD(s, rs, schema, \"TABLE_NAME\", \"SYNONYM\");\n \n // sequences\n if ( sysSequencesExists( conn ) )\n {\n psf = conn.prepareStatement\n (\n \"SELECT SEQUENCENAME FROM SYS.SYSSEQUENCES A, SYS.SYSSCHEMAS S\" +\n \" WHERE A.SCHEMAID = S.SCHEMAID \" +\n \" AND S.SCHEMANAME = ?\");\n psf.setString(1, schema);\n rs = psf.executeQuery();\n dropUsingDMD(s, rs, schema, \"SEQUENCENAME\", \"SEQUENCE\");\n psf.close();\n }\n\n // Finally drop the schema if it is not APP\n if (!schema.equals(\"APP\")) {\n s.executeUpdate(\"DROP SCHEMA \" + escape(schema) + \" RESTRICT\");\n }\n conn.commit();\n s.close();\n}\n\n /**\n * Return true if the SYSSEQUENCES table exists.\n */\nprivate static boolean sysSequencesExists( Connection conn ) throws SQLException\n{\n PreparedStatement ps = null;\n ResultSet rs = null;\n try {\n ps = conn.prepareStatement\n (\n \"select count(*) from sys.systables t, sys.sysschemas s\\n\" +\n \"where t.schemaid = s.schemaid\\n\" +\n \"and ( cast(s.schemaname as varchar(128)))= 'SYS'\\n\" +\n \"and ( cast(t.tablename as varchar(128))) = 'SYSSEQUENCES'\" );\n rs = ps.executeQuery();\n rs.next();\n return ( rs.getInt( 1 ) > 0 );\n }\n finally\n {\n if ( rs != null ) { rs.close(); }\n if ( ps != null ) { ps.close(); }\n }\n}\n\n/**\n * Escape a non-qualified name so that it is suitable\n * for use in a SQL query executed by JDBC.\n */\npublic static String escape(String name)\n{\n StringBuffer buffer = new StringBuffer(name.length() + 2);\n buffer.append('\"');\n for (int i = 0; i < name.length(); i++) {\n char c = name.charAt(i);\n // escape double quote characters with an extra double quote\n if (c == '\"') buffer.append('\"');\n buffer.append(c);\n }\n buffer.append('\"');\n return buffer.toString();\n} \n\n/**\n * Escape a schema-qualified name so that it is suitable\n * for use in a SQL query executed by JDBC.\n */\npublic static String escape(String schema, String name)\n{\n return escape(schema) + \".\" + escape(name);\n}\n\n\n/**\n * DROP a set of objects based upon a ResultSet from a\n * DatabaseMetaData call.\n * \n * TODO: Handle errors to ensure all objects are dropped,\n * probably requires interaction with its caller.\n * \n * @param s Statement object used to execute the DROP commands.\n * @param rs DatabaseMetaData ResultSet\n * @param schema Schema the objects are contained in\n * @param mdColumn The column name used to extract the object's\n * name from rs\n * @param dropType The keyword to use after DROP in the SQL statement\n * @throws SQLException database errors.\n */\nprivate static void dropUsingDMD(\n Statement s, ResultSet rs, String schema,\n String mdColumn,\n String dropType) throws SQLException\n{\n String dropLeadIn = \"DROP \" + dropType + \" \";\n \n // First collect the set of DROP SQL statements.\n ArrayList<String> ddl = new ArrayList<String>();\n while (rs.next())\n {\n String objectName = rs.getString(mdColumn);\n String raw = dropLeadIn + escape(schema, objectName);\n if (\n \"TYPE\".equals( dropType ) ||\n \"SEQUENCE\".equals( dropType ) ||\n \"DERBY AGGREGATE\".equals( dropType )\n )\n { raw = raw + \" restrict \"; }\n ddl.add( raw );\n }\n rs.close();\n if (ddl.isEmpty())\n return;\n \n // Execute them as a complete batch, hoping they will all succeed.\n s.clearBatch();\n int batchCount = 0;\n for (Iterator i = ddl.iterator(); i.hasNext(); )\n {\n Object sql = i.next();\n if (sql != null) {\n s.addBatch(sql.toString());\n batchCount++;\n }\n }\n\n int[] results;\n boolean hadError;\n try {\n results = s.executeBatch();\n //Assert.assertNotNull(results);\n //Assert.assertEquals(\"Incorrect result length from executeBatch\", batchCount, results.length);\n hadError = false;\n } catch (BatchUpdateException batchException) {\n results = batchException.getUpdateCounts();\n //Assert.assertNotNull(results);\n //Assert.assertTrue(\"Too many results in BatchUpdateException\", results.length <= batchCount);\n hadError = true;\n }\n \n // Remove any statements from the list that succeeded.\n boolean didDrop = false;\n for (int i = 0; i < results.length; i++)\n {\n int result = results[i];\n if (result == Statement.EXECUTE_FAILED)\n hadError = true;\n else if (result == Statement.SUCCESS_NO_INFO || result >= 0) {\n didDrop = true;\n ddl.set(i, null);\n }\n //else\n //Assert.fail(\"Negative executeBatch status\");\n }\n s.clearBatch();\n if (didDrop) {\n // Commit any work we did do.\n s.getConnection().commit();\n }\n\n // If we had failures drop them as individual statements\n // until there are none left or none succeed. We need to\n // do this because the batch processing stops at the first\n // error. This copes with the simple case where there\n // are objects of the same type that depend on each other\n // and a different drop order will allow all or most\n // to be dropped.\n if (hadError) {\n do {\n hadError = false;\n didDrop = false;\n for (ListIterator<String> i = ddl.listIterator(); i.hasNext();) {\n String sql = i.next();\n if (sql != null) {\n try {\n s.executeUpdate(sql);\n i.set(null);\n didDrop = true;\n } catch (SQLException e) {\n hadError = true;\n }\n }\n }\n if (didDrop)\n s.getConnection().commit();\n } while (hadError && didDrop);\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15100/" ]
171,730
<p>I have a small problem with interfaces. Here it is in Pseudo code :</p> <pre><code>type Interface1 = interface end; Interface2 = interface end; TParentClass = class(TInterfacedObject, Interface1) private fChild : Interface2; public procedure AddChild(aChild : Interface2); end; TChildClass = class(TInterfacedObject, Interface2) private fParent : Interface2; public constructor Create(aPArent : Interface1); end; </code></pre> <p>Can anyone see the flaw? I need the child to have a reference to it's parent, but the reference counting doesn't work in this situation. If I create a ParentClass instance, and add a child, then the parent class is never released. I can see why. How do I get round it?</p>
[ { "answer_id": 171795, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "TChildClass = class(TInterfacedObject, Interface2)\nprivate\n fParent : Pointer;\n function GetParent: Interface1;\npublic\n constructor Create(aPArent : Interface1);\n property Parent: Interface1 read GetParent;\nend;\n\nfunction TChildClass.GetParent: Interface1;\nbegin\n Result := Interface1(fParent);\nend;\n\nconstructor TChildClass.Create(AParent: Interface1);\nbegin\n fParent := Pointer(AParent);\nend;\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
171,765
<p>Here's the very dumb way:</p> <pre><code>def divisorGenerator(n): for i in xrange(1,n/2+1): if n%i == 0: yield i yield n </code></pre> <p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p> <p>I can find prime factors and their multiplicity fast enough. I've an generator that generates factor in this way:</p> <p>(factor1, multiplicity1)<br> (factor2, multiplicity2)<br> (factor3, multiplicity3)<br> and so on...</p> <p>i.e. the output of </p> <pre><code>for i in factorGenerator(100): print i </code></pre> <p>is:</p> <pre><code>(2, 2) (5, 2) </code></pre> <p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p> <pre><code>for i in divisorGen(100): print i </code></pre> <p>output this:</p> <pre><code>1 2 4 5 10 20 25 50 100 </code></pre> <hr> <p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :) Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p> <p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="https://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
[ { "answer_id": 171779, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 5, "selected": false, "text": "n / i import math\n\ndef divisorGenerator(n):\n large_divisors = []\n for i in xrange(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\n\nprint list(divisorGenerator(100))\n" }, { "answer_id": 171784, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": true, "text": "factorGenerator divisorGen def divisorGen(n):\n factors = list(factorGenerator(n))\n nfactors = len(factors)\n f = [0] * nfactors\n while True:\n yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)\n i = 0\n while True:\n f[i] += 1\n if f[i] <= factors[i][1]:\n break\n f[i] = 0\n i += 1\n if i >= nfactors:\n return\n factorGenerator" }, { "answer_id": 371129, "author": "Pietro Speroni", "author_id": 46634, "author_profile": "https://Stackoverflow.com/users/46634", "pm_score": 3, "selected": false, "text": "from math import sqrt\n\n\n##############################################################\n### cartesian product of lists ##################################\n##############################################################\n\ndef appendEs2Sequences(sequences,es):\n result=[]\n if not sequences:\n for e in es:\n result.append([e])\n else:\n for e in es:\n result+=[seq+[e] for seq in sequences]\n return result\n\n\ndef cartesianproduct(lists):\n \"\"\"\n given a list of lists,\n returns all the possible combinations taking one element from each list\n The list does not have to be of equal length\n \"\"\"\n return reduce(appendEs2Sequences,lists,[])\n\n##############################################################\n### prime factors of a natural ##################################\n##############################################################\n\ndef primefactors(n):\n '''lists prime factors, from greatest to smallest''' \n i = 2\n while i<=sqrt(n):\n if n%i==0:\n l = primefactors(n/i)\n l.append(i)\n return l\n i+=1\n return [n] # n is prime\n\n\n##############################################################\n### factorization of a natural ##################################\n##############################################################\n\ndef factorGenerator(n):\n p = primefactors(n)\n factors={}\n for p1 in p:\n try:\n factors[p1]+=1\n except KeyError:\n factors[p1]=1\n return factors\n\ndef divisors(n):\n factors = factorGenerator(n)\n divisors=[]\n listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]\n listfactors=cartesianproduct(listexponents)\n for f in listfactors:\n divisors.append(reduce(lambda x, y: x*y, f, 1))\n divisors.sort()\n return divisors\n\n\n\nprint divisors(60668796879)\n" }, { "answer_id": 15025068, "author": "YvesgereY", "author_id": 995896, "author_profile": "https://Stackoverflow.com/users/995896", "pm_score": 2, "selected": false, "text": "num=1 from itertools import product\nimport operator\n\ndef prod(ls):\n return reduce(operator.mul, ls, 1)\n\ndef powered(factors, powers):\n return prod(f**p for (f,p) in zip(factors, powers))\n\n\ndef divisors(num) :\n\n pf = dict(prime_factors(num))\n primes = pf.keys()\n #For each prime, possible exponents\n exponents = [range(i+1) for i in pf.values()]\n return (powered(primes,es) for es in product(*exponents))\n" }, { "answer_id": 18366032, "author": "user448810", "author_id": 448810, "author_profile": "https://Stackoverflow.com/users/448810", "pm_score": 0, "selected": false, "text": "factors factors(60) function divisors(n)\n divs := [1]\n for fact in factors(n)\n temp := []\n for div in divs\n if fact * div not in divs\n append fact * div to temp\n divs := divs + temp\n return divs\n" }, { "answer_id": 23983542, "author": "user3697453", "author_id": 3697453, "author_profile": "https://Stackoverflow.com/users/3697453", "pm_score": 0, "selected": false, "text": "return [x for x in range(n+1) if n/x==int(n/x)]\n" }, { "answer_id": 31340346, "author": "Amber Xue", "author_id": 3371387, "author_profile": "https://Stackoverflow.com/users/3371387", "pm_score": 0, "selected": false, "text": "import math as m \n\ndef findfac(n):\n faclist = [1]\n for i in range(2, int(m.sqrt(n) + 2)):\n if n%i == 0:\n if i not in faclist:\n faclist.append(i)\n if n/i not in faclist:\n faclist.append(n/i)\n return facts\n" }, { "answer_id": 36070582, "author": "joksnet", "author_id": 408564, "author_profile": "https://Stackoverflow.com/users/408564", "pm_score": 2, "selected": false, "text": "def divs(n, m):\n if m == 1: return [1]\n if n % m == 0: return [m] + divs(n, m - 1)\n return divs(n, m - 1)\n def divisorGenerator(n):\n for x in reversed(divs(n, n)):\n yield x\n" }, { "answer_id": 36700288, "author": "Anivarth", "author_id": 3442438, "author_profile": "https://Stackoverflow.com/users/3442438", "pm_score": 5, "selected": false, "text": "math.sqrt(n) sqrt(28) 5.29 ceil(5.29) import math\ndef divisors(n):\n divs = [1]\n for i in xrange(2,int(math.sqrt(n))+1):\n if n%i == 0:\n divs.extend([i,n/i])\n divs.extend([n])\n return list(set(divs))\n 1 i=2" }, { "answer_id": 37058745, "author": "Tomas Kulich", "author_id": 1761457, "author_profile": "https://Stackoverflow.com/users/1761457", "pm_score": 5, "selected": false, "text": "def divisors(n):\n # get factors and their counts\n factors = {}\n nn = n\n i = 2\n while i*i <= nn:\n while nn % i == 0:\n factors[i] = factors.get(i, 0) + 1\n nn //= i\n i += 1\n if nn > 1:\n factors[nn] = factors.get(nn, 0) + 1\n\n primes = list(factors.keys())\n\n # generates factors from primes[k:] subset\n def generate(k):\n if k == len(primes):\n yield 1\n else:\n rest = generate(k+1)\n prime = primes[k]\n for factor in rest:\n prime_to_i = 1\n # prime_to_i iterates prime**i values, i being all possible exponents\n for _ in range(factors[prime] + 1):\n yield factor * prime_to_i\n prime_to_i *= prime\n\n # in python3, `yield from generate(0)` would also work\n for factor in generate(0):\n yield factor\n" }, { "answer_id": 46637377, "author": "Bruno Astrolino", "author_id": 8694657, "author_profile": "https://Stackoverflow.com/users/8694657", "pm_score": 3, "selected": false, "text": "from itertools import compress\n\ndef primes(n):\n \"\"\" Returns a list of primes < n for n > 2 \"\"\"\n sieve = bytearray([True]) * (n//2)\n for i in range(3,int(n**0.5)+1,2):\n if sieve[i//2]:\n sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)\n return [2,*compress(range(3,n,2), sieve[1:])]\n\ndef factorization(n):\n \"\"\" Returns a list of the prime factorization of n \"\"\"\n pf = []\n for p in primeslist:\n if p*p > n : break\n count = 0\n while not n % p:\n n //= p\n count += 1\n if count > 0: pf.append((p, count))\n if n > 1: pf.append((n, 1))\n return pf\n\ndef divisors(n):\n \"\"\" Returns an unsorted list of the divisors of n \"\"\"\n divs = [1]\n for p, e in factorization(n):\n divs += [x*p**k for k in range(1,e+1) for x in divs]\n return divs\n\nn = 600851475143\nprimeslist = primes(int(n**0.5)+1) \nprint(divisors(n))\n" }, { "answer_id": 49888733, "author": "Sadiq", "author_id": 3575229, "author_profile": "https://Stackoverflow.com/users/3575229", "pm_score": 0, "selected": false, "text": "from itertools import combinations\nfrom functools import reduce\n\ndef get_devisors(n):\n f = [f for f,e in list(factorGenerator(n)) for i in range(e)]\n fc = [x for l in range(len(f)+1) for x in combinations(f, l)]\n devisors = [1 if c==() else reduce((lambda x, y: x * y), c) for c in set(fc)]\n return sorted(devisors)\n" }, { "answer_id": 54047215, "author": "ppw0", "author_id": 7143340, "author_profile": "https://Stackoverflow.com/users/7143340", "pm_score": 4, "selected": false, "text": "from itertools import chain\nfrom math import sqrt\n\ndef divisors(n):\n return set(chain.from_iterable((i,n//i) for i in range(1,int(sqrt(n))+1) if n%i == 0))\n from sympy import divisors\n" }, { "answer_id": 63416316, "author": "Mathieu Villion", "author_id": 6175500, "author_profile": "https://Stackoverflow.com/users/6175500", "pm_score": 2, "selected": false, "text": "N = 10000000; tst = np.arange(1, N); tst[np.mod(N, tst) == 0]\nOut: \narray([ 1, 2, 4, 5, 8, 10, 16,\n 20, 25, 32, 40, 50, 64, 80,\n 100, 125, 128, 160, 200, 250, 320,\n 400, 500, 625, 640, 800, 1000, 1250,\n 1600, 2000, 2500, 3125, 3200, 4000, 5000,\n 6250, 8000, 10000, 12500, 15625, 16000, 20000,\n 25000, 31250, 40000, 50000, 62500, 78125, 80000,\n 100000, 125000, 156250, 200000, 250000, 312500, 400000,\n 500000, 625000, 1000000, 1250000, 2000000, 2500000, 5000000])\n" }, { "answer_id": 63450265, "author": "Eugene", "author_id": 9135063, "author_profile": "https://Stackoverflow.com/users/9135063", "pm_score": 0, "selected": false, "text": "def divisor(num):\n for x in range(1, num + 1):\n if num % x == 0:\n yield x\n while True:\n yield None\n" }, { "answer_id": 67455769, "author": "Arvind Pant", "author_id": 4878423, "author_profile": "https://Stackoverflow.com/users/4878423", "pm_score": 0, "selected": false, "text": "number = int(input(\"Enter a Number: \"))\nsquare_root = round(number ** (1.0 / 2))\nprint(square_root)\ndivisor_list = []\nfor i in range(1,square_root+1):\n if number % i == 0: # Check if mod return 0 if yes then append i and number/i in the list\n divisor_list.append(i)\n divisor_list.append(int(number/i))\n\nprint(divisor_list)\n" }, { "answer_id": 69464666, "author": "amiralidev", "author_id": 11753050, "author_profile": "https://Stackoverflow.com/users/11753050", "pm_score": 0, "selected": false, "text": "def divisorGen(n): v = n last = [] for i in range(1, v+1) : if n % i == 0 : last.append(i)\n" }, { "answer_id": 70406267, "author": "Rodrigo V", "author_id": 12647804, "author_profile": "https://Stackoverflow.com/users/12647804", "pm_score": 0, "selected": false, "text": "def divisors(n):\n lis =[1]\n s = math.ceil(math.sqrt(n))\n for g in range(s,1, -1):\n if n % g == 0:\n lis.append(g)\n lis.append(int(n / g))\n return (set(lis))\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21384/" ]
171,771
<p>Okay, so I'm doing my first foray into using the ADO.NET Entity Framework. </p> <p>My test case right now includes a SQL Server 2008 database with 2 tables, Member and Profile, with a 1:1 relationship.</p> <p>I then used the Entity Data Model wizard to auto-generate the EDM from the database. It generated a model with the correct association. Now I want to do this:</p> <pre><code>ObjectQuery&lt;Member&gt; members = entities.Member; IQueryable&lt;Member&gt; membersQuery = from m in members select m; foreach (Member m in membersQuery) { Profile p = m.Profile; ... } </code></pre> <p>Which halfway works. I am able to iterate through all of the Members. But the problem I'm having is that m.Profile is always null. The examples for LINQ to Entities on the MSDN library seem to suggest that I will be able to seamlessly follow the navigation relationships like that, but it doesn't seem to work that way. I found that if I first load the profiles in a separate call somehow, such as using entities.Profile.ToList, then m.Profile will point to a valid Profile.</p> <p>So my question is, is there an elegant way to force the framework to automatically load the data along the navigation relationships, or do I need to do that explicitly with a join or something else?</p> <p>Thanks</p>
[ { "answer_id": 173273, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 4, "selected": true, "text": "IQueryable<Member> membersQuery = from m in members.Include(\"Profile\") select m;\n" }, { "answer_id": 329342, "author": "WestDiscGolf", "author_id": 33116, "author_profile": "https://Stackoverflow.com/users/33116", "pm_score": 1, "selected": false, "text": "context.Survey.Include(\"SurveyQuestion\").Where(x => x.Id == id).First()\n context.Survey.Include<T>().Where(x => x.Id == id).First()\n public static ObjectQuery<T> Include<T,U>(this ObjectQuery<T> context)\n {\n string path = typeof(U).ToString();\n string[] split = path.Split('.');\n\n return context.Include(split[split.Length - 1]);\n }\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19404/" ]
171,776
<p>I've looked at <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">this explanation on Wikipedia</a>, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example?</p> <hr> <p>What I can make from the answers so far, it seems to me to be just a more complex way of doing this:</p> <pre><code>have an abstract class: MoveAlong with a virtual method: DoIt() have class Car inherit from MoveAlong, implementing DoIt() { ..start-car-and-drive..} have class HorseCart inherit from MoveAlong, implementing DoIt() { ..hit-horse..} have class Bicycle inherit from MoveAlong, implementing DoIt() { ..pedal..} now I can call any function taking MoveAlong as parm passing any of the three classes and call DoIt Isn't this what Strategy intents? (just simpler?) </code></pre> <p>[Edit-update] The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.)</p> <hr> <p>[Edit-update] <strong>Conclusion</strong></p> <p>The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!).</p>
[ { "answer_id": 171781, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "execute ioctl" }, { "answer_id": 171782, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 3, "selected": false, "text": "String path = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), ???);\n String path = ... ;\nCipher strategy = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), strategy);\n" }, { "answer_id": 171803, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 5, "selected": true, "text": "class IClockDisplay\n{\n public:\n virtual void Display( int hour, int minute, int second ) = 0;\n};\n class Clock\n{\n protected:\n IClockDisplay* mDisplay;\n int mHour;\n int mMinute;\n int mSecond;\n\n public:\n Clock( IClockDisplay* display )\n {\n mDisplay = display;\n }\n\n void Start(); // initiate the timer\n\n void OnTimer()\n {\n mDisplay->Display( mHour, mMinute, mSecond );\n }\n\n void ChangeDisplay( IClockDisplay* display )\n {\n mDisplay = display;\n }\n};\n" }, { "answer_id": 42359459, "author": "PapaDiHatti", "author_id": 3600304, "author_profile": "https://Stackoverflow.com/users/3600304", "pm_score": 0, "selected": false, "text": "class CEncryptor\n{\n virtual void encrypt () = 0;\n virtual void decrypt () = 0;\n};\nclass CMessage\n{\nprivate:\n shared_ptr<CEncryptor> m_pcEncryptor;\npublic:\n virtual void send() = 0;\n\n virtual void receive() = 0;\n\n void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor)\n {\n m_pcEncryptor = arg_pcEncryptor;\n }\n\n void performEncryption()\n {\n m_pcEncryptor->encrypt();\n }\n};\n CMessage *ptr = new CMailMessage();\nptr->setEncryptor(new CDESEncrypto());\nptr->performEncryption();\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
171,778
<p>Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle).</p> <p>Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order?</p> <p>Based on the answer to the question referenced by nickf the answer is:</p> <pre><code>select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty </code></pre>
[ { "answer_id": 171781, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "execute ioctl" }, { "answer_id": 171782, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 3, "selected": false, "text": "String path = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), ???);\n String path = ... ;\nCipher strategy = ... ;\nInputStream = new CipherInputStream(new FileInputStream(path), strategy);\n" }, { "answer_id": 171803, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 5, "selected": true, "text": "class IClockDisplay\n{\n public:\n virtual void Display( int hour, int minute, int second ) = 0;\n};\n class Clock\n{\n protected:\n IClockDisplay* mDisplay;\n int mHour;\n int mMinute;\n int mSecond;\n\n public:\n Clock( IClockDisplay* display )\n {\n mDisplay = display;\n }\n\n void Start(); // initiate the timer\n\n void OnTimer()\n {\n mDisplay->Display( mHour, mMinute, mSecond );\n }\n\n void ChangeDisplay( IClockDisplay* display )\n {\n mDisplay = display;\n }\n};\n" }, { "answer_id": 42359459, "author": "PapaDiHatti", "author_id": 3600304, "author_profile": "https://Stackoverflow.com/users/3600304", "pm_score": 0, "selected": false, "text": "class CEncryptor\n{\n virtual void encrypt () = 0;\n virtual void decrypt () = 0;\n};\nclass CMessage\n{\nprivate:\n shared_ptr<CEncryptor> m_pcEncryptor;\npublic:\n virtual void send() = 0;\n\n virtual void receive() = 0;\n\n void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor)\n {\n m_pcEncryptor = arg_pcEncryptor;\n }\n\n void performEncryption()\n {\n m_pcEncryptor->encrypt();\n }\n};\n CMessage *ptr = new CMailMessage();\nptr->setEncryptor(new CDESEncrypto());\nptr->performEncryption();\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3509/" ]
171,785
<p>When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them.</p> <p>How do you keep everything manageable?</p>
[ { "answer_id": 172538, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "Components Projects setup.py Projects setup.py PYTHONPATH" }, { "answer_id": 173715, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 5, "selected": true, "text": "paster create" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672/" ]
171,809
<p>Are there LaTeX packages for (more or less) easily drawing Gantt diagrams?</p> <p>Thanks.</p>
[ { "answer_id": 2772068, "author": "ablaeul", "author_id": 331618, "author_profile": "https://Stackoverflow.com/users/331618", "pm_score": 2, "selected": false, "text": "\\psline" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11384/" ]
171,816
<p>(The original question was asked there : <a href="http://www.ogre3d.org/phpBB2/viewtopic.php?t=44832" rel="nofollow noreferrer">http://www.ogre3d.org/phpBB2/viewtopic.php?t=44832</a> )</p> <p>Someone asked : "While I would like to build everything in vs2008 (VC9), the PhysX SDK is built with vs2005 (VC8). Would this cause any problems, using all vc9 compiled libs and used in combination with this vc8 lib?"</p> <p>I answered that the day before i tried to use a .lib file (and a .dll) generated with VC8 and include it in a vc9 compiled exe, the compiler couldn't open the .lib file.</p> <p>Now, other answered they did this with no problems....</p> <p>I can't find the information about lib compatibility between vc9 and vc8. </p> <p>so... Help?</p>
[ { "answer_id": 2772068, "author": "ablaeul", "author_id": 331618, "author_profile": "https://Stackoverflow.com/users/331618", "pm_score": 2, "selected": false, "text": "\\psline" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2368/" ]
171,824
<p>I have a plug-in to an Eclipse RCP application that has a view. After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu.</p> <p>I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere.</p>
[ { "answer_id": 172082, "author": "ILikeCoffee", "author_id": 25270, "author_profile": "https://Stackoverflow.com/users/25270", "pm_score": 7, "selected": true, "text": "PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(\"viewId\");\n" }, { "answer_id": 675164, "author": "Imaskar", "author_id": 78569, "author_profile": "https://Stackoverflow.com/users/78569", "pm_score": 4, "selected": false, "text": "HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().showView(viewId);\n" }, { "answer_id": 888682, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "PlatformUI.getWorkbench()\n .getActiveWorkbenchWindow()\n .getActivePage()\n .activate(workbenchPartToActivate);\n IWorkbenchPart" }, { "answer_id": 22612362, "author": "Max Hohenegger", "author_id": 794836, "author_profile": "https://Stackoverflow.com/users/794836", "pm_score": 0, "selected": false, "text": "public class Opener {\n @Inject\n EPartService partService;\n\n public void openPart() {\n MPart part = partService.createPart(\"org.eclipse.ui.browser.view\");\n part.setLabel(\"Browser\");\n\n partService.showPart(part, PartState.ACTIVATE);\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/725/" ]
171,828
<p>When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question.</p> <p>I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look in/at the JAR and switch to the same branch, version or tag that was the source of the released JAR.</p> <p>How can I best adjust the ant build process so that the version information in the svn checkout remains in the created build?</p> <p>I was thinking along the lines of:</p> <ul> <li>adding a VERSION file, but with what content?</li> <li>storing information in the META-INF file, but under what property with which content?</li> <li>copying sources into the result archive</li> <li>added svn:properties to all sources with keywords in places the compiler leaves them be</li> </ul> <hr> <p>I ended up using the svnversion approach (the accepted anwser), because it scans the entire subtree as opposed to svn info which just looks at the current file / directory. For this I defined the SVN task in the ant file to make it more portable. </p> <pre><code>&lt;taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask"&gt; &lt;classpath&gt; &lt;pathelement location="${dir.lib}/ant/svnant.jar"/&gt; &lt;pathelement location="${dir.lib}/ant/svnClientAdapter.jar"/&gt; &lt;pathelement location="${dir.lib}/ant/svnkit.jar"/&gt; &lt;pathelement location="${dir.lib}/ant/svnjavahl.jar"/&gt; &lt;/classpath&gt; &lt;/taskdef&gt; </code></pre> <p>Not all builds result in webservices. The ear file before deployment must remain the same name because of updating in the application server. Making the file executable is still an option, but until then I just include a version information file.</p> <pre><code>&lt;target name="version"&gt; &lt;svn&gt;&lt;wcVersion path="${dir.source}"/&gt;&lt;/svn&gt; &lt;echo file="${dir.build}/VERSION"&gt;${revision.range}&lt;/echo&gt; &lt;/target&gt; </code></pre> <p>Refs:<br> svnrevision: <a href="http://svnbook.red-bean.com/en/1.1/re57.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.1/re57.html</a><br> svn info <a href="http://svnbook.red-bean.com/en/1.1/re13.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.1/re13.html</a><br> subclipse svn task: <a href="http://subclipse.tigris.org/svnant/svn.html" rel="noreferrer">http://subclipse.tigris.org/svnant/svn.html</a><br> svn client: <a href="http://svnkit.com/" rel="noreferrer">http://svnkit.com/</a></p>
[ { "answer_id": 171859, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "svn info" }, { "answer_id": 171927, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": true, "text": "<exec executable=\"svnversion\" outputproperty=\"svnversion\" failonerror=\"true\">\n <env key=\"path\" value=\"/usr/bin\"/>\n <arg value=\"--no-newline\" />\n</exec>\n <!-- myapp-r1234.ear -->\n<property name=\"ear\" value=\"myapp-r${svnrevision}.ear\" />\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16352/" ]
171,835
<p><a href="http://oreilly.com/catalog/9780596515829/" rel="nofollow noreferrer">Python for Unix and Linux System Administration</a> is aimed at sysadmins. Any other favorites besides this.</p>
[ { "answer_id": 1149731, "author": "ghostdog74", "author_id": 131527, "author_profile": "https://Stackoverflow.com/users/131527", "pm_score": 3, "selected": false, "text": " for line in open(\"file\"):\n print line\n f=open(\"file\")\n for line in f:\n print line\n f.close()\n f=open(\"file\")\n while 1:\n line=f.readline()\n if not line: break\n print line\n f.close()\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11065/" ]
171,849
<p>I have a program that spits out an Excel workbook in Excel 2003 XML format. It works fine with one problem, I cannot get the column widths to set automatically.</p> <p>A snippet of what I produce:</p> <pre><code> &lt;Table &gt; &lt;Column ss:AutoFitWidth="1" ss:Width="2"/&gt; &lt;Row ss:AutoFitHeight="0" ss:Height="14.55"&gt; &lt;Cell ss:StyleID="s62"&gt;&lt;Data ss:Type="String"&gt;Database&lt;/Data&gt;&lt;/Cell&gt; </code></pre> <p>This does not set the column to autofit. I have tried not setting width, I have tried many things and I am stuck.</p> <p>Thanks.</p>
[ { "answer_id": 26046306, "author": "Mathijs Beentjes", "author_id": 4080802, "author_profile": "https://Stackoverflow.com/users/4080802", "pm_score": 0, "selected": false, "text": " <xsl:for-each select=\"/*/*[1]/*\">\n <Column>\n <xsl:variable name=\"columnNum\" select=\"position()\"/>\n <xsl:for-each select=\"/*/*/*[position()=$columnNum]\">\n <xsl:sort select=\"concat(string-length(string-length(.)),string-length(.))\" order=\"descending\"/>\n <xsl:if test=\"position()=1\">\n <xsl:if test=\"string-length(.) &lt; 201\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"5.25 * (string-length(.)+2)\"/>\n </xsl:attribute>\n </xsl:if>\n <xsl:if test=\"string-length(.) &gt; 200\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"1000\"/>\n </xsl:attribute>\n </xsl:if>\n </xsl:if>\n <xsl:if test = \"local-name() = 'Sorteer'\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"0\"/>\n </xsl:attribute>\n </xsl:if>\n </xsl:for-each>\n </Column>\n </xsl:for-each>\n <xsl:sort select=\"concat(string-length(string-length(.)),string-length(.))\" order=\"descending\"/>\n <xsl:sort select=\"string-length(.)\" order=\"descending\"/>\n <xsl:if test=\"string-length(.) &lt; 201\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"5.25 * (string-length(.)+2)\"/>\n </xsl:attribute>\n </xsl:if>\n <xsl:if test=\"string-length(.) &gt; 200\">\n <xsl:attribute name=\"ss:Width\">\n <xsl:value-of select=\"1000\"/>\n </xsl:attribute>\n </xsl:if>\n <xsl:value-of select=\"5.25 * Min((string-length(.)+2),200)\"/>\n" }, { "answer_id": 45016090, "author": "m.nachury", "author_id": 8282397, "author_profile": "https://Stackoverflow.com/users/8282397", "pm_score": 0, "selected": false, "text": "Dim colsTmp as ArrayList '(of Arraylist(of String))\nDim cols as Arraylist '(of Integer) Max size of cols\n'Whe populate the Arraylist\nDim width As Integer\n'For each column\nFor i As Integer = 0 To colsTmp.Count - 1\n 'Whe sort cells by the length of their String\n colsTmp(i) = (From f In CType(colsTmp(i), String()) Order By f.Length).ToArray\n Dim deb As Integer = 0\n 'If they are more than a 100 cells whe only take the biggest 10%\n If colsTmp(i).length > 100 Then\n deb = colsTmp(i).length * 0.9\n End If\n 'For each cell taken\n For j As Integer = deb To colsTmp(i).length - 1\n 'Whe messure the lenght with the good font and size\n width = Windows.Forms.TextRenderer.MeasureText(colsTmp(i)(j), font).Width\n 'Whe convert it to \"excel lenght\"\n width = (width / 1.42) + 10\n 'Whe update the max Width\n If width > cols(i) Then cols(i) = width\n Next\nNext\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
171,855
<p>I want to update a list of storage devices as the user inserts USB keys, adds external disks and mounts disk images. IOKit's IOServiceAddInterestNotification looks like the way to go, but the obvious use of registering general interest in kIOMediaClass only gives you notifications for unmounting of volumes and then only sometimes.</p> <p>What's the right way to do this?</p>
[ { "answer_id": 171973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "/Volumes" }, { "answer_id": 194691, "author": "Rhythmic Fistman", "author_id": 22147, "author_profile": "https://Stackoverflow.com/users/22147", "pm_score": 3, "selected": true, "text": "DARegisterDiskAppearedCallback DARegisterDiskDisappearedCallback DARegisterDiskDescriptionChangedCallback DASession" }, { "answer_id": 8790344, "author": "Orwellophile", "author_id": 912236, "author_profile": "https://Stackoverflow.com/users/912236", "pm_score": 1, "selected": false, "text": "File: USBNotificationExample.c\n\nDescription: This sample demonstrates how to use IOKitLib and IOUSBLib to set up asynchronous\n callbacks when a USB device is attached to or removed from the system.\n It also shows how to associate arbitrary data with each device instance.\n matchingDict = IOServiceMatching(kIOUSBDeviceClassName); // Interested in instances of class\n // IOUSBDevice and its subclasses\n void DeviceAdded(void *refCon, io_iterator_t iterator)\n{\n kern_return_t kr;\n io_service_t usbDevice;\n IOCFPlugInInterface **plugInInterface=NULL;\n SInt32 score;\n HRESULT res; \n\n while ( (usbDevice = IOIteratorNext(iterator)) )\n {\n io_name_t deviceName;\n CFStringRef deviceNameAsCFString;\n MyPrivateData *privateDataRef = NULL;\n UInt32 locationID;\n\n printf(\"Device 0x%08x added.\\n\", usbDevice);\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22147/" ]
171,862
<p>When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:</p> <pre><code>namespace Lib { class A { }; A operator+(const A&amp;, const A&amp;); } // namespace Lib </code></pre> <p>or the global namespace</p> <pre><code>namespace Lib { class A { }; } // namespace Lib Lib::A operator+(const Lib::A&amp;, const Lib::A&amp;); </code></pre> <p>From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?</p>
[ { "answer_id": 171881, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "namespace Lib {\n\nclass A {\npublic:\n A operator+(const A&);\n};\n\n} // namespace Lib\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78437/" ]
171,868
<p>When you take your first look at an Oracle database, one of the first questions is often "where's the alert log?". Grid Control can tell you, but its often not available in the environment.</p> <p>I posted some bash and Perl scripts to find and tail the alert log <a href="http://tardate.blogspot.com/2007/04/find-and-tail-oracle-alert-log.html" rel="nofollow noreferrer">on my blog</a> some time back, and I'm surprised to see that post still getting lots of hits.</p> <p>The technique used is to lookup background_dump_dest from v$parameter. But I only tested this on Oracle Database 10g.</p> <p>Is there a better approach than this? And does anyone know if this still works in 11g?</p>
[ { "answer_id": 172936, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 2, "selected": false, "text": "File::Tail::App" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6329/" ]
171,873
<p>I try to write KSH script for processing a file consisting of name-value pairs, several of them on each line.</p> <p>Format is:</p> <pre><code>NAME1 VALUE1,NAME2 VALUE2,NAME3 VALUE3, etc </code></pre> <p>Suppose I write:</p> <pre><code>read l IFS="," set -A nvls $l echo "$nvls[2]" </code></pre> <p>This will give me second name-value pair, nice and easy. Now, suppose that the task is extended so that values could include commas. They should be escaped, like this:</p> <pre><code>NAME1 VALUE1,NAME2 VALUE2_1\,VALUE2_2,NAME3 VALUE3, etc </code></pre> <p>Obviously, my code no longer works, since "read" strips all quoting and second element of array will be just "NAME2 VALUE2_1". </p> <p>I'm stuck with older ksh that does not have "read -A array". I tried various tricks with "read -r" and "eval set -A ....", to no avail. I can't use "read nvl1 nvl2 nvl3" to do unescaping and splitting inside read, since I dont know beforehand how many name-value pairs are in each line.</p> <p>Does anyone have a useful trick up their sleeve for me?</p> <p>PS I know that I have do this in a nick of time in Perl, Python, even in awk. However, I have to do it in ksh (... or die trying ;)</p>
[ { "answer_id": 171945, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "sed -e 's/\\([^\\]\\),/\\1\\\n/g;s/$/\\\n/\n NAME1.1 VALUE1.1\nNAME1.2 VALUE1.2_1\\,VALUE1.2_2\nNAME1.3 VALUE1.3\n<empty line>\nNAME2.1 VALUE2.1\n<second record continues>\n while read name value ; do\n echo \"$name => $value\"\ndone\n" }, { "answer_id": 249153, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": true, "text": "\\, read l\nl=${l//\\\\,/!!}\nIFS=\",\"\nset -A nvls $l\nunset IFS\necho ${nvls[2]/!!/,}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10105/" ]
171,917
<h2>Context:</h2> <p>A while ago, I stumbled upon this 2001 DDJ article by Alexandrescu: <a href="http://www.ddj.com/cpp/184403799" rel="noreferrer">http://www.ddj.com/cpp/184403799</a></p> <p>It's about comparing various ways to initialized a buffer to some value. Like what "memset" does for single-byte values. He compared various implementations (memcpy, explicit "for" loop, duff's device) and did not really find the best candidate across all dataset sizes and all compilers.</p> <p>Quote:</p> <blockquote> <p>There is a very deep, and sad, realization underlying all this. We are in 2001, the year of the Spatial Odyssey. (...) Just step out of the box and look at us — after 50 years, we're still not terribly good at filling and copying memory.</p> </blockquote> <h2>Question:</h2> <ol> <li>does anyone have more recent information about this problem ? Do recent GCC and Visual C++ implementations perform significantly better than 7 years ago ? <li>I'm writing code that has a lifetime of 5+ (probably 10+) years and that will process arrays' sizes from a few bytes to hundred of megabytes. I can't assume that my choices now will still be optimal in 5 years. What should I do: <ul> <li>a) use the system's memset (or equivalent) and forget about optimal performance or assume the runtime and compiler will handle this for me. <li>b) benchmark once and for all on various array sizes and compilers and switch at runtime between several routines. <li>c) run the benchmark at program initialization and switch at runtime based on accurate (?) data. </ul> </ol> <p>Edit: I'm working on image processing software. My array items are PODs and every millisecond counts !</p> <p>Edit 2: Thanks for the first answers, here are some additional informations:<ul><li>Buffer initialization may represent 20%-40% of total runtime of some algorithms. <li>The platform may vary in the next 5+ years, although it will stay in the "fastest CPU money can buy from DELL" category. Compilers will be some form of GCC and Visual C++. No embedded stuff or exotic architectures on the radar<li>I'd like to hear from people who had to update their software when MMX and SSE appeared, since I'll have to do the same when "SSE2015" becomes available... :) </ul></p>
[ { "answer_id": 172489, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 3, "selected": false, "text": "for" }, { "answer_id": 173572, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "memset void memset (void *memory, size_t size, byte value)\n{\n}\n memset" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20055/" ]
171,924
<p>Is it possible to check a bash script syntax without executing it?</p> <p>Using Perl, I can run <code>perl -c 'script name'</code>. Is there any equivalent command for bash scripts?</p>
[ { "answer_id": 171932, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 10, "selected": true, "text": "bash -n scriptname\n ech hello echo hello" }, { "answer_id": 4874883, "author": "Jeevan", "author_id": 600032, "author_profile": "https://Stackoverflow.com/users/600032", "pm_score": 5, "selected": false, "text": "sh -n script-name \n echo $? 0" }, { "answer_id": 10721734, "author": "Diego Tercero", "author_id": 2046272, "author_profile": "https://Stackoverflow.com/users/2046272", "pm_score": 5, "selected": false, "text": "set -u \n #!/bin/sh\nset -u\nmessage=hello\necho $mesage\n $ check_init.sh\n" }, { "answer_id": 21183850, "author": "mug896", "author_id": 1330706, "author_profile": "https://Stackoverflow.com/users/1330706", "pm_score": 2, "selected": false, "text": "set -x\nfor i in {1..10}; do\n let i=i+1\n : i=$i\ndone\nset - \n" }, { "answer_id": 45483537, "author": "Gerald Hughes", "author_id": 3264998, "author_profile": "https://Stackoverflow.com/users/3264998", "pm_score": 3, "selected": false, "text": "find find . -name '*.sh' -print0 | xargs -0 -P\"$(nproc)\" -I{} bash -n \"{}\"" }, { "answer_id": 57053947, "author": "E Ciotti", "author_id": 415032, "author_profile": "https://Stackoverflow.com/users/415032", "pm_score": 1, "selected": false, "text": "bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \\; 2>&1 > /dev/null)\n if [ \"$bashErrLines\" != \"\" ]; then \n # at least one sh file in the bin dir has a syntax error\n echo $bashErrLines; \n exit; \n fi\n" }, { "answer_id": 68978644, "author": "Mike", "author_id": 16783589, "author_profile": "https://Stackoverflow.com/users/16783589", "pm_score": 2, "selected": false, "text": "set -o noexec\n set +o noexec\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
171,928
<p>I am using the <a href="https://jqueryui.com/dialog/" rel="noreferrer"><code>jquery-ui-dialog</code></a> plugin</p> <p>I am looking for way to refresh the page when in some circumstances when the dialog is closed.</p> <p>Is there a way to capture a close event from the dialog?</p> <p>I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner.</p>
[ { "answer_id": 172000, "author": "Brownie", "author_id": 6600, "author_profile": "https://Stackoverflow.com/users/6600", "pm_score": 9, "selected": true, "text": " $('div#popup_content').on('dialogclose', function(event) {\n alert('closed');\n });\n" }, { "answer_id": 172506, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 8, "selected": false, "text": "dialog = $('#dialog').dialog({\n modal: true,\n autoOpen: false,\n width: 700,\n height: 500,\n minWidth: 700,\n minHeight: 500,\n position: [\"center\", 200],\n close: CloseFunction,\n overlay: {\n opacity: 0.5,\n background: \"black\"\n }\n});\n close: CloseFunction" }, { "answer_id": 1706313, "author": "Mo Ming C", "author_id": 207599, "author_profile": "https://Stackoverflow.com/users/207599", "pm_score": 5, "selected": false, "text": "$(\"#dialog\").dialog({\n autoOpen: false,\n resizable: false,\n width: 400,\n height: 140,\n modal: true, \n buttons: {\n \"SUBMIT\": function() { \n $(\"form\").submit();\n }, \n \"CANCEL\": function() { \n $(this).dialog(\"close\");\n } \n },\n close: function() {\n alert('close');\n }\n});\n" }, { "answer_id": 6371397, "author": "Alexei", "author_id": 801390, "author_profile": "https://Stackoverflow.com/users/801390", "pm_score": 2, "selected": false, "text": "$(\"#dialog\").live('pagehide', function(event, ui) {\n $(this).hide();\n});\n" }, { "answer_id": 6751789, "author": "morttan", "author_id": 852580, "author_profile": "https://Stackoverflow.com/users/852580", "pm_score": 3, "selected": false, "text": "$('#dialog').live(\"dialogclose\", function(){\n //code to run on dialog close\n});\n" }, { "answer_id": 11116841, "author": "Umair Noor", "author_id": 1300558, "author_profile": "https://Stackoverflow.com/users/1300558", "pm_score": 4, "selected": false, "text": "$(\"#dialog\").dialog({\n autoOpen: false,\n resizable: true,\n height: 400,\n width: 150,\n position: 'center',\n title: 'Term Sheet',\n beforeClose: function(event, ui) { \n console.log('Event Fire');\n },\n modal: true,\n buttons: {\n \"Submit\": function () {\n $(this).dialog(\"close\");\n },\n \"Cancel\": function () {\n $(this).dialog(\"close\");\n }\n }\n });\n" }, { "answer_id": 24798789, "author": "Taksh", "author_id": 3828576, "author_profile": "https://Stackoverflow.com/users/3828576", "pm_score": 5, "selected": false, "text": "$( \"#dialogueForm\" ).dialog({\n autoOpen: false,\n height: \"auto\",\n width: \"auto\",\n modal: true,\n my: \"center\",\n at: \"center\",\n of: window,\n close : function(){\n // functionality goes here\n } \n });\n" }, { "answer_id": 26839292, "author": "Disper", "author_id": 799750, "author_profile": "https://Stackoverflow.com/users/799750", "pm_score": 3, "selected": false, "text": "on() bind() $('div#dialog').on('dialogclose', function(event) {\n //custom logic fired after dialog is closed. \n});\n" }, { "answer_id": 40784613, "author": "Mehdi Roostaeian", "author_id": 5321043, "author_profile": "https://Stackoverflow.com/users/5321043", "pm_score": 3, "selected": false, "text": "close: function(e){\n //do something\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ]
171,948
<p>I've been hearing a lot about about how the new version of VMWare Fusion can run virtual operating systems in "headless mode". </p> <p>A Google search makes it clear that other virtualisation products also have similar features, however, I have not been able to find a good description of what this actually means? What is happening when you do this?</p>
[ { "answer_id": 171951, "author": "Binarytales", "author_id": 319, "author_profile": "https://Stackoverflow.com/users/319", "pm_score": 2, "selected": false, "text": "defaults write com.vmware.fusion fluxCapacitor -bool YES\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ]
171,952
<p>Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect?</p> <p>To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed.</p> <p>Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed.</p> <p>I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this.</p>
[ { "answer_id": 171955, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 4, "selected": false, "text": "java.lang.Object#finalize java.lang.Runtime#runFinalizersOnExit(boolean)" }, { "answer_id": 171956, "author": "Shimi Bandiel", "author_id": 15100, "author_profile": "https://Stackoverflow.com/users/15100", "pm_score": 3, "selected": false, "text": "finalize() finalize() try{...} finally{...}" }, { "answer_id": 171957, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 10, "selected": true, "text": "finalize" }, { "answer_id": 172011, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 5, "selected": false, "text": "Resource r = new Resource();\ntry {\n //work\n} finally {\n r.dispose();\n}\n" }, { "answer_id": 1328823, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " * Called by the browser or applet viewer to inform\n * this applet that it is being reclaimed and that it should destroy\n * any resources that it has allocated. The stop() method\n * will always be called before destroy().\n" }, { "answer_id": 8351435, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 7, "selected": false, "text": "try (BufferedReader br = new BufferedReader(new FileReader(path))) {\n System.out.println(br.readLine());\n} catch (Exception e) {\n ...\n} finally {\n ...\n}\n BufferedReader.close() AutoCloseable finalize finalize" }, { "answer_id": 11724589, "author": "waku", "author_id": 1563393, "author_profile": "https://Stackoverflow.com/users/1563393", "pm_score": 5, "selected": false, "text": "try-with-resources public class Closeable implements AutoCloseable {\n @Override\n public void close() {\n System.out.println(\"closing...\"); \n }\n public static void main(String[] args) {\n try (Closeable c = new Closeable()) {\n System.out.println(\"trying...\"); \n throw new Exception(\"throwing...\"); \n }\n catch (Exception e) {\n System.out.println(\"catching...\"); \n }\n finally {\n System.out.println(\"finalizing...\"); \n } \n }\n}\n c.close() try catch finally finalize() close() finally" }, { "answer_id": 16613662, "author": "ChristianGLong", "author_id": 1718739, "author_profile": "https://Stackoverflow.com/users/1718739", "pm_score": -1, "selected": false, "text": "public myDestructor() {\n\nvariableA = 0; //INT\nvariableB = 0.0; //DOUBLE & FLOAT\nvariableC = \"NO NAME ENTERED\"; //TEXT & STRING\nvariableD = false; //BOOL\n\n}\n" }, { "answer_id": 37214353, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 3, "selected": false, "text": "finalize ShutdownHook finalize() finalize() finalize Exception System.runFinalization(true) Runtime.getRuntime().runFinalization(true) finalize() public void addShutdownHook(Thread hook)\n System.exit SIGKILL TerminateProcess try{} catch{} finally{} finally(} finally{} Exception Throwable" }, { "answer_id": 40410576, "author": "mike rodent", "author_id": 595305, "author_profile": "https://Stackoverflow.com/users/595305", "pm_score": 2, "selected": false, "text": "Closeable close Bag Closeables accessor.getPlaypen().closeCloseables();\naccessor.setPlaypen( new Playpen() );\n closeCloseables CountdownLatch Runnables Callables Playpen" }, { "answer_id": 41362640, "author": "Alexey", "author_id": 126529, "author_profile": "https://Stackoverflow.com/users/126529", "pm_score": 2, "selected": false, "text": "@Cleanup\nResourceClass resource = new ResourceClass();\n try-finally resource.close() resource.dispose() @Cleanup(\"dispose\")\nResourceClass resource = new ResourceClass();\n" }, { "answer_id": 57189001, "author": "Kaan", "author_id": 11374957, "author_profile": "https://Stackoverflow.com/users/11374957", "pm_score": 2, "selected": false, "text": "System.exit() Runtime.getRuntime().exit() System.runFinalization() System.runFinalizersOnExit()" }, { "answer_id": 70789843, "author": "Markus Schulte", "author_id": 1645517, "author_profile": "https://Stackoverflow.com/users/1645517", "pm_score": 1, "selected": false, "text": "@javax.enterprise.context.ApplicationScoped\npublic class Foo {\n\n @javax.annotation.PreDestroy\n public void cleanup() {\n // do your cleanup \n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18500/" ]
171,962
<p>I'm storing all localizable strings in a <code>ResourceDictionary</code> (in <code>App.xaml</code>) and assign those via the <code>StaticResource</code> markup extension to <code>TextBlock.Text</code>, <code>Button.Content</code> etc.</p> <p>In Beta 2 and RC0, <em>sometimes</em> parsing the XAML in <code>InitializeComponent()</code> will fail with an <code>AG_E_PARSER_BAD_PROPERTY_VALUE</code> on the line and position where I set the attribute value to the <code>StaticResource</code>.</p> <p>It only happens sometimes: When restarting the app, it parses and displays without any problems. The same interface code works for days or weeks, then it happens again.</p> <p>Any ideas?</p>
[ { "answer_id": 179607, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 2, "selected": false, "text": "Text=\"{StaticResource bleh}\" \n Text = \"{StaticResource bleh}\"\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23222/" ]
171,970
<p>When logging in C#, how can I learn the name of the method that called the current method? I know all about <code>System.Reflection.MethodBase.GetCurrentMethod()</code>, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like <code>Assembly.GetCallingAssembly()</code> but for methods.</p>
[ { "answer_id": 171974, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 10, "selected": true, "text": "using System.Diagnostics;\n// Get call stack\nStackTrace stackTrace = new StackTrace(); \n// Get calling method name\nConsole.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);\n (new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name\n" }, { "answer_id": 172015, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 6, "selected": false, "text": "System.Diagnostics.StackTrace System.Diagnostics.StackFrame GetMethod() System.Reflection.MethodBase" }, { "answer_id": 172487, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": false, "text": "new StackFrame(1).GetMethod().Name;\n new StackFrame(1) .GetFrame(1) null" }, { "answer_id": 172558, "author": "jesal", "author_id": 20092, "author_profile": "https://Stackoverflow.com/users/20092", "pm_score": 3, "selected": false, "text": "StackFrame frame = new StackFrame(1);\nframe.GetMethod().Name; //Gets the current method name\n\nMethodBase method = frame.GetMethod();\nmethod.DeclaringType.Name //Gets the current class name\n" }, { "answer_id": 207091, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 2, "selected": false, "text": "void Foo() void Foo(string context) param" }, { "answer_id": 2932128, "author": "Flanders", "author_id": 353229, "author_profile": "https://Stackoverflow.com/users/353229", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Returns the call that occurred just before the \"GetCallingMethod\".\n/// </summary>\npublic static string GetCallingMethod()\n{\n return GetCallingMethod(\"GetCallingMethod\");\n}\n\n/// <summary>\n/// Returns the call that occurred just before the the method specified.\n/// </summary>\n/// <param name=\"MethodAfter\">The named method to see what happened just before it was called. (case sensitive)</param>\n/// <returns>The method name.</returns>\npublic static string GetCallingMethod(string MethodAfter)\n{\n string str = \"\";\n try\n {\n StackTrace st = new StackTrace();\n StackFrame[] frames = st.GetFrames();\n for (int i = 0; i < st.FrameCount - 1; i++)\n {\n if (frames[i].GetMethod().Name.Equals(MethodAfter))\n {\n if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.\n {\n str = frames[i + 1].GetMethod().ReflectedType.FullName + \".\" + frames[i + 1].GetMethod().Name;\n break;\n }\n }\n }\n }\n catch (Exception) { ; }\n return str;\n}\n" }, { "answer_id": 5197900, "author": "Orson", "author_id": 207756, "author_profile": "https://Stackoverflow.com/users/207756", "pm_score": 2, "selected": false, "text": "private static MethodBase GetCallingMethod()\n{\n return new StackFrame(2, false).GetMethod();\n}\n\nprivate static Type GetCallingType()\n{\n return new StackFrame(2, false).GetMethod().DeclaringType;\n}\n" }, { "answer_id": 9621581, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 9, "selected": false, "text": "//using System.Runtime.CompilerServices;\npublic void SendError(string Message, [CallerMemberName] string callerName = \"\") \n{ \n Console.WriteLine(callerName + \"called me.\"); \n} \n [CallerFilePath] [CallerLineNumber]" }, { "answer_id": 13496108, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 7, "selected": false, "text": "public static string WhoseThere([CallerMemberName] string memberName = \"\")\n{\n return memberName;\n}\n [Test]\npublic void Should_get_name_of_calling_method()\n{\n var methodName = CachingHelpers.WhoseThere();\n Assert.That(methodName, Is.EqualTo(\"Should_get_name_of_calling_method\"));\n}\n" }, { "answer_id": 13874947, "author": "caner", "author_id": 1829714, "author_profile": "https://Stackoverflow.com/users/1829714", "pm_score": 0, "selected": false, "text": "StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1);\nstring methodName = caller.GetMethod().Name;\n" }, { "answer_id": 16840439, "author": "smiron", "author_id": 1662637, "author_profile": "https://Stackoverflow.com/users/1662637", "pm_score": 1, "selected": false, "text": "public void MethodA()\n {\n /*\n * Method code here\n */\n }\n public void MethodA(Action helperAction)\n {\n /*\n * Method code here\n */\n }\n private MethodInfo GetCallingMethodInfo(string funcName)\n {\n return GetType().GetMethod(\n funcName.Substring(1,\n funcName.IndexOf(\"&gt;\", 1, StringComparison.Ordinal) - 1)\n );\n }\n MethodA(() => {});\n MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name);\n" }, { "answer_id": 33237690, "author": "Ivan Pinto", "author_id": 5467316, "author_profile": "https://Stackoverflow.com/users/5467316", "pm_score": 6, "selected": false, "text": "CallerFilePath CallerLineNumber CallerMemberName public void WriteLine(\n [CallerFilePath] string callerFilePath = \"\", \n [CallerLineNumber] long callerLineNumber = 0,\n [CallerMemberName] string callerMember= \"\")\n{\n Debug.WriteLine(\n \"Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}\", \n callerFilePath,\n callerLineNumber,\n callerMember);\n}\n CallerFilePathAttribute CallerLineNumberAttribute CallerMemberNameAttribute" }, { "answer_id": 33939304, "author": "Tikall", "author_id": 2470012, "author_profile": "https://Stackoverflow.com/users/2470012", "pm_score": 7, "selected": false, "text": "static void Log(object message, \n[CallerMemberName] string memberName = \"\",\n[CallerFilePath] string fileName = \"\",\n[CallerLineNumber] int lineNumber = 0)\n{\n // we'll just use a simple Console write for now \n Console.WriteLine(\"{0}({1}):{2} - {3}\", fileName, lineNumber, memberName, message);\n}\n static void Log(object message)\n{\n // frame 1, true for source info\n StackFrame frame = new StackFrame(1, true);\n var method = frame.GetMethod();\n var fileName = frame.GetFileName();\n var lineNumber = frame.GetFileLineNumber();\n\n // we'll just use a simple Console write for now \n Console.WriteLine(\"{0}({1}):{2} - {3}\", fileName, lineNumber, method.Name, message);\n}\n Time for 1,000,000 iterations with Attributes: 196 ms\nTime for 1,000,000 iterations with StackTrace: 5096 ms\n" }, { "answer_id": 37885619, "author": "Camilo Terevinto", "author_id": 2141621, "author_profile": "https://Stackoverflow.com/users/2141621", "pm_score": 4, "selected": false, "text": "internal static void WriteInformation<T>(string text, [CallerMemberName]string method = \"\")\n{\n Console.WriteLine(DateTime.Now.ToString() + \" => \" + typeof(T).FullName + \".\" + method + \": \" + text);\n}\n 6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized\n Logger.WriteInformation<MainWindow>(\"MainWindow initialized\");\n" }, { "answer_id": 53942029, "author": "Arian", "author_id": 648723, "author_profile": "https://Stackoverflow.com/users/648723", "pm_score": 2, "selected": false, "text": " public static void Call()\n {\n StackTrace stackTrace = new StackTrace();\n\n var methodName = stackTrace.GetFrame(1).GetMethod();\n var className = methodName.DeclaringType.Name.ToString();\n\n Console.WriteLine(methodName.Name + \"*****\" + className );\n }\n" }, { "answer_id": 53942589, "author": "cdev", "author_id": 827918, "author_profile": "https://Stackoverflow.com/users/827918", "pm_score": 2, "selected": false, "text": "new StackFrame(1).GetMethod().Name; [System.Runtime.CompilerServices.CallerMemberName] string callerName = \"\"" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470/" ]
171,999
<p>How can I extract the whole line in a row, for example, row 3. These data are saved in my text editor in linux. Here's my data:</p> <pre><code>1,julz,kath,shiela,angel 2,may,ann,janice,aika 3,christal,justine,kim 4,kris,allan,jc,mine </code></pre> <p>I want output like:</p> <pre><code>3,christal,justine,kim </code></pre>
[ { "answer_id": 172005, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "open $fh, \"myfile.txt\";\nmy @lines = <$fh>;\n $lines[2]" }, { "answer_id": 172017, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "$ perl -ne'print if $. == 3' your_file.txt\n $ perl -mTie::File -e'tie @lines, q(Tie::File), q(your_file.txt); \n> print $lines[2]'\n" }, { "answer_id": 172046, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "perl -ne 'if ($. == 3) {print;exit}' infile.txt\n $." }, { "answer_id": 172355, "author": "Randal Schwartz", "author_id": 22483, "author_profile": "https://Stackoverflow.com/users/22483", "pm_score": 3, "selected": false, "text": "perl -ne 'print if 3..3' <infile >outfile\n perl -F, -nae 'print if $F[0] == 3' <infile >outfile # thanks for the comment doh!\n" }, { "answer_id": 172665, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "use Tie::File;\nuse Fcntl \"O_RDONLY\";\ntie my @line, \"Tie::File\", \"yourfilename\", mode => O_RDONLY\n or die \"Couldn't open file: $!\";\nprint \"The third line is \", $line[2];\n" }, { "answer_id": 173951, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "open my $fh, '<', 'infile.txt';\nwhile (my $line = <$fh>) {\n print $line if i_want_this_line($line);\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
172,018
<p>Is there a way to exclude all svn externals when doing a recursive update?</p> <p>Is there a way to exclude only 1 of all of the svn externals when doing a recursive update?</p> <p>Basically I'd like to cut down the svn update time, and a couple of the SVN externals that I have will just about never get updated.</p>
[ { "answer_id": 172043, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 6, "selected": true, "text": "> svn update --ignore-externals\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
172,066
<p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p> <p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
[ { "answer_id": 172097, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": true, "text": "django.contrib.auth.models.User.get_profile AUTH_PROFILE_MODULE ForeignKey User get_profile ForeignKey User ForeignKey User null Photo User" }, { "answer_id": 172464, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "import random\nuser.set_password( str(random.random()) )\n" }, { "answer_id": 176825, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 2, "selected": false, "text": "AUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'userprofile.my_authenticate.MyLoginBackend', # if they fail the normal test\n )\n from django.contrib.auth.backends import ModelBackend\nfrom django.contrib.auth.models import User\n\nclass MyLoginBackend(ModelBackend):\n \"\"\"Return User record if username + (some test) is valid.\n Return None if no match.\n \"\"\"\n\n def authenticate(self, username=None, password=None, request=None):\n try:\n user = User.objects.get(username=username)\n # plus any other test of User/UserProfile, etc.\n return user # indicates success\n except User.DoesNotExist:\n return None\n # authenticate\n# class MyLoginBackend\n" }, { "answer_id": 180657, "author": "saturdayplace", "author_id": 3912, "author_profile": "https://Stackoverflow.com/users/3912", "pm_score": 0, "selected": false, "text": "UserProfile django.contrib.auth.models.User UserProfile" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25274/" ]
172,095
<p>I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc. </p> <p>I'm using the web reference in a console application. I often change something, recompile and run. Compilation is fast, but newing up the web service reference is very slow, taking some 15-20 seconds: <code> CrmService service = new CrmService(); </code> Profiling reveals that all time is spent in the SoapHttpClientProtocol constructor.</p> <p>The culprit is apparently the fact that the XML serialization code (not included in the 90k loc mentioned above) is generated at run time, before being JIT'ed. This happens during the constructor call. The wait is rather frustrating when playing around and trying things out.</p> <p>I've tried various combinations of sgen.exe, ngen and XGenPlus (which takes several hours and generates 500MB of additional code) but to no avail. I've considered implementing a Windows service that have few CrmService instances ready to dish out when needed but that seems excessive.</p> <p>Any ideas?</p>
[ { "answer_id": 172106, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 1, "selected": false, "text": "Sgen.exe Sgen" }, { "answer_id": 965857, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 6, "selected": true, "text": "_service = new VimService();\n XmlSerializer System.Xml.Serialization.* VimService XmlSerializationAssemblyAttribute wsdl.exe vim.wsdl vimService.wsdl csc /t:library /out:VimService.dll VimService.cs sgen /p VimService.dll System.Xml.Serialization.* [System.Xml.Serialization.XmlIncludeAttribute // [System.Xml.Serialization.XmlIncludeAttribute Xml.Serialization [System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = \"VimService.XmlSerializers\")] // ... Some code here ...\n[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = \"VimService.XmlSerializers\")]\npublic partial class VimService : System.Web.Services.Protocols.SoapHttpClientProtocol {\n// ... More code here csc /t:library /out:VimService.dll VimService.cs SoapDocumentMethodAttribute" }, { "answer_id": 13755462, "author": "Adam Marshall", "author_id": 1420588, "author_profile": "https://Stackoverflow.com/users/1420588", "pm_score": 0, "selected": false, "text": "SoapHttpClientProtocol this.Proxy = GlobalProxySelection.GetEmptyWebProxy();\n" }, { "answer_id": 39400236, "author": "Dragan Jovanović", "author_id": 1506226, "author_profile": "https://Stackoverflow.com/users/1506226", "pm_score": 0, "selected": false, "text": "REM if your path for wsdl, csc or sgen is missing, please add it here (it varies from machine to machine)\nset PATH=%PATH%;C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.1 Tools;C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\n\nwsdl http://localhost:57237/VIM_WS.asmx?wsdl REM create source code out of WSDL\nPowerShell.exe -ExecutionPolicy Bypass -Command \"& '%~dpn0.ps1'\" REM proces source code (remove annotations, add other annotation, put class into namespace)\ncsc /t:library /out:references\\VIM_Service.dll VIM_WS.cs REM compile source into dll\nsgen /p references\\VIM_Service.dll /force REM generate serializtion dll\n (Get-Content VIM.cs) | \n ForEach-Object { \n $_ -replace \"(?<attr>\\[global::System.Xml.Serialization.[^\\]]*\\])\", \"/*${attr}*/\" `\n -replace \"public partial class VIM\", \"[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = \"\"VIM_Service.XmlSerializers\"\")] `npublic partial class VIM\" `\n -replace \"using System;\", \"namespace Classes.WS_VIM { `n`nusing System;\"\n } |\nSet-Content VIM.cs\nAdd-Content VIM.cs \"`n}\"\n cd..\\..\ngenerateproxy\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2942/" ]
172,110
<p>How can I elegantly print the date in RFC822 format in Perl?</p>
[ { "answer_id": 172119, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 6, "selected": true, "text": "use POSIX qw(strftime);\nprint strftime(\"%a, %d %b %Y %H:%M:%S %z\", localtime(time())) . \"\\n\";\n" }, { "answer_id": 172342, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": false, "text": "use DateTime;\nprint DateTime->now()->strftime(\"%a, %d %b %Y %H:%M:%S %z\");\n\nuse DateTime::Format::Mail;\nprint DateTime::Format::Mail->format_datetime( DateTime->now() );\n\nprint DateTime->now( formatter => DateTime::Format::Mail->new() );\n DateTime->now( time_zone => $ENV{'TZ'}, ... )\n" }, { "answer_id": 40149475, "author": "Daniel Vérité", "author_id": 238814, "author_profile": "https://Stackoverflow.com/users/238814", "pm_score": 3, "selected": false, "text": "strftime %a %b man strftime day = \"Mon\" / \"Tue\" / \"Wed\" / \"Thu\" / \"Fri\" / \"Sat\" / \"Sun\"\n\nmonth = \"Jan\" / \"Feb\" / \"Mar\" / \"Apr\" / \"May\" / \"Jun\" /\n \"Jul\" / \"Aug\" / \"Sep\" / \"Oct\" / \"Nov\" / \"Dec\"\n C use POSIX qw(strftime locale_h);\n\nmy $old_locale = setlocale(LC_TIME, \"C\");\nmy $date_rfc822 = strftime(\"%a, %d %b %Y %H:%M:%S %z\", localtime(time()));\nsetlocale(LC_TIME, $old_locale);\n\nprint \"$date_rfc822\\n\";\n" }, { "answer_id": 52787169, "author": "Guido Flohr", "author_id": 5464233, "author_profile": "https://Stackoverflow.com/users/5464233", "pm_score": 0, "selected": false, "text": "POSIX::strftime() %z sub rfc822_local {\n my ($epoch) = @_;\n\n my @time = localtime $epoch;\n\n use integer;\n\n my $tz_offset = (Time::Local::timegm(@time) - $now) / 60;\n my $tz = sprintf('%s%02u%02u',\n $tz_offset < 0 ? '-' : '+',\n $tz_offset / 60, $tz_offset % 60);\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u %s',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0], $tz);\n}\n sub rfc822_gm {\n my ($epoch) = @_;\n\n my @time = gmtime $epoch;\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u +0000',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0]);\n}\n +0000" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
172,111
<p>Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible?</p>
[ { "answer_id": 172119, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 6, "selected": true, "text": "use POSIX qw(strftime);\nprint strftime(\"%a, %d %b %Y %H:%M:%S %z\", localtime(time())) . \"\\n\";\n" }, { "answer_id": 172342, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": false, "text": "use DateTime;\nprint DateTime->now()->strftime(\"%a, %d %b %Y %H:%M:%S %z\");\n\nuse DateTime::Format::Mail;\nprint DateTime::Format::Mail->format_datetime( DateTime->now() );\n\nprint DateTime->now( formatter => DateTime::Format::Mail->new() );\n DateTime->now( time_zone => $ENV{'TZ'}, ... )\n" }, { "answer_id": 40149475, "author": "Daniel Vérité", "author_id": 238814, "author_profile": "https://Stackoverflow.com/users/238814", "pm_score": 3, "selected": false, "text": "strftime %a %b man strftime day = \"Mon\" / \"Tue\" / \"Wed\" / \"Thu\" / \"Fri\" / \"Sat\" / \"Sun\"\n\nmonth = \"Jan\" / \"Feb\" / \"Mar\" / \"Apr\" / \"May\" / \"Jun\" /\n \"Jul\" / \"Aug\" / \"Sep\" / \"Oct\" / \"Nov\" / \"Dec\"\n C use POSIX qw(strftime locale_h);\n\nmy $old_locale = setlocale(LC_TIME, \"C\");\nmy $date_rfc822 = strftime(\"%a, %d %b %Y %H:%M:%S %z\", localtime(time()));\nsetlocale(LC_TIME, $old_locale);\n\nprint \"$date_rfc822\\n\";\n" }, { "answer_id": 52787169, "author": "Guido Flohr", "author_id": 5464233, "author_profile": "https://Stackoverflow.com/users/5464233", "pm_score": 0, "selected": false, "text": "POSIX::strftime() %z sub rfc822_local {\n my ($epoch) = @_;\n\n my @time = localtime $epoch;\n\n use integer;\n\n my $tz_offset = (Time::Local::timegm(@time) - $now) / 60;\n my $tz = sprintf('%s%02u%02u',\n $tz_offset < 0 ? '-' : '+',\n $tz_offset / 60, $tz_offset % 60);\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u %s',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0], $tz);\n}\n sub rfc822_gm {\n my ($epoch) = @_;\n\n my @time = gmtime $epoch;\n\n my @month_names = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\n my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n return sprintf('%s, %02u %s %04u %02u:%02u:%02u +0000',\n $day_names[$time[6]], $time[3], $month_names[$time[4]],\n $time[5] + 1900, $time[2], $time[1], $time[0]);\n}\n +0000" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
172,125
<p>Memory (and resource) leaks happen. How do you make sure they don't?</p> <p>What tips &amp; techniques would you suggest to help avoid creating memory leaks in first place?</p> <p>Once you have an application that is leaking how do you track down the source of leaks?</p> <p>(Oh and please avoid the "just use GC" answer. Until the iPhone supports GC this isn't a valid answer, and even then - it is possible to leak resources and memory on GC)</p>
[ { "answer_id": 172243, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 4, "selected": false, "text": "cd scan-build -k -V xcodebuild" }, { "answer_id": 172270, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 3, "selected": false, "text": "init* dealloc retain release dealloc retain copy" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23113/" ]
172,130
<p>Is there a way to stop the path showing in a source code tab in Visual Studio 2008?</p> <p>Currently when developing an ASP.NET site, I get the path from the root plus the filename - truncated when it gets too long. So something like:</p> <blockquote> <p>MyDir/MyPage.aspx</p> </blockquote> <p>for a short path and filename, or:</p> <blockquote> <p>MyDir/MyLong...yPage.aspx</p> </blockquote> <p>for a longer path and filename.</p> <p>I'd prefer to see just the filename (ie just MyPage.aspx), allowing more tabs to show at once and making it easier to see which files I have open without using the drop-down list or Crtl-Tab to show the full set.</p> <p>In VS2005, I just get the filename - no path however long it is. Oddly in VS2003 I get the path and filename. I've scoured the options and I can't find a setting that lets me change what appears in the tabs. Searching suggests that other people have similar issues (although which version it occurs in appears to differ) but no-one could identify an option to change what appears.</p> <p>Can anyone point me in the right direction to get rid of the paths in the tabs (or confirm that it can't be changed to save me wasting more time searching)?</p>
[ { "answer_id": 172243, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 4, "selected": false, "text": "cd scan-build -k -V xcodebuild" }, { "answer_id": 172270, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 3, "selected": false, "text": "init* dealloc retain release dealloc retain copy" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4733/" ]
172,151
<p>I want to write a program in which plays an audio file that reads a text. I want to highlite the current syllable that the audiofile plays in green and the rest of the current word in red. What kind of datastructure should I use to store the audio file and the information that tells the program when to switch to the next word/syllable?</p>
[ { "answer_id": 221712, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 3, "selected": true, "text": "{\\K132}Unmei {\\K34}no {\\K54}tobira\n{\\K60}{\\K132}yukkuri {\\K36}to {\\K142}hirakareta\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25282/" ]
172,175
<p>Here's my code in a gridview that is bound at runtime:</p> <pre><code>... &lt;asp:templatefield&gt; &lt;edititemtemplate&gt; &lt;asp:dropdownlist runat="server" id="ddgvOpp" /&gt; &lt;/edititemtemplate&gt; &lt;itemtemplate&gt; &lt;%# Eval("opponent.name") %&gt; &lt;/itemtemplate&gt; &lt;/asp:templatefield&gt; ... </code></pre> <p>I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:</p> <pre><code>protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) //skip header row { DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp"); BindOpponentDD(ddOpp); } } </code></pre> <p>Where <code>BindOpponentDD()</code> is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?</p> <p>Thanks so much in advance...</p>
[ { "answer_id": 172220, "author": "Jason", "author_id": 7173, "author_profile": "https://Stackoverflow.com/users/7173", "pm_score": 4, "selected": true, "text": "if (myGridView.EditIndex == e.Row.RowIndex)\n{\n //do work\n}\n" }, { "answer_id": 1198319, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (grdDevelopment.EditIndex == e.Row.RowIndex && e.Row.RowType==DataControlRowType.DataRow) \n { \n DropDownList drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl(\"ddlBuildServers\"); \n }\n}\n" }, { "answer_id": 4807544, "author": "Tom Hamming", "author_id": 412107, "author_profile": "https://Stackoverflow.com/users/412107", "pm_score": 1, "selected": false, "text": "<asp:ObjectDataSource ID=\"objInfo\" runat=\"server\" SelectMethod=\"GetData\" TypeName=\"MyTypeName\">\n<SelectParameters>\n <asp:SessionParameter Name=\"MyID\" SessionField=\"MID\" Type=\"Int32\" />\n</SelectParameters>\n <asp:TemplateField HeaderText=\"My Info\" SortExpression=\"MyInfo\">\n <EditItemTemplate>\n <asp:DropDownList ID=\"ddlEditMyInfo\" runat=\"server\" DataSourceID=\"objInfo\" DataTextField=\"MyInfo\" DataValueField=\"MyInfoID\" SelectedValue='<%#Bind(\"ID\") %>' />\n </EditItemTemplate>\n <ItemTemplate>\n <span><%#Eval(\"MyInfo\") %></span>\n </ItemTemplate>\n </asp:TemplateField>\n <asp:TemplateField>\n <ItemTemplate>\n <asp:ImageButton ID=\"ibtnDelete\" runat=\"server\" ImageUrl=\"~/images/delete.gif\" AlternateText=\"Delete\" CommandArgument='<%#Eval(\"UniqueID\") %>' CommandName=\"Delete\" />\n <asp:ImageButton ID=\"ibtnEdit\" runat=\"server\" ImageUrl=\"~/images/edit.gif\" AlternateText=\"Edit\" CommandArgument='<%#Eval(\"MyID\") %>' CommandName=\"Edit\" />\n </ItemTemplate>\n <EditItemTemplate>\n <asp:ImageButton ID=\"ibtnUpdate\" runat=\"server\" ImageUrl=\"~/images/update.gif\" AlternateText=\"Update\" CommandArgument='<%#Eval(\"UniqueID\") %>' CommandName=\"Update\" />\n <asp:ImageButton ID=\"ibtnCancel\" runat=\"server\" ImageUrl=\"~/images/cancel.gif\" AlternateText=\"Cancel\" CommandName=\"Cancel\" />\n </EditItemTemplate>\n </asp:TemplateField>\n void grdOverrides_RowCommand(object sender, GridViewCommandEventArgs e)\n {\n if (e.CommandName == \"Edit\")\n Session[\"MID\"] = Int32.Parse(e.CommandArgument.ToString());\n }\n" }, { "answer_id": 8703063, "author": "Amol", "author_id": 982692, "author_profile": "https://Stackoverflow.com/users/982692", "pm_score": 2, "selected": false, "text": "if(gridView.EditIndex == e.Row.RowIndex && e.Row.RowType == DataControlRowType.DataRow)\n{\n // FindControl\n // And populate it\n}\n" }, { "answer_id": 21546548, "author": "Riki_VaL", "author_id": 2746112, "author_profile": "https://Stackoverflow.com/users/2746112", "pm_score": 0, "selected": false, "text": "<asp:TemplateField HeaderText=\"garantia\" SortExpression=\"garantia\">\n <EditItemTemplate>\n <asp:DropDownList ID=\"ddgvOpp\" runat=\"server\" SelectedValue='<%# Bind(\"opponent.name\") %>'>\n <asp:ListItem Text=\"Si\" Value=\"True\"></asp:ListItem>\n <asp:ListItem Text=\"No\" Value=\"False\"></asp:ListItem>\n </asp:DropDownList>\n </EditItemTemplate>\n <ItemTemplate>\n <asp:Label ID=\"Label1\" runat=\"server\" Text='<%# Bind(\"opponent.name\") %>'></asp:Label>\n </ItemTemplate>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173/" ]
172,176
<p>What is the best way to deal with storing and indexing URL's in SQL Server 2005? </p> <p>I have a WebPage table that stores metadata and content about Web Pages. I also have many other tables related to the WebPage table. They all use URL as a key. </p> <p>The problem is URL's can be very large, and using them as a key makes the indexes larger and slower. How much I don't know, but I have read many times using large fields for indexing is to be avoided. Assuming a URL is nvarchar(400), they are enormous fields to use as a primary key.</p> <p>What are the alternatives? </p> <p>How much pain would there likely to be with using URL as a key instead of a smaller field.</p> <p>I have looked into the WebPage table having a identity column, and then using this as the primary key for a WebPage. This keeps all the associated indexes smaller and more efficient but it makes importing data a bit of a pain. Each import for the associated tables has to first lookup what the id of a url is before inserting data in the tables.</p> <p>I have also played around with using a hash on the URL, to create a smaller index, but am still not sure if it is the best way of doing things. It wouldn't be a unique index, and would be subject to a small number of collisions. So I am unsure what foreign key would be used in this case...</p> <p>There will be millions of records about webpages stored in the database, and there will be a lot of batch updating. Also there will be a quite a lot of activity reading and aggregating the data.</p> <p>Any thoughts?</p>
[ { "answer_id": 172205, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 3, "selected": true, "text": "CREATE FUNCTION GetUrlId (@Url nvarchar(400)) \nRETURNS int\nAS BEGIN\n DECLARE @UrlId int\n SELECT @UrlId = Id FROM Url WHERE Url = @Url\n RETURN @UrlId\nEND\n INSERT INTO \n UrlHistory(UrlId, Visited, RemoteIp) \nVALUES \n (dbo.GetUrlId('http://www.stackoverflow.com/'), @Visited, @RemoteIp)\n" }, { "answer_id": 172381, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 2, "selected": false, "text": "stackoverflow.com -> com.stackoverflow \nblog.stackoverflow.com -> com.stackoverflow.blog\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1982/" ]
172,192
<p>I am working on a web-application in which dynamically-created images are used to display information. This data is currently sent to the images using a GET query-string but with more complex images and data I am worried about running into problems with the url character limit.</p> <p>I could simply pass the record ID to the image and have this query the database but this would obviously increase demand on the server. Is there some way I could add an image retrieved using POST into a HTML document?</p>
[ { "answer_id": 172292, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 0, "selected": false, "text": "<? //index.php\n $_SESSION['imagedata']['header'] = array('name'=>'Simon','backgroundcolor'=>'red');\n echo '<img src=\"image.php?image=header\">';\n // more stuff\n echo '<img src=\"image.php?image=header\">'; // same image\n?> \n <? //image.php\n switch($_GET['image']){\n case 'header':\n if(isSet($_SESSION['imagedata']['header'])){\n // create image using $_SESSION['imagedata']['header'] data\n // create cached image\n unset($_SESSION['imagedata']['header']);\n else if(cache_file_exists()){\n // display cached file\n }else{\n // no data, use plan B\n }\n break;\n }\n?>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16822/" ]
172,199
<p>Where can I find a list of all types of bsd style socket errors?</p>
[ { "answer_id": 172273, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 4, "selected": true, "text": "% man connect\n...\n ECONNREFUSED\n No-one listening on the remote address.\n EISCONN\n The socket is already connected.\n\n ENETUNREACH\n Network is unreachable.\n" }, { "answer_id": 173533, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 1, "selected": false, "text": "errno errno.h perror perror errno stderr if (connect())\n{\n perror(\"connect() failed in function foo\");\n ...\n}\n perror strerror strerror_r stderr" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946/" ]
172,208
<p>We're starting a large web project, mostly green field. I like the Tapestry framework for java/web solutions. I have concerns about starting a Tapestry 5 project since T5 is still in beta. However, if I understand the documentation correctly, T4 development will not be supported by T5 and up. My question: Should I begin a large project for a large company with T5? If not, with the imminent release of T5, should I ignore T4 altogether?</p>
[ { "answer_id": 371982, "author": "Chochos", "author_id": 10165, "author_profile": "https://Stackoverflow.com/users/10165", "pm_score": 3, "selected": false, "text": "@Property @Property archiveClasses" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
172,209
<p>Can perforce be adjusted so I don't need to "open files for edit"? Someone told me that this was a "feature", and that s/he guessed it could be turned off.</p>
[ { "answer_id": 172765, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "command.name.0.*=P4 edit\ncommand.0.*=p4 edit -c default $(FileNameExt)\ncommand.save.before.0.*=2\n" }, { "answer_id": 175639, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 2, "selected": true, "text": "allwrite p4 revert -a" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9987/" ]
172,223
<p>From the Apple <a href="http://developer.apple.com/internet/safari/faq.html" rel="noreferrer">developer faq</a></p> <blockquote> <p>Safari ships with a conservative cookie policy which limits cookie writes to only the pages chosen ("navigated to") by the user.</p> </blockquote> <p>By default Safari only allows cookies from sites you navigate to directly. (i.e. if you click on links with the url of that domainname).</p> <p>This means that if you load a page from your own site with an iFrame with a page from another site, that the other site is not able to set cookies. (for instance, a ticketshop). As soon as you have visited the other domain directly, the other site is able to access and change its own cookies. </p> <p>Without having access to code on the other site, how can i make the user-experience as inobtrusive as possible?</p> <p>Is there a (javascript?) way to check if the other site's cookies are already set, and accordingly, show a direct link to the other site first, if needed?</p> <p>Update:</p> <p>The HTML5 feature 'window.postmessage' seems to be a nice solution.<br> There are some jQuery libraries that might help, and compatible with most recent browsers.<br> In essence, the iFrame document sends messages, with Json, thru the window element.</p> <p>The very nice <a href="http://postmessage.freebaseapps.com" rel="noreferrer">Postmessage-plugin</a>, by daepark, which i got working.<br> and another <a href="http://benalman.com/projects/jquery-postmessage-plugin/" rel="noreferrer">jQuery postMessage</a>, by Ben Alman i found, but haven't tested.</p>
[ { "answer_id": 1032746, "author": "M.W. Felker", "author_id": 127012, "author_profile": "https://Stackoverflow.com/users/127012", "pm_score": 3, "selected": false, "text": " (parent doc) (iframe doc)\n HTML --> IFRAME <-- HTML \n ^--------|---------^\n (parent doc) (iframe doc)\n HTML --> IFRAME <-- HTML \n X\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25286/" ]
172,255
<p>I'd like to zoom and unzoom in ways the base class doesn't support.</p> <p>For instance, upon receiving a double tap.</p>
[ { "answer_id": 668166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "- (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {\n UIScrollView *scrollView = (UIScrollView*)[self superview];\n UITouch *touch = [touches anyObject];\n CGSize size;\n CGPoint point;\n\n if([touch tapCount] == 2) {\n if(![_viewController _isZoomed]) {\n point = [touch locationInView:self];\n size = [self bounds].size;\n point.x /= size.width;\n point.y /= size.height;\n\n [_viewController _setZoomed:YES];\n\n size = [scrollView contentSize];\n point.x *= size.width;\n point.y *= size.height;\n size = [scrollView bounds].size;\n point.x -= size.width / 2;\n point.y -= size.height / 2;\n [scrollView setContentOffset:point animated:NO];\n }\n else\n [_viewController _setZoomed:NO];\n }\n }\n\n}\n" }, { "answer_id": 837090, "author": "Andrey Tarantsov", "author_id": 58146, "author_profile": "https://Stackoverflow.com/users/58146", "pm_score": 4, "selected": false, "text": "viewForZoomingInScrollView: scrollViewDidEndZooming: contentView.transform = CGAffineTransformMakeScale(zoomScale, zoomScale) /*\n ZoomScrollView makes UIScrollView easier to use:\n\n - ZoomScrollView is a drop-in replacement subclass of UIScrollView\n\n - ZoomScrollView adds programmatic zooming\n (see `setZoomScale:centeredAt:animated:`)\n\n - ZoomScrollView allows you to get the current zoom scale\n (see `zoomScale` property)\n\n - ZoomScrollView handles double-tap zooming for you\n (see `zoomInOnDoubleTap`, `zoomOutOnDoubleTap`)\n\n - ZoomScrollView forwards touch events to its delegate, allowing to handle\n custom gestures easily (triple-tap? two-finger scrolling?)\n\n Drop-in replacement:\n\n You can replace `[UIScrollView alloc]` with `[ZoomScrollView alloc]` or change\n class in Interface Builder, and everything should continue to work. The only\n catch is that you should not *read* the 'delegate' property; to get your delegate,\n please use zoomScrollViewDelegate property instead. (You can set the delegate\n via either of these properties, but reading 'delegate' does not work.)\n\n Zoom scale:\n\n Reading zoomScale property returns the scale of the last scaling operation.\n If your viewForZoomingInScrollView can return different views over time,\n please keep in mind that any view you return is instantly scaled to zoomScale.\n\n Delegate:\n\n The delegate accepted by ZoomScrollView is a regular UIScrollViewDelegate,\n however additional methods from `NSObject(ZoomScrollViewDelegateMethods)` category\n will be called on your delegate if defined.\n\n Method `scrollViewDidEndZooming:withView:atScale:` is called after any 'bounce'\n animations really finish. UIScrollView often calls it earlier, violating\n the documented contract of UIScrollViewDelegate.\n\n Instead of reading 'delegate' property (which currently returns the scroll\n view itself), you should read 'zoomScrollViewDelegate' property which\n correctly returns your delegate. Setting works with either of them (so you\n can still set your delegate in the Interface Builder).\n\n */\n\n@interface ZoomScrollView : UIScrollView {\n@private\n BOOL _zoomInOnDoubleTap;\n BOOL _zoomOutOnDoubleTap;\n BOOL _zoomingDidEnd;\n BOOL _ignoreSubsequentTouches; // after one of delegate touch methods returns YES, subsequent touch events are not forwarded to UIScrollView\n float _zoomScale;\n float _realMinimumZoomScale, _realMaximumZoomScale; // as set by the user (UIScrollView's min/maxZoomScale == our min/maxZoomScale divided by _zoomScale)\n id _realDelegate; // as set by the user (UIScrollView's delegate is set to self)\n UIView *_realZoomView; // the view for zooming returned by the delegate\n UIView *_zoomWrapperView; // the disposable wrapper view actually used for zooming\n}\n\n// if both are enabled, zoom-in takes precedence unless the view is at maximum zoom scale\n@property(nonatomic, assign) BOOL zoomInOnDoubleTap;\n@property(nonatomic, assign) BOOL zoomOutOnDoubleTap;\n\n@property(nonatomic, assign) id<UIScrollViewDelegate> zoomScrollViewDelegate;\n\n@end\n\n@interface ZoomScrollView (Zooming)\n\n@property(nonatomic, assign) float zoomScale; // from minimumZoomScale to maximumZoomScale\n\n- (void)setZoomScale:(float)zoomScale animated:(BOOL)animated; // centerPoint == center of the scroll view\n- (void)setZoomScale:(float)zoomScale centeredAt:(CGPoint)centerPoint animated:(BOOL)animated;\n\n@end\n\n@interface NSObject (ZoomScrollViewDelegateMethods)\n\n// return YES to stop processing, NO to pass the event to UIScrollView (mnemonic: default is to pass, and default return value in Obj-C is NO)\n- (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;\n- (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;\n- (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;\n- (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;\n\n@end\n @interface ZoomScrollView (DelegateMethods) <UIScrollViewDelegate>\n@end\n\n@interface ZoomScrollView (ZoomingPrivate)\n- (void)_setZoomScaleAndUpdateVirtualScales:(float)zoomScale; // set UIScrollView's minimumZoomScale/maximumZoomScale\n- (BOOL)_handleDoubleTapWith:(UITouch *)touch;\n- (UIView *)_createWrapperViewForZoomingInsteadOfView:(UIView *)view; // create a disposable wrapper view for zooming\n- (void)_zoomDidEndBouncing;\n- (void)_programmaticZoomAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(UIView *)context;\n- (void)_setTransformOn:(UIView *)view;\n@end\n\n\n@implementation ZoomScrollView\n\n@synthesize zoomInOnDoubleTap=_zoomInOnDoubleTap, zoomOutOnDoubleTap=_zoomOutOnDoubleTap;\n@synthesize zoomScrollViewDelegate=_realDelegate;\n\n- (id)initWithFrame:(CGRect)frame {\n if (self = [super initWithFrame:frame]) {\n _zoomScale = 1.0f;\n _realMinimumZoomScale = super.minimumZoomScale;\n _realMaximumZoomScale = super.maximumZoomScale;\n super.delegate = self;\n }\n return self;\n}\n\n- (id)initWithCoder:(NSCoder *)aDecoder {\n if (self = [super initWithCoder:aDecoder]) {\n _zoomScale = 1.0f;\n _realMinimumZoomScale = super.minimumZoomScale;\n _realMaximumZoomScale = super.maximumZoomScale;\n super.delegate = self;\n }\n return self;\n}\n\n- (id<UIScrollViewDelegate>)realDelegate {\n return _realDelegate;\n}\n- (void)setDelegate:(id<UIScrollViewDelegate>)delegate {\n _realDelegate = delegate;\n}\n\n- (float)minimumZoomScale {\n return _realMinimumZoomScale;\n}\n- (void)setMinimumZoomScale:(float)value {\n _realMinimumZoomScale = value;\n [self _setZoomScaleAndUpdateVirtualScales:_zoomScale];\n}\n\n- (float)maximumZoomScale {\n return _realMaximumZoomScale;\n}\n- (void)setMaximumZoomScale:(float)value {\n _realMaximumZoomScale = value;\n [self _setZoomScaleAndUpdateVirtualScales:_zoomScale];\n}\n\n@end\n\n\n@implementation ZoomScrollView (Zooming)\n\n- (void)_setZoomScaleAndUpdateVirtualScales:(float)zoomScale {\n _zoomScale = zoomScale;\n // prevent accumulation of error, and prevent a common bug in the user's code (comparing floats with '==')\n if (ABS(_zoomScale - _realMinimumZoomScale) < 1e-5)\n _zoomScale = _realMinimumZoomScale;\n else if (ABS(_zoomScale - _realMaximumZoomScale) < 1e-5)\n _zoomScale = _realMaximumZoomScale;\n super.minimumZoomScale = _realMinimumZoomScale / _zoomScale;\n super.maximumZoomScale = _realMaximumZoomScale / _zoomScale;\n}\n\n- (void)_setTransformOn:(UIView *)view {\n if (ABS(_zoomScale - 1.0f) < 1e-5)\n view.transform = CGAffineTransformIdentity;\n else\n view.transform = CGAffineTransformMakeScale(_zoomScale, _zoomScale);\n}\n\n- (float)zoomScale {\n return _zoomScale;\n}\n\n- (void)setZoomScale:(float)zoomScale {\n [self setZoomScale:zoomScale animated:NO];\n}\n\n- (void)setZoomScale:(float)zoomScale animated:(BOOL)animated {\n [self setZoomScale:zoomScale centeredAt:CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2) animated:animated];\n}\n\n- (void)setZoomScale:(float)zoomScale centeredAt:(CGPoint)centerPoint animated:(BOOL)animated {\n if (![_realDelegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {\n NSLog(@\"setZoomScale called on ZoomScrollView, however delegate does not implement viewForZoomingInScrollView\");\n return;\n }\n\n // viewForZoomingInScrollView may change contentOffset, and centerPoint is relative to the current one\n CGPoint origin = self.contentOffset;\n centerPoint = CGPointMake(centerPoint.x - origin.x, centerPoint.y - origin.y);\n\n UIView *viewForZooming = [_realDelegate viewForZoomingInScrollView:self];\n if (viewForZooming == nil)\n return;\n\n if (animated) {\n [UIView beginAnimations:nil context:viewForZooming];\n [UIView setAnimationDuration: 0.2];\n [UIView setAnimationDelegate: self];\n [UIView setAnimationDidStopSelector: @selector(_programmaticZoomAnimationDidStop:finished:context:)];\n }\n\n [self _setZoomScaleAndUpdateVirtualScales:zoomScale];\n [self _setTransformOn:viewForZooming];\n\n CGSize zoomViewSize = viewForZooming.frame.size;\n CGSize scrollViewSize = self.frame.size;\n viewForZooming.frame = CGRectMake(0, 0, zoomViewSize.width, zoomViewSize.height);\n self.contentSize = zoomViewSize;\n self.contentOffset = CGPointMake(MAX(MIN(zoomViewSize.width*centerPoint.x/scrollViewSize.width - scrollViewSize.width/2, zoomViewSize.width - scrollViewSize.width), 0),\n MAX(MIN(zoomViewSize.height*centerPoint.y/scrollViewSize.height - scrollViewSize.height/2, zoomViewSize.height - scrollViewSize.height), 0));\n\n if (animated) {\n [UIView commitAnimations];\n } else {\n [self _programmaticZoomAnimationDidStop:nil finished:nil context:viewForZooming];\n }\n}\n\n- (void)_programmaticZoomAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(UIView *)context {\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)])\n [_realDelegate scrollViewDidEndZooming:self withView:context atScale:_zoomScale];\n}\n\n- (BOOL)_handleDoubleTapWith:(UITouch *)touch {\n if (!_zoomInOnDoubleTap && !_zoomOutOnDoubleTap)\n return NO;\n if (_zoomInOnDoubleTap && ABS(_zoomScale - _realMaximumZoomScale) > 1e-5)\n [self setZoomScale:_realMaximumZoomScale centeredAt:[touch locationInView:self] animated:YES];\n else if (_zoomOutOnDoubleTap && ABS(_zoomScale - _realMinimumZoomScale) > 1e-5)\n [self setZoomScale:_realMinimumZoomScale animated:YES];\n return YES;\n}\n\n// the heart of the zooming technique: zooming starts here\n- (UIView *)_createWrapperViewForZoomingInsteadOfView:(UIView *)view {\n if (_zoomWrapperView != nil) // not sure this is really possible\n [self _zoomDidEndBouncing]; // ...but just in case cleanup the previous zoom op\n\n _realZoomView = [view retain];\n [view removeFromSuperview];\n [self _setTransformOn:_realZoomView]; // should be already set, except if this is a different view\n _realZoomView.frame = CGRectMake(0, 0, _realZoomView.frame.size.width, _realZoomView.frame.size.height);\n _zoomWrapperView = [[UIView alloc] initWithFrame:view.frame];\n [_zoomWrapperView addSubview:view];\n [self addSubview:_zoomWrapperView];\n\n return _zoomWrapperView;\n}\n\n// the heart of the zooming technique: zooming ends here\n- (void)_zoomDidEndBouncing {\n _zoomingDidEnd = NO;\n [_realZoomView removeFromSuperview];\n [self _setTransformOn:_realZoomView];\n _realZoomView.frame = _zoomWrapperView.frame;\n [self addSubview:_realZoomView];\n\n [_zoomWrapperView release];\n _zoomWrapperView = nil;\n\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)])\n [_realDelegate scrollViewDidEndZooming:self withView:_realZoomView atScale:_zoomScale];\n [_realZoomView release];\n _realZoomView = nil;\n}\n\n@end\n\n\n@implementation ZoomScrollView (DelegateMethods)\n\n- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {\n if ([_realDelegate respondsToSelector:@selector(scrollViewWillBeginDragging:)])\n [_realDelegate scrollViewWillBeginDragging:self];\n}\n\n- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)])\n [_realDelegate scrollViewDidEndDragging:self willDecelerate:decelerate];\n}\n\n- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {\n if ([_realDelegate respondsToSelector:@selector(scrollViewWillBeginDecelerating:)])\n [_realDelegate scrollViewWillBeginDecelerating:self];\n}\n\n- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)])\n [_realDelegate scrollViewDidEndDecelerating:self];\n}\n\n- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndScrollingAnimation:)])\n [_realDelegate scrollViewDidEndScrollingAnimation:self];\n}\n\n- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {\n UIView *viewForZooming = nil;\n if ([_realDelegate respondsToSelector:@selector(viewForZoomingInScrollView:)])\n viewForZooming = [_realDelegate viewForZoomingInScrollView:self];\n if (viewForZooming != nil)\n viewForZooming = [self _createWrapperViewForZoomingInsteadOfView:viewForZooming];\n return viewForZooming;\n}\n\n- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {\n [self _setZoomScaleAndUpdateVirtualScales:_zoomScale * scale];\n\n // often UIScrollView continues bouncing even after the call to this method, so we have to use delays\n _zoomingDidEnd = YES; // signal scrollViewDidScroll to schedule _zoomDidEndBouncing call\n [self performSelector:@selector(_zoomDidEndBouncing) withObject:nil afterDelay:0.1];\n}\n\n- (void)scrollViewDidScroll:(UIScrollView *)scrollView {\n if (_zoomWrapperView != nil && _zoomingDidEnd) {\n [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_zoomDidEndBouncing) object:nil];\n [self performSelector:@selector(_zoomDidEndBouncing) withObject:nil afterDelay:0.1];\n }\n\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidScroll:)])\n [_realDelegate scrollViewDidScroll:self];\n}\n\n- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {\n if ([_realDelegate respondsToSelector:@selector(scrollViewShouldScrollToTop:)])\n return [_realDelegate scrollViewShouldScrollToTop:self];\n else\n return YES;\n}\n\n- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {\n if ([_realDelegate respondsToSelector:@selector(scrollViewDidScrollToTop:)])\n [_realDelegate scrollViewDidScrollToTop:self]; \n}\n\n@end\n\n\n@implementation ZoomScrollView (EventForwarding)\n\n- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {\n id delegate = self.delegate;\n if ([delegate respondsToSelector:@selector(zoomScrollView:touchesBegan:withEvent:)])\n _ignoreSubsequentTouches = [delegate zoomScrollView:self touchesBegan:touches withEvent:event];\n if (_ignoreSubsequentTouches)\n return;\n if ([touches count] == 1 && [[touches anyObject] tapCount] == 2)\n if ([self _handleDoubleTapWith:[touches anyObject]])\n return;\n [super touchesBegan:touches withEvent:event];\n}\n\n- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {\n id delegate = self.delegate;\n if ([delegate respondsToSelector:@selector(zoomScrollView:touchesMoved:withEvent:)])\n if ([delegate zoomScrollView:self touchesMoved:touches withEvent:event]) {\n _ignoreSubsequentTouches = YES;\n [super touchesCancelled:touches withEvent:event];\n }\n if (_ignoreSubsequentTouches)\n return;\n [super touchesMoved:touches withEvent:event];\n}\n\n- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {\n id delegate = self.delegate;\n if ([delegate respondsToSelector:@selector(zoomScrollView:touchesEnded:withEvent:)])\n if ([delegate zoomScrollView:self touchesEnded:touches withEvent:event]) {\n _ignoreSubsequentTouches = YES;\n [super touchesCancelled:touches withEvent:event];\n }\n if (_ignoreSubsequentTouches)\n return;\n [super touchesEnded:touches withEvent:event];\n}\n\n- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {\n id delegate = self.delegate;\n if ([delegate respondsToSelector:@selector(zoomScrollView:touchesCancelled:withEvent:)])\n if ([delegate zoomScrollView:self touchesCancelled:touches withEvent:event])\n _ignoreSubsequentTouches = YES;\n [super touchesCancelled:touches withEvent:event];\n}\n\n@end\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22704/" ]
172,258
<p>I've written up a weekly-review GTD checklist for myself in TiddlyWiki, using <a href="http://www.tiddlytools.com/#CheckboxPlugin" rel="nofollow noreferrer">CheckboxPlugin</a>. After I'm finished with it each week, I'd like to click one link to uncheck (reset) all of the items on it, so it's ready for the next use.</p> <p>I'm storing the check information as tags on a separate tiddler page. I should be able to just erase all the tags on that page and refresh the checklist page, but I haven't been able to work out how to do that yet.</p> <p>I generally work in C, C++, and Lisp, I'm just learning about Javascript. Can anyone offer some useful pointers?</p> <p>(And before anyone suggests it, I've looked at the ChecklistScript on the same site. It doesn't use the CheckboxPlugin stuff, and isn't compatible with it.)</p>
[ { "answer_id": 178066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<html><form style=\"display:inline\">\n <input type=\"button\" value=\"clear all\" onclick=\"\n var tid='SomeTiddler';\n var list='tag1 [[tag 2]] tag3 tag4';\n var tags=list.readBracketedList();\n store.suspendNotifications();\n for (var t=0; t<tags.length; t++)\n store.setTiddlerTag(tid,false,tags[t]);\n store.resumeNotifications();\n story.refreshTiddler(tid,null,true);\n\"></form></html>\n" }, { "answer_id": 179200, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 1, "selected": true, "text": "<script label=\"(Reset All)\" title=\"Reset all items\" key=\"X\">\n var tid='WeeklyReviewStepsChecklistItems';\n store.getTiddler(tid).tags=[];\n story.refreshTiddler(tid,null,true);\n\n story.refreshTiddler('Weekly Review Steps',null,true);\n</script>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
172,262
<p>What is the difference between <code>#include</code> and <code>#import</code> in C++?</p>
[ { "answer_id": 172264, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": false, "text": "#import #import #import #pragma #import #include #include" }, { "answer_id": 172274, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 7, "selected": true, "text": "#import #include" }, { "answer_id": 723996, "author": "thatha", "author_id": 87910, "author_profile": "https://Stackoverflow.com/users/87910", "pm_score": 3, "selected": false, "text": "#import #ifndef ...\n#define ...\n#include ...\n#endif\n #import #import" }, { "answer_id": 2114036, "author": "Mike Godin", "author_id": 256305, "author_profile": "https://Stackoverflow.com/users/256305", "pm_score": 2, "selected": false, "text": "#import #import" }, { "answer_id": 66323669, "author": "Alex Vergara", "author_id": 14075508, "author_profile": "https://Stackoverflow.com/users/14075508", "pm_score": 3, "selected": false, "text": "import #include" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
172,265
<p>I've got a WCF Web Service method whose prototype is:</p> <pre><code>[OperationContract] Response&lt;List&lt;Customer&gt;&gt; GetCustomers(); </code></pre> <p>When I add the service reference to a client, Visual Studio (2005) creates a type called "ResponseOfArrayOfCustomerrleXg3IC" that is a wrapper for "Response&lt;List&lt;Customer>>". Is there any way I can control the wrapper name? ResponseOfArrayOfCustomerrleXg3IC doesn't sound very appealing...</p>
[ { "answer_id": 172349, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": -1, "selected": false, "text": "[OperationContract(Name = \"NameGoesHere\")]\nResponse<List<Customer>> GetCustomers();\n" }, { "answer_id": 172370, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 2, "selected": false, "text": "[OperationContract]\n[return: MessageParameter(Name=\"YOURNAME\")]\nResponse<List<Customer>> GetCustomers();\n" }, { "answer_id": 172671, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 5, "selected": true, "text": "DataContract [DataContract(Name = \"ResponseOf{0}\")]\npublic class Response<T>\n {0} ResponseOfArrayOfCustomer" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
172,278
<p>I have a stored procedure with the following header:</p> <pre><code>FUNCTION SaveShipment (p_user_id IN INTEGER, p_transaction_id IN INTEGER, p_vehicle_code IN VARCHAR2 DEFAULT NULL, p_seals IN VARCHAR2 DEFAULT NULL) RETURN INTEGER; </code></pre> <p>And I am having trouble running it from TOAD's Editor. I cannot run it as part of a select from dual statement because it preforms DML, but if I try the following syntax which I saw recommended on some forum:</p> <pre><code>var c integer; exec :c := orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, ''); print c; </code></pre> <p>I get:</p> <pre><code>ORA-01008: not all variables bound Details: BEGIN :c := orm_helper.orm_helper.saveshipment (9999, 31896, null, ''); END; Error at line 2 ORA-01008: not all variables bound </code></pre> <p>What's the proper syntax to run this sp manually?</p>
[ { "answer_id": 172309, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 3, "selected": true, "text": "declare\n c integer;\nbegin\n\nc:=storedProc(...parameters...);\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
172,300
<p>When using Mercurial I sometimes find that it is hard to understand the relationship between changesets when there are thousands of changesets, and sometimes ten or more active branches at any one time. Currently, I use <a href="http://www.logilab.org/project/hgview/screenshots?selected=4873" rel="noreferrer">hgview</a> which is okay, and while it makes a reasonable attempt to represent the parent relationships it is still basically one dimensional. I imagine something making use of graph visualisation programs such as <a href="http://www.graphviz.org/" rel="noreferrer">GraphViz</a> might work nicely, or perhaps something more wacky.</p> <p>Currently I'm working on projects with around 30,000 revisions, and I expect that number to grow significantly; if 100 full time developers really grok distributed version control and start committing regularly and sharing their full development history then we could end up dealing with millions of revisions. A browser which doesn't have to load the entire history in to RAM every time you want to look at it therefore becomes necessary</p> <p>I'm interested in good history browsers for any version control systems as well, especially if there is a chance I can port them to Mercurial.</p>
[ { "answer_id": 172358, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 4, "selected": true, "text": "gitk(1) git rev-list" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22668/" ]
172,302
<p>This is for a small scheduling app. I need an algorithm to efficiently compare two "schedules", find differences, and update only the data rows which have been changed, as well as entries in another table having this table as a foreign key. This is a big question, so I'll say right away I'm looking for either <strong>general advice</strong> or <strong>specific solutions</strong>.</p> <p><strong>EDIT:</strong> As suggested, I have significantly shortened the question.</p> <p>In one table, I associate resources with a span of time when they are used. </p> <p>I also have a second table (Table B) which uses the ID from Table A as a foreign key.</p> <p>The entry from Table A corresponding to Table B will have a span of time which <strong>subsumes</strong> the span of time from Table B. Not all entries in Table A will have an entry in Table B.</p> <p>I'm providing an interface for users to edit the resource schedule in Table A. They basically provide a new set of data for Table A that I need to treat as a <em>diff</em> from the version in the DB.</p> <p>If they completely remove an object from Table A that is pointed to by Table B, I want to remove the entry from Table B as well.</p> <p>So, given the following 3 sets:</p> <ul> <li>The original objects from Table A (from the DB)</li> <li>The original objects from Table B (from the DB)</li> <li>The edited set of objects from Table A (from the user, so no unique IDs)</li> </ul> <p>I need an algorithm that will:</p> <ul> <li>Leave rows in Table A and Table B untouched if no changes are needed for those objects.</li> <li>Add rows to Table A as needed.</li> <li>Remove rows from Table A and Table B as needed.</li> <li>Modify rows in Table A and Table B as needed.</li> </ul> <p>Just sorting the objects into an arrangement where I can apply the appropriate database operations is more than adequate for a solution.</p> <p>Again, please answer as <strong>specifically</strong> or <strong>generally</strong> as you like, I'm looking for advice but if someone has a complete algorithm that would just make my day. :)</p> <p><strong>EDIT:</strong> In response to lassvek, I am providing some additional detail:</p> <p>Table B's items are always contained entirely within Table A items, not merely overlapping.</p> <p><em>Importantly,</em> Table B's items are quantized so they should fall either entirely within or entirely outside. If this doesn't happen, then I have a data integrity error that I'll have to handle separately.</p> <p>For example (to use a shorthand):</p> <pre> Table A ID Resource Start End 01 Resource A 10/6 7:00AM 10/6 11:00AM 02 Resource A 10/6 1:00PM 10/6 3:00PM Table B ID Table_A_ID Start End 01 02 10/6 1:00PM 10/6 2:00PM </pre> <p>So I want the following behaviours:</p> <ul> <li>If I remove ID 02 from table A, or shorten it to 2:00PM - 3:00PM, I should remove ID 01 from Table B.</li> <li>If I extend Table A ID 01 to where it ends at 1:00PM, <strong>these two entries should be merged together into one row</strong>, and Table B ID 01 should now point to table A ID 01.</li> <li>If I remove 8:00AM-10:00AM from Table A ID 01, that entry should be split into two entries: One for 7:00AM-8:00AM, and a new entry (ID 03) for 10:00AM-11:00AM.</li> </ul>
[ { "answer_id": 174037, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": true, "text": "|---------------- A -------------------|\n |--- B ----| |--- B ---|\n |---------------- A -------------------|\n|--- B ----| |--- B ---|\n * A removed A-timespan removes all the linked timespans from B\n* An added A-timespan, what about this?\n* A shortened A-timespan removes all the linked timespans from B that now falls outside A\n* A lenghtened A-timespan, will this include all matching B-timespans now inside?\n |-------------- A1 --------------| |-------- A2 --------------|\n |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|\n |-------------- A1 ---------------------------------| |--- A2 --|\n |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|\n 1. Lengthen (update) A1\n2. Shorten and move (update) A2\n3. Re-link (update) B3 from A2 to A1 instead\n |-------------- A1 -----------------------------| |--- A2 --|\n |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --|\n |------------------ A -----------------------|\n |------- B1 -------| |------- B2 ------|\n |---| <-- I want to remove this from A\n |------------------ A1 ----| |---- A2 -----|\n |------- B1 -------| |B3| |--- B2 ---|\n |------------------ A1 ----| |---- A2 -----|\n |------- B1 -------|\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ]
172,303
<p>Is it possible to detect a valid regular expression with another regular expression? If so please give example code below.</p>
[ { "answer_id": 172312, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 8, "selected": false, "text": "try..catch" }, { "answer_id": 172316, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 11, "selected": true, "text": "/\n^ # start of string\n( # first group start\n (?:\n (?:[^?+*{}()[\\]\\\\|]+ # literals and ^, $\n | \\\\. # escaped characters\n | \\[ (?: \\^?\\\\. | \\^[^\\\\] | [^\\\\^] ) # character classes\n (?: [^\\]\\\\]+ | \\\\. )* \\]\n | \\( (?:\\?[:=!]|\\?<[=!]|\\?>)? (?1)?? \\) # parenthesis, with recursive content\n | \\(\\? (?:R|[+-]?\\d+) \\) # recursive matching\n )\n (?: (?:[?+*]|\\{\\d+(?:,\\d*)?\\}) [?+]? )? # quantifiers\n | \\| # alternative\n )* # repeat content\n) # end first group\n$ # end of string\n/\n /^((?:(?:[^?+*{}()[\\]\\\\|]+|\\\\.|\\[(?:\\^?\\\\.|\\^[^\\\\]|[^\\\\^])(?:[^\\]\\\\]+|\\\\.)*\\]|\\((?:\\?[:=!]|\\?<[=!]|\\?>)?(?1)??\\)|\\(\\?(?:R|[+-]?\\d+)\\))(?:(?:[?+*]|\\{\\d+(?:,\\d*)?\\})[?+]?)?|\\|)*)$/\n (?1) (?R) ^ # start of string\n(?:\n (?: [^?+*{}()[\\]\\\\|]+ # literals and ^, $\n | \\\\. # escaped characters\n | \\[ (?: \\^?\\\\. | \\^[^\\\\] | [^\\\\^] ) # character classes\n (?: [^\\]\\\\]+ | \\\\. )* \\]\n | \\( (?:\\?[:=!]\n | \\?<[=!]\n | \\?>\n | \\?<[^\\W\\d]\\w*>\n | \\?'[^\\W\\d]\\w*'\n )? # opening of group\n (?<N>) # increment counter\n | \\) # closing of group\n (?<-N>) # decrement counter\n )\n (?: (?:[?+*]|\\{\\d+(?:,\\d*)?\\}) [?+]? )? # quantifiers\n| \\| # alternative\n)* # repeat content\n$ # end of string\n(?(N)(?!)) # fail if counter is non-zero.\n ^(?:(?:[^?+*{}()[\\]\\\\|]+|\\\\.|\\[(?:\\^?\\\\.|\\^[^\\\\]|[^\\\\^])(?:[^\\]\\\\]+|\\\\.)*\\]|\\((?:\\?[:=!]|\\?<[=!]|\\?>|\\?<[^\\W\\d]\\w*>|\\?'[^\\W\\d]\\w*')?(?<N>)|\\)(?<-N>))(?:(?:[?+*]|\\{\\d+(?:,\\d*)?\\})[?+]?)?|\\|)*$(?(N)(?!))\n s/<this part>/.../ []()/\\ ^(?:[\\.]+)$ ^abcdefg$ [^?+*{}()[\\]\\\\|] a z ^ $ ." }, { "answer_id": 172338, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 6, "selected": false, "text": "'(' ')'" }, { "answer_id": 172363, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 8, "selected": false, "text": "[] [ ] \"\\[.*\\]\"" }, { "answer_id": 174440, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 4, "selected": false, "text": "SKIP :\n{\n \" \"\n| \"\\r\"\n| \"\\t\"\n| \"\\n\"\n}\nTOKEN : \n{\n < DIGITO: [\"0\" - \"9\"] >\n| < MAYUSCULA: [\"A\" - \"Z\"] >\n| < MINUSCULA: [\"a\" - \"z\"] >\n| < LAMBDA: \"LAMBDA\" >\n| < VACIO: \"VACIO\" >\n}\n\nIRegularExpression Expression() :\n{\n IRegularExpression r; \n}\n{\n r=Alternation() { return r; }\n}\n\n// Matchea disyunciones: ER | ER\nIRegularExpression Alternation() :\n{\n IRegularExpression r1 = null, r2 = null; \n}\n{\n r1=Concatenation() ( \"|\" r2=Alternation() )?\n { \n if (r2 == null) {\n return r1;\n } else {\n return createAlternation(r1,r2);\n } \n }\n}\n\n// Matchea concatenaciones: ER.ER\nIRegularExpression Concatenation() :\n{\n IRegularExpression r1 = null, r2 = null; \n}\n{\n r1=Repetition() ( \".\" r2=Repetition() { r1 = createConcatenation(r1,r2); } )*\n { return r1; }\n}\n\n// Matchea repeticiones: ER*\nIRegularExpression Repetition() :\n{\n IRegularExpression r; \n}\n{\n r=Atom() ( \"*\" { r = createRepetition(r); } )*\n { return r; }\n}\n\n// Matchea regex atomicas: (ER), Terminal, Vacio, Lambda\nIRegularExpression Atom() :\n{\n String t;\n IRegularExpression r;\n}\n{\n ( \"(\" r=Expression() \")\" {return r;}) \n | t=Terminal() { return createTerminal(t); }\n | <LAMBDA> { return createLambda(); }\n | <VACIO> { return createEmpty(); }\n}\n\n// Matchea un terminal (digito o minuscula) y devuelve su valor\nString Terminal() :\n{\n Token t;\n}\n{\n ( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; }\n}\n" }, { "answer_id": 2904721, "author": "PaulMcG", "author_id": 165216, "author_profile": "https://Stackoverflow.com/users/165216", "pm_score": 3, "selected": false, "text": "# \n# invRegex.py\n#\n# Copyright 2008, Paul McGuire\n#\n# pyparsing script to expand a regular expression into all possible matching strings\n# Supports:\n# - {n} and {m,n} repetition, but not unbounded + or * repetition\n# - ? optional elements\n# - [] character ranges\n# - () grouping\n# - | alternation\n#\n__all__ = [\"count\",\"invert\"]\n\nfrom pyparsing import (Literal, oneOf, printables, ParserElement, Combine, \n SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,\n Suppress, ParseResults, srange)\n\nclass CharacterRangeEmitter(object):\n def __init__(self,chars):\n # remove duplicate chars in character range, but preserve original order\n seen = set()\n self.charset = \"\".join( seen.add(c) or c for c in chars if c not in seen )\n def __str__(self):\n return '['+self.charset+']'\n def __repr__(self):\n return '['+self.charset+']'\n def makeGenerator(self):\n def genChars():\n for s in self.charset:\n yield s\n return genChars\n\nclass OptionalEmitter(object):\n def __init__(self,expr):\n self.expr = expr\n def makeGenerator(self):\n def optionalGen():\n yield \"\"\n for s in self.expr.makeGenerator()():\n yield s\n return optionalGen\n\nclass DotEmitter(object):\n def makeGenerator(self):\n def dotGen():\n for c in printables:\n yield c\n return dotGen\n\nclass GroupEmitter(object):\n def __init__(self,exprs):\n self.exprs = ParseResults(exprs)\n def makeGenerator(self):\n def groupGen():\n def recurseList(elist):\n if len(elist)==1:\n for s in elist[0].makeGenerator()():\n yield s\n else:\n for s in elist[0].makeGenerator()():\n for s2 in recurseList(elist[1:]):\n yield s + s2\n if self.exprs:\n for s in recurseList(self.exprs):\n yield s\n return groupGen\n\nclass AlternativeEmitter(object):\n def __init__(self,exprs):\n self.exprs = exprs\n def makeGenerator(self):\n def altGen():\n for e in self.exprs:\n for s in e.makeGenerator()():\n yield s\n return altGen\n\nclass LiteralEmitter(object):\n def __init__(self,lit):\n self.lit = lit\n def __str__(self):\n return \"Lit:\"+self.lit\n def __repr__(self):\n return \"Lit:\"+self.lit\n def makeGenerator(self):\n def litGen():\n yield self.lit\n return litGen\n\ndef handleRange(toks):\n return CharacterRangeEmitter(srange(toks[0]))\n\ndef handleRepetition(toks):\n toks=toks[0]\n if toks[1] in \"*+\":\n raise ParseFatalException(\"\",0,\"unbounded repetition operators not supported\")\n if toks[1] == \"?\":\n return OptionalEmitter(toks[0])\n if \"count\" in toks:\n return GroupEmitter([toks[0]] * int(toks.count))\n if \"minCount\" in toks:\n mincount = int(toks.minCount)\n maxcount = int(toks.maxCount)\n optcount = maxcount - mincount\n if optcount:\n opt = OptionalEmitter(toks[0])\n for i in range(1,optcount):\n opt = OptionalEmitter(GroupEmitter([toks[0],opt]))\n return GroupEmitter([toks[0]] * mincount + [opt])\n else:\n return [toks[0]] * mincount\n\ndef handleLiteral(toks):\n lit = \"\"\n for t in toks:\n if t[0] == \"\\\\\":\n if t[1] == \"t\":\n lit += '\\t'\n else:\n lit += t[1]\n else:\n lit += t\n return LiteralEmitter(lit) \n\ndef handleMacro(toks):\n macroChar = toks[0][1]\n if macroChar == \"d\":\n return CharacterRangeEmitter(\"0123456789\")\n elif macroChar == \"w\":\n return CharacterRangeEmitter(srange(\"[A-Za-z0-9_]\"))\n elif macroChar == \"s\":\n return LiteralEmitter(\" \")\n else:\n raise ParseFatalException(\"\",0,\"unsupported macro character (\" + macroChar + \")\")\n\ndef handleSequence(toks):\n return GroupEmitter(toks[0])\n\ndef handleDot():\n return CharacterRangeEmitter(printables)\n\ndef handleAlternative(toks):\n return AlternativeEmitter(toks[0])\n\n\n_parser = None\ndef parser():\n global _parser\n if _parser is None:\n ParserElement.setDefaultWhitespaceChars(\"\")\n lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,\"[]{}()\")\n\n reMacro = Combine(\"\\\\\" + oneOf(list(\"dws\")))\n escapedChar = ~reMacro + Combine(\"\\\\\" + oneOf(list(printables)))\n reLiteralChar = \"\".join(c for c in printables if c not in r\"\\[]{}().*?+|\") + \" \\t\"\n\n reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)\n reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )\n reDot = Literal(\".\")\n repetition = (\n ( lbrace + Word(nums).setResultsName(\"count\") + rbrace ) |\n ( lbrace + Word(nums).setResultsName(\"minCount\")+\",\"+ Word(nums).setResultsName(\"maxCount\") + rbrace ) |\n oneOf(list(\"*+?\")) \n )\n\n reRange.setParseAction(handleRange)\n reLiteral.setParseAction(handleLiteral)\n reMacro.setParseAction(handleMacro)\n reDot.setParseAction(handleDot)\n\n reTerm = ( reLiteral | reRange | reMacro | reDot )\n reExpr = operatorPrecedence( reTerm,\n [\n (repetition, 1, opAssoc.LEFT, handleRepetition),\n (None, 2, opAssoc.LEFT, handleSequence),\n (Suppress('|'), 2, opAssoc.LEFT, handleAlternative),\n ]\n )\n _parser = reExpr\n\n return _parser\n\ndef count(gen):\n \"\"\"Simple function to count the number of elements returned by a generator.\"\"\"\n i = 0\n for s in gen:\n i += 1\n return i\n\ndef invert(regex):\n \"\"\"Call this routine as a generator to return all the strings that\n match the input regular expression.\n for s in invert(\"[A-Z]{3}\\d{3}\"):\n print s\n \"\"\"\n invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()\n return invReGenerator()\n\ndef main():\n tests = r\"\"\"\n [A-EA]\n [A-D]*\n [A-D]{3}\n X[A-C]{3}Y\n X[A-C]{3}\\(\n X\\d\n foobar\\d\\d\n foobar{2}\n foobar{2,9}\n fooba[rz]{2}\n (foobar){2}\n ([01]\\d)|(2[0-5])\n ([01]\\d\\d)|(2[0-4]\\d)|(25[0-5])\n [A-C]{1,2}\n [A-C]{0,3}\n [A-C]\\s[A-C]\\s[A-C]\n [A-C]\\s?[A-C][A-C]\n [A-C]\\s([A-C][A-C])\n [A-C]\\s([A-C][A-C])?\n [A-C]{2}\\d{2}\n @|TH[12]\n @(@|TH[12])?\n @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?\n @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?\n (([ECMP]|HA|AK)[SD]|HS)T\n [A-CV]{2}\n A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]\n (a|b)|(x|y)\n (a|b) (x|y)\n \"\"\".split('\\n')\n\n for t in tests:\n t = t.strip()\n if not t: continue\n print '-'*50\n print t\n try:\n print count(invert(t))\n for s in invert(t):\n print s\n except ParseFatalException,pfe:\n print pfe.msg\n print\n continue\n print\n\nif __name__ == \"__main__\":\n main()\n" }, { "answer_id": 7222877, "author": "Richard - Rogue Wave Limited", "author_id": 206263, "author_profile": "https://Stackoverflow.com/users/206263", "pm_score": 4, "selected": false, "text": "preg_match @ @preg_match($regexToTest, '');\n //" }, { "answer_id": 55575718, "author": "Davide Visentin", "author_id": 6761184, "author_profile": "https://Stackoverflow.com/users/6761184", "pm_score": 4, "selected": false, "text": "x y z |x|>=1 && |xy|<=N y L a^Nb^Mc^N x y z y" }, { "answer_id": 67020534, "author": "Charanjit Singh", "author_id": 9275249, "author_profile": "https://Stackoverflow.com/users/9275249", "pm_score": 2, "selected": false, "text": "SyntaxError\n // VALID ONE\n> /yes[^]*day/\nOut: /yes[^]*day/\n\n// INVALID ONE\n> /yes[^*day/\nOut: VM227:1 Uncaught SyntaxError: Invalid regular expression: missing /\n var RegexParser = function(input) {\n\n // Parse input\n var m = input.match(/(\\/?)(.+)\\1([a-z]*)/i);\n\n // Invalid flags\n if (m[3] && !/^(?!.*?(.).*?\\1)[gmixXsuUAJ]+$/.test(m[3])) {\n return RegExp(input);\n }\n\n // Create the regular expression\n return new RegExp(m[2], m[3]);\n};\n var RegexString = \"/yes.*day/\"\n\nvar isRegexValid = input => {\n try {\n const regex = RegexParser(input);\n }\n catch(error) {\n if(error.name === \"SyntaxError\") \n {\n return false;\n }\n else \n {\n throw error;\n }\n }\n return true;\n}\n\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10950/" ]
172,306
<p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p> <ol> <li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p> <ul> <li>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</li> </ul></li> </ol>
[ { "answer_id": 172350, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 3, "selected": false, "text": "from __future__ import X" }, { "answer_id": 214601, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 8, "selected": true, "text": "2to3 /usr/bin/python 3to2" }, { "answer_id": 2977934, "author": "Evan Plaice", "author_id": 290340, "author_profile": "https://Stackoverflow.com/users/290340", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n# py2and3.py\n\nimport sys\nfrom pypreprocessor import pypreprocessor\n\n#exclude\nif sys.version[:3].split('.')[0] == '2':\n pypreprocessor.defines.append('python2')\nif sys.version[:3].split('.')[0] == '3':\n pypreprocessor.defines.append('python3')\n\npypreprocessor.parse()\n#endexclude\n#ifdef python2\nprint('You are using Python 2x')\n#ifdef python3\nprint('You are using python 3x')\n#else\nprint('Python version not supported')\n#endif\n pypreprocessor.output = outputFileName.py\npypreprocessor.removeMeta = True\n" }, { "answer_id": 13095022, "author": "Thane Brimhall", "author_id": 1255748, "author_profile": "https://Stackoverflow.com/users/1255748", "pm_score": 3, "selected": false, "text": "six six" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
172,320
<p>I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.</p> <p>Right now In my code I'm forced to do something like this:</p> <pre><code>if( _animalType == AnimalType.Pig ) { //namespace is pigfeet PigFeet.Feet feet = new Feet(); feet.WashFeet(); } if( _animalType == AnimalType.Horse ) { //namespace is horsefeet HorseFeet.Feet feet = new Feet(); feet.WashFeet(); } </code></pre> <p>This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically?</p>
[ { "answer_id": 172324, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "using PigFeet = PigFeet.Feet;\nusing HorseFeet = HorseFeet.Feet;\n\n//now your sample code should look something like\n\nif( _animalType == AnimalType.Pig )\n{ \n //namespace is pigfeet\n PigFeet feet = new PigFeet();\n feet.WashFeet();\n}\n\nif( _animalType == AnimalType.Horse )\n{\n //namespace is horsefeet\n HorseFeet feet = new HorseFeet();\n feet.WashFeet();\n }\n" }, { "answer_id": 172369, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "interface IFeet {\n void WashFeet();\n}\n\nclass FeetAdapter : IFeet {\n private PigFeet.Feet _pigFeet;\n private HorseFeet.Feet _horseFeet;\n\n private FeetAdapter(PigFeet.Feet pigFeet) {\n _pigFeet = pigFeet;\n }\n\n private FeetAdapter(HorseFeet.Feet horseFeet) {\n _horseFeet = horseFeet;\n }\n\n public void WashFeet() {\n if (_pigFeet != null) {\n _pigFeet.WashFeet();\n } else {\n _horseFeet.WashFeet();\n }\n }\n\n public static FeetAdapter Create(AnimalType animalType) {\n switch (animalType) {\n case AnimalType.Pig:\n return new FeetAdapter(new PigFeet.Feet());\n case AnimalType.Horse:\n return new FeetAdapter(new HorseFeet.Feet());\n }\n }\n}\n" }, { "answer_id": 172385, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "AnimalFeetFacade myFacade = new AnimalFeetFacade(_animalType);\nmyFacade.WashFeet();\n public class AnimalFeetFacade\n{\n public AnimalFeetFacade(AnimalType theType)\n {\n if (theType == AnimalType.Pig)\n {\n _washFeet = WashPigFeet;\n //TODO reference more PigFeet methods here\n }\n else if (theType == AnimalType.Horse)\n {\n _washFeet = WashHorseFeet;\n //TODO reference more HorseFeet methods here\n }\n else\n {\n throw new NotImplementedException(\"AnimalFeetFacade only works with PigFeet and HorseFeet\");\n }\n }\n\n protected Action _washFeet;\n\n public void WashFeet()\n {\n _washFeet.Invoke();\n }\n\n protected void WashPigFeet()\n {\n PigFeet.Feet = new PigFeet.Feet()\n feet.WashFeet()\n } \n\n protected void WashHorseFeet()\n {\n HorseFeet.Feet = new HorseFeet.Feet()\n feet.WashFeet()\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25300/" ]
172,353
<p>I am writing a C# program which captures signals from a external device, and sends keystrokes to another application. I am using SendKeys and it works fine.</p> <p>SendKeys does "press" a key by holding and releasing it immediately. I would like to make it push key and release it at will.</p> <p>My question is : "is there a way to send a "push" signal to a key, then a "release" signal after a certain amount of time ?"</p> <p>I am not sure SendKeys is able to do this. Any clue ?</p>
[ { "answer_id": 9509588, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 2, "selected": false, "text": "keybd_event SendInput WM_KEYDOWN WM_KEYUP WM_KEYDOWN KeyboardDelay KeyboardSpeed SystemInformation.KeyboardDelay SystemInformation.KeyboardSpeed await/async static Task SimulateKeyHold(VirtualKeyCode key, int holdDurationMs, \n int repeatDelayMs, int repeatRateMs, CancellationToken token)\n{\n var tcs = new TaskCompletionSource<object>();\n var ctr = new CancellationTokenRegistration();\n var startCount = Environment.TickCount;\n Timer timer = null;\n timer = new Timer(s => \n {\n lock (timer)\n {\n if (Environment.TickCount - startCount <= holdDurationMs)\n InputSimulator.SimulateKeyDown(key);\n else if (startCount != -1)\n { \n startCount = -1; \n timer.Dispose();\n ctr.Dispose(); \n InputSimulator.SimulateKeyUp(key);\n tcs.TrySetResult(null);\n }\n }\n });\n timer.Change(repeatDelayMs, repeatRateMs);\n\n if (token.CanBeCanceled)\n ctr = token.Register(() =>\n {\n timer.Dispose();\n tcs.TrySetCanceled();\n });\n return tcs.Task;\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24472/" ]
172,365
<p>I've created a web page that lets you input some information and then draws an image in a canvas element based on that info. I have it pretty much working the way I want except for the printing.</p> <p>Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it?</p> <p>Update:</p> <p>The answer was so simple. I was thinking of a lot more complicated solution. </p> <p>I wish I could pick more than 1 answer. I wasn't able to get the canvas to print when I used * to disable display. The simplest solution was to just turn off the form that I was using for input, using form {display:none;} in the CSS inside an @media print{}. Thanks for the quick response.</p> <pre><code> @media print { form { display:none; } } </code></pre>
[ { "answer_id": 172376, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<link> media=\"print\" display:none;" }, { "answer_id": 172377, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "@media print {\n * {\n display:none;\n }\n\n #SOME-CANVAS-ID {\n display:block;\n }\n}\n *:not(canvas) {\n display:none;\n}\n" }, { "answer_id": 13531805, "author": "Dedan", "author_id": 1768420, "author_profile": "https://Stackoverflow.com/users/1768420", "pm_score": 0, "selected": false, "text": "this.Print = function () {\n var printCanvas = $('#printCanvas');\n printCanvas.attr(\"width\", mainCanvas.width);\n printCanvas.attr(\"height\", mainCanvas.height);\n var printCanvasContext = printCanvas.get(0).getContext('2d');\n window.print();\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791/" ]
172,372
<p>I am wondering about what the difference between logging and tracing is.</p> <p>Is the difference basically that tracing is more detailed log giving developers a tool to debug applications at runtime?</p> <p>I have been experimenting with log4net and doing logging. Now I am wondering if I should be doing tracing as well and if I could/should use log4net for that purpose. Should I be doing tracing with log4net and is there some trace level for log4net loggers? Should I use a different log level for debug and trace purposes or is it ok to use the same? Can you give a simple example on how I would do logging and tracing for a simple method?</p> <p>Edit: Despite a few helpful answers below I am still unsure how I should be doing tracing versus logging. </p> <p>I have the following method in my Business layer and I want to add logging/tracing to it. I am wondering how to do it efficiently. Is the following method acceptable in terms of logging/tracing? Should the log messages be of type Info instead of Debug? Are the Debug messages I am logging considered trace? How would you change it?</p> <pre> <code> IEnumerable&lt;Car&gt; GetCars() { try { logger.Debug("Getting cars"); IEnumerable&lt;Car&gt; cars = CarAccessor.GetCars().ConvertAll(DataAccessToBusinessConverter); logger.Debug("Got total of " + cars.Count + " cars"); } catch (Exception e) { logger.Error("Error when getting cars", e); throw new Exception("Unexpected error when getting cars"); } } </code> </pre>
[ { "answer_id": 172488, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 4, "selected": false, "text": "Debug() <root>\n <level value=\"DEBUG\" />\n ...\n</root>\n <level value=\"INFO\" />\n" }, { "answer_id": 172525, "author": "martin", "author_id": 8421, "author_profile": "https://Stackoverflow.com/users/8421", "pm_score": 5, "selected": false, "text": "private void TestMethod(string x)\n{\n if(x.Length> 10)\n {\n Trace.Write(\"String was \" + x.Length);\n throw new ArgumentException(\"String too long\");\n }\n}\n private void TestMethod(string x)\n{\n Log.Info(\"String length is \" + x.Length);\n if(x.Length> 10)\n {\n Log.Error(\"String was \" + x.Length);\n throw new ArgumentException(\"String too long\");\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
172,393
<p>I have a method that takes an IQueryable. Is there a LINQ query that will give me back the size of each column in the IQueryable?</p> <p>To be more clear: this is Linq-to-objects. I want to get the length of the ToString() of each "column".</p>
[ { "answer_id": 172413, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": true, "text": "\npublic IEnumerable GetColumnSize(IQueryable source)\n{\n var types = MapTypeToMembers(source).Select(x => x.Type);\n return types.Select(x => MapTypeToSize(x));\n}\n" }, { "answer_id": 180723, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 0, "selected": false, "text": "var lengths = from o in myObjectCollection\n select new \n {\n PropertyLength1 = o.Property1.ToString().Length,\n PropertyLength2 = o.Property2.ToString().Length,\n ...\n }\n var lengths = from o in myObjectCollection\n select o.ToString().Length;\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
172,439
<p>I have a multi-line string that I want to do an operation on each line, like so:</p> <pre><code>inputString = &quot;&quot;&quot;Line 1 Line 2 Line 3&quot;&quot;&quot; </code></pre> <p>I want to iterate on each line:</p> <pre><code>for line in inputString: doStuff() </code></pre>
[ { "answer_id": 172454, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 10, "selected": true, "text": "inputString.splitlines()\n splitlines()" }, { "answer_id": 172468, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 8, "selected": false, "text": "inputString.split('\\n') # --> ['Line 1', 'Line 2', 'Line 3']\n import string\nstring.split(inputString, '\\n') # --> ['Line 1', 'Line 2', 'Line 3']\n splitlines True inputString.splitlines(True) # --> ['Line 1\\n', 'Line 2\\n', 'Line 3']\n" }, { "answer_id": 16752366, "author": "iruvar", "author_id": 753731, "author_profile": "https://Stackoverflow.com/users/753731", "pm_score": 4, "selected": false, "text": "StringIO for line in StringIO.StringIO(inputString):\n doStuff()\n" }, { "answer_id": 22233816, "author": "loopbackbee", "author_id": 1595865, "author_profile": "https://Stackoverflow.com/users/1595865", "pm_score": 6, "selected": false, "text": "inputString.splitlines() splitlines splitlines split True split(\"\\n\") split \\n \\n CR LF \\r \\n LF print >>> print \" a \\n b \\r\\n c \"\n a \n b \n c\n >>> \" a \\n b \\r\\n c \".split(\"\\n\")\n[' a ', ' b \\r', ' c ']\n os.linesep \\n >>> \" a \\n b \\r\\n c \".split(os.linesep)\n[' a \\n b ', ' c ']\n splitlines >>> \" a \\n b \\r\\n c \".splitlines()\n[' a ', ' b ', ' c ']\n \\n split('\\n')" }, { "answer_id": 30873284, "author": "Mike S", "author_id": 3768749, "author_profile": "https://Stackoverflow.com/users/3768749", "pm_score": 0, "selected": false, "text": "try:\n import cStringIO\n StringIO = cStringIO\nexcept ImportError:\n import StringIO\n\nfor line in StringIO.StringIO(variable_with_multiline_string):\n pass\nprint line.strip()\n" }, { "answer_id": 52282723, "author": "Finrod Felagund", "author_id": 7423100, "author_profile": "https://Stackoverflow.com/users/7423100", "pm_score": 1, "selected": false, "text": "text = \"\"\"1 sfasdf\nasdfasdf\n2 sfasdf\nasdfgadfg\n1 asfasdf\nsdfasdgf\n\"\"\"\n\ntext = text.splitlines()\nrows_to_print = {}\n\nfor line in range(len(text)):\n if text[line][0] == '1':\n rows_to_print = rows_to_print | {line, line + 1}\n\nrows_to_print = sorted(list(rows_to_print))\n\nfor i in rows_to_print:\n print(text[i])\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1546/" ]
172,443
<p>I'm looking for a getopt library for c#. So far I found a few (<a href="http://www.phpguru.org/static/getopt.html" rel="noreferrer">phpguru</a>, <a href="http://69.10.233.10/KB/cs/XGetoptCS.aspx" rel="noreferrer">XGetOptCS</a>, <a href="http://www.codeproject.com/KB/cs/geoptfordotnet.aspx" rel="noreferrer">getoptfordotnet</a>) but these look more like unfinished attempts that only support a part of C's getopt. Is there a full getopt c# implementation?</p>
[ { "answer_id": 9068889, "author": "kostix", "author_id": 720999, "author_profile": "https://Stackoverflow.com/users/720999", "pm_score": 0, "selected": false, "text": "src\\ClientUtilities\\util\\CommandLineOptions.cs ConsoleRunner.cs Runner.cs src\\ConsoleRunner\\nunit-console /verbose /filename:bar.txt / - --" }, { "answer_id": 47006226, "author": "Watercolor Games", "author_id": 8456308, "author_profile": "https://Stackoverflow.com/users/8456308", "pm_score": 1, "selected": false, "text": "using System;\nusing DocoptNet;\n\nnamespace MyProgram\n{\n static class Program\n {\n static void Main(string[] args)\n {\n // Usage string\n string usage = @\"This program does this thing.\n\nUsage:\n program set <something>\n program do <something> [-o <optionalthing>]\n program do <something> [somethingelse]\";\n\n try\n {\n var arguments = new Docopt().Apply(usage, args, version: \"My program v0.1.0\", exit: false);\n foreach(var argument in arguments)\n Console.WriteLine(\"{0} = {1}\", argument.Key, argument.Value);\n }\n catch(Exception ex)\n {\n //Parser errors are thrown as exceptions.\n Console.WriteLine(ex.Message);\n }\n }\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798/" ]
172,465
<pre><code>y: &amp;pause cd ptls5.0 &amp;pause sdp describe Integration.dpk &amp;pause z: &amp;pause cd ptls5.0 &amp;pause dir &amp;pause </code></pre> <p>I have those commands in the 1.cmd file. First three are executed fine. The result of it is that after "sdp describe Integration.dpk &amp;pause" is executed I'm given "press any key to continue..." after I hit any key. The command prompt quits. Instead of changing drive to z:>. What is wrong with it?</p>
[ { "answer_id": 172471, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "call call sdp describe Integration.dpk &pause\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
172,484
<p>I recently added <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1" rel="nofollow noreferrer">-pedantic</a> and <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-errors-1" rel="nofollow noreferrer">-pedantic-errors</a> to my make GCC compile options to help clean up my cross-platform code. All was fine until it found errors in external-included header files. Is there a way to turn off this error checking in external header files, i.e.:</p> <p>Keep checking for files included like this:</p> <pre><code>#include &quot;myheader.h&quot; </code></pre> <p>Stop checking for include files like this:</p> <pre><code>#include &lt;externalheader.h&gt; </code></pre> <p>Here are the errors I am getting:</p> <pre class="lang-none prettyprint-override"><code>g++ -Wall -Wextra -Wno-long-long -Wno-unused-parameter -pedantic --pedantic-errors -O3 -D_FILE_OFFSET_BITS=64 -DMINGW -I&quot;freetype/include&quot; -I&quot;jpeg&quot; -I&quot;lpng128&quot; -I&quot;zlib&quot; -I&quot;mysql/include&quot; -I&quot;ffmpeg/libswscale&quot; -I&quot;ffmpeg/libavformat&quot; -I&quot;ffmpeg/libavcodec&quot; -I&quot;ffmpeg/libavutil&quot; -o omingwd/kguimovie.o -c kguimovie.cpp In file included from ffmpeg/libavutil/avutil.h:41, from ffmpeg/libavcodec/avcodec.h:30, from kguimovie.cpp:44: ffmpeg/libavutil/mathematics.h:32: error: comma at end of enumerator list In file included from ffmpeg/libavcodec/avcodec.h:30, from kguimovie.cpp:44: ffmpeg/libavutil/avutil.h:110: error: comma at end of enumerator list In file included from kguimovie.cpp:44: ffmpeg/libavcodec/avcodec.h:277: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:303: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:334: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:345: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:2249: warning: `ImgReSampleContext' is deprecated (declared at ffmpeg/libavcodec/avcodec.h:2243) ffmpeg/libavcodec/avcodec.h:2259: warning: `ImgReSampleContext' is deprecated (declared at ffmpeg/libavcodec/avcodec.h:2243) In file included from kguimovie.cpp:45: ffmpeg/libavformat/avformat.h:262: error: comma at end of enumerator list In file included from ffmpeg/libavformat/rtsp.h:26, from ffmpeg/libavformat/avformat.h:465, from kguimovie.cpp:45: ffmpeg/libavformat/rtspcodes.h:38: error: comma at end of enumerator list In file included from ffmpeg/libavformat/avformat.h:465, from kguimovie.cpp:45: ffmpeg/libavformat/rtsp.h:32: error: comma at end of enumerator list ffmpeg/libavformat/rtsp.h:69: error: comma at end of enumerator list </code></pre>
[ { "answer_id": 172536, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": true, "text": "-pedantic" }, { "answer_id": 761156, "author": "Good Person", "author_id": 87280, "author_profile": "https://Stackoverflow.com/users/87280", "pm_score": 1, "selected": false, "text": "llvm-gcc -pedantic 2>&1|grep -v \"/usr/\"" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
172,504
<p>I like to read about new and clever algorithms. And I like to think out of the box, so all kinds of algorithms from all fields of computation are welcome.</p> <p>From time to time I read research papers to keep up with the current research and expand my horizon. I also like to learn new tricks. Unfortunately I tend to concentrate only on my field of interest, so I miss a lot of usefull stuff.</p> <p>Let's just not post mainstream things. Instead write about something special that made you think: "Wow - now <em>that's</em> a clever solution!".</p>
[ { "answer_id": 172535, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 2, "selected": false, "text": "P BP _P \"_\" BP PP BBP _B __P \"__\" BBP PBP BPP _BBP __BP ___P \"___\" __BBP ___BP ____P \"____\" BPBBP BBPBP BPBPP B B" }, { "answer_id": 172585, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 3, "selected": false, "text": "def assert\n raise \"Assertion failed !\" if $DEBUG and not yield\nend\n\ndef sqrt(v)\n value = v.abs\n residue = value\n root = 0\n onebit = 1\n onebit <<= 8 while (onebit < residue)\n onebit >>= 2 while (onebit > residue)\n while (onebit > 0)\n x = root + onebit\n if (residue >= x) then\n residue -= x\n root = x + onebit\n end\n root >>= 1\n onebit >>= 2\n end\n assert {value == (root**2+residue)}\n assert {value < ((root+1)**2)}\n return [root,residue]\nend\n\n$DEBUG = true\n\na = sqrt(4141290379431273280)\nputs a.inspect\n" }, { "answer_id": 173094, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "float SquareRootFloat(float num) {\n long i;\n float x, y;\n const float f = 1.5F;\n\n x = num * 0.5F;\n y = num;\n i = * ( long * ) &y;\n i = 0x5f3759df - ( i >> 1 );\n y = * ( float * ) &i;\n y = y * ( f - ( x * y * y ) );\n y = y * ( f - ( x * y * y ) );\n return num * y;\n}\n" }, { "answer_id": 1848036, "author": "Broam", "author_id": 213880, "author_profile": "https://Stackoverflow.com/users/213880", "pm_score": 1, "selected": false, "text": "((m+n) + (m-n)) / 2 === m (for any two real numbers m and n)" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
172,524
<p>Last time <a href="https://stackoverflow.com/questions/169506/get-form-input-fields-with-jquery">I asked about the reverse process</a>, and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.</p>
[ { "answer_id": 172532, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 4, "selected": false, "text": "$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });\n" }, { "answer_id": 172579, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 3, "selected": false, "text": "$.each(data, function(name,value) {\n $(\"input[name='\" + name + \"']\").val(value);\n});\n" }, { "answer_id": 173162, "author": "J5.", "author_id": 25380, "author_profile": "https://Stackoverflow.com/users/25380", "pm_score": 4, "selected": true, "text": "\njQuery.each(data, function (name,value) {\n jQuery(\"input[name='\"+name+\"'],select[name='\"+name+\"']\").each(function() {\n switch (this.nodeName.toLowerCase()) {\n case \"input\":\n switch (this.type) {\n case \"radio\":\n case \"checkbox\":\n if (this.value==value) { jQuery(this).click(); }\n break;\n default:\n jQuery(this).val(value);\n break;\n }\n break;\n case \"select\":\n jQuery(\"option\",this).each(function(){\n if (this.value==value) { this.selected=true; }\n });\n break;\n }\n });\n});\n" }, { "answer_id": 1835300, "author": "Brian Franklin", "author_id": 223186, "author_profile": "https://Stackoverflow.com/users/223186", "pm_score": 1, "selected": false, "text": "function populateForm(data, form) {\n $.each( data, function(name, value) {\n var input = $(\":input[name='\" + name + \"']:not(:button,:reset,:submit,:image)\", form );\n input.val( ( !$.isArray( value ) && ( input.is(':checkbox') || input.is(':radio') ) ) ? [ value ] : value );\n } );\n};\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
172,526
<p>I'll go first.</p> <p>I'm 100% in the set-operations camp. But what happens when the set logic on the entire desired input domain leads to a such a large retrieval that the query slows down significantly, comes to a crawl, or basically takes infinite time?</p> <p>That's one case where I'll use a itty-bitty cursor (or a while loop) of perhaps most dozens of rows (as opposed to the millions I'm targeting). Thus, I'm still working in (partitioned sub) sets, but my retrieval runs faster.</p> <p>Of course, an even faster solution would be to call the partioned input domains in parallel from outside, but that introduces an interaction will an external system, and when "good enough" speed can be achieved by looping in serial, just may not be worth it (epecially during development).</p>
[ { "answer_id": 172879, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": true, "text": "sp_getapplock" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23422/" ]
172,544
<p>I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.</p> <p>How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?</p> <pre><code>try { if (cbSubFolders.Checked == false) { string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath); foreach (string fileName in files) ProcessFile(fileName); } else { string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories); foreach (string fileName in files) ProcessFile(fileName); } lblNumberOfFilesDisplay.Enabled = true; } catch (UnauthorizedAccessException) { } finally {} </code></pre>
[ { "answer_id": 172575, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "using System;\nusing System.IO;\nstatic class Program\n{\n static void Main()\n {\n string path = \"\"; // TODO\n ApplyAllFiles(path, ProcessFile);\n }\n static void ProcessFile(string path) {/* ... */}\n static void ApplyAllFiles(string folder, Action<string> fileAction)\n {\n foreach (string file in Directory.GetFiles(folder))\n {\n fileAction(file);\n }\n foreach (string subDir in Directory.GetDirectories(folder))\n {\n try\n {\n ApplyAllFiles(subDir, fileAction);\n }\n catch\n {\n // swallow, log, whatever\n }\n }\n }\n}\n" }, { "answer_id": 172612, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 1, "selected": false, "text": "private string[] GetFiles(string path)\n{\n string[] files = null;\n try\n {\n files = Directory.GetFiles(path);\n }\n catch (UnauthorizedAccessException)\n {\n // might be nice to log this, or something ...\n }\n\n return files;\n}\n\nprivate void Processor(string path, bool recursive)\n{\n // leaving the recursive directory navigation out.\n string[] files = this.GetFiles(path);\n if (null != files)\n {\n foreach (string file in files)\n {\n this.Process(file);\n }\n }\n else\n {\n // again, might want to do something when you can't access the path?\n }\n}\n" }, { "answer_id": 24440132, "author": "Ben Gripka", "author_id": 530658, "author_profile": "https://Stackoverflow.com/users/530658", "pm_score": 4, "selected": false, "text": "private List<string> GetFiles(string path, string pattern)\n{\n var files = new List<string>();\n var directories = new string[] { };\n\n try\n {\n files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));\n directories = Directory.GetDirectories(path);\n }\n catch (UnauthorizedAccessException) { }\n\n foreach (var directory in directories)\n try\n {\n files.AddRange(GetFiles(directory, pattern));\n }\n catch (UnauthorizedAccessException) { }\n\n return files;\n}\n" }, { "answer_id": 38959208, "author": "Shubham", "author_id": 6310707, "author_profile": "https://Stackoverflow.com/users/6310707", "pm_score": 3, "selected": false, "text": "public static List<string> GetAllFilesFromFolder(string root, bool searchSubfolders) {\n Queue<string> folders = new Queue<string>();\n List<string> files = new List<string>();\n folders.Enqueue(root);\n while (folders.Count != 0) {\n string currentFolder = folders.Dequeue();\n try {\n string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, \"*.*\", System.IO.SearchOption.TopDirectoryOnly);\n files.AddRange(filesInCurrent);\n }\n catch {\n // Do Nothing\n }\n try {\n if (searchSubfolders) {\n string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, \"*.*\", System.IO.SearchOption.TopDirectoryOnly);\n foreach (string _current in foldersInCurrent) {\n folders.Enqueue(_current);\n }\n }\n }\n catch {\n // Do Nothing\n }\n }\n return files;\n}\n" }, { "answer_id": 49850530, "author": "user541686", "author_id": 541686, "author_profile": "https://Stackoverflow.com/users/541686", "pm_score": 2, "selected": false, "text": "List FileSystemInfo null public static IEnumerable<KeyValuePair<string, string[]>> GetFileSystemInfosRecursive(string dir, bool depth_first)\n{\n foreach (var item in GetFileSystemObjectsRecursive(new DirectoryInfo(dir), depth_first))\n {\n string[] result;\n var children = item.Value;\n if (children != null)\n {\n result = new string[children.Count];\n for (int i = 0; i < result.Length; i++)\n { result[i] = children[i].Name; }\n }\n else { result = null; }\n string fullname;\n try { fullname = item.Key.FullName; }\n catch (IOException) { fullname = null; }\n catch (UnauthorizedAccessException) { fullname = null; }\n yield return new KeyValuePair<string, string[]>(fullname, result);\n }\n}\n\npublic static IEnumerable<KeyValuePair<DirectoryInfo, List<FileSystemInfo>>> GetFileSystemInfosRecursive(DirectoryInfo dir, bool depth_first)\n{\n var stack = depth_first ? new Stack<DirectoryInfo>() : null;\n var queue = depth_first ? null : new Queue<DirectoryInfo>();\n if (depth_first) { stack.Push(dir); }\n else { queue.Enqueue(dir); }\n for (var list = new List<FileSystemInfo>(); (depth_first ? stack.Count : queue.Count) > 0; list.Clear())\n {\n dir = depth_first ? stack.Pop() : queue.Dequeue();\n FileSystemInfo[] children;\n try { children = dir.GetFileSystemInfos(); }\n catch (UnauthorizedAccessException) { children = null; }\n catch (IOException) { children = null; }\n if (children != null) { list.AddRange(children); }\n yield return new KeyValuePair<DirectoryInfo, List<FileSystemInfo>>(dir, children != null ? list : null);\n if (depth_first) { list.Reverse(); }\n foreach (var child in list)\n {\n var asdir = child as DirectoryInfo;\n if (asdir != null)\n {\n if (depth_first) { stack.Push(asdir); }\n else { queue.Enqueue(asdir); }\n }\n }\n }\n}\n" }, { "answer_id": 61868218, "author": "Shahin Dohan", "author_id": 1469494, "author_profile": "https://Stackoverflow.com/users/1469494", "pm_score": 4, "selected": false, "text": "var filePaths = Directory.EnumerateFiles(@\"C:\\my\\files\", \"*.xml\", new EnumerationOptions\n{\n IgnoreInaccessible = true,\n RecurseSubdirectories = true\n});\n DirectoryInfo" }, { "answer_id": 63242543, "author": "Ciccio Pasticcio", "author_id": 4375410, "author_profile": "https://Stackoverflow.com/users/4375410", "pm_score": 1, "selected": false, "text": "// search file in every subdirectory ignoring access errors\n static List<string> list_files(string path)\n {\n List<string> files = new List<string>();\n\n // add the files in the current directory\n try\n {\n string[] entries = Directory.GetFiles(path);\n\n foreach (string entry in entries)\n files.Add(System.IO.Path.Combine(path,entry));\n }\n catch \n { \n // an exception in directory.getfiles is not recoverable: the directory is not accessible\n }\n\n // follow the subdirectories\n try\n {\n string[] entries = Directory.GetDirectories(path);\n\n foreach (string entry in entries)\n {\n string current_path = System.IO.Path.Combine(path, entry);\n List<string> files_in_subdir = list_files(current_path);\n\n foreach (string current_file in files_in_subdir)\n files.Add(current_file);\n }\n }\n catch\n {\n // an exception in directory.getdirectories is not recoverable: the directory is not accessible\n }\n\n return files;\n }\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2493/" ]
172,546
<p>I'd like to use the new <b>CMFCListCtrl</b> features with my <b>CListView</b> class (and, of course, the new CMFCHeaderCtrl inside it). Unfortunately, you can't use <i>Attach()</i> or <i>SubclassWindow()</i> because the SysListView32 window is already associated with a CListView object.</p> <p>Do I have to override CListView's <i>OnCmdMsg()</i> and route all messages to my own instance of CMFCListCtrl? (Will that even work?) Or is there an easier/cleaner solution?</p>
[ { "answer_id": 2809830, "author": "Frekers", "author_id": 338149, "author_profile": "https://Stackoverflow.com/users/338149", "pm_score": 2, "selected": false, "text": "CMFCHeaderCtrl& CMyMFCListCtrl::GetHeaderCtrl() \n{ \n return m_myHeaderCtrl; \n}\n\nvoid CMyMFCListCtrl::InitHeader()\n{\n // Initialize header control:\n m_myHeaderCtrl.SubclassDlgItem(0, this);\n}\n\n\nvoid CMyMFCListCtrl::OnSize(UINT nType, int cx, int cy)\n{\n CListCtrl::OnSize(nType, cx, cy);\n if (myHeaderCtrl.GetSafeHwnd() != NULL)\n {\n myHeaderCtrl.RedrawWindow();\n }\n}\n OnDrawItem(CDC* pDC, int iItem, CRect rect, BOOL bIsPressed, BOOL bIsHighlighted);\n afx_msg LRESULT OnHeaderLayout(WPARAM wp, LPARAM lp); \n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4858/" ]
172,552
<p>I wrote a short bash script to complete a task that involves creating a temporary directory and storing various files in it and performing various operations on it.</p> <p>In my first pass I just created the temp dir at /tmp/$$.$script", but then I tested the script on a computer where I didn't have write access to /tmp/, and I'd like to take that case into account. So my question is where's a good secondary location for this temp dir? Should I just use the current directory? The home directory? ~/tmp/? The output location of the script?</p> <p>All created files do get cleaned up on script exit.</p>
[ { "answer_id": 172555, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "/var/tmp /tmp" }, { "answer_id": 172556, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "/var/tmp /tmp $TMPDIR $ echo $TMPDIR\n/var/folders/jf/jfu4pjGtGGGkUuuq8HL7UE+++TI/-Tmp-/\n" }, { "answer_id": 172586, "author": "rnicholson", "author_id": 14075, "author_profile": "https://Stackoverflow.com/users/14075", "pm_score": 3, "selected": false, "text": "case $TMPDIR in '') tmp_dir=\".${0}/tmp\";; *) tmp_dir=$TMPDIR;; esac\n" }, { "answer_id": 172660, "author": "Nick", "author_id": 4949, "author_profile": "https://Stackoverflow.com/users/4949", "pm_score": 2, "selected": false, "text": "\nMYTMPDIR=$(mktemp -d)\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
172,559
<pre><code>function returnsAnArray () { return array ('test'); } echo returnsAnArray ()[0]; </code></pre> <p>generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?</p>
[ { "answer_id": 172570, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 1, "selected": false, "text": " <?php\n echo current(returnsAnArray());\n ?>\n" }, { "answer_id": 172582, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 4, "selected": true, "text": "function returnsAnArray ()\n{\n return array ('test');\n}\n\nlist($foo)=returnsAnArray();\n list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);\n" }, { "answer_id": 172591, "author": "pmg", "author_id": 25324, "author_profile": "https://Stackoverflow.com/users/25324", "pm_score": 2, "selected": false, "text": "function arr_index($arr, $i) { return $arr[$i]; }\n echo arr_index(returnsAnArray(), 0);\n" }, { "answer_id": 172694, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<?php\necho reset(functionThatReturnsAnArray());\n?>\n" }, { "answer_id": 1675509, "author": "user202817", "author_id": 202817, "author_profile": "https://Stackoverflow.com/users/202817", "pm_score": 1, "selected": false, "text": "array_pop(array_slice(func(),$n,1)); array_pop(array_intersect_keys(func(),Array($key => \"\"));" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24288/" ]
172,573
<p>I've been using <a href="http://www.jcraft.com/jsch/" rel="nofollow noreferrer">JSch</a> for a couple of weeks now. It seems to <em>work</em> okay, but its API is a little bit cumbersome. I'm also a little off put by its total lack of documentation (not even javadoc style comments). Has anyone used a good Java SSH2 library that they'd recommend. I'm particularly interested in SCP file transfer and issuing commands to a remote Linux box programmatically via the SSH protocol.</p>
[ { "answer_id": 172570, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 1, "selected": false, "text": " <?php\n echo current(returnsAnArray());\n ?>\n" }, { "answer_id": 172582, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 4, "selected": true, "text": "function returnsAnArray ()\n{\n return array ('test');\n}\n\nlist($foo)=returnsAnArray();\n list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);\n" }, { "answer_id": 172591, "author": "pmg", "author_id": 25324, "author_profile": "https://Stackoverflow.com/users/25324", "pm_score": 2, "selected": false, "text": "function arr_index($arr, $i) { return $arr[$i]; }\n echo arr_index(returnsAnArray(), 0);\n" }, { "answer_id": 172694, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<?php\necho reset(functionThatReturnsAnArray());\n?>\n" }, { "answer_id": 1675509, "author": "user202817", "author_id": 202817, "author_profile": "https://Stackoverflow.com/users/202817", "pm_score": 1, "selected": false, "text": "array_pop(array_slice(func(),$n,1)); array_pop(array_intersect_keys(func(),Array($key => \"\"));" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
172,587
<p>What is the difference between g++ and gcc? Which one of them should be used for general c++ development?</p>
[ { "answer_id": 172592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "gcc g++ cc1 cc1plus -x language g++ gcc -xc++ -lstdc++ -shared-libgcc -v" }, { "answer_id": 172613, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 5, "selected": false, "text": ".c .c -x c" }, { "answer_id": 173007, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 9, "selected": false, "text": "gcc g++ gcc *.c\\*.cpp g++ *.c\\*.cpp g++ gcc gcc gcc *.cpp g++ *.c\\*.cpp *.cpp #define __GXX_WEAK__ 1\n#define __cplusplus 1\n#define __DEPRECATED 1\n#define __GNUG__ 4\n#define __EXCEPTIONS 1\n#define __private_extern__ extern\n" }, { "answer_id": 29082054, "author": "Konstantin Burlachenko", "author_id": 1154447, "author_profile": "https://Stackoverflow.com/users/1154447", "pm_score": 4, "selected": false, "text": "$ g++ --version | head -n1 \ng++.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3\n\n$ gcc --version | head -n1\ngcc.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3\n gcc -std=c99 test_c99.c\ngcc -std=c89 test_c89.c \ng++ -std=c++98 test_cpp.cpp\ngcc -std=c++98 test_cpp.cpp\n $ gcc -std=c++98 test_cpp.c\ncc1.exe: warning: command line option '-std=c++98' is valid for C++/ObjC++ but not for C [enabled by default]\n $ gcc -x c++ -std=c++98 test_cpp.c\n $ g++ -std=c++0x test_cpp_11.cpp \n $ cat test_c89.c test_c99.c test_cpp.cpp\n\n// C89 compatible file\nint main()\n{\n int x[] = {0, 2};\n return sizeof(x);\n}\n\n// C99 compatible file\nint main()\n{\n int x[] = {[1]=2};\n return sizeof(x);\n}\n\n// C++1998,2003 compatible file\nclass X{};\nint main()\n{\n X x;\n return sizeof(x);\n}\n\n// C++11\n#include <vector>\nenum class Color : int{red,green,blue}; // scoped enum\nint main()\n{\n std::vector<int> a {1,2,3}; // bracket initialization\n return 0;\n}\n" }, { "answer_id": 34609548, "author": "l --marc l", "author_id": 3103448, "author_profile": "https://Stackoverflow.com/users/3103448", "pm_score": 6, "selected": false, "text": "g++ gcc gcc gcc man gcc\n\n# GCC(1) GNU\n# \n# NAME\n# gcc - GNU project C and C++ compiler\n g++ gnat gcc man g++ GCC(1) man gcc g++ gcc gcc g++ gcc gcc g++ gcc g++ g++ gcc machine-gcc machine-gcc-version g++ g++ gcc g++ ls -l /Applications/Xcode.app/Contents/Developer/usr/bin\n# …\n# lrwxr-xr-x 1 root wheel 3 Apr 27 2021 g++ -> gcc\n# -rwxr-xr-x 1 root wheel 167120 Nov 23 20:51 gcc\n\n### -- versus --\nwhich -a g++\n# /usr/bin/g++\nls -l /usr/bin/g++\n# -rwxr-xr-x 1 root wheel 137616 Jan 1 2020 /usr/bin/g++\n" }, { "answer_id": 40389469, "author": "magicmax", "author_id": 7106856, "author_profile": "https://Stackoverflow.com/users/7106856", "pm_score": 0, "selected": false, "text": "int main(){\n\nint * myptr = new int;\n* myptr = 1;\nprintf(\"myptr[0] is %i\\n\",*myptr);\nreturn 0;\n}\n undefined reference to `operator new(unsigned long)'\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
172,598
<p>I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.</p> <p>I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C. </p> <p>Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them?</p> <hr/> <p>As for my findings so far.</p> <p>It is possible to use <a href="http://www.otierney.net/objective-c.html#categories" rel="noreferrer">categories</a> [e.g. MyClass (Private)] defined in MyClass.m file to group private methods.</p> <p>This approach has 2 issues:</p> <ol> <li>Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block</li> <li>You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo".</li> </ol> <p>The first issue can be worked around with <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_5.html#//apple_ref/doc/uid/TP30001163-CH20-SW2" rel="noreferrer">empty category</a> [e.g. MyClass ()].<br/> The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.</p>
[ { "answer_id": 173287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "@interface @interface GLObject (PrivateMethods) GLObject+PrivateMethods.h @implementation GLObject(PrivateMethods)\n- (void)secretFeature;\n@end\n GLObject+Extension.h" }, { "answer_id": 651623, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 1, "selected": false, "text": "@interface @implementation" }, { "answer_id": 651692, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 4, "selected": false, "text": "//.h file\n@interface MyClass : Object\n{\n int test;\n}\n- (void) someMethod: anArg;\n\n@end\n\n\n//.m file \n@implementation MyClass\n\nstatic void somePrivateMethod (MyClass *myClass, id anArg)\n{\n fprintf (stderr, \"MyClass (%d) was passed %p\", myClass->test, anArg);\n}\n\n\n- (void) someMethod: (id) anArg\n{\n somePrivateMethod (self, anArg);\n}\n\n@end\n" }, { "answer_id": 651852, "author": "Alex", "author_id": 35999, "author_profile": "https://Stackoverflow.com/users/35999", "pm_score": 9, "selected": false, "text": "@interface MyClass () @implementation MyClass @interface MyClass {\n // My Instance Variables\n}\n\n- (void)myPublicMethod;\n\n@end\n @interface MyClass()\n\n- (void)myPrivateMethod;\n\n@end\n\n@implementation MyClass\n\n- (void)myPublicMethod {\n // Implementation goes here\n}\n\n- (void)myPrivateMethod {\n // Implementation goes here\n}\n\n@end\n" }, { "answer_id": 3401583, "author": "rebelzach", "author_id": 363522, "author_profile": "https://Stackoverflow.com/users/363522", "pm_score": 2, "selected": false, "text": "@interface MyClassPrivate.h interface MyClass : NSObject {\n @private\n BOOL publicIvar_;\n BOOL privateIvar_;\n}\n\n@property (nonatomic, assign) BOOL publicIvar;\n//any other public methods. etc\n@end\n @interface MyClass ()\n\n@property (nonatomic, assign) BOOL privateIvar;\n//any other private methods etc.\n@end\n #import \"MyClass.h\"\n#import \"MyClassPrivate.h\"\n@implementation MyClass\n\n@synthesize privateIvar = privateIvar_;\n@synthesize publicIvar = publicIvar_;\n\n@end\n" }, { "answer_id": 4227000, "author": "Zack Sheppard", "author_id": 513736, "author_profile": "https://Stackoverflow.com/users/513736", "pm_score": 2, "selected": false, "text": "-(void)myHelperMethod: (id) sender{\n // code here...\n}\n [self performSelector:@selector(myHelperMethod:)];\n" }, { "answer_id": 11068947, "author": "FellowMD", "author_id": 379163, "author_profile": "https://Stackoverflow.com/users/379163", "pm_score": 2, "selected": false, "text": "@implementation MyClass\n\nid (^createTheObject)() = ^(){ return [[NSObject alloc] init];};\n\nNSInteger (^addEm)(NSInteger, NSInteger) =\n^(NSInteger a, NSInteger b)\n{\n return a + b;\n};\n\n//public methods, etc.\n\n- (NSObject) thePublicOne\n{\n return createTheObject();\n}\n\n@end\n" }, { "answer_id": 14867152, "author": "Rich Schonthal", "author_id": 2023738, "author_profile": "https://Stackoverflow.com/users/2023738", "pm_score": 2, "selected": false, "text": "//MyClass.m\n#import \"MyClass.h\"\n#import \"MyClass_private.h\"\n" }, { "answer_id": 16758022, "author": "justin", "author_id": 191596, "author_profile": "https://Stackoverflow.com/users/191596", "pm_score": 5, "selected": false, "text": "@implementation @implementation @implementation static @interface MONObject (PrivateStuff) @implementation MONObject (PrivateStuff)\n...HERE...\n@end\n @interface MONObject : NSObject\n\n// public declaration required for clients' visibility/use.\n@property (nonatomic, assign, readwrite) bool publicBool;\n\n// public declaration required for clients' visibility/use.\n- (void)publicMethod;\n\n@end\n @interface MONObject ()\n@property (nonatomic, assign, readwrite) bool privateBool;\n\n// you can use a convention where the class name prefix is reserved\n// for private methods this can reduce accidental overriding:\n- (void)MONObject_privateMethod;\n\n@end\n\n// The potentially good thing about functions is that they are truly\n// inaccessible; They may not be overridden, accidentally used,\n// looked up via the objc runtime, and will often be eliminated from\n// backtraces. Unlike methods, they can also be inlined. If unused\n// (e.g. diagnostic omitted in release) or every use is inlined,\n// they may be removed from the binary:\nstatic void PrivateMethod(MONObject * pObject) {\n pObject.privateBool = true;\n}\n\n@implementation MONObject\n{\n bool anIvar;\n}\n\nstatic void AnotherPrivateMethod(MONObject * pObject) {\n if (0 == pObject) {\n assert(0 && \"invalid parameter\");\n return;\n }\n\n // if declared in the @implementation scope, you *could* access the\n // private ivars directly (although you should rarely do this):\n pObject->anIvar = true;\n}\n\n- (void)publicMethod\n{\n // declared below -- but clang can see its declaration in this\n // translation:\n [self privateMethod];\n}\n\n// no declaration required.\n- (void)privateMethod\n{\n}\n\n- (void)MONObject_privateMethod\n{\n}\n\n@end\n" }, { "answer_id": 52979295, "author": "Milan", "author_id": 1998518, "author_profile": "https://Stackoverflow.com/users/1998518", "pm_score": 0, "selected": false, "text": "@implementation pragma mark private @implementation MyClass \n// .. public methods\n\n# pragma mark private \n// ...\n\n@end\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20294/" ]
172,600
<p>When I try this with a generic class where this.value is T:</p> <pre><code>if (this.value.GetType() == typeof(int)) { ((int)this.value)++; } else { throw new InvalidOperationException ("T must be an int to perform this operation"); } </code></pre> <p>I get a compile-time error: "Cannot convert type 'T' to 'int'"</p> <p>What should I do to perform an integral operation on this.value when it's an int?</p> <p>Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T. </p>
[ { "answer_id": 172639, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "int i = (int)(object)this.value;\ni++;\nthis.value = (T)(object)i;\n this.value = Operator.AddAlternative(this.value, 1);\n this.value = Operator.AddAlternative<T,int>(this.value, 1);\n" }, { "answer_id": 172651, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "using System;\n\nclass Foo<T>\n{\n public T value;\n\n public void Increment()\n {\n if (value is int) value = (T)(object)(((int)(object)value)+1);\n }\n}\n\nstatic class Program\n{\n static void Main()\n {\n Foo<int> x = new Foo<int>();\n x.Increment();\n x.Increment();\n Console.WriteLine(x.value); \n } \n}\n" }, { "answer_id": 172657, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 0, "selected": false, "text": "namespace GenericsOne\n{\n using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n Sample<int> one = new Sample<int>();\n one.AddFive(10);\n\n // yes, this will fail, it is to show why the approach is generally not a good one.\n Sample<DateTime> two = new Sample<DateTime>();\n two.AddFive(new DateTime());\n }\n}\n\n}\n\nnamespace GenericsOne\n{\n using System;\npublic class Sample<T>\n{\n public int AddFive(T number)\n {\n int junk = 0;\n\n try\n {\n junk = Convert.ToInt32(number);\n }\n catch (Exception)\n {\n Console.WriteLine(\"Nope\");\n }\n\n return junk + 5;\n }\n}\n}\n" }, { "answer_id": 172669, "author": "Collin K", "author_id": 1369, "author_profile": "https://Stackoverflow.com/users/1369", "pm_score": 4, "selected": false, "text": "public class MyClass<T>\n{\n ...\n}\n\npublic class IntClass : MyClass<int>\n{\n public void IncrementMe()\n {\n this.value++;\n }\n}\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
172,648
<p>I have a photo website and i want to support tags as my original category bucketing is starting to fail (some pictures are family and vacations, or school and friends). Is there an agreed tagging db schema? </p> <p>I still want to support having photos as part of an album.</p> <p>Right now i have a few tables:</p> <p><strong>Photos</strong></p> <ul> <li>PhotoID</li> <li>PhotoAlbumID</li> <li>Caption</li> <li>Date</li> </ul> <p><strong>Photo Album</strong></p> <ul> <li>AlbumID</li> <li>AlbumName</li> <li>AlbumDate</li> </ul>
[ { "answer_id": 172833, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 4, "selected": false, "text": "photos\n photoid\n caption\n filename\n date\n\ntags\n tagid\n tagname\n\nphototags\n photoid\n tagid\n" }, { "answer_id": 172853, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": " public static void threadproc_tags(object obj)\n {\n System.Web.HttpApplicationState app = (System.Web.HttpApplicationState)obj;\n\n SortedDictionary<string,List<int>> tags = new SortedDictionary<string,List<int>>();\n\n // update the cache\n DbUtil dbutil = new DbUtil();\n DataSet ds = dbutil.get_dataset(\"select bg_id, bg_tags from bugs where isnull(bg_tags,'') <> ''\");\n\n foreach (DataRow dr in ds.Tables[0].Rows)\n {\n string[] labels = btnet.Util.split_string_using_commas((string) dr[1]);\n\n // for each tag label, build a list of bugids that have that label\n for (int i = 0; i < labels.Length; i++)\n {\n\n string label = normalize_tag(labels[i]);\n\n if (label != \"\")\n {\n if (!tags.ContainsKey(label))\n {\n tags[label] = new List<int>();\n }\n\n tags[label].Add((int)dr[0]);\n }\n }\n }\n\n app[\"tags\"] = tags;\n\n }\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/172648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]