qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
151,303
<p>Using the <code>AddHandler</code> method, if I never use <code>RemoveHandler</code>, will that lead to memory leaks in some conditions and situations? I'm not so sure about the truth of this.</p> <p>And are there other causes to memory leaks that are solely available in VB as opposed to C#?</p>
[ { "answer_id": 151430, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 4, "selected": false, "text": "button1.Click += new EventHandler(Form_Click_Handler);\n childForm.Event -= new EventHandler(Form_Handler)\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8505/" ]
151,335
<p>Is there anyway to combine all resources into a single exe file such as app.config and associated DLL's?</p> <p>Some applications seem to do this such as eMule.</p> <p>I don't want my app.config sitting there waiting to be edited.</p> <p>Thanks</p>
[ { "answer_id": 151352, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 4, "selected": true, "text": "Solution Explorer Right-click Properties Build Action Embedded Resource" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
151,337
<p>I'm looking for a cross-browser method - I know IE has something (I've already forgotten what), and the way to do it in Mozilla may have to do with a focusNode thing I found, that seems related to getting text selections.</p> <p>Methods involving jQuery or another common JS library are fine by me.</p> <p>Thanks!</p>
[ { "answer_id": 151364, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 1, "selected": false, "text": "var currentFocus = null; \n$(':input').focus( function() { \n currentFocus = this; \n}).blur( function() { \n\n currentFocus = null; \n}); \n" }, { "answer_id": 151383, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 3, "selected": true, "text": ":focus" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1507554/" ]
151,338
<p>How can I add an instance variable to a defined class at <b>runtime</b>, and later get and set its value from outside of the class?</p> <p>I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about. </p>
[ { "answer_id": 151354, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 6, "selected": false, "text": "instance_variable_get instance_variable_set >> foo = Object.new\n=> #<Object:0x2aaaaaacc400>\n\n>> foo.instance_variable_set(:@bar, \"baz\")\n=> \"baz\"\n\n>> foo.inspect\n=> #<Object:0x2aaaaaacc400 @bar=\\\"baz\\\">\n" }, { "answer_id": 151359, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 5, "selected": true, "text": "class Array\n attr_accessor :var\nend\n array = []\narray.var = 123\nputs array.var\n attr_reader attr_writer class Array\n attr_reader :getter_only_method\n attr_writer :setter_only_method\n\n # Manual definitions equivalent to using attr_reader/writer/accessor\n def var\n @var\n end\n\n def var=(value)\n @var = value\n end\nend\n array = []\n\ndef array.var\n @var\nend\n\ndef array.var=(value)\n @var = value\nend\n\narray.var = 123\nputs array.var\n irb(main):001:0> class A\nirb(main):002:1> attr_accessor :b\nirb(main):003:1> end\n=> nil\nirb(main):004:0> a = A.new\n=> #<A:0x7fbb4b0efe58>\nirb(main):005:0> a.b = 1\n=> 1\nirb(main):006:0> a.b\n=> 1\nirb(main):007:0> def a.setit=(value)\nirb(main):008:1> @b = value\nirb(main):009:1> end\n=> nil\nirb(main):010:0> a.setit = 2\n=> 2\nirb(main):011:0> a.b\n=> 2\nirb(main):012:0> \n setit @b" }, { "answer_id": 151398, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "s1 = 'string 1'\ns2 = 'string 2'\n\nclass String\n attr_accessor :my_var\nend\n\ns1.my_var = 'comment #1'\ns2.my_var = 'comment 2'\n\nputs s1.my_var, s2.my_var\n" }, { "answer_id": 151440, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "class A\n def hello\n print \"hello \"\n end\nend\n\nclass A\n def world\n puts \"world!\"\n end\nend\n\na = A.new\na.hello\na.world\n" }, { "answer_id": 151477, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "array = []\narray.class.send(:define_method, :var) { @var }\narray.class.send(:define_method, :var=) { |value| @var = value }\n irb(main):001:0> array = []\n=> []\nirb(main):002:0> array.class.send(:define_method, :var) { @var }\n=> #<Proc:0x00007f289ccb62b0@(irb):2>\nirb(main):003:0> array.class.send(:define_method, :var=) { |value| @var = value }\n=> #<Proc:0x00007f289cc9fa88@(irb):3>\nirb(main):004:0> array.var = 123\n=> 123\nirb(main):005:0> array.var\n=> 123\nirb(main):006:0> array2 = []\n=> []\nirb(main):007:0> array2.var = 321\n=> 321\nirb(main):008:0> array2.var\n=> 321\nirb(main):009:0> array.var\n=> 123\n" }, { "answer_id": 152193, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 4, "selected": false, "text": "m = MyObject.new\nmetaclass = class << m; self; end\nmetaclass.send :attr_accessor, :first, :second\nm.first = \"first\"\nm.second = \"second\"\nputs m.first, m.second\n class MyObject\n def metaclass\n class << self\n self\n end\n end\n\n def define_attributes(hash)\n hash.each_pair { |key, value|\n metaclass.send :attr_accessor, key\n send \"#{key}=\".to_sym, value\n }\n end\nend\n\nm = MyObject.new\nm.define_attributes({ :first => \"first\", :second => \"second\" })\n m1 = MyObject.new\nm2 = MyObject.new\nm1.define_attributes({:a => 123, :b => 321})\nm2.define_attributes({:c => \"abc\", :d => \"zxy\"})\nputs m1.a, m1.b, m2.c, m2.d # this will work\nm1.c = 5 # this will fail because c= is not defined on m1!\nm2.a = 5 # this will fail because a= is not defined on m2!\n" }, { "answer_id": 13335121, "author": "musicmatze", "author_id": 1391026, "author_profile": "https://Stackoverflow.com/users/1391026", "pm_score": 0, "selected": false, "text": "class Foo\n include Flexible\nend\nf = Foo.new\nf.bar = 1\n f.bar?\n#=> true\n" }, { "answer_id": 33244256, "author": "Huliax", "author_id": 1025695, "author_profile": "https://Stackoverflow.com/users/1025695", "pm_score": 0, "selected": false, "text": "# example classes that we want to tweak\nclass Foo;end\nclass Bar;end\nklasses = [Foo, Bar]\n\n# iterating over a collection of klasses\nklasses.each do |klass|\n # #class_eval gets it done\n klass.class_eval do\n attr_accessor :baz\n end\nend\n\n# it works\nf = Foo.new\nf.baz # => nil\nf.baz = 'it works' # => \"it works\"\nb = Bar.new\nb.baz # => nil\nb.baz = 'it still works' # => \"it still works\"\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
151,348
<p>Why is NodeList undefined in IE6/7?</p> <pre><code>&lt;form action="/" method="post" id="testform"&gt; &lt;input type="checkbox" name="foobar[]" value="1" id="" /&gt; &lt;input type="checkbox" name="foobar[]" value="2" id="" /&gt; &lt;input type="checkbox" name="foobar[]" value="3" id="" /&gt; &lt;/form&gt; &lt;script type="text/javascript" charset="utf-8"&gt; (function () { var el = document.getElementById('testform')['foobar[]'] if (el instanceof NodeList) { alert("I'm a NodeList"); } })(); &lt;/script&gt; </code></pre> <p>This works in FF3/Safari 3.1 but doesn't work in IE6/7. Anyone have any ideas how to check if el is an instance of NodeList across all browsers?</p>
[ { "answer_id": 151631, "author": "Adam Franco", "author_id": 15872, "author_profile": "https://Stackoverflow.com/users/15872", "pm_score": 4, "selected": false, "text": "...\n\nif (typeof el.length == 'number' \n && typeof el.item == 'function'\n && typeof el.nextNode == 'function'\n && typeof el.reset == 'function')\n{\n alert(\"I'm a NodeList\");\n}\n" }, { "answer_id": 8452783, "author": "Andrew Banks", "author_id": 448801, "author_profile": "https://Stackoverflow.com/users/448801", "pm_score": 0, "selected": false, "text": "if (1 < $(el).length) {\n alert(\"I'm a NodeList\");\n}\n" }, { "answer_id": 10740835, "author": "craigpatik", "author_id": 348995, "author_profile": "https://Stackoverflow.com/users/348995", "pm_score": 2, "selected": false, "text": "typeof el.item typeof el.item !== \"undefined\" == === if (typeof el.length === 'number' \n && typeof el.item !== 'undefined'\n && typeof el.nextNode === 'function'\n && typeof el.reset === 'function')\n{\n alert(\"I'm a NodeList\");\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8369/" ]
151,350
<p>What are my options? I tried MonoDevelop over a year ago but it was extremely buggy. Is the latest version a stable development environment?</p>
[ { "answer_id": 171663, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "make run" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
151,362
<p>For posting AJAX forms in a form with many parameters, I am using a solution of creating an <code>iframe</code>, posting the form to it by POST, and then accessing the <code>iframe</code>'s content. specifically, I am accessing the content like this:</p> <pre><code>$("some_iframe_id").get(0).contentWindow.document </code></pre> <p>I tested it and it worked. </p> <p>On some of the pages, I started getting an "Access is denied" error. As far as I know, this shouldn't happen if the iframe is served from the same domain. </p> <p>I'm pretty sure it was working before. Anybody have a clue? </p> <p>If I'm not being clear enough: I'm posting to the <em>same domain</em>. So this is not a cross-domain request. I am testing on IE only.</p> <p>P.S. I can't use simple ajax POST queries (don't ask...)</p>
[ { "answer_id": 151395, "author": "Ris Adams", "author_id": 15683, "author_profile": "https://Stackoverflow.com/users/15683", "pm_score": 0, "selected": false, "text": "document.domain = www.foo.com\n" }, { "answer_id": 151404, "author": "Ovesh", "author_id": 3751, "author_profile": "https://Stackoverflow.com/users/3751", "pm_score": 7, "selected": true, "text": "iframe res://ieframe.dll/http_500.htm" }, { "answer_id": 14805501, "author": "gak", "author_id": 11125, "author_profile": "https://Stackoverflow.com/users/11125", "pm_score": 2, "selected": false, "text": "X-Frame-Options Header always append X-Frame-Options DENY\n" }, { "answer_id": 18017982, "author": "AaronLS", "author_id": 84206, "author_profile": "https://Stackoverflow.com/users/84206", "pm_score": 2, "selected": false, "text": "src='javascript:void(0)' frame.document.location =... src='/content/blank.html'" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
151,369
<p>Given an HTML page that has a complex table-based layout and many tags that are duplicated and wasteful, e.g.:</p> <pre><code>td align="left" class="tableformat" width="65%" style="border-bottom:1px solid #ff9600; border-right:1px solid #ff9600; background-color:#FDD69E" nowrap etc. </code></pre> <p>Are there tools to aide the task of refactoring the page into a more compact form? For instance, a tool that automatically generates CSS styles and selectors? That converts tables into div layouts? </p> <p>Just to give a sense of the order of the problem, the page I'm looking at is >8000 lines of HTML and JavaScript, which is 500Kb <em>not counting</em> images! </p> <hr> <p>Update: In re. "give up and start from scratch" comments. What does that mean, in the real world? Print out the page, scan it, set it as the background image in Dreamweaver, and start with that? Seriously? Would that really be more efficient than refactoring? </p> <hr> <p>Update: I'm not denigrating "trace it from scratch" nor did I mean to imply that Dreamweaver is by any means my tool of choice. I'm just very surprised that refactoring a layout is considered to be an intractable problem. </p>
[ { "answer_id": 151549, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 1, "selected": false, "text": "<body>\n <div id=\"header\">\n <img id=\"logo\"/>\n <h1 id=\"title\">\n My Site\n </h1>\n <div id=\"subtitle\">Playing with css</div>\n </div>\n <div id=\"content\">\n <h2>Page 1</h2>\n <p>Blah blah blah..</p>\n </div>\n <div id=\"menu\">\n <ul>\n <li><a>Some link</a></li>\n ...\n </ul>\n </div>\n</body>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10116/" ]
151,392
<p>Does anyone know any good tool that I can use to perform stress tests on a video streaming server? I need to test how well my server handles 5,000+ connections. </p>
[ { "answer_id": 151650, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 4, "selected": true, "text": "$i = 0;\n$myurl = \"udp://someurl\";\n@cmdline = (\"/usr/bin/vlc\", \"\");\nfor( $i = 1; $i <= 5000; $i++ )\n{\n if( $pid = fork )\n {\n # parent - ignore\n }\n elsif( defined $pid )\n {\n $cmdline[1] = sprintf \"%s:%d\", $myurl, $i;\n exec(@cmdline);\n }\n # elseif - do more error checking here\n}\n /proc/net/igmp" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23637/" ]
151,403
<p>According to the answers to <a href="https://stackoverflow.com/questions/151250/how-do-i-embed-a-file-version-in-an-msi-file-with-visual-studio">this</a> question, I cannot embed a file version in my .msi file. </p> <p>The installer that I give the client needs to have a file version. </p> <p>So, what I want to do is create a self-extracting executable containing the msi file and the setup.exe generated by Visual Studio, and put the file version on this self-extracting executable instead.</p> <p>Therefore, I need a utility to create self-extracting executables which supports embedding a file version in its output. It also needs to support automatically running a file after extraction, so I can start the real installer automatically. It would be nice if it was scriptable.</p> <p>All I could find was <a href="http://www.gdgsoft.com/pb/customize-package.aspx" rel="nofollow noreferrer">this</a>, which looks great, but I would much prefer a free alternative.</p> <p>Does anyone have any suggestions?</p> <p><strong>Edit:</strong> To clarify, I'm not really looking to create an installer - I already have a VS setup project. I just want a self-extractor (like WinZip can create). So, the user mouses over Setup-Blorgbeard2008.exe, sees "Version: 1.0.0.0". User doubleclicks it, it silently extracts setup.exe and setup.msi to a temp folder, then runs setup.exe. User then sees normal installer screen and proceeds as normal.</p> <p><strong>Another Edit:</strong> Yay, I don't need a self-extractor anymore, since my other question has now been answered. That makes this whole question pretty much irrelevant. It <em>would</em> still be nice to be able to distribute only one file, rather than setup.exe and setup.msi.</p>
[ { "answer_id": 151423, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "VersionInfoVersion = 1.1.0.0\n" }, { "answer_id": 151833, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 2, "selected": false, "text": "VIProductVersion \"1.0.0.0\" ; set version here\nVIAddVersionKey \"FileVersion\" \"1.0.0.0\" ; and here!\nVIAddVersionKey \"CompanyName\" \"MyCompany\"\nVIAddVersionKey \"LegalCopyright\" \"© MyCompany\"\nVIAddVersionKey \"FileDescription\" \"Installer for MyProgram\"\nOutFile MyProgram-Setup.exe\n\nSilentInstall silent\n\nSection Main \n SetOutPath $TEMP\n SetOverwrite on\n File SharedManagementObjects.msi\n File SQLSysClrTypes.msi\n File Release\\Setup.exe\n File Release\\Setup.msi\n ExecWait 'msiexec /passive /i \"$OUTDIR\\SharedManagementObjects.msi\"'\n ExecWait 'msiexec /passive /i \"$OUTDIR\\SQLSysClrTypes.msi\"'\n Exec '\"$OUTDIR\\Setup.exe\"'\nSectionEnd\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
151,407
<p>Under Linux, my C++ application is using fork() and execv() to launch multiple instances of OpenOffice so as to view some powerpoint slide shows. This part works.</p> <p>Next I want to be able to move the OpenOffice windows to specific locations on the display. I can do that with the XMoveResizeWindow() function but I need to find the Window for each instance.</p> <p>I have the process ID of each instance, how can I find the X11 Window from that ?</p> <hr> <p><strong>UPDATE</strong> - Thanks to Andy's suggestion, I have pulled this off. I'm posting the code here to share it with the Stack Overflow community.</p> <p>Unfortunately Open Office does not seem to set the _NET_WM_PID property so this doesn't ultimately solve my problem but it does answer the question.</p> <pre><code>// Attempt to identify a window by name or attribute. // by Adam Pierce &lt;adam@doctort.org&gt; #include &lt;X11/Xlib.h&gt; #include &lt;X11/Xatom.h&gt; #include &lt;iostream&gt; #include &lt;list&gt; using namespace std; class WindowsMatchingPid { public: WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid) : _display(display) , _pid(pid) { // Get the PID property atom. _atomPID = XInternAtom(display, "_NET_WM_PID", True); if(_atomPID == None) { cout &lt;&lt; "No such atom" &lt;&lt; endl; return; } search(wRoot); } const list&lt;Window&gt; &amp;result() const { return _result; } private: unsigned long _pid; Atom _atomPID; Display *_display; list&lt;Window&gt; _result; void search(Window w) { // Get the PID for the current Window. Atom type; int format; unsigned long nItems; unsigned long bytesAfter; unsigned char *propPID = 0; if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL, &amp;type, &amp;format, &amp;nItems, &amp;bytesAfter, &amp;propPID)) { if(propPID != 0) { // If the PID matches, add this window to the result set. if(_pid == *((unsigned long *)propPID)) _result.push_back(w); XFree(propPID); } } // Recurse into child windows. Window wRoot; Window wParent; Window *wChild; unsigned nChildren; if(0 != XQueryTree(_display, w, &amp;wRoot, &amp;wParent, &amp;wChild, &amp;nChildren)) { for(unsigned i = 0; i &lt; nChildren; i++) search(wChild[i]); } } }; int main(int argc, char **argv) { if(argc &lt; 2) return 1; int pid = atoi(argv[1]); cout &lt;&lt; "Searching for windows associated with PID " &lt;&lt; pid &lt;&lt; endl; // Start with the root window. Display *display = XOpenDisplay(0); WindowsMatchingPid match(display, XDefaultRootWindow(display), pid); // Print the result. const list&lt;Window&gt; &amp;result = match.result(); for(list&lt;Window&gt;::const_iterator it = result.begin(); it != result.end(); it++) cout &lt;&lt; "Window #" &lt;&lt; (unsigned long)(*it) &lt;&lt; endl; return 0; } </code></pre>
[ { "answer_id": 27486173, "author": "Gauthier", "author_id": 108802, "author_profile": "https://Stackoverflow.com/users/108802", "pm_score": 3, "selected": false, "text": "xdotool #!/bin/bash\n# --any and --name present only as a work-around, see: https://github.com/jordansissel/xdotool/issues/14\nids=$(xdotool search --any --pid \"$1\" --name \"dummy\")\n seturgent xdotool seturgent" }, { "answer_id": 43566150, "author": "Shuman", "author_id": 2052889, "author_profile": "https://Stackoverflow.com/users/2052889", "pm_score": 0, "selected": false, "text": "xprop import subprocess\nimport re\n\nimport struct\nimport xcffib as xcb\nimport xcffib.xproto\n\ndef get_property_value(property_reply):\n assert isinstance(property_reply, xcb.xproto.GetPropertyReply)\n\n if property_reply.format == 8:\n if 0 in property_reply.value:\n ret = []\n s = ''\n for o in property_reply.value:\n if o == 0:\n ret.append(s)\n s = ''\n else:\n s += chr(o)\n else:\n ret = str(property_reply.value.buf())\n\n return ret\n elif property_reply.format in (16, 32):\n return list(struct.unpack('I' * property_reply.value_len,\n property_reply.value.buf()))\n\n return None\n\ndef getProperty(connection, ident, propertyName):\n\n propertyType = eval(' xcb.xproto.Atom.%s' % propertyName)\n\n try:\n return connection.core.GetProperty(False, ident, propertyType,\n xcb.xproto.GetPropertyType.Any,\n 0, 2 ** 32 - 1)\n except:\n return None\n\n\nc = xcb.connect()\nroot = c.get_setup().roots[0].root\n\n_NET_CLIENT_LIST = c.core.InternAtom(True, len('_NET_CLIENT_LIST'),\n '_NET_CLIENT_LIST').reply().atom\n\n\nraw_clientlist = c.core.GetProperty(False, root, _NET_CLIENT_LIST,\n xcb.xproto.GetPropertyType.Any,\n 0, 2 ** 32 - 1).reply()\n\nclientlist = get_property_value(raw_clientlist)\n\ncookies = {}\n\nfor ident in clientlist:\n wm_command = getProperty(c, ident, 'WM_COMMAND')\n cookies[ident] = (wm_command)\n\nxids=[]\n\nfor ident in cookies:\n cmd = get_property_value(cookies[ident].reply())\n if cmd and spref in cmd:\n xids.append(ident)\n\nfor xid in xids:\n pid = subprocess.check_output('xprop -id %s _NET_WM_PID' % xid, shell=True)\n pid = re.search('(?<=\\s=\\s)\\d+', pid).group()\n\n if int(pid) == self.pid:\n print 'found pid:', pid\n break\n\nprint 'your xid:', xid\n" }, { "answer_id": 55921742, "author": "DarioP", "author_id": 2140449, "author_profile": "https://Stackoverflow.com/users/2140449", "pm_score": 2, "selected": false, "text": "// Attempt to identify a window by name or attribute.\n// originally written by Adam Pierce <adam@doctort.org>\n// revised by Dario Pellegrini <pellegrini.dario@gmail.com>\n\n#include <X11/Xlib.h>\n#include <X11/Xatom.h>\n#include <iostream>\n#include <vector>\n\n\nstd::vector<Window> pid2windows(pid_t pid, Display* display, Window w) {\n struct implementation {\n struct FreeWrapRAII {\n void * data;\n FreeWrapRAII(void * data): data(data) {}\n ~FreeWrapRAII(){ XFree(data); }\n };\n\n std::vector<Window> result;\n pid_t pid;\n Display* display;\n Atom atomPID;\n\n implementation(pid_t pid, Display* display): pid(pid), display(display) {\n // Get the PID property atom\n atomPID = XInternAtom(display, \"_NET_WM_PID\", True);\n if(atomPID == None) {\n throw std::runtime_error(\"pid2windows: no such atom\");\n }\n }\n\n std::vector<Window> getChildren(Window w) {\n Window wRoot;\n Window wParent;\n Window *wChild;\n unsigned nChildren;\n std::vector<Window> children;\n if(0 != XQueryTree(display, w, &wRoot, &wParent, &wChild, &nChildren)) {\n FreeWrapRAII tmp( wChild );\n children.insert(children.end(), wChild, wChild+nChildren);\n }\n return children;\n }\n\n void emplaceIfMatches(Window w) {\n // Get the PID for the given Window\n Atom type;\n int format;\n unsigned long nItems;\n unsigned long bytesAfter;\n unsigned char *propPID = 0;\n if(Success == XGetWindowProperty(display, w, atomPID, 0, 1, False, XA_CARDINAL,\n &type, &format, &nItems, &bytesAfter, &propPID)) {\n if(propPID != 0) {\n FreeWrapRAII tmp( propPID );\n if(pid == *reinterpret_cast<pid_t*>(propPID)) {\n result.emplace_back(w);\n }\n }\n }\n }\n\n void recurse( Window w) {\n emplaceIfMatches(w);\n for (auto & child: getChildren(w)) {\n recurse(child);\n }\n }\n\n std::vector<Window> operator()( Window w ) {\n result.clear();\n recurse(w);\n return result;\n }\n };\n //back to pid2windows function\n return implementation{pid, display}(w);\n}\n\nstd::vector<Window> pid2windows(const size_t pid, Display* display) {\n return pid2windows(pid, display, XDefaultRootWindow(display));\n}\n\n\nint main(int argc, char **argv) {\n if(argc < 2)\n return 1;\n\n int pid = atoi(argv[1]);\n std::cout << \"Searching for windows associated with PID \" << pid << std::endl;\n\n // Start with the root window.\n Display *display = XOpenDisplay(0);\n auto res = pid2windows(pid, display);\n\n // Print the result.\n for( auto & w: res) {\n std::cout << \"Window #\" << static_cast<unsigned long>(w) << std::endl;\n }\n\n XCloseDisplay(display);\n return 0;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
151,414
<p>Here is the directory layout that was installed with Leopard. What is the "A" directory and why the "Current" directory in addition to the "CurrentJDK"?</p> <p>It seems like you can easily switch the current JDK by move the CurrentJDK link, but then the contents under Current and A will be out of sync.</p> <pre> lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.3 -> 1.3.1 drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2 lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 1.4.1 -> 1.4 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0 lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.6 -> 1.6.0 drwxr-xr-x 8 root wheel 272 Jun 14 15:49 1.6.0 drwxr-xr-x 8 root wheel 272 Jun 14 15:49 A lrwxr-xr-x 1 root wheel 1 Jun 14 15:49 Current -> A lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 CurrentJDK -> 1.5 steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions $ </pre> <p>and the contents of A</p> <pre> -rw-r--r-- 1 root wheel 1925 Feb 29 2008 CodeResources drwxr-xr-x 34 root wheel 1156 Jun 14 15:49 Commands drwxr-xr-x 3 root wheel 102 Mar 6 2008 Frameworks drwxr-xr-x 16 root wheel 544 Jun 14 15:49 Headers -rwxr-xr-x 1 root wheel 236080 Feb 29 2008 JavaVM drwxr-xr-x 29 root wheel 986 Jun 14 15:49 Resources steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions/A $ </pre>
[ { "answer_id": 151463, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": true, "text": "A Current A JavaVM.framework CurrentJDK" }, { "answer_id": 151515, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 2, "selected": false, "text": "~/.profile export JAVA_HOME=\"/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/\"\nexport PATH=$JAVA_HOME/bin/:$PATH\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21176/" ]
151,418
<p>I have a function pointer defined by:</p> <pre><code>typedef void (*EventFunction)(int nEvent); </code></pre> <p>Is there a way to handle that function with a specific instance of a C++ object?</p> <pre><code>class A { private: EventFunction handler; public: void SetEvent(EventFunction func) { handler = func; } void EventOne() { handler(1); } }; class B { private: A a; public: B() { a.SetEvent(EventFromA); } // What do I do here? void EventFromA(int nEvent) { // do stuff } }; </code></pre> <p><strong>Edit:</strong> Orion pointed out the options that Boost offers such as:</p> <pre><code>boost::function&lt;int (int)&gt; f; X x; f = std::bind1st( std::mem_fun(&amp;X::foo), &amp;x); f(5); // Call x.foo(5) </code></pre> <p>Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?</p>
[ { "answer_id": 151427, "author": "markets", "author_id": 4662, "author_profile": "https://Stackoverflow.com/users/4662", "pm_score": 1, "selected": false, "text": "typedef void (*B::EventFunction)(int nEvent); static void EventFrom A(int nEvent);" }, { "answer_id": 151439, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": false, "text": "std::function boost::function boost:function std::function" }, { "answer_id": 151449, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 4, "selected": false, "text": "class A;\nclass B;\ntypedef void (B::*EventFunction)(int nEvent)\n class A\n{\nprivate:\n EventFunction handler;\n\npublic:\n void SetEvent(EventFunction func) { handler = func; }\n\n void EventOne(B* delegate) { ((*delegate).*handler)(1); } // note: \".*\"\n};\n\nclass B\n{\nprivate:\n A a;\npublic:\n B() { a.SetEvent(&B::EventFromA); } // note: \"&::\"\n\n void EventFromA(int nEvent) { /* do stuff */ }\n};\n" }, { "answer_id": 151712, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 0, "selected": false, "text": "#define CALLBACKGLUE(classname , func) static void CB_ ## func(void *obj) {static_cast< classname *>(obj)->func();}\n#define CALLBACKGLUEPTR(classname , func, type) static void CB_ ## func(void *obj,type *name) {static_cast< classname *>(obj)->func(name);}\n#define CALLBACKGLUEPTRPTR(classname , func, type,type2) static void CB_ ## func(void *obj,type *name,type2 *name2) {static_cast< classname *>(obj)->func(name,name2);}\n#define CALLBACKGLUEPTRPTRPTR(classname , func, type,type2,type3) static void CB_ ## func(void *obj,type *name,type2 *name2,type3 *name3) {static_cast< classname *>(obj)->func(name,name2,name3);}\n#define CALLBACKGLUEVAL(classname , func, type) static void CB_ ## func(void *obj,type val) {static_cast< classname *>(obj)->func(val);}\n" }, { "answer_id": 151733, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "boost::bind void* \nclass C\n{\npublic:\n int Method1(void) { return 3; }\n int Method2(void) { return x; }\n\n int x;\n};\n\n// This structure will hold a thunk to\nstruct CCallback\n{\n C *obj; // Instance to callback on\n int (C::*callback)(void); // Class callback method, taking no arguments and returning int\n};\n\nint CBootstrapper(CCallback *pThunk)\n{\n // Call the thunk\n return ((pThunk->obj) ->* (pThunk->callback))( /* args go here */ );\n}\n\nvoid DoIt(C *obj, int (C::*callback)(void))\n{\n // foobar() is some C library function that takes a function which takes no arguments and returns int, and it also takes a void*, and we can't change it\n struct CCallback thunk = {obj, callback};\n foobar(&CBootstrapper, &thunk);\n}\n\nint main(void)\n{\n C c;\n DoIt(&c, &C::Method1); // Essentially calls foobar() with a callback of C::Method1 on c\n DoIt(&c, &C::Method2); // Ditto for C::Method2\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4592/" ]
151,434
<p>I have a web service API. Some calls return objects containing text fields with information provided by the user. From both a design and a security standpoint, what are the downsides to returning null in those fields when no information has been provided? Is there a clear advantage to always returning an empty string instead, other then simplifying the API by not requiring the client code to check for nulls?</p>
[ { "answer_id": 151457, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "string.IsNullOrEmpty()\n" }, { "answer_id": 151685, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "{\n [WebMethod]\n public MyClass HelloWorld() \n {\n MyClass val = new MyClass()\n {\n IsValid = false,\n HelloString = \"Hello World\",\n BlankString = \"\",\n Nested = new NestedClass { Name = \"Bob\" }\n };\n\n return val;\n }\n\n}\n\npublic class MyClass\n{\n public bool IsValid { get; set; }\n public string HelloString { get; set; }\n public string BlankString { get; set; }\n public string OtherString { get; set; }\n public NestedClass Nested { get; set; }\n public NestedClass NullNested { get; set; }\n}\n\npublic class NestedClass\n{\n public string Name { get; set; }\n}\n OtherString NullNested BlankString <MyClass>\n <IsValid>false</IsValid> \n <HelloString>Hello World</HelloString> \n <BlankString /> \n <Nested>\n <Name>Bob</Name> \n </Nested>\n</MyClass>\n" }, { "answer_id": 151732, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 1, "selected": false, "text": "<element/> <element/> <element></element> <element></element>" }, { "answer_id": 55490011, "author": "Remigius Stalder", "author_id": 3639856, "author_profile": "https://Stackoverflow.com/users/3639856", "pm_score": 0, "selected": false, "text": "private static ObjectMapper configureMapper(ObjectMapper mapper) {\n mapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPY, JsonInclude.Include.NON_NULL));\n mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);\n return mapper;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14128/" ]
151,448
<p>Bearing in mind this is for <strong>classic asp</strong></p> <p>Which is better, all HTML contained within Response.Write Statements or inserting variables into HTML via &lt;%= %>.<br> Eg </p> <pre><code>Response.Write "&lt;table&gt;" &amp; vbCrlf Response.Write "&lt;tr&gt;" &amp;vbCrLf Response.Write "&lt;td class=""someClass""&gt;" &amp; someVariable &amp; "&lt;/td&gt;" &amp; vbCrLf Response.Write "&lt;/tr&gt;" &amp; vbCrLf Response.Write "&lt;/table&gt;" &amp; vbCrLf </code></pre> <p>VS</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td class="someClass"&gt;&lt;%= someVariable %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I am mainly asking from a performance point of view in which will have the least server impact when there multiple variables to insert?</p> <p>If there are no technical differences what are the arguments for one over the other?</p>
[ { "answer_id": 151455, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<%= %> Response.Write()" }, { "answer_id": 151536, "author": "Russell Myers", "author_id": 18194, "author_profile": "https://Stackoverflow.com/users/18194", "pm_score": 2, "selected": false, "text": "<table>\n<tr>\n<td class=\"someClass\">variable value</td>\n</tr>\n</table>\n" }, { "answer_id": 151592, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 6, "selected": true, "text": "<%= expression %> Response.Write <%= %> <%= %> <%= %> <%= %> Response.Write <%= %>" }, { "answer_id": 151657, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 2, "selected": false, "text": "<%= %> var myControl = document.getElementById('<%= myControl.ClientID %>');\n" }, { "answer_id": 151672, "author": "Simon Forrest", "author_id": 4733, "author_profile": "https://Stackoverflow.com/users/4733", "pm_score": 3, "selected": false, "text": "Response.Write \"<table><tr><td class=\"\"someClass\"\">\" & someVar & \"</td></tr></table>\"\n Response.Write \"<table>\" _\n & \"<tr>\" _\n & \"<td class=\"\"someClass\"\">\" & someVar & \"</td>\" _\n & \"</tr>\" _\n & \"<tr>\" _\n & \"<td class=\"\"anotherClass\"\">\" & anotherVar & \"</td>\" _\n & \"</tr>\" _\n & \"<tr>\" _\n & \"<td class=\"\"etc\"\">\" & andSoOn & \"</td>\" _\n & \"</tr>\" _\n & \"</table>\"\n" }, { "answer_id": 152126, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 4, "selected": false, "text": "<%\n Response.CodePage = 65001\n Response.CharSet = \"UTF-8\"\n %>\n<p> The British £</p>\n<%Response.Write(\"<p> The British £</p>\")%>\n" }, { "answer_id": 230697, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 2, "selected": false, "text": "Response.Write \"<table>\" & vbCrlf\nResponse.Write \"<tr>\" &vbCrLf\nResponse.Write \"<tdclass=\"\"someClass\"\">\" & someVariable & \"</td>\" & vbCrLf \nResponse.Write \"</tr>\" & vbCrLf \nResponse.Write \"</table>\" & vbCrLf\n <table>\n <tr>\n <td class=\"someClass\"><%= someVariable %></td>\n </tr>\n</table>\n Response.Write\"<table>\\r\\n<tr>\\r\\n<td class=\"someClass\">\"\nResponse.Write someVariable\nResponse.Write \"</td>\\r\\n</tr>\\r\\n</table>\"\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4665/" ]
151,472
<p>In .NET, what is the difference between <code>String.Empty</code> and <code>""</code>, and are they interchangable, or is there some underlying reference or Localization issues around equality that <code>String.Empty</code> will ensure are not a problem?</p>
[ { "answer_id": 151481, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 9, "selected": true, "text": "\"\" string.Empty string.Empty \"\" \"\" .Empty .Length == 0 .Length == 0 .Empty" }, { "answer_id": 156100, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 5, "selected": false, "text": "String.Empty \"\" String.Empty" }, { "answer_id": 13703103, "author": "Habib", "author_id": 961113, "author_profile": "https://Stackoverflow.com/users/961113", "pm_score": 8, "selected": false, "text": "string.Empty \"\" void SomeMethod(int ID, string value = string.Empty)\n// Error: Default parameter value for 'value' must be a compile-time constant\n{\n //... implementation\n}\n string str = \"\";\nswitch(str)\n{\n case string.Empty: // Error: A constant value is expected. \n break;\n\n case \"\":\n break;\n\n}\n [Example(String.Empty)]\n// Error: An attribute argument must be a constant expression, typeof expression \n// or array creation expression of an attribute parameter type\n" }, { "answer_id": 17386465, "author": "Bruno Martinez", "author_id": 65569, "author_profile": "https://Stackoverflow.com/users/65569", "pm_score": 4, "selected": false, "text": "string foo()\n{\n return \"foo\" + \"\";\n}\nstring bar()\n{\n return \"bar\" + string.Empty;\n}\n .method private hidebysig instance string foo() cil managed\n{\n .maxstack 8\n L_0000: ldstr \"foo\"\n L_0005: ret \n}\n.method private hidebysig instance string bar() cil managed\n{\n .maxstack 8\n L_0000: ldstr \"bar\"\n L_0005: ldsfld string [mscorlib]System.String::Empty\n L_000a: call string [mscorlib]System.String::Concat(string, string)\n L_000f: ret \n}\n" }, { "answer_id": 29704826, "author": "Salvuccino", "author_id": 4802043, "author_profile": "https://Stackoverflow.com/users/4802043", "pm_score": 2, "selected": false, "text": "string mystring = \"\";\nldstr \"\"\n ldstr string mystring = String.Empty;\nldsfld string [mscorlib]System.String::Empty\n ldsfld String.Empty \"\"" }, { "answer_id": 33915636, "author": "Justinw", "author_id": 5318793, "author_profile": "https://Stackoverflow.com/users/5318793", "pm_score": 4, "selected": false, "text": "String.Empty \"\" \"\" \"\"" }, { "answer_id": 34928377, "author": "DeepakTheGeek", "author_id": 5797641, "author_profile": "https://Stackoverflow.com/users/5797641", "pm_score": -1, "selected": false, "text": "string str=null;\nConsole.WriteLine(str.Length); // Exception(NullRefernceException) for pointing to null reference. \n\n\nstring str = string.Empty;\nConsole.WriteLine(str.Length); // 0\n" }, { "answer_id": 35335169, "author": "Mojtaba Rezaeian", "author_id": 2721611, "author_profile": "https://Stackoverflow.com/users/2721611", "pm_score": 3, "selected": false, "text": "String.Empty \"\" \"\" \"\" \"\" \"\" String.Empty \"\" String.Empty \"\" String.Empty String.Empty \"\"" }, { "answer_id": 42779748, "author": "tsiva124", "author_id": 3830433, "author_profile": "https://Stackoverflow.com/users/3830433", "pm_score": 2, "selected": false, "text": "public void test(int i=0,string s=\"\")\n {\n // Function Body\n }\n" }, { "answer_id": 54453417, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 2, "selected": false, "text": "String.Concat static String s00() => default(String) + default(String);\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n add rsp,28h\n ret\n\nstatic String s01() => default(String) + \"\";\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n add rsp,28h\n ret\n\nstatic String s02() => default(String) + String.Empty;\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n mov rdx,rax\n test rdx,rdx\n jne _L\n mov rdx,rax\n_L: mov rax,rdx\n add rsp,28h\n ret\n static String s03() => \"\" + default(String);\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n add rsp,28h\n ret\n\nstatic String s04() => \"\" + \"\";\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n add rsp,28h\n ret\n\nstatic String s05() => \"\" + String.Empty;\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n mov rdx,rax\n test rdx,rdx\n jne _L\n mov rdx,rax\n_L: mov rax,rdx\n add rsp,28h\n ret\n static String s06() => String.Empty + default(String);\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n mov rdx,rax\n test rdx,rdx\n jne _L\n mov rdx,rax\n_L: mov rax,rdx\n add rsp,28h\n ret\n\nstatic String s07() => String.Empty + \"\";\n mov rax,[String::Empty]\n mov rax,qword ptr [rax]\n mov rdx,rax\n test rdx,rdx\n jne _L\n mov rdx,rax\n_L: mov rax,rdx\n add rsp,28h\n ret\n\nstatic String s08() => String.Empty + String.Empty;\n mov rcx,[String::Empty]\n mov rcx,qword ptr [rcx]\n mov qword ptr [rsp+20h],rcx\n mov rcx,qword ptr [rsp+20h]\n mov rdx,qword ptr [rsp+20h]\n call F330CF60 ; <-- String.Concat\n nop\n add rsp,28h\n ret\n Microsoft (R) Visual C# Compiler version 2.10.0.0 (b9fb1610)\nAMD64 Release\n[MethodImpl(MethodImplOptions.NoInlining)]\n'SuppressJitOptimization' = false\n" }, { "answer_id": 56024307, "author": "K0D4", "author_id": 1181624, "author_profile": "https://Stackoverflow.com/users/1181624", "pm_score": 2, "selected": false, "text": "var i = 30;\nvar f = Math.Pi;\nvar s = \"\";\nvar d = 22.2m;\nvar t = \"I am some text\";\nvar e = string.Empty;\n" }, { "answer_id": 66604787, "author": "kingletit", "author_id": 10776503, "author_profile": "https://Stackoverflow.com/users/10776503", "pm_score": -1, "selected": false, "text": " if string + \"\" = \"\"" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
151,496
<p>I am converting an excel sheet formula to java but I can't understand how excel manages to take the following: 0.22 Applies a formula: =TEXT(R5/14, "h:mm") and somehow arrives at: 0.22</p> <p>Again if I provide: 2.8 it arrives at 4.48 Can someone please explain to me how it does this. I have read a little regarding decimal and I understand the conversion but this hasn't yet helped to explain the above.</p>
[ { "answer_id": 151535, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 0, "selected": false, "text": "int msInADay= 86400000;\nTime value = new Time(R5/14 * msInADay);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
151,505
<p>I came from Java, and now I am working more with Ruby. </p> <p>One language feature I am not familiar with is the <code>module</code>. I am wondering what exactly is a <code>module</code> and when do you use one, and why use a <code>module</code> over a <code>class</code>?</p>
[ { "answer_id": 151534, "author": "hurcane", "author_id": 21363, "author_profile": "https://Stackoverflow.com/users/21363", "pm_score": 5, "selected": false, "text": "http://www.rubycentral.com/pickaxe/classes.html" }, { "answer_id": 9778021, "author": "Sergii Shevchyk", "author_id": 946224, "author_profile": "https://Stackoverflow.com/users/946224", "pm_score": 9, "selected": false, "text": "╔═══════════════╦═══════════════════════════╦═════════════════════════════════╗\n║ ║ class ║ module ║\n╠═══════════════╬═══════════════════════════╬═════════════════════════════════╣\n║ instantiation ║ can be instantiated ║ can *not* be instantiated ║\n╟───────────────╫───────────────────────────╫─────────────────────────────────╢\n║ usage ║ object creation ║ mixin facility. provide ║\n║ ║ ║ a namespace. ║\n╟───────────────╫───────────────────────────╫─────────────────────────────────╢\n║ superclass ║ module ║ object ║\n╟───────────────╫───────────────────────────╫─────────────────────────────────╢\n║ methods ║ class methods and ║ module methods and ║\n║ ║ instance methods ║ instance methods ║\n╟───────────────╫───────────────────────────╫─────────────────────────────────╢\n║ inheritance ║ inherits behaviour and can║ No inheritance ║\n║ ║ be base for inheritance ║ ║\n╟───────────────╫───────────────────────────╫─────────────────────────────────╢\n║ inclusion ║ cannot be included ║ can be included in classes and ║\n║ ║ ║ modules by using the include ║\n║ ║ ║ command (includes all ║\n║ ║ ║ instance methods as instance ║\n║ ║ ║ methods in a class/module) ║\n╟───────────────╫───────────────────────────╫─────────────────────────────────╢\n║ extension ║ can not extend with ║ module can extend instance by ║\n║ ║ extend command ║ using extend command (extends ║\n║ ║ (only with inheritance) ║ given instance with singleton ║\n║ ║ ║ methods from module) ║\n╚═══════════════╩═══════════════════════════╩═════════════════════════════════╝\n" }, { "answer_id": 17027346, "author": "Boris Stitnicky", "author_id": 1153747, "author_profile": "https://Stackoverflow.com/users/1153747", "pm_score": 3, "selected": false, "text": "Module include" }, { "answer_id": 18134471, "author": "Linan", "author_id": 2665730, "author_profile": "https://Stackoverflow.com/users/2665730", "pm_score": 7, "selected": false, "text": "Math Math.random()" }, { "answer_id": 50575317, "author": "Daniel Viglione", "author_id": 4501354, "author_profile": "https://Stackoverflow.com/users/4501354", "pm_score": 2, "selected": false, "text": "module Apple\n def a\n puts 'a'\n end\nend\n\nmodule Apple \n def b\n puts 'b'\n end\nend\n \nclass Fruit\n include Apple\nend\n \n > f = Fruit.new\n => #<Fruit:0x007fe90c527c98> \n > f.a\n => a\n > f.b\n => b\n module Apple\n module Green\n def green\n puts 'green'\n end\n end\nend\n \nclass Fruit\n include Apple\nend\n\n> f = Fruit.new\n => #<Fruit:0x007fe90c462420> \n> f.green\nNoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>\n class Fruit\n include Apple::Green\nend\n => Fruit \n > f.green\n=> green\n" }, { "answer_id": 50883761, "author": "apadana", "author_id": 3769451, "author_profile": "https://Stackoverflow.com/users/3769451", "pm_score": 3, "selected": false, "text": "module MySampleModule\n CONST1 = \"some constant\"\n\n def self.method_one(arg1)\n arg1 + 2\n end\nend\n puts MySampleModule.method_one(1) # prints: 3\n puts MySampleModule::CONST1 # prints: some constant\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
151,520
<p>It is unclear to me from the <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx" rel="nofollow noreferrer">MSDN documentation</a> if I should provide a deep or a shallow clone when implementing ICloneable. What is the preferred option?</p>
[ { "answer_id": 20873097, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "Foo List<Bar> Foo List<Bar> List<IdentityOfFoo> List<MutableStateOfFoo>" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20164/" ]
151,521
<p>I'm a LINQ to XML newbie, and a KML newbie as well; so bear with me. </p> <p>My goal is to extract individual Placemarks from a KML file. My KML begins thusly:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Document xmlns="http://earth.google.com/kml/2.0"&gt; &lt;name&gt;Concessions&lt;/name&gt; &lt;visibility&gt;1&lt;/visibility&gt; &lt;Folder&gt; &lt;visibility&gt;1&lt;/visibility&gt; &lt;Placemark&gt; &lt;name&gt;IN920211&lt;/name&gt; &lt;Style&gt; &lt;PolyStyle&gt; &lt;color&gt;80000000&lt;/color&gt; &lt;/PolyStyle&gt; &lt;/Style&gt; &lt;Polygon&gt; &lt;altitudeMode&gt;relativeToGround&lt;/altitudeMode&gt; &lt;outerBoundaryIs&gt; &lt;LinearRing&gt; &lt;coordinates&gt;11.728374,1.976421,0 11.732967,1.965322,0 11.737225,1.953161,0 11.635858,1.940812,0 11.658102,1.976874,0 11.728374,1.976421,0 &lt;/coordinates&gt; &lt;/LinearRing&gt; &lt;/outerBoundaryIs&gt; &lt;/Polygon&gt; &lt;/Placemark&gt; &lt;Placemark&gt; ... </code></pre> <p>This is as far as I've gotten:</p> <pre class="lang-vb prettyprint-override"><code> Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml")) Dim Placemarks = From Placemark In Kml.Descendants("Placemark") _ Select Name = Placemark.Element("Name").Value </code></pre> <p>So far no good - Kml.Descendants("Placemark") gives me an empty enumeration. The document is loaded properly - because KML.Descendants contains every node. For what it's worth these queries come up empty as well:</p> <pre><code>Dim foo = Kml.Descendants("Document") Dim foo = Kml.Descendants("Folder") </code></pre> <p>Can someone point me in the right direction? Bonus points for links to good Linq to XML tutorials - the ones I've found online stop at very simple scenarios. </p>
[ { "answer_id": 151561, "author": "Bruce Murdock", "author_id": 23650, "author_profile": "https://Stackoverflow.com/users/23650", "pm_score": 0, "selected": false, "text": "Dim ns as string = \"http://earth.google.com/kml/2.0\"\ndim foo = Kml.Descendants(ns + \"Document\") \n XElement.Name XElement.Name.LocalName/ foreach XElements private string GpNamespace = \n \"{http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions}\";\n\n var results = admldoc.Descendants(GpNamespace + \n \"presentationTable\").Descendants().Select(\n p => new dcPolicyPresentation(p));\n" }, { "answer_id": 153139, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": " ' Read raw XML\n Dim RawXml As String = ReadFile(\"../kmlimport/ga.kml\")\n ' HACK: Linq to XML choking on the namespace, just get rid of it\n RawXml = RawXml.Replace(\"xmlns=\"\"http://earth.google.com/kml/2.0\"\"\", \"\")\n ' Parse XML\n Dim Kml As XDocument = XDocument.Parse(RawXml)\n ' Loop through placemarks\n Dim Placemarks = From Placemark In Kml.<Document>.<Folder>.Descendants(\"Placemark\")\n For Each Placemark As XElement In Placemarks\n Dim Name As String = Placemark.<name>.Value\n ...\n Next\n" }, { "answer_id": 153282, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": true, "text": "Imports <xmlns:g='http://earth.google.com/kml/2.0'>\nImports System.Xml.Linq\n\n ...\n\n Dim Kml As XDocument = XDocument.Load(Server.MapPath(\"../kmlimport/ga.kml\"))\n For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>\n Dim Name As String = Placemark.<g:name>.Value\n Next\n" }, { "answer_id": 223422, "author": "Matthew Ruston", "author_id": 506, "author_profile": "https://Stackoverflow.com/users/506", "pm_score": 1, "selected": false, "text": "// This code should get all Placemarks from a KML file \nvar xdoc = XDocument.Parse(kmlContent);\nXNamespace ns = XNamespace.Get(\"http://earth.google.com/kml/2.0\");\nvar ele = xdoc.Element(ns + \"kml\").Element(ns + \"Document\").Elements(ns + \"Placemark\");\n" }, { "answer_id": 1494001, "author": "Jacob", "author_id": 181298, "author_profile": "https://Stackoverflow.com/users/181298", "pm_score": 3, "selected": false, "text": "XDocument doc = XDocument.Load(@\"TheFile.kml\");\n\nvar q = doc.Descendants().Where(x => x.Name.LocalName == \"Placemark\"); \n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
151,528
<p>I have this big data-entry sort of page, a table kind of layout using divs. Each row has subrows which can be toggled open/closed. The toggling is triggered using css visibility settings. Each "cell" of the table has a little image in its corner, you click on the image, and a popup window opens that allows you to put notes on the entry.</p> <p>This popup window has a text area and a set of checkboxes, along with a button (input type=submit, I think). The popup is an iframe nested inside a hidden div. </p> <p>In IE7, once you've popped open this notes iframe and scrolled the page down, mousing over the popup's textarea makes it disappear and show the page content beneath it. The checkboxes also show the page below when you mouse over.</p> <p>So, I've tried a few different fixes. Z-index was what I was hoping could be used to fix this. no such luck. I might try replacing the text area with a plain input type=text but since the checkboxes also exhibit this bug, I suspect the one-line text input will also cause the bug.</p>
[ { "answer_id": 152633, "author": "user20916", "author_id": 20916, "author_profile": "https://Stackoverflow.com/users/20916", "pm_score": 3, "selected": false, "text": "hasLayout zoom: 1 * {\n zoom: 1;\n}\n zoom" }, { "answer_id": 801622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "filter:alpha(opacity=100)\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13800/" ]
151,544
<p>I'm looking for a cross-browser method of detecting that a client web browser is scrolled all the way to the bottom (or top) of the screen.</p> <p>Really, the top is fairly easy, as<br> <code>scrY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop</code><br> is zero if you're at the top. The problem is that scrY seems to return the top of the scroll bar, and not the bottom, so instead of getting something equivalent to the height of the document (in pixels) I what is presumably the height of the document less the size of the scroll bar.</p> <p>Is there an easy, cross-browser way to find out if the user has scrolled down to the bottom of the document/window? Most specifically, I understand general scroll bar manipulation (setting it, moving it, etc.) but how can I get the delta of the bottom of the scrollbar's position relative to the bottom of the window/document. </p>
[ { "answer_id": 1090683, "author": "yanchenko", "author_id": 15187, "author_profile": "https://Stackoverflow.com/users/15187", "pm_score": 2, "selected": false, "text": "function isTop() {\n return window.pageYOffset == 0;\n}\n\nfunction isBottom() {\n return window.pageYOffset >= window.scrollMaxY;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13623/" ]
151,545
<p>I need to get the fully expanded hostname of the host that my Ruby script is running on. In Perl I've used Sys::Hostname::Long with good results. Google seems to suggest I should use Socket.hostname in ruby, but that's returning just the nodename, not the full hostname.</p>
[ { "answer_id": 151570, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 4, "selected": false, "text": "hostname = Socket.gethostbyname(Socket.gethostname).first \n" }, { "answer_id": 12046321, "author": "Alexis Lê-Quôc", "author_id": 318497, "author_profile": "https://Stackoverflow.com/users/318497", "pm_score": 3, "selected": false, "text": "hostname = Socket.gethostbyname(Socket.gethostname).first\n fqdn = hostname + domainname\n hostname = %[hostname]\ndomainname = %[hostname -f] # minus the first element\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19235/" ]
151,555
<p>I'm creating a Firefox extension for demo purposes. I to call a specific JavaScript function in the document from the extension. I wrote this in my HTML document (not inside extension, but a page that is loaded by Firefox):</p> <pre><code>document.funcToBeCalled = function() { // function body }; </code></pre> <p>Then, the extension will run this on some event:</p> <pre><code>var document = Application.activeWindow.activeTab.document; document.funcToBeCalled(); </code></pre> <p>However it raises an error saying that <code>funcToBeCalled</code> is not defined.</p> <p>Note: I could get an element on the document by calling <code>document.getElementById(id);</code></p>
[ { "answer_id": 2525816, "author": "Carlos Rendon", "author_id": 43851, "author_profile": "https://Stackoverflow.com/users/43851", "pm_score": 3, "selected": false, "text": "document.wrappedJSObject.funcToBeCalled();\n" }, { "answer_id": 2896066, "author": "user307635", "author_id": 307635, "author_profile": "https://Stackoverflow.com/users/307635", "pm_score": 2, "selected": false, "text": "<input type=\"button\" id=\"testbutton\" onclick=\"xyz()\" />\n mainDoc.getElementById('testbutton').click();\n" }, { "answer_id": 60200632, "author": "w04301706", "author_id": 12889712, "author_profile": "https://Stackoverflow.com/users/12889712", "pm_score": 0, "selected": false, "text": "var pattern = \"the url you want to block\";\n\nfunction onExecuted(result) {\nconsole.log(`We made it`);\n}\n\nfunction onError(error) {\nconsole.log(`Error: ${error}`);\n}\n\nfunction redirect(requestDetails) {\nvar callbackName = 'callbackFunction'; //a function in content js\nvar data = getDictForkey('a url');\nvar funcStr = callbackName + '(' + data + ')';\nconst scriptStr = 'var header = document.createElement(\\'button\\');\\n' +\n ' header.setAttribute(\\'onclick\\',\\'' + funcStr + '\\');' +\n ' var t=document.createTextNode(\\'\\');\\n' +\n ' header.appendChild(t);\\n' +\n ' document.body.appendChild(header);' +\n ' header.style.visibility=\"hidden\";' +\n ' header.click();';\nconst executing = browser.tabs.executeScript({\n code: scriptStr\n});\nexecuting.then(onExecuted, onError);\nreturn {\n cancel: true\n}\n}\n\nchrome.webRequest.onBeforeRequest.addListener(\nredirect,\n{urls: [pattern]},\n[\"blocking\"]\n);\n\nfunction getDictForkey(url) {\nxxxx\nreturn xxxx;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11238/" ]
151,587
<p>I'm a huge fan of bzr and I'm glad they're working on tortoise for it, but currently it's WAY too slow to be useful. The icons are almost always incorrect and when I load a directory in explorer with a lot of branches it locks up my entire system for anywhere from 10 seconds to 2 minutes. I look forward to trying it again in the future, but for now I'd like to disable it.</p> <p>Unfortunately I don't see it in add/remove programs and I can't find a way to disable it in the bazaar config directory. When I right click the icon in the task panel (by the clock) and choose "Exit Program" it just restarts moments later. I don't see it in the Services panel either. Is there any way to disable it?</p> <p>I'm running Windows XP on the system in question.</p>
[ { "answer_id": 151911, "author": "Jason Anderson", "author_id": 5142, "author_profile": "https://Stackoverflow.com/users/5142", "pm_score": 2, "selected": false, "text": "python tortoise-bzr.py --unregister\n" }, { "answer_id": 542445, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": true, "text": "regsvr32 /u tbzrshellext_x86.dll\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14651/" ]
151,590
<p>How do you detect if <code>Socket#close()</code> has been called on a socket on the remote side?</p>
[ { "answer_id": 152116, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 7, "selected": true, "text": "isConnected true public class MyServer {\n public static final int PORT = 12345;\n public static void main(String[] args) throws IOException, InterruptedException {\n ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);\n Socket s = ss.accept();\n Thread.sleep(5000);\n ss.close();\n s.close();\n }\n}\n\npublic class MyClient {\n public static void main(String[] args) throws IOException, InterruptedException {\n Socket s = SocketFactory.getDefault().createSocket(\"localhost\", MyServer.PORT);\n System.out.println(\" connected: \" + s.isConnected());\n Thread.sleep(10000);\n System.out.println(\" connected: \" + s.isConnected());\n }\n}\n IOException" }, { "answer_id": 1647054, "author": "Sangamesh", "author_id": 199298, "author_profile": "https://Stackoverflow.com/users/199298", "pm_score": 4, "selected": false, "text": "out.println(output);\nif(out.checkError())\n{\n throw new Exception(\"Error transmitting data.\");\n}\n" }, { "answer_id": 8268497, "author": "Thorsten Niehues", "author_id": 993494, "author_profile": "https://Stackoverflow.com/users/993494", "pm_score": 5, "selected": false, "text": "ServerSocket serverSocket = new ServerSocket(4444);\nSocket clientSocket = serverSocket.accept();\nPrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);\nwhile (true) {\n out.println(\"output\");\n if (out.checkError()) System.out.println(\"ERROR writing data to socket !!!\");\n System.out.println(clientSocket.isConnected());\n System.out.println(clientSocket.getInputStream().read());\n // thread sleep ...\n // break condition , close sockets and the like ...\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ]
151,594
<p>You can have different naming convention for class members, static objects, global objects, and structs. Some of the examples of them are as below.</p> <pre><code>_member m_member </code></pre> <p>or in Java case, the usage of <code>this.member</code>.</p> <p>But is there any good technique or naming convention for function variables scope that conveys when a single variable has complete function scope or a short lifespan scope?</p> <pre><code>void MyFunction() { int functionScopeVariable; if(true) { //no need for function variable scope naming convention } } </code></pre>
[ { "answer_id": 151693, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 0, "selected": false, "text": " m_varname - Class member variables\n g_varname - Global variables\n" }, { "answer_id": 3282684, "author": "Tion", "author_id": 69144, "author_profile": "https://Stackoverflow.com/users/69144", "pm_score": 1, "selected": false, "text": "_memberName _\" Na _ _" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17382/" ]
151,595
<p>I'm looking to try out JRuby and JRuby on Rails. I'm having trouble finding information on what's difference between JRuby on Rails and Ruby on Rails. </p> <p>What's the differences I need to look out for?</p>
[ { "answer_id": 11258063, "author": "kares", "author_id": 454312, "author_profile": "https://Stackoverflow.com/users/454312", "pm_score": 6, "selected": false, "text": "config.threadsafe!" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ]
151,639
<p>I am trying to get the yasnippet and pabbrev packages working together with emacs, but I cannot seem to get any love. How can I get them to play nicely together?</p> <p>The crux of the problem is that pabbrev and yasnippet are binding to the tab keys. Both packages seem to do this fallback when a match isn't found, but they don't fall back properly.</p> <p>I am currently using Emacs W32 (the last emacs 22 release). yasnippet is byte compiled, but pabbrev is not.</p> <p>Edit: Thus far neither tabkey2 nor hippie expand work out of the box, which is why I have yet to mark either solution as a correct answer. I'm hacking away at tabkey2 to make it work though.</p>
[ { "answer_id": 152047, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 2, "selected": false, "text": "(require 'hippie-exp)\n\n(setq hippie-expand-try-functions-list\n '(yas/hippie-try-expand\n try-expand-dabbrev\n try-expand-dabbrev-all-buffers\n try-expand-dabbrev-from-kill\n try-complete-file-name\n try-complete-lisp-symbol))\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11052/" ]
151,641
<p>Banging my head against the wall here. I don't want to reinvent the wheel.</p> <p>The default Flex 3 classs for PopupButton is a combination of two buttons. One is a normal button with label and/or icon, and the second is the arrow which opens the popup. </p> <p>My struggle here is that I just want a button with an icon that opens the popup directly, without having to write all the popup handling code all over again. The plan was to override the PopupButton class with, say, a new class called SimplePopupButton. This class would just hide the arrow, and point the button click handler to open the popup.</p> <p>Seems simple, but I don't see an easy way to do this. Suggestions? Alternatives?</p> <hr> <p>[<strong>Edit</strong>] I want a 16x16 icon button that opens a popup. PopupButton shipped with flex has two buttons: "It contains a main button and a secondary button, called the pop-up button, which pops up any UIComponent object when a user clicks the pop-up button." (<a href="http://livedocs.adobe.com/flex/3/langref/index.html" rel="nofollow noreferrer">source</a>). I want the main button to open the popup, and hide the popup-button. (or vice-versa) </p>
[ { "answer_id": 153567, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 0, "selected": false, "text": "print(</mx:Script>\n <![CDATA[\n import mx.controls.Alert;\n public var myAlert:Alert = new Alert();\n ]]>\n </mx:Script>\n <mx:popUpButton popUp=\"{myAlert}\" label=\"Button\"/>\n" }, { "answer_id": 381515, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<mx:PopUpButton icon=\"@Embed(source='pathToIcon.png')\" arrowButtonWidth=\"16\" paddingLeft=\"0\" paddingRight=\"0\" width=\"16\" height=\"16\" popUp=\"{menu}\"/>\n" }, { "answer_id": 683898, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": ".camButtons\n{\n padding-left:0;\n padding-right:1;\n up-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControlsOver\");\n over-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n down-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n disabled-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n\n pop-up-up-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControlsOver\");\n pop-up-down-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n pop-up-over-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n}\n\n<mx:PopUpButton width=\"38\" popUpGap=\"0\" paddingLeft=\"37\" arrowButtonWidth=\"38\" id=\"flirts_btn\" popUp=\"{flirts_menu}\" styleName=\"camButtons\" icon=\"@Embed(source='/assets/images/skins.swf', symbol='Icon_WinkOver')\" downIcon=\"@Embed(source='/assets/images/skins.swf', symbol='Icon_WinkOver')\" disabledIcon=\"@Embed(source='/assets/images/skins.swf', symbol='Icon_Wink')\" toolTip=\"Send Flirt to User\" buttonMode=\"true\" useHandCursor=\"true\" />\n pop-up-up-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControlsOver\");\n pop-up-down-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n pop-up-over-skin: Embed(source=\"/assets/images/skins.swf\", symbol=\"Button_ChatRoomControls\");\n\n\nwidth=\"38\" popUpGap=\"0\" paddingLeft=\"37\" arrowButtonWidth=\"38\"\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11814/" ]
151,652
<p>This question might not seem programming related at first, but let me explain.</p> <p>I'm stuck with using a keyboard that doesn't have <kbd>home</kbd> <kbd>end</kbd> <kbd>page up</kbd> and <kbd>page down</kbd> buttons. I need those functions for programming.</p> <p>So the question is: what's a good/free utility to define system wide shortcuts and macros in vista? Mapping for example "<kbd>ctrl</kbd>/<kbd>left arrow</kbd> to <kbd>home</kbd>, <kbd>ctrl</kbd>/<kbd>right arrow</kbd> to <kbd>end</kbd> would solve my problem.</p>
[ { "answer_id": 153653, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 1, "selected": false, "text": "#Right::End\n#Left::Home \n#Up::PgUp\n#Down::PgDn\n#BS::Del\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
151,660
<p>In PHP5, is the __destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?</p>
[ { "answer_id": 8293937, "author": "Mikko Rantalainen", "author_id": 334451, "author_profile": "https://Stackoverflow.com/users/334451", "pm_score": 4, "selected": false, "text": "exit() FATAL" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ]
151,677
<p>I'm looking for a tool that will, in bulk, add a license header to some source files, some of which already have the header. Is there a tool out there that will insert a header, if it is not already present?</p> <p><em>Edit: I am intentionally not marking an answer to this question, since answers are basically all environment-specific and subjective</em> </p>
[ { "answer_id": 151684, "author": "Silver Dragon", "author_id": 9440, "author_profile": "https://Stackoverflow.com/users/9440", "pm_score": 4, "selected": false, "text": "excludedir # updates the copyright information for all .cs files\n# usage: call recursive_traversal, with the following parameters\n# parent directory, old copyright text content, new copyright text content\n\nimport os\n\nexcludedir = [\"..\\\\Lib\"]\n\ndef update_source(filename, oldcopyright, copyright):\n utfstr = chr(0xef)+chr(0xbb)+chr(0xbf)\n fdata = file(filename,\"r+\").read()\n isUTF = False\n if (fdata.startswith(utfstr)):\n isUTF = True\n fdata = fdata[3:]\n if (oldcopyright != None):\n if (fdata.startswith(oldcopyright)):\n fdata = fdata[len(oldcopyright):]\n if not (fdata.startswith(copyright)):\n print \"updating \"+filename\n fdata = copyright + fdata\n if (isUTF):\n file(filename,\"w\").write(utfstr+fdata)\n else:\n file(filename,\"w\").write(fdata)\n\ndef recursive_traversal(dir, oldcopyright, copyright):\n global excludedir\n fns = os.listdir(dir)\n print \"listing \"+dir\n for fn in fns:\n fullfn = os.path.join(dir,fn)\n if (fullfn in excludedir):\n continue\n if (os.path.isdir(fullfn)):\n recursive_traversal(fullfn, oldcopyright, copyright)\n else:\n if (fullfn.endswith(\".cs\")):\n update_source(fullfn, oldcopyright, copyright)\n \n \noldcright = file(\"oldcr.txt\",\"r+\").read()\ncright = file(\"copyrightText.txt\",\"r+\").read()\nrecursive_traversal(\"..\", oldcright, cright)\nexit()\n" }, { "answer_id": 151690, "author": "Tim", "author_id": 23665, "author_profile": "https://Stackoverflow.com/users/23665", "pm_score": 7, "selected": true, "text": "#!/bin/bash\n\nfor i in *.cc # or whatever other pattern...\ndo\n if ! grep -q Copyright $i\n then\n cat copyright.txt $i >$i.new && mv $i.new $i\n fi\ndone\n" }, { "answer_id": 151699, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "#!/bin/bash \nfor x in $*; do \nhead -$LICENSELEN $x | diff license.txt - || ( ( cat license.txt; echo; cat $x) > /tmp/file; \nmv /tmp/file $x ) \ndone \n export LICENSELEN=`wc -l license.txt | cut -f1 -d ' '` \nfind . -type f \\(-name \\*.cpp -o -name \\*.h \\) -print0 | xargs -0 ./addlicense.sh \n" }, { "answer_id": 9671565, "author": "Jens Timmerman", "author_id": 869482, "author_profile": "https://Stackoverflow.com/users/869482", "pm_score": 4, "selected": false, "text": "#!/usr/bin/python\n\"\"\"\nThis script attempts to add a header to each file in the given directory \nThe header will be put the line after a Shebang (#!) if present.\nIf a line starting with a regular expression 'skip' is present as first line or after the shebang it will ignore that file.\nIf filename is given only files matchign the filename regex will be considered for adding the license to,\nby default this is '*'\n\nusage: python addheader.py headerfile directory [filenameregex [dirregex [skip regex]]]\n\neasy example: add header to all files in this directory:\npython addheader.py licenseheader.txt . \n\nharder example adding someone as copyrightholder to all python files in a source directory,exept directories named 'includes' where he isn't added yet:\npython addheader.py licenseheader.txt src/ \".*\\.py\" \"^((?!includes).)*$\" \"#Copyright .* Jens Timmerman*\" \nwhere licenseheader.txt contains '#Copyright 2012 Jens Timmerman'\n\"\"\"\nimport os\nimport re\nimport sys\n\ndef writeheader(filename,header,skip=None):\n \"\"\"\n write a header to filename, \n skip files where first line after optional shebang matches the skip regex\n filename should be the name of the file to write to\n header should be a list of strings\n skip should be a regex\n \"\"\"\n f = open(filename,\"r\")\n inpt =f.readlines()\n f.close()\n output = []\n\n #comment out the next 3 lines if you don't wish to preserve shebangs\n if len(inpt) > 0 and inpt[0].startswith(\"#!\"): \n output.append(inpt[0])\n inpt = inpt[1:]\n\n if skip and skip.match(inpt[0]): #skip matches, so skip this file\n return\n\n output.extend(header) #add the header\n for line in inpt:\n output.append(line)\n try:\n f = open(filename,'w')\n f.writelines(output)\n f.close()\n print \"added header to %s\" %filename\n except IOError,err:\n print \"something went wrong trying to add header to %s: %s\" % (filename,err)\n\n\ndef addheader(directory,header,skipreg,filenamereg,dirregex):\n \"\"\"\n recursively adds a header to all files in a dir\n arguments: see module docstring\n \"\"\"\n listing = os.listdir(directory)\n print \"listing: %s \" %listing\n #for each file/dir in this dir\n for i in listing:\n #get the full name, this way subsubdirs with the same name don't get ignored\n fullfn = os.path.join(directory,i) \n if os.path.isdir(fullfn): #if dir, recursively go in\n if (dirregex.match(fullfn)):\n print \"going into %s\" % fullfn\n addheader(fullfn, header,skipreg,filenamereg,dirregex)\n else:\n if (filenamereg.match(fullfn)): #if file matches file regex, write the header\n writeheader(fullfn, header,skipreg)\n\n\ndef main(arguments=sys.argv):\n \"\"\"\n main function: parses arguments and calls addheader\n \"\"\"\n ##argument parsing\n if len(arguments) > 6 or len(arguments) < 3:\n sys.stderr.write(\"Usage: %s headerfile directory [filenameregex [dirregex [skip regex]]]\\n\" \\\n \"Hint: '.*' is a catch all regex\\nHint:'^((?!regexp).)*$' negates a regex\\n\"%sys.argv[0])\n sys.exit(1)\n\n skipreg = None\n fileregex = \".*\"\n dirregex = \".*\"\n if len(arguments) > 5:\n skipreg = re.compile(arguments[5])\n if len(arguments) > 3:\n fileregex = arguments[3]\n if len(arguments) > 4:\n dirregex = arguments[4]\n #compile regex \n fileregex = re.compile(fileregex)\n dirregex = re.compile(dirregex)\n #read in the headerfile just once\n headerfile = open(arguments[1])\n header = headerfile.readlines()\n headerfile.close()\n addheader(arguments[2],header,skipreg,fileregex,dirregex)\n\n#call the main method\nmain()\n" }, { "answer_id": 11531530, "author": "Erik Osterman", "author_id": 1237191, "author_profile": "https://Stackoverflow.com/users/1237191", "pm_score": 4, "selected": false, "text": "sudo gem install copyright-header copyright-header --license GPL3 \\\n --add-path lib/ \\\n --copyright-holder 'Dude1 <dude1@host.com>' \\\n --copyright-holder 'Dude2 <dude2@host.com>' \\\n --copyright-software 'Super Duper' \\\n --copyright-software-description \"A program that makes life easier\" \\\n --copyright-year 2012 \\\n --copyright-year 2012 \\\n --word-wrap 80 --output-dir ./\n" }, { "answer_id": 16127586, "author": "Josh Ribakoff", "author_id": 2279347, "author_profile": "https://Stackoverflow.com/users/2279347", "pm_score": 2, "selected": false, "text": "<?php\nclass Licenses\n{\n protected $paths = array();\n protected $oldTxt = '/**\n * Old license to delete\n */';\n protected $newTxt = '/**\n * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)\n */';\n\n function licensesForDir($path)\n {\n foreach(glob($path.'/*') as $eachPath)\n {\n if(is_dir($eachPath))\n {\n $this->licensesForDir($eachPath);\n }\n if(preg_match('#\\.php#',$eachPath))\n {\n $this->paths[] = $eachPath;\n }\n }\n }\n\n function exec()\n {\n\n $this->licensesForDir('.');\n foreach($this->paths as $path)\n {\n $this->handleFile($path);\n }\n }\n\n function handleFile($path)\n {\n $source = file_get_contents($path);\n $source = str_replace($this->oldTxt, '', $source);\n $source = preg_replace('#\\<\\?php#',\"<?php\\n\".$this->newTxt,$source,1);\n file_put_contents($path,$source);\n echo $path.\"\\n\";\n }\n}\n\n$licenses = new Licenses;\n$licenses->exec();\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5897/" ]
151,682
<pre><code> &lt;my:DataGridTemplateColumn CanUserResize="False" Width="150" Header="{Binding MeetingName, Source={StaticResource LocStrings}}" SortMemberPath="MeetingName"&gt; &lt;/my:DataGridTemplateColumn&gt; </code></pre> <p>I have the above column in a Silverlight grid control. But it is giving me a XamlParser error because of how I am trying to set the Header property. Has anyone done this before? I want to do this for multiple languages.</p> <p>Also my syntax for the binding to a resouce is correct because I tried it in a lable outside of the grid.</p>
[ { "answer_id": 151879, "author": "Adam Kinney", "author_id": 1973, "author_profile": "https://Stackoverflow.com/users/1973", "pm_score": 6, "selected": true, "text": "xmlns:data=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data\"\nxmlns:dataprimitives=\"clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data\"\n\n<data:DataGridTemplateColumn> \n <data:DataGridTemplateColumn.HeaderStyle>\n <Style TargetType=\"dataprimitives:DataGridColumnHeader\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate> \n <TextBlock Text=\"{Binding MeetingName, Source={StaticResource LocStrings}}\" /> \n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </data:DataGridTemplateColumn.HeaderStyle>\n</data:DataGridTemplateColumn>\n" }, { "answer_id": 2208696, "author": "Jersey Dude", "author_id": 33787, "author_profile": "https://Stackoverflow.com/users/33787", "pm_score": 1, "selected": false, "text": "dg1.Columns[3].Header = SomeDynamicValue;\n" }, { "answer_id": 2584831, "author": "Dimitar", "author_id": 310013, "author_profile": "https://Stackoverflow.com/users/310013", "pm_score": 0, "selected": false, "text": " HeaderTextBlock.SetBinding(TextBlock.TextProperty, HeaderBinding);\n" }, { "answer_id": 3627372, "author": "Lars Holm Jensen", "author_id": 348005, "author_profile": "https://Stackoverflow.com/users/348005", "pm_score": 4, "selected": false, "text": "<Setter Property=\"ContentTemplate\">\n<Setter.Value>\n <DataTemplate>\n <Image Source=\"<image url goes here>\"/>\n </DataTemplate>\n</Setter.Value>\n" }, { "answer_id": 5246350, "author": "Rudi", "author_id": 45045, "author_profile": "https://Stackoverflow.com/users/45045", "pm_score": 2, "selected": false, "text": "IValueConverter public class BindingConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value.GetType().Name == \"Binding\")\n {\n ContentControl cc = new ContentControl();\n cc.SetBinding(ContentControl.ContentProperty, value as Binding);\n return cc;\n }\n else return value;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n\n return null;\n }\n}\n DataGridColumnHeader <UserControl.Resources>\n <local:BindingConverter x:Key=\"BindCon\"/>\n <Style x:Key=\"ColBinding\" TargetType=\"dataprimitives:DataGridColumnHeader\" >\n <Setter Property=\"ContentTemplate\" >\n <Setter.Value>\n <DataTemplate>\n <ContentPresenter Content=\"{Binding Converter={StaticResource BindCon}}\" />\n </DataTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</UserControl.Resources>\n Header <Grid x:Name=\"LayoutRoot\" Background=\"White\">\n <StackPanel>\n <TextBox Text=\"binding header\" x:Name=\"tbox\" />\n\n <data:DataGrid ItemsSource=\"{Binding AllPeople,Source={StaticResource folks}}\" AutoGenerateColumns=\"False\" ColumnHeaderStyle=\"{StaticResource ColBinding}\" >\n <data:DataGrid.Columns>\n <data:DataGridTextColumn Binding=\"{Binding ID}\" \n\n Header=\"{Binding Text, ElementName=tbox}\" />\n <data:DataGridTextColumn Binding=\"{Binding Name}\" \n\n Header=\"hello\" />\n </data:DataGrid.Columns>\n </data:DataGrid>\n </StackPanel>\n\n</Grid>\n" }, { "answer_id": 5833800, "author": "RobSiklos", "author_id": 270348, "author_profile": "https://Stackoverflow.com/users/270348", "pm_score": 4, "selected": false, "text": "public static class DataGridColumnHelper\n{\n public static readonly DependencyProperty HeaderBindingProperty = DependencyProperty.RegisterAttached(\n \"HeaderBinding\",\n typeof(object),\n typeof(DataGridColumnHelper),\n new PropertyMetadata(null, DataGridColumnHelper.HeaderBinding_PropertyChanged));\n\n public static object GetHeaderBinding(DependencyObject source)\n {\n return (object)source.GetValue(DataGridColumnHelper.HeaderBindingProperty);\n }\n\n public static void SetHeaderBinding(DependencyObject target, object value)\n {\n target.SetValue(DataGridColumnHelper.HeaderBindingProperty, value);\n }\n\n private static void HeaderBinding_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n DataGridColumn column = d as DataGridColumn;\n\n if (column == null) { return; }\n\n column.Header = e.NewValue;\n }\n}\n <data:DataGridTextColumn util:DataGridColumnHelper.HeaderBinding=\"{Binding MeetingName, Source={StaticResource LocStrings}}\" />\n" }, { "answer_id": 8093741, "author": "Steve", "author_id": 1041659, "author_profile": "https://Stackoverflow.com/users/1041659", "pm_score": 2, "selected": false, "text": "dg1.Columns[3].Header = SomeDynamicValue;\n dg1.Columns[3].Header" }, { "answer_id": 18269929, "author": "Jit", "author_id": 2688869, "author_profile": "https://Stackoverflow.com/users/2688869", "pm_score": 1, "selected": false, "text": "Binding DataContext.SelectedHistoryTypeItem,RelativeSource={RelativeSource AncestorType=sdk:DataGrid},\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23663/" ]
151,686
<p><strong><em>Note</strong>: The code in this question is part of <a href="http://www.codeplex.com/desleeper" rel="noreferrer">deSleeper</a> if you want the full source.</em></p> <p>One of the things I wanted out of commands was a baked design for asynchronous operations. I wanted the button pressed to disable while the command was executing, and come back when complete. I wanted the actual work to be performed in a ThreadPool work item. And lastly, I wanted a way to handle any errors that occurred during the asynchronous processing.</p> <p>My solution was an AsyncCommand:</p> <pre><code>public abstract class AsyncCommand : ICommand { public event EventHandler CanExecuteChanged; public event EventHandler ExecutionStarting; public event EventHandler&lt;AsyncCommandCompleteEventArgs&gt; ExecutionComplete; public abstract string Text { get; } private bool _isExecuting; public bool IsExecuting { get { return _isExecuting; } private set { _isExecuting = value; if (CanExecuteChanged != null) CanExecuteChanged(this, EventArgs.Empty); } } protected abstract void OnExecute(object parameter); public void Execute(object parameter) { try { IsExecuting = true; if (ExecutionStarting != null) ExecutionStarting(this, EventArgs.Empty); var dispatcher = Dispatcher.CurrentDispatcher; ThreadPool.QueueUserWorkItem( obj =&gt; { try { OnExecute(parameter); if (ExecutionComplete != null) dispatcher.Invoke(DispatcherPriority.Normal, ExecutionComplete, this, new AsyncCommandCompleteEventArgs(null)); } catch (Exception ex) { if (ExecutionComplete != null) dispatcher.Invoke(DispatcherPriority.Normal, ExecutionComplete, this, new AsyncCommandCompleteEventArgs(ex)); } finally { dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =&gt; IsExecuting = false)); } }); } catch (Exception ex) { IsExecuting = false; if (ExecutionComplete != null) ExecutionComplete(this, new AsyncCommandCompleteEventArgs(ex)); } } public virtual bool CanExecute(object parameter) { return !IsExecuting; } } </code></pre> <p>so the question is: Is all this necessary? I've noticed built in asynchronous support for data-binding, so why not command execution? Perhaps it's related to the parameter question, which is my next question.</p>
[ { "answer_id": 228713, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 3, "selected": true, "text": "public abstract class AsyncCommand : ICommand\n{\n public event EventHandler CanExecuteChanged;\n public event EventHandler RunWorkerStarting;\n public event RunWorkerCompletedEventHandler RunWorkerCompleted;\n\n public abstract string Text { get; }\n private bool _isExecuting;\n public bool IsExecuting\n {\n get { return _isExecuting; }\n private set\n {\n _isExecuting = value;\n if (CanExecuteChanged != null)\n CanExecuteChanged(this, EventArgs.Empty);\n }\n }\n\n protected abstract void OnExecute(object parameter);\n\n public void Execute(object parameter)\n { \n try\n { \n onRunWorkerStarting();\n\n var worker = new BackgroundWorker();\n worker.DoWork += ((sender, e) => OnExecute(e.Argument));\n worker.RunWorkerCompleted += ((sender, e) => onRunWorkerCompleted(e));\n worker.RunWorkerAsync(parameter);\n }\n catch (Exception ex)\n {\n onRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, ex, true));\n }\n }\n\n private void onRunWorkerStarting()\n {\n IsExecuting = true;\n if (RunWorkerStarting != null)\n RunWorkerStarting(this, EventArgs.Empty);\n }\n\n private void onRunWorkerCompleted(RunWorkerCompletedEventArgs e)\n {\n IsExecuting = false;\n if (RunWorkerCompleted != null)\n RunWorkerCompleted(this, e);\n }\n\n public virtual bool CanExecute(object parameter)\n {\n return !IsExecuting;\n }\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5504/" ]
151,687
<p>I'm developing an embedded system which currently boots linux with console output on serial port 1 (using the console boot param from the boot loader). However, eventually we will be using this serial port. What is the best solution for the kernel console output? /dev/null? Can it be put on a pty somehow so that we could potentially get access to it?</p>
[ { "answer_id": 228713, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 3, "selected": true, "text": "public abstract class AsyncCommand : ICommand\n{\n public event EventHandler CanExecuteChanged;\n public event EventHandler RunWorkerStarting;\n public event RunWorkerCompletedEventHandler RunWorkerCompleted;\n\n public abstract string Text { get; }\n private bool _isExecuting;\n public bool IsExecuting\n {\n get { return _isExecuting; }\n private set\n {\n _isExecuting = value;\n if (CanExecuteChanged != null)\n CanExecuteChanged(this, EventArgs.Empty);\n }\n }\n\n protected abstract void OnExecute(object parameter);\n\n public void Execute(object parameter)\n { \n try\n { \n onRunWorkerStarting();\n\n var worker = new BackgroundWorker();\n worker.DoWork += ((sender, e) => OnExecute(e.Argument));\n worker.RunWorkerCompleted += ((sender, e) => onRunWorkerCompleted(e));\n worker.RunWorkerAsync(parameter);\n }\n catch (Exception ex)\n {\n onRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, ex, true));\n }\n }\n\n private void onRunWorkerStarting()\n {\n IsExecuting = true;\n if (RunWorkerStarting != null)\n RunWorkerStarting(this, EventArgs.Empty);\n }\n\n private void onRunWorkerCompleted(RunWorkerCompletedEventArgs e)\n {\n IsExecuting = false;\n if (RunWorkerCompleted != null)\n RunWorkerCompleted(this, e);\n }\n\n public virtual bool CanExecute(object parameter)\n {\n return !IsExecuting;\n }\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20889/" ]
151,701
<p>Our company runs a web site (oursite.com) with affiliate partners who send us traffic. In some cases, we set up our affiliates with their own subdomain (affiliate.oursite.com), and they display selected content from our site on their site (affiliate.com) using an iframe.</p> <p>Example of a page on their site:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;iframe src="affiliate.example.com/example_page.html"&gt; ...content... [google analytics code for affiliate.oursite.com] &lt;/iframe&gt; [google analytics code for affiliate.com] &lt;/body&gt; &lt;/html&gt; </code></pre> <p>We would like to have Google Analytics tracking for affiliate.oursite.com. At present, it does not seem that Google is receiving any data from the affiliate when the page is loaded from the iframe.</p> <p>Now, there are security implications in that Javascript doesn't like accessing information about a page in a different domain, and IE doesn't like setting cookies for a different domain.</p> <p>Does anyone have a solution to this? Will we need to CNAME the affiliate.oursite.com to cname.oursite.com, or is there a cleaner solution?</p>
[ { "answer_id": 152389, "author": "Silver Dragon", "author_id": 9440, "author_profile": "https://Stackoverflow.com/users/9440", "pm_score": 5, "selected": true, "text": "example_page.html <iframe> </iframe>" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15088/" ]
151,731
<p>I've been trying to submit a form with the FormPanel using the Action class Ext defaults to. However, I'd like it to consider the response as a script, not JSON-encoded.</p> <p>Has anyone had any experience on this?</p>
[ { "answer_id": 152134, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 3, "selected": true, "text": "Ext.form.Action eval response result success Ext.form.BasicForm" }, { "answer_id": 1160562, "author": "Ballsacian1", "author_id": 100658, "author_profile": "https://Stackoverflow.com/users/100658", "pm_score": 1, "selected": false, "text": "Form.getForm().submit() Ext.ajax.request Ext.data.ScriptTagProxy" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5646/" ]
151,752
<p>I've created some fairly simple XAML, and it works perfectly (at least in KAXML). The storyboards run perfectly when called from within the XAML, but when I try to access them from outside I get the error:</p> <pre><code>'buttonGlow' name cannot be found in the name scope of 'System.Windows.Controls.Button'. </code></pre> <p>I am loading the XAML with a stream reader, like this:</p> <pre><code>Button x = (Button)XamlReader.Load(stream); </code></pre> <p>And trying to run the Storyboard with: </p> <pre><code>Storyboard pressedButtonStoryboard = Storyboard)_xamlButton.Template.Resources["ButtonPressed"]; pressedButtonStoryboard.Begin(_xamlButton); </code></pre> <p>I think that the problem is that fields I am animating are in the template and that storyboard is accessing the button. </p> <p>Here is the XAML:</p> <pre><code>&lt;Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:customControls="clr-namespace:pk_rodoment.SkinningEngine;assembly=pk_rodoment" Width="150" Height="55"&gt; &lt;Button.Resources&gt; &lt;Style TargetType="Button"&gt; &lt;Setter Property="Control.Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="Button"&gt; &lt;Grid Background="#00FFFFFF"&gt; &lt;Grid.BitmapEffect&gt; &lt;BitmapEffectGroup&gt; &lt;OuterGlowBitmapEffect x:Name="buttonGlow" GlowColor="#A0FEDF00" GlowSize="0"/&gt; &lt;/BitmapEffectGroup&gt; &lt;/Grid.BitmapEffect&gt; &lt;Border x:Name="background" Margin="1,1,1,1" CornerRadius="15"&gt; &lt;Border.Background&gt; &lt;SolidColorBrush Color="#FF0062B6"/&gt; &lt;/Border.Background&gt; &lt;/Border&gt; &lt;ContentPresenter HorizontalAlignment="Center" Margin="{TemplateBinding Control.Padding}" VerticalAlignment="Center" Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"/&gt; &lt;/Grid&gt; &lt;ControlTemplate.Resources&gt; &lt;Storyboard x:Key="ButtonPressed"&gt; &lt;Storyboard.Children&gt; &lt;DoubleAnimation Duration="0:0:0.4" FillBehavior="HoldEnd" Storyboard.TargetName="buttonGlow" Storyboard.TargetProperty="GlowSize" To="4"/&gt; &lt;ColorAnimation Duration="0:0:0.6" FillBehavior="HoldEnd" Storyboard.TargetName="background" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" To="#FF844800"/&gt; &lt;/Storyboard.Children&gt; &lt;/Storyboard&gt; &lt;Storyboard x:Key="ButtonReleased"&gt; &lt;Storyboard.Children&gt; &lt;DoubleAnimation Duration="0:0:0.2" FillBehavior="HoldEnd" Storyboard.TargetName="buttonGlow" Storyboard.TargetProperty="GlowSize" To="0"/&gt; &lt;ColorAnimation Duration="0:0:0.2" FillBehavior="Stop" Storyboard.TargetName="background" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" To="#FF0062B6"/&gt; &lt;/Storyboard.Children&gt; &lt;/Storyboard&gt; &lt;/ControlTemplate.Resources&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="ButtonBase.IsPressed" Value="True"&gt; &lt;Trigger.EnterActions&gt; &lt;BeginStoryboard Storyboard="{StaticResource ButtonPressed}"/&gt; &lt;/Trigger.EnterActions&gt; &lt;Trigger.ExitActions&gt; &lt;BeginStoryboard Storyboard="{StaticResource ButtonReleased}"/&gt; &lt;/Trigger.ExitActions&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Button.Resources&gt; &lt;DockPanel&gt; &lt;TextBlock x:Name="TextContent" FontSize="28" Foreground="White" &gt;Test&lt;/TextBlock&gt; &lt;/DockPanel&gt; &lt;/Button&gt; </code></pre> <p>Any suggestions from anyone who understands WPF and XAML a lot better than me?</p> <p>Here is the error stacktrace:</p> <pre><code>at System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element) at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer) at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer) at System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer) at System.Windows.Media.Animation.Storyboard.Begin(FrameworkElement containingObject) at pk_rodoment.SkinningEngine.ButtonControlWPF._button_MouseDown(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at ControlTestbed.App.Main() in C:\svnprojects\rodomont\ControlsTestbed\obj\Debug\App.g.cs:line 0 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() </code></pre>
[ { "answer_id": 154189, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 5, "selected": true, "text": "pressedButtonStoryboard.Begin(_xamlButton);\n pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);\n" }, { "answer_id": 154203, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 3, "selected": false, "text": "SolidColorBrush OuterGlowBitmapEffect Storyboard Storyboard Begin() Button \"buttonGlow\" \"borderBackground\" StaticResource <Button\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Width=\"150\"\n Height=\"55\">\n <Button.Resources>\n <OuterGlowBitmapEffect\n x:Key=\"buttonGlow\"\n GlowColor=\"#A0FEDF00\"\n GlowSize=\"0\" />\n <SolidColorBrush\n x:Key=\"borderBackground\"\n Color=\"#FF0062B6\" />\n <Style\n TargetType=\"Button\">\n <Setter\n Property=\"Control.Template\">\n <Setter.Value>\n <ControlTemplate\n TargetType=\"Button\">\n <Grid\n Name=\"outerGrid\"\n Background=\"#00FFFFFF\"\n BitmapEffect=\"{StaticResource buttonGlow}\">\n <Border\n x:Name=\"background\"\n Margin=\"1,1,1,1\"\n CornerRadius=\"15\"\n Background=\"{StaticResource borderBackground}\">\n </Border>\n <ContentPresenter\n HorizontalAlignment=\"Center\"\n Margin=\"{TemplateBinding Control.Padding}\"\n VerticalAlignment=\"Center\"\n Content=\"{TemplateBinding ContentControl.Content}\"\n ContentTemplate=\"{TemplateBinding ContentControl.ContentTemplate}\" />\n </Grid>\n <ControlTemplate.Resources>\n <Storyboard\n x:Key=\"ButtonPressed\">\n <Storyboard.Children>\n <DoubleAnimation\n Duration=\"0:0:0.4\"\n FillBehavior=\"HoldEnd\"\n Storyboard.Target=\"{StaticResource buttonGlow}\"\n Storyboard.TargetProperty=\"GlowSize\"\n To=\"4\" />\n <ColorAnimation\n Duration=\"0:0:0.6\"\n FillBehavior=\"HoldEnd\"\n Storyboard.Target=\"{StaticResource borderBackground}\"\n Storyboard.TargetProperty=\"Color\"\n To=\"#FF844800\" />\n </Storyboard.Children>\n </Storyboard>\n <Storyboard\n x:Key=\"ButtonReleased\">\n <Storyboard.Children>\n <DoubleAnimation\n Duration=\"0:0:0.2\"\n FillBehavior=\"HoldEnd\"\n Storyboard.Target=\"{StaticResource buttonGlow}\"\n Storyboard.TargetProperty=\"GlowSize\"\n To=\"0\" />\n <ColorAnimation\n Duration=\"0:0:0.2\"\n FillBehavior=\"Stop\"\n Storyboard.Target=\"{StaticResource borderBackground}\"\n Storyboard.TargetProperty=\"Color\"\n To=\"#FF0062B6\" />\n </Storyboard.Children>\n </Storyboard>\n </ControlTemplate.Resources>\n <ControlTemplate.Triggers>\n <Trigger\n Property=\"ButtonBase.IsPressed\"\n Value=\"True\">\n <Trigger.EnterActions>\n <BeginStoryboard\n Storyboard=\"{StaticResource ButtonPressed}\" />\n </Trigger.EnterActions>\n <Trigger.ExitActions>\n <BeginStoryboard\n Storyboard=\"{StaticResource ButtonReleased}\" />\n </Trigger.ExitActions>\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </Button.Resources>\n <DockPanel>\n <TextBlock\n x:Name=\"TextContent\"\n FontSize=\"28\"\n Foreground=\"White\">Test</TextBlock>\n </DockPanel>\n</Button>\n" }, { "answer_id": 6055265, "author": "Emmanuel", "author_id": 446066, "author_profile": "https://Stackoverflow.com/users/446066", "pm_score": 1, "selected": false, "text": "pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);\n pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template,true);\n pressedButtonStoryboard.Stop(xamlButton)\n" }, { "answer_id": 7067483, "author": "ouflak", "author_id": 446477, "author_profile": "https://Stackoverflow.com/users/446477", "pm_score": 1, "selected": false, "text": " this.RegisterName(\"button1\", this.button1);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
151,756
<p>Is it possible for a web server to know which <em>type</em> of device request has been received from?</p> <p>For example, can a create a website which shows different contents if request came from a computer (Firefox) and something different if it came from iPhone?</p>
[ { "answer_id": 151759, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "User-Agent" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23671/" ]
151,769
<p>Originally there was the DAL object which my BO's called for info and then passed to UI. Then I started noticing reduced code in UI and there were Controller classes. What's the decent recomendation.</p> <p>I currently structure mine</p> <pre><code>Public Class OrderDAL Private _id Integer Private _order as Order Public Function GetOrder(id as Integer) as Order ...return Order End Function End Class </code></pre> <p>then I have controller classes (recently implemented this style)</p> <pre><code>Public Class OrderController Private Shared _orderDAL as new OrderDAL Public Shared Function GetOrder(id) As Order Return _orderDAL.GetOrder(id) End Function End Class </code></pre> <p>Then in my application</p> <pre><code>My app Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click msgbox(OrderController.GetOrder(12345).Customer.Name) End Sub End app </code></pre> <p>I originally found that with the Shared Class I didn't have to keep creating a new instance of the DAL whenever I need to fetch data</p> <pre><code>Dim _orderDAL as New OrderDal _orderDAL.GetOrder(1234) ..... </code></pre> <p>What's your take?</p> <p>Thanks</p>
[ { "answer_id": 152228, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": true, "text": "OrderControllerFactory.ConfiguredOrderController().GetOrder(42);\n public interface IOrderController\n{\n Order GetOrder(int Id)\n}\n\npublic class OrderController: IOrderController\n{\n public Order GetOrder(int Id)\n {}\n}\n public class OrderControllerFactory()\n{\n public IOrderController ConfiguredOrderController()\n {}\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
151,777
<p>I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example:</p> <pre class="lang-java prettyprint-override"><code>package com.android.hello; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { private TextView mTextView = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTextView = new TextView(this); if (savedInstanceState == null) { mTextView.setText(&quot;Welcome to HelloAndroid!&quot;); } else { mTextView.setText(&quot;Welcome back.&quot;); } setContentView(mTextView); } } </code></pre> <p>I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.</p> <p>I'm sure the solution is as simple as overriding <code>onPause</code> or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious.</p>
[ { "answer_id": 151822, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 9, "selected": false, "text": "savedInstanceState onCreate onSaveInstanceState" }, { "answer_id": 151940, "author": "Reto Meier", "author_id": 822, "author_profile": "https://Stackoverflow.com/users/822", "pm_score": 12, "selected": true, "text": "onSaveInstanceState(Bundle savedInstanceState) Bundle @Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n super.onSaveInstanceState(savedInstanceState);\n // Save UI state changes to the savedInstanceState.\n // This bundle will be passed to onCreate if the process is\n // killed and restarted.\n savedInstanceState.putBoolean(\"MyBoolean\", true);\n savedInstanceState.putDouble(\"myDouble\", 1.9);\n savedInstanceState.putInt(\"MyInt\", 1);\n savedInstanceState.putString(\"MyString\", \"Welcome back to Android\");\n // etc.\n}\n onCreate() onRestoreInstanceState() @Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n // Restore UI state from the savedInstanceState.\n // This bundle has also been passed to onCreate.\n boolean myBoolean = savedInstanceState.getBoolean(\"MyBoolean\");\n double myDouble = savedInstanceState.getDouble(\"myDouble\");\n int myInt = savedInstanceState.getInt(\"MyInt\");\n String myString = savedInstanceState.getString(\"MyString\");\n}\n @Override\npublic void onViewStateRestored(@Nullable Bundle savedInstanceState) {\n super.onViewStateRestored(savedInstanceState);\n // Restore UI state from the savedInstanceState.\n // This bundle has also been passed to onCreate.\n boolean myBoolean = savedInstanceState.getBoolean(\"MyBoolean\");\n double myDouble = savedInstanceState.getDouble(\"myDouble\");\n int myInt = savedInstanceState.getInt(\"MyInt\");\n String myString = savedInstanceState.getString(\"MyString\");\n}\n" }, { "answer_id": 2785419, "author": "Fedor", "author_id": 95313, "author_profile": "https://Stackoverflow.com/users/95313", "pm_score": 7, "selected": false, "text": "onSaveInstanceState onPause Preferences" }, { "answer_id": 2893765, "author": "u-foka", "author_id": 347184, "author_profile": "https://Stackoverflow.com/users/347184", "pm_score": 6, "selected": false, "text": "onSaveInstanceState()" }, { "answer_id": 2909211, "author": "Steve Moseley", "author_id": 299472, "author_profile": "https://Stackoverflow.com/users/299472", "pm_score": 9, "selected": false, "text": "onSaveInstanceState onRestoreInstanceState onPause() onSaveInstanceState(Bundle) onPause() onResume() onSaveInstanceState() onCreate(Bundle) onRestoreInstanceState(Bundle)" }, { "answer_id": 3584836, "author": "Martin Belcher - AtWrk", "author_id": 379115, "author_profile": "https://Stackoverflow.com/users/379115", "pm_score": 8, "selected": false, "text": "Bundle SharedPreferences [Code sample – Store state in state bundle]\n@Override\npublic void onSaveInstanceState(Bundle savedInstanceState)\n{\n // Store UI state to the savedInstanceState.\n // This bundle will be passed to onCreate on next call. EditText txtName = (EditText)findViewById(R.id.txtName);\n String strName = txtName.getText().toString();\n\n EditText txtEmail = (EditText)findViewById(R.id.txtEmail);\n String strEmail = txtEmail.getText().toString();\n\n CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);\n boolean blnTandC = chkTandC.isChecked();\n\n savedInstanceState.putString(“Name”, strName);\n savedInstanceState.putString(“Email”, strEmail);\n savedInstanceState.putBoolean(“TandC”, blnTandC);\n\n super.onSaveInstanceState(savedInstanceState);\n}\n [Code sample – store state in SharedPreferences]\n@Override\nprotected void onPause()\n{\n super.onPause();\n\n // Store values between instances here\n SharedPreferences preferences = getPreferences(MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI\n EditText txtName = (EditText)findViewById(R.id.txtName);\n String strName = txtName.getText().toString();\n\n EditText txtEmail = (EditText)findViewById(R.id.txtEmail);\n String strEmail = txtEmail.getText().toString();\n\n CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);\n boolean blnTandC = chkTandC.isChecked();\n\n editor.putString(“Name”, strName); // value to store\n editor.putString(“Email”, strEmail); // value to store\n editor.putBoolean(“TandC”, blnTandC); // value to store\n // Commit to storage\n editor.commit();\n}\n [Code sample – store object instance]\nprivate cMyClassType moInstanceOfAClass; // Store the instance of an object\n@Override\npublic Object onRetainNonConfigurationInstance()\n{\n if (moInstanceOfAClass != null) // Check that the object exists\n return(moInstanceOfAClass);\n return super.onRetainNonConfigurationInstance();\n}\n" }, { "answer_id": 6457934, "author": "Mike A.", "author_id": 782695, "author_profile": "https://Stackoverflow.com/users/782695", "pm_score": 6, "selected": false, "text": "import java.util.Date;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\npublic class dataHelper {\n\n private static final String DATABASE_NAME = \"autoMate.db\";\n private static final int DATABASE_VERSION = 1;\n\n private Context context;\n private SQLiteDatabase db;\n private OpenHelper oh ;\n\n public dataHelper(Context context) {\n this.context = context;\n this.oh = new OpenHelper(this.context);\n this.db = oh.getWritableDatabase();\n }\n\n public void close() {\n db.close();\n oh.close();\n db = null;\n oh = null;\n SQLiteDatabase.releaseMemory();\n }\n\n\n public void setCode(String codeName, Object codeValue, String codeDataType) {\n Cursor codeRow = db.rawQuery(\"SELECT * FROM code WHERE codeName = '\"+ codeName + \"'\", null);\n String cv = \"\" ;\n\n if (codeDataType.toLowerCase().trim().equals(\"long\") == true){\n cv = String.valueOf(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"int\") == true)\n {\n cv = String.valueOf(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"date\") == true)\n {\n cv = String.valueOf(((Date)codeValue).getTime());\n }\n else if (codeDataType.toLowerCase().trim().equals(\"boolean\") == true)\n {\n String.valueOf(codeValue);\n }\n else\n {\n cv = String.valueOf(codeValue);\n }\n\n if(codeRow.getCount() > 0) //exists-- update\n {\n db.execSQL(\"update code set codeValue = '\" + cv +\n \"' where codeName = '\" + codeName + \"'\");\n }\n else // does not exist, insert\n {\n db.execSQL(\"INSERT INTO code (codeName, codeValue, codeDataType) VALUES(\" +\n \"'\" + codeName + \"',\" +\n \"'\" + cv + \"',\" +\n \"'\" + codeDataType + \"')\" );\n }\n }\n\n public Object getCode(String codeName, Object defaultValue){\n\n //Check to see if it already exists\n String codeValue = \"\";\n String codeDataType = \"\";\n boolean found = false;\n Cursor codeRow = db.rawQuery(\"SELECT * FROM code WHERE codeName = '\"+ codeName + \"'\", null);\n if (codeRow.moveToFirst())\n {\n codeValue = codeRow.getString(codeRow.getColumnIndex(\"codeValue\"));\n codeDataType = codeRow.getString(codeRow.getColumnIndex(\"codeDataType\"));\n found = true;\n }\n\n if (found == false)\n {\n return defaultValue;\n }\n else if (codeDataType.toLowerCase().trim().equals(\"long\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return (long)0;\n }\n return Long.parseLong(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"int\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return (int)0;\n }\n return Integer.parseInt(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"date\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return null;\n }\n return new Date(Long.parseLong(codeValue));\n }\n else if (codeDataType.toLowerCase().trim().equals(\"boolean\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return false;\n }\n return Boolean.parseBoolean(codeValue);\n }\n else\n {\n return (String)codeValue;\n }\n }\n\n\n private static class OpenHelper extends SQLiteOpenHelper {\n\n OpenHelper(Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(\"CREATE TABLE IF NOT EXISTS code\" +\n \"(id INTEGER PRIMARY KEY, codeName TEXT, codeValue TEXT, codeDataType TEXT)\");\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n }\n }\n}\n dataHelper dh = new dataHelper(getBaseContext());\nString status = (String) dh.getCode(\"appState\", \"safetyDisabled\");\nDate serviceStart = (Date) dh.getCode(\"serviceStartTime\", null);\ndh.close();\ndh = null;\n" }, { "answer_id": 6495812, "author": "David", "author_id": 817751, "author_profile": "https://Stackoverflow.com/users/817751", "pm_score": 6, "selected": false, "text": "onSaveInstanceState() onRestoreInstanceState() onResume() onCreate() InstanceState" }, { "answer_id": 8899745, "author": "User", "author_id": 930450, "author_profile": "https://Stackoverflow.com/users/930450", "pm_score": 6, "selected": false, "text": "onSaveInstanceState() onCreate() onRestoreInstanceState() onPause() onResume()" }, { "answer_id": 9148893, "author": "roy mathew", "author_id": 1052709, "author_profile": "https://Stackoverflow.com/users/1052709", "pm_score": 6, "selected": false, "text": "<activity android:name=\".activity2\"\n android:alwaysRetainTaskState=\"true\" \n android:launchMode=\"singleInstance\">\n</activity>\n Intent intent = new Intent();\nintent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);\nintent.setClassName(this,\"com.mainscreen.activity2\");\nstartActivity(intent);\n Intent intent=new Intent();\nintent.setClassName(this,\"com.mainscreen.activity1\");\nstartActivity(intent);\n" }, { "answer_id": 9956341, "author": "stefan bachert", "author_id": 732454, "author_profile": "https://Stackoverflow.com/users/732454", "pm_score": 5, "selected": false, "text": "Bundle savedInstanceState & Co\n SharedPreferences p;\n p.edit().put(..).commit()\n" }, { "answer_id": 12277349, "author": "Mahorad", "author_id": 659326, "author_profile": "https://Stackoverflow.com/users/659326", "pm_score": 5, "selected": false, "text": "onSaveInstanceState(bundle) onRestoreInstanceState(bundle) onSaveInstanceState() onCreate(bundle) onRestoreInstanceState(bundle)" }, { "answer_id": 12983901, "author": "Mike Repass", "author_id": 614880, "author_profile": "https://Stackoverflow.com/users/614880", "pm_score": 7, "selected": false, "text": "if (!isTaskRoot()) {\n Intent intent = getIntent();\n String action = intent.getAction();\n if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {\n finish();\n return;\n }\n}\n" }, { "answer_id": 23115933, "author": "torwalker", "author_id": 3501046, "author_profile": "https://Stackoverflow.com/users/3501046", "pm_score": 5, "selected": false, "text": "mySavedInstanceState=savedInstanceState;\n if (mySavedInstanceState !=null) {\n boolean myVariable = mySavedInstanceState.getBoolean(\"MyVariable\");\n}\n onSaveInstanceState onRestoreInstanceState putBoolean" }, { "answer_id": 32108444, "author": "Jared Rummler", "author_id": 1048340, "author_profile": "https://Stackoverflow.com/users/1048340", "pm_score": 5, "selected": false, "text": "interface class Bundle import java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n@Documented\n@Retention(RetentionPolicy.RUNTIME)\n@Target({\n ElementType.FIELD\n})\npublic @interface SaveInstance {\n\n}\n import android.app.Activity;\nimport android.app.Fragment;\nimport android.os.Bundle;\nimport android.os.Parcelable;\nimport android.util.Log;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Field;\n\n/**\n * Save and load fields to/from a {@link Bundle}. All fields should be annotated with {@link\n * SaveInstance}.</p>\n */\npublic class Icicle {\n\n private static final String TAG = \"Icicle\";\n\n /**\n * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.\n *\n * @param outState\n * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link\n * Fragment#onSaveInstanceState(Bundle)}\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @see #load(Bundle, Object)\n */\n public static void save(Bundle outState, Object classInstance) {\n save(outState, classInstance, classInstance.getClass());\n }\n\n /**\n * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.\n *\n * @param outState\n * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link\n * Fragment#onSaveInstanceState(Bundle)}\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @param baseClass\n * Base class, used to get all superclasses of the instance.\n * @see #load(Bundle, Object, Class)\n */\n public static void save(Bundle outState, Object classInstance, Class<?> baseClass) {\n if (outState == null) {\n return;\n }\n Class<?> clazz = classInstance.getClass();\n while (baseClass.isAssignableFrom(clazz)) {\n String className = clazz.getName();\n for (Field field : clazz.getDeclaredFields()) {\n if (field.isAnnotationPresent(SaveInstance.class)) {\n field.setAccessible(true);\n String key = className + \"#\" + field.getName();\n try {\n Object value = field.get(classInstance);\n if (value instanceof Parcelable) {\n outState.putParcelable(key, (Parcelable) value);\n } else if (value instanceof Serializable) {\n outState.putSerializable(key, (Serializable) value);\n }\n } catch (Throwable t) {\n Log.d(TAG, \"The field '\" + key + \"' was not added to the bundle\");\n }\n }\n }\n clazz = clazz.getSuperclass();\n }\n }\n\n /**\n * Load all saved fields that have the {@link SaveInstance} annotation.\n *\n * @param savedInstanceState\n * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @see #save(Bundle, Object)\n */\n public static void load(Bundle savedInstanceState, Object classInstance) {\n load(savedInstanceState, classInstance, classInstance.getClass());\n }\n\n /**\n * Load all saved fields that have the {@link SaveInstance} annotation.\n *\n * @param savedInstanceState\n * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @param baseClass\n * Base class, used to get all superclasses of the instance.\n * @see #save(Bundle, Object, Class)\n */\n public static void load(Bundle savedInstanceState, Object classInstance, Class<?> baseClass) {\n if (savedInstanceState == null) {\n return;\n }\n Class<?> clazz = classInstance.getClass();\n while (baseClass.isAssignableFrom(clazz)) {\n String className = clazz.getName();\n for (Field field : clazz.getDeclaredFields()) {\n if (field.isAnnotationPresent(SaveInstance.class)) {\n String key = className + \"#\" + field.getName();\n field.setAccessible(true);\n try {\n Object fieldVal = savedInstanceState.get(key);\n if (fieldVal != null) {\n field.set(classInstance, fieldVal);\n }\n } catch (Throwable t) {\n Log.d(TAG, \"The field '\" + key + \"' was not retrieved from the bundle\");\n }\n }\n }\n clazz = clazz.getSuperclass();\n }\n }\n\n}\n public class MainActivity extends Activity {\n\n @SaveInstance\n private String foo;\n\n @SaveInstance\n private int bar;\n\n @SaveInstance\n private Intent baz;\n\n @SaveInstance\n private boolean qux;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Icicle.load(savedInstanceState, this);\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icicle.save(outState, this);\n }\n\n}\n" }, { "answer_id": 34354935, "author": "Krishna Satwaji Khandagale", "author_id": 4549000, "author_profile": "https://Stackoverflow.com/users/4549000", "pm_score": 4, "selected": false, "text": "onSaveInstanceState() onRestoreInstanceState() android:configChanges=\"orientation|screenSize\" class MyModel extends Serializable{\nJSONObject obj;\n\nsetJsonObject(JsonObject obj)\n{\nthis.obj=obj;\n}\n\nJSONObject getJsonObject()\nreturn this.obj;\n} \n}\n @override\nonCreate(Bundle savedInstaceState){\nMyModel data= (MyModel)savedInstaceState.getSerializable(\"yourkey\")\nJSONObject obj=data.getJsonObject();\n//Here you have retained JSONObject and can use.\n}\n\n\n@Override\nprotected void onSaveInstanceState(Bundle outState) {\nsuper.onSaveInstanceState(outState);\n//Obj is some json object \nMyModel dataToSave= new MyModel();\ndataToSave.setJsonObject(obj);\noustate.putSerializable(\"yourkey\",dataToSave); \n\n}\n" }, { "answer_id": 35006431, "author": "Kevin Cronly", "author_id": 2559202, "author_profile": "https://Stackoverflow.com/users/2559202", "pm_score": 4, "selected": false, "text": "class MainActivity extends Activity {\n @State String username; // These will be automatically saved and restored\n @State String password;\n @State int age;\n\n @Override public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Icepick.restoreInstanceState(this, savedInstanceState);\n }\n\n @Override public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icepick.saveInstanceState(this, outState);\n }\n}\n class MainActivity extends Activity {\n String username;\n String password;\n int age;\n\n @Override\n public void onSaveInstanceState(Bundle savedInstanceState) {\n super.onSaveInstanceState(savedInstanceState);\n savedInstanceState.putString(\"MyString\", username);\n savedInstanceState.putString(\"MyPassword\", password);\n savedInstanceState.putInt(\"MyAge\", age); \n /* remember you would need to actually initialize these variables before putting it in the\n Bundle */\n }\n\n @Override\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n username = savedInstanceState.getString(\"MyString\");\n password = savedInstanceState.getString(\"MyPassword\");\n age = savedInstanceState.getInt(\"MyAge\");\n }\n}\n Bundle" }, { "answer_id": 38820371, "author": "THANN Phearum", "author_id": 1863510, "author_profile": "https://Stackoverflow.com/users/1863510", "pm_score": 3, "selected": false, "text": "app/build.gradle repositories {\n maven {url \"https://clojars.org/repo/\"}\n}\ndependencies {\n compile 'frankiesardo:icepick:3.2.0'\n provided 'frankiesardo:icepick-processor:3.2.0'\n}\n public class ExampleActivity extends Activity {\n @State String username; // This will be automatically saved and restored\n\n @Override public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Icepick.restoreInstanceState(this, savedInstanceState);\n }\n\n @Override public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icepick.saveInstanceState(this, outState);\n }\n}\n class CustomView extends View {\n @State int selectedPosition; // This will be automatically saved and restored\n\n @Override public Parcelable onSaveInstanceState() {\n return Icepick.saveInstanceState(this, super.onSaveInstanceState());\n }\n\n @Override public void onRestoreInstanceState(Parcelable state) {\n super.onRestoreInstanceState(Icepick.restoreInstanceState(this, state));\n }\n\n // You can put the calls to Icepick into a BaseCustomView and inherit from it\n // All Views extending this CustomView automatically have state saved/restored\n}\n" }, { "answer_id": 39746554, "author": "iamabhaykmr", "author_id": 5800969, "author_profile": "https://Stackoverflow.com/users/5800969", "pm_score": 3, "selected": false, "text": "onCreate() SaveInstanceState(Bundle savedInstanceState) SaveInstanceState(Bundle savedInstanceState) onCreate()" }, { "answer_id": 41804128, "author": "Mansuu....", "author_id": 3578677, "author_profile": "https://Stackoverflow.com/users/3578677", "pm_score": 4, "selected": false, "text": " @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n outState.putString(\"key\",\"Welcome Back\")\n super.onSaveInstanceState(outState); //save state\n }\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n //restore activity's state\n if(savedInstanceState!=null){\n String reStoredString=savedInstanceState.getString(\"key\");\n }\n }\n //restores activity's saved state\n @Override\n protected void onRestoreInstanceState(Bundle savedInstanceState) {\n String restoredMessage=savedInstanceState.getString(\"key\");\n }\n" }, { "answer_id": 48754303, "author": "Rafols", "author_id": 4765832, "author_profile": "https://Stackoverflow.com/users/4765832", "pm_score": 4, "selected": false, "text": "override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState.apply {\n putInt(\"intKey\", 1)\n putString(\"stringKey\", \"String Value\")\n putParcelable(\"parcelableKey\", parcelableObject)\n })\n}\n onCreate() onRestoreInstanceState() val restoredInt = savedInstanceState?.getInt(\"intKey\") ?: 1 //default int\n val restoredString = savedInstanceState?.getString(\"stringKey\") ?: \"default string\"\n val restoredParcelable = savedInstanceState?.getParcelable<ParcelableClass>(\"parcelableKey\") ?: ParcelableClass() //default parcelable\n" }, { "answer_id": 54124841, "author": "Rohit Singh", "author_id": 4700156, "author_profile": "https://Stackoverflow.com/users/4700156", "pm_score": 2, "selected": false, "text": "EditText Bundle EditText ListView onSavedInstanceState(Bundle savedinstaneState) int currentScore @Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n // Save the user's current game state\n savedInstanceState.putInt(STATE_SCORE, mCurrentScore);\n\n // Always call the superclass so it can save the view hierarchy state\n super.onSaveInstanceState(savedInstanceState);\n}\n super.onSaveInstanceState(savedInstanceState); onCreate(Bundle savedInstanceState)\n onRestoreInstanceState(Bundle savedInstanceState)\n onCreate(Bundle savedInstanceState) @Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n // Always call the superclass so it can restore the view hierarchy\n super.onRestoreInstanceState(savedInstanceState);\n\n // Restore state members from the saved instance\n mCurrentScore = savedInstanceState.getInt(STATE_SCORE);\n}\n super.onRestoreInstanceState(savedInstanceState); onSaveInstanceState(Bundle savedInstanceState) onSaveInstanceState(Bundle savedInstanceState) onSaveInstanceState(Bundle savedInstanceState)" }, { "answer_id": 56404590, "author": "Sazzad Hissain Khan", "author_id": 1084174, "author_profile": "https://Stackoverflow.com/users/1084174", "pm_score": 3, "selected": false, "text": "onSaveInstanceState onRestoreInstanceState public override fun onSaveInstanceState(savedInstanceState: Bundle) {\n super.onSaveInstanceState(savedInstanceState)\n\n // prepare variables here\n savedInstanceState.putInt(\"kInt\", 10)\n savedInstanceState.putBoolean(\"kBool\", true)\n savedInstanceState.putDouble(\"kDouble\", 4.5)\n savedInstanceState.putString(\"kString\", \"Hello Kotlin\")\n}\n public override fun onRestoreInstanceState(savedInstanceState: Bundle) {\n super.onRestoreInstanceState(savedInstanceState)\n\n val myInt = savedInstanceState.getInt(\"kInt\")\n val myBoolean = savedInstanceState.getBoolean(\"kBool\")\n val myDouble = savedInstanceState.getDouble(\"kDouble\")\n val myString = savedInstanceState.getString(\"kString\")\n // use variables here\n}\n" }, { "answer_id": 58032458, "author": "Sana Ebadi", "author_id": 10699119, "author_profile": "https://Stackoverflow.com/users/10699119", "pm_score": 2, "selected": false, "text": "Live Data View Model ifecycle Handel JetPack" }, { "answer_id": 58485428, "author": "IgniteCoders", "author_id": 2835520, "author_profile": "https://Stackoverflow.com/users/2835520", "pm_score": 2, "selected": false, "text": "android:configChanges=\"orientation|screenSize\"\n <activity\n android:name=\".activities.MyActivity\"\n android:configChanges=\"orientation|screenSize\">\n</activity>\n" }, { "answer_id": 59262445, "author": "Umut ADALI", "author_id": 4300071, "author_profile": "https://Stackoverflow.com/users/4300071", "pm_score": 2, "selected": false, "text": "public class HelloAndroidViewModel extends ViewModel {\n public Booelan firstInit = false;\n\n public HelloAndroidViewModel() {\n firstInit = false;\n }\n ...\n}\n\npublic class HelloAndroid extends Activity {\n\n private TextView mTextView = null;\n HelloAndroidViewModel viewModel = ViewModelProviders.of(this).get(HelloAndroidViewModel.class);\n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n mTextView = new TextView(this);\n\n //Because even if the state is deleted, the data in the viewmodel will be kept because the activity does not destroy\n if(!viewModel.firstInit){\n viewModel.firstInit = true\n mTextView.setText(\"Welcome to HelloAndroid!\");\n }else{\n mTextView.setText(\"Welcome back.\");\n }\n\n setContentView(mTextView);\n }\n}\n" }, { "answer_id": 62368924, "author": "Jamil Hasnine Tamim", "author_id": 6160172, "author_profile": "https://Stackoverflow.com/users/6160172", "pm_score": 2, "selected": false, "text": "onSaveInstanceState JSON Gson String, Double, Int, Long Fragment Activity saveInstanceState override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n\n //for custom class-----\n val gson = Gson()\n val json = gson.toJson(your_custom_class)\n outState.putString(\"CUSTOM_CLASS\", json)\n\n //for single value------\n outState.putString(\"MyString\", stringValue)\n outState.putBoolean(\"MyBoolean\", true)\n outState.putDouble(\"myDouble\", doubleValue)\n outState.putInt(\"MyInt\", intValue)\n }\n override fun onRestoreInstanceState(savedInstanceState: Bundle) {\n super.onRestoreInstanceState(savedInstanceState)\n\n //for custom class restore\n val json = savedInstanceState?.getString(\"CUSTOM_CLASS\")\n if (!json!!.isEmpty()) {\n val gson = Gson()\n testBundle = gson.fromJson(json, Session::class.java)\n }\n\n //for single value restore\n\n val myBoolean: Boolean = savedInstanceState?.getBoolean(\"MyBoolean\")\n val myDouble: Double = savedInstanceState?.getDouble(\"myDouble\")\n val myInt: Int = savedInstanceState?.getInt(\"MyInt\")\n val myString: String = savedInstanceState?.getString(\"MyString\")\n }\n onCreate saveInstanceState override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n val gson = Gson()\n val json = gson.toJson(customClass)\n outState.putString(\"CUSTOM_CLASS\", json)\n }\n override fun onActivityCreated(savedInstanceState: Bundle?) {\n super.onActivityCreated(savedInstanceState)\n\n //for custom class restore\n if (savedInstanceState != null) {\n val json = savedInstanceState.getString(\"CUSTOM_CLASS\")\n if (!json!!.isEmpty()) {\n val gson = Gson()\n val customClass: CustomClass = gson.fromJson(json, CustomClass::class.java)\n }\n }\n\n // for single value restore\n val myBoolean: Boolean = savedInstanceState.getBoolean(\"MyBoolean\")\n val myDouble: Double = savedInstanceState.getDouble(\"myDouble\")\n val myInt: Int = savedInstanceState.getInt(\"MyInt\")\n val myString: String = savedInstanceState.getString(\"MyString\")\n }\n" }, { "answer_id": 64619764, "author": "i30mb1", "author_id": 9674249, "author_profile": "https://Stackoverflow.com/users/9674249", "pm_score": 2, "selected": false, "text": "Activity Activity onSaveInstanceState onRestoreInstanceState onCreate Fragment onSaveInstanceState onCreate onCreateView onActivityCreated SavedStateRegistry SavedStateRegistry SavedStateProvider class MyActivity : AppCompatActivity() {\n\n companion object {\n private const val MY_SAVED_STATE_KEY = \"MY_SAVED_STATE_KEY \"\n private const val SOME_VALUE_KEY = \"SOME_VALUE_KEY \"\n }\n \n private lateinit var someValue: String\n private val savedStateProvider = SavedStateRegistry.SavedStateProvider { \n Bundle().apply {\n putString(SOME_VALUE_KEY, someValue)\n }\n }\n \n override fun onCreate(savedInstanceState: Bundle?) { \n super.onCreate(savedInstanceState)\n savedStateRegistry.registerSavedStateProvider(MY_SAVED_STATE_KEY, savedStateProvider)\n someValue = savedStateRegistry.consumeRestoredStateForKey(MY_SAVED_STATE_KEY)?.getString(SOME_VALUE_KEY) ?: \"\"\n }\n \n}\n SavedStateRegistry SavedStateProvider Activity/Fragment SavedStateProvider" }, { "answer_id": 65560389, "author": "Yessy", "author_id": 6456129, "author_profile": "https://Stackoverflow.com/users/6456129", "pm_score": 2, "selected": false, "text": "public class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());\n binding.setViewModel(new ViewModelProvider(this).get(ViewModel.class));\n binding.setLifecycleOwner(this);\n setContentView(binding.getRoot());\n }\n\n public static class ViewModel extends AndroidViewModel {\n\n //This field SURVIVE the background process reclaim/killing & the configuration change\n public final SavedStateHandle savedStateHandle;\n\n //This field NOT SURVIVE the background process reclaim/killing but SURVIVE the configuration change\n public final MutableLiveData<String> inputText2 = new MutableLiveData<>();\n\n\n public ViewModel(@NonNull Application application, SavedStateHandle savedStateHandle) {\n super(application);\n this.savedStateHandle = savedStateHandle;\n }\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n <data>\n\n <variable\n name=\"viewModel\"\n type=\"com.xxx.viewmodelsavedstatetest.MainActivity.ViewModel\" />\n </data>\n\n <LinearLayout xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n\n\n <EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:autofillHints=\"\"\n android:hint=\"This field SURVIVE the background process reclaim/killing &amp; the configuration change\"\n android:text='@={(String)viewModel.savedStateHandle.getLiveData(\"activity_main/inputText\", \"\")}' />\n\n <SeekBar\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:max=\"100\"\n android:progress='@={(Integer)viewModel.savedStateHandle.getLiveData(\"activity_main/progress\", 50)}' />\n\n <EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"This field SURVIVE the background process reclaim/killing &amp; the configuration change\"\n android:text='@={(String)viewModel.savedStateHandle.getLiveData(\"activity_main/inputText\", \"\")}' />\n\n <SeekBar\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:max=\"100\"\n android:progress='@={(Integer)viewModel.savedStateHandle.getLiveData(\"activity_main/progress\", 50)}' />\n\n <EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"This field NOT SURVIVE the background process reclaim/killing but SURVIVE the configuration change\"\n android:text='@={viewModel.inputText2}' />\n\n </LinearLayout>\n</layout>\n 1. start the test activity\n2. press home key to go home\n3. adb shell kill <the test activity process>\n4. open recent app list and restart the test activity\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
151,778
<p>I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from <code>ModelBase</code>.</p> <p><code>ModelBase</code> is abstract &amp; provides a bunch of static methods for finding &amp; binding objects from the db, for example:</p> <pre><code>public static ArrayList findAll(Class cast_to_class) { //build the sql query &amp; execute it } </code></pre> <p>So you can do things like <code>ModelBase.findAll(Albums.class)</code> to get a list of all persisted albums. My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like </p> <pre><code>public class Album extends ModelBase { public static String getSelectSQL() { return "select * from albums.....";} } </code></pre> <p>because there is no polymorphism for static methods in Java. But I don't want to make <code>getSelectSQL()</code> an instance method in <code>Album</code> because then I need to create an instance of it just to get a string that is really static in behavior.</p> <p>At the moment, <code>findAll()</code> uses reflection to get the appropriate sql for the class in question:</p> <pre><code>select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null); </code></pre> <p>But that's pretty gross. </p> <p>So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know <em>why</em> static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!</p> <p>Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)?</p>
[ { "answer_id": 152170, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 1, "selected": false, "text": "public abstract class BaseFactory<E> {\n public abstract String getSelectSQL();\n public List<E> findAll(Class<E> clazz) {\n // Use getSelectSQL();\n }\n}\n\npublic class AlbumFactory extends BaseFactory<Album> {\n public String getSelectSQL() { return \"select * from albums.....\"; }\n}\n" }, { "answer_id": 154057, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 3, "selected": true, "text": "class ModelBase {\n // Initialize the queries\n private static Map<String,String> selectMap = new HashMap<String,String>(); static {\n selectMap.put( \"Album\", \"select field_1, field_2 from album\");\n selectMap.put( \"Artist\", \"select field_1, field_2 from artist\");\n selectMap.put( \"Track\", \"select field_1, field_2 from track\");\n }\n\n // Finds all the objects for the specified class...\n // Note: it is better to use \"List\" rather than \"ArrayList\" I'll explain this later.\n public static List findAll(Class classToFind ) {\n String sql = getSelectSQL( classToFind );\n results = execute( sql );\n //etc...\n return ....\n }\n\n // Return the correct select sql..\n private static String getSelectSQL( Class classToFind ){\n String statement = tableMap.get( classToFind.getSimpleName() );\n if( statement == null ) {\n throw new IllegalArgumentException(\"Class \" + \n classToFind.getSimpleName + \" is not mapped\");\n }\n return statement;\n\n }\n}\n // Client usage:\n\n...\nList albums = ModelBase.findAll( Album.class );\n // Second option, instance used under the hood.\nclass ModelBase {\n // Initialize the queries\n private static Map<String,ModelBase> daoMap = new HashMap<String,ModelBase>(); static {\n selectMap.put( \"Album\", new AlbumModel() );\n selectMap.put( \"Artist\", new ArtistModel());\n selectMap.put( \"Track\", new TrackModel());\n }\n\n // Finds all the objects for the specified class...\n // Note: it is better to use \"List\" rather than \"ArrayList\" I'll explain this later.\n public static List findAll(Class classToFind ) {\n String sql = getSelectSQL( classToFind );\n results = execute( sql );\n //etc...\n return ....\n }\n\n // Return the correct select sql..\n private static String getSelectSQL( Class classToFind ){\n ModelBase dao = tableMap.get( classToFind.getSimpleName() );\n if( statement == null ) {\n throw new IllegalArgumentException(\"Class \" + \n classToFind.getSimpleName + \" is not mapped\");\n }\n return dao.selectSql();\n }\n // Instance class to be overrided... \n // this is \"protected\" ... \n protected abstract String selectSql();\n}\nclass AlbumModel extends ModelBase {\n public String selectSql(){\n return \"select ... from album\";\n }\n}\nclass ArtistModel extends ModelBase {\n public String selectSql(){\n return \"select ... from artist\";\n }\n}\nclass TrackModel extends ModelBase {\n public String selectSql(){\n return \"select ... from track\";\n }\n}\n // Client usage:\n\n...\nList albums = ModelBase.findAll( Album.class ); // Does not know , behind the scenes you use instances.\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16925/" ]
151,783
<p>just curious to know which CPU architectures support compare and swap atomic primitives? </p>
[ { "answer_id": 151802, "author": "mat_geek", "author_id": 11032, "author_profile": "https://Stackoverflow.com/users/11032", "pm_score": 3, "selected": false, "text": "bool_t My_CompareAndSwap(IN int *ptr, IN int old, IN int new)\n{\n unsigned char ret;\n\n /* Note that sete sets a 'byte' not the word */\n __asm__ __volatile__ (\n \" lock\\n\"\n \" cmpxchgl %2,%1\\n\"\n \" sete %0\\n\"\n : \"=q\" (ret), \"=m\" (*ptr)\n : \"r\" (new), \"m\" (*ptr), \"a\" (old)\n : \"memory\");\n\n return ret;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
151,794
<p>Any idea on how to unit test the views in ASP.NET MVC?</p> <p>I am sick of encountering the yellow screen of death when I launch my MVC project just because I forget to update the views when one of the <code>Action</code> methods of my controller changes name.</p>
[ { "answer_id": 1110422, "author": "Richard Ev", "author_id": 39709, "author_profile": "https://Stackoverflow.com/users/39709", "pm_score": 3, "selected": false, "text": "<MvcBuildViews> <Target Name=\"AfterBuild\" Condition=\"'$(MvcBuildViews)'=='true'\">\n <AspNetCompiler VirtualPath=\"temp\" PhysicalPath=\"$(ProjectDir)\\..\\$(ProjectName)\" />\n</Target>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
151,800
<p>Given a database field named "widget_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget_ids... how would you make an update statement with SQL that would say: "if the widget_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"</p> <p>Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL?</p>
[ { "answer_id": 151829, "author": "Logan", "author_id": 3518, "author_profile": "https://Stackoverflow.com/users/3518", "pm_score": 4, "selected": true, "text": "update <tablename>\n set widget_id = widget_id + \"somenumber/\"\n where row_id = X\n and widget_id not like \"%/somenumber/%\"\n and widget_id not like \"somenumber/%\";\n" }, { "answer_id": 151949, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "CREATE TABLE ThingieWidgets (\n thingie_id INT REFERENCES Thingies,\n widget_id INT REFERENCES Widgets,\n PRIMARY KEY(thingie_id, widget_id)\n);\n INSERT INTO ThingieWidgets (thingie_id, widget_id)\n VALUES (1234, 67), (1234, 797), (1234, 124);\n SELECT * FROM ThingieWidgets\nWHERE thingie_id = 1234 AND widget_id = 45;\n INSERT INTO ThingieWidgets (thingie_id, widget_id)\n VALUES (1234, 45);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14278/" ]
151,804
<p>I want to watch a folder tree on a network server for changes. The files all have a specific extension. There are about 200 folders in the tree and about 1200 files with the extension I am watching.</p> <p>I can't write a service to run on the server (off-limits!) so the solution has to be local to the client. Timeliness is not particularly important. I can live with a minute or more delay in notifications. I am watching for Create, Delete, Rename and Changes.</p> <p>Would using the .NET System.IO.fileSystemWatcher create much of a load on the server? </p> <p>How about 10 separate watchers to cut down the number of folders/files being watched? (down to 200 from 700 folders, 1200 from 5500 files in total) More network traffic instead of less? My thoughts are a reshuffle on the server to put the watched files under 1 tree. I may not always have this option hence the team of watchers.</p> <p>I suppose the other solution is a periodic check if the FSW creates an undue load on the server, or if it doesn't work for a whole bunch of SysAdmin type reasons.</p> <p>Is there a better way to do this?</p>
[ { "answer_id": 37476692, "author": "trevorwong77", "author_id": 1089235, "author_profile": "https://Stackoverflow.com/users/1089235", "pm_score": 1, "selected": false, "text": "var fileNames = Directory.GetFiles(srcFolder);\nforeach (string fileName in fileNames)\n{\n string[] lines = File.ReadAllLines(fileName);\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492/" ]
151,841
<p>I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives... </p> <p>E.g., WIN32 on x86 has a family of functions <code>_InterlockedCompareExchange</code> in the <code>&lt;_intrin.h&gt;</code> header.</p>
[ { "answer_id": 151847, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "atomic_compare_exchange() \n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
151,844
<p>Since Unicode lacks a series of zero width sorting characters, I need to determine equivalent characters that will allow me to force a certain order on a list that is automatically sorted by character values. Unfortunately the list items are not in an alphabetical order, nor is it acceptable to prefix them with visible characters to ensure the result of the sort matches the wanted outcome.</p> <p>What Unicode characters can be thrown in front of regular Latin alphabet text, and will not appear, but still allow me to "spike" the sort in the way I require?</p> <p>(BTW this is being done with Drupal 5 with a user profile list field. Don't bother suggesting changing that to a vocabulary/category.)</p>
[ { "answer_id": 151918, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 1, "selected": false, "text": "usort(array, comparisonFunction)" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5697/" ]
151,846
<p>This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.</p>
[ { "answer_id": 152094, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 2, "selected": false, "text": "win32gui" }, { "answer_id": 152454, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 5, "selected": true, "text": "import win32con\nimport win32gui\n\ndef isRealWindow(hWnd):\n '''Return True iff given window is a real Windows application window.'''\n if not win32gui.IsWindowVisible(hWnd):\n return False\n if win32gui.GetParent(hWnd) != 0:\n return False\n hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0\n lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)\n if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)\n or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):\n if win32gui.GetWindowText(hWnd):\n return True\n return False\n\ndef getWindowSizes():\n '''\n Return a list of tuples (handler, (width, height)) for each real window.\n '''\n def callback(hWnd, windows):\n if not isRealWindow(hWnd):\n return\n rect = win32gui.GetWindowRect(hWnd)\n windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))\n windows = []\n win32gui.EnumWindows(callback, windows)\n return windows\n\nfor win in getWindowSizes():\n print win\n GetWindowRect GetClientRect" }, { "answer_id": 155587, "author": "Dustin Wyatt", "author_id": 23972, "author_profile": "https://Stackoverflow.com/users/23972", "pm_score": 3, "selected": false, "text": "import win32com.client\noAutoItX = win32com.client.Dispatch( \"AutoItX3.Control\" )\n\noAutoItX.Opt(\"WinTitleMatchMode\", 2) #Match text anywhere in a window title\n\nwidth = oAutoItX.WinGetClientSizeWidth(\"Firefox\")\nheight = oAutoItX.WinGetClientSizeHeight(\"Firefox\")\n\nprint width, height\n" }, { "answer_id": 60392234, "author": "user3881450", "author_id": 3881450, "author_profile": "https://Stackoverflow.com/users/3881450", "pm_score": 0, "selected": false, "text": "import win32con\nimport win32gui\n\ndef isRealWindow(hWnd):\n #'''Return True iff given window is a real Windows application window.'''\n if not win32gui.IsWindowVisible(hWnd):\n return False\n if win32gui.GetParent(hWnd) != 0:\n return False\n hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0\nlExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)\nif (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)\n or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):\n if win32gui.GetWindowText(hWnd):\n return True\nreturn False\n\ndef getWindowSizes():\n\nReturn a list of tuples (handler, (width, height)) for each real window.\n'''\ndef callback(hWnd, windows):\n if not isRealWindow(hWnd):\n return\n rect = win32gui.GetWindowRect(hWnd)\n text = win32gui.GetWindowText(hWnd)\n windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1]), text ))\nwindows = []\nwin32gui.EnumWindows(callback, windows)\nreturn windows\n\nfor win in getWindowSizes():\nprint(win)\n" }, { "answer_id": 69610455, "author": "kalopseeia", "author_id": 12622913, "author_profile": "https://Stackoverflow.com/users/12622913", "pm_score": 0, "selected": false, "text": "import win32process\nimport subprocess\nimport win32gui\nimport time \n \ndef get_hwnds_for_pid (pid):\n def callback (hwnd, hwnds):\n if win32gui.IsWindowVisible (hwnd) and win32gui.IsWindowEnabled (hwnd):\n _, found_pid = win32process.GetWindowThreadProcessId (hwnd)\n if found_pid == pid:\n hwnds.append (hwnd)\n return True\n \n hwnds = []\n win32gui.EnumWindows (callback, hwnds)\n return hwnds\n\n# This the process I want to get windows size. \nnotepad = subprocess.Popen ([r\"C:\\\\Users\\\\dniwa\\\\Adb\\\\scrcpy.exe\"]) \ntime.sleep (2.0)\n\nwhile True: \n for hwnd in get_hwnds_for_pid (notepad.pid):\n rect = win32gui.GetWindowRect(hwnd)\n print(hwnd, \"=>\", win32gui.GetWindowText (hwnd))\n\n # You need to test if your resolution really get exactly because mine is doesn't . \n # I use . 16:9 Monitor , Calculate the percent using this calculations , , (x * .0204082) and (y * .0115774)\n print((hwnd, (rect[2] - rect[0], rect[3] - rect[1])))\n x = rect[2] - rect[0]\n y = rect[3] - rect[1]\n print(type(x), type(y))\n time.sleep(1)\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176/" ]
151,850
<p>In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:</p> <pre><code>if (var1 = var2) { ... } </code></pre> <p>instead of:</p> <pre><code>var1 = var2; if (var1) { ... } </code></pre> <p>?</p>
[ { "answer_id": 151855, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "while ((c = getchar()) != EOF) {\n // process the character\n}\n\n// end of file reached...\n" }, { "answer_id": 151856, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 5, "selected": false, "text": "if (n = foo())\n{\n /* foo returned a non-zero value, do something with the return value */\n} else {\n /* foo returned zero, do something else */\n}\n" }, { "answer_id": 151868, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "while if if c = getchar();\nwhile (c != EOF) {\n // ...\n c = getchar();\n}\n while (true) {\n c = getchar();\n if (c == EOF) break;\n // ...\n}\n" }, { "answer_id": 151869, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 4, "selected": false, "text": "if ((n = foo())) {\n ...\n}\n" }, { "answer_id": 151870, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 8, "selected": true, "text": "while(var = GetNext())\n{\n ...do something with 'var' \n}\n var = GetNext();\nwhile(var)\n{\n ...do something\n var = GetNext();\n}\n" }, { "answer_id": 151871, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "while ($row = mysql_fetch_assoc($result)) {\n // Display row\n}\n $row = mysql_fetch_assoc($result);\nwhile ($row) {\n // Display row\n $row = mysql_fetch_assoc($result);\n}\n" }, { "answer_id": 151920, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "if ((rc = first_check(arg1, arg2)) != 0)\n{\n report error based on rc\n}\nelse if ((rc = second_check(arg2, arg3)) != 0)\n{\n report error based on new rc\n}\nelse if ((rc = third_check(arg3, arg4)) != 0)\n{\n report error based on new rc\n}\nelse\n{\n do what you really wanted to do\n}\n rc = first_check(arg1, arg2);\nif (rc != 0)\n{\n report error based on rc\n}\nelse\n{\n rc = second_check(arg2, arg3);\n if (rc != 0)\n {\n report error based on new rc\n }\n else\n {\n rc = third_check(arg3, arg4);\n if (rc != 0)\n {\n report error based on new rc\n }\n else\n {\n do what you really wanted to do\n }\n }\n}\n first_action() second_action() third_action()" }, { "answer_id": 19288770, "author": "plasmixs", "author_id": 2648143, "author_profile": "https://Stackoverflow.com/users/2648143", "pm_score": 2, "selected": false, "text": "while (checkstatus() != -1) {\n // Process\n}\n while (true) {\n int error = checkstatus();\n if (error != -1)\n // Process\n else\n // Fail\n}\n" }, { "answer_id": 40677085, "author": "Gangadhar", "author_id": 7178124, "author_profile": "https://Stackoverflow.com/users/7178124", "pm_score": -1, "selected": false, "text": "someMethod() if null If(null != someMethod()){\n String s = someMethod();\n ......\n //Use s\n}\n String s;\nIf(null != (s = someMethod())) {\n ......\n //Use s\n}\n" }, { "answer_id": 58999988, "author": "Julien-L", "author_id": 143504, "author_profile": "https://Stackoverflow.com/users/143504", "pm_score": 0, "selected": false, "text": "boost::optional std::optional std::optional<int> maybe_int(); // function maybe returns an int\n\nif (auto i = maybe_int()) {\n use_int(*i);\n}\n int* ptr_int();\n\nif (int* i = ptr_int()) {\n use_int(*i);\n}\n" }, { "answer_id": 67721528, "author": "Priteem", "author_id": 5160364, "author_profile": "https://Stackoverflow.com/users/5160364", "pm_score": 0, "selected": false, "text": "while (!(newtork_joined = transmitter.send(data))) {\nSerial.println(\"Not Joined\");\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
151,872
<p>I have a form where i have used Infragistics windows grid control to display the data. In this, i have placed a button on one of the cell. I want to set its visibility either True or False based on the row condition. I have handled the <strong>InitializeRow</strong> event of <strong>UltraWinGrid</strong> control and able to disable the button. But i am unable to set the button's visible to False.</p>
[ { "answer_id": 152634, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 2, "selected": false, "text": "UltraGridRow row = ...\n\nrow.Cells[buttonCellIndex].Hidden = true;\n UltraGrid" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
151,874
<p>I am working with web Dynpro java.. I have created a stateless session bean wherein I have created business methods for inserting and retrieving records from my dictionary table. My table has two fields of <code>java.sql.Date</code> type The web service that i have created is working fine for <code>insertRecords()</code>, but for <code>showRecords()</code> I am not able to fetch the dates..</p> <p>This is the following code I have applied..</p> <pre><code>public WrapperClass[] showRecords() { ArrayList arr = new ArrayList(); WrapperClass model; WrapperClass[] modelArr = null; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("jdbc/SAPSR3DB"); Connection conn = ds.getConnection(); PreparedStatement stmt = conn.prepareStatement("select * from TMP_DIC"); ResultSet rs = stmt.executeQuery(); while(rs.next()) { model = new WrapperClass(); model.setTitle(rs.getString("TITLE")); model.setStatus(rs.getString("STATUS")); model.setSt_date(rs.getDate("START_DATE")); model.setEnd_date(rs.getDate("END_DATE")); arr.add(model); //arr.add(rs.getString(2)); //arr.add(rs.getString(3)); } modelArr = new WrapperClass[arr.size()]; for(int j=0;j&lt;arr.size();j++) { model = (WrapperClass)arr.get(j); modelArr[j] = model; } stmt.close(); conn.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } arr.toArray(modelArr); return modelArr; } </code></pre> <p>Can anybody please help.. Thanks Ankita</p>
[ { "answer_id": 22613604, "author": "sharkbait", "author_id": 1353274, "author_profile": "https://Stackoverflow.com/users/1353274", "pm_score": 0, "selected": false, "text": "try {\n ctx = new InitialContext();\n\n Object o = ctx\n .lookup(\"sc.fiat.com/um~pers_app/LOCAL/UserServices/com.fiat.sc.um.pers.services.UserServicesLocal\");\n userServices = (UserServicesLocal) o;\n\n} catch (Exception e) {\n logger.traceThrowableT(Severity.ERROR, e.getMessage(), e);\n msgMgr.reportException(e);\n }\n private UserServicesLocal userServices;\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
151,905
<p>What's the best way of inserting information in table A and using the index from table A to relate to table B. </p> <p>The "solution" I tried is inserting the info in table A (which has a automatically generated ID), then, select the last index and insert it in table B. This may not be very useful, as the last index may change between the inserts because another user could generate a new index in table A</p> <p>I have had this problem with various DBMS postgreSQL, Informix, MySQL and MSSQL (thanks to lomaxx for the answer)</p>
[ { "answer_id": 151912, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "postgres=# create table foo(id serial primary key, text varchar);\nNOTICE: CREATE TABLE will create implicit sequence \"foo_id_seq\" for serial column \"foo.id\"\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"foo_pkey\" for table \"foo\"\nCREATE TABLE\n\npostgres=# create table bar(id int references foo, text varchar);\nCREATE TABLE\npostgres=# select nextval('foo_id_seq');\n nextval\n---------\n 1\n(1 row)\n\npostgres=# insert into foo values (1,'a'); insert into bar values(1,'b');\nINSERT 0 1\nINSERT 0 1\n mysql> create table foo(id int primary key auto_increment, text varchar(10)) Engine=InnoDB;\nQuery OK, 0 rows affected (0.06 sec)\n\nmysql> create table bar(id int references foo, text varchar(10)) Engine=InnoDB;\nQuery OK, 0 rows affected (0.01 sec)\n\nmysql> begin;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> insert into foo(text) values ('x');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> insert into bar values (last_insert_id(),'y');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> commit;\nQuery OK, 0 rows affected (0.04 sec)\n" }, { "answer_id": 152151, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT @@Identity" }, { "answer_id": 152233, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 0, "selected": false, "text": "VIEW SELECT INNER JOIN IDENTITY INSERT INTO VIEW NOT NULL DEFAULT IDENTITY IDENTITY IDENTITY IDENTITY FOREIGN KEY CREATE TABLE Table1 \n(\n key_col INTEGER IDENTITY NOT NULL PRIMARY KEY, \n data_col_1 INTEGER NOT NULL\n)\n;\nCREATE TABLE Table2\n(\n key_col INTEGER NOT NULL, \n data_col_2 INTEGER NOT NULL, \n PRIMARY KEY (key_col, data_col_2)\n)\n;\nCREATE VIEW View1\nAS \nSELECT T1.key_col AS key_col_1, T2.key_col AS key_col_2, \n T1.data_col_1, T2.data_col_2\n FROM Table2 AS T2\n INNER JOIN Table1 AS T1\n ON T1.key_col = T2.key_col\n;\nINSERT INTO View1 (data_col_1, data_col_2) \nVALUES (1, 2)\n;\n" }, { "answer_id": 152300, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 0, "selected": false, "text": "INSERT DEFINE ... etc etc \n\nBEGIN TRANSACTION\n\nINSERT INTO table1 ( value1 ) VALUES ( @p_value1 )\nSET @pk_table1 = @@IDENTITY\n\nINSERT INTO table2 ( pk_table1, value2 ) VALUES ( @pk_table1, @p_value2 )\n\nCOMMIT\n @@IDENTITY INSERT" }, { "answer_id": 152696, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "INSERT INTO table1 ( pk_table1, value1 ) \n VALUES ( table1_seq.NEXTVAL, p_value1 ) RETURNING pk_table1 INTO l_table1_id;\n\nINSERT INTO table2 ( pk_table2, pk_table1, value2 ) \n VALUES ( table2_seq.NEXTVAL, l_table1_id, p_value2 );\n" }, { "answer_id": 244825, "author": "seFausto", "author_id": 23146, "author_profile": "https://Stackoverflow.com/users/23146", "pm_score": 0, "selected": false, "text": "import com.informix.jdbc.*;\n\ncmd = \"insert into serialTable(i) values (100)\";\nstmt.executeUpdate(cmd);\nSystem.out.println(cmd+\"...okay\");\nint serialValue = ((IfmxStatement)stmt).getSerial();\nSystem.out.println(\"serial value: \" + serialValue);\n" }, { "answer_id": 478896, "author": "mechanical_meat", "author_id": 42346, "author_profile": "https://Stackoverflow.com/users/42346", "pm_score": 0, "selected": false, "text": "BEGIN;\n\nINSERT INTO products (prod_id, prod_name, description) VALUES (\n nextval('products_prod_id_seq')\n , 'a product'\n , 'a product description'\n);\n\nINSERT INTO prices (price_id, prod_id, price) VALUES (\n nextval('prices_price_id_seq')\n , currval('products_prod_id_seq')\n , 0.99\n);\n\nCOMMIT;\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23146/" ]
151,917
<p>What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?</p>
[ { "answer_id": 151932, "author": "Michael Barker", "author_id": 6365, "author_profile": "https://Stackoverflow.com/users/6365", "pm_score": 5, "selected": true, "text": "Lock l = new Lock();\nl.lock(); // Call the lock before calling try.\ntry {\n // Do some processing.\n // All code must go in here including break, return etc.\n return something;\n} finally {\n l.unlock();\n}\n" }, { "answer_id": 47512211, "author": "Raúl Salinas-Monteagudo", "author_id": 1691599, "author_profile": "https://Stackoverflow.com/users/1691599", "pm_score": 1, "selected": false, "text": "public class MutexTests {\n\n static class Autolock implements AutoCloseable {\n Autolock(ReentrantLock lock) {\n this.mLock = lock;\n mLock.lock();\n }\n\n @Override\n public void close() {\n mLock.unlock();\n }\n\n private final ReentrantLock mLock;\n }\n\n public static void main(String[] args) throws InterruptedException {\n final ReentrantLock lock = new ReentrantLock();\n\n try (Autolock alock = new Autolock(lock)) {\n // Whatever you need to do while you own the lock\n }\n // Here, you have already released the lock, regardless of exceptions\n\n }\n\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18174/" ]
151,919
<p>Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states:</p> <blockquote> <p>The __forceinline keyword overrides the cost/benefit analysis and relies on the judgment of the programmer instead.</p> </blockquote> <p>This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am I supposed to know that it's wrong? </p> <p>In what scenario is it assumed that I know better than my compiler on this issue?</p>
[ { "answer_id": 161473, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 3, "selected": false, "text": "__forceinline" }, { "answer_id": 46281942, "author": "Cookie", "author_id": 698504, "author_profile": "https://Stackoverflow.com/users/698504", "pm_score": 2, "selected": false, "text": " BOOST_CONTAINER_FORCEINLINE flat_tree& operator=(BOOST_RV_REF(flat_tree) x)\n BOOST_NOEXCEPT_IF( (allocator_traits_type::propagate_on_container_move_assignment::value ||\n allocator_traits_type::is_always_equal::value) &&\n boost::container::container_detail::is_nothrow_move_assignable<Compare>::value)\n { m_data = boost::move(x.m_data); return *this; }\n\n BOOST_CONTAINER_FORCEINLINE const value_compare &priv_value_comp() const\n { return static_cast<const value_compare &>(this->m_data); }\n\n BOOST_CONTAINER_FORCEINLINE value_compare &priv_value_comp()\n { return static_cast<value_compare &>(this->m_data); }\n\n BOOST_CONTAINER_FORCEINLINE const key_compare &priv_key_comp() const\n { return this->priv_value_comp().get_comp(); }\n\n BOOST_CONTAINER_FORCEINLINE key_compare &priv_key_comp()\n { return this->priv_value_comp().get_comp(); }\n\n public:\n // accessors:\n BOOST_CONTAINER_FORCEINLINE Compare key_comp() const\n { return this->m_data.get_comp(); }\n\n BOOST_CONTAINER_FORCEINLINE value_compare value_comp() const\n { return this->m_data; }\n\n BOOST_CONTAINER_FORCEINLINE allocator_type get_allocator() const\n { return this->m_data.m_vect.get_allocator(); }\n\n BOOST_CONTAINER_FORCEINLINE const stored_allocator_type &get_stored_allocator() const\n { return this->m_data.m_vect.get_stored_allocator(); }\n\n BOOST_CONTAINER_FORCEINLINE stored_allocator_type &get_stored_allocator()\n { return this->m_data.m_vect.get_stored_allocator(); }\n\n BOOST_CONTAINER_FORCEINLINE iterator begin()\n { return this->m_data.m_vect.begin(); }\n\n BOOST_CONTAINER_FORCEINLINE const_iterator begin() const\n { return this->cbegin(); }\n\n BOOST_CONTAINER_FORCEINLINE const_iterator cbegin() const\n { return this->m_data.m_vect.begin(); }\n" }, { "answer_id": 52687231, "author": "Soonts", "author_id": 126995, "author_profile": "https://Stackoverflow.com/users/126995", "pm_score": 2, "selected": false, "text": "const __m128 c = _mm_setr_ps(1,2,3,4); __forceinline __forceinline" }, { "answer_id": 64094614, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "noinline __noinline noinline __forceinline callee caller caller noinline noinline noinline noinline baz foo baz foo baz noinline foo baz baz noinline foo foo baz foo foo baz noinline foo baz baz noinline noinline" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22244/" ]
151,929
<p>I'm using the <code>mechanize</code> module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.</p> <p>I just call it with:</p> <pre><code> self.browser = mechanize.Browser() self.browser.addheaders = [('User-agent', browser_header)] self.browser.open(query_url) self.result_page = self.browser.response().read() </code></pre> <p>How can I know what errors / exceptions can be thrown here and handle them ?</p>
[ { "answer_id": 155127, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": true, "text": "$ perl -0777 -ne'print qq($1) if /__all__ = \\[(.*?)\\]/s' __init__.py | grep Error \n\n'BrowserStateError',\n'ContentTooShortError',\n'FormNotFoundError',\n'GopherError',\n'HTTPDefaultErrorHandler',\n'HTTPError',\n'HTTPErrorProcessor',\n'LinkNotFoundError',\n'LoadError',\n'ParseError',\n'RobotExclusionError',\n'URLError',\n >>> import mechanize\n>>> filter(lambda s: \"Error\" in s, dir(mechanize))\n['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError'\n, 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr\nor', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError']\n" }, { "answer_id": 4648973, "author": "remote", "author_id": 186467, "author_profile": "https://Stackoverflow.com/users/186467", "pm_score": 2, "selected": false, "text": "import urllib2\ntry:\n... br.open(\"http://www.example.org/invalid-page\")\n... except urllib2.HTTPError, e:\n... print e.code\n... \n404\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
151,936
<p>I have some code where I'm returning an array of objects.</p> <p>Here's a simplified example:</p> <pre><code>string[] GetTheStuff() { List&lt;string&gt; s = null; if( somePredicate() ) { s = new List&lt;string&gt;(); // imagine we load some data or something } return (s == null) ? new string[0] : s.ToArray(); } </code></pre> <p>The question is, how expensive is the <code>new string[0]</code> ?<br /> Should I just return null and make the caller accept null as a valid way of indicating &quot;nothing was found&quot;?</p> <p>NB: This is being called in a loop which gets run hundreds and hundreds of times, so it's one of the few cases where I think this kind of optimiziation is not actually 'premature'.</p> <p>PS: And even if it was premature, I'd still like to know how it works :-)</p> <h3>Update:</h3> <p>Initially when I asked if it used any space, I was thinking of things from the 'C/C++' point of view, kind of like how in C, writing <code>char a[5];</code> will allocate 5 bytes of space on the stack, and <code>char b[0];</code> will allocate 0 bytes.</p> <p>I realise this is not a good fit for the .NET world, but I was curious if this was something that the compiler or CLR would detect and optimize out, as a non-resizeable array of size zero really shouldn't (as far as I can see?) require any storage space.</p>
[ { "answer_id": 151947, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "List<string> GetTheStuff()\n{\n List<string> s = new List<string();\n if (somePredicarte())\n {\n // more code\n }\n return s;\n}\n" }, { "answer_id": 151950, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "private static readonly string[] EmptyStringArray = new string[0];\n\nstring[] GetTheStuff() {\n if( somePredicate() ) {\n List<string> s = new List<string>(); \n // imagine we load some data or something\n return s.ToArray();\n } else {\n return EmptyStringArray;\n }\n}\n public static class Arrays<T> {\n public static readonly Empty = new T[0];\n}\n" }, { "answer_id": 151958, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "IList<string> GetTheStuff() {\n List<string> s = new List<string>();\n if( somePredicate() ) {\n // imagine we load some data or something\n }\n return s;\n}\n return new ReadOnlyCollection(s);\n" }, { "answer_id": 152141, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "List<T>, IList<T>, ICollection<T>, IEnumerable<T>" }, { "answer_id": 553975, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 2, "selected": false, "text": "Enumerable.Empty<T>() IEnumerable<string> GetTheStuff()\n{\n List<string> s = null;\n if (somePredicate())\n {\n var stuff = new List<string>();\n // load data\n return stuff;\n }\n\n return Enumerable.Empty<string>();\n}\n" }, { "answer_id": 30405133, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 3, "selected": false, "text": "string[] Array.Empty<string>()\n" }, { "answer_id": 51593741, "author": "Yitzchak", "author_id": 2830676, "author_profile": "https://Stackoverflow.com/users/2830676", "pm_score": 2, "selected": false, "text": "int[] int[] myArray = new int[0];\nint[] myArray2 = new int[1];\nchar[] myArray3 = new char[0];\n myArray: a8 1a 8f 70 00 00 00 00 00 00 00 00\nmyArray2: a8 1a 8f 70 01 00 00 00 00 00 00 00 00 00 00 00\nmyArray3: 50 06 8f 70 00 00 00 00 00 00 00 00\n int[] char[] a8 1a 8f 70 50 06 8f 70 00 00 00 00 myArray 01 00 00 00 myArray2 00 00 00 00" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
151,945
<p>Emacs puts backup files named <code>foo~</code> everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful. How can I either eliminate these backup files, or have them go somewhere other than the same directory?</p>
[ { "answer_id": 151946, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 10, "selected": true, "text": ".emacs (setq backup-directory-alist `((\".\" . \"~/.saves\")))\n (setq backup-by-copying t)\n backup-by-copying-when-linked C-h v (setq delete-old-versions t\n kept-new-versions 6\n kept-old-versions 2\n version-control t)\n (setq make-backup-files nil)\n" }, { "answer_id": 152192, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 5, "selected": false, "text": "M-x customize-group\n Customize group: backup Regexp matching filename: .*\nBackup directory name: /path/to/your/backup/dir\n off .emacs" }, { "answer_id": 467083, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 5, "selected": false, "text": "(setq make-backup-files nil)\n" }, { "answer_id": 18330742, "author": "Andreas Spindler", "author_id": 887771, "author_profile": "https://Stackoverflow.com/users/887771", "pm_score": 6, "selected": false, "text": "~ ~9~ make-backup-files save-buffer C-x C-s diff-backup dired-diff-backup C:\\Users\\USERNAME\\.emacs.d\\backups\\!drive_c!Users!USERNAME!.emacs.el.~7~\n C:\\Users\\USERNAME\\.emacs.el\n # C-x C-s save-buffer auto-save-interval auto-save-timeout revert-buffer recover-file recover-session M-x revert-buffer RET auto-save-intervall (defvar --backup-directory (concat user-emacs-directory \"backups\"))\n(if (not (file-exists-p --backup-directory))\n (make-directory --backup-directory t))\n(setq backup-directory-alist `((\".\" . ,--backup-directory)))\n(setq make-backup-files t ; backup of a file the first time it is saved.\n backup-by-copying t ; don't clobber symlinks\n version-control t ; version numbers for backup files\n delete-old-versions t ; delete excess backup files silently\n delete-by-moving-to-trash t\n kept-old-versions 6 ; oldest versions to keep when a new numbered backup is made (default: 2)\n kept-new-versions 9 ; newest versions to keep when a new numbered backup is made (default: 2)\n auto-save-default t ; auto-save every buffer that visits a file\n auto-save-timeout 20 ; number of seconds idle time before auto-save (default: 30)\n auto-save-interval 200 ; number of keystrokes between auto-saves (default: 300)\n )\n sensitive-minor-mode (setq auto-mode-alist\n (append\n (list\n '(\"\\\\.\\\\(vcf\\\\|gpg\\\\)$\" . sensitive-minor-mode)\n )\n auto-mode-alist))\n // -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-\n" }, { "answer_id": 20824625, "author": "ntc2", "author_id": 470844, "author_profile": "https://Stackoverflow.com/users/470844", "pm_score": 6, "selected": false, "text": "(setq version-control t ;; Use version numbers for backups.\n kept-new-versions 10 ;; Number of newest versions to keep.\n kept-old-versions 0 ;; Number of oldest versions to keep.\n delete-old-versions t ;; Don't ask to delete excess backup versions.\n backup-by-copying t) ;; Copy all files, don't rename them.\n (setq vc-make-backup-files t)\n ;; Default and per-save backups go here:\n(setq backup-directory-alist '((\"\" . \"~/.emacs.d/backup/per-save\")))\n\n(defun force-backup-of-buffer ()\n ;; Make a special \"per session\" backup at the first save of each\n ;; emacs session.\n (when (not buffer-backed-up)\n ;; Override the default parameters for per-session backups.\n (let ((backup-directory-alist '((\"\" . \"~/.emacs.d/backup/per-session\")))\n (kept-new-versions 3))\n (backup-buffer)))\n ;; Make a \"per save\" backup on each save. The first save results in\n ;; both a per-session and a per-save backup, to keep the numbering\n ;; of per-save backups consistent.\n (let ((buffer-backed-up nil))\n (backup-buffer)))\n\n(add-hook 'before-save-hook 'force-backup-of-buffer)\n $< $@ Makefile" }, { "answer_id": 71820260, "author": "FeralWhippet", "author_id": 3342122, "author_profile": "https://Stackoverflow.com/users/3342122", "pm_score": 0, "selected": false, "text": "(setq delete-auto-save-files t)" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11138/" ]
151,952
<p>The Project's Web section (under project properties in VS2008) has a list of debuggers: ASP.NET, Native Code, SQL Server. What is Native Code?</p>
[ { "answer_id": 16656663, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " [ CPU ] ==================================== [ RAM ]\n ^^^^^\n | |\n\n LOAD _memoryAddress12, D1 ; tells the CPU to get data from slot 12\n ; in RAM, and put it in register D1 inside the CPU\n\n ^^^^^\n | |\n\n ADD D1, 24 ; tells the CPU to do an internal calculation\n\n ^^^^^\n | |\n\n STORE R0, _memoryAddress23 ; tells the CPU to put the answer into slot 23 in ram\n load _firstInstruction, D1\n if_equal D1, 12\n jump _itsAnAddInstructionHandleIt\n if_equal D1, 13\n jump _itsASubstractInstructionHandleIt\n if_equal D1, 14\n jump _itsAMultiplyInstructionHandleIt\n if_equal D1, 15\n jump _itsADivideInstructionHandleIt\n if_equal D1, 16\n jump _itsALoadInstructionHandleIt\n ...\n\n_itsALoadInstructionHandleIt:\n load D1, D2\n add 4, D2\n load D2, D3\n return\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
151,959
<p>I have 2 fields in the database month (numeric) and year (numeric) and I want to combine them in a report that combines those 2 fields and format them with MMM-YYYY. e.g 7-2008 becomes Jul-2008. How do I do that?</p>
[ { "answer_id": 152114, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": true, "text": "DateSerial 1" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ]
151,963
<p>Is it possible to get the route/virtual url associated with a controller action or on a view? I saw that Preview 4 added LinkBuilder.BuildUrlFromExpression helper, but it's not very useful if you want to use it on the master, since the controller type can be different. Any thoughts are appreciated.</p>
[ { "answer_id": 691985, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<%= this.Url.RouteUrl(this.ViewContext.RouteData.Values) %> /Home/About" }, { "answer_id": 1268335, "author": "Jim Geurts", "author_id": 3085, "author_profile": "https://Stackoverflow.com/users/3085", "pm_score": 5, "selected": true, "text": "public bool IsController(string controller)\n{\n if (ViewContext.RouteData.Values[\"controller\"] != null)\n {\n return ViewContext.RouteData.Values[\"controller\"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);\n }\n return false;\n}\npublic bool IsAction(string action)\n{\n if (ViewContext.RouteData.Values[\"action\"] != null)\n {\n return ViewContext.RouteData.Values[\"action\"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);\n }\n return false;\n}\npublic bool IsAction(string action, string controller)\n{\n return IsController(controller) && IsAction(action);\n}\n public static class UrlHelperExtensions\n{\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <typeparam name=\"TController\">The type of the controller.</typeparam>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"action\">The action to check.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller\n {\n MethodCallExpression call = action.Body as MethodCallExpression;\n if (call == null)\n {\n throw new ArgumentException(\"Expression must be a method call\", \"action\");\n }\n\n return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&\n typeof(TController) == helper.ViewContext.Controller.GetType());\n }\n\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"actionName\">Name of the action.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction(this UrlHelper helper, string actionName)\n {\n if (String.IsNullOrEmpty(actionName))\n {\n throw new ArgumentException(\"Please specify the name of the action\", \"actionName\");\n }\n string controllerName = helper.ViewContext.RouteData.GetRequiredString(\"controller\");\n return IsAction(helper, actionName, controllerName);\n }\n\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"actionName\">Name of the action.</param>\n /// <param name=\"controllerName\">Name of the controller.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)\n {\n if (String.IsNullOrEmpty(actionName))\n {\n throw new ArgumentException(\"Please specify the name of the action\", \"actionName\");\n }\n if (String.IsNullOrEmpty(controllerName))\n {\n throw new ArgumentException(\"Please specify the name of the controller\", \"controllerName\");\n }\n\n if (!controllerName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n controllerName = controllerName + \"Controller\";\n }\n\n bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);\n return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);\n }\n\n /// <summary>\n /// Determines if the current request is on the specified controller\n /// </summary>\n /// <param name=\"helper\">The helper.</param>\n /// <param name=\"controllerName\">Name of the controller.</param>\n /// <returns>\n /// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsController(this UrlHelper helper, string controllerName)\n {\n if (String.IsNullOrEmpty(controllerName))\n {\n throw new ArgumentException(\"Please specify the name of the controller\", \"controllerName\");\n }\n\n if (!controllerName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n controllerName = controllerName + \"Controller\";\n }\n\n return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);\n }\n\n /// <summary>\n /// Determines if the current request is on the specified controller\n /// </summary>\n /// <typeparam name=\"TController\">The type of the controller.</typeparam>\n /// <param name=\"helper\">The helper.</param>\n /// <returns>\n /// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsController<TController>(this UrlHelper helper) where TController : Controller\n {\n return (typeof(TController) == helper.ViewContext.Controller.GetType());\n }\n}\n" }, { "answer_id": 4790073, "author": "Tarzan", "author_id": 152118, "author_profile": "https://Stackoverflow.com/users/152118", "pm_score": 5, "selected": false, "text": "<%: Request.Path %>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3085/" ]
151,966
<p>I want to use remote debugging. The program that I want to debug runs on machine b. Visual Studio runs on machine a. </p> <p>On machine b I have a folder with the following files:</p> <ul> <li>msvcr72.dll</li> <li>msvsmon.exe</li> <li>NatDbgDE.dll</li> <li>NatDbgDEUI.dll</li> <li>NatDbgEE.dll</li> <li>NatDbgEEUI.dll</li> </ul> <p>If you think some files are missing, could you also describe where they are usually located?</p> <p>In the next step I started the <code>msvsmon.exe</code> and my program on machine b. On machine a, I started Visual Studio 2008 and my solution in which the program was written. Then I choose "Debug - Attach to Process". I chose "Remote Transport (Native Only with no authentication)". I used the correct IP as a qualifier and took the right process (program.exe). After a while the following message occurred in a popup-window:</p> <blockquote> <p>Unhandled exception at 0x7c812a7b in program.exe: 0xE0434F4D: 0xe0434f4d</p> </blockquote> <p>I can continue or break; When continuing, the exception occurs again and again and again. So I pressed break and the following message occurred:</p> <blockquote> <p>No symbols are loaded for any call stack frame. The source code cannot be displayed.</p> </blockquote>
[ { "answer_id": 1144616, "author": "BrianR", "author_id": 140302, "author_profile": "https://Stackoverflow.com/users/140302", "pm_score": 4, "selected": false, "text": "_NT_SYMBOL_PATH" }, { "answer_id": 54309251, "author": "Joel", "author_id": 7392502, "author_profile": "https://Stackoverflow.com/users/7392502", "pm_score": 0, "selected": false, "text": "Set as StartUp Project" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23681/" ]
151,969
<p>In PHP 5, what is the difference between using <code>self</code> and <code>$this</code>?</p> <p>When is each appropriate?</p>
[ { "answer_id": 151975, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 4, "selected": false, "text": "$self $this self" }, { "answer_id": 151976, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 12, "selected": true, "text": "$this self $this->member self::$member $this self <?php\nclass X {\n private $non_static_member = 1;\n private static $static_member = 2;\n\n function __construct() {\n echo $this->non_static_member . ' '\n . self::$static_member;\n }\n}\n\nnew X();\n?>\n $this self <?php\nclass X {\n private $non_static_member = 1;\n private static $static_member = 2;\n\n function __construct() {\n echo self::$non_static_member . ' '\n . $this->static_member;\n }\n}\n\nnew X();\n?>\n $this <?php\nclass X {\n function foo() {\n echo 'X::foo()';\n }\n\n function bar() {\n $this->foo();\n }\n}\n\nclass Y extends X {\n function foo() {\n echo 'Y::foo()';\n }\n}\n\n$x = new Y();\n$x->bar();\n?>\n self <?php\nclass X {\n function foo() {\n echo 'X::foo()';\n }\n\n function bar() {\n self::foo();\n }\n}\n\nclass Y extends X {\n function foo() {\n echo 'Y::foo()';\n }\n}\n\n$x = new Y();\n$x->bar();\n?>\n $this->foo() foo() type X X::foo() type Y Y::foo() X::foo()" }, { "answer_id": 152073, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 7, "selected": false, "text": "self $this self $this this $this->member self self::member" }, { "answer_id": 226844, "author": "lo_fye", "author_id": 3407, "author_profile": "https://Stackoverflow.com/users/3407", "pm_score": 7, "selected": false, "text": "$this-> Example: \n$derek = new Person();\n function __construct()\n{\n if(!isset $num_connections || $num_connections==null)\n {\n $num_connections=0;\n }\n else\n {\n $num_connections++;\n }\n}\n function __destruct()\n{\n $num_connections--;\n}\n echo DB::num_connections;\n public static function prettyName($first_name, $last_name)\n{\n echo ucfirst($first_name).' '.ucfirst($last_name);\n}\n\necho Person::prettyName($derek->first_name, $derek->last_name);\n" }, { "answer_id": 879425, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "ClassName::staticMember self::classmember $this->classmember self:: $this-> class Person{\n private $name;\n private $address;\n\n public function __construct($new_name,$new_address){\n $this->name = $new_name;\n $this->address = $new_address;\n }\n}\n\nclass Person{\n private $name;\n private $address;\n public function __construct($new_name,$new_address){\n self::$name = $new_name;\n self::$address = $new_address;\n }\n}\n" }, { "answer_id": 1189663, "author": "nbeagle", "author_id": 145910, "author_profile": "https://Stackoverflow.com/users/145910", "pm_score": 10, "selected": false, "text": "self parent::methodName() self::methodName() class Person {\n private $name;\n\n public function __construct($name) {\n $this->name = $name;\n }\n\n public function getName() {\n return $this->name;\n }\n\n public function getTitle() {\n return $this->getName().\" the person\";\n }\n\n public function sayHello() {\n echo \"Hello, I'm \".$this->getTitle().\"<br/>\";\n }\n\n public function sayGoodbye() {\n echo \"Goodbye from \".self::getTitle().\"<br/>\";\n }\n}\n\nclass Geek extends Person {\n public function __construct($name) {\n parent::__construct($name);\n }\n\n public function getTitle() {\n return $this->getName().\" the geek\";\n }\n}\n\n$geekObj = new Geek(\"Ludwig\");\n$geekObj->sayHello();\n$geekObj->sayGoodbye();\n sayHello() $this Geek::getTitle() sayGoodbye() self::getTitle() Person::getTitle() $this" }, { "answer_id": 6807615, "author": "Sqoo", "author_id": 199687, "author_profile": "https://Stackoverflow.com/users/199687", "pm_score": 9, "selected": false, "text": "self:: static:: self:: class Person\n{\n\n public static function status()\n {\n self::getStatus();\n }\n\n protected static function getStatus()\n {\n echo \"Person is alive\";\n }\n\n}\n Person::status() class Deceased extends Person\n{\n\n protected static function getStatus()\n {\n echo \"Person is deceased\";\n }\n\n}\n Deceased::status() self::getStatus() static:: status() static::getStatus() $this-> static::" }, { "answer_id": 8399151, "author": "Mohit Bumb", "author_id": 1470999, "author_profile": "https://Stackoverflow.com/users/1470999", "pm_score": 4, "selected": false, "text": "<?php\nclass X {\n private $non_static_member = 1;\n private static $static_member = 2;\n\n function __construct() {\n echo $this->non_static_member . ' '\n . self::$static_member;\n }\n}\n\nnew X();\n?> \n" }, { "answer_id": 15573773, "author": "mrDjouk", "author_id": 2199125, "author_profile": "https://Stackoverflow.com/users/2199125", "pm_score": 4, "selected": false, "text": "self :: $this $this" }, { "answer_id": 15573992, "author": "Xeoncross", "author_id": 99923, "author_profile": "https://Stackoverflow.com/users/99923", "pm_score": 4, "selected": false, "text": "$this static self parent <?php\n\nclass A {\n\n public static function newStaticClass()\n {\n return new static;\n }\n\n public static function newSelfClass()\n {\n return new self;\n }\n\n public function newThisClass()\n {\n return new $this;\n }\n}\n\nclass B extends A\n{\n public function newParentClass()\n {\n return new parent;\n }\n}\n\n\n$b = new B;\n\nvar_dump($b::newStaticClass()); // B\nvar_dump($b::newSelfClass()); // A because self belongs to \"A\"\nvar_dump($b->newThisClass()); // B\nvar_dump($b->newParentClass()); // A\n\n\nclass C extends B\n{\n public static function newSelfClass()\n {\n return new self;\n }\n}\n\n\n$c = new C;\n\nvar_dump($c::newStaticClass()); // C\nvar_dump($c::newSelfClass()); // C because self now points to \"C\" class\nvar_dump($c->newThisClass()); // C\nvar_dump($b->newParentClass()); // A because parent was defined *way back* in class \"B\"\n static $this self" }, { "answer_id": 15929796, "author": "Minhaj", "author_id": 2162092, "author_profile": "https://Stackoverflow.com/users/2162092", "pm_score": 3, "selected": false, "text": "self this" }, { "answer_id": 16434516, "author": "Tarun Singhal", "author_id": 1719634, "author_profile": "https://Stackoverflow.com/users/1719634", "pm_score": 5, "selected": false, "text": "$this self self $this self::STAT // refer to a constant value\nself::$stat // static variable\n$this->stat // refer to an object variable \n" }, { "answer_id": 16481781, "author": "okconfused", "author_id": 1541177, "author_profile": "https://Stackoverflow.com/users/1541177", "pm_score": 5, "selected": false, "text": "self self self self $this $this $this self $this" }, { "answer_id": 17027307, "author": "ircmaxell", "author_id": 338665, "author_profile": "https://Stackoverflow.com/users/338665", "pm_score": 8, "selected": false, "text": "self $this class Person {\n public $name = 'my name';\n public function sayHello() {\n echo \"Hello\";\n }\n}\n $name sayHello() Person $bob = new Person;\n$adam = new Person;\n$bob->name = 'Bob';\necho $adam->name; // \"my name\"\n new -> instanceof $bob instanceof Person $bob Person Person class Foo {\n public $bar = 1;\n}\n class Foo {\n public static $bar = 1;\n}\n class Foo {\n public function bar() {}\n}\n class Foo {\n public static function bar() {}\n}\n class Foo {\n const BAR = 1;\n}\n $this $this -> $bob = new Person;\necho $bob->name;\n Person->foo Person :: echo Foo::bar()\n echo $foo::bar()\n bar() $class = get_class($foo);\n$class::bar();\n $this -> class Foo {\n public $a = 1;\n public function bar() {\n return $this->a;\n }\n}\n bar() $foo Foo $foo->bar() $a :: :: class Foo {\n public function bar() {\n return Foo::baz();\n }\n public function baz() {\n return isset($this);\n }\n}\n Foo::bar() baz() $this E_STRICT :: static $foo->bar() true self self::baz() Foo::baz() Foo parent static static class Person {\n public static $number = 0;\n public $id = 0;\n public function __construct() {\n self::$number++;\n $this->id = self::$number;\n }\n public $name = \"\";\n public function getName() {\n return $this->name;\n }\n public function getId() {\n return $this->id;\n }\n}\n\nclass Child extends Person {\n public $age = 0;\n public function __construct($age) {\n $this->age = $age;\n parent::__construct();\n }\n public function getName() {\n return 'child: ' . parent::getName();\n }\n}\n $bob = new Person;\n$bob->name = \"Bob\";\n$adam = new Person;\n$adam->name = \"Adam\";\n$billy = new Child;\n$billy->name = \"Billy\";\nvar_dump($bob->getId()); // 1\nvar_dump($adam->getId()); // 2\nvar_dump($billy->getId()); // 3\n self static var_dump($bob->getName()); // Bob\nvar_dump($adam->getName()); // Adam\nvar_dump($billy->getName()); // child: Billy\n Person::getName() parent::getName() class Foo {\n public function isFoo() {\n return $this instanceof Foo;\n }\n}\n class Bar {\n public function doSomething() {\n return Foo::isFoo();\n }\n}\n$b = new Bar;\nvar_dump($b->doSomething()); // bool(false)\n $this Foo::isFoo() $bar :: static self parent static self static self self $this self $this -> ::" }, { "answer_id": 25842131, "author": "Rakesh Singh", "author_id": 1855621, "author_profile": "https://Stackoverflow.com/users/1855621", "pm_score": 3, "selected": false, "text": "$this self self for static this for none-static members or methods self / parent" }, { "answer_id": 26107386, "author": "Will B.", "author_id": 1144627, "author_profile": "https://Stackoverflow.com/users/1144627", "pm_score": 3, "selected": false, "text": "$this:: static:: $this:: class Foo\n{\n const NAME = 'Foo';\n\n //Always Foo::NAME (Foo) due to self\n protected static $staticName = self::NAME;\n\n public function __construct()\n {\n echo $this::NAME;\n }\n\n public function getStaticName()\n {\n echo $this::$staticName;\n }\n}\n\nclass Bar extends Foo\n{\n const NAME = 'FooBar';\n\n /**\n * override getStaticName to output Bar::NAME\n */\n public function getStaticName()\n {\n $this::$staticName = $this::NAME;\n parent::getStaticName();\n }\n}\n\n$foo = new Foo; //outputs Foo\n$bar = new Bar; //outputs FooBar\n$foo->getStaticName(); //outputs Foo\n$bar->getStaticName(); //outputs FooBar\n$foo->getStaticName(); //outputs FooBar\n $object::CONSTANT echo $foo::NAME; $this::NAME;" }, { "answer_id": 27689715, "author": "ramin rostami", "author_id": 1512065, "author_profile": "https://Stackoverflow.com/users/1512065", "pm_score": 5, "selected": false, "text": "$this->method() self::method() method() class ParentClass {\n function test() {\n self::who(); // will output 'parent'\n $this->who(); // will output 'child'\n }\n\n function who() {\n echo 'parent';\n }\n}\n\nclass ChildClass extends ParentClass {\n function who() {\n echo 'child';\n }\n}\n\n$obj = new ChildClass();\n$obj->test();\n self::who() $this->who() $this $this" }, { "answer_id": 30554801, "author": "tleb", "author_id": 4255615, "author_profile": "https://Stackoverflow.com/users/4255615", "pm_score": 4, "selected": false, "text": " Speed (in seconds) Percentage\n$this-> 0.91760206222534 100\nself:: 1.0047659873962 109.49909865716\nstatic:: 0.98066782951355 106.87288857386\n <?php\n\nclass Foo\n{\n public function calling_this() { $this->called(); }\n public function calling_self() { self::called(); }\n public function calling_static() { static::called(); }\n public static function called() {}\n}\n\n$foo = new Foo();\n$n = 4000000;\n$times = [];\n\n// warmup\nfor ($i = 0; $i < $n; $i++) { $foo->calling_this(); }\nfor ($i = 0; $i < $n; $i++) { $foo->calling_self(); }\nfor ($i = 0; $i < $n; $i++) { $foo->calling_static(); }\n\n$start = microtime(true);\nfor ($i = 0; $i < $n; $i++) { $foo->calling_this(); }\n$times[\"this\"] = microtime(true)-$start;\n\n$start = microtime(true);\nfor ($i = 0; $i < $n; $i++) { $foo->calling_self(); }\n$times[\"self\"] = microtime(true)-$start;\n\n$start = microtime(true);\nfor ($i = 0; $i < $n; $i++) { $foo->calling_static(); }\n$times[\"static\"] = microtime(true)-$start;\n\n$min = min($times);\necho $times[\"this\"] . \"\\t\" . ($times[\"this\"] / $min)*100 . \"\\n\";\necho $times[\"self\"] . \"\\t\" . ($times[\"self\"] / $min)*100 . \"\\n\";\necho $times[\"static\"] . \"\\t\" . ($times[\"static\"] / $min)*100 . \"\\n\";\n" }, { "answer_id": 34131217, "author": "Fil", "author_id": 3721034, "author_profile": "https://Stackoverflow.com/users/3721034", "pm_score": 1, "selected": false, "text": "self parent static $this" }, { "answer_id": 34554103, "author": "Kabir Hossain", "author_id": 3173328, "author_profile": "https://Stackoverflow.com/users/3173328", "pm_score": 5, "selected": false, "text": "self $this class ParentClass {\n function test() {\n self::which(); // Outputs 'parent'\n $this->which(); // Outputs 'child'\n }\n\n function which() {\n echo 'parent';\n }\n}\n\nclass ChildClass extends ParentClass {\n function which() {\n echo 'child';\n }\n}\n\n$obj = new ChildClass();\n$obj->test();\n parent\n child\n" }, { "answer_id": 35163551, "author": "li bing zhao", "author_id": 4637840, "author_profile": "https://Stackoverflow.com/users/4637840", "pm_score": 2, "selected": false, "text": "self classA::POUNDS_TO_KILOGRAMS" }, { "answer_id": 50426807, "author": "Mike", "author_id": 8243442, "author_profile": "https://Stackoverflow.com/users/8243442", "pm_score": 4, "selected": false, "text": "$this self:: self: $this" }, { "answer_id": 61258357, "author": "Deepak Syal", "author_id": 5371637, "author_profile": "https://Stackoverflow.com/users/5371637", "pm_score": 3, "selected": false, "text": "class cars{\n var $doors = 4;\n static $car_wheel = 4;\n\n public function car_features(){\n echo $this->doors . \" Doors <br>\";\n echo self::$car_wheel . \" Wheels <br>\";\n }\n}\n\nclass spec extends cars{\n function car_spec(){\n print(self::$car_wheel . \" Doors <br>\");\n print($this->doors . \" Wheels <br>\");\n }\n}\n\n/********Parent class output*********/\n\n$car = new cars;\nprint_r($car->car_features());\n\necho \"------------------------<br>\";\n\n/********Extend class from another class output**********/\n\n\n$car_spec_show = new spec;\n\nprint($car_spec_show->car_spec());\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ]
151,979
<p>Have a look at this very simple example WPF program:</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;GroupBox&gt; &lt;GroupBox.Header&gt; &lt;CheckBox Content="Click Here"/&gt; &lt;/GroupBox.Header&gt; &lt;/GroupBox&gt; &lt;/Window&gt; </code></pre> <p>So I have a GroupBox whose header is a CheckBox. We've all done something like this - typically you bind the content of the GroupBox in such a way that it's disabled when the CheckBox is unchecked.</p> <p>However, when I run this application and click on the CheckBox, I've found that sometimes my mouse clicks are swallowed and the CheckBox's status doesn't change. If I'm right, it's when I click on the exact row of pixels that the GroupBox's top border sits on.</p> <p>Can someone duplicate this? Why would this occur, and is there a way around it?</p> <p>Edit: Setting the GroupBox's BorderThickness to 0 solves the problem, but obviously it removes the border, so it doesn't look like a GroupBox anymore.</p>
[ { "answer_id": 151999, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 2, "selected": false, "text": "<GroupBox BorderBrush=\"{x:Null}\">\n" }, { "answer_id": 152562, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 5, "selected": true, "text": "<BorderGapMaskConverter x:Key=\"BorderGapMaskConverter\"/>\n\n<Style x:Key=\"GroupBoxStyle1\" TargetType=\"{x:Type GroupBox}\">\n <Setter Property=\"BorderBrush\" Value=\"#D5DFE5\"/>\n <Setter Property=\"BorderThickness\" Value=\"1\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type GroupBox}\">\n <Grid SnapsToDevicePixels=\"true\">\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"*\"/>\n <RowDefinition Height=\"6\"/>\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"6\"/>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"6\"/>\n </Grid.ColumnDefinitions>\n <Border Grid.Column=\"0\" Grid.ColumnSpan=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" Background=\"{TemplateBinding Background}\" BorderBrush=\"Transparent\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"4\"/>\n <ContentPresenter Margin=\"{TemplateBinding Padding}\" SnapsToDevicePixels=\"{TemplateBinding SnapsToDevicePixels}\" Grid.Column=\"1\" Grid.ColumnSpan=\"2\" Grid.Row=\"2\"/>\n <Border Grid.ColumnSpan=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" BorderBrush=\"White\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"4\">\n <Border.OpacityMask>\n <MultiBinding Converter=\"{StaticResource BorderGapMaskConverter}\" ConverterParameter=\"7\">\n <Binding Path=\"ActualWidth\" ElementName=\"Header\"/>\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Self}\"/>\n <Binding Path=\"ActualHeight\" RelativeSource=\"{RelativeSource Self}\"/>\n </MultiBinding>\n </Border.OpacityMask>\n <Border BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"3\">\n <Border BorderBrush=\"White\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"2\"/>\n </Border>\n </Border>\n <Border x:Name=\"Header\" Grid.Column=\"1\" Grid.Row=\"0\" Grid.RowSpan=\"2\" Padding=\"3,1,3,0\">\n <ContentPresenter SnapsToDevicePixels=\"{TemplateBinding SnapsToDevicePixels}\" ContentSource=\"Header\" RecognizesAccessKey=\"True\"/>\n </Border>\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n" }, { "answer_id": 3709904, "author": "Rune Andersen", "author_id": 447453, "author_profile": "https://Stackoverflow.com/users/447453", "pm_score": 4, "selected": false, "text": "public override void OnApplyTemplate()\n{\n base.OnApplyTemplate();\n if (Children.Count == 0) return;\n\n var grid = GetVisualChild(0) as Grid;\n if (grid != null && grid.Children.Count > 3)\n {\n var bd = grid.Children[3] as Border;\n if (bd != null)\n {\n bd.IsHitTestVisible = false;\n }\n }\n}\n" }, { "answer_id": 4014508, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 5, "selected": false, "text": "IsHitTestVisible=false <BorderGapMaskConverter x:Key=\"GroupBoxBorderGapMaskConverter\" />\n\n<Style x:Key=\"{x:Type GroupBox}\" TargetType=\"{x:Type GroupBox}\">\n <Setter Property=\"Control.BorderBrush\" Value=\"#FFD5DFE5\" />\n <Setter Property=\"Control.BorderThickness\" Value=\"1\" />\n <Setter Property=\"Control.Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type GroupBox}\">\n <Grid SnapsToDevicePixels=\"True\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"6\" />\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"6\" />\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"6\" />\n </Grid.RowDefinitions>\n <Border Name=\"Header\" Padding=\"3,1,3,0\" Grid.Row=\"0\" Grid.RowSpan=\"2\" Grid.Column=\"1\">\n <ContentPresenter ContentSource=\"Header\" RecognizesAccessKey=\"True\" SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" />\n </Border>\n <Border CornerRadius=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" Grid.Column=\"0\" Grid.ColumnSpan=\"4\" BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"#00FFFFFF\" Background=\"{TemplateBinding Control.Background}\" IsHitTestVisible=\"False\" />\n <ContentPresenter Grid.Row=\"2\" Grid.Column=\"1\" Grid.ColumnSpan=\"2\" Margin=\"{TemplateBinding Control.Padding}\" SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\"/>\n <Border CornerRadius=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"4\" BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"#FFFFFFFF\" IsHitTestVisible=\"False\">\n <UIElement.OpacityMask>\n <MultiBinding Converter=\"{StaticResource GroupBoxBorderGapMaskConverter}\" ConverterParameter=\"7\">\n <Binding ElementName=\"Header\" Path=\"ActualWidth\" />\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Self}\" />\n <Binding Path=\"ActualHeight\" RelativeSource=\"{RelativeSource Self}\" />\n </MultiBinding>\n </UIElement.OpacityMask>\n <Border BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"{TemplateBinding Control.BorderBrush}\" CornerRadius=\"3\">\n <Border BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"#FFFFFFFF\" CornerRadius=\"2\" />\n </Border>\n </Border> \n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
152,003
<p>I need to scan uploaded files for viruses on a Linux server, but I'm not sure how to go about it.</p> <p>What are my options, if any? I'm also interested in how the scanners perform when multiple users send multiple files at the same time.</p>
[ { "answer_id": 152014, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "clamscan" }, { "answer_id": 165899, "author": "kari.patila", "author_id": 21716, "author_profile": "https://Stackoverflow.com/users/21716", "pm_score": 4, "selected": false, "text": "+-----------+------------------------------+\n| Results | File |\n+-----------+------------------------------+\n| infected | AdvancedXPFixerInstaller.exe |\n| pass | auto.exe |\n| pass | cartao.exe |\n| infected | cartoes_natal.exe |\n| pass | codec.exe |\n| pass | e421.exe |\n| pass | fixtool.exe |\n| infected | flash_install.exe |\n| infected | issj.exe |\n| infected | iwmdo.exe |\n| infected | jobxxc.exe |\n| infected | kbmt.exe |\n| pass | killer_cdj.exe |\n| pass | killer_javqhc.exe |\n| infected | killer_rodog.exe |\n| infected | kl.exe |\n| infected | MacromediaFlash.exe |\n| infected | MacromediaFlashPlayer.exe |\n| infected | paraense.exe |\n| infected | pibzero.exe |\n| pass | scan.exe |\n| pass | uaqxtg.exe |\n| pass | vejkcfu.exe |\n| infected | VIDeoSS.exe |\n| infected | wujowpq.exe |\n| pass | X-IrCBOT.exe |\n+-----------+------------------------------+\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ]
152,005
<p>What is currying?</p> <p>How can currying be done in C++?</p> <p>Please Explain binders in STL container?</p>
[ { "answer_id": 152020, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "f(x, y) Y g(x) g(x) == f(x, Y)\n f Y #include <functional>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n// declare a binary function object\nclass adder: public binary_function<int, int, int> {\npublic:\n int operator()(int x, int y) const\n {\n return x + y;\n }\n};\n\nint main()\n{\n // initialise some sample data\n vector<int> a, b;\n a.push_back(1);\n a.push_back(2);\n a.push_back(3);\n\n // here we declare a function object f and try it out\n adder f;\n cout << \"f(2, 3) = \" << f(2, 3) << endl;\n\n // transform() expects a function with one argument, so we use\n // bind2nd to make a new function based on f, that takes one\n // argument and adds 5 to it\n transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));\n\n // output b to see what we got\n cout << \"b = [\" << endl;\n for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {\n cout << \" \" << *i << endl;\n }\n cout << \"]\" << endl;\n\n return 0;\n}\n" }, { "answer_id": 152021, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "full = (lambda a, b, c: (a + b + c))\nprint full (1, 2, 3) # print 6\n\n# Curried style\ncurried = (lambda a: (lambda b: (lambda c: (a + b + c))))\nprint curried (1)(2)(3) # print 6\n" }, { "answer_id": 152268, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "transform(a.begin(), a.end(), back_inserter(b), bind(f, _1, 5));\n 5 f" }, { "answer_id": 160286, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 4, "selected": false, "text": "#include <functional> \nusing namespace std;\nusing namespace std::tr1;\nusing namespace std::tr1::placeholders;\n\nint f(int, int);\n..\nint main(){\n function<int(int)> g = bind(f, _1, 5); // g(x) == f(x, 5)\n function<int(int)> h = bind(f, 2, _1); // h(x) == f(2, x)\n function<int(int,int)> j = bind(g, _2); // j(x,y) == g(y)\n}\n int f(int, int);\n..\nint main(){\n auto g = [](int x){ return f(x,5); }; // g(x) == f(x, 5)\n auto h = [](int x){ return f(2,x); }; // h(x) == f(2, x)\n auto j = [](int x, int y){ return g(y); }; // j(x,y) == g(y)\n}\n struct foo{\n int x;\n int operator()(int y) const {\n x = 42; // error! const function can't modify members\n }\n};\n..\nint main(){\n int x;\n auto f = [](int y){ x = 42; }; // error! lambdas don't capture by default.\n}\n" }, { "answer_id": 6137984, "author": "missingfaktor", "author_id": 192247, "author_profile": "https://Stackoverflow.com/users/192247", "pm_score": 4, "selected": false, "text": "#include <iostream>\n#include <functional>\n\nusing namespace std;\n\nconst function<int(int, int)> & simple_add = \n [](int a, int b) -> int {\n return a + b;\n };\n\nconst function<function<int(int)>(int)> & curried_add = \n [](int a) -> function<int(int)> {\n return [a](int b) -> int {\n return a + b;\n };\n };\n\nint main() {\n // Demonstrating simple_add\n cout << simple_add(4, 5) << endl; // prints 9\n\n // Demonstrating curried_add\n cout << curried_add(4)(5) << endl; // prints 9\n\n // Create a partially applied function from curried_add\n const auto & add_4 = curried_add(4);\n cout << add_4(5) << endl; // prints 9\n}\n" }, { "answer_id": 26213996, "author": "kasoki", "author_id": 2292096, "author_profile": "https://Stackoverflow.com/users/2292096", "pm_score": 4, "selected": false, "text": "template<typename Function, typename... Arguments>\nauto curry(Function function, Arguments... args) {\n return [=](auto... rest) {\n return function(args..., rest...);\n }; // don't forget semicolumn\n}\n auto add = [](auto x, auto y) { return x + y; }\n\n// curry 4 into add\nauto add4 = curry(add, 4);\n\nadd4(6); // 10\n" }, { "answer_id": 26768388, "author": "Julian", "author_id": 2622629, "author_profile": "https://Stackoverflow.com/users/2622629", "pm_score": 6, "selected": false, "text": "f int\nf(int a,std::string b,float c)\n{\n // do something with a, b, and c\n return 0;\n}\n f f(1,\"some string\",19.7f) f curried_f=curry(f) f a f(1,\"some string\",19.7f) curried_f(1)(\"some string\")(19.7f) curried_f(1) f curried_f curried_f(first_arg)(second_arg)...(last_arg) == f(first_arg,second_arg,...,last_arg).\n auto curried=curry(f)(arg1)(arg2)(arg3) auto result=curried(arg4)(arg5) #include <functional>\n\nnamespace _dtl {\n\n template <typename FUNCTION> struct\n _curry;\n\n // specialization for functions with a single argument\n template <typename R,typename T> struct\n _curry<std::function<R(T)>> {\n using\n type = std::function<R(T)>;\n \n const type\n result;\n \n _curry(type fun) : result(fun) {}\n \n };\n\n // recursive specialization for functions with more arguments\n template <typename R,typename T,typename...Ts> struct\n _curry<std::function<R(T,Ts...)>> {\n using\n remaining_type = typename _curry<std::function<R(Ts...)> >::type;\n \n using\n type = std::function<remaining_type(T)>;\n \n const type\n result;\n \n _curry(std::function<R(T,Ts...)> fun)\n : result (\n [=](const T& t) {\n return _curry<std::function<R(Ts...)>>(\n [=](const Ts&...ts){ \n return fun(t, ts...); \n }\n ).result;\n }\n ) {}\n };\n}\n\ntemplate <typename R,typename...Ts> auto\ncurry(const std::function<R(Ts...)> fun)\n-> typename _dtl::_curry<std::function<R(Ts...)>>::type\n{\n return _dtl::_curry<std::function<R(Ts...)>>(fun).result;\n}\n\ntemplate <typename R,typename...Ts> auto\ncurry(R(* const fun)(Ts...))\n-> typename _dtl::_curry<std::function<R(Ts...)>>::type\n{\n return _dtl::_curry<std::function<R(Ts...)>>(fun).result;\n}\n\n#include <iostream>\n\nvoid \nf(std::string a,std::string b,std::string c)\n{\n std::cout << a << b << c;\n}\n\nint \nmain() {\n curry(f)(\"Hello \")(\"functional \")(\"world!\");\n return 0;\n}\n _dtl::_curry curry std::function FUNCTION _curry(std::function<R(T,Ts...)> fun)\n : result (\n [=](const T& t) {\n return _curry<std::function<R(Ts...)>>(\n [=](const Ts&...ts){ \n return fun(t, ts...); \n }\n ).result;\n }\n ) {}\n fun N-1 _curry<Ts...> if constexpr void_t template< class, class = std::void_t<> > struct \nneeds_unapply : std::true_type { };\n \ntemplate< class T > struct \nneeds_unapply<T, std::void_t<decltype(std::declval<T>()())>> : std::false_type { };\n\ntemplate <typename F> auto\ncurry(F&& f) {\n /// Check if f() is a valid function call. If not we need \n /// to curry at least one argument:\n if constexpr (needs_unapply<decltype(f)>::value) {\n return [=](auto&& x) {\n return curry(\n [=](auto&&...xs) -> decltype(f(x,xs...)) {\n return f(x,xs...);\n }\n );\n }; \n }\n else { \n /// If 'f()' is a valid call, just call it, we are done.\n return f();\n }\n}\n\nint \nmain()\n{\n auto f = [](auto a, auto b, auto c, auto d) {\n return a * b * c * d;\n };\n \n return curry(f)(1)(2)(3)(4);\n}\n constexpr if needs_unapply<decltype(f)>::value template <typename F> auto\ncurry(F&& f);\n\ntemplate <bool> struct\ncurry_on;\n\ntemplate <> struct\ncurry_on<false> {\n template <typename F> static auto\n apply(F&& f) {\n return f();\n }\n};\n\ntemplate <> struct\ncurry_on<true> {\n template <typename F> static auto \n apply(F&& f) {\n return [=](auto&& x) {\n return curry(\n [=](auto&&...xs) -> decltype(f(x,xs...)) {\n return f(x,xs...);\n }\n );\n };\n }\n};\n\ntemplate <typename F> auto\ncurry(F&& f) {\n return curry_on<needs_unapply<decltype(f)>::value>::template apply(f);\n}\n" }, { "answer_id": 27736361, "author": "Gabriel Garcia", "author_id": 612169, "author_profile": "https://Stackoverflow.com/users/612169", "pm_score": 2, "selected": false, "text": "std::function main #include <type_traits>\n#include <tuple>\n#include <functional>\n#include <iostream>\n\n// ---\n\ntemplate <typename FType>\nstruct function_traits;\n\ntemplate <typename RType, typename... ArgTypes>\nstruct function_traits<RType(ArgTypes...)> {\n using arity = std::integral_constant<size_t, sizeof...(ArgTypes)>;\n\n using result_type = RType;\n\n template <size_t Index>\n using arg_type = typename std::tuple_element<Index, std::tuple<ArgTypes...>>::type;\n};\n\n// ---\n\nnamespace details {\n template <typename T>\n struct function_type_impl\n : function_type_impl<decltype(&T::operator())>\n { };\n\n template <typename RType, typename... ArgTypes>\n struct function_type_impl<RType(ArgTypes...)> {\n using type = RType(ArgTypes...);\n };\n\n template <typename RType, typename... ArgTypes>\n struct function_type_impl<RType(*)(ArgTypes...)> {\n using type = RType(ArgTypes...);\n };\n\n template <typename RType, typename... ArgTypes>\n struct function_type_impl<std::function<RType(ArgTypes...)>> {\n using type = RType(ArgTypes...);\n };\n\n template <typename T, typename RType, typename... ArgTypes>\n struct function_type_impl<RType(T::*)(ArgTypes...)> {\n using type = RType(ArgTypes...);\n };\n\n template <typename T, typename RType, typename... ArgTypes>\n struct function_type_impl<RType(T::*)(ArgTypes...) const> {\n using type = RType(ArgTypes...);\n };\n}\n\ntemplate <typename T>\nstruct function_type\n : details::function_type_impl<typename std::remove_cv<typename std::remove_reference<T>::type>::type>\n{ };\n\n// ---\n\ntemplate <typename Args, typename Params>\nstruct apply_args;\n\ntemplate <typename HeadArgs, typename... Args, typename HeadParams, typename... Params>\nstruct apply_args<std::tuple<HeadArgs, Args...>, std::tuple<HeadParams, Params...>>\n : std::enable_if<\n std::is_constructible<HeadParams, HeadArgs>::value,\n apply_args<std::tuple<Args...>, std::tuple<Params...>>\n >::type\n{ };\n\ntemplate <typename... Params>\nstruct apply_args<std::tuple<>, std::tuple<Params...>> {\n using type = std::tuple<Params...>;\n};\n\n// ---\n\ntemplate <typename TupleType>\nstruct is_empty_tuple : std::false_type { };\n\ntemplate <>\nstruct is_empty_tuple<std::tuple<>> : std::true_type { };\n\n// ----\n\ntemplate <typename FType, typename GivenArgs, typename RestArgs>\nstruct currying;\n\ntemplate <typename FType, typename... GivenArgs, typename... RestArgs>\nstruct currying<FType, std::tuple<GivenArgs...>, std::tuple<RestArgs...>> {\n std::tuple<GivenArgs...> given_args;\n\n FType func;\n\n template <typename Func, typename... GivenArgsReal>\n constexpr\n currying(Func&& func, GivenArgsReal&&... args) :\n given_args(std::forward<GivenArgsReal>(args)...),\n func(std::move(func))\n { }\n\n template <typename... Args>\n constexpr\n auto operator() (Args&&... args) const& {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CanExecute = is_empty_tuple<RestArgsPrime>;\n\n return apply(CanExecute{}, std::make_index_sequence<sizeof...(GivenArgs)>{}, std::forward<Args>(args)...);\n }\n\n template <typename... Args>\n constexpr\n auto operator() (Args&&... args) && {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CanExecute = is_empty_tuple<RestArgsPrime>;\n\n return std::move(*this).apply(CanExecute{}, std::make_index_sequence<sizeof...(GivenArgs)>{}, std::forward<Args>(args)...);\n }\n\nprivate:\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::false_type, std::index_sequence<Indices...>, Args&&... args) const& {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CurryType = currying<FType, std::tuple<GivenArgs..., Args...>, RestArgsPrime>;\n\n return CurryType{ func, std::get<Indices>(given_args)..., std::forward<Args>(args)... };\n }\n\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::false_type, std::index_sequence<Indices...>, Args&&... args) && {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CurryType = currying<FType, std::tuple<GivenArgs..., Args...>, RestArgsPrime>;\n\n return CurryType{ std::move(func), std::get<Indices>(std::move(given_args))..., std::forward<Args>(args)... };\n }\n\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::true_type, std::index_sequence<Indices...>, Args&&... args) const& {\n return func(std::get<Indices>(given_args)..., std::forward<Args>(args)...);\n }\n\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::true_type, std::index_sequence<Indices...>, Args&&... args) && {\n return func(std::get<Indices>(std::move(given_args))..., std::forward<Args>(args)...);\n }\n};\n\n// ---\n\ntemplate <typename FType, size_t... Indices>\nconstexpr\nauto curry(FType&& func, std::index_sequence<Indices...>) {\n using RealFType = typename function_type<FType>::type;\n using FTypeTraits = function_traits<RealFType>;\n\n using CurryType = currying<FType, std::tuple<>, std::tuple<typename FTypeTraits::template arg_type<Indices>...>>;\n\n return CurryType{ std::move(func) };\n}\n\ntemplate <typename FType>\nconstexpr\nauto curry(FType&& func) {\n using RealFType = typename function_type<FType>::type;\n using FTypeArity = typename function_traits<RealFType>::arity;\n\n return curry(std::move(func), std::make_index_sequence<FTypeArity::value>{});\n}\n\n// ---\n\nint main() {\n auto add = curry([](int a, int b) { return a + b; });\n\n std::cout << add(5)(10) << std::endl;\n}\n" }, { "answer_id": 43131224, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 3, "selected": false, "text": "auto sum0 = [](){return 0;};\nstd::cout << partial_apply(sum0)() << std::endl;\n auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};\nstd::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10\n constexpr static_assert static_assert(partial_apply(sum0)() == 0);\n auto sum1 = [](int x){ return x;};\npartial_apply(sum1)(1)(1);\n operator() namespace detail{\ntemplate<class F>\nusing is_zero_callable = decltype(std::declval<F>()());\n\ntemplate<class F>\nconstexpr bool is_zero_callable_v = std::experimental::is_detected_v<is_zero_callable, F>;\n}\n\ntemplate<class F>\nstruct partial_apply_t\n{\n template<class... Args>\n constexpr auto operator()(Args... args)\n {\n static_assert(sizeof...(args) == 0 || !is_zero_callable, \"Attempting to apply too many arguments!\");\n auto bind_some = [=](auto... rest) -> decltype(myFun(args..., rest...))\n {\n return myFun(args..., rest...);\n };\n using bind_t = decltype(bind_some);\n\n return partial_apply_t<bind_t>{bind_some};\n }\n explicit constexpr partial_apply_t(F fun) : myFun(fun){}\n\n constexpr operator auto()\n {\n if constexpr (is_zero_callable)\n return myFun();\n else\n return *this; // a callable\n }\n static constexpr bool is_zero_callable = detail::is_zero_callable_v<F>;\n F myFun;\n};\n constexpr auto sum0 = [](){return 0;};\nauto sum1 = [](int x){ return x;};\nauto sum2 = [](int x, int y){ return x + y;};\nauto sum3 = [](int x, int y, int z){ return x + y + z; };\nauto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};\n\nstd::cout << partial_apply(sum0)() << std::endl; //0\nstatic_assert(partial_apply(sum0)() == 0, \"sum0 should return 0\");\nstd::cout << partial_apply(sum1)(1) << std::endl; // 1\nstd::cout << partial_apply(sum2)(1)(1) << std::endl; // 2\nstd::cout << partial_apply(sum3)(1)(1)(1) << std::endl; // 3\nstatic_assert(partial_apply(sum3)(1)(1)(1) == 3, \"sum3 should return 3\");\nstd::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10\n//partial_apply(sum1)(1)(1); // fails static assert\nauto partiallyApplied = partial_apply(sum3)(1)(1);\nstd::function<int(int)> finish_applying = partiallyApplied;\nstd::cout << std::boolalpha << (finish_applying(1) == 3) << std::endl; // true\n\nauto plus2 = partial_apply(sum3)(1)(1);\nstd::cout << std::boolalpha << (plus2(1) == 3) << std::endl; // true\nstd::cout << std::boolalpha << (plus2(3) == 5) << std::endl; // true\n" }, { "answer_id": 72160331, "author": "anton_rh", "author_id": 5447906, "author_profile": "https://Stackoverflow.com/users/5447906", "pm_score": 0, "selected": false, "text": "template <typename TFunc, typename TArg>\nclass CurryT\n{\nprivate:\n TFunc func;\n TArg arg ;\n\npublic:\n template <typename TFunc_, typename TArg_>\n CurryT(TFunc_ &&func, TArg_ &&arg)\n : func(std::forward<TFunc_>(func))\n , arg (std::forward<TArg_ >(arg ))\n {}\n\n template <typename... TArgs>\n auto operator()(TArgs &&...args) const\n -> decltype( func(arg, std::forward<TArgs>(args)...) )\n { return func(arg, std::forward<TArgs>(args)...); }\n};\n\ntemplate <typename TFunc, typename TArg>\nCurryT<std::decay_t<TFunc>, std::remove_cv_t<TArg>> Curry(TFunc &&func, TArg &&arg)\n { return {std::forward<TFunc>(func), std::forward<TArg>(arg)}; }\n void Abc(std::string a, int b, int c)\n{\n std::cerr << a << b << c << std::endl;\n}\n\nint main()\n{\n std::string str = \"Hey\";\n auto c1 = Curry(Abc, str);\n std::cerr << \"str: \" << str << std::endl;\n c1(1, 2);\n auto c2 = Curry(std::move(c1), 3);\n c2(4);\n auto c3 = Curry(c2, 5);\n c3();\n}\n str: \nHey12\nHey34\nHey35\n std::shared_ptr template <typename TFunc>\nclass SharedFunc\n{\npublic:\n struct Tag{}; // For avoiding shadowing copy/move constructors with the\n // templated constructor below which accepts any parameters.\n\n template <typename... TArgs>\n SharedFunc(Tag, TArgs &&...args)\n : p_func( std::make_shared<TFunc>(std::forward<TArgs>(args)...) )\n {}\n\n template <typename... TArgs>\n auto operator()(TArgs &&...args) const\n -> decltype( (*p_func)(std::forward<TArgs>(args)...) )\n { return (*p_func)(std::forward<TArgs>(args)...); }\n\nprivate:\n std::shared_ptr<TFunc> p_func;\n};\n\ntemplate <typename TFunc, typename TArg>\nSharedFunc<\n CurryT<std::decay_t<TFunc>, std::remove_cv_t<TArg>>\n>\nCurryShared(TFunc &&func, TArg &&arg)\n{\n return { {}, std::forward<TFunc>(func), std::forward<TArg>(arg) };\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
152,006
<p>I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.</p> <p>Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml?</p>
[ { "answer_id": 152009, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 8, "selected": true, "text": "header('Content-type: application/xml');\n header()" }, { "answer_id": 152010, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "Content-Type header('Content-Type: text/xml');\n" }, { "answer_id": 152011, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 2, "selected": false, "text": "Content-Type header('Content-Type: text/xml');\n" }, { "answer_id": 152304, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<?php\nheader('Content-Type: text/xml');\necho '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<root><foo a=\"b\">Tada</foo></root>';\n?>\n" }, { "answer_id": 45046861, "author": "Thomas", "author_id": 8212246, "author_profile": "https://Stackoverflow.com/users/8212246", "pm_score": 1, "selected": false, "text": "Start XML file, echo parent node\nheader(\"Content-type: text/xml\");\necho \"<?xml version='1.0' encoding='UTF-8'?>\";\necho \"<marker>\";\n while ($row = @mysqli_fetch_assoc($results)){\n // Add to XML document node\n echo '<marker ';\n echo 'id=\"' . $ind . '\" ';\n echo 'name=\"' . parseToXML($row['name']) . '\" ';\n echo 'address=\"' . parseToXML($row['address']) . '\" ';\n echo 'lat=\"' . $row['lat'] . '\" ';\n echo 'lng=\"' . $row['lng'] . '\" ';\n echo 'type=\"' . $row['type'] . '\" ';\n echo '/>';\n}\n\n// End XML file\necho \"</marker>\";\n" }, { "answer_id": 48734864, "author": "Usman Ahmed", "author_id": 2243776, "author_profile": "https://Stackoverflow.com/users/2243776", "pm_score": 2, "selected": false, "text": "header('Content-Type: application/xml; charset=utf-8');\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
152,016
<p>What is the most reliable way to find out CPU architecture when compiling C or C++ code? As far as I can tell, different compilers have their own set of non-standard preprocessor definitions (<code>_M_X86</code> in MSVS, <code>__i386__</code>, <code>__arm__</code> in GCC, etc).</p> <p>Is there a <em>standard</em> way to detect the architecture I'm building for? If not, is there a source for a comprehensive list of such definitions for various compilers, such as a header with all the boilerplate <code>#ifdef</code>s?</p>
[ { "answer_id": 152034, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "#if MSVC\n#ifdef _M_X86\n#define ARCH_X86\n#endif\n#endif\n\n#if GCC\n#ifdef __i386__\n#define ARCH_X86\n#endif\n#endif\n" }, { "answer_id": 37018251, "author": "Wei Shen", "author_id": 1657877, "author_profile": "https://Stackoverflow.com/users/1657877", "pm_score": 4, "selected": false, "text": "gcc -march=native -dM -E - </dev/null\n #define __SSE3__ 1 #define __AES__ 1" }, { "answer_id": 52867605, "author": "phuclv", "author_id": 995714, "author_profile": "https://Stackoverflow.com/users/995714", "pm_score": 3, "selected": false, "text": "Boost.Predef BOOST_ARCH_ BOOST_COMP_ BOOST_LANG_ BOOST_LIB_C_ BOOST_LIB_STD_ BOOST_OS_ BOOST_PLAT_ BOOST_ENDIAN_ BOOST_HW_ BOOST_HW_SIMD Boost.Predef #include <boost/predef.h>\n// or just include the necessary headers\n// #include <boost/predef/architecture.h>\n// #include <boost/predef/other.h>\n\n#if BOOST_ARCH_X86\n #if BOOST_ARCH_X86_64\n std::cout << \"x86-64\\n\";\n #elif BOOST_ARCH_X86_32\n std::cout << \"x86-32\\n\";\n #else\n std::cout << \"x86-\" << BOOST_ARCH_WORD_BITS << '\\n'; // Probably x86-16\n #endif\n#elif BOOST_ARCH_ARM\n #if BOOST_ARCH_ARM >= BOOST_VERSION_NUMBER(8, 0, 0)\n #if BOOST_ARCH_WORD_BITS == 64\n std::cout << \"ARMv8+ Aarch64\\n\";\n #elif BOOST_ARCH_WORD_BITS == 32\n std::cout << \"ARMv8+ Aarch32\\n\";\n #else\n std::cout << \"Unexpected ARMv8+ \" << BOOST_ARCH_WORD_BITS << \"bit\\n\";\n #endif\n #elif BOOST_ARCH_ARM >= BOOST_VERSION_NUMBER(7, 0, 0)\n std::cout << \"ARMv7 (ARM32)\\n\";\n #elif BOOST_ARCH_ARM >= BOOST_VERSION_NUMBER(6, 0, 0)\n std::cout << \"ARMv6 (ARM32)\\n\";\n #else\n std::cout << \"ARMv5 or older\\n\";\n #endif\n#elif BOOST_ARCH_MIPS\n #if BOOST_ARCH_WORD_BITS == 64\n std::cout << \"MIPS64\\n\";\n #else\n std::cout << \"MIPS32\\n\";\n #endif\n#elif BOOST_ARCH_PPC_64\n std::cout << \"PPC64\\n\";\n#elif BOOST_ARCH_PPC\n std::cout << \"PPC32\\n\";\n#else\n std::cout << \"Unknown \" << BOOST_ARCH_WORD_BITS << \"-bit arch\\n\";\n#endif\n" }, { "answer_id": 66249936, "author": "FreakAnon", "author_id": 14804593, "author_profile": "https://Stackoverflow.com/users/14804593", "pm_score": 4, "selected": false, "text": "extern \"C\" {\n const char *getBuild() { //Get current architecture, detectx nearly every architecture. Coded by Freak\n #if defined(__x86_64__) || defined(_M_X64)\n return \"x86_64\";\n #elif defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)\n return \"x86_32\";\n #elif defined(__ARM_ARCH_2__)\n return \"ARM2\";\n #elif defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__)\n return \"ARM3\";\n #elif defined(__ARM_ARCH_4T__) || defined(__TARGET_ARM_4T)\n return \"ARM4T\";\n #elif defined(__ARM_ARCH_5_) || defined(__ARM_ARCH_5E_)\n return \"ARM5\"\n #elif defined(__ARM_ARCH_6T2_) || defined(__ARM_ARCH_6T2_)\n return \"ARM6T2\";\n #elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__)\n return \"ARM6\";\n #elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)\n return \"ARM7\";\n #elif defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)\n return \"ARM7A\";\n #elif defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)\n return \"ARM7R\";\n #elif defined(__ARM_ARCH_7M__)\n return \"ARM7M\";\n #elif defined(__ARM_ARCH_7S__)\n return \"ARM7S\";\n #elif defined(__aarch64__) || defined(_M_ARM64)\n return \"ARM64\";\n #elif defined(mips) || defined(__mips__) || defined(__mips)\n return \"MIPS\";\n #elif defined(__sh__)\n return \"SUPERH\";\n #elif defined(__powerpc) || defined(__powerpc__) || defined(__powerpc64__) || defined(__POWERPC__) || defined(__ppc__) || defined(__PPC__) || defined(_ARCH_PPC)\n return \"POWERPC\";\n #elif defined(__PPC64__) || defined(__ppc64__) || defined(_ARCH_PPC64)\n return \"POWERPC64\";\n #elif defined(__sparc__) || defined(__sparc)\n return \"SPARC\";\n #elif defined(__m68k__)\n return \"M68K\";\n #else\n return \"UNKNOWN\";\n #endif\n }\n}\n" }, { "answer_id": 69856463, "author": "Timmmm", "author_id": 265521, "author_profile": "https://Stackoverflow.com/users/265521", "pm_score": 2, "selected": false, "text": "#define __amd64__ __amd64 __x86_64__ __x86_64 _M_X64 _M_AMD64" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23643/" ]
152,019
<p>.Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not? </p>
[ { "answer_id": 152026, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 6, "selected": false, "text": "#region tuples\n\n public class Tuple<T>\n {\n public Tuple(T first)\n {\n First = first;\n }\n\n public T First { get; set; }\n }\n\n public class Tuple<T, T2> : Tuple<T>\n {\n public Tuple(T first, T2 second)\n : base(first)\n {\n Second = second;\n }\n\n public T2 Second { get; set; }\n }\n\n public class Tuple<T, T2, T3> : Tuple<T, T2>\n {\n public Tuple(T first, T2 second, T3 third)\n : base(first, second)\n {\n Third = third;\n }\n\n public T3 Third { get; set; }\n }\n\n public class Tuple<T, T2, T3, T4> : Tuple<T, T2, T3>\n {\n public Tuple(T first, T2 second, T3 third, T4 fourth)\n : base(first, second, third)\n {\n Fourth = fourth;\n }\n\n public T4 Fourth { get; set; }\n }\n\n #endregion\n public static class Tuple\n{\n //Allows Tuple.New(1, \"2\") instead of new Tuple<int, string>(1, \"2\")\n public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2)\n {\n return new Tuple<T1, T2>(t1, t2);\n }\n //etc...\n}\n" }, { "answer_id": 152054, "author": "ChaosSpeeder", "author_id": 205962, "author_profile": "https://Stackoverflow.com/users/205962", "pm_score": 4, "selected": false, "text": "var p1 = new {a = \"A\", b = 3};\n" }, { "answer_id": 152785, "author": "Chris Ballard", "author_id": 18782, "author_profile": "https://Stackoverflow.com/users/18782", "pm_score": 4, "selected": false, "text": "let (a, b) = someTupleFunc\n Tuple<int,int> x = someTupleFunc();\nint a = x.get_Item1();\nint b = x.get_Item2();\n" }, { "answer_id": 417454, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "Tuple<Int32,String> Tuple<Int32,String,Boolean> Tuple<Int32, String> t1 = new Tuple<Int32, String>(10, \"a\");\nTuple<Int32, String, Boolean> t2 = new Tuple<Int32, String, Boolean>(10, \"a\", true);\nif (t1.Equals(t2))\n Console.Out.WriteLine(t1 + \" == \" + t2);\nelse\n Console.Out.WriteLine(t1 + \" != \" + t2);\n 10, a != 10, a, True\n" }, { "answer_id": 1047961, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 7, "selected": true, "text": "class Program {\n static void Main(string[] args) {\n Tuple<string, int> t = new Tuple<string, int>(\"Hello\", 4);\n PrintStringAndInt(t.Item1, t.Item2);\n }\n static void PrintStringAndInt(string s, int i) {\n Console.WriteLine(\"{0} {1}\", s, i);\n }\n}\n var t = new Tuple<string, int>(\"Hello\", 4);\n var t = Tuple.Create(\"Hello\", 4);\n" }, { "answer_id": 42646341, "author": "Tim Pohlmann", "author_id": 4961688, "author_profile": "https://Stackoverflow.com/users/4961688", "pm_score": 3, "selected": false, "text": "var unnamedTuple = (\"Peter\", 29);\nvar namedTuple = (Name: \"Peter\", Age: 29);\n(string Name, double Age) typedTuple = (\"Peter\", 29);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
152,024
<p>I have a submission table that is very simple: userId, submissionGuid</p> <p>I want to select the username (simple inner join to get it) of all the users who have more than 10 submissions in the table. </p> <p>I would do this with embedded queries and a group by to count submissions... but is there a better way of doing it (without embedded queries)?</p> <p>Thanks!</p>
[ { "answer_id": 152030, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 1, "selected": false, "text": "select userId, count(*)\nfrom submissions\nhaving count(*) > 10\ngroup by userId\n" }, { "answer_id": 152037, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": true, "text": "select userId\nfrom submission \ngroup by userId\nhaving count(submissionGuid) > 10\n" }, { "answer_id": 152044, "author": "EggyBach", "author_id": 15475, "author_profile": "https://Stackoverflow.com/users/15475", "pm_score": 1, "selected": false, "text": "SELECT \n username \nFROM \n usertable \n JOIN submissions \n ON usertable.userid = submissions.userid \nGROUP BY \n usertable.username \nHAVING \n Count(*) > 1\n" }, { "answer_id": 152057, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "SELECT s.userId, u.userName\nFROM submission s INNER JOIN users u on u.userId = s.userId \nGROUP BY s.userId, u.username\nHAVING COUNT(submissionGuid) > 10\n SELECT u.userId, u.userName\nFROM users u INNER JOIN (\n SELECT userId, COUNT(submissionGuid) AS cnt\n FROM submission\n GROUP BY userId ) sc ON sc.userId = u.userId\nWHERE sc.cnt > 10\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
152,028
<p>I want to be able to compare an image taken from a webcam to an image stored on my computer.</p> <p>The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with.</p> <p>I have tried a demonstration project for <a href="http://www.codeproject.com/KB/cs/BackPropagationNeuralNet.aspx" rel="noreferrer">Image Recognition from CodeProject</a>, and it only works with small images / doesn't work at all when I compare an exact same image 120x90 pixels (this is not classified as OK :P ).</p> <p>Has there been any success with image recognition before?</p> <p>If so, would you be able to provide a link to a library I could use in either C# or VB.NET?</p>
[ { "answer_id": 152059, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 7, "selected": true, "text": "// The class also can be used to get similarity level between two image of the same size, which can be useful to get information about how different/similar are images:\n// Create template matching algorithm's instance\n\n// Use zero similarity to make sure algorithm will provide anything\nExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);\n\n// Compare two images\nTemplateMatch[] matchings = tm.ProcessImage( image1, image2 );\n\n// Check similarity level\nif (matchings[0].Similarity > 0.95)\n{\n // Do something with quite similar images\n}\n" }, { "answer_id": 12421754, "author": "Hydarnes", "author_id": 1671007, "author_profile": "https://Stackoverflow.com/users/1671007", "pm_score": 2, "selected": false, "text": " use eyeopen.imaging.processing\n ComparableImage cc;\n\nComparableImage pc;\n\nint sim;\n\nvoid compare(object sender, EventArgs e){\n\n pc = new ComparableImage(new FileInfo(files));\n\n cc = new ComparableImage(new FileInfo(file));\n\n pc.CalculateSimilarity(cc);\n\n sim = pc.CalculateSimilarity(cc);\n\n int sim2 = sim*100\n\n Messagebox.show(sim2 + \"% similar\");\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ]
152,071
<p>I'm trying to display a boolean field in Report Designer in Visual Studio 2008. When I tried to run it, an error occurred:</p> <pre><code> "An error has occurred during report processing. String was not recognized as a valid Boolean." </code></pre> <p>I tried to convert it using CBool() but it didn't work. </p>
[ { "answer_id": 169691, "author": "roman m", "author_id": 3661, "author_profile": "https://Stackoverflow.com/users/3661", "pm_score": 2, "selected": false, "text": "=iif(Fields!YourBool.Value, \"True\", \"False\") \n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20877/" ]
152,077
<p>I agree, that programming against interfaces is a good practice. In most cases in Java "interface" in this sense means the language construct interface, so that you write an interface and an implementation class and that you use the interface instead of the implementation class most of the time.</p> <p>I wonder if this is a good practice for writing domain models as well. So, for example if you've got a domain class Customer and each customer may have a list of Orders, would you <em>generally</em> also write interfaces ICustomer and IOrder. And also would Customer have a list of IOrders instead of Orders? Or would you use interfaces in the domain model, only if it is really driven by the domain, e.g. you've got at least two different types of Orders? In other words, would you use interfaces because of only technical needs in the domain model, or only when it is really appropriate with respect to the actual domain?</p>
[ { "answer_id": 1056141, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 2, "selected": false, "text": "ArrayList List" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
152,084
<p>I'm interested in actual examples of using fixed point combinators (such as the <a href="https://stackoverflow.com/questions/93526/what-is-a-y-combinator">y-combinator</a> in C++. Have you ever used a fixed point combinator with <a href="http://p-stade.sourceforge.net/boost/libs/egg/doc/html/boost_egg/function_adaptors.html#boost_egg.function_adaptors.fix" rel="noreferrer">egg</a> or <a href="http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html" rel="noreferrer">bind</a> in real live code?</p> <p>I found this example in egg a little dense:</p> <pre><code>void egg_example() { using bll::_1; using bll::_2; int r = fix2( bll::ret&lt;int&gt;( // \(f,a) -&gt; a == 0 ? 1 : a * f(a-1) bll::if_then_else_return( _2 == 0, 1, _2 * lazy(_1)(_2 - 1) ) ) ) (5); BOOST_CHECK(r == 5*4*3*2*1); } </code></pre> <p>Can you explain how this all works?</p> <p>Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?</p>
[ { "answer_id": 154267, "author": "Ted", "author_id": 8965, "author_profile": "https://Stackoverflow.com/users/8965", "pm_score": 6, "selected": true, "text": "boost::bind #include <boost/function.hpp>\n#include <boost/bind.hpp>\n#include <iostream>\n\n// Y-combinator compatible factorial\nint fact(boost::function<int(int)> f,int v)\n{\n if(v == 0)\n return 1;\n else\n return v * f(v -1);\n}\n\n// Y-combinator for the int type\nboost::function<int(int)>\n y(boost::function<int(boost::function<int(int)>,int)> f)\n{\n return boost::bind(f,boost::bind(&y,f),_1);\n}\n\n\nint main(int argc,char** argv)\n{\n boost::function<int(int)> factorial = y(fact);\n std::cout << factorial(5) << std::endl;\n return 0;\n}\n" }, { "answer_id": 154514, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "if(second arg == 0)\n{\n return 1;\n}\nelse\n{\n return second arg * first arg(second arg - 1);\n}\n" }, { "answer_id": 11968754, "author": "matthewtff", "author_id": 1600499, "author_profile": "https://Stackoverflow.com/users/1600499", "pm_score": 3, "selected": false, "text": "#include <functional>\n#include <iostream>\n\ntemplate <typename Lamba, typename Type>\nauto y (std::function<Type(Lamba, Type)> f) -> std::function<Type(Type)>\n{\n return std::bind(f, std::bind(&y<Lamba, Type>, f), std::placeholders::_1);\n}\n\nint main(int argc,char** argv)\n{\n std::cout << y < std::function<int(int)>, int> ([](std::function<int(int)> f, int x) {\n return x == 0 ? 1 : x * f(x - 1);\n }) (5) << std::endl;\n return 0;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
152,099
<p>I have an ASP.NET page with a gridview control on it with a CommandButton column with delete and select commands active.</p> <p>Pressing the enter key causes the first command button in the gridview to fire, which deletes a row. I don't want this to happen. Can I change the gridview control in a way that it does not react anymore to pressing the enter key?</p> <p>There is a textbox and button on the screen as well. They don't need to be responsive to hitting enter, but you must be able to fill in the textbox. Currently we popup a confirmation dialog to prevent accidental deletes, but we need something better than this.</p> <p>This is the markup for the gridview, as you can see it's inside an asp.net updatepanel (i forgot to mention that, sorry): (I left out most columns and the formatting)</p> <pre><code>&lt;asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Conditional"&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="btnFilter" /&gt; &lt;asp:AsyncPostBackTrigger ControlID="btnEdit" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;ContentTemplate&gt; &lt;div id="CodeGrid" class="Grid"&gt; &lt;asp:GridView ID="dgCode" runat="server"&gt; &lt;Columns&gt; &lt;asp:CommandField SelectImageUrl="~/Images/Select.GIF" ShowSelectButton="True" ButtonType="Image" CancelText="" EditText="" InsertText="" NewText="" UpdateText="" DeleteImageUrl="~/Images/Delete.GIF" ShowDeleteButton="True" /&gt; &lt;asp:BoundField DataField="Id" HeaderText="ID" Visible="False" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;/div&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre>
[ { "answer_id": 233011, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": false, "text": "myGridView.Attributes.Add(\"onkeydown\", \"if(event.keyCode==13)return false;\");\n" }, { "answer_id": 234812, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 0, "selected": false, "text": "//jQuery document ready function – fires when document structure loads\n$(document).ready(function() {\n\n //Find all input controls of type text and bind the given\n //function to them\n $(\":text\").keydown(function(e) {\n if (e.keyCode == 13) {\n return false;\n }\n });\n\n});\n" }, { "answer_id": 2721527, "author": "Heather", "author_id": 326889, "author_profile": "https://Stackoverflow.com/users/326889", "pm_score": 0, "selected": false, "text": "if (window.event.keyCode == 13) { \n event.returnValue=false; \n event.cancel = true;\n}\n" }, { "answer_id": 7602331, "author": "Derrick", "author_id": 971829, "author_profile": "https://Stackoverflow.com/users/971829", "pm_score": 1, "selected": false, "text": "Private Sub gvSerials_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvSerials.PreRender\n If gvSerials.EditIndex < 0 'READ ONLY MODE\n 'Enables the form submit during Read mode on my 'search' submit button\n Me.bnSearch.UseSubmitBehavior = True\n Else 'EDIT MODE\n 'disables the form submit during edit mode, this allows the APPLY/Update button to be activated after Enter Key is pressed (which really is creating a form submit)\n Me.bnSearch.UseSubmitBehavior = False\n End If\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23697/" ]
152,101
<p>I want to learn MVC "architecture pattern" but I don't want to jump into a framework like Rails or Django just yet. I want to understand the concept first and write some simple code in my currently familiar environment, which happens to be PHP/HTML/CSS/MySQL. I don't necessarily need a tutorial that is based on PHP, as I do understand a lot of different languages. And I don't want to have to install any frameworks or APIs or libraries. I just want to learn how to think in MVC and apply it to my projects. Any suggestions?</p>
[ { "answer_id": 599262, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 4, "selected": false, "text": "class Model:\n def get_post(self, id):\n # Would query database, perhaps\n return {\"title\": \"A test\", \"body\": \"An example..\"}\n\nclass Controller:\n def __init__(self):\n self.model = Model()\n self.view = View()\n\n def main(self):\n post = self.model.get_post(1)\n self.view.display(post)\n\nclass View:\n def display(self, item):\n print \"<h1>%(title)s</h1>\\n%(body)s\" % item\n\nc = Controller()\nc.main()\n" }, { "answer_id": 4913874, "author": "Michael", "author_id": 584811, "author_profile": "https://Stackoverflow.com/users/584811", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python\nclass Model:\n def get_post(self):\n return {\"title\":\"A test\",\"body\":\"An example..\"}\n\nclass View:\n def display(self,items):\n print 'Title:',items['title'],'\\n'+'Body:',items['body']\n\nclass Controller:\n def __init__(self):\n self.model=Model()\n self.view=View()\n\n def main(self):\n post=self.model.get_post()\n self.view.display(post)\n\nmvc=Controller()\nmvc.main()\n #!/usr/bin/python3\nclass Control:\n def find(self,user):\n return self._look(user)\n\n def _look(self,user):\n if user in self.users:\n return self.users[user]\n else:\n return 'The data class ({}) has no {}'.format(self.userName(),user)\n\n def userName(self):\n return self.__class__.__name__.lower()\n\nclass Model(Control):\n users=dict(one='Bob',two='Michael',three='Dave')\n\nclass View():\n def user(self,users):\n print(users.find('two'))\n\ndef main():\n users=Model()\n find=View()\n print('--> The user two\\'s \"real name\" is:\\n')\n find.user(users)\n\nif __name__==\"__main__\":\n main()\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23701/" ]
152,104
<p>I work on a Webproject using <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a> and CakePHP. I use <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a> as an inplace edit plugin. For textareas I extend it using the <a href="http://www.appelsiini.net/2008/4/autogrow-textarea-for-jeditable" rel="nofollow noreferrer">autogrow plugin</a>.</p> <p>Well, I have two problems with this:</p> <ul> <li>First, autogrow does only work on Firefox, not on IE, Safari, Opera and Chrome.</li> <li>Second, I need a callback event for jeditable, when its finished showing the edit-component, to recalculate the <a href="http://kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html" rel="nofollow noreferrer">scrollbar</a></li> </ul> <p>Im not so familiar with Javascript, so i can't extend/correct this two libraries by my own. Has anyone used another js-library for inplace edit with auto growing textareas (no complete editors like TinyMCE, I need a solution for plain text)?</p> <p>I also found <a href="http://plugins.jquery.com/project/Growfield" rel="nofollow noreferrer">Growfield</a>, it would work for other browsers, but there's no jeditable integration...</p> <p><em>(sorry for my english)</em></p>
[ { "answer_id": 154377, "author": "Alexander Pendleton", "author_id": 21201, "author_profile": "https://Stackoverflow.com/users/21201", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\">\n/* This is the growfield integration into jeditable\n You can use almost any field plugin you'd like if you create an input type for it.\n It just needs the \"element\" function (to create the editable field) and the \"plugin\"\n function which applies the effect to the field. This is very close to the code in the\n jquery.jeditable.autogrow.js input type that comes with jeditable.\n */\n$.editable.addInputType('growfield', {\n element : function(settings, original) {\n var textarea = $('<textarea>');\n if (settings.rows) {\n textarea.attr('rows', settings.rows);\n } else {\n textarea.height(settings.height);\n }\n if (settings.cols) {\n textarea.attr('cols', settings.cols);\n } else {\n textarea.width(settings.width);\n }\n // will execute when textarea is rendered\n textarea.ready(function() {\n // implement your scroll pane code here\n });\n $(this).append(textarea);\n return(textarea);\n },\n plugin : function(settings, original) {\n // applies the growfield effect to the in-place edit field\n $('textarea', this).growfield(settings.growfield);\n }\n});\n\n/* jeditable initialization */\n$(function() {\n $('.editable_textarea').editable('postto.html', {\n type: \"growfield\", // tells jeditable to use your growfield input type from above\n submit: 'OK', // this and below are optional\n tooltip: \"Click to edit...\",\n onblur: \"ignore\",\n growfield: { } // use this to pass options to the growfield that gets created\n });\n})\n" }, { "answer_id": 166955, "author": "Roman Ganz", "author_id": 17981, "author_profile": "https://Stackoverflow.com/users/17981", "pm_score": 1, "selected": false, "text": "$('.edit_memo').editable('/cakephp/efforts/updateValue', {\n id : 'data[Effort][id]',\n name : 'data[Effort][value]',\n type : 'growfield',\n cancel : 'Abort',\n submit : 'Save',\n tooltip : 'click to edit',\n indicator : \"<span class='save'>saving...</span>\",\n onblur : 'ignore',\n placeholder : '<span class=\"hint\">&lt;click to edit&gt;</span>',\n loadurl : '/cakephp/efforts/getValue',\n loadtype : 'POST',\n loadtext : 'loading...',\n width : 447,\n onreadytoedit : function(value){\n $(this).removeClass('edit_memo_hover'); //remove css hover effect\n },\n onfinishededit : function(value){\n $(this).addClass('edit_memo_hover'); //add css hover effect\n }\n});\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17981/" ]
152,115
<p>How can I set points on a 24h period spreaded by the Gaussian distributions? For example to have the peak at 10 o'clock?</p>
[ { "answer_id": 153016, "author": "Chris Johnson", "author_id": 23732, "author_profile": "https://Stackoverflow.com/users/23732", "pm_score": 4, "selected": true, "text": "$peak=10; // Peak at 10-o-clock\n$stdev=2; // Standard deviation of two hours\n$hoursOnClock=24; // 24-hour clock\n\ndo // Generate gaussian variable using Box-Muller\n{\n $u=2.0*mt_rand()/mt_getrandmax()-1.0;\n $v=2.0*mt_rand()/mt_getrandmax()-1.0;\n $s = $u*$u+$v*$v;\n} while ($s > 1);\n$gauss=$u*sqrt(-2.0*log($s)/$s);\n\n$gauss = $gauss*$stdev + $peak; // Transform to correct peak and standard deviation\n\nwhile ($gauss < 0) $gauss+=$hoursOnClock; // Wrap around hours to keep the random time \n$result = fmod($gauss,$hoursOnClock); // on the clock\n\necho $result;\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22470/" ]
152,127
<p>I am trying to use Lucene Java 2.3.2 to implement search on a catalog of products. Apart from the regular fields for a product, there is field called 'Category'. A product can fall in multiple categories. Currently, I use FilteredQuery to search for the same search term with every Category to get the number of results per category.</p> <p>This results in 20-30 internal search calls per query to display the results. This is slowing down the search considerably. Is there a faster way of achieving the same result using Lucene?</p>
[ { "answer_id": 152764, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 2, "selected": false, "text": "public static void countDocumentsInCategories(IndexReader reader) throws IOException {\n TermEnum terms = null;\n TermDocs td = null;\n\n\n try {\n terms = reader.terms(new Term(\"Category\", \"\"));\n td = reader.termDocs();\n do {\n Term currentTerm = terms.term();\n\n if (!currentTerm.field().equals(\"Category\")) {\n break;\n }\n\n int numDocs = 0;\n td.seek(terms);\n while (td.next()) {\n numDocs++;\n }\n\n System.out.println(currentTerm.field() + \" : \" + currentTerm.text() + \" --> \" + numDocs);\n } while (terms.next());\n } finally {\n if (td != null) td.close();\n if (terms != null) terms.close();\n }\n}\n public static void main(String[] args) throws Exception {\n RAMDirectory store = new RAMDirectory();\n\n IndexWriter w = new IndexWriter(store, new StandardAnalyzer());\n addDocument(w, 1, \"Apple\", \"fruit\", \"computer\");\n addDocument(w, 2, \"Orange\", \"fruit\", \"colour\");\n addDocument(w, 3, \"Dell\", \"computer\");\n addDocument(w, 4, \"Cumquat\", \"fruit\");\n w.close();\n\n IndexReader r = IndexReader.open(store);\n countDocumentsInCategories(r);\n r.close();\n}\n\nprivate static void addDocument(IndexWriter w, int id, String name, String... categories) throws IOException {\n Document d = new Document();\n d.add(new Field(\"ID\", String.valueOf(id), Field.Store.YES, Field.Index.UN_TOKENIZED));\n d.add(new Field(\"Name\", name, Field.Store.NO, Field.Index.UN_TOKENIZED));\n\n for (String category : categories) {\n d.add(new Field(\"Category\", category, Field.Store.NO, Field.Index.UN_TOKENIZED));\n }\n\n w.addDocument(d);\n}\n" }, { "answer_id": 158945, "author": "Rowan", "author_id": 22424, "author_profile": "https://Stackoverflow.com/users/22424", "pm_score": 3, "selected": false, "text": "int numDocs = 0;\ntd.seek(terms);\nwhile (td.next()) {\n numDocs++;\n}\n int numDocs = terms.docFreq()\n" }, { "answer_id": 392107, "author": "Rowan", "author_id": 22424, "author_profile": "https://Stackoverflow.com/users/22424", "pm_score": 0, "selected": false, "text": "originalQuery AND (category1 OR category2 or ...) Map<String,Long>" }, { "answer_id": 482639, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 3, "selected": false, "text": "BitSet public BitSet[] getBitSets(IndexSearcher indexSearcher, \n Category[] categories) {\n BitSet[] bitSets = new BitSet[categories.length];\n for(int i=0; i<categories.length; i++)\n {\n Query query = categories[i].getQuery();\n final BitSet bitset = new BitSet()\n indexSearcher.search(query, new HitCollector() {\n public void collect(int doc, float score) {\n bitSet.set(doc);\n }\n });\n bitSets[i] = bitSet;\n }\n return bitSets;\n}\n public int[] getCategroryCount(IndexSearcher indexSearcher, \n Query query, \n final BitSet[] bitSets) {\n final int[] count = new int[bitSets.length];\n indexSearcher.search(query, new HitCollector() {\n public void collect(int doc, float score) {\n for(int i=0; i<bitSets.length; i++) {\n if(bitSets[i].get(doc)) count[i]++;\n }\n }\n });\n return count;\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
152,137
<p>I don't need a Link but rather only the href= part of the ActionLink.</p> <p>But if I call Html.ActionLink(...) I get a back. Is there a way to just return the URL of the Action while not getting the ?</p>
[ { "answer_id": 152165, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 2, "selected": false, "text": "<% =Html.BuildUrlFromExpression<YourController>(c => c.YourAction(parameter)) %>\n" }, { "answer_id": 152898, "author": "Dave Weaver", "author_id": 11991, "author_profile": "https://Stackoverflow.com/users/11991", "pm_score": 4, "selected": true, "text": "<%=Url.Action(actionName)%>\n<%=Url.Action(actionName, htmlValues)%>\n<%=Url.Action(actionName, controllerName, htmlValues)%>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
152,138
<p>I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :</p> <pre><code>public interface Translator { public void loadTranslations(); public String getTranslation(String key); } </code></pre> <p>loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.</p> <p>My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.</p> <p>A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.</p> <p>Thanks for your help !</p>
[ { "answer_id": 152201, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "if (instance == null) {\n synchronized {\n if (instance == null) {\n instance = new SomeClass();\n }\n }\n}\n if (translationsNeedLoading()) {\n synchronized {\n if (translationsNeedLoading()) {\n loadTranslations();\n }\n }\n}\n" }, { "answer_id": 152593, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 3, "selected": true, "text": "/**\n * @author McDowell\n */\npublic abstract class NonconcurrentTask implements Runnable {\n\n private boolean token = true;\n\n private synchronized boolean acquire() {\n boolean ret = token;\n token = false;\n return ret;\n }\n\n private synchronized void release() {\n token = true;\n }\n\n public final void run() {\n if (acquire()) {\n try {\n doTask();\n } finally {\n release();\n }\n }\n }\n\n protected abstract void doTask();\n\n}\n public class Test {\n\n public static void main(String[] args) {\n final NonconcurrentTask shared = new NonconcurrentTask() {\n private boolean working = false;\n\n protected void doTask() {\n System.out.println(\"Working: \"\n + Thread.currentThread().getName());\n if (working) {\n throw new IllegalStateException();\n }\n working = true;\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (!working) {\n throw new IllegalStateException();\n }\n working = false;\n }\n };\n\n Runnable taskWrapper = new Runnable() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n shared.run();\n }\n }\n };\n for (int i = 0; i < 100; i++) {\n new Thread(taskWrapper).start();\n }\n }\n\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23704/" ]
152,160
<p>Has anyone used the <a href="http://www.cs.tufts.edu/~nr/noweb/" rel="noreferrer">noweb</a> literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?</p>
[ { "answer_id": 775062, "author": "Jason Catena", "author_id": 27685, "author_profile": "https://Stackoverflow.com/users/27685", "pm_score": 3, "selected": false, "text": "<</path/to/file.java>>=\n reallyImportantVariable += 1;\n@ %def reallyImportantVariable\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
152,187
<p>What type of authentication would you suggest for the service that is:</p> <ul> <li>implemented as WCF and exposed via varios enpoints (including XML-RPC)</li> <li>has to be consumed easily by various cross-platform clients</li> </ul> <p>Why?</p> <p>Options that I'm aware of are:</p> <ul> <li>Forms-based authentication for IIS-hosted WCF (easy to implement, but has horrible cross-platform support, plus it is not REST)</li> <li>Sending plain-text username/pwd with every call (easy to use on any platform, but totally unsecure)</li> <li>Using ticket-based authentication, when username&amp;pwd are used to create a ticket that is valid for some time and is passed with every request (can be consumed by any client easily, but the API model is bound to this type of security)</li> </ul> <p>Thanks for your time!</p>
[ { "answer_id": 775062, "author": "Jason Catena", "author_id": 27685, "author_profile": "https://Stackoverflow.com/users/27685", "pm_score": 3, "selected": false, "text": "<</path/to/file.java>>=\n reallyImportantVariable += 1;\n@ %def reallyImportantVariable\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47366/" ]
152,188
<p>I have read in some of the ClickOnce posts that ClickOnce does not allow you to create a desktop icon for you application. Is there any way around this?</p>
[ { "answer_id": 152194, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": ".application" }, { "answer_id": 152208, "author": "Timo", "author_id": 15415, "author_profile": "https://Stackoverflow.com/users/15415", "pm_score": 5, "selected": true, "text": "private void CreateDesktopIcon()\n{\n ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;\n\n if (ad.IsFirstRun)\n {\n Assembly assembly = Assembly.GetEntryAssembly();\n string company = string.Empty;\n string description = string.Empty;\n\n if (Attribute.IsDefined(assembly, typeof(AssemblyCompanyAttribute)))\n {\n AssemblyCompanyAttribute ascompany =\n (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(\n assembly, typeof(AssemblyCompanyAttribute));\n\n company = ascompany.Company;\n }\n if (Attribute.IsDefined(assembly, typeof(AssemblyDescriptionAttribute)))\n {\n AssemblyDescriptionAttribute asdescription =\n (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(\n assembly, typeof(AssemblyDescriptionAttribute));\n\n description = asdescription.Description;\n }\n if (!string.IsNullOrEmpty(company))\n {\n string desktopPath = string.Empty;\n desktopPath = string.Concat(\n Environment.GetFolderPath(Environment.SpecialFolder.Desktop),\n \"\\\\\",\n description,\n \".appref-ms\");\n\n string shortcutName = string.Empty;\n shortcutName = string.Concat(\n Environment.GetFolderPath(Environment.SpecialFolder.Programs),\n \"\\\\\",\n company,\n \"\\\\\",\n description,\n \".appref-ms\");\n\n System.IO.File.Copy(shortcutName, desktopPath, true);\n }\n }\n }\n}\n" }, { "answer_id": 65900724, "author": "Krzysztof Gapski", "author_id": 1837177, "author_profile": "https://Stackoverflow.com/users/1837177", "pm_score": 0, "selected": false, "text": "@ECHO OFF\nPowerShell -ExecutionPolicy Unrestricted .\\script.ps1 >> \"%TEMP%\\StartupLog.txt\" 2>&1\nEXIT /B %errorlevel%\n $app = \"http://your.site/YourApp/YourApp.application\";\n[Diagnostics.Process]::Start(\"rundll32.exe\", \"dfshim.dll,ShOpenVerbApplication \" + $app);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18826/" ]
152,190
<p>I'm using StringBuffer in Java to concat strings together, like so:</p> <pre><code>StringBuffer str = new StringBuffer(); str.append("string value"); </code></pre> <p>I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding".</p> <p>Let me explain; every time I append something to the string, I want to add a space in the end, like so:</p> <pre><code>String foo = "string value"; str.append(foo + " "); </code></pre> <p>and I have several calls to append.. and every time, I want to add a space. Is there a way to set the object so that it will add a space automatically after each append?</p> <p>EDIT --</p> <pre><code>String input StringBuffer query = new StringBuffer(); Scanner scanner = new Scanner(System.in); scanner.UseDelimiter("\n"); do { System.out.println("sql&gt; "); input = scanner.next(); if (!empty(input)) query.append(input); if (query.toString().trim().endsWith(";")) { //run query } } while (!input.equalsIgnoreCase("exit"); </code></pre> <p>I'll use StringBuilder though as grom suggested, but that's how the code looks right now</p>
[ { "answer_id": 152210, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "StringBuffer appendWithTrailingSpace() CustomStringBuffer str = new CustomStringBuffer();\nstr.appendWithTrailingSpace(\"string value\");\n" }, { "answer_id": 152270, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "str.append(\"string value\").append(\" \");\n" }, { "answer_id": 152677, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 4, "selected": true, "text": "public String myMethod() {\n StringBuilder sb = new StringBuilder();\n addToBuffer(sb, \"Hello\").addToBuffer(\"there,\");\n addToBuffer(sb, \"it\").addToBuffer(sb, \"works\");\n}\n\nprivate StringBuilder addToBuffer(StringBuilder sb, String what) {\n return sb.append(what).append(' '); // char is even faster here! ;)\n}\n public String myMethod() {\n SBBuilder builder = new SBBuilder()\n .add(\"Hello\").add(\"there\")\n .add(\"it\", \"works\", \"just\", \"fine!\");\n\n for (int i = 0; i < 10; i++) {\n builder.add(\"adding\").add(String.valueOf(i));\n }\n\n System.out.println(builder.build());\n}\n\npublic static class SBBuilder {\n private StringBuilder sb = new StringBuilder();\n\n public SBBuilder add(String... parts) {\n for (String p : parts) {\n sb.append(p).append(' '); // char is even faster here! ;)\n }\n return this;\n }\n\n public String build() {\n return sb.toString();\n }\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6618/" ]
152,205
<p>I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc.</p> <p>I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles).</p> <p>Are there any 'best practices' about removing redundant public code?</p> <p>/JaanusSiim </p>
[ { "answer_id": 152235, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "/**\n * @deprecated\n * This method will be removed after Halloween!\n * @see #newLocationForFunctionality\n */\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706/" ]
152,216
<p>Boost range library (<a href="http://www.boost.org/doc/libs/1_35_0/libs/range/index.html" rel="noreferrer">http://www.boost.org/doc/libs/1_35_0/libs/range/index.html</a>) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz:</p> <p>given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to define r as a range using r1 and r2?</p>
[ { "answer_id": 3308176, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 4, "selected": true, "text": "#include \"boost/range/join.hpp\"\n#include \"boost/foreach.hpp\"\n#include <iostream>\n\nint main() {\n int a[] = {1, 2, 3, 4};\n int b[] = {7, 2, 3, 4};\n\n boost::iterator_range<int*> ai(&a[0], &a[4]);\n boost::iterator_range<int*> bi(&b[0], &b[4]);\n boost::iterator_range<\n boost::range_detail::\n join_iterator<int*, int*, int, int&, \n boost::random_access_traversal_tag> > ci = boost::join(ai, bi); \n\n BOOST_FOREACH(int& i, ci) {\n std::cout << i; //prints 12347234\n }\n}\n auto" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19501/" ]
152,218
<p>Here's the problem:</p> <pre><code>split=re.compile('\\W*') </code></pre> <p>This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like <code>k&amp;amp;auml;ytt&amp;amp;auml;j&amp;aml;auml;</code>.</p> <p>What should I add to the regex to include the <code>&amp;</code> and <code>;</code> characters?</p>
[ { "answer_id": 152225, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 4, "selected": true, "text": "[^ \\t\\n]*\n [a-zA-Z0-9&;]*\n (\\w+|&\\w+;)*\n" }, { "answer_id": 152245, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 2, "selected": false, "text": "split=re.compile('[\\w&;]+')\n \\w \\W * + *" }, { "answer_id": 152249, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "(\\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+\n _ & # x" }, { "answer_id": 152305, "author": "kari.patila", "author_id": 21716, "author_profile": "https://Stackoverflow.com/users/21716", "pm_score": -1, "selected": false, "text": "split=re.compile('(\\\\\\W+&\\\\\\W+;)*')\n re.compile" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ]
152,243
<p>I have a database scenario (I'm using Oracle) in which several processes make inserts into a table and a single process selects from it. The table is basically used as intermediate storage, to which multiple processes (in the following called the Writers) write log events, and from which a single process (in the following referred to as the Reader) reads the events for further processing. The Reader must read all events inserted into the table.</p> <p>Currently, this is done by each inserted record being assigned an id from an ascending sequence. The reader periodically selects a block of entries from the table where the id is larger than the largest id of the previously read block. E.g. something like:</p> <pre><code>SELECT * FROM TRANSACTION_LOG WHERE id &gt; ( SELECT last_id FROM READER_STATUS ); </code></pre> <p>The problem with this approach is that since writers operate concurrently, rows are not always inserted in order according to their assigned id, even though these are assigned in sequentially ascending order. That is, a row with id=100 is sometimes written after a record with id=110, because the process of writing the row with id=110 started after the processes writing the record id=100, but committed first. This can result in the Reader missing the row with id=100 if it has already read row with id=110.</p> <p>Forcing the Writers to an exclusive lock on the table would solve the problem as this would force them to insert sequentially and also for the Reader to wait for any outstanding commits. This, however, would probably not be very fast.</p> <p>It is my thinking, that it would suffice for the Reader to wait for any outstanding Writer commits before reading. That is, Writers may continue to operate concurrently as longs as the Reader does read until all writers have finished.</p> <p>My question is this:<br> How can I instruct my reader process to wait for any outstanding commits of my writer processes? Any alternative suggestions to the above problem are also welcome. </p>
[ { "answer_id": 152375, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "SELECT *\nFROM TRANSACTION_LOG\nWHERE id > (SELECT last_id\n FROM READER_STATUS)\nOR id IN ( SELECT id from MISSING_IDS ) \n" }, { "answer_id": 154056, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "SELECT * FROM Transaction_Log\nWHERE processed = 0\nORDER BY id\nLIMIT 10;\n UPDATE Transaction_Log\nSET processed = 1\nWHERE id = ?; -- do this for each row processed\n" }, { "answer_id": 154406, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "last_id select * from Transaction_log where id = (\n select last_id + 1 /* or whatever increment your sequencer has */\n from Reader_status)\n" }, { "answer_id": 156175, "author": "Rejeev Divakaran", "author_id": 10980, "author_profile": "https://Stackoverflow.com/users/10980", "pm_score": 0, "selected": false, "text": "Oracle Sequence auto-increment INSERT INTO transaction_table VALUES(id__seq.nextval, <other columns>);\n autoCommit(true)" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7742/" ]
152,248
<p>We have a website running on Apache, access to which has a number of static pages protected via HTTP Basic authentication.</p> <p>I've written a new part of the site with Django using Django's built in support for user management.</p> <p>The problem I have is that users have to log in once via the HTTP Basic authentication and then again using a Django login form. This both clumsy and very confusing for users.</p> <p>I was wondering if anyone had found a way to make Django log a user in using the HTTP Basic authentication information.</p> <p>I not expecting to pass a password to Django, but rather if a user <code>dave</code> has been authenticated by Apache then they should be automatically logged into Django as <code>dave</code> too.</p> <p>(One option would be to make Apache and Django share a user store to ensure common usernames and passwords but this would still involve two login prompts which is what I'm trying to avoid.)</p>
[ { "answer_id": 156593, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 3, "selected": false, "text": "RemoteUserAuthMiddleware AuthenticationMiddleware AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.RemoteUserAuthBackend',) testuser 123 urls.py from django.conf.urls.defaults import *\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nurlpatterns = patterns('',\n url(regex='^$',\n view=lambda request: HttpResponse(repr(request), 'text/plain')),\n\n url(regex='^user/$',\n view=lambda request: HttpResponse(repr(request.user), 'text/plain')),\n\n url(regex='^users/$',\n view=lambda request: HttpResponse(\n ','.join(u.username for u in User.objects.all()),\n 'text/plain')),\n)\n testuser 'AUTH_TYPE': 'Basic'\n'HTTP_AUTHORIZATION': 'Basic dGVzdHVzZXI6MTIz'\n'REMOTE_USER': 'testuser'\n /user/ testuser <User: testuser>\n /users/ testuser admin syncdb admin,testuser\n RemoteUserAuthBackend RemoteUserAuthMiddleware" }, { "answer_id": 156832, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 0, "selected": false, "text": "AuthenticationBackend AuthenticationBackend" }, { "answer_id": 62028635, "author": "praveen", "author_id": 6286278, "author_profile": "https://Stackoverflow.com/users/6286278", "pm_score": 2, "selected": false, "text": "def post(self, request):\n auth_header = request.META.get('HTTP_AUTHORIZATION', '')\n token_type, _, credentials = auth_header.partition(' ')\n import base64\n expected = base64.b64encode(b'<username>:<password>').decode()\n if token_type != 'Basic' or credentials != expected:\n return HttpResponse(status=401)\n authorization success flow code ...\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3171/" ]
152,250
<p>I have my winform application gathering data using databinding. Everything looks fine except that I have to link the <strong>property</strong> with the <strong>textedit</strong> using a string:</p> <blockquote> <p>Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True))</p> </blockquote> <p>This works fine but if I change the class' property name, the compiler obviously will not warn me . </p> <p>I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class) </p> <p>Any idea?</p>
[ { "answer_id": 152279, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "[AttributeUsage(AttributeTargets.Property)]\nclass TextProperyAttribute: Attribute\n{}\n\nclass MyTextBox\n{\n [TextPropery]\n public string Text { get; set;}\n public int Foo { get; set;}\n public double Bar { get; set;}\n}\n\n\nstatic string GetTextProperty(Type type)\n{\n foreach (PropertyInfo info in type.GetProperties())\n {\n if (info.GetCustomAttributes(typeof(TextProperyAttribute), true).Length > 0)\n {\n return info.Name;\n }\n }\n\n return null;\n}\n\n...\n\nType type = typeof (MyTextBox);\n\nstring name = GetTextProperty(type);\n\nConsole.WriteLine(name); // Prints \"Text\"\n" }, { "answer_id": 152293, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 3, "selected": false, "text": "private string GetPropertyName<TValue>(Expression<Func<BindingSourceType, TValue>> propertySelector)\n{\n var memberExpression = propertySelector.Body as MemberExpression;\n return memberExpression != null \n ? memberExpression.Member.Name \n : string.empty;\n}\n BindingSourceType this.textBox.DataBindings.Add(GetPropertyName(o => o.MyClassProperty),\n this.myDataSourceObject,\n \"Text\");\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
152,259
<p>Say if I had a table of books in a MySQL database and I wanted to search the 'title' field for keywords (input by the user in a search field); what's the best way of doing this in PHP? Is the MySQL <code>LIKE</code> command the most efficient way to search?</p>
[ { "answer_id": 152320, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 3, "selected": false, "text": "$terms=explode(',', $_GET['keywords']);\n$clauses=array();\nforeach($terms as $term)\n{\n //remove any chars you don't want to be searching - adjust to suit\n //your requirements\n $clean=trim(preg_replace('/[^a-z0-9]/i', '', $term)); \n if (!empty($clean))\n {\n //note use of mysql_escape_string - while not strictly required\n //in this example due to the preg_replace earlier, it's good\n //practice to sanitize your DB inputs in case you modify that\n //filter...\n $clauses[]=\"title like '%\".mysql_escape_string($clean).\"%'\";\n }\n}\n\nif (!empty($clauses))\n{ \n //concatenate the clauses together with AND or OR, depending on\n //your requirements\n $filter='('.implode(' AND ', $clauses).')';\n\n //build and execute the required SQL\n $sql=\"select * from foo where $filter\";\n}\nelse\n{\n //no search term, do something else, find everything?\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
152,262
<p>I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.</p> <p>On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page.</p> <p>Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them. But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them.</p> <p>Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked? Does it have to be some ugly javascript that catches every clicks and deal with them accordingly?</p> <p>Thanks.</p>
[ { "answer_id": 152273, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "<a href=\"/Whatever/Wherever.htm\" onclick=\"handler(); return false;\" />\n" }, { "answer_id": 152274, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 4, "selected": false, "text": "<a href=\"javascript:code\">...</a>\n <a href=\"/non/ajax/display/page\" id=\"thisLink\">...</a>\n $(\"#thisLink\").click(function(ev, ob) {\n alert(\"thisLink was clicked\");\n ev.stopPropagation();\n});\n onclick" }, { "answer_id": 152277, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "href #bookmark" }, { "answer_id": 153275, "author": "Fczbkk", "author_id": 22920, "author_profile": "https://Stackoverflow.com/users/22920", "pm_score": 1, "selected": false, "text": "<a href=\"/original/url\" onclick=\"return !doSomething();\">link text</a>\n" }, { "answer_id": 15722884, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 2, "selected": false, "text": "$(\".detailLink\").click(function (ev, ob) {\n //ev.which == 1 == left\n //ev.which == 2 == middle\n if (ev.which == 1) {\n //do ajaxy stuff\n\n return false; //tells browser to stop processing the event\n }\n //else just let it go on its merry way and open the new tab.\n});\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16070/" ]
152,276
<p>I have report on my asp page and every time I change a filter and click view report, I get this error:</p> <p>Microsoft JScript runtime error: 'this._postBackSettings.async' is null or not an object</p> <p>I tried change the EnablePartialRendering="true" to EnablePartialRendering="false" but then people can't login on the site</p>
[ { "answer_id": 1289646, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "event.cancelBubble = true;\nif (event.stopPropagation)\n event.stopPropagation();\n" }, { "answer_id": 3342506, "author": "Sunil Pandey", "author_id": 403242, "author_profile": "https://Stackoverflow.com/users/403242", "pm_score": 2, "selected": false, "text": "EnablePartialRendering ScriptManager ScriptManager1.EnablePartialRendering = false;\n OnInit rsweb:ReportViewer OnInit" }, { "answer_id": 5105110, "author": "Gorgsenegger", "author_id": 412036, "author_profile": "https://Stackoverflow.com/users/412036", "pm_score": 2, "selected": false, "text": "var script = @\"\nif (Sys &&\n Sys.WebForms && Sys.WebForms.PageRequestManager &&\n Sys.WebForms.PageRequestManager.getInstance) \n{\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n if (prm &&\n !prm._postBackSettings)\n {\n prm._postBackSettings = prm._createPostBackSettings(false, null, null);\n }\";\n\nScriptManager.RegisterOnSubmitStatement(\n Page, \n Page.GetType(), \n \"FixPopupFormSubmit\", \n script);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12311/" ]
152,288
<p>I've been pulling my hear out over this problem for a few hours yesterday:</p> <p>I've a database on MySQL 4.1.22 server with encoding set to "UTF-8 Unicode (utf8)" (as reported by phpMyAdmin). Tables in this database have default charset set to <b>latin2</b>. But, the web application (CMS Made Simple written in PHP) using it displays pages in <b>utf8</b>...</p> <p>However screwed up this may be, it actually works. The web app displays characters correctly (mostly Czech and Polish are used).</p> <p>I run: "mysqldump -u xxx -p -h yyy dbname > dump.sql". This gives me an SQL script which:</p> <ul> <li>looks perfect in any editor (like Notepad+) when displaying in <b>UTF-8</b> - all characters display properly</li> <li>all tables in the script have default charset set to <b>latin2</b></li> <li>it has "/*!40101 SET NAMES latin2 */;" line at the beginning (among other settings)</li> </ul> <p>Now, I want to export this database to another server running on MySQL 5.0.67, also with server encoding set to "UTF-8 Unicode (utf8)". I copied the whole CMS Made Simple installation over, copied the dump.sql script and ran "mysql -h ddd -u zzz -p dbname &lt; dump.sql". After that, all the characters are scrambled when displaying CMSMS web pages.</p> <p>I tried setting:<br> SET character_set_client = utf8;<br> SET character_set_connection = latin2;</p> <p>And all combinations (just to be safe, even if it doesn't make any sense to me): latin2/utf8, latin2/latin2, utf8/utf8, etc. - doesn't help. All characters still scrambled, however sometimes in a different way :).</p> <p>I also tried replacing all latin2 settings with utf8 in the script (set names and default charsets for tables). Nothing.</p> <p>Are there any MySQL experts here who could explain in just a few words (I'm sure it's simple after all) how this whole encoding stuff really works? I read <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html" rel="noreferrer">9.1.4. Connection Character Sets and Collations</a> but found nothing helpful there.</p> <p>Thanks, Matt</p>
[ { "answer_id": 152740, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 5, "selected": false, "text": "mysql --default-character-set=utf8 -h ddd -u zzz -p dbname < dump.sql\n" }, { "answer_id": 21157493, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 0, "selected": false, "text": "mysql_query(\"SET NAMES 'utf8'\");\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23723/" ]
152,299
<p>I am about to set up a subversion server to be accessed via svn+ssh. I was wondering, where the <em>default</em> repository location is (on a unix box).</p> <p>Do you put it in</p> <pre><code>/opt/svn </code></pre> <p>or</p> <pre><code>/home/svn </code></pre> <p>or</p> <pre><code>/usr/subversion </code></pre> <p>or even</p> <pre><code>/svn </code></pre> <p>or somewhere else?</p> <p>I am looking for the place, most people put it. Is there a convention?</p> <p>EDIT:</p> <p>It is absolutely possible to "hide" the actual repository location from the user. For example (in my case) by wrapping the <code>svnserve</code> executable in a way that it is called like:</p> <pre><code>svnserve -r /var/svn/repos </code></pre>
[ { "answer_id": 152403, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 4, "selected": true, "text": "/var /var/lib/svn /var /usr /usr /var" }, { "answer_id": 152428, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 2, "selected": false, "text": "/home/svn svn" }, { "answer_id": 153789, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 2, "selected": false, "text": "command=\"/usr/local/bin/svnserve -t -r /repository/\" \n svnadmin create /repository/proj1\n svn co svn+ssh://host/proj1\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
152,307
<p>I've got an ASP.NET 2.0 website with a custom 404 page. When content is not found the site serves the custom 404 page with a query string addition of aspxerrorpath=/mauro.aspx. The 404 page itself is served with an <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" rel="nofollow noreferrer">HTTP</a> status of 200. To try to resolve this I've added</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { Response.StatusCode = 404; } </code></pre> <p>I added the Google widget and have two issues with it. In <a href="http://en.wikipedia.org/wiki/Internet_Explorer_7" rel="nofollow noreferrer">Internet&nbsp;Explorer&nbsp;7</a> it does not display where it should. If I add it to the content, I get an "unknown error" on char 79 line 226 or thereabouts; if I add it to the head section the search boxes appear above the content. In Firefox it works fine.</p> <p>So my issues are:</p> <ol> <li>How do I make the widget appear inline?</li> <li>How do I make the error page render as a 404 with the original name and path of the file being requested so that when I request mauro.aspx I get the content for the 404 page, but with the URL of mauro.aspx? (I assume that I will have to do some <a href="http://en.wikipedia.org/wiki/Rewrite_engine" rel="nofollow noreferrer">URL rewriting</a> in the begin_request global.asax file, but would like this confirmed before I do anything silly.)</li> </ol>
[ { "answer_id": 152366, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": true, "text": "protected void Application_BeginRequest(object sender, EventArgs e)\n{\n string url = Request.RawUrl;\n if ((url.Contains(\".aspx\")) && (!System.IO.File.Exists(Server.MapPath(url))))\n {\n Server.Transfer(\"/Error/FileNotFound.aspx\");\n }\n}\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2208/" ]
152,313
<p>When should you use XML attributes and when should you use XML elements?</p> <p>e.g.</p> <pre><code>&lt;customData&gt; &lt;records&gt; &lt;record name="foo" description="bar" /&gt; &lt;/records&gt; &lt;/customData&gt; </code></pre> <p>or</p> <pre><code>&lt;customData&gt; &lt;records&gt; &lt;record&gt; &lt;name&gt;foo&lt;/name&gt; &lt;description&gt;bar&lt;/description&gt; &lt;/record&gt; &lt;/records&gt; &lt;/customData&gt; </code></pre>
[ { "answer_id": 152346, "author": "Rory Becker", "author_id": 11356, "author_profile": "https://Stackoverflow.com/users/11356", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n <people>\n <person name=\"Rory\" surname=\"Becker\" age=\"30\" />\n <person name=\"Travis\" surname=\"Illig\" age=\"32\" />\n <person name=\"Scott\" surname=\"Hanselman\" age=\"34\" />\n </people>\n</data>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n <people>\n <person>\n <name>Rory</name>\n <surname>Becker</surname>\n <age>30</age>\n </person>\n <person>\n <name>Travis</name>\n <surname>Illig</surname>\n <age>32</age>\n </person>\n <person>\n <name>Scott</name>\n <surname>Hanselman</surname>\n <age>34</age>\n </person>\n </people>\n</data>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n <people>\n <person name=\"Rory\" surname=\"Becker\" age=\"30\" >\n <comment>A programmer whose interested in all sorts of misc stuff. His Blog can be found at http://rorybecker.blogspot.com and he's on twitter as @RoryBecker</comment>\n </person>\n <person name=\"Travis\" surname=\"Illig\" age=\"32\" >\n <comment>A cool guy for who has helped me out with all sorts of SVn information</comment>\n </person>\n <person name=\"Scott\" surname=\"Hanselman\" age=\"34\" >\n <comment>Scott works for MS and has a great podcast available at http://www.hanselminutes.com </comment>\n </person>\n </people>\n</data>\n" }, { "answer_id": 172688, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 4, "selected": false, "text": " <DateOfBirth>1975-06-03</DateOfBirth> \n <DateOfBirth VerifiedBy=\"View of Birth Certificate\">1975-06-03</DateOfBirth> \n <DateOfBirth VerifiedBy=\"View of Birth Certificate\" ValueSet=\"ISO 8601\" Code=\"2\">1975-06-03</DateOfBirth> \n <DateOfBirth> \n <VerifiedBy Code=\"2\">View of Birth Certificate</VerifiedBy> \n <Value ValueSet=\"ISO 8601\">1975-06-03</Value>\n </DateOfBirth>\n" }, { "answer_id": 2734004, "author": "Iz.", "author_id": 328405, "author_profile": "https://Stackoverflow.com/users/328405", "pm_score": 1, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<item id=\"69\" type=\"book\">\n <authors count=\"1\">\n <author>\n <name>John Smith</name>\n <author>\n </authors>\n <ISBN>123456790</ISBN>\n</item>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23726/" ]
152,319
<p>I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other <a href="http://web.archive.org/web/20180224071555/http://www.cs.ubc.ca:80/~harrison/Java/sorting-demo.html" rel="noreferrer">sort algorithm</a> other than bubble or merge would suffice.</p> <p>Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.</p>
[ { "answer_id": 152325, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 8, "selected": true, "text": "0 UBound(myArray) Call QuickSort(myArray, 0, UBound(myArray)) myArray Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)\n Dim pivot As Variant\n Dim tmpSwap As Variant\n Dim tmpLow As Long\n Dim tmpHi As Long\n\n tmpLow = inLow\n tmpHi = inHi\n\n pivot = vArray((inLow + inHi) \\ 2)\n\n While (tmpLow <= tmpHi)\n While (vArray(tmpLow) < pivot And tmpLow < inHi)\n tmpLow = tmpLow + 1\n Wend\n\n While (pivot < vArray(tmpHi) And tmpHi > inLow)\n tmpHi = tmpHi - 1\n Wend\n\n If (tmpLow <= tmpHi) Then\n tmpSwap = vArray(tmpLow)\n vArray(tmpLow) = vArray(tmpHi)\n vArray(tmpHi) = tmpSwap\n tmpLow = tmpLow + 1\n tmpHi = tmpHi - 1\n End If\n Wend\n\n If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi\n If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi\nEnd Sub\n" }, { "answer_id": 152333, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "Private Sub QuickSort(ByRef Field() As String, ByVal LB As Long, ByVal UB As Long)\n Dim P1 As Long, P2 As Long, Ref As String, TEMP As String\n\n P1 = LB\n P2 = UB\n Ref = Field((P1 + P2) / 2)\n\n Do\n Do While (Field(P1) < Ref)\n P1 = P1 + 1\n Loop\n\n Do While (Field(P2) > Ref)\n P2 = P2 - 1\n Loop\n\n If P1 <= P2 Then\n TEMP = Field(P1)\n Field(P1) = Field(P2)\n Field(P2) = TEMP\n\n P1 = P1 + 1\n P2 = P2 - 1\n End If\n Loop Until (P1 > P2)\n\n If LB < P2 Then Call QuickSort(Field, LB, P2)\n If P1 < UB Then Call QuickSort(Field, P1, UB)\nEnd Sub\n Call QuickSort(MyArray, LBound(MyArray), UBound(MyArray))\n" }, { "answer_id": 4347723, "author": "Alain", "author_id": 529618, "author_profile": "https://Stackoverflow.com/users/529618", "pm_score": 5, "selected": false, "text": "Private Sub QuickSort(ByRef a() As Long, ByVal l As Long, ByVal r As Long)\n Dim M As Long, i As Long, j As Long, v As Long\n M = 4\n\n If ((r - l) > M) Then\n i = (r + l) / 2\n If (a(l) > a(i)) Then swap a, l, i '// Tri-Median Methode!'\n If (a(l) > a(r)) Then swap a, l, r\n If (a(i) > a(r)) Then swap a, i, r\n\n j = r - 1\n swap a, i, j\n i = l\n v = a(j)\n Do\n Do: i = i + 1: Loop While (a(i) < v)\n Do: j = j - 1: Loop While (a(j) > v)\n If (j < i) Then Exit Do\n swap a, i, j\n Loop\n swap a, i, r - 1\n QuickSort a, l, j\n QuickSort a, i + 1, r\n End If\nEnd Sub\n\nPrivate Sub swap(ByRef a() As Long, ByVal i As Long, ByVal j As Long)\n Dim T As Long\n T = a(i)\n a(i) = a(j)\n a(j) = T\nEnd Sub\n\nPrivate Sub InsertionSort(ByRef a(), ByVal lo0 As Long, ByVal hi0 As Long)\n Dim i As Long, j As Long, v As Long\n\n For i = lo0 + 1 To hi0\n v = a(i)\n j = i\n Do While j > lo0\n If Not a(j - 1) > v Then Exit Do\n a(j) = a(j - 1)\n j = j - 1\n Loop\n a(j) = v\n Next i\nEnd Sub\n\nPublic Sub sort(ByRef a() As Long)\n QuickSort a, LBound(a), UBound(a)\n InsertionSort a, LBound(a), UBound(a)\nEnd Sub\n" }, { "answer_id": 6123532, "author": "lucas0x7B", "author_id": 516035, "author_profile": "https://Stackoverflow.com/users/516035", "pm_score": 2, "selected": false, "text": "Option Base 1\n\n\nPrivate Function sort_array_2D_excel(array_2D, array_sortkeys, Optional array_sortorders, Optional tag_header As String = \"Guess\", Optional tag_matchcase As String = \"False\")\n\n' Dependencies: Excel; Tools > References > Microsoft Excel [Version] Object Library\n\n Dim excel_application As Excel.Application\n Dim excel_workbook As Excel.Workbook\n Dim excel_worksheet As Excel.Worksheet\n\n Set excel_application = CreateObject(\"Excel.Application\")\n\n excel_application.Visible = True\n excel_application.ScreenUpdating = False\n excel_application.WindowState = xlNormal\n\n Set excel_workbook = excel_application.Workbooks.Add\n excel_workbook.Activate\n\n Set excel_worksheet = excel_workbook.Worksheets.Add\n excel_worksheet.Activate\n excel_worksheet.Visible = xlSheetVisible\n\n Dim excel_range As Excel.Range\n Set excel_range = excel_worksheet.Range(\"A1\").Resize(UBound(array_2D, 1) - LBound(array_2D, 1) + 1, UBound(array_2D, 2) - LBound(array_2D, 2) + 1)\n excel_range = array_2D\n\n\n For i_sortkey = LBound(array_sortkeys) To UBound(array_sortkeys)\n\n If IsNumeric(array_sortkeys(i_sortkey)) Then\n sortkey_range = Chr(array_sortkeys(i_sortkey) + 65 - 1) & \"1\"\n Set array_sortkeys(i_sortkey) = excel_worksheet.Range(sortkey_range)\n\n Else\n MsgBox \"Error in sortkey parameter:\" & vbLf & \"array_sortkeys(\" & i_sortkey & \") = \" & array_sortkeys(i_sortkey) & vbLf & \"Terminating...\"\n End\n\n End If\n\n Next i_sortkey\n\n\n For i_sortorder = LBound(array_sortorders) To UBound(array_sortorders)\n Select Case LCase(array_sortorders(i_sortorder))\n Case \"asc\"\n array_sortorders(i_sortorder) = XlSortOrder.xlAscending\n Case \"desc\"\n array_sortorders(i_sortorder) = XlSortOrder.xlDescending\n Case Else\n array_sortorders(i_sortorder) = XlSortOrder.xlAscending\n End Select\n Next i_sortorder\n\n Select Case LCase(tag_header)\n Case \"yes\"\n tag_header = Excel.xlYes\n Case \"no\"\n tag_header = Excel.xlNo\n Case \"guess\"\n tag_header = Excel.xlGuess\n Case Else\n tag_header = Excel.xlGuess\n End Select\n\n Select Case LCase(tag_matchcase)\n Case \"true\"\n tag_matchcase = True\n Case \"false\"\n tag_matchcase = False\n Case Else\n tag_matchcase = False\n End Select\n\n\n Select Case (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)\n Case 1\n Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Header:=tag_header, MatchCase:=tag_matchcase)\n Case 2\n Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Header:=tag_header, MatchCase:=tag_matchcase)\n Case 3\n Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Key3:=array_sortkeys(3), Order3:=array_sortorders(3), Header:=tag_header, MatchCase:=tag_matchcase)\n Case Else\n MsgBox \"Error in sortkey parameter:\" & vbLf & \"Maximum number of sort columns is 3!\" & vbLf & \"Currently passed: \" & (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)\n End\n End Select\n\n\n For i_row = 1 To excel_range.Rows.Count\n\n For i_column = 1 To excel_range.Columns.Count\n\n array_2D(i_row, i_column) = excel_range(i_row, i_column)\n\n Next i_column\n\n Next i_row\n\n\n excel_workbook.Close False\n excel_application.Quit\n\n Set excel_worksheet = Nothing\n Set excel_workbook = Nothing\n Set excel_application = Nothing\n\n\n sort_array_2D_excel = array_2D\n\n\nEnd Function\n Private Sub test_sort()\n\n array_unsorted = dim_sort_array()\n\n Call msgbox_array(array_unsorted)\n\n array_sorted = sort_array_2D_excel(array_unsorted, Array(2, 1, 3), Array(\"desc\", \"\", \"asdas\"), \"yes\", \"False\")\n\n Call msgbox_array(array_sorted)\n\nEnd Sub\n\n\nPrivate Function dim_sort_array()\n\n Dim array_unsorted(1 To 5, 1 To 3) As String\n\n i_row = 0\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"Column1\": array_unsorted(i_row, 2) = \"Column2\": array_unsorted(i_row, 3) = \"Column3\"\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"OR\": array_unsorted(i_row, 2) = \"A\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"XOR\": array_unsorted(i_row, 2) = \"A\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"NOT\": array_unsorted(i_row, 2) = \"B\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"AND\": array_unsorted(i_row, 2) = \"A\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n dim_sort_array = array_unsorted\n\nEnd Function\n\n\nSub msgbox_array(array_2D, Optional string_info As String = \"2D array content:\")\n\n msgbox_string = string_info & vbLf\n\n For i_row = LBound(array_2D, 1) To UBound(array_2D, 1)\n\n msgbox_string = msgbox_string & vbLf & i_row & vbTab\n\n For i_column = LBound(array_2D, 2) To UBound(array_2D, 2)\n\n msgbox_string = msgbox_string & array_2D(i_row, i_column) & vbTab\n\n Next i_column\n\n Next i_row\n\n MsgBox msgbox_string\n\nEnd Sub\n" }, { "answer_id": 19415281, "author": "Profex", "author_id": 1445339, "author_profile": "https://Stackoverflow.com/users/1445339", "pm_score": 3, "selected": false, "text": " Text1\n Text10\n Text100\n Text11\n Text2\n Text20\n Text1\n Text2\n Text10\n Text11\n Text20\n Text100\n Public Sub QuickSortNaturalNum(strArray() As String, intBottom As Integer, intTop As Integer)\nDim strPivot As String, strTemp As String\nDim intBottomTemp As Integer, intTopTemp As Integer\n\n intBottomTemp = intBottom\n intTopTemp = intTop\n\n strPivot = strArray((intBottom + intTop) \\ 2)\n\n Do While (intBottomTemp <= intTopTemp)\n ' < comparison of the values is a descending sort\n Do While (CompareNaturalNum(strArray(intBottomTemp), strPivot) < 0 And intBottomTemp < intTop)\n intBottomTemp = intBottomTemp + 1\n Loop\n Do While (CompareNaturalNum(strPivot, strArray(intTopTemp)) < 0 And intTopTemp > intBottom) '\n intTopTemp = intTopTemp - 1\n Loop\n If intBottomTemp < intTopTemp Then\n strTemp = strArray(intBottomTemp)\n strArray(intBottomTemp) = strArray(intTopTemp)\n strArray(intTopTemp) = strTemp\n End If\n If intBottomTemp <= intTopTemp Then\n intBottomTemp = intBottomTemp + 1\n intTopTemp = intTopTemp - 1\n End If\n Loop\n\n 'the function calls itself until everything is in good order\n If (intBottom < intTopTemp) Then QuickSortNaturalNum strArray, intBottom, intTopTemp\n If (intBottomTemp < intTop) Then QuickSortNaturalNum strArray, intBottomTemp, intTop\nEnd Sub\n Function CompareNaturalNum(string1 As Variant, string2 As Variant) As Integer\n'string1 is less than string2 -1\n'string1 is equal to string2 0\n'string1 is greater than string2 1\nDim n1 As Long, n2 As Long\nDim iPosOrig1 As Integer, iPosOrig2 As Integer\nDim iPos1 As Integer, iPos2 As Integer\nDim nOffset1 As Integer, nOffset2 As Integer\n\n If Not (IsNull(string1) Or IsNull(string2)) Then\n iPos1 = 1\n iPos2 = 1\n Do While iPos1 <= Len(string1)\n If iPos2 > Len(string2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n If isDigit(string1, iPos1) Then\n If Not isDigit(string2, iPos2) Then\n CompareNaturalNum = -1\n Exit Function\n End If\n iPosOrig1 = iPos1\n iPosOrig2 = iPos2\n Do While isDigit(string1, iPos1)\n iPos1 = iPos1 + 1\n Loop\n\n Do While isDigit(string2, iPos2)\n iPos2 = iPos2 + 1\n Loop\n\n nOffset1 = (iPos1 - iPosOrig1)\n nOffset2 = (iPos2 - iPosOrig2)\n\n n1 = Val(Mid(string1, iPosOrig1, nOffset1))\n n2 = Val(Mid(string2, iPosOrig2, nOffset2))\n\n If (n1 < n2) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf (n1 > n2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n\n ' front padded zeros (put 01 before 1)\n If (n1 = n2) Then\n If (nOffset1 > nOffset2) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf (nOffset1 < nOffset2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n End If\n ElseIf isDigit(string2, iPos2) Then\n CompareNaturalNum = 1\n Exit Function\n Else\n If (Mid(string1, iPos1, 1) < Mid(string2, iPos2, 1)) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf (Mid(string1, iPos1, 1) > Mid(string2, iPos2, 1)) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n\n iPos1 = iPos1 + 1\n iPos2 = iPos2 + 1\n End If\n Loop\n ' Everything was the same so far, check if Len(string2) > Len(String1)\n ' If so, then string1 < string2\n If Len(string2) > Len(string1) Then\n CompareNaturalNum = -1\n Exit Function\n End If\n Else\n If IsNull(string1) And Not IsNull(string2) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf IsNull(string1) And IsNull(string2) Then\n CompareNaturalNum = 0\n Exit Function\n ElseIf Not IsNull(string1) And IsNull(string2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n End If\nEnd Function\n Function isDigit(ByVal str As String, pos As Integer) As Boolean\nDim iCode As Integer\n If pos <= Len(str) Then\n iCode = Asc(Mid(str, pos, 1))\n If iCode >= 48 And iCode <= 57 Then isDigit = True\n End If\nEnd Function\n" }, { "answer_id": 33755670, "author": "Jarek", "author_id": 5571713, "author_profile": "https://Stackoverflow.com/users/5571713", "pm_score": 2, "selected": false, "text": " For AR1 = LBound(eArray, 1) To UBound(eArray, 1)\n eValue = eArray(AR1)\n For AR2 = LBound(eArray, 1) To UBound(eArray, 1)\n If eArray(AR2) < eValue Then\n eArray(AR1) = eArray(AR2)\n eArray(AR2) = eValue\n eValue = eArray(AR1)\n End If\n Next AR2\n Next AR1\n" }, { "answer_id": 37779637, "author": "Reged", "author_id": 4765416, "author_profile": "https://Stackoverflow.com/users/4765416", "pm_score": 0, "selected": false, "text": "Sub sortlist()\n\n Dim xarr As Variant\n Dim yarr As Variant\n Dim zarr As Variant\n\n xarr = Sheets(\"sheet\").Range(\"sing col range\")\n ReDim yarr(1 To UBound(xarr), 1 To 1)\n ReDim zarr(1 To UBound(xarr), 1 To 1)\n\n For n = 1 To UBound(xarr)\n zarr(n, 1) = 1\n Next n\n\n For n = 1 To UBound(xarr) - 1\n y = zarr(n, 1)\n For a = n + 1 To UBound(xarr)\n If xarr(n, 1) > xarr(a, 1) Then\n y = y + 1\n Else\n zarr(a, 1) = zarr(a, 1) + 1\n End If\n Next a\n yarr(y, 1) = xarr(n, 1)\n Next n\n\n y = zarr(UBound(xarr), 1)\n yarr(y, 1) = xarr(UBound(xarr), 1)\n\n yrng = \"A1:A\" & UBound(yarr)\n Sheets(\"sheet\").Range(yrng) = yarr\n\nEnd Sub\n" }, { "answer_id": 41886947, "author": "Moreno", "author_id": 6254149, "author_profile": "https://Stackoverflow.com/users/6254149", "pm_score": 0, "selected": false, "text": "Option Base 1\n\n'Function to sort an array decscending\nFunction SORT(Rango As Range) As Variant\n Dim check As Boolean\n check = True\n If IsNull(Rango) Then\n check = False\n End If\n If check Then\n Application.Volatile\n Dim x() As Variant, n As Double, m As Double, i As Double, j As Double, k As Double\n n = Rango.Rows.Count: m = Rango.Columns.Count: k = n * m\n ReDim x(n, m)\n For i = 1 To n Step 1\n For j = 1 To m Step 1\n x(i, j) = Application.Large(Rango, k)\n k = k - 1\n Next j\n Next i\n SORT = x\n Else\n Exit Function\n End If\nEnd Function\n" }, { "answer_id": 45379461, "author": "Prasand Kumar", "author_id": 6486100, "author_profile": "https://Stackoverflow.com/users/6486100", "pm_score": 4, "selected": false, "text": "Dim arr As Object\nDim InputArray\n\n'Creating a array list\nSet arr = CreateObject(\"System.Collections.ArrayList\")\n\n'String\nInputArray = Array(\"d\", \"c\", \"b\", \"a\", \"f\", \"e\", \"g\")\n\n'number\n'InputArray = Array(6, 5, 3, 4, 2, 1)\n\n' adding the elements in the array to array_list\nFor Each element In InputArray\n arr.Add element\nNext\n\n'sorting happens\narr.Sort\n\n'Converting ArrayList to an array\n'so now a sorted array of elements is stored in the array sorted_array.\n\nsorted_array = arr.toarray\n" }, { "answer_id": 56689287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Call HeapSort(A) A Option Base 1 Sub SiftUp(A() As Variant, I As Long)\n Dim K As Long, P As Long, S As Variant\n K = I\n While K > 1\n P = K \\ 2\n If A(K) > A(P) Then\n S = A(P): A(P) = A(K): A(K) = S\n K = P\n Else\n Exit Sub\n End If\n Wend\nEnd Sub\n\nSub SiftDown(A() As Variant, I As Long)\n Dim K As Long, L As Long, S As Variant\n K = 1\n Do\n L = K + K\n If L > I Then Exit Sub\n If L + 1 <= I Then\n If A(L + 1) > A(L) Then L = L + 1\n End If\n If A(K) < A(L) Then\n S = A(K): A(K) = A(L): A(L) = S\n K = L\n Else\n Exit Sub\n End If\n Loop\nEnd Sub\n\nSub HeapSort(A() As Variant)\n Dim N As Long, I As Long, S As Variant\n N = UBound(A)\n For I = 2 To N\n Call SiftUp(A, I)\n Next I\n For I = N To 2 Step -1\n S = A(I): A(I) = A(1): A(1) = S\n Call SiftDown(A, I - 1)\n Next\nEnd Sub\n" }, { "answer_id": 57996291, "author": "pstraton", "author_id": 3685516, "author_profile": "https://Stackoverflow.com/users/3685516", "pm_score": 1, "selected": false, "text": "Public Sub ArrayListSort(ByRef SortArray As Variant)\n '\n 'Uses the sort capabilities of a System.Collections.ArrayList object to sort an array of values of any simple\n 'data-type.\n '\n 'AUTHOR: Peter Straton\n '\n 'CREDIT: Derived from Prasand Kumar's post at: https://stackoverflow.com/questions/152319/vba-array-sort-function\n '\n '*************************************************************************************************************\n\n Static ArrayListObj As Object\n Dim i As Long\n Dim LBnd As Long\n Dim UBnd As Long\n\n LBnd = LBound(SortArray)\n UBnd = UBound(SortArray)\n\n 'If necessary, create the ArrayList object, to be used to sort the specified array's values\n\n If ArrayListObj Is Nothing Then\n Set ArrayListObj = CreateObject(\"System.Collections.ArrayList\")\n Else\n ArrayListObj.Clear 'Already allocated so just clear any old contents\n End If\n\n 'Add the ArrayList elements from the array of values to be sorted. (There appears to be no way to do this\n 'using a single assignment statement.)\n\n For i = LBnd To UBnd\n ArrayListObj.Add SortArray(i)\n Next i\n\n ArrayListObj.Sort 'Do the sort\n\n 'Transfer the sorted ArrayList values back to the original array, which can be done with a single assignment\n 'statement. But the result is always zero-based so then, if necessary, adjust the resulting array to match\n 'its original index base.\n\n SortArray = ArrayListObj.ToArray\n If LBnd <> 0 Then ReDim Preserve SortArray(LBnd To UBnd)\nEnd Sub\n" }, { "answer_id": 60141995, "author": "q335r49", "author_id": 1318498, "author_profile": "https://Stackoverflow.com/users/1318498", "pm_score": 1, "selected": false, "text": "\"0|2|3|4|9\" Private Enum LeafType: tEMPTY: tTree: tValue: End Enum\nPrivate Left As Variant, Right As Variant, Center As Variant\nPrivate LeftType As LeafType, RightType As LeafType, CenterType As LeafType\nPublic Sub Add(x As Variant)\n If CenterType = tEMPTY Then\n Center = x\n CenterType = tValue\n ElseIf x > Center Then\n If RightType = tEMPTY Then\n Right = x\n RightType = tValue\n ElseIf RightType = tTree Then\n Right.Add x\n ElseIf x <> Right Then\n curLeaf = Right\n Set Right = New TreeList\n Right.Add curLeaf\n Right.Add x\n RightType = tTree\n End If\n ElseIf x < Center Then\n If LeftType = tEMPTY Then\n Left = x\n LeftType = tValue\n ElseIf LeftType = tTree Then\n Left.Add x\n ElseIf x <> Left Then\n curLeaf = Left\n Set Left = New TreeList\n Left.Add curLeaf\n Left.Add x\n LeftType = tTree\n End If\n End If\nEnd Sub\nPublic Function GetList$()\n Const sep$ = \"|\"\n If LeftType = tValue Then\n LeftList$ = Left & sep\n ElseIf LeftType = tTree Then\n LeftList = Left.GetList & sep\n End If\n If RightType = tValue Then\n RightList$ = sep & Right\n ElseIf RightType = tTree Then\n RightList = sep & Right.GetList\n End If\n GetList = LeftList & Center & RightList\nEnd Function\n\n'Sample code\nDim Tree As new TreeList\nTree.Add(\"0\")\nTree.Add(\"2\")\nTree.Add(\"2\")\nTree.Add(\"-1\")\nDebug.Print Tree.GetList() 'prints \"-1|0|2\"\nsortedList = Split(Tree.GetList(),\"|\")\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/152319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4134/" ]