qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
211,051
<p>Because Canvas3D doesn't have the ability to resize dynamically with the parent frame, I would like to be able to track when a user resizes a window and then resize it manually myself. (If this ends up crashing Canvas3D, as some docs suggest, I will simply destroy and recreate it when the user resizes their window). Part of this procedure involves being able to accurately tell how big the container panel is to begin with.</p> <p>The two methods I've tried:</p> <pre>panel.getHeight(); panel.getPreferredSize().height;</pre> <p>Don't seem to accurately report things: <code>getHeight()</code> is invariably zero, and <code>getPreferredSize()</code> returns numbers that don't actually have anything to do with the actual size of the panel.</p> <p>Any ideas?</p> <p><b>Edit</b>: So, I took a debugger to the panel object and manually inspected the non-object properties and I didn't see anything that resembled width/height. Granted, there are sub-objects that I didn't look at. Also, maybe the window has to be visible (it isn't, at the point I'm interfacing the object) when I query for height/object?</p> <p><b>Edit 2</b>: So, Swing classes are subclasses of AWT classes, so I imagine if you're able to find the height/width of those, the approach would generalize. I've amended the title accordingly.</p>
[ { "answer_id": 211095, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 5, "selected": true, "text": "public class WindowResizeTest extends JFrame {\n\n public static void main(String[] args) {\n new WindowResizeTest();\n }\n\n public WindowResizeTest() {\n this.setSize(640, 480);\n\n JPanel panel = new JPanel();\n panel.setBackground(Color.RED);\n this.add(panel);\n\n this.addComponentListener(new ComponentListener() {\n\n public void componentResized(ComponentEvent e) {\n System.out.println(e.getComponent().getSize());\n }\n\n public void componentHidden(ComponentEvent e) {}\n\n public void componentMoved(ComponentEvent e) {}\n\n public void componentShown(ComponentEvent e) {}\n });\n\n this.setVisible(true);\n }\n\n}\n" }, { "answer_id": 11252652, "author": "Taylor Golden", "author_id": 1461754, "author_profile": "https://Stackoverflow.com/users/1461754", "pm_score": 1, "selected": false, "text": "int windowWidth = getWidth();\nint windowHeight = getHeight();\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
211,055
<p>Does Linux/Unix/Posix provide an API to user-space applications to access a monotonically increasing clock, with centisecond to millisecond accuracy?</p> <p>On Linux, /proc/uptime provides a string-based representation of a floating point number of the number of seconds the system has been up.</p> <p>gettimeofday(2) does not provide a monotonically increasing clock.</p> <p>I could use getitimer(2) in the ITIMER_REAL time domain, set the timer to start at the (platform dependent) maximum and ignore the signal generated, but according to the man page the longest the timer can run for is approximately 100 days, which is shorter than my expected run time.</p>
[ { "answer_id": 211077, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 3, "selected": false, "text": "struct timespec tp;\nclock_gettime(CLOCK_MONOTONIC, &tp);\n" }, { "answer_id": 211080, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "clock_gettime() CLOCK_MONOTONIC" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23744/" ]
211,062
<p>I have an Excel spreadsheet with 1 column, 700 rows. I care about every seventh line. I don't want to have to go in and delete the 6 rows between each row I care about. So my solution was to create another sheet and specify a reference to each cell I want.</p> <pre><code>=sheet1!a1 =sheet1!a8 =sheet1!a15 </code></pre> <p>But I don't want to type in each of these formulas ... `100 times.I thought if I selected the three and dragged the box around, it would understand what I was trying to do, but no luck.</p> <p>Any ideas on how to do this elegantly/efficiently?</p>
[ { "answer_id": 211098, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 1, "selected": false, "text": "Dim strValue As String\nDim strCellNum As String\nDim x As String\nx = 1\n\nFor i = 1 To 700 Step 7\n strCellNum = \"A\" & i\n strValue = Worksheets(\"Sheet1\").Range(strCellNum).Value\n Debug.Print strValue\n Worksheets(\"Sheet2\").Range(\"A\" & x).Value = strValue\n x = x + 1\nNext\n" }, { "answer_id": 211729, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 8, "selected": true, "text": "=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)\n =OFFSET(Sheet1!A$1,(ROW()-1)*7,0)\n" }, { "answer_id": 36298246, "author": "cameronroytaylor", "author_id": 4541374, "author_profile": "https://Stackoverflow.com/users/4541374", "pm_score": 0, "selected": false, "text": "=OFFSET(C$42,(ROW(C42)-ROW(C$42))*7,0)\n" }, { "answer_id": 39706574, "author": "CoderGuy123", "author_id": 3980197, "author_profile": "https://Stackoverflow.com/users/3980197", "pm_score": 4, "selected": false, "text": "OFFSET OFFSET OFFNET OFFSET(A1, 1, 2) C2 A1 (1,1) (1,2) (2,3) C2 ROW OFFSET ROW ROW OFFSET(A$1,ROW()*3,0) $1 1 ADDRESS INDIRECT ADDRESS ADDRESS(1,1) \"$A$1\" INDIRECT INDIRECT(\"A1\") A1 $ ROW ADDRESS ADDRESS(ROW(), 1) \"$A$1\" \"$A$2\" INDIRECT INDIRECT(ADDRESS(1*ROW()*3,1)) A B OFFSET $ 3 C OFFSET $ D OFFSET E ADDRESS INDRECT C F ADDRESS INDRECT" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23105/" ]
211,074
<p>The mouse hovers over an element and a tip appears. The tip overflows the page, triggering a scrollbar, which changes the layout just enough so that the underlying element that triggered the tip is no longer under the mouse pointer, so the tip goes away.</p> <p>The tip goes away, so the scrollbar goes away, and now the mouse is again over the element.</p> <p>Wash, rinse, repeat.</p> <p>If I could make sure that tip isn't too big so as to trigger scrollbars, that would solve my problem.</p> <p>EDIT: After reading comments, some things to clarify: The div contains text which can vary. If I can, I want to show all the text. The div's location needs to be near the element the mouse's tip is over. So the key is, I need to know whether to truncate the text.</p> <p>I did find this link:<br> <a href="http://www.howtocreate.co.uk/tutorials/javascript/browserwindow" rel="nofollow noreferrer">http://www.howtocreate.co.uk/tutorials/javascript/browserwindow</a><br> which contains this piece of the puzzle, figuring out how big the browser window is: </p> <pre><code>function alertSize() { var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement &amp;&amp; ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } else if( document.body &amp;&amp; ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myWidth = document.body.clientWidth; myHeight = document.body.clientHeight; } window.alert( 'Width = ' + myWidth ); window.alert( 'Height = ' + myHeight ); } </code></pre>
[ { "answer_id": 211078, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "#tooltip {\n position: absolute;\n height: 100px;\n width: 200px;\n border: 1px solid #444444;\n background-color: #EEEEEE;\n display: none;\n}\n top left block" }, { "answer_id": 211083, "author": "andyk", "author_id": 26721, "author_profile": "https://Stackoverflow.com/users/26721", "pm_score": 1, "selected": false, "text": "width height overflow: hidden overflow: scroll position: absolute top left" }, { "answer_id": 211151, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "var toolTipDiv; //this is your tooltip div element\n//call AdjustToolTipPosition(window.event);\nfunction AdjustToolTipPosition(e)\n{\n var cpos = getPosition(e);\n mouseX = cpos.x;\n mouseY = cpos.y;\n\n //Depending on IE/Firefox, find out what \n //object to use to find mouse position\n\n toolTipDiv.style.visibility = \"visible\";\n\n //backdrop 'yardstick' for client area measurement\n var backdropDiv = document.getElementById(\"divBackdrop\");\n\n //make sure floating box doesn't leave the screen\n //we know box is 200x200 plus margins, say 215x215\n if ((cpos.y + 215) > backdropDiv.offsetHeight)\n {\n cpos.y = backdropDiv.offsetHeight - 215;\n }\n if ((cpos.x + 215) > backdropDiv.offsetWidth)\n {\n cpos.x = backdropDiv.offsetWidth - 215;\n }\n toolTipDiv.style.left = cpos.x + \"px\";\n toolTipDiv.style.top = cpos.y + \"px\";\n}\n//this function courtesy of \n//http://hartshorne.ca/2006/01/23/javascript_cursor_position/\nfunction getPosition(e) \n{\n e = e || window.event;\n var cursor = {x:0, y:0};\n if (e.pageX || e.pageY) \n {\n cursor.x = e.pageX;\n cursor.y = e.pageY;\n }\n else \n {\n var de = document.documentElement;\n var b = document.body;\n cursor.x = e.clientX + \n (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);\n cursor.y = e.clientY + \n (de.scrollTop || b.scrollTop) - (de.clientTop || 0);\n }\n return cursor;\n}\n" }, { "answer_id": 212153, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 0, "selected": false, "text": "max-height max-width overflow: scroll" }, { "answer_id": 213171, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 0, "selected": false, "text": "if (!e) var e = window.event;\nif(e) {\n var posx = 0;\n var posy = 0;\n\n if (e.pageX || e.pageY) {\n posx = e.pageX;\n posy = e.pageY;\n }\n else if (e.clientX || e.clientY) {\n posx = e.clientX + document.body.scrollLeft\n + document.documentElement.scrollLeft;\n posy = e.clientY + document.body.scrollTop\n + document.documentElement.scrollTop;\n }\n\n var overflowX = (document.body.clientWidth + document.body.scrollLeft + document.documentElement.scrollLeft) - (posx + 25+ tooltip.clientWidth);\n if(overflowX < 0) posx -= 25+ (tooltip.clientWidth);\n\n var overflowY = (document.body.clientHeight + document.body.scrollTop + document.documentElement.scrollTop) - (posy + 15+ tooltip.clientHeight);\n if(overflowY < 0) posy += overflowY;\n\n tooltip.style.left=(10+posx);\n tooltip.style.top=(10+posy);\n}\n" }, { "answer_id": 249898, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "function display_popup(s)\n{ \n\n var popup = document.getElementById(\"popup\");\n popup.innerHTML = s\n\n //viewport_height = $(document).height() doesn't work\n viewport_height = get_viewport_size()[1] // does this factor in scrollbar?\n\n mytop = $(current_element).offset().top + $(current_element).height() + 4\n scroll_offset_y = $(document).scrollTop()\n y_in_viewport = mytop - scroll_offset_y\n\n if (y_in_viewport < viewport_height) // are we even visible?\n {\n // Display the popup, but truncate it if it overflows \n // to prevent scrollbar, which shifts element under mouse\n // which leads to flicker...\n\n popup.style.height= \"\"\n popup.style.display = \"block\";\n\n if (y_in_viewport + popup.offsetHeight > viewport_height)\n {\n overflow = (y_in_viewport + popup.offsetHeight) - viewport_height\n\n newh = popup.offsetHeight - overflow\n newh -= 10 // not sure why i need the margin..\n\n if (newh > 0)\n {\n popup.style.height = newh \n }\n else\n {\n popup.style.display = \"none\";\n }\n }\n popup.style.left = $(current_element).offset().left + 40\n popup.style.top = mytop\n }\n}\n\n\nfunction get_viewport_size()\n{\n var myWidth = 0, myHeight = 0;\n\n if( typeof( window.innerWidth ) == 'number' )\n {\n //Non-IE\n myWidth = window.innerWidth;\n myHeight = window.innerHeight;\n }\n else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )\n {\n //IE 6+ in 'standards compliant mode'\n myWidth = document.documentElement.clientWidth;\n myHeight = document.documentElement.clientHeight;\n }\n else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )\n {\n //IE 4 compatible\n myWidth = document.body.clientWidth;\n myHeight = document.body.clientHeight;\n }\n\n return [myWidth, myHeight];\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
211,099
<p>I've recently gotten my hobby java project embedded into a page <a href="https://stackoverflow.com/questions/138157/java-console-like-web-applet">thanks to this very site</a>, but now I'm having some security issues.</p> <p>I have the include:</p> <pre><code>import java.sql.*; </code></pre> <p>and the line:</p> <pre><code>Class.forName("com.mysql.jdbc.Driver").newInstance(); </code></pre> <p>as well as a mysql .jar file in my src directory, it works from the console, and in the applet works fine from the applet - up until that forName() line in my code, where it throws the exception:</p> <pre> Exception: com.mysql.jdbc.Driverjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.-1) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkExit(Unknown Source) at java.lang.Runtime.exit(Unknown Source) at java.lang.System.exit(Unknown Source) at applet.Database.connectDB(Database.java:80) etc... </pre> <p>I think I may be able to fix it with a client.policy file, otherwise I might need to write an abstraction layer which uses a server-client network connection to query from the server-side...</p> <p>I'm sure the Java gurus here probably know the best way about it.</p>
[ { "answer_id": 211140, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "newInstance() Class.forName()" }, { "answer_id": 212976, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 3, "selected": true, "text": "<APPLET ARCHIVE=\"mysql.jar\" CODEBASE=\"./src/\" ...\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14966/" ]
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
[ { "answer_id": 211101, "author": "dwestbrook", "author_id": 3119, "author_profile": "https://Stackoverflow.com/users/3119", "pm_score": 7, "selected": true, "text": "__import__ __import__( name[, globals[, locals[, fromlist[, level]]]])\n def my_import(name):\n mod = __import__(name)\n components = name.split('.')\n for comp in components[1:]:\n mod = getattr(mod, comp)\n return mod\n somepackage.somemodule __import__ somepackage.__init__.py somemodule fromlist somemodule" }, { "answer_id": 214682, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 3, "selected": false, "text": "twisted.python.reflect.namedAny >>> from twisted.python.reflect import namedAny\n>>> namedAny(\"operator.eq\")\n<built-in function eq>\n>>> namedAny(\"pysqlite2.dbapi2.connect\")\n<built-in function connect>\n>>> namedAny(\"os\")\n<module 'os' from '/usr/lib/python2.5/os.pyc'>\n" }, { "answer_id": 5138775, "author": "cerberos", "author_id": 121725, "author_profile": "https://Stackoverflow.com/users/121725", "pm_score": 5, "selected": false, "text": "import importlib\nfoo = importlib.import_module('a.dotted.path')\ninstance = foo.SomeClass()\n" }, { "answer_id": 5489623, "author": "David Seddon", "author_id": 684377, "author_profile": "https://Stackoverflow.com/users/684377", "pm_score": 1, "selected": false, "text": "def import_and_get_mod(str, parent_mod=None):\n \"\"\"Attempts to import the supplied string as a module.\n Returns the module that was imported.\"\"\"\n mods = str.split('.')\n child_mod_str = '.'.join(mods[1:])\n if parent_mod is None:\n if len(mods) > 1:\n #First time this function is called; import the module\n #__import__() will only return the top level module\n return import_and_get_mod(child_mod_str, __import__(str))\n else:\n return __import__(str)\n else:\n mod = getattr(parent_mod, mods[0])\n if len(mods) > 1:\n #We're not yet at the intended module; drill down\n return import_and_get_mod(child_mod_str, mod)\n else:\n return mod\n" }, { "answer_id": 6957437, "author": "Paolo", "author_id": 880698, "author_profile": "https://Stackoverflow.com/users/880698", "pm_score": 4, "selected": false, "text": ">>> import sys\n>>> name = 'foo.bar.baz'\n>>> __import__(name)\n<module 'foo' from ...>\n>>> baz = sys.modules[name]\n>>> baz\n<module 'foo.bar.baz' from ...>\n" }, { "answer_id": 25381926, "author": "rahul mishra", "author_id": 2732515, "author_profile": "https://Stackoverflow.com/users/2732515", "pm_score": 0, "selected": false, "text": "foo = __import__('foo', globals(), locals(), [\"bar\"], -1)\nfoobar = eval(\"foo.bar\")\n foobar.functionName()\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3119/" ]
211,118
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { for (var tag in doc.tags) { if (doc.tags[tag] == "%s") { emit(doc.published, doc) } } } }; ''' % tag </code></pre>
[ { "answer_id": 213138, "author": "Bahadır Yağan", "author_id": 3812, "author_profile": "https://Stackoverflow.com/users/3812", "pm_score": 4, "selected": true, "text": "function(doc) {\n for (var tag in doc.tags) {\n emit([tag, doc.published], doc)\n }\n};\n" }, { "answer_id": 312181, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "# Works on CouchDB 0.8.0\nfrom couchdb import Server # http://code.google.com/p/couchdb-python/\n\nbyTag = \"\"\"\nfunction(doc) {\nif (doc.type == 'post' && doc.tags) {\n doc.tags.forEach(function(tag) {\n emit(tag, doc);\n });\n}\n}\n\"\"\"\n\ndef findPostsByTag(self, tag):\n server = Server(\"http://localhost:1234\")\n db = server['my_table']\n return [row for row in db.query(byTag, key = tag)]\n value" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28809/" ]
211,122
<p>In an application that is hosting several WCF services, what would be the best way to add custom configuration information for each service? For example you may want to pass or set a company name or specify the connectionString a service or some other parameter. </p> <p>I'm guessing this might be possible by implementing IServiceBehavior.</p> <p>i.e something like....</p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug /&gt; &lt;customBehavior myCompany="ABC" /&gt; &lt;/behavior&gt; &lt;behavior name="MyOtherBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug /&gt; &lt;customBehavior myCompany="DEF" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service behaviorConfiguration="MyBehavior" name="MyNameSpace.MyService"&gt; &lt;endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:4000/MyService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;service behaviorConfiguration="MyOtherBehavior" name="MyNameSpace.MyOtherService"&gt; &lt;endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyOtherService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:4000/MyOtherService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; </code></pre> <p>Would set ABC on MyService and DEF on MyOtherService (assuming they have some common interface with a company name).</p> <p>Can anyone elaborate on how you implement this?</p> <p>TIA</p> <p>Michael</p>
[ { "answer_id": 619295, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 3, "selected": false, "text": "<%@ ServiceHost\n Language=\"C#\"\n Debug=\"true\"\n Service=\"Ionic.Samples.Webservices.Sep20.CustomConfigService\"\n Factory=\"Ionic.ServiceModel.ServiceHostFactory\"%>\n protected override void ApplyConfiguration()\n{\n // generate the name of the custom configFile, from the service name:\n string configFilename = System.IO.Path.Combine ( physicalPath,\n String.Format(\"{0}.config\", this.Description.Name));\n\n if (string.IsNullOrEmpty(configFilename) || !System.IO.File.Exists(configFilename))\n base.ApplyConfiguration();\n else\n LoadConfigFromCustomLocation(configFilename);\n}\n private string _physicalPath = null;\nprivate string physicalPath\n{\n get\n {\n if (_physicalPath == null)\n {\n // if hosted in IIS\n _physicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;\n\n if (String.IsNullOrEmpty(_physicalPath))\n {\n // for hosting outside of IIS\n _physicalPath= System.IO.Directory.GetCurrentDirectory();\n }\n }\n return _physicalPath;\n }\n}\n\n\nprivate void LoadConfigFromCustomLocation(string configFilename)\n{\n var filemap = new System.Configuration.ExeConfigurationFileMap();\n filemap.ExeConfigFilename = configFilename;\n System.Configuration.Configuration config =\n System.Configuration.ConfigurationManager.OpenMappedExeConfiguration\n (filemap,\n System.Configuration.ConfigurationUserLevel.None);\n var serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);\n bool loaded= false;\n foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services)\n {\n if(!loaded)\n if (se.Name == this.Description.ConfigurationName)\n {\n base.LoadConfigurationSection(se);\n loaded= true;\n }\n }\n\n if (!loaded)\n throw new ArgumentException(\"ServiceElement doesn't exist\");\n}\n" }, { "answer_id": 2085416, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 2, "selected": false, "text": "public class CustomDuplexChannelFactory<TChannel> : DuplexChannelFactory<TChannel>\n{\n public static string ConfigurationPath { get; set; }\n\n public CustomDuplexChannelFactory(InstanceContext callbackInstance)\n : base(callbackInstance)\n {\n }\n\n protected override ServiceEndpoint CreateDescription()\n {\n ServiceEndpoint serviceEndpoint = base.CreateDescription();\n\n if(ConfigurationPath == null || !File.Exists(ConfigurationPath))\n return base.CreateDescription();\n\n ExeConfigurationFileMap executionFileMap = new ExeConfigurationFileMap();\n executionFileMap.ExeConfigFilename = ConfigurationPath;\n System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(executionFileMap, ConfigurationUserLevel.None);\n ServiceModelSectionGroup serviceModeGroup = ServiceModelSectionGroup.GetSectionGroup(config);\n ChannelEndpointElement selectedEndpoint = null;\n foreach(ChannelEndpointElement endpoint in serviceModeGroup.Client.Endpoints)\n {\n if(endpoint.Contract == serviceEndpoint.Contract.ConfigurationName)\n {\n selectedEndpoint = endpoint; break;\n }\n }\n if(selectedEndpoint != null)\n {\n if(serviceEndpoint.Binding == null)\n {\n serviceEndpoint.Binding = CreateBinding(selectedEndpoint.Binding, serviceModeGroup);\n } if(serviceEndpoint.Address == null)\n {\n serviceEndpoint.Address = new EndpointAddress(selectedEndpoint.Address,\n GetIdentity(selectedEndpoint.Identity), selectedEndpoint.Headers.Headers);\n } if(serviceEndpoint.Behaviors.Count == 0 && !String.IsNullOrEmpty(selectedEndpoint.BehaviorConfiguration))\n {\n AddBehaviors(selectedEndpoint.BehaviorConfiguration,\n serviceEndpoint, serviceModeGroup);\n }\n serviceEndpoint.Name = selectedEndpoint.Contract;\n }\n return serviceEndpoint;\n }\n\n private Binding CreateBinding(string bindingName, ServiceModelSectionGroup group)\n {\n BindingCollectionElement bindingElementCollection = group.Bindings[bindingName];\n if(bindingElementCollection.ConfiguredBindings.Count > 0)\n {\n IBindingConfigurationElement be = bindingElementCollection.ConfiguredBindings[0];\n Binding binding = GetBinding(be); if(be != null)\n {\n be.ApplyConfiguration(binding);\n }\n return binding;\n }\n return null;\n }\n\n private void AddBehaviors(string behaviorConfiguration, ServiceEndpoint serviceEndpoint, ServiceModelSectionGroup group)\n {\n EndpointBehaviorElement behaviorElement = group.Behaviors.EndpointBehaviors[behaviorConfiguration];\n for(int i = 0; i < behaviorElement.Count; i++)\n {\n BehaviorExtensionElement behaviorExtension = behaviorElement[i];\n object extension = behaviorExtension.GetType().InvokeMember(\"CreateBehavior\", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, behaviorExtension, null);\n if(extension != null)\n {\n serviceEndpoint.Behaviors.Add((IEndpointBehavior)extension);\n }\n }\n }\n\n private EndpointIdentity GetIdentity(IdentityElement element)\n {\n EndpointIdentity identity = null;\n PropertyInformationCollection properties = element.ElementInformation.Properties;\n if(properties[\"userPrincipalName\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateUpnIdentity(element.UserPrincipalName.Value);\n }\n if(properties[\"servicePrincipalName\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateSpnIdentity(element.ServicePrincipalName.Value);\n }\n if(properties[\"dns\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateDnsIdentity(element.Dns.Value);\n }\n if(properties[\"rsa\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateRsaIdentity(element.Rsa.Value);\n }\n if(properties[\"certificate\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n X509Certificate2Collection supportingCertificates = new X509Certificate2Collection();\n supportingCertificates.Import(Convert.FromBase64String(element.Certificate.EncodedValue));\n\n if(supportingCertificates.Count == 0)\n {\n throw new InvalidOperationException(\"UnableToLoadCertificateIdentity\");\n }\n\n X509Certificate2 primaryCertificate = supportingCertificates[0]; supportingCertificates.RemoveAt(0);\n return EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate, supportingCertificates);\n }\n return identity;\n }\n\n private Binding GetBinding(IBindingConfigurationElement configurationElement)\n {\n if(configurationElement is CustomBindingElement)\n return new CustomBinding();\n else if(configurationElement is BasicHttpBindingElement)\n return new BasicHttpBinding();\n else if(configurationElement is NetMsmqBindingElement)\n return new NetMsmqBinding();\n else if(configurationElement is NetNamedPipeBindingElement)\n return new NetNamedPipeBinding();\n else if(configurationElement is NetPeerTcpBindingElement)\n return new NetPeerTcpBinding();\n else if(configurationElement is NetTcpBindingElement)\n return new NetTcpBinding();\n else if(configurationElement is WSDualHttpBindingElement)\n return new WSDualHttpBinding();\n else if(configurationElement is WSHttpBindingElement)\n return new WSHttpBinding();\n else if(configurationElement is WSFederationHttpBindingElement)\n return new WSFederationHttpBinding();\n return null;\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,133
<p>Oracle has this concept of allowing database users to be identified by the operating system user who is running the program that is connecting to Oracle. See <a href="http://www.oracle-base.com/articles/misc/OsAuthentication.php" rel="noreferrer">here</a>.</p> <p>This allows you to do, as that user on a unix machine for example, a command such as:</p> <pre><code>sqlplus / </code></pre> <p>I am attempting to write a Java program for Oracle 10.2 which connects without a username or password. The obvious choice of url:</p> <pre><code>jdbc:oracle:thin:/@localhost:1521:MYDBSID </code></pre> <p>doesn't work, giving an error (Sorry I don't have the error available right now).</p> <p>I have attempted many other forms of doing this as well, but with no luck.</p> <p>Does anyone have any suggestions on how I can connect a Java program to Oracle using the OS identification method?</p>
[ { "answer_id": 211228, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 4, "selected": true, "text": "jdbc:oracle:oci8:/@MYDBSID" }, { "answer_id": 30893239, "author": "evgeny", "author_id": 5019899, "author_profile": "https://Stackoverflow.com/users/5019899", "pm_score": -1, "selected": false, "text": "jdbc:oracle:oci:@" }, { "answer_id": 30902935, "author": "Jean de Lavarene", "author_id": 4612499, "author_profile": "https://Stackoverflow.com/users/4612499", "pm_score": 1, "selected": false, "text": "REMOTE_OS_AUTHENT = TRUE\n CREATE USER OSUSERDEMO IDENTIFIED EXTERNALLY;\n GRANT CONNECT,CREATE SESSION,RESOURCE TO OSUSERDEMO; \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27308/" ]
211,137
<p>I have ASP.Net code similar to the following (this is inside a FIELDSET):</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;one or more form controls, ASP.Net controls, labels, etc.&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;... more of the same...&gt; &lt;/li&gt; ... &lt;/ol&gt; </code></pre> <p>I'm trying to keep my markup as clean as I possibly can, but I've decided that for various reasons, I need to wrap a DIV around everything in the list item after the first label, like this:</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;div class="GroupThese"&gt; &lt;one or more form controls, ASP.Net controls, labels, etc.&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;div class="GroupThese"&gt; &lt;... more of the same...&gt; &lt;/div&gt; &lt;/li&gt; ... &lt;/ol&gt; </code></pre> <p>I would rather do this with "unobtrusive Javascript" via jQuery instead of littering my page with extra markup so I can keep the form semantically "clean".</p> <p>I know how to write a jQuery selector to get to the first label in each list item $("li+label") or use :first-child. I also know how to insert things after the selection.</p> <p>What I can't figure out (at least this late at night) is how to find everything after the first label in the list item (or basically everything in the list item except for the first label would be another way to put it) and wrap a DIV around that in the document ready function. </p> <p><strong>UPDATE:</strong></p> <p>Owen's code worked once I removed the single quotes from around: <pre>$('this')</pre> and set the proper decendent selector: <pre>$("li label:first-child")</pre> in order to only select the first label that occurs after a list item.</p> <p>Here is what I did:</p> <pre><code>$(document).ready(function() { $('li label:first-child').each(function() { $(this).siblings().wrapAll('&lt;div class="GroupThese"&gt;&lt;/div&gt;'); }); }); </code></pre>
[ { "answer_id": 211150, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 2, "selected": false, "text": "var $div = $('li').wrapInner('<div></div>').children('div');\n$div.children('label').prependTo($div.parent());\n" }, { "answer_id": 211159, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "$('li label:first-child').each(function() {\n $(this).siblings().wrapAll('<div class=\"li-non-label-child-wrapper\">');\n});\n <li>\n <label>Some label</label>\n <div>stuff</div>\n <div>other stuff</div>\n</li>\n<li>\n <label>Another label</label>\n <div>stuff3</div>\n</li>\n <li>\n <label>Some label</label>\n <div class=\"li-non-label-child-wrapper\">\n <div>stuff</div>\n <div>other stuff</div>\n </div>\n</li>\n<li>\n <label>Another label</label>\n <div class=\"li-non-label-child-wrapper\">\n <div>stuff3</div>\n </div>\n</li>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14894/" ]
211,143
<p>I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:</p> <pre><code>class Enum&lt;E extends Enum&lt;E&gt;&gt; </code></pre> <p>Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.</p>
[ { "answer_id": 211161, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "public class StatusCode extends Enum<StatusCode>\n Enum<StatusCode> E=StatusCode E Enum<StatusCode> Enum<E> Comparable<E> public interface IBuilder<TMessage, TBuilder>\n where TMessage : IMessage<TMessage, TBuilder> \n where TBuilder : IBuilder<TMessage, TBuilder>\n\npublic interface IMessage<TMessage, TBuilder>\n where TMessage : IMessage<TMessage, TBuilder> \n where TBuilder : IBuilder<TMessage, TBuilder>\n Enum public class First extends Enum<First> {}\npublic class Second extends Enum<First> {}\n Second Comparable<First> Comparable<Second> First" }, { "answer_id": 758595, "author": "Maurice Naftalin", "author_id": 1859863, "author_profile": "https://Stackoverflow.com/users/1859863", "pm_score": 5, "selected": false, "text": "Enum enum Season { WINTER, SPRING, SUMMER, FALL }\n final class Season extends ...\n ... Season Comparable<Season> Season extends ... implements Comparable<Season>\n ... Enum Enum<Season> Season extends Enum<Season>\nEnum<Season> implements Comparable<Season>\n Enum Season Season Enum E extends Enum<E>\n" }, { "answer_id": 1562221, "author": "nozebacle", "author_id": 114564, "author_profile": "https://Stackoverflow.com/users/114564", "pm_score": 1, "selected": false, "text": "public abstract class Node<T extends Node<T>>\n{\n public void addNeighbor(T);\n\n public void addNeighbors(Collection<? extends T> nodes);\n\n public Collection<T> getNeighbor();\n}\n public class City extends Node<City>\n{\n public void addNeighbor(City){...}\n\n public void addNeighbors(Collection<? extends City> nodes){...}\n\n public Collection<City> getNeighbor(){...}\n}\n" }, { "answer_id": 20253960, "author": "Andrey Chaschev", "author_id": 1851024, "author_profile": "https://Stackoverflow.com/users/1851024", "pm_score": 3, "selected": false, "text": "setName Node City class Node {\n String name;\n\n Node setName(String name) {\n this.name = name;\n return this;\n }\n}\n\nclass City extends Node {\n int square;\n\n City setSquare(int square) {\n this.square = square;\n return this;\n }\n}\n\npublic static void main(String[] args) {\n City city = new City()\n .setName(\"LA\")\n .setSquare(100); // won't compile, setName() returns Node\n}\n City abstract class Node<SELF extends Node<SELF>>{\n String name;\n\n SELF setName(String name) {\n this.name = name;\n return self();\n }\n\n protected abstract SELF self();\n}\n\nclass City extends Node<City> {\n int square;\n\n City setSquare(int square) {\n this.square = square;\n return self();\n }\n\n @Override\n protected City self() {\n return this;\n }\n\n public static void main(String[] args) {\n City city = new City()\n .setName(\"LA\")\n .setSquare(100); // ok!\n }\n}\n" }, { "answer_id": 30667912, "author": "EpicPandaForce", "author_id": 2413303, "author_profile": "https://Stackoverflow.com/users/2413303", "pm_score": 1, "selected": false, "text": "Enum public abstract class Enum<E extends Enum<E>>\n implements Comparable<E>, Serializable {\n\n public final int compareTo(E o) {\n Enum<?> other = (Enum<?>)o;\n Enum<E> self = this;\n if (self.getClass() != other.getClass() && // optimization\n self.getDeclaringClass() != other.getDeclaringClass())\n throw new ClassCastException();\n return self.ordinal - other.ordinal;\n }\n\n @SuppressWarnings(\"unchecked\")\n public final Class<E> getDeclaringClass() {\n Class<?> clazz = getClass();\n Class<?> zuper = clazz.getSuperclass();\n return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;\n }\n\n public static <T extends Enum<T>> T valueOf(Class<T> enumType,\n String name) {\n T result = enumType.enumConstantDirectory().get(name);\n if (result != null)\n return result;\n if (name == null)\n throw new NullPointerException(\"Name is null\");\n throw new IllegalArgumentException(\n \"No enum constant \" + enumType.getCanonicalName() + \".\" + name);\n } \n}\n E extends Enum<E> public enum MyEnum {\n THING1,\n THING2;\n}\n public final class MyEnum extends Enum<MyEnum> {\n public static final MyEnum THING1 = new MyEnum();\n public static final MyEnum THING2 = new MyEnum();\n}\n public final int compareTo(MyEnum o) {\n Enum<?> other = (Enum<?>)o;\n Enum<MyEnum> self = this;\n if (self.getClass() != other.getClass() && // optimization\n self.getDeclaringClass() != other.getDeclaringClass())\n throw new ClassCastException();\n return self.ordinal - other.ordinal;\n}\n @SuppressWarnings(\"unchecked\")\n public final Class<MyEnum> getDeclaringClass() {\n Class<?> clazz = getClass();\n Class<?> zuper = clazz.getSuperclass();\n return (zuper == Enum.class) ? (Class<MyEnum>)clazz : (Class<MyEnum>)zuper;\n }\n getDeclaringClass() Class<T>" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
[ { "answer_id": 211174, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 8, "selected": true, "text": "from numpy import matrix\nfrom numpy import linalg\nA = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.\nx = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).\ny = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).\nprint A.T # Transpose of A.\nprint A*x # Matrix multiplication of A and x.\nprint A.I # Inverse of A.\nprint linalg.solve(A, x) # Solve the linear equation system.\n" }, { "answer_id": 3128931, "author": "user377367", "author_id": 377367, "author_profile": "https://Stackoverflow.com/users/377367", "pm_score": 3, "selected": false, "text": "A = matrix( [[1,2,3],[11,12,13],[21,22,23]])\n A = matrix( [[2,2,3],[11,24,13],[21,22,46]])\n" }, { "answer_id": 21126480, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "M = Matrix([[1, 3], [-2, 3]])\nM\nM**-1\n M**(1/2)" }, { "answer_id": 62940942, "author": "Vladimir Salin", "author_id": 839518, "author_profile": "https://Stackoverflow.com/users/839518", "pm_score": 3, "selected": false, "text": "pandas numpy AM IM def invert_matrix(AM, IM):\n for fd in range(len(AM)):\n fdScaler = 1.0 / AM[fd][fd]\n for j in range(len(AM)):\n AM[fd][j] *= fdScaler\n IM[fd][j] *= fdScaler\n for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:\n crScaler = AM[i][fd]\n for j in range(len(AM)):\n AM[i][j] = AM[i][j] - crScaler * AM[fd][j]\n IM[i][j] = IM[i][j] - crScaler * IM[fd][j]\n return IM\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
211,169
<p>So I was wondering if there are any major differences between the various implementations of the hash algorithms, take the SHA series of algorithms for example. All of them have 3 implementations each, 1 in managed code and 2 wrappers around different native crypto APIs, but are there any major differences between using any of them? I can imagine that the wrapper versions could have higher performance since its being executed in native code, but surley hey all need to perform the exact same calculations and thus provide the same output ie hey are interchangable. Is this correct?</p> <p>For instance SHA512CNG cant be used on XP SP2 (docs are wrong) but SHA512MANAGED can.</p> <hr> <p>@Maxim - Thank you, but not quite what I was asking for. I was asking if there is any difference, other than possibly performance, from using the Managed/CryptoServiceProvider/CNG implementations of a given hash algorithm. With .NET 3.5 you get all of the hash algorithms with three implementations, so</p> <p>SHA512Managed SHA512CryptoServiceProvider SHA512Cng</p> <p>The latter two being wrappers around native APIs. This is true for all SHAxxx implementations for example.</p>
[ { "answer_id": 1004127, "author": "Joe Basirico", "author_id": 20795, "author_profile": "https://Stackoverflow.com/users/20795", "pm_score": 2, "selected": false, "text": "CalculateHash(1, 1024, new SHA1CryptoServiceProvider());\n\nstatic long CalculateHash(UInt64 repetitions, UInt64 size, HashAlgorithm engine)\n {\n RandomNumberGenerator rng = RandomNumberGenerator.Create();\n\n byte[][] goo = new byte[repetitions][];\n for (UInt64 i = 0; i < repetitions; i++)\n {\n goo[i] = new byte[size];\n rng.GetBytes(goo[i]);\n }\n\n DateTime start = DateTime.Now;\n for (UInt64 i = 0; i < repetitions; i++)\n {\n engine.ComputeHash(goo[i]);\n }\n return DateTime.Now.Subtract(start).Ticks;\n }\n int loops = 32;\n UInt64 reps = 1;\n\n int width = 20;\n Console.WriteLine(\"Loop#\".PadRight(6) +\n \"MD5\".PadRight(width) +\n \"SHA1\".PadRight(width) +\n \"SHA1Cng\".PadRight(width) +\n \"SHA256\".PadRight(width) +\n \"SHA256Cng\".PadRight(width));\n\n for (int i = 0; i < loops; i++)\n {\n UInt64 size = (UInt64)Math.Pow((double)2, (double)i);\n\n Console.WriteLine((i + 1).ToString().PadRight(6) +\n CalculateHash(reps, size, new MD5CryptoServiceProvider()).ToString().PadRight(width) +\n CalculateHash(reps, size, new SHA1CryptoServiceProvider()).ToString().PadRight(width) +\n CalculateHash(reps, size, new SHA1Cng() ).ToString().PadRight(width) +\n CalculateHash(reps, size, new SHA256CryptoServiceProvider()).ToString().PadRight(width) +\n CalculateHash(reps, size, new SHA256Cng()).ToString().PadRight(width));\n }\n\nLoop# MD5 SHA1 SHA1Cng SHA256 SHA256Cng\n1 50210 0 0 0 0\n2 0 0 0 0 0\n3 0 0 0 0 0\n4 0 0 0 0 0\n5 0 0 0 0 0\n6 0 0 0 0 0\n7 0 0 0 0 0\n8 0 0 0 0 0\n9 0 0 0 0 0\n10 0 0 10042 0 0\n11 0 0 0 0 0\n12 0 0 0 0 0\n13 0 0 0 0 0\n14 0 0 0 0 0\n15 10042 0 0 10042 10042\n16 10042 0 0 0 0\n17 0 0 0 10042 10042\n18 0 10042 10042 20084 10042\n19 0 10042 10042 30126 40168\n20 20084 20084 20084 70294 70294\n21 30126 40168 40168 140588 140588\n22 60252 70294 80336 291218 281176\n23 120504 140588 180756 572394 612562\n24 241008 281176 361512 1144788 1215082\n25 482016 572394 723024 2289576 2420122\n26 953990 1134746 1456090 4538984 4830202\n27 1907980 2259450 2982474 9118136 9660404\n28 3805918 4508858 5804276 18336692 19581900\n" }, { "answer_id": 39615096, "author": "IdontCareAboutReputationPoints", "author_id": 554893, "author_profile": "https://Stackoverflow.com/users/554893", "pm_score": 1, "selected": false, "text": "CNG managed static void Main(string[] args)\n {\n int loops = 10000000;\n var data = Encoding.ASCII.GetBytes(\"123\");\n\n var hashLoop = new Action<HashAlgorithm>((HashAlgorithm ha) =>\n {\n for (int i = 0; i < loops; i++)\n ha.ComputeHash(data);\n });\n\n var t1 = Task.Factory.StartNew(() =>\n {\n Time(hashLoop, new SHA512Managed());\n });\n var t2 = Task.Factory.StartNew(() =>\n {\n Time(hashLoop, new SHA512Cng());\n });\n\n Task.WaitAll(t1, t2);\n Console.WriteLine(\"Benchmark done!\");\n Console.ReadKey();\n }\n static void Time(Action<HashAlgorithm> action, HashAlgorithm ha)\n {\n var sw = new Stopwatch();\n sw.Start();\n action(ha);\n sw.Stop();\n Console.WriteLine(\"{1} done in {0}ms\", sw.ElapsedMilliseconds, ha.ToString());\n }\n 21.7% to 49.5%" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25319/" ]
211,176
<p>I am seeing following exception when I try to use dynamic proxy </p> <pre><code> com.intellij.rt.execution.application.AppMain DynamicProxy.DynamicProxy Exception in thread "main" java.lang.IllegalArgumentException: interface Interfaces.IPerson is not visible from class loader at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353) at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581) at DynamicProxy.Creator.getProxy(Creator.java:18) at DynamicProxy.DynamicProxy.main(DynamicProxy.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) </code></pre> <p>Any idea what I need to do to resolve it</p>
[ { "answer_id": 211226, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "DynamicProxy Class.forName(youInterfaceClass.getName()) java.lang.Class" }, { "answer_id": 13379769, "author": "omnomnom", "author_id": 577812, "author_profile": "https://Stackoverflow.com/users/577812", "pm_score": 4, "selected": false, "text": "Proxy.newProxyInstance(\n ClassLoader.getSystemClassLoader(),\n new Class < ? >[] {MyInterface.class},\n new InvocationHandler() {\n // (...)\n});\n Proxy.newProxyInstance(\n this.getClass().getClassLoader(), // here is the trick\n new Class < ? >[] {MyInterface.class},\n new InvocationHandler() {\n // (...)\n});\n Bootstrap\n |\n System\n |\n Common\n / \\\n Webapp1 Webapp2 ... \n" }, { "answer_id": 65004457, "author": "malloc32", "author_id": 3804377, "author_profile": "https://Stackoverflow.com/users/3804377", "pm_score": 0, "selected": false, "text": "@Autowired\nprivate ResourceLoader resourceLoader;\n\n....\nClassLoader classLoader = resourceLoader.getClassLoader();\n...\n\n\nProxy.newProxyInstance(\n classLoader, //for example...\n new Class < ? >[] {MyInterface.class},\n new InvocationHandler() {\n // (...)\n});\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,216
<p>What are the lesser-known but useful features of the Haskell programming language. (I understand the language itself is lesser-known, but work with me. Even explanations of the simple things in Haskell, like defining the Fibonacci sequence with one line of code, will get upvoted by me.) </p> <ul> <li>Try to limit answers to the Haskell core</li> <li>One feature per answer</li> <li>Give an example and short description of the feature, not just a link to documentation</li> <li>Label the feature using bold title as the first line</li> </ul>
[ { "answer_id": 212014, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 4, "selected": false, "text": "let {\n x = 40;\n y = 2\n } in\n x + y\n let { x = 40; y = 2 } in x + y\n let x = 40\n y = 2\n in x + y\n" }, { "answer_id": 212103, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 4, "selected": false, "text": "main = print (1 +++ 2 *** 3)\n\ninfixr 6 +++\ninfixr 7 ***,///\n\n(+++) :: Int -> Int -> Int\na +++ b = a + 2*b\n\n(***) :: Int -> Int -> Int\na *** b = a - 4*b\n\n(///) :: Int -> Int -> Int\na /// b = 2*a - 3*b\nOutput: -19\n main = print (a `foo` b)\n\nfoo :: Int -> Int -> Int\nfoo a b = a + b\n infixr 4 `foo`\n" }, { "answer_id": 212131, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 4, "selected": false, "text": "seq ($!) main = print \"hi \" `seq` print \"there\"\n main = foo (error \"explode!\")\n where foo _ = print \"ignored\"\n seq main = error \"first\" `seq` print \"impossible to print\"\n main = seq (error \"first\") (print \"impossible to print\")\n seq [1..] main = [1..] `seq` print \"done\"\n" }, { "answer_id": 212767, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "fib@(1:tfib) = 1 : 1 : [ a+b | (a,b) <- zip fib tfib ]\n take 10 fib\n take 10 (map (\\x -> x+1) fib)\n" }, { "answer_id": 213229, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "concat $ map f list\nconcatMap f list\nlist >>= f\n concat :: [[a]] -> [a]\n concat map :: (a -> b) -> [a] -> [b]\n map concatMap :: (a -> [b]) -> [a] -> [b]\n concatMap (.) concat . map class Monad m where\n (>>=) :: m a -> (a -> m b) -> m b\n return :: a -> m a\n Monad >>= do [] Monad [] m instance Monad [] where\n (>>=) :: [a] -> (a -> [b]) -> [b]\n return :: a -> [a]\n Monad return a >>= f == f a\nma >>= (\\a -> return a) == ma\n(ma >>= f) >>= g == ma >>= (\\a -> f a >>= g)\n instance Monad [] where\n (>>=) = concatMap\n return = (:[])\n\nreturn a >>= f == [a] >>= f == concatMap f [a] == f a\nma >>= (\\a -> return a) == concatMap (\\a -> [a]) ma == ma\n(ma >>= f) >>= g == concatMap g (concatMap f ma) == concatMap (concatMap g . f) ma == ma >>= (\\a -> f a >>= g)\n Monad [] double x = [x,x]\nmain = do\n print $ map double [1,2,3]\n -- [[1,1],[2,2],[3,3]]\n print . concat $ map double [1,2,3]\n -- [1,1,2,2,3,3]\n print $ concatMap double [1,2,3]\n -- [1,1,2,2,3,3]\n print $ [1,2,3] >>= double\n -- [1,1,2,2,3,3]\n" }, { "answer_id": 213426, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "Prelude (.) g . f f g import Control.Arrow g . f\nf >>> g\n Control.Arrow instance Arrow (->)" }, { "answer_id": 213428, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "(.) ($) Prelude f (g (h x))\nf $ g $ h x\nf . g $ h x\nf . g . h $ x\n flip map (\\a -> {- some long expression -}) list\nflip map list $ \\a ->\n {- some long expression -}\n" }, { "answer_id": 213431, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "{- inside a comment,\n {- inside another comment, -}\nstill commented! -}\n" }, { "answer_id": 213434, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "Prelude otherwise = True fac n\n | n < 1 = 1\n | otherwise = n * fac (n-1)\n" }, { "answer_id": 213436, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "-- factorial can be written, using the strict HOF foldl':\nfac n = Data.List.foldl' (*) 1 [1..n]\n-- there's a shortcut for that:\nfac n = product [1..n]\n-- and it can even be written pointfree:\nfac = product . enumFromTo 1\n" }, { "answer_id": 213438, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "module Foo (module Bar, blah) -- this is module Foo, export everything that Bar expored, plus blah\n\nimport qualified Some.Long.Name as Short\nimport Some.Long.Name (name) -- can import multiple times, with different options\n\nimport Baz hiding (blah) -- import everything from Baz, except something named 'blah'\n" }, { "answer_id": 213441, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 6, "selected": true, "text": "{-# LANGUAGE ExistentialQuantification #-}\ndata Foo = forall a. Foo a\nignorefoo f = 1 where Foo a = f\n" }, { "answer_id": 213956, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": false, "text": "if then else ?: if True ? x = const x\nFalse ? _ = id\n (?) (a ? b $ c) == (if a then b else c)\n -- prints \"I'm alive! :)\"\nmain = True ? putStrLn \"I'm alive! :)\" $ error \"I'm dead :(\"\n" }, { "answer_id": 750002, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 4, "selected": false, "text": "{-# LANGUAGE GADTs #-}\nmodule Exp\nwhere\n\ndata Exp a where\n Num :: (Num a) => a -> Exp a\n Bool :: Bool -> Exp Bool\n Plus :: (Num a) => Exp a -> Exp a -> Exp a\n If :: Exp Bool -> Exp a -> Exp a -> Exp a \n Lt :: (Num a, Ord a) => Exp a -> Exp a -> Exp Bool\n Lam :: (a -> Exp b) -> Exp (a -> b) -- higher order abstract syntax\n App :: Exp (a -> b) -> Exp a -> Exp b\n -- deriving (Show) -- failse\n\neval :: Exp a -> a\neval (Num n) = n\neval (Bool b) = b\neval (Plus e1 e2) = eval e1 + eval e2\neval (If p t f) = eval $ if eval p then t else f\neval (Lt e1 e2) = eval e1 < eval e2\neval (Lam body) = \\x -> eval $ body x\neval (App f a) = eval f $ eval a\n\ninstance Eq a => Eq (Exp a) where\n e1 == e2 = eval e1 == eval e2\n\ninstance Show (Exp a) where\n show e = \"<exp>\" -- very weak show instance\n\ninstance (Num a) => Num (Exp a) where\n fromInteger = Num\n (+) = Plus\n" }, { "answer_id": 954901, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 4, "selected": false, "text": "five :: Int\nJust five = Just 5\n\na, b, c :: Char\n[a,b,c] = \"abc\"\n fromJust head" }, { "answer_id": 1035661, "author": "yairchu", "author_id": 40916, "author_profile": "https://Stackoverflow.com/users/40916", "pm_score": 5, "selected": false, "text": "cabal install hoogle $ hoogle \"Num a => [a] -> a\"\nPrelude product :: Num a => [a] -> a\nPrelude sum :: Num a => [a] -> a\n\n$ hoogle \"[Maybe a] -> [a]\"\nData.Maybe catMaybes :: [Maybe a] -> [a]\n\n$ hoogle \"Monad m => [m a] -> m [a]\"\nPrelude sequence :: Monad m => [m a] -> m [a]\n\n$ hoogle \"[a] -> [b] -> (a -> b -> c) -> [c]\"\nPrelude zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n" }, { "answer_id": 1088316, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 5, "selected": false, "text": "fmap :: Functor f => (a -> b) -> f a -> f b\n seq" }, { "answer_id": 1088522, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 3, "selected": false, "text": "let ~(Just x) = someExpression\n" }, { "answer_id": 1088546, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 3, "selected": false, "text": " fibs = 0 : 1 : [ a + b | a <- fibs | b <- tail fibs ]\n" }, { "answer_id": 1092209, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 3, "selected": false, "text": "fibs = 1 : 1 : zipWith (+) fibs (tail fibs)\n val fun where \\x -> f x" }, { "answer_id": 1536510, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 4, "selected": false, "text": "let 5 = 6 in ..." }, { "answer_id": 1901118, "author": "beerboy", "author_id": 231299, "author_profile": "https://Stackoverflow.com/users/231299", "pm_score": 3, "selected": false, "text": "alphabet :: String\nalphabet = ['A' .. 'Z']\n data MyEnum = A | B | C deriving(Eq, Show, Enum)\n\nmain = do\n print $ [A ..] -- prints \"[A,B,C]\"\n print $ map fromEnum [A ..] -- prints \"[0,1,2]\"\n" }, { "answer_id": 1901146, "author": "beerboy", "author_id": 231299, "author_profile": "https://Stackoverflow.com/users/231299", "pm_score": 4, "selected": false, "text": "foo : bar : baz : _ = [100 ..] -- foo = 100, bar = 101, baz = 102\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
211,219
<p>Having some issues loading files from media hosting into swf shell (a swf loading swfs as assets). Mp3s and images work fine but a swf never loads. Code is like:</p> <p>swfpath = "<a href="http://555.55.555.555/vir_dir/swf/N000001.swf" rel="nofollow noreferrer">http://555.55.555.555/vir_dir/swf/N000001.swf</a>" movie_loader.loadMovie(swfpath, "mc_swfimage");</p> <p>if the swfpath is set to "swf/N00001.swf" it loads fine and if I point firefox towards the http link above (555s as placeholders here) it opens the file in firefox just fine.</p> <p>Is it some security or does loadMovie not handle http paths?</p> <p>Note it works fine if I do loadAudio with the same thing pointing to an MP3.</p>
[ { "answer_id": 217664, "author": "Ronnie Liew", "author_id": 1987, "author_profile": "https://Stackoverflow.com/users/1987", "pm_score": 2, "selected": true, "text": "http://mysubdomain.mydomain.com/fu/bar/ http://mysubdomin.mydomain.com/crossdomain.xml" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
211,236
<p>Since we cannot setup Eclipse's RSE to use at the tool for remote editing, I have installed <a href="http://www.cis.upenn.edu/~bcpierce/unison/docs.html" rel="nofollow noreferrer">Unison</a>. But how can I get Eclipse to automatically run unison on every file save? Is there an eclipse plugin available for this?</p> <p>TIA</p>
[ { "answer_id": 271641, "author": "javamonkey79", "author_id": 27657, "author_profile": "https://Stackoverflow.com/users/27657", "pm_score": 3, "selected": false, "text": "@Override\npublic void start( final BundleContext context ) throws Exception {\n super.start( context );\n plugin = this;\n\n ICommandService commandService = (ICommandService)plugin.getWorkbench().getService( ICommandService.class );\n commandService.addExecutionListener( new IExecutionListener() {\n\n public void notHandled( final String commandId, final NotHandledException exception ) {}\n\n public void postExecuteFailure( final String commandId, final ExecutionException exception ) {}\n\n public void postExecuteSuccess( final String commandId, final Object returnValue ) {\n if ( commandId.equals( \"org.eclipse.ui.file.save\" ) ) {\n // add in your action here...\n // personally, I would use a custom preference page, \n // but hard coding would work ok too\n }\n }\n\n public void preExecute( final String commandId, final ExecutionEvent event ) {}\n\n } );\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14351/" ]
211,237
<p>C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes).</p> <p>But, the order of initialization of variables, is undefined across different compilation units.</p> <p>Where can I see some explanations about this order for gcc and MSVC (I know that relying on that is a very bad idea - it is just to understand the problems that we may have with legacy code when moving to new GCC major and different OS)?</p>
[ { "answer_id": 211307, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": true, "text": "main()" }, { "answer_id": 211314, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "init_priority class Thingy\n{\npublic:\n Thingy(char*p) {printf(p);}\n};\n\nThingy a(\"A\");\nThingy b(\"B\");\nThingy c(\"C\");\n Thingy a __attribute__((init_priority(300))) (\"A\");\nThingy b __attribute__((init_priority(200))) (\"B\");\nThingy c __attribute__((init_priority(400))) (\"C\");\n" }, { "answer_id": 62896355, "author": "Moritz", "author_id": 6783666, "author_profile": "https://Stackoverflow.com/users/6783666", "pm_score": 2, "selected": false, "text": "// Foo.h\nclass Foo {\n public:\n Foo() {}\n\n static bool insertIntoBar(int number);\n\n private:\n static std::vector<int>& getBar();\n};\n\n// Foo.cpp\nstd::vector<int>& Foo::getBar() {\n static std::vector<int> bar;\n return bar;\n}\n\nbool Foo::insertIntoBar(int number) {\n getBar().push_back(number);\n return true;\n}\n\n// A.h\nclass A {\n public:\n A() {}\n\n private:\n static bool a1;\n};\n\n// A.cpp\nbool A::a1 = Foo::insertIntoBar(22);\n bool A::a1 Foo::insertIntoBar(22) Foo::getBar() std::vector<int> static std::vector<int> bar Foo class bar insertIntoBar() insertIntoBar() std::vector<int>" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18174/" ]
211,241
<p>My current solution for renaming the project folder is:</p> <ul> <li>Remove the project from the solution.</li> <li>Rename the folder outside Visual Studio.</li> <li>Re-add the project to the solution.</li> </ul> <p>Is there a better way?</p>
[ { "answer_id": 211268, "author": "rabashani", "author_id": 10977, "author_profile": "https://Stackoverflow.com/users/10977", "pm_score": 7, "selected": false, "text": "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Shani.Commands.Impl\", \"Shani.Commands.Impl\\Shani.Commands.Impl.csproj\", \"{747CFA4B-FC83-419A-858E-5E2DE2B948EE}\" Impl\\Shani.Commands.Impl\\Shani.Commands.Impl.csproj" }, { "answer_id": 224788, "author": "andersjanmyr", "author_id": 1740, "author_profile": "https://Stackoverflow.com/users/1740", "pm_score": 11, "selected": true, "text": ".*proj .sln AssemblyProductAttribute AssemblyDescriptionAttribute AssemblyTitleAttribute" }, { "answer_id": 3099493, "author": "Robo A GoGo", "author_id": 373953, "author_profile": "https://Stackoverflow.com/users/373953", "pm_score": 2, "selected": false, "text": ".sln .sln .sln" }, { "answer_id": 3146875, "author": "CRice", "author_id": 55693, "author_profile": "https://Stackoverflow.com/users/55693", "pm_score": 4, "selected": false, "text": "<RootNamespace>SomeProjectName</RootNamespace>\n<AssemblyName>SomeProjectName</AssemblyName>\n" }, { "answer_id": 18413296, "author": "Etan", "author_id": 151706, "author_profile": "https://Stackoverflow.com/users/151706", "pm_score": 0, "selected": false, "text": "./path/to/pro/ject/YourProject/YourProject.**proj\n ject ./path/to/pro/ject/YourProject.**proj\n ./path/to/pro/ject/ject.**proj\n ./path/to/pro/ject/YourProject.**proj\n" }, { "answer_id": 33195945, "author": "wired00", "author_id": 629222, "author_profile": "https://Stackoverflow.com/users/629222", "pm_score": 7, "selected": false, "text": ".sln fu\\bar.csproj bar\\bar.csproj" }, { "answer_id": 45905249, "author": "Valkyrias", "author_id": 8428374, "author_profile": "https://Stackoverflow.com/users/8428374", "pm_score": 2, "selected": false, "text": "' Script parameters'\nSolution = \"Rename_Visual_Studio_Project\" '.sln'\nProject = \"Rename_Visual_Studio_Project\" '.csproj'\nNewProject = \"SUCCESS\"\n\nConst ForReading = 1\nConst ForWriting = 2\n\nSet objFso = CreateObject(\"Scripting.FileSystemObject\")\nscriptDirr = objFso.GetParentFolderName(wscript.ScriptFullName)\n\n' Rename the all project references in the .sln file'\nSet objFile = objFso.OpenTextFile(scriptDirr + \"\\\" + Solution + \".sln\", ForReading)\nfileText = objFile.ReadAll\nnewFileText = Replace(fileText, Project, NewProject)\nSet objFile = objFSO.OpenTextFile(scriptDirr + \"\\\" + Solution + \".sln\", ForWriting)\nobjFile.WriteLine(newFileText)\nobjFile.Close\n\n' Rename the .csproj file'\nobjFso.MoveFile scriptDirr + \"\\\" + Project + \"\\\" + Project + \".csproj\", scriptDirr + \"\\\" + Project + \"\\\" + NewProject + \".csproj\"\n\n' Rename the folder of the .csproj file'\nobjFso.MoveFolder scriptDirr + \"\\\" + Project, scriptDirr + \"\\\" + NewProject\n" }, { "answer_id": 51897557, "author": "ivke", "author_id": 6533764, "author_profile": "https://Stackoverflow.com/users/6533764", "pm_score": 3, "selected": false, "text": "git mv <old_folder_name> <new_folder_name>\n Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"<Project name>\", \"<path-to-project>\\<project>.csproj\"\n" }, { "answer_id": 63741288, "author": "Modern Ronin", "author_id": 1946186, "author_profile": "https://Stackoverflow.com/users/1946186", "pm_score": 2, "selected": false, "text": "dotnet tool install -g ModernRonin.ProjectRenamer renameproject <oldName> <newName>" }, { "answer_id": 66394207, "author": "Elias Prado", "author_id": 9661008, "author_profile": "https://Stackoverflow.com/users/9661008", "pm_score": 2, "selected": false, "text": "right-click > rename" }, { "answer_id": 70630063, "author": "usr", "author_id": 122718, "author_profile": "https://Stackoverflow.com/users/122718", "pm_score": 0, "selected": false, "text": ".csproj" }, { "answer_id": 71157865, "author": "Beefcake", "author_id": 13768310, "author_profile": "https://Stackoverflow.com/users/13768310", "pm_score": 0, "selected": false, "text": "Project -> Export Template... -> Project Template -> Finish File -> New Project -> Find the template -> Give it the name you want -> Add to existing solution or just as new" }, { "answer_id": 72025102, "author": "KushalSeth", "author_id": 4393351, "author_profile": "https://Stackoverflow.com/users/4393351", "pm_score": 2, "selected": false, "text": "TemplateServiceSolution UserServiceSolution TemplateService UserService namespace TemplateService namespace UserService using TemplateService using UserService launchsettings.json launchsettings.json TemplateService UserService TemplateService UserService" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1740/" ]
211,243
<p>I have code looking something like this:</p> <pre><code>$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory $hash = md5($data); $query = "INSERT INTO some_table SET BlobData = '" . mysql_real_escape_string($data) . "', BlobHash = '$hash' "; mysql_query($query); </code></pre> <p>I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.</p> <p>Is there anything more efficient than the following solution?</p> <pre><code>$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory $hash = md5($data); $query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'"; mysql_query(sprintf($query, mysql_real_escape_string($data))); </code></pre>
[ { "answer_id": 211265, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 0, "selected": false, "text": "ob_start();\necho 'INSERT INTO some_table SET BlobData = \\'', mysql_real_escape_string( $data ), '\\', BlobHash = \\'', $hash, '\\'';\nmysql_query( ob_get_clean() );\n" }, { "answer_id": 211271, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": -1, "selected": false, "text": " $id = 1337;\n$h = fopen(\"path/to/file.ext\", \"r\");\nwhile (!feof($h)) \n {\n $buffer = fread($h, 4096);\n $sql = \"UPDATE table SET my_field = CONCAT(my_field, '\" . mysql_real_escape_string($buffer) . \"') WHERE Id = \" . $id;\n mysql_query($sql);\n }\n" }, { "answer_id": 214794, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": true, "text": "md5() md5_file() md5 md5_file exec() md5sum MD5() exec md5_file mysql_real_escape_string mysqli_stmt::send_long_data md5_file exec" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
211,260
<p>No extracted data output to data2.txt? What goes wrong to the code?</p> <p><strong>MyFile.txt</strong></p> <pre><code>ex1,fx2,xx1 mm1,nn2,gg3 EX1,hh2,ff7 </code></pre> <p>This is my desired output in data2.txt:</p> <pre><code>ex1,fx2,xx1 EX1,hh2,ff7 </code></pre> <p><br></p> <pre><code>#! /DATA/PLUG/pvelasco/Softwares/PERLINUX/bin/perl -w my $infile ='My1.txt'; my $outfile ='data2.txt'; open IN, '&lt;', $infile or die "Cant open $infile:$!"; open OUT, '&gt;', $outfile or die "Cant open $outfile:$!"; while (&lt;IN&gt;) { if (m/EX$HF|ex$HF/) { print OUT $_, "\n"; print $_; } } close IN; close OUT; </code></pre>
[ { "answer_id": 211269, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "My1.txt MyFile.txt , \"\\n\"" }, { "answer_id": 211279, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 3, "selected": false, "text": "m/EX$HF|ex$HF/\n use strict;\n" }, { "answer_id": 211282, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "while (<IN>) {\n if (m/^(EX|ex)\\d.*/) { \n print OUT \"$_\"; \n print $_; \n }\n}\n" }, { "answer_id": 213165, "author": "Berserk", "author_id": 26313, "author_profile": "https://Stackoverflow.com/users/26313", "pm_score": 1, "selected": false, "text": "open(my $inhandle, '<', $infile) or die \"Cant open $infile: $!\";\nopen(my $outhandle, '>', $outfile) or die \"Cant open $outfile: $!\";\n\nwhile(my $line = <$inhandle>) { \n\n # Assumes that ex, Ex, eX, EX all are valid first characters\n if($line =~ m{^ex}i) { # or if(lc(substr $line, 0 => 2) eq 'ex') {\n print { $outhandle } $line; \n print $line;\n }\n}\n" }, { "answer_id": 214736, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 2, "selected": false, "text": "grep -i ^ex < My1.txt > data2.txt\n perl -ne '/^ex/i && print' < My1.txt > data2.txt\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
211,278
<p>Is there a Maven archetype that will generate the same scaffolding as <code>maven-archetype-quickstart</code>, but will in addition create the basic project site layout generated by <code>maven-archetype-site</code>? Or do I always have to run each in sequence?</p>
[ { "answer_id": 721930, "author": "paulgreg", "author_id": 3122, "author_profile": "https://Stackoverflow.com/users/3122", "pm_score": 1, "selected": false, "text": "mvn site" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
211,299
<p>I have implemented some table-per-type inheritance in my data model (basically have a <code>BaseEntity</code> type with all the base information for my items and a <code>Employer</code> type that inherits from the <code>BaseEntity</code> item). Everything appears to be set up correctly and when using the Entities (either via ADO.net Data Services or via Linq to Entities) I can see the <code>Employer</code> type and things appear to be fine. The issue starts when I create a new <code>Employer</code> entity and attempt to save it.</p> <p>On the context that doesn't appear to be an <code>.AddToEmployer</code> item (only and <code>AddObject</code> or <code>AddToBaseEntity</code>).</p> <p>If I use <code>AddObject("Employer", NewEmployer)</code> I get and error message of:</p> <blockquote> <p>The EntitySet name 'DataEntities.Employer' could not be found.</p> </blockquote> <p>If I use <code>AddToBaseEntity(NewEmployer)</code> I get an error message of:</p> <blockquote> <p>Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements orstore generated values.</p> </blockquote> <p>Have I missed a step in setting up the inheritance? Is there some specific way to save objects that are inherited? What am I doing wrong? I assume that the basic issue is that I should have an <code>AddToEmployer</code>, what do I need to do to get that exposed? It seems odd that it is not an option since I can see the Employer type on the client side and can do things such as:</p> <p><code>var NewEmployer = new Employer()</code> - which seems to suggest that I can see the Employer type fine.</p>
[ { "answer_id": 369491, "author": "Phani Raj", "author_id": 46455, "author_profile": "https://Stackoverflow.com/users/46455", "pm_score": 3, "selected": false, "text": "ResolveName ResolveType ResolveName public class Employee {\n public int EmployeeID {get;set;}\n public string EmployeeName {get;set;}\n}\n\npublic class Manager:Employee {\n public List<int> employeesWhoReportToMe {get;set;}\n}\n context.AddObject(\"Employees\",ManagerInstance ); <-- add manager instance to the employees set.\ncontext.SaveChanges();\n context.ResolveName = delegate(Type entityType){\n //do what you have to do to resolve the type to the right type of the entity on the server\n return entityType.FullName;\n}\n context.ResolveType = delegate(string entitySetName){\n //do what you have to do to convert the entitysetName to a type that the client understands\n return Type.GetType(entitySetName);\n}\n" }, { "answer_id": 4520699, "author": "JohnMetta", "author_id": 74919, "author_profile": "https://Stackoverflow.com/users/74919", "pm_score": 1, "selected": false, "text": "public ContextHelper\n{\n …\n _context = ModelEntities();\n\n public T Create<T>() where T : class\n {\n // Create a new context\n _context = new ModelEntities();\n\n // Create the object using the context (can create outside of context too, FYI)\n T obj = _context.CreateObject<T>();\n\n // Somewhat kludgy workaround for determining if the object is\n // inherited from the base object or not, and adding it to the context's\n // object list appropriately. \n if (obj is BaseObject)\n {\n _context.AddObject(\"BaseObjects\", obj);\n }\n else\n {\n ObjectSet<T> set = _context.CreateObjectSet<T>();\n set.AddObject(obj);\n }\n\n return obj;\n }\n …\n}\n class ObjectOne : BaseObject {}\nclass ObjectTwo {}\n ContextHelper ch = ContextHelper()\nObjectOne inherited = ch.Create<ObjectOne>();\nObjectTwo toplevel = ch.Create<ObjectTwo>();\n…\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25719/" ]
211,311
<p>I want to find out if length property for Java arrays is an int/long or something else.</p>
[ { "answer_id": 211324, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 2, "selected": false, "text": "int" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28836/" ]
211,319
<p>i wonder if it is possible to cascade converters when using wpf databinding. e.g. something like </p> <pre><code>&lt;SomeControl Visibility="{Binding Path=SomeProperty, Converter={StaticResource firstConverter}, Converter={StaticResource secondConverter}}"/&gt; </code></pre> <p>is it possible at all or do i have to create a custom converter that combines the functionality of converter A and B?</p>
[ { "answer_id": 211812, "author": "Brad Leach", "author_id": 708, "author_profile": "https://Stackoverflow.com/users/708", "pm_score": 4, "selected": false, "text": "<local:ValueConverterGroup x:Key=\"statusDisplayNameGroup\">\n <local:IntegerStringToProcessingStateConverter />\n <local:EnumToDisplayNameConverter />\n</local:ValueConverterGroup> \n <TextBlock Text=\"{Binding XPath=@Status, \n Converter={StaticResource statusDisplayNameGroup}}\" />\n" }, { "answer_id": 211856, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 4, "selected": true, "text": "<SomeControl>\n <SomeControl.Visibility>\n <MultiBinding Converter=\"{StaticResource combiningConverter}\">\n <Binding Path=\"SomeProperty\" Converter=\"{StaticResource firstConverter}\"/>\n <Binding Path=\"SomeProperty\" Converter=\"{StaticResource secondConverter}\"/>\n </MultiBinding>\n </SomeControl.Visibility>\n</SomeControl>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20227/" ]
211,329
<p>What is a fast way to select a random row from a large mysql table?</p> <p>I'm working in php, but I'm interested in any solution even if it's in another language.</p>
[ { "answer_id": 142311, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "SELECT * FROM table \n WHERE id=\n (FLOOR(RAND() * \n (SELECT COUNT(*) FROM table)\n )\n );\n" }, { "answer_id": 142318, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "ORDER BY RANDOM() SELECT SELECT * FROM `foo` WHERE `foo_rand` >= {some random value} LIMIT 1\n" }, { "answer_id": 211331, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "SELECT * from TABLE order by RAND() LIMIT 1\n" }, { "answer_id": 211349, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 0, "selected": false, "text": "sql \"select id from table\"\nstore result in list\nn = random(size of list)\nsql \"select * from table where id=\" + list[n]\n id" }, { "answer_id": 211388, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "SELECT name\n FROM random AS r1 JOIN\n (SELECT (RAND() *\n (SELECT MAX(id)\n FROM random)) AS id)\n AS r2\n WHERE r1.id >= r2.id\n ORDER BY r1.id ASC\n LIMIT 1;\n" }, { "answer_id": 213242, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "SET @r := (SELECT ROUND(RAND() * (SELECT COUNT(*) FROM mytable)));\nSET @sql := CONCAT('SELECT * FROM mytable LIMIT ', @r, ', 1');\nPREPARE stmt1 FROM @sql;\nEXECUTE stmt1;\n" }, { "answer_id": 214620, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": -1, "selected": false, "text": "SET @COUNTER=SELECT COUNT(*) FROM your_table;\n\nSELECT PrimaryKey\nFROM your_table\nLIMIT 1 OFFSET (RAND() * @COUNTER);\n CREATE TABLE Aux(\n MyPK INT AUTO_INCREMENT,\n PrimaryKey INT\n);\n\nSET @MaxPK = (SELECT MAX(MyPK) FROM Aux);\nSET @RandPK = CAST(RANDOM() * @MaxPK, INT)\nSET @PrimaryKey = (SELECT PrimaryKey FROM Aux WHERE MyPK = @RandPK);\n SET @delta = CAST(@RandPK/10, INT);\n\nSET @PrimaryKey = (SELECT PrimaryKey\n FROM Aux\n WHERE MyPK BETWEEN @RandPK - @delta AND @RandPK + @delta\n LIMIT 1);\n" }, { "answer_id": 382429, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT * FROM the_table WHERE primary_key >= $randNr\n SELECT primary_key FROM the_table\n SELECT * FROM the_table WHERE primary_key = rand_number\n SELECT * FROM the_table mysql_num_rows() mysql_data_seek()" }, { "answer_id": 668191, "author": "Dipin", "author_id": 67976, "author_profile": "https://Stackoverflow.com/users/67976", "pm_score": 0, "selected": false, "text": "SELECT name\n FROM random AS r1 JOIN\n (SELECT (RAND() *\n (SELECT MAX(id)\n FROM random)) AS id)\n AS r2\n WHERE r1.id >= r2.id\n ORDER BY r1.id ASC\n LIMIT 1;\n" }, { "answer_id": 780893, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SELECT * FROM\n`words` AS r1 JOIN \n(SELECT MAX(`WordID`) as wid_c FROM `words`) as tmp1\nWHERE r1.WordID >= (SELECT (RAND() * tmp1.wid_c) AS id) LIMIT n\n" }, { "answer_id": 2945922, "author": "parm.95", "author_id": 354850, "author_profile": "https://Stackoverflow.com/users/354850", "pm_score": 1, "selected": false, "text": "SELECT MIN(id) AS minId, MAX(id) AS maxId FROM table WHERE 1\n\n$randId=mt_rand((int)$row['minId'], (int)$row['maxId']);\n\nSELECT id,name,... FROM table WHERE id=$randId LIMIT 1\n" }, { "answer_id": 10825269, "author": "bikedorkseattle", "author_id": 480735, "author_profile": "https://Stackoverflow.com/users/480735", "pm_score": 0, "selected": false, "text": "SELECT * FROM products WHERE RAND()<=(5/(SELECT COUNT(*) FROM products)) LIMIT 1\n SELECT * FROM products WHERE RAND()<=(100/(SELECT COUNT(*) FROM pt_products)) AND discount<.2 LIMIT 1\n" }, { "answer_id": 21273291, "author": "proggL", "author_id": 3221782, "author_profile": "https://Stackoverflow.com/users/3221782", "pm_score": -1, "selected": false, "text": "SELECT DISTINCT * FROM yourTable WHERE 4 = 4 LIMIT 1;" }, { "answer_id": 21952313, "author": "Zillur", "author_id": 3260963, "author_profile": "https://Stackoverflow.com/users/3260963", "pm_score": 1, "selected": false, "text": "select a.* from random_data a, (select max(id)*rand() randid from random_data) b\n where a.id >= b.randid limit 1;\n" }, { "answer_id": 28689308, "author": "MANOJ", "author_id": 3489584, "author_profile": "https://Stackoverflow.com/users/3489584", "pm_score": 0, "selected": false, "text": "SELECT user_firstname ,\nCOUNT(DISTINCT usr_fk_id) cnt\nFROM userdetails \nGROUP BY usr_fk_id \nORDER BY cnt ASC \nLIMIT 1\n" }, { "answer_id": 30262044, "author": "António Almeida", "author_id": 1192479, "author_profile": "https://Stackoverflow.com/users/1192479", "pm_score": 0, "selected": false, "text": "COUNT(*) MAX(id) logTime();\nquery(\"SELECT COUNT(id) FROM tbl\");\nlogTime();\nquery(\"SELECT MAX(id) FROM tbl\");\nlogTime();\nquery(\"SELECT id FROM tbl ORDER BY id DESC LIMIT 1\");\nlogTime();\n 36.8418693542479 ms 0.241041183472 ms 0.216960906982 ms SELECT FLOOR(RAND() * (\n SELECT id FROM tbl ORDER BY id DESC LIMIT 1\n)) n FROM tbl LIMIT 1\n\n...\nSELECT * FROM tbl WHERE id = $result;\n" }, { "answer_id": 35960336, "author": "Yousef Altaf", "author_id": 454012, "author_profile": "https://Stackoverflow.com/users/454012", "pm_score": 0, "selected": false, "text": "SELECT * FROM myTable WHERE RAND()<(SELECT ((30/COUNT(*))*10) FROM myTable) ORDER BY RAND() LIMIT 30;\n" }, { "answer_id": 43101955, "author": "RandomGuest", "author_id": 7787854, "author_profile": "https://Stackoverflow.com/users/7787854", "pm_score": 0, "selected": false, "text": "<?\n\n$sqlConnect = mysqli_connect('localhost','username','password','database');\n\nfunction rando($data,$find,$max = '0'){\n global $sqlConnect; // Set as mysqli connection variable, fetches variable outside of function set as GLOBAL\n if($data == 's1'){\n $query = mysqli_query($sqlConnect, \"SELECT * FROM `yourtable` ORDER BY `id` DESC LIMIT {$find},1\");\n\n $fetched_data = mysqli_fetch_assoc($query);\n if(mysqli_num_rows($fetched_data>0){\n return $fetch_$data;\n }else{\n rando('','',$max); // Start Over the results returned nothing\n }\n }else{\n if($max != '0'){\n $irand = rand(0,$max); \n rando('s1',$irand,$max); // Start rando with new random ID to fetch\n }else{\n\n $query = mysqli_query($sqlConnect, \"SELECT `id` FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1\");\n $fetched_data = mysqli_fetch_assoc($query);\n $max = $fetched_data['id'];\n $irand = rand(1,$max);\n rando('s1',$irand,$max); // Runs rando against the random ID we have selected if data exist will return\n }\n }\n }\n\n $your_data = rando(); // Returns listing data for a random entry as a ASSOC ARRAY\n?>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
211,335
<p>I have a swf file that is not controlled by me. The swf expects a javascript call to set some variables after initialization. </p> <p>The swf is embedded using the swfobject and I'm trying to call the as function right after the embed. This appears to be too soon because I get an error. Everything else should be fine since calling the as function manually via firebug does not produce the error.</p> <p>So the question is how do I call the function when the embed is complete?</p>
[ { "answer_id": 211489, "author": "jcoder", "author_id": 417292, "author_profile": "https://Stackoverflow.com/users/417292", "pm_score": 1, "selected": false, "text": "window.onload = function() {\n // your code here \n}\n" }, { "answer_id": 217690, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 0, "selected": false, "text": "if (typeof yourFunctionName == 'function') {\n yourFunctionName();\n}\n while" }, { "answer_id": 2956719, "author": "Fenton", "author_id": 75525, "author_profile": "https://Stackoverflow.com/users/75525", "pm_score": 0, "selected": false, "text": "MovieLoaded() function MovieLoaded() {\n doSomething();\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22673/" ]
211,336
<p>How do you stay up-to-date when it comes to new software versions? Above all, I mean minor updates (new version for your Joomla-Installation, forum-software, FTP-Client, ...).</p> <p>Versiontracker, RSS-Feeds, Newsletter... what else? Anyone wrote a script crawling websites for new versions or something similar?</p>
[ { "answer_id": 211343, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "emerge --sync && emerge -p world\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27404/" ]
211,341
<p>We have an Access DB which has a set of local tables and input forms etc. in which a user maintains their data.</p> <p>We also have a SQL DB with the same tables which is used to displays the data in a web search form.</p> <p>What is the best way to allow the user to udate his changes to the SQL db while keeping the working copy local so he can work offline and then push the files when he is happy with new version of the data?</p> <p>My first thought was add the SQL tables as linked tables I could then truncate (access does like that) or delete the content in each table and then do an insert for each table.</p> <p>Can I call a SP from access on the SQL to truncate the tables as I am have problem running deletes</p> <p>I really do want to get it down to the user running a macro/sql call that is repeatable etc.</p> <p>Thanks for your help</p>
[ { "answer_id": 211343, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "emerge --sync && emerge -p world\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3582/" ]
211,345
<p>To use <a href="http://en.wikipedia.org/wiki/Modular_exponentiation" rel="noreferrer">modular exponentiation</a> as you would require when using the <a href="http://en.wikipedia.org/wiki/Fermat_primality_test" rel="noreferrer">Fermat Primality Test</a> with large numbers (100,000+), it calls for some very large calculations.</p> <p>When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values.</p> <pre><code>$x = 62574 * 62574; var_dump($x); // float(3915505476) ... correct var_dump($x % 104659); // int(-72945) ... wtf. </code></pre> <p>Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?</p>
[ { "answer_id": 211371, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": false, "text": "bcmod() var_dump(bcmod(\"$x\", '104659') ); // string(4) \"2968\"\n" }, { "answer_id": 6027015, "author": "K.Sya", "author_id": 756824, "author_profile": "https://Stackoverflow.com/users/756824", "pm_score": 6, "selected": false, "text": " $num1 = \"123456789012345678901234567890\";\n $num2 = \"9876543210\";\n $r = mysql_query(\"Select @sum:=$num1 + $num2\");\n $sumR = mysql_fetch_row($r);\n $sum = $sumR[0];\n" }, { "answer_id": 12435667, "author": "bob", "author_id": 1088866, "author_profile": "https://Stackoverflow.com/users/1088866", "pm_score": 2, "selected": false, "text": "$x = 62574 * 62574;\n\n// Cast to an integer\n$asInt = intval($x);\nvar_dump($asInt);\nvar_dump($asInt % 104659);\n\n// Use use sprintf to convert to integer (%d), which will casts to string\n$asIntStr = sprintf('%d', $x);\nvar_dump($asIntStr);\nvar_dump($asIntStr % 104659);\n" }, { "answer_id": 21509321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "/**\n * @param string $a\n * @param string $b\n * @return string\n */\nfunction terminal_add($a,$b)\n{\n exec('echo \"'.$a.'+'.$b.'\"|bc',$result);\n $ret = \"\";\n foreach($result as $line) $ret .= str_replace(\"\\\\\",\"\",$line);\n return $ret;\n}\n\n// terminal_add(\"123456789012345678901234567890\", \"9876543210\")\n// output: \"123456789012345678911111111100\"\n" }, { "answer_id": 30286733, "author": "gauravparmar", "author_id": 3700385, "author_profile": "https://Stackoverflow.com/users/3700385", "pm_score": 2, "selected": false, "text": "<?php\n $x = gmp_strval(gmp_mul(\"62574\",\"62574\")); // $x=\"3915505476\"\n $mod=gmp_strval(gmp_mod($x,\"104659\")); //$mod=\"2968\"\n\n echo \"x : \".$x.\"<br>\";\n echo \"mod : \".$mod;\n\n /* Output:\n x : 3915505476\n mod : 2968\n */\n?>\n" }, { "answer_id": 58050412, "author": "Mrigank Shekhar", "author_id": 12103098, "author_profile": "https://Stackoverflow.com/users/12103098", "pm_score": 2, "selected": false, "text": "<?php\nfunction add($int1,$int2){\n $int1 = str_pad($int1, strlen($int2), '0', STR_PAD_LEFT);\n $int2 = str_pad($int2, strlen($int1), '0', STR_PAD_LEFT);\n $carry = 0;\n $str = \"\";\n for($i=strlen($int1);$i>0;$i--){\n $var = $int1[$i-1] + $int2[$i-1] + $carry;\n $var = str_pad($var, 2, '0', STR_PAD_LEFT);\n $var = (string) $var;\n $carry = $var[0];\n $str = $str . $var[1];\n }\n $res = strrev($str.$carry);\n echo ltrim($res,\"0\");\n}\nadd($int1,$int2);\n?>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
211,346
<p>I've read a number of books and websites on the subject of TDD, and they all make a lot of sense, especially Kent Beck's book. However, when I try to do TDD myself, i find myself staring at the keyboard wondering how to begin. Is there a process you use? What is your thought process? How do you identify your first tests?</p> <p>The majority of the books on the subject do a great job of describing what TDD is, but not how to <em>practice</em> TDD in real world non-trivial applications. How do you do TDD?</p>
[ { "answer_id": 211362, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 3, "selected": false, "text": "int main(int argc, char *argv[]) {\n int result = 0;\n\n myApp &mw = getApp(); // Singleton method to return main app instance\n if(mw.initialize(argc, argv) == kErrorNone) {\n result = mw.run();\n }\n\n mw.shutdown();\n return(result);\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22912/" ]
211,348
<p>I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.</p> <p>However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:</p> <pre><code>[System.Web.Script.Services.ScriptService] public class _default : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] public string[] UserDetails() { return new string[] { "abc", "def" }; } } </code></pre>
[ { "answer_id": 10214090, "author": "marc", "author_id": 12260, "author_profile": "https://Stackoverflow.com/users/12260", "pm_score": 4, "selected": false, "text": " $.ajax({\n url: \"MyWebService.asmx/MethodName\",\n type: \"POST\",\n contentType: \"application/json\",\n data: JSON.stringify({ searchString: q }),\n success: function (response) { \n },\n error: function (jqXHR, textStatus, errorThrown) {\n alert(textStatus + \": \" + jqXHR.responseText);\n }\n });\n" }, { "answer_id": 13511873, "author": "iCorrect", "author_id": 1844892, "author_profile": "https://Stackoverflow.com/users/1844892", "pm_score": 6, "selected": false, "text": "HttpResponse WebMethod void [System.Web.Script.Services.ScriptService]\n public class WebServiceClass : System.Web.Services.WebService {\n [WebMethod]\n public void WebMethodName()\n {\n HttpContext.Current.Response.Write(\"{property: value}\");\n }\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
211,355
<p>A while ago I had a query that I ran quite a lot for one of my users. It was still being evolved and tweaked but eventually it stablised and ran quite quickly, so we created a stored procedure from it. </p> <p>So far, so normal. </p> <p>The stored procedure, though, was dog slow. No material difference between the query and the proc, but the speed change was massive. </p> <p>[Background, we're running SQL Server 2005.]</p> <p>A friendly local DBA (who no longer works here) took one look at the stored procedure and said "parameter spoofing!" (<strong>Edit:</strong> although it seems that it is possibly also known as 'parameter sniffing', which might explain the paucity of Google hits when I tried to search it out.) </p> <p>We abstracted some of the stored procedure to a second one, wrapped the call to this new inner proc into the pre-existing outer one, called the outer one and, hey presto, it was as quick as the original query. </p> <p>So, what gives? Can someone explain parameter spoofing? </p> <p>Bonus credit for </p> <ul> <li>highlighting how to avoid it </li> <li>suggesting how to recognise possible cause</li> <li>discuss alternative strategies, e.g. stats, indices, keys, for mitigating the situation</li> </ul>
[ { "answer_id": 215785, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 5, "selected": false, "text": "CREATE PROCEDURE uspParameterSniffingAvoidance\n @SniffedFormalParameter int\nAS\nBEGIN\n\n DECLARE @SniffAvoidingLocalParameter int\n SET @SniffAvoidingLocalParameter = @SniffedFormalParameter\n\n --Work w/ @SniffAvoidingLocalParameter in sproc body \n -- ...\n" }, { "answer_id": 215861, "author": "Brent Ozar", "author_id": 26837, "author_profile": "https://Stackoverflow.com/users/26837", "pm_score": 7, "selected": true, "text": "usp_QueryMyDataByState 'Rhode Island'\n usp_QueryMyDataByState 'Texas'\n" }, { "answer_id": 225015, "author": "Jan", "author_id": 25727, "author_profile": "https://Stackoverflow.com/users/25727", "pm_score": 3, "selected": false, "text": "WITH RECOMPILE" }, { "answer_id": 11524368, "author": "katlego.nkosi", "author_id": 1532058, "author_profile": "https://Stackoverflow.com/users/1532058", "pm_score": -1, "selected": false, "text": "exec ('select * from order where order id ='''+ @ordersID')\n select * from order where order id = @ordersID\n nvarchar" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2902/" ]
211,369
<p>I'm writing a MFC app that uses the MS Mappoint OCX. I need to display the locations of people and vehicles on the map and the best of doing this appears to be with Pushpin objects. I have no problem displaying a stock pushpin icon with some text but want to change the icon to a custom designed one. From the limited amount of Mappoint programming info out there it appears the way to do this is to create a symbol object from a symbols object then assign this to a pushpin like this ..</p> <pre><code>CSymbols symbols; CSymbol symbol; symbol=symbols.Add("c:/temp/myicon.ico"); pushpin.put_Symbol(symbol.get_ID()); </code></pre> <p>But the program crashes with a unhandled exception on the symbols.add instruction.</p> <p>Can anyone tell me what I am doing wrong here ? or am I on totally the wrong track ?</p> <p>Thanks for your time</p> <p>Ian</p>
[ { "answer_id": 221651, "author": "IanW", "author_id": 3875, "author_profile": "https://Stackoverflow.com/users/3875", "pm_score": 2, "selected": false, "text": "CSymbols symbols;\nCSymbol symbol;\n\nsymbols=map.get_Symbols();\nsymbol=symbols.Add(\"c:/temp/myicon.ico\");\npushpin.put_Symbol(symbol.get_ID());\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875/" ]
211,376
<p>I've got a big big code base that includes two main namespaces: the engine and the application. </p> <p>The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality operators in the application namespace. </p> <p>When I tried to compile, unrelated but near-by vector3 comparisons failed because it couldn't find an appropriate equality operator. I suspected I was causing a conflict so moved my equality operators into the class I added, and the compile succeeded.</p> <pre><code>// engine.h namespace Engine { class Vector3Impl { ... }; typedef Vector3Impl Vector3; bool operator==(Vector3 const &amp;lhs, Vector3 const &amp;rhs) { ... } } // myfile.cpp #include "engine.h" namespace application { class MyClass { ... }; bool operator==(MyClass const &amp;lhs, MyClass const &amp;rhs) { ... } void myFunc(...) { if ( myClassA == myClassB ) { ... } // builds } void anotherFunc(...) { Engine::Vector3 a, b; ... if ( a == b ) { ... } // fails } } </code></pre> <p>However after thinking about it I can't see why the compile failed. There are no implicit conversions from vector3s to my class or vice-versa, and argument-dependent look-up should be pulling in the equality operator from the engine namespace and matching it.</p> <p>I've tried reproducing this bug in a sample C++ project but that refuses to break. There must be something in the big big code base that is causing this problem, but I'm not sure where to start looking. Something like the opposite of a rogue "using Engine"? Anyone got any ideas?</p>
[ { "answer_id": 211386, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": -1, "selected": false, "text": "bool operator==(Vector3 const &lhs, Vector3 const &rhs) { ... }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801/" ]
211,378
<p>Shell scripts are often used as glue, for automation and simple one-off tasks. What are some of your favorite "hidden" features of the Bash shell/scripting language?</p> <ul> <li>One feature per answer</li> <li>Give an example and short description of the feature, not just a link to documentation</li> <li>Label the feature using bold title as the first line</li> </ul> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/questions/132241/hidden-features-of-c">Hidden features of C</a></li> <li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden features of C#</a></li> <li><a href="https://stackoverflow.com/questions/75538/hidden-features-of-c">Hidden features of C++</a></li> <li><a href="https://stackoverflow.com/questions/102254/hidden-features-of-delphi">Hidden features of Delphi</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></li> <li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden features of Java</a></li> <li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">Hidden features of JavaScript</a></li> <li><a href="https://stackoverflow.com/questions/63998/hidden-features-of-ruby">Hidden features of Ruby</a></li> <li><a href="https://stackoverflow.com/questions/61401/hidden-features-of-php">Hidden features of PHP</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl">Hidden features of Perl</a></li> <li><a href="https://stackoverflow.com/questions/102084/hidden-features-of-vbnet">Hidden features of VB.Net</a></li> </ul>
[ { "answer_id": 211382, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "if [ 2 -lt 3 ]\n then echo \"Numbers are still good!\"\nfi\n if [[ 2 < 3 ]]\n then echo \"Numbers are still good!\"\nfi\n" }, { "answer_id": 211398, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "if [[ $((2+1)) = $((1+2)) ]]\n then echo \"still ok\"\nfi\n" }, { "answer_id": 211406, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "A | B | C\n device=/dev/rmt8\ndd_noise='^[0-9]+\\+[0-9]+ records (in|out)$'\nexec 3>&1\nstatus=`((dd if=$device ibs=64k 2>&1 1>&3 3>&- 4>&-; echo $? >&4) |\n egrep -v \"$dd_noise\" 1>&2 3>&- 4>&-) 4>&1`\nexit $status;\n" }, { "answer_id": 211410, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "if [[ $(($RANDOM % 6)) = 0 ]]\n then echo \"BANG\"\nelse\n echo \"Try again\"\nfi \n" }, { "answer_id": 211413, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": 4, "selected": false, "text": "bash -x script.sh \n" }, { "answer_id": 211460, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "$ I=foobar\n$ echo ${I/oo/aa} #replacement\nfaabar\n$ echo ${I:1:2} #substring\noo\n$ echo ${I%bar} #trailing substitution\nfoo\n$ echo ${I#foo} #leading substitution\nbar\n" }, { "answer_id": 211525, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "#!/bin/bash\n\narray[0]=\"a string\"\narray[1]=\"a string with spaces and \\\"quotation\\\" marks in it\"\narray[2]=\"a string with spaces, \\\"quotation marks\\\" and (parenthesis) in it\"\n\necho \"There are ${#array[*]} elements in the array.\"\nfor n in \"${array[@]}\"; do\n echo \"element = >>${n}<<\"\ndone\n" }, { "answer_id": 211581, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 3, "selected": false, "text": "bash -n script.sh\n cd -\n" }, { "answer_id": 211913, "author": "Jaime Soriano", "author_id": 28855, "author_profile": "https://Stackoverflow.com/users/28855", "pm_score": 5, "selected": false, "text": "! history !<n> n history ls -l foo bar\ntouch foo bar\n!-2\n !:<n> ls -l foo\ntouch !:2\ncp !:1 bar\n !<n>:<m> touch foo bar\nls -l !:1 !:2\nrm !-2:1 !-2:2\n!-2\n !<n>:<x>-<y> touch boo far\nls -l !:1-2\n ! * ls -l foo bar\nls !*\n ^ !:1 !^ $ ls -l foo bar\ncat !$ > /dev/null\n" }, { "answer_id": 212238, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 2, "selected": false, "text": "let x=\"RANDOM%2**8\"\necho -n \"$x = 0b\"\nfor ((i=8; i>=0; i--)); do\n let n=\"2**i\"\n if (( (x&n) == n )); then echo -n \"1\"\n else echo -n \"0\"\n fi\ndone\necho \"\"\n" }, { "answer_id": 255695, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 2, "selected": false, "text": "> file\n" }, { "answer_id": 377929, "author": "th_in_gs", "author_id": 37006, "author_profile": "https://Stackoverflow.com/users/37006", "pm_score": 4, "selected": false, "text": "if [[ \"mystring\" =~ REGEX ]] ; then \n echo match\nfi\n" }, { "answer_id": 585666, "author": "Alex Reynolds", "author_id": 19410, "author_profile": "https://Stackoverflow.com/users/19410", "pm_score": 5, "selected": false, "text": "disown -h <pid> nohup disown ps echo $! bg disown" }, { "answer_id": 789475, "author": "mihi", "author_id": 90203, "author_profile": "https://Stackoverflow.com/users/90203", "pm_score": 4, "selected": false, "text": "$ cat /proc/cupinfo\ncat: /proc/cupinfo: No such file or directory\n$ ^cup^cpu\n !:s/old/new !:gs/old/new gs s !-2:s/old/new\n old new" }, { "answer_id": 956064, "author": "danieljimenez", "author_id": 95363, "author_profile": "https://Stackoverflow.com/users/95363", "pm_score": 4, "selected": false, "text": ".inputrc set completion-ignore-case on\n" }, { "answer_id": 956125, "author": "Shawn Chin", "author_id": 115845, "author_profile": "https://Stackoverflow.com/users/115845", "pm_score": 3, "selected": false, "text": "[lsc@home]$ export PROMPT_COMMAND=\"date\"\nFri Jun 5 15:19:18 BST 2009\n[lsc@home]$ ls\nfile_a file_b file_c\nFri Jun 5 15:19:19 BST 2009\n[lsc@home]$ ls\n" }, { "answer_id": 956148, "author": "Alberto Zaccagni", "author_id": 57095, "author_profile": "https://Stackoverflow.com/users/57095", "pm_score": 4, "selected": false, "text": "SECONDS=0; sleep 5 ; echo \"that took approximately $SECONDS seconds\"" }, { "answer_id": 956386, "author": "Shawn Chin", "author_id": 115845, "author_profile": "https://Stackoverflow.com/users/115845", "pm_score": 1, "selected": false, "text": "A=10\nlet B=\"A * 10 + 1\" # B=101\nlet B=\"B / 8\" # B=12, let does not do floating point\nlet B=\"(RANDOM % 6) + 1\" # B is now a random number between 1 and 6\n FP=`echo \"scale=4; 10 / 3\" | bc` # FP=\"3.3333\"\n" }, { "answer_id": 960044, "author": "danieljimenez", "author_id": 95363, "author_profile": "https://Stackoverflow.com/users/95363", "pm_score": 2, "selected": false, "text": "export HISTCONTROL=erasedups\nexport HISTSIZE=1000\n history" }, { "answer_id": 1061412, "author": "Robin", "author_id": 130768, "author_profile": "https://Stackoverflow.com/users/130768", "pm_score": 4, "selected": false, "text": "export VISUAL=vi\n" }, { "answer_id": 1061499, "author": "David Plumpton", "author_id": 16709, "author_profile": "https://Stackoverflow.com/users/16709", "pm_score": 2, "selected": false, "text": "a() { alias $1=cd\\ $PWD; }\n cd a 1 1" }, { "answer_id": 1063939, "author": "GloryFish", "author_id": 3238, "author_profile": "https://Stackoverflow.com/users/3238", "pm_score": 5, "selected": false, "text": "sudo !!\n" }, { "answer_id": 1339852, "author": "camh", "author_id": 23744, "author_profile": "https://Stackoverflow.com/users/23744", "pm_score": 2, "selected": false, "text": "$ less foobar.txt\n...\n# I dont want that file any more\n$ rm !$\n" }, { "answer_id": 1416093, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "man man man man ^ man" }, { "answer_id": 1416125, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 5, "selected": false, "text": "rm -r source/d*.c rm -r source/delete_me.c source/do_not_delete_me.c ls $HOME/tmp ls -N --color=tty -T 0 /home/cramey" }, { "answer_id": 1881808, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 2, "selected": false, "text": "stty -ixon\n ~/.bashrc ~/.inputrc \"\\C-q\": menu-complete\n" }, { "answer_id": 1881855, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 2, "selected": false, "text": "$ foo=bar\n$ baz=foo\n$ echo ${!baz}\nbar\n" }, { "answer_id": 1881903, "author": "Alok Singhal", "author_id": 226621, "author_profile": "https://Stackoverflow.com/users/226621", "pm_score": 2, "selected": false, "text": "r='fc-s' r r $ gcc -c <file_name>.c <lots of options> -o <file_name>.o\n .o $ r <file_name>=<new_file>\n $ r <new_file>=<other_file>\n" }, { "answer_id": 1881938, "author": "aDev", "author_id": 228840, "author_profile": "https://Stackoverflow.com/users/228840", "pm_score": 3, "selected": false, "text": "export TMOUT=$((15*60))" }, { "answer_id": 2825154, "author": "René Nyffenegger", "author_id": 180275, "author_profile": "https://Stackoverflow.com/users/180275", "pm_score": 2, "selected": false, "text": "set -o vi" }, { "answer_id": 3964440, "author": "Sionide21", "author_id": 111644, "author_profile": "https://Stackoverflow.com/users/111644", "pm_score": 3, "selected": false, "text": "FIGNORE export FIGNORE=\".svn\"\n cd .svn" }, { "answer_id": 5230804, "author": "wnrph", "author_id": 345520, "author_profile": "https://Stackoverflow.com/users/345520", "pm_score": 2, "selected": false, "text": "<<< $ cat<<<\"$(( 10*3+1 )) nice isn't it?\"\n31 nice isn't it?\n" }, { "answer_id": 7048325, "author": "Tom", "author_id": 180807, "author_profile": "https://Stackoverflow.com/users/180807", "pm_score": 1, "selected": false, "text": "$ echo A file to read: <(cat), a file to write to: >(cat)\nA file to read: /dev/fd/63, a file to write to: /dev/fd/62\n $ diff <(curl -s http://tldp.org/LDP/abs/html/) <(curl -s http://www.redhat.com/mirrors/LDP/LDP/abs/html/)\n $ do_thingee --log -\nerror: can't open log file: '-'\n$ do_thingee --log >(cat)\ndo_thingee v0.2\ninitializing things\nprocessing 4 things\ndone\n" }, { "answer_id": 7048453, "author": "Tom", "author_id": 180807, "author_profile": "https://Stackoverflow.com/users/180807", "pm_score": 1, "selected": false, "text": "$ cat < /dev/tcp/utcnist.colorado.edu/13\n\n55786 11-08-13 03:34:21 50 0 0 172.3 UTC(NIST) *\n $ exec 3<>/dev/tcp/www.google.com/80 # hook up to file desc 3\n$ echo -e \"GET / HTTP/1.1\\n\\n\" >&3 # send the HTTP request\n$ cat <&3 # read the HTTP response\n" }, { "answer_id": 7048510, "author": "Tom", "author_id": 180807, "author_profile": "https://Stackoverflow.com/users/180807", "pm_score": 3, "selected": false, "text": "$ echo foo{bar,baz,blam}\nfoobar foobaz fooblam\n$ cp program.py{,.bak} # very useful with cp and mv\n $ echo {a..z}\na b c d e f g h i j k l m n o p q r s t u v w x y z\n$ echo {a..f}{0..3}\na0 a1 a2 a3 b0 b1 b2 b3 c0 c1 c2 c3 d0 d1 d2 d3 e0 e1 e2 e3 f0 f1 f2 f3\n" }, { "answer_id": 7048821, "author": "Kasun Gajasinghe", "author_id": 388714, "author_profile": "https://Stackoverflow.com/users/388714", "pm_score": 0, "selected": false, "text": "~/.inputrc /etc/inputrc $ cat ~/.inputrc\n\"\\e[A\": history-search-backward\n\"\\e[B\": history-search-forward\n Esc p \"\\ep\": history-search-backward\n\"\\en\": history-search-forward\n grep grep -ri myText ." }, { "answer_id": 8870060, "author": "Fish Monitor", "author_id": 547578, "author_profile": "https://Stackoverflow.com/users/547578", "pm_score": 2, "selected": false, "text": "do done For do...done for f in *;\ndo\n ls \"$f\";\ndone\n for f in *; {\n ls \"$f\";\n}\n do...done" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429/" ]
211,383
<p>I have the age-old problem of a <code>div</code> wrapping a two-column layout. My sidebar is floated, so my container <code>div</code> fails to wrap the content and sidebar.</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;div id="sidebar"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>There seem to be numerous methods of fixing the clear bug in Firefox:</p> <ul> <li><code>&lt;br clear="all"/&gt;</code></li> <li><code>overflow:auto</code></li> <li><code>overflow:hidden</code></li> </ul> <p>In my situation, the only one that seems to work correctly is the <code>&lt;br clear="all"/&gt;</code> solution, which is a little bit scruffy. <code>overflow:auto</code> gives me nasty scrollbars, and <code>overflow:hidden</code> must surely have side effects. Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.</p> <p>Which method currently available to us is the most robust?</p>
[ { "answer_id": 211415, "author": "Torkel", "author_id": 24425, "author_profile": "https://Stackoverflow.com/users/24425", "pm_score": -1, "selected": false, "text": "<div style=\"clear:both;\"/>\n" }, { "answer_id": 461858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "height = 0 /* float clearing for everyone else */\n.clearfix:after{\n clear: both;\n content: \".\";\n display: block;\n height: 0;\n visibility: hidden;\n font-size: 0;\n}\n" }, { "answer_id": 531906, "author": "Jack Sleight", "author_id": 39428, "author_profile": "https://Stackoverflow.com/users/39428", "pm_score": 5, "selected": false, "text": ".container { overflow: hidden; }\n .container { zoom: 1; }\n" }, { "answer_id": 1341057, "author": "draco", "author_id": 92776, "author_profile": "https://Stackoverflow.com/users/92776", "pm_score": 3, "selected": false, "text": "overflow:hidden auto #test {\n overflow:hidden; // or auto;\n _height:1%; forces hasLayout in IE6\n}\n\n<div id=\"test\">\n <div style=\"floatLeft\"></div>\n <div style=\"random\"></div>\n</div>\n #test {\n float: left; // using float to clear float\n width: 99%;\n}\n" }, { "answer_id": 1633170, "author": "Beau Smith", "author_id": 101290, "author_profile": "https://Stackoverflow.com/users/101290", "pm_score": 11, "selected": true, "text": "overflow: auto; overflow: auto <div style=\"overflow: auto;\">\n <img\n style=\"float: right;\"\n src=\"path/to/floated-element.png\"\n width=\"500\"\n height=\"500\"\n > \n <p>Your content here…</p>\n</div>\n hidden img display: block display: table .container::after {\n content: \"\";\n display: block;\n clear: both;\n}\n zoom ::before .container::after {\n content: \"\";\n display: table;\n clear: both;\n}\n .container::before, .container::after {\n content: \"\";\n display: table;\n}\n.container::after {\n clear: both;\n}\n.container {\n zoom: 1;\n}\n width: 100% .container {\n overflow: hidden;\n display: inline-block;\n display: block;\n}\n display .container {\n overflow: hidden;\n zoom: 1;\n display: block;\n}\n overflow zoom .container {\n overflow: hidden;\n _overflow: visible; /* for IE */\n _zoom: 1; /* for IE */\n}\n <br style=\"clear: both\" /> <!-- So dirty! -->\n <br style=\"clear: both\" />" }, { "answer_id": 2909912, "author": "Thierry Koblentz", "author_id": 350504, "author_profile": "https://Stackoverflow.com/users/350504", "pm_score": 2, "selected": false, "text": "#content #content" }, { "answer_id": 3196924, "author": "duggi", "author_id": 262942, "author_profile": "https://Stackoverflow.com/users/262942", "pm_score": 3, "selected": false, "text": "<br clear=\"all\" /> class=\"clearfix\" display: hidden" }, { "answer_id": 3805213, "author": "Eric the Red", "author_id": 86537, "author_profile": "https://Stackoverflow.com/users/86537", "pm_score": 5, "selected": false, "text": "/* >> The Magnificent CLEARFIX << */\n .clearfix:after { \n content: \".\"; \n display: block; \n height: 0; \n clear: both; \n visibility: hidden; \n}\n.clearfix { \n display: inline-block; \n}\n* html .clearfix { \n height: 1%; \n} /* Hides from IE-mac \\*/\n.clearfix { \n display: block; \n}\n" }, { "answer_id": 5066285, "author": "Salman von Abbas", "author_id": 362006, "author_profile": "https://Stackoverflow.com/users/362006", "pm_score": 3, "selected": false, "text": ".clear:after{\n clear: both;\n content: \"\";\n display: block;\n}\n" }, { "answer_id": 5519692, "author": "Hakan", "author_id": 673108, "author_profile": "https://Stackoverflow.com/users/673108", "pm_score": 0, "selected": false, "text": ".cb:after{\n visibility: hidden;\n display: block;\n content: \".\";\n clear: both;\n height: 0;\n}\n\n*:first-child+html .cb{zoom: 1} /* for IE7 */\n <div id=\"container\" class=\"cb\">\n" }, { "answer_id": 5745706, "author": "paulslater19", "author_id": 705752, "author_profile": "https://Stackoverflow.com/users/705752", "pm_score": 4, "selected": false, "text": "/* For modern browsers */\n.cf:before,\n.cf:after {\n content:\"\";\n display:table;\n}\n\n.cf:after {\n clear:both;\n}\n\n/* For IE 6/7 (trigger hasLayout) */\n.cf {\n zoom:1;\n}\n" }, { "answer_id": 6072143, "author": "Phpascal", "author_id": 762759, "author_profile": "https://Stackoverflow.com/users/762759", "pm_score": 2, "selected": false, "text": "<br style=\"clear:both\" />\n .clear { clear:both; }" }, { "answer_id": 6404718, "author": "Tim Huynh", "author_id": 576066, "author_profile": "https://Stackoverflow.com/users/576066", "pm_score": 2, "selected": false, "text": "<div id=\"container\">\n <div id=\"content\">\n </div>\n <div id=\"sidebar\">\n </div>\n</div>\n div#container {\n overflow: hidden; /* makes element contain floated child elements */\n}\n\ndiv#content, div#sidebar {\n float: left;\n display: inline; /* preemptively fixes IE6 dobule-margin bug */\n}\n" }, { "answer_id": 7101649, "author": "Neil G", "author_id": 899758, "author_profile": "https://Stackoverflow.com/users/899758", "pm_score": 3, "selected": false, "text": "clear: both;" }, { "answer_id": 9932508, "author": "Chris Calo", "author_id": 101869, "author_profile": "https://Stackoverflow.com/users/101869", "pm_score": 6, "selected": false, "text": "clear: both zoom: 1 display: inline-block width: 100% width: 100% box-sizing: border-box padding margin border <div class=\"container\">\n <div class=\"sidebar\">\n sidebar<br/>sidebar<br/>sidebar\n </div>\n <div class=\"main\">\n <div class=\"main-content\">\n main content\n <span style=\"clear: both\">\n main content that uses <code>clear: both</code>\n </span>\n </div>\n </div>\n</div>\n /* Should contain all floated and non-floated content, so it needs to\n * establish a new block formatting context without using overflow: hidden.\n */\n.container {\n display: inline-block;\n width: 100%;\n zoom: 1; /* new block formatting context via hasLayout for IE 6/7 */\n}\n\n/* Fixed-width floated sidebar. */\n.sidebar {\n float: left;\n width: 160px;\n}\n\n/* Needs to make space for the sidebar. */\n.main {\n margin-left: 160px;\n}\n\n/* Establishes a new block formatting context to insulate descendants from\n * the floating sidebar. */\n.main-content {\n display: inline-block;\n width: 100%;\n zoom: 1; /* new block formatting context via hasLayout for IE 6/7 */\n}\n :after clear: both" }, { "answer_id": 12235179, "author": "John Xiao", "author_id": 1252528, "author_profile": "https://Stackoverflow.com/users/1252528", "pm_score": 2, "selected": false, "text": "<html> .clearfix:after { \n visibility: hidden; \n display: block; \n content: \".\"; \n clear: both; \n height: 0;\n}\n font-size: 0;" }, { "answer_id": 13081256, "author": "Gaurang", "author_id": 1453858, "author_profile": "https://Stackoverflow.com/users/1453858", "pm_score": 2, "selected": false, "text": ".clearfix:after {\n content: \" \"; /* Older browser do not support empty content */\n visibility: hidden;\n display: block;\n height: 0;\n clear: both;\n}\n.cleaner {\n clear: both;\n}\n <div style=\"float: left;\">Sidebar</div>\n<div class=\"cleaner\"></div> <!-- Clear the float -->\n <div style=\"float: left;\" class=\"clearfix\">Sidebar</div>\n<!-- No Clearing div! -->\n" }, { "answer_id": 13718078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": ".clearfix {\n *zoom: 1;\n}\n\n.clearfix:before,\n.clearfix:after {\n display: table;\n line-height: 0;\n content: \"\";\n}\n\n.clearfix:after {\n clear: both;\n}\n" }, { "answer_id": 15291536, "author": "Vipul Vaghasiya", "author_id": 937911, "author_profile": "https://Stackoverflow.com/users/937911", "pm_score": 0, "selected": false, "text": "#content{float:left;}\n#sidebar{float:left;}\n.clear{clear:both; display:block; height:0px; width:0px; overflow:hidden;} <div id=\"container\">\n <div id=\"content\">text 1 </div>\n <div id=\"sidebar\">text 2</div>\n <div class=\"clear\"></div>\n</div>" }, { "answer_id": 15437402, "author": "Musa Butt", "author_id": 2174728, "author_profile": "https://Stackoverflow.com/users/2174728", "pm_score": 3, "selected": false, "text": ".clearFix:after { \n content: \"\";\n display: table; \n clear: both; \n}\n" }, { "answer_id": 15522931, "author": "jmu", "author_id": 454985, "author_profile": "https://Stackoverflow.com/users/454985", "pm_score": 3, "selected": false, "text": ".clearfix() {\n zoom: 1;\n &:before { \n content: ''; \n display: block; \n }\n &:after { \n content: ''; \n display: table; \n clear: both; \n }\n}\n <!-- HTML -->\n<div id=\"container\">\n <div id=\"content\"></div>\n <div id=\"sidebar\"></div>\n</div>\n /* LESS */\ndiv#container {\n .clearfix();\n}\n" }, { "answer_id": 16099501, "author": "iono", "author_id": 1129420, "author_profile": "https://Stackoverflow.com/users/1129420", "pm_score": 6, "selected": false, "text": ".btcf:after {\n content:\"\";\n display:block;\n clear:both;\n}\n display: block display: table" }, { "answer_id": 20979670, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 2, "selected": false, "text": ".cf:before,\n.cf:after {\n content: \" \";\n display: table;\n}\n\n.cf:after {\n clear: both;\n}\n\n/**\n * For IE 6/7 only\n */\n.cf {\n *zoom: 1;\n}\n" }, { "answer_id": 23479523, "author": "fernandopasik", "author_id": 1877754, "author_profile": "https://Stackoverflow.com/users/1877754", "pm_score": 3, "selected": false, "text": "@mixin clearfix {\n &:before, &:after {\n content: '';\n display: table;\n }\n &:after {\n clear: both;\n }\n *zoom: 1;\n}\n .container {\n @include clearfix;\n}\n @mixin newclearfix {\n &:after {\n content:\"\";\n display:table;\n clear:both;\n }\n}\n" }, { "answer_id": 29156752, "author": "Omar", "author_id": 931377, "author_profile": "https://Stackoverflow.com/users/931377", "pm_score": 3, "selected": false, "text": "...the use of floated elements for layout is getting more and more discouraged with the use of better alternatives... <div classs=\"clear\"></div> <div class=\"floated\">1st</div>\n<div class=\"floated\">2nd</div>\n<div class=\"floated\">3nd</div>\n<div classs=\"clear\"></div> <!-- Acts as a wall -->\n<section>Below</section>\n div {\n border: 1px solid #f00;\n width: 200px;\n height: 100px;\n}\n\ndiv.floated {\n float: left;\n}\n\n.clear {\n clear: both;\n}\nsection {\n border: 1px solid #f0f;\n}\n all you have to do is to place your floats in a container <div id=\"container\" class=\"\">\n <div class=\"floated\">1st</div>\n <div class=\"floated\">2nd</div>\n <div class=\"floated\">3nd</div>\n</div> <!-- /#conteiner -->\n<div classs=\"clear\"></div> <!-- Acts as a wall -->\n<section>Below</section>\n #container {\n min-height: 100px; /* To prevent it from collapsing */\n border: 1px solid #0f0;\n}\n.floated {\n float: left;\n border: 1px solid #f00;\n width: 200px;\n height: 100px;\n}\n\n.clear {\n clear: both;\n}\nsection {\n border: 1px solid #f0f;\n}\n .clearfix:before, .clearfix:after { \n content: \"\";\n display: table;\n clear: both;\n zoom: 1; /* ie 6/7 */\n}\n <div class=\"clearfix\">\n <div class=\"floated\">1st</div>\n <div class=\"floated\">2nd</div>\n <div class=\"floated\">3nd</div>\n</div>\n<section>Below</section>\n div.floated {\n float: left;\n border: 1px solid #f00;\n width: 200px;\n height: 100px;\n}\nsection {\n border: 4px solid #00f;\n}\n\n\n.clearfix:before, .clearfix:after { \n content: \"\";\n display: table;\n clear: both;\n zoom: 1; /* ie 6/7 */\n}\n <div classs=\"clear\"></div> <!-- Acts as a wall --> @media .clearfix:before, .clearfix:after { \n content: \"\";\n display: table;\n clear: both;\n zoom: 1; /* ie 6/7 */\n}\n" }, { "answer_id": 29513176, "author": "Serge Stroobandt", "author_id": 2192488, "author_profile": "https://Stackoverflow.com/users/2192488", "pm_score": 2, "selected": false, "text": "<div> h1 {\n clear: both;\n display: inline-block;\n width: 100%;\n}\n" }, { "answer_id": 35912310, "author": "Eric", "author_id": 4872291, "author_profile": "https://Stackoverflow.com/users/4872291", "pm_score": -1, "selected": false, "text": ".clearfix{\n clear:both;\n}\n <html>\n <div class=\"div-number-one\">\n Some Content before the clearfix\n </div>\n\n <!-- Let's say we need to clearfix Here between these two divs --->\n <div class=\"clearfix\"></div>\n\n <div class=\"div-number-two\">\n Some more content after the clearfix\n </div>\n</html>\n" }, { "answer_id": 45734276, "author": "Damien Golding", "author_id": 1764521, "author_profile": "https://Stackoverflow.com/users/1764521", "pm_score": 3, "selected": false, "text": "display: flow-root;\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
211,399
<p>I need to execute a select and then update some of the rows in the <code>ResultSet</code> in an atomic way.</p> <p>The code I am using looks like (simplified):</p> <pre><code>stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery("SELECT ..."); while (rs.next()) { if (conditions_to_update) { rs.updateString(...); rs.updateRow(); } } </code></pre> <ul> <li>Can I guarantee that the updates are going to be executed atomically ? If not, how could I assure that ?</li> <li>What happens if any other process has changed the database row that you are updating via <code>updateRow()</code> ? Is there any way to lock the rows in the <code>ResultSet</code> ?</li> </ul>
[ { "answer_id": 211502, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 3, "selected": true, "text": "...\ncon.setAutoCommit(false);\ntry {\n while (rs.next()) {\n if (conditions_to_update) {\n rs.updateString(...);\n rs.updateRow();\n }\n }\n con.setAutoCommit(true);\n} catch (Exception ex) {\n //log the exception and rollback\n con.rollback();\n} finally {\n con.close();\n}\n" }, { "answer_id": 212457, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "select cola, colB from tabA for update;\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
211,436
<p>In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'." </p>
[ { "answer_id": 211462, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 6, "selected": true, "text": "myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value\n DEFAULT NULL" }, { "answer_id": 211463, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "Guid? Guid myGuid.Value (Guid)myGuid myGuid.GetValueOrDefault() Guid Guid? object DBNull.Value Guid?" }, { "answer_id": 211522, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "public static class Ado {\n public static void SetParameterValue<T>( IDataParameter parameter, T? value ) where T : struct {\n if ( null == value ) { parameter.Value = DBNull.Value; }\n else { parameter.Value = value.Value; }\n }\n public static void SetParameterValue( IDataParameter parameter, string value ) {\n if ( null == value ) { parameter.Value = DBNull.Value; }\n else { parameter.Value = value; }\n }\n}\n" }, { "answer_id": 211645, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " internal static T CastTo<T>(object value)\n {\n return value != DBNull.Value ? (T)value : default(T);\n }\n" }, { "answer_id": 211667, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 2, "selected": false, "text": "myGuid != Guid.Empty" }, { "answer_id": 211882, "author": "cheeves", "author_id": 15826, "author_profile": "https://Stackoverflow.com/users/15826", "pm_score": 3, "selected": false, "text": "myNewRow.myGuidColumn = (object)myGuid ?? DBNull.Value\n" }, { "answer_id": 16443648, "author": "Justin", "author_id": 945875, "author_profile": "https://Stackoverflow.com/users/945875", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// Returns nullable Guid (Guid?) value if not null or Guid.Empty, otherwise returns DBNull.Value\n/// </summary>\npublic static object GetValueOrDBNull(this Guid? aGuid)\n{\n return (!aGuid.IsNullOrEmpty()) ? (object)aGuid : DBNull.Value;\n}\n\n/// <summary>\n/// Determines if a nullable Guid (Guid?) is null or Guid.Empty\n/// </summary>\npublic static bool IsNullOrEmpty(this Guid? aGuid)\n{\n return (!aGuid.HasValue || aGuid.Value == Guid.Empty);\n}\n myNewRow.myGuidColumn = myGuid.GetValueOrDBNull(); myGuid == Guid.Empty" }, { "answer_id": 26699430, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 3, "selected": false, "text": "null nullable Guid myRecord.myGuidCol = (myGuid == null) ? (Guid?)null : myGuid.Value\n" }, { "answer_id": 33213838, "author": "maurox", "author_id": 662403, "author_profile": "https://Stackoverflow.com/users/662403", "pm_score": 0, "selected": false, "text": "Guid? _field = null;\nif (myValue!=\"\")//test if myValue has value\n{\n_field = Guid.Parse(myValue)\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
211,448
<p>I have a custom class that implements <code>ICollection</code>, and this class is readonly, ie. <code>IsReadOnly</code> returns true (as opposed to using the <code>readonly</code> keyword), and all functions that would normally modify the data in the collection throw <code>InvalidOperationException</code>'s.</p> <p>Now, given such a construct, and a quick skim over the thread-safety issues when implementing <code>ICollection</code> (specifically <a href="http://msdn.microsoft.com/en-us/library/system.collections.icollection.issynchronized.aspx" rel="noreferrer"><code>ICollection.IsSynchronized</code></a> and friends), I came up with this quick and dirty solution.</p> <pre><code>bool ICollection.IsSynchronised { get{ return true; } } object ICollection.SyncRoot { get{ return new Object(); } } </code></pre> <p>Now, given the examples in MSDN, this won't cause different threads to lock properly, because they are getting different objects from <code>SyncRoot</code>. Given that this is a readonly collection though, is this an issue? Are there memory/GC issues with returning <code>new Object()</code>? Any other issues you can see with this implementation?</p>
[ { "answer_id": 211479, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "private readonly object lockObj = new object();\n [MethodImpl]" }, { "answer_id": 211491, "author": "Kimoz", "author_id": 7753, "author_profile": "https://Stackoverflow.com/users/7753", "pm_score": 3, "selected": true, "text": "private readonly object syncRoot = new object();\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
211,477
<p>I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().</p> <p>My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.</p>
[ { "answer_id": 212474, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 2, "selected": false, "text": "pointcut profilling(): execution(public * *(..)) && (\n within(com.myPackage..*) ||\n Object around(): profilling() {\n\n //Do wherever you need before method call\n proceed();\n //Do wherever you need after method call\n\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,493
<p>I'm just in the process of upgrading my Preview 5 application to Beta 1, and I'm nearly there save for this one error when trying to render a control:</p> <blockquote> <p>'System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartial' and no extension method 'RenderPartial' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)</p> </blockquote> <p>My markup (in the .aspx View Content Page) is:</p> <pre><code>&lt;% Html.RenderPartial("Controls/UserForm", ViewData); %&gt; </code></pre> <p>I've tried using Microsoft.Web.Mvc but to no avail. Does anyone know where Html.RenderPartial has gone, or what alternative I could use?</p>
[ { "answer_id": 211524, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 3, "selected": false, "text": "<add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n" }, { "answer_id": 212829, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 2, "selected": false, "text": " <add namespace=\"System.Web.Mvc.Html\"/>\" \n" }, { "answer_id": 216867, "author": "spinodal", "author_id": 11374, "author_profile": "https://Stackoverflow.com/users/11374", "pm_score": 4, "selected": true, "text": "<namespaces>\n <add namespace=\"System.Web.Mvc\"/>\n <add namespace=\"System.Web.Mvc.Ajax\"/>\n <add namespace=\"System.Web.Mvc.Html\"/>\n <add namespace=\"System.Web.Routing\"/>\n <add namespace=\"System.Linq\"/>\n <add namespace=\"System.Collections.Generic\"/>\n</namespaces>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
211,496
<p>Is using a handrolled POCO queue class using pseudo code</p> <pre><code>T Dequeue() { lock(syncRoot) { if(queue.Empty) Thread.Wait(); } } void Enqueue(T item) { queue.Enqueue(item); Thread.Notify(); } </code></pre> <p>For WCF is request queueing a scalable approach?</p>
[ { "answer_id": 211524, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 3, "selected": false, "text": "<add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n" }, { "answer_id": 212829, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 2, "selected": false, "text": " <add namespace=\"System.Web.Mvc.Html\"/>\" \n" }, { "answer_id": 216867, "author": "spinodal", "author_id": 11374, "author_profile": "https://Stackoverflow.com/users/11374", "pm_score": 4, "selected": true, "text": "<namespaces>\n <add namespace=\"System.Web.Mvc\"/>\n <add namespace=\"System.Web.Mvc.Ajax\"/>\n <add namespace=\"System.Web.Mvc.Html\"/>\n <add namespace=\"System.Web.Routing\"/>\n <add namespace=\"System.Linq\"/>\n <add namespace=\"System.Collections.Generic\"/>\n</namespaces>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28413/" ]
211,498
<p>We use GUIDs for primary key, which you know is clustered by default.</p> <p>When inserting a new row into a table it is inserted at a random page in the table (because GUIDs are random). This has a measurable performance impact because the DB will split data pages all the time (fragmentation). But the main reason I what a sequential GUID is because I want new rows to be inserted as the last row in the table... which will help when debugging.</p> <p>I could make a clustered index on <code>CreateDate</code>, but our DB is auto-generated and in development, we need to do something extra to facilitate this. Also, <code>CreateDate</code> is not a good candidate for a clustered index.</p> <p>Back in the day, I used <a href="http://www.informit.com/articles/article.aspx?p=25862" rel="nofollow noreferrer">Jimmy Nielsons COMB's</a>, but I was wondering if there is something in the .NET framework for this. In SQL 2005 Microsoft introduced <code>newsequentialid()</code> as an alternative to <code>newid()</code>, so I was hoping that they made a .NET equivalent because we generate the ID in the code.</p> <p>PS: Please don't start discussing if this is right or wrong, because GUIDs should be unique etc.</p>
[ { "answer_id": 211542, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "newsequentialid()" }, { "answer_id": 211757, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 6, "selected": true, "text": "[DllImport(\"rpcrt4.dll\", SetLastError=true)]\nstatic extern int UuidCreateSequential(out Guid guid);\n" }, { "answer_id": 1314226, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 2, "selected": false, "text": "byte[] guidArray = System.Guid.NewGuid().ToByteArray();\n\nDateTime baseDate = new DateTime(1900, 1, 1);\nDateTime now = DateTime.Now;\n\n// Get the days and milliseconds which will be used to build the byte string \nTimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);\nTimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));\n\n// Convert to a byte array \n// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 \nbyte[] daysArray = BitConverter.GetBytes(days.Days);\nbyte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));\n\n// Reverse the bytes to match SQL Servers ordering \nArray.Reverse(daysArray);\nArray.Reverse(msecsArray);\n\n// Copy the bytes into the guid \nArray.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);\nArray.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);\n\nreturn new System.Guid(guidArray);\n" }, { "answer_id": 3936157, "author": "Daniel", "author_id": 169388, "author_profile": "https://Stackoverflow.com/users/169388", "pm_score": 0, "selected": false, "text": "declare @ids table(id uniqueidentifier default NEWSEQUENTIALID(), dummy char(1))\n\ndeclare @c int\nset @c = 0;\nwhile (@c < 100)\nbegin\n insert into @ids (dummy) values ('a');\n set @c += 1;\nend\n\nselect id from @ids\n" }, { "answer_id": 12580020, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 5, "selected": false, "text": "/// <summary>\n/// Generate a new <see cref=\"Guid\"/> using the comb algorithm.\n/// </summary>\nprivate Guid GenerateComb()\n{\n byte[] guidArray = Guid.NewGuid().ToByteArray();\n\n DateTime baseDate = new DateTime(1900, 1, 1);\n DateTime now = DateTime.Now;\n\n // Get the days and milliseconds which will be used to build the byte string \n TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);\n TimeSpan msecs = now.TimeOfDay;\n\n // Convert to a byte array \n // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 \n byte[] daysArray = BitConverter.GetBytes(days.Days);\n byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds / 3.333333));\n\n // Reverse the bytes to match SQL Servers ordering \n Array.Reverse(daysArray);\n Array.Reverse(msecsArray);\n\n // Copy the bytes into the guid \n Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);\n Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);\n\n return new Guid(guidArray);\n}\n" }, { "answer_id": 47682820, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "UuidCreateSequential UuidCreateSequential public static Guid NewSequentialId()\n{\n Guid guid;\n UuidCreateSequential(out guid);\n var s = guid.ToByteArray();\n var t = new byte[16];\n \n t[3] = s[0];\n t[2] = s[1];\n t[1] = s[2];\n t[0] = s[3];\n \n t[5] = s[4];\n t[4] = s[5];\n t[7] = s[6];\n t[6] = s[7];\n t[8] = s[8];\n t[9] = s[9];\n t[10] = s[10];\n t[11] = s[11];\n t[12] = s[12];\n t[13] = s[13];\n t[14] = s[14];\n t[15] = s[15];\n \n return new Guid(t);\n}\n 1582-10-15 00:00:00 0x01E7DA9FDCA45C22 0x01E7DA9FDCA45C22\n\n| Hi | Mid | Low |\n|--------|--------|------------|\n| 0x01E7 | 0xDA9F | 0xDCA45C22 |\n DC A4 5C 22 DA 9F x1 E7 xx xx xx xx xx xx xx xx\n 22 5C A4 DC 9F DA E7 x1 xx xx xx xx xx xx xx xx\n Int64 225CA4DC9FDAE701\n UuidCreateSequential DCA45C22-DA9F-11E7-DDDD-FFFFFFFFFFFF\n 22 5C A4 DC 9F DA E7 11 DD DD FF FF FF FF FF FF\n Low Mid Version High\n-------- ---- ------- ---- -----------------\nDCA45C22-DA9F-1 1E7 -DDDD-FFFFFFFFFFFF\n DC A4 5C 22 DA 9F 11 E7 DD DD FF FF FF FF FF FF\n | Swap | Swap | Swap | Copy as-is\nStart index | 0 1 2 3 | 4 5 | 6 7 | \nEnd index | 3 2 1 0 | 5 4 | 7 6 | \n---------------|-------------|-------|-------|------------------------ \nLittle-endian: | 22 5C A4 DC | 9F DA | E7 11 | DD DD FF FF FF FF FF FF\nBig-endian: | DC A4 5C 22 | DA 9F | 11 E7 | DD DD FF FF FF FF FF FF\n" }, { "answer_id": 49256827, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 3, "selected": false, "text": "Install-Package NewId\n Guid myNewSequentialGuid = NewId.NextGuid();\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p> <p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p> <p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p> <p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
[ { "answer_id": 211541, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 2, "selected": false, "text": "import sqlite3\nimport os\ndatabase_name = \"newdb.db\"\nif not os.path.isfile(database_name):\n print \"the database already exist\"\ndb_connection = sqlite3.connect(database_name)\ndb_cursor = db_connection.cursor()\ntry:\n db_cursor.execute('CREATE TABLE TEST (a INTEGER);')\nexcept sqlite3.OperationalError, msg:\n print msg\n" }, { "answer_id": 211562, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": false, "text": "import os\nimport sqlite3\nif not os.path.exists(mydb_path):\n #create new DB, create table stocks\n con = sqlite3.connect(mydb_path)\n con.execute('''create table stocks\n (date text, trans text, symbol text, qty real, price real)''')\nelse:\n #use existing DB\n con = sqlite3.connect(mydb_path)\n...\n" }, { "answer_id": 211573, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 3, "selected": false, "text": "IF NOT EXISTS CREATE TABLE IF EXISTS CREATE TABLE" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
211,510
<p>I am trying to come up with such a solution that the user is going to enter the URL of a web-service and it is going to be tested.</p> <p>Although what I want is a URL change, I guarantee the Service Description is always going to be the same (except the wsdl:service tag of course which contains the soap:address); I just want to test different customers, running the same service.</p>
[ { "answer_id": 211517, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Url" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22186/" ]
211,535
<h2>Note</h2> <p>The question below was asked in 2008 about some code from 2003. As the OP's <strong>update</strong> shows, this entire post has been obsoleted by vintage 2008 algorithms and persists here only as a historical curiosity.</p> <hr> <p>I need to do a fast case-insensitive substring search in C/C++. My requirements are as follows:</p> <ul> <li>Should behave like strstr() (i.e. return a pointer to the match point).</li> <li>Must be case-insensitive (doh).</li> <li>Must support the current locale.</li> <li>Must be available on Windows (MSVC++ 8.0) or easily portable to Windows (i.e. from an open source library).</li> </ul> <p>Here is the current implementation I am using (taken from the GNU C Library):</p> <pre><code>/* Return the offset of one string within another. Copyright (C) 1994,1996,1997,1998,1999,2000 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* * My personal strstr() implementation that beats most other algorithms. * Until someone tells me otherwise, I assume that this is the * fastest implementation of strstr() in C. * I deliberately chose not to comment it. You should have at least * as much fun trying to understand it, as I had to write it :-). * * Stephen R. van den Berg, berg@pool.informatik.rwth-aachen.de */ /* * Modified to use table lookup instead of tolower(), since tolower() isn't * worth s*** on Windows. * * -- Anders Sandvig (anders@wincue.org) */ #if HAVE_CONFIG_H # include &lt;config.h&gt; #endif #include &lt;ctype.h&gt; #include &lt;string.h&gt; typedef unsigned chartype; char char_table[256]; void init_stristr(void) { int i; char string[2]; string[1] = '\0'; for (i = 0; i &lt; 256; i++) { string[0] = i; _strlwr(string); char_table[i] = string[0]; } } #define my_tolower(a) ((chartype) char_table[a]) char * my_stristr (phaystack, pneedle) const char *phaystack; const char *pneedle; { register const unsigned char *haystack, *needle; register chartype b, c; haystack = (const unsigned char *) phaystack; needle = (const unsigned char *) pneedle; b = my_tolower (*needle); if (b != '\0') { haystack--; /* possible ANSI violation */ do { c = *++haystack; if (c == '\0') goto ret0; } while (my_tolower (c) != (int) b); c = my_tolower (*++needle); if (c == '\0') goto foundneedle; ++needle; goto jin; for (;;) { register chartype a; register const unsigned char *rhaystack, *rneedle; do { a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) == (int) b) break; a = *++haystack; if (a == '\0') goto ret0; shloop: ; } while (my_tolower (a) != (int) b); jin: a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) != (int) c) goto shloop; rhaystack = haystack-- + 1; rneedle = needle; a = my_tolower (*rneedle); if (my_tolower (*rhaystack) == (int) a) do { if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); if (my_tolower (*rhaystack) != (int) a) break; if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); } while (my_tolower (*rhaystack) == (int) a); needle = rneedle; /* took the register-poor approach */ if (a == '\0') break; } } foundneedle: return (char*) haystack; ret0: return 0; }</code></pre> <p>Can you make this code faster, or do you know of a better implementation?</p> <p><strong>Note:</strong> I noticed that the GNU C Library now has <a href="http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/string/strstr.c?rev=1.2&amp;content-type=text/x-cvsweb-markup&amp;cvsroot=glibc" rel="nofollow noreferrer">a new implementation of <code>strstr()</code></a>, but I am not sure how easily it can be modified to be case-insensitive, or if it is in fact faster than the old one (in my case). I also noticed that <a href="http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/wcsmbs/wcsstr.c?rev=1.4&amp;content-type=text/x-cvsweb-markup&amp;cvsroot=glibc" rel="nofollow noreferrer">the old implementation is still used for wide character strings</a>, so if anyone knows why, please share.</p> <p><strong>Update</strong></p> <p>Just to make things clear&mdash;in case it wasn't already&mdash;I didn't write this function, it's a part of the GNU C Library. I only modified it to be case-insensitive.</p> <p>Also, thanks for the tip about <code>strcasestr()</code> and checking out other implementations from other sources (like OpenBSD, FreeBSD, etc.). It seems to be the way to go. The code above is from 2003, which is why I posted it here in hope for a better version being available, which apparently it is. :)</p>
[ { "answer_id": 211561, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "char_table[i] = tolower(i);\n" }, { "answer_id": 211859, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": true, "text": "strcasestr $ gcc -Wall -o my_stristr my_stristr.c\nsteve@solaris:~/code/tmp\n$ gcc -Wall -o strcasestr strcasestr.c \nsteve@solaris:~/code/tmp\n$ ./bench ./my_stristr > my_stristr.result ; ./bench ./strcasestr > strcasestr.result;\nsteve@solaris:~/code/tmp\n$ cat my_stristr.result \nrun 1... time = 6.32\nrun 2... time = 6.31\nrun 3... time = 6.31\nrun 4... time = 6.31\nrun 5... time = 6.32\nrun 6... time = 6.31\nrun 7... time = 6.31\nrun 8... time = 6.31\nrun 9... time = 6.31\nrun 10... time = 6.31\naverage user time over 10 runs = 6.3120\nsteve@solaris:~/code/tmp\n$ cat strcasestr.result \nrun 1... time = 3.82\nrun 2... time = 3.82\nrun 3... time = 3.82\nrun 4... time = 3.82\nrun 5... time = 3.82\nrun 6... time = 3.82\nrun 7... time = 3.82\nrun 8... time = 3.82\nrun 9... time = 3.82\nrun 10... time = 3.82\naverage user time over 10 runs = 3.8200\nsteve@solaris:~/code/tmp\n main int main(void)\n{\n char * needle=\"hello\";\n char haystack[1024];\n int i;\n\n for(i=0;i<sizeof(haystack)-strlen(needle)-1;++i)\n {\n haystack[i]='A'+i%57;\n }\n memcpy(haystack+i,needle, strlen(needle)+1);\n /*printf(\"%s\\n%d\\n\", haystack, haystack[strlen(haystack)]);*/\n init_stristr();\n\n for (i=0;i<1000000;++i)\n {\n /*my_stristr(haystack, needle);*/\n strcasestr(haystack,needle);\n }\n\n\n return 0;\n}\n init_stristr bench #!/bin/bash\nfunction bc_calc()\n{\n echo $(echo \"scale=4;$1\" | bc)\n}\ntime=\"/usr/bin/time -p\"\nprog=\"$1\"\naccum=0\nruns=10\nfor a in $(jot $runs 1 $runs)\ndo\n echo -n \"run $a... \"\n t=$($time $prog 2>&1| grep user | awk '{print $2}')\n echo \"time = $t\"\n accum=$(bc_calc \"$accum+$t\")\ndone\n\necho -n \"average user time over $runs runs = \"\necho $(bc_calc \"$accum/$runs\")\n" }, { "answer_id": 211904, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 1, "selected": false, "text": "int StringInStringFindFirst(const char* p_cText, const char* p_cSearchText)\n{\n int iTextSize = strlen(p_cText);\n int iSearchTextSize = strlen(p_cSearchText);\n\n char* p_cFound = NULL;\n\n if(iTextSize >= iSearchTextSize)\n {\n int iCounter = 0;\n while((iCounter + iSearchTextSize) <= iTextSize)\n {\n if(memcmp( (p_cText + iCounter), p_cSearchText, iSearchTextSize) == 0)\n return iCounter;\n iCounter ++;\n }\n }\n\n return -1;\n}\n long GetStringMask(const char* p_cText)\n{\n long lMask=0;\n\n while(*p_cText != '\\0')\n { \n if (*p_cText>='a' && *p_cText<='z')\n lMask = lMask | (1 << (*p_cText - 'a') );\n else if(*p_cText != ' ')\n {\n lMask = 0;\n break; \n }\n\n p_cText ++;\n }\n return lMask;\n}\n int main(int argc, char* argv[])\n{\n\n char* p_cText = \"this is a test\"; \n char* p_cSearchText = \"test\";\n\n long lTextMask = GetStringMask(p_cText);\n long lSearchMask = GetStringMask(p_cSearchText);\n\n int iFoundAt = -1;\n // If Both masks are Valid\n if(lTextMask != 0 && lSearchMask != 0)\n {\n if((lTextMask & lSearchMask) == lSearchMask)\n { \n iFoundAt = StringInStringFindFirst(p_cText, p_cSearchText);\n }\n }\n else\n {\n iFoundAt = StringInStringFindFirst(p_cText, p_cSearchText);\n }\n\n\n return 0;\n}\n" }, { "answer_id": 212137, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "if (BitLookup(table[char1], char2)) { /* match */ }\n #define kCongruentCase (1 << 0)\n#define kCongruentDiacritical (1 << 1)\n#define kCongruentVowel (1 << 2)\n#define kCongruentConsonant (1 << 3)\n inline bool CharsAreCongruent(char c1, char c2, unsigned char congruency)\n{\n return (_congruencyTable[c1][c2] & congruency) != 0;\n}\n\n#define CaseInsensitiveCharEqual(c1, c2) CharsAreCongruent(c1, c2, kCongruentCase)\n" }, { "answer_id": 213542, "author": "deft_code", "author_id": 28817, "author_profile": "https://Stackoverflow.com/users/28817", "pm_score": 2, "selected": false, "text": "#include <boost/algorithm/string/find.hpp>\n\nconst char* istrstr( const char* haystack, const char* needle )\n{\n using namespace boost;\n iterator_range<char*> result = ifind_first( haystack, needle );\n if( result ) return result.begin();\n\n return NULL;\n}\n" }, { "answer_id": 15758849, "author": "Lefteris E", "author_id": 1017417, "author_profile": "https://Stackoverflow.com/users/1017417", "pm_score": 1, "selected": false, "text": "#define IS_ALPHA(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z'))\n#define TO_UPPER(c) ((c) & 0xDF)\n\nchar * __cdecl strstri (const char * str1, const char * str2){\n char *cp = (char *) str1;\n char *s1, *s2;\n\n if ( !*str2 )\n return((char *)str1);\n\n while (*cp){\n s1 = cp;\n s2 = (char *) str2;\n\n while ( *s1 && *s2 && (IS_ALPHA(*s1) && IS_ALPHA(*s2))?!(TO_UPPER(*s1) - TO_UPPER(*s2)):!(*s1-*s2))\n ++s1, ++s2;\n\n if (!*s2)\n return(cp);\n\n ++cp;\n }\n return(NULL);\n}\n" }, { "answer_id": 37402374, "author": "Suzuki Keem", "author_id": 6373579, "author_profile": "https://Stackoverflow.com/users/6373579", "pm_score": 2, "selected": false, "text": "const wchar_t *szk_wcsstri(const wchar_t *s1, const wchar_t *s2)\n{\n if (s1 == NULL || s2 == NULL) return NULL;\n const wchar_t *cpws1 = s1, *cpws1_, *cpws2;\n char ch1, ch2;\n bool bSame;\n\n while (*cpws1 != L'\\0')\n {\n bSame = true;\n if (*cpws1 != *s2)\n {\n ch1 = towlower(*cpws1);\n ch2 = towlower(*s2);\n\n if (ch1 == ch2)\n bSame = true;\n }\n\n if (true == bSame)\n {\n cpws1_ = cpws1;\n cpws2 = s2;\n while (*cpws1_ != L'\\0')\n {\n ch1 = towlower(*cpws1_);\n ch2 = towlower(*cpws2);\n\n if (ch1 != ch2)\n break;\n\n cpws2++;\n\n if (*cpws2 == L'\\0')\n return cpws1_-(cpws2 - s2 - 0x01);\n cpws1_++;\n }\n }\n cpws1++;\n }\n return NULL;\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
211,536
<p>Me and some friends are writing a MORPG in Java, and we would like to use a scripting language to, eg. to create quests.</p> <p>We have non experience with scripting in Java. We have used Python, but we are very inexperienced with it. One of us also have used Javascript. </p> <p>What scripting language should we use? What scripting language should we not use? </p>
[ { "answer_id": 211555, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "javax.script" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
211,583
<p>I am using a microcontroller with a C51 core. I have a fairly timeconsuming and large subroutine that needs to be called every 500ms. An RTOS is not being used. </p> <p>The way I am doing it right now is that I have an existing Timer interrupt of 10 ms. I set a flag after every 50 interrupts that is checked for being true in the main program loop. If the Flag is true the subroutine is called. The issue is that by the time the program loop comes round to servicing the flag, it is already more than 500ms,sometimes even >515 ms in case of certain code paths. The time taken is not accurately predictable.</p> <p>Obviously, the subroutine cannot be called from inside the timer interrupt due to that large time it takes to execute.The subroutine takes 50ms to 89ms depending upon various conditions.</p> <p>Is there a way to ensure that the subroutine is called in exactly 500ms each time?</p>
[ { "answer_id": 211893, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "#define FUDGE_MARGIN 2 //In 10ms increments\n\nvolatile unsigned int ticks = 0;\n\nvoid timer_10ms_interrupt( void ) { ticks++; }\n\nvoid mainloop( void )\n{\n unsigned int next_time = ticks+50;\n\n while( 1 )\n {\n do_mainloopy_stuff();\n\n if( ticks >= next_time-FUDGE_MARGIN )\n {\n while( ticks < next_time );\n do_500ms_thingy();\n next_time += 50;\n }\n }\n}\n" }, { "answer_id": 211896, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "volatile int xtime = 0;\nvoid isr_10ms(void) {\n xtime += 10;\n}\nvoid loop(void) {\n while (1) {\n /* Do all your regular main stuff here. */\n if (xtime >= 500) {\n xtime -= 500;\n /* Do your 500ms activity here */\n }\n }\n}\n" }, { "answer_id": 234402, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 1, "selected": false, "text": "#define PREACTION_HOLD_TICKS (2)\n#define TOTAL_WAIT_TICKS (10)\n\nvolatile unsigned char pre_action_flag;\nvolatile unsigned char trigger_flag;\n\nstatic isr_ticks;\ninterrupt void timer0_isr (void) {\n isr_ticks--;\n if (!isr_ticks) {\n isr_ticks=TOTAL_WAIT_TICKS;\n trigger_flag=1;\n } else {\n if (isr_ticks==PREACTION_HOLD_TICKS)\n preaction_flag=1;\n }\n}\n\n// ...\n\nint main(...) {\n\n\nisr_ticks = TOTAL_WAIT_TICKS;\npreaction_flag = 0;\ntigger_flag = 0;\n// ...\n\n while (1) {\n if (preaction_flag) {\n preaction_flag=0;\n while(!trigger_flag)\n ;\n trigger_flag=0;\n service_routine();\n } else {\n main_processing_routines();\n }\n }\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27795/" ]
211,586
<p>I've recently heard about the <a href="http://msdn.microsoft.com/en-us/library/bb204633(VS.85).aspx" rel="nofollow noreferrer">CaptureStackBackTrace</a> function by reading <a href="https://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c">this post</a>. I cannot find it in any of my Visual Studio 2005 header files however, and I'm guessing (from the MSDN URL which mentions VS.85) that this may only be a Visual Studio 2008 thing.</p> <p>Is there a way, perhaps by manually finding the entry point in a system DLL somewhere, to get this function under Visual Studio 2005?</p>
[ { "answer_id": 211719, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 2, "selected": false, "text": "typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG);\nCaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary(\"kernel32.dll\"), \"RtlCaptureStackBackTrace\"));\n// Then use 'func' as if it were CaptureStackBackTrace\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ]
211,611
<p>I have a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> <a href="http://www.google.com/search?hl=en&amp;q=TreeView%20msdn&amp;btnG=Search" rel="noreferrer">TreeView</a> (node, subnodes). Each node contains some additional information in its Tag. Also, each nodes maps a file on the disk. What's the easiest way copy/cut/paste nodes/files in C#?</p> <p>It would be nice to have some sample code.</p>
[ { "answer_id": 211619, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "StringCollection paths = new StringCollection();\npaths.Add(\"f:\\\\temp\\\\test.txt\");\npaths.Add(\"f:\\\\temp\\\\test2.txt\");\nClipboard.SetFileDropList(paths);\n" }, { "answer_id": 213294, "author": "AR.", "author_id": 1354, "author_profile": "https://Stackoverflow.com/users/1354", "pm_score": 3, "selected": false, "text": "TreeNode selectedNode;\nTreeNode copiedNode;\n\nselectedNode = yourTreeview.SelectedNode;\n\nif (selectedNode != null)\n{\n copiedNode = selectedNode.Clone;\n}\n\n// Then you can do whatever you like with copiedNode elsewhere in your app.\n Clipboard.SetDataObjecT(yourTreeNodeDataObject);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,612
<p>There are a dozen Rails plugins whose goal is to replace fixtures in testing. Here are a few I can think of:</p> <ul> <li>fixture replacement</li> <li>factory girl</li> <li>factories and workers</li> <li>rails scenarios</li> <li>fixture-scenarios</li> <li>object daddy</li> </ul> <p>There are probably others. Which of these plugins do you prefer and why?</p>
[ { "answer_id": 211649, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 3, "selected": false, "text": "# spec/factory.rb\nmodule Factory\n def self.create_offer(options={})\n Offer.create({\n :code => Faker::Lorem.words(1),\n :expires_on => Time.now + (rand(30) + 1).day\n }.merge(options))\n end\nend\n\n\n# spec_helper.rb\nrequire 'faker'\nrequire 'spec/factory'\n\n\n# In the specs\n@offer = Factory.create_offer(:code => 'TESTING')\n" }, { "answer_id": 214227, "author": "James Baker", "author_id": 9365, "author_profile": "https://Stackoverflow.com/users/9365", "pm_score": 2, "selected": false, "text": "new_*, create_*, and default_* stub_model()" }, { "answer_id": 1061002, "author": "James Conroy-Finn", "author_id": 123142, "author_profile": "https://Stackoverflow.com/users/123142", "pm_score": 0, "selected": false, "text": "Factory.define :usa, :class => Team do |f|\n f.country_name 'USA'\n f.rank 15.6\nend\n\nFactory.define :player do |f|\n f.first_name 'Stevie'\n f.last_name 'Wonder'\n f.team Factory.build(:usa)\nend\n Factory.build(:usa) Factory.create(:usa)" }, { "answer_id": 1523938, "author": "Kyle Daigle", "author_id": 184780, "author_profile": "https://Stackoverflow.com/users/184780", "pm_score": 2, "selected": false, "text": "Factory.define :project_manager do |f|\n f.first_name \"John\"\n f.last_name \"Doe\"\nend\n\nFactory.define :project do |f|\n f.name \"Sample Project\"\n f.association :project_manager\nend\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082/" ]
211,616
<p>Objective-C is getting wider use due to its use by Apple for Mac OS X and iPhone development. What are some of your favourite "hidden" features of the Objective-C language?</p> <ul> <li>One feature per answer.</li> <li>Give an example and short description of the feature, not just a link to documentation.</li> <li>Label the feature using a title as the first line.</li> </ul>
[ { "answer_id": 211672, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": false, "text": "@interface CustomNSApplication : NSApplication\n@end\n\n@implementation CustomNSApplication\n- (void) setMainMenu: (NSMenu*) menu\n{\n // do something with menu\n}\n@end\n\nclass_poseAs ([CustomNSApplication class], [NSApplication class]);\n" }, { "answer_id": 212690, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 3, "selected": false, "text": "#include <Foundation/Debug.h>\n" }, { "answer_id": 214448, "author": "pfeilbr", "author_id": 29148, "author_profile": "https://Stackoverflow.com/users/29148", "pm_score": 4, "selected": false, "text": "-(retval_t)forward:(SEL)sel :(arglist_t)args {\n if ([myDelegate respondsTo:sel])\n return [myDelegate performv:sel :args]\n else\n return [super forward:sel :args];\n }\n" }, { "answer_id": 214628, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 4, "selected": false, "text": "sharedFoo foo foo foo foo sharedFoo foo" }, { "answer_id": 214710, "author": "Michael Ledford", "author_id": 21834, "author_profile": "https://Stackoverflow.com/users/21834", "pm_score": 2, "selected": false, "text": "MLAbstractDataPacket MLAbstractDataPacket +(BOOL)isMyKindOfDataPacket:(NSData *)data MLAbstractDataPacket +(id)initWithDataPacket:(NSData *)data objc_getClassList() objc_getSuperclass() +isMyKindOfDataPacket:" }, { "answer_id": 227402, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "[myArray writeToFile:myPath atomically:YES]" }, { "answer_id": 679866, "author": "Becca Royal-Gordon", "author_id": 41222, "author_profile": "https://Stackoverflow.com/users/41222", "pm_score": 4, "selected": false, "text": "obj->isa = [NewClass class];\n A isa LazyA release retain LazyA isa A" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2438/" ]
211,621
<p>I want to impersonate other user in Windows. For example: I create a directory with permission only for user A and for the administrators, when logon with user B and run .exe I want to impersonate user A to have permission to edit/remove/insert in that specific directory.</p> <p>I found this: <a href="http://msdn.microsoft.com/en-us/library/aa374731(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa374731(VS.85).aspx</a></p>
[ { "answer_id": 211811, "author": "brianb", "author_id": 27892, "author_profile": "https://Stackoverflow.com/users/27892", "pm_score": 0, "selected": false, "text": "AcquireCredentialsHandle()\nInitializeSecurityContext()\nAcceptSecurityContext()\nCompleteAuthToken()\n ImpersonateSecurityContext()\nRevertContext()\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,622
<p>I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging.</p> <p>Something along the lines of</p> <pre><code>static void Main () { if (Debugger.IsAttached) RunApp(); else { try { RunApp(); } catch (Exception e) { LogException(e); throw; } } } </code></pre> <p>While this all works fine, my problem is when I want to attach the debugger after the exception has been raised.</p> <p>Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost.</p> <p>Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?</p>
[ { "answer_id": 211641, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 0, "selected": false, "text": "Exception e1 = e;\nLogException(e);\nthrow(e1);\n" }, { "answer_id": 211870, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": "catch (Exception e) {\n#if DEBUG\n System.Diagnostics.Debugger.Launch()\n#endif\n LogException(e);\n throw;\n }\n" }, { "answer_id": 536210, "author": "Alexander", "author_id": 63231, "author_profile": "https://Stackoverflow.com/users/63231", "pm_score": 0, "selected": false, "text": " private static void Main(string[] args)\n {\n try\n {\n // ...\n }\n catch (Exception exception)\n {\n System.Diagnostics.Trace.Write(exception);\n #if DEBUG\n System.Diagnostics.Trace.Write(\"Waiting 20 seconds for debuggers to attach to process.\");\n System.Threading.Thread.Sleep(20000);\n System.Diagnostics.Trace.Write(\"Continue with process...\");\n #endif\n throw;\n }\n }\n" }, { "answer_id": 539502, "author": "ShuggyCoUk", "author_id": 12748, "author_profile": "https://Stackoverflow.com/users/12748", "pm_score": 2, "selected": false, "text": "#if DEBUG\nSystem.Diagnostics.Debugger.Launch()\n#endif\n" }, { "answer_id": 546922, "author": "Leaf Garland", "author_id": 30348, "author_profile": "https://Stackoverflow.com/users/30348", "pm_score": 5, "selected": true, "text": "class Program\n{\n static void Main()\n {\n AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;\n\n RunApp();\n }\n\n static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e)\n {\n Console.WriteLine(e.ExceptionObject);\n Console.WriteLine(\"Do you want to Debug?\");\n if (Console.ReadLine().StartsWith(\"y\"))\n Debugger.Break();\n }\n\n static void RunApp()\n {\n throw new Exception();\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28859/" ]
211,629
<p>How to remove the program icon from the Programs folder?</p>
[ { "answer_id": 211637, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "File.Delete(path_to_lnk_file);\n" }, { "answer_id": 211657, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": false, "text": "string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);\nstring shortcut = Path.Combine(startMenuDir, @\"The Company\\MyShortcut.lnk\");\nif (File.Exists(shortcut))\n File.Delete(shortcut);\n" }, { "answer_id": 211674, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "File.Delete(\"Shortcut to foobar.exe.lnk\");\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,634
<p>We have a Win32 application that hosts the .NET runtime and opens up .NET managed forms from the Win32 portion of the application.</p> <p>These windows are always opened as modal windows.</p> <p>On some machines, when these windows are closed, the Win32 window that lies behind does not get focus, but gets sent behind Word, Outlook, or whatever else you might have open.</p> <p>Also, sometimes, if we open such a .NET form, then alt-tab to Word or some other application, and then click on the taskbar icon for our app, the Win32 window appear. This is of course still waiting for the modal .NET window to close, so it is of course unusable. If we alt-tab to something else and just minimize that other thing, then our .NET window reappears.</p> <p>The inconsistent part is that this occurs on only some machines, and not all. On many machines, mine included, it works exactly as expected. Focus to the right window works every time.</p> <p>I don't doubt we have done something wrong, but I can't figure out what the problem is.</p> <p>Does anyone have any idea what I should be looking for? We've looked at the .NET runtimes installed, and since two such machines where it works on one but not the other are both developer machines, they contain the same service packs for .NET and so on.</p> <hr> <p><strong>Edit:</strong> Well, <a href="https://stackoverflow.com/users/7021/sam">@sam</a>, you were right in that we had some different setups in this lane. Both machines run Windows XP SP3, but mine was running classic windows theme, and the other was running the new XP theme. Changing theme on that other computer to classic removed the problem, but changing it back to the XP theme did not make it reappear.</p> <p>So now we have two machines where it work, and the customer still has the problem, even though the customer apparently runs classic theme.</p>
[ { "answer_id": 211825, "author": "thmsn", "author_id": 28145, "author_profile": "https://Stackoverflow.com/users/28145", "pm_score": 0, "selected": false, "text": "Form2 form2 = new Form2();\nform2.ShowDialog();\n form2.ShowDialog(this);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
211,648
<p>I have a form, when I click on submit button, I want to communicate with the server and get something from the server to be displayed on the same page. Everything must be done in AJAX manner. How to do it in Google App Engine? If possible, I want to do it in JQuery.</p> <p>Edit: The example in <a href="http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#" rel="nofollow noreferrer">code.google.com/appengine/articles/rpc.html</a> doesn't work on form. </p> <hr> <p>Edit: The rpc procedure <a href="http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#" rel="nofollow noreferrer">doesn't work for form</a>. </p>
[ { "answer_id": 220197, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 1, "selected": false, "text": "function jsonhandler(data) {\n // do stuff with the JSON data here\n}\n\nvar doajax = function () {\n arr = Object();\n $(\"#form_id\").children(\"input,select\").each(function() { arr[this.name] = this.value;});\n $.getJSON(\"<page to call with AJAX>\", arr, function (data) { jsonhandler(data);});\n}\n\n$(document).ready(function () {\n $(\"#submit_button_id\").replaceWith(\"<input id=\\\"sub\\\" name=\\\"sub\\\" type=\\\"button\\\" value=\\\"Submit\\\">\");\n $(\"#sub\").click(doajax);\n}\n" }, { "answer_id": 253067, "author": "Rik Heywood", "author_id": 4012, "author_profile": "https://Stackoverflow.com/users/4012", "pm_score": 3, "selected": false, "text": "$('#myFormId').submit(function() {\n // submit the form\n $(this).ajaxSubmit();\n return false;\n});\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
211,689
<p>I'm using xsd.exe to make the C# classes for our settings. I have a setting that is per-server and per-database, so I want the class to behave like Dictionary&lt;string, string[][]&gt;. So I want to be able to say</p> <pre><code>string serverName = "myServer"; int databaseId = 1; FieldSettings fieldSettings = getFieldSettings(); string[] fields = fieldSettings[serverName][databaseId]; </code></pre> <p>how do I represent that in XSD?</p>
[ { "answer_id": 211700, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "xsd [XmlIgnore]" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
211,693
<p>What steps do I need to take to get HTML documentation automatically building via the build step in Visual Studio? I have all the comments in place and the comments.xml file being generated, and Sandcastle installed. I just need to know what to add to the post-build step in order to generate the docs.</p>
[ { "answer_id": 211710, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<install-path>\\SandcastleBuilderConsole.exe ProjectName.shfb\n CALL \"$(ProjectDir)PostBuild.cmd\" $(ConfigurationName)\n" }, { "answer_id": 5200822, "author": "Chev", "author_id": 498624, "author_profile": "https://Stackoverflow.com/users/498624", "pm_score": 6, "selected": true, "text": "SandcastleBuilderConsole.exe MSBuild.exe IF \"$(ConfigurationName)\"==\"Release\" Goto Exit\n\n\"$(SystemRoot)\\microsoft.net\\framework64\\v4.0.30319\\msbuild.exe\" /p:CleanIntermediates=True /p:Configuration=Release \"$(SolutionDir)ProjectName\\doc\\DocumentationProjectName.shfbproj\"\n\n:Exit\n framework64 framework msbuild.exe ProjectName\\ doc" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
211,694
<p>I am writing controls that work nice with JavaScript, but they have to work even without it. Now testing with selenium works fine for me. But all test with disabled JavaScript (in my browser) won't run with selenium. Is there a way to do automated test for this purpose?</p>
[ { "answer_id": 214739, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 2, "selected": true, "text": "use Test::More tests => 5;\nuse Test::WWW::Mechanize;\n\nmy $mech = Test::WWW::Mechanize->new;\n\n# Test you can get http://petdance.com\n$mech->get_ok( \"http://petdance.com\" );\n\n# Test the <BASE> tag\n$mech->base_is( 'http://petdance.com/', 'Proper <BASE HREF>' );\n\n# Test the <TITLE>\n$mech->title_is( \"Invoice Status\", \"Make sure we're on the invoice page\" );\n\n# Test the text of the page contains \"Andy Lester\"\n$mech->content_contains( \"Andy Lester\", \"My name somewhere\" );\n\n# Test that all links on the page succeed.\n$mech->page_links_ok('Check all links');\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p> <p>I <em>thought</em> that I should be able to do</p> <pre><code>options = object() </code></pre> <p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p> <pre><code>options.VERBOSE = True Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'VERBOSE' </code></pre> <p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
[ { "answer_id": 211774, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "import collections\nopt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')\nmyoptions=opt(True, False)\n\n>>> myoptions\noptions(VERBOSE=True, IGNORE_WARNINGS=False)\n>>> myoptions.VERBOSE\nTrue\n class options(object):\n pass\n\nmyoptions=options()\nmyoptions.VERBOSE=True\nmyoptions.IGNORE_WARNINGS=False\n>>> myoptions.IGNORE_WARNINGS,myoptions.VERBOSE\n(False, True)\n" }, { "answer_id": 211918, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 3, "selected": false, "text": "class attrdict(dict):\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n self.__dict__ = self\n >>> ad = attrdict({'foo': 100, 'bar': 200})\n>>> ad.foo\n100\n>>> ad.bar\n200\n>>> ad.baz = 'hello'\n>>> ad.baz\n'hello'\n>>> ad\n{'baz': 'hello', 'foo': 100, 'bar': 200}\n>>> isinstance(ad, dict)\nTrue\n" }, { "answer_id": 211970, "author": "mhagger", "author_id": 24478, "author_profile": "https://Stackoverflow.com/users/24478", "pm_score": 2, "selected": false, "text": "class attrdict2(object):\n def __init__(self, *args, **kwargs):\n self.__dict__.update(*args, **kwargs)\n dict ad.has_key attrdict2 attrdict attrdict2 >>> ad = attrdict2(foo = 100, bar = 200)\n attrdict2 dict class attrdict3(object):\n pass\n\nad = attrdict3()\nad.foo = 100\nad.bar = 200\n" }, { "answer_id": 212010, "author": "mhagger", "author_id": 24478, "author_profile": "https://Stackoverflow.com/users/24478", "pm_score": 1, "selected": false, "text": "class options(object):\n VERBOSE = True\n IGNORE_WARNINGS = False\n\noptions.VERBOSE = False\n\nif options.VERBOSE:\n ...\n options" }, { "answer_id": 212144, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 1, "selected": false, "text": "class Struct:\n def __init__(self, **entries): \n self.__dict__.update(entries)\n john = Struct(name='john doe', salary=34000)\nprint john.salary\n namedtuple namedtuple" }, { "answer_id": 212187, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": ">>> x = lambda: 0 # any function will do\n>>> x.foo = 'bar'\n>>> x.bar = 0\n>>> x.xyzzy = x\n>>> x.foo\n'bar'\n>>> x.bar\n0\n>>> x.xyzzy\n<function <lambda> at 0x6cf30>\n >>> dir(x)\n['__call__', '__class__', '__delattr__', '__dict__', '__doc__',\n'__get__', '__getattribute__', '__hash__', '__init__',\n'__module__', '__name__', '__new__', '__reduce__',\n'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'foo',\n'func_closure', 'func_code', 'func_defaults', 'func_dict',\n'func_doc', 'func_globals', 'func_name', 'xyzzy']\n" }, { "answer_id": 212299, "author": "David Eyk", "author_id": 18950, "author_profile": "https://Stackoverflow.com/users/18950", "pm_score": 4, "selected": true, "text": "class options(object):\n VERBOSE = True\n IGNORE_WARNINGS = True\n\nif options.VERBOSE:\n # ...\n options.py options.py VERBOSE = True\nIGNORE_WARNINGS = True\n main.py import options\n\nif options.VERBOSE:\n # ...\n" }, { "answer_id": 212959, "author": "alif", "author_id": 12650, "author_profile": "https://Stackoverflow.com/users/12650", "pm_score": 3, "selected": false, "text": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nfile = options.filename\nif options.quiet == True:\n [...]\n" }, { "answer_id": 216453, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 2, "selected": false, "text": "type options = type('Options', (object,), { 'VERBOSE': True })()\noptions.IGNORE_WARNINGS = False\n Options = type('Options', (object,), {})\noptions = Options()\noptions.VERBOSE = True\noptions.IGNORE_WARNINGS = False\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24478/" ]
211,703
<p>Is this doable in either IE7 or Firefox?</p>
[ { "answer_id": 211732, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "$('#myelement.').offset();\n" }, { "answer_id": 211737, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 6, "selected": true, "text": "var e = document.getElementById('xxx');\nvar offset = {x:0,y:0};\nwhile (e)\n{\n offset.x += e.offsetLeft;\n offset.y += e.offsetTop;\n e = e.offsetParent;\n}\n\nif (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft))\n{\n offset.x -= document.documentElement.scrollLeft;\n offset.y -= document.documentElement.scrollTop;\n}\nelse if (document.body && (document.body.scrollTop || document.body.scrollLeft))\n{\n offset.x -= document.body.scrollLeft;\n offset.y -= document.body.scrollTop;\n}\nelse if (window.pageXOffset || window.pageYOffset)\n{\n offset.x -= window.pageXOffset;\n offset.y -= window.pageYOffset;\n}\n\nalert(offset.x + '\\n' + offset.y);\n" }, { "answer_id": 211935, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "$('divname').viewportOffset.top\n$('divname').viewportOffset.left\n" }, { "answer_id": 36233305, "author": "Himanshu P", "author_id": 1091378, "author_profile": "https://Stackoverflow.com/users/1091378", "pm_score": 4, "selected": false, "text": "getBoundingClientRect() var viewportOffset = el.getBoundingClientRect();\n// these are relative to the viewport, i.e. the window\nvar top = viewportOffset.top;\nvar left = viewportOffset.left;\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
211,715
<p>How does one execute some VBA code periodically, completely automated?</p>
[ { "answer_id": 211742, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "Sub MyTimer()\n Application.Wait Now + TimeValue(\"00:00:05\")\n MsgBox (\"5 seconds\")\nEnd Sub\n" }, { "answer_id": 211779, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": true, "text": "Option Explicit\n\nPrivate m_dtNextTime As Date\nPrivate m_dtInterval As Date\n\nPublic Sub Enable(Interval As Date)\n Disable\n m_dtInterval = Interval\n StartTimer\nEnd Sub\n\nPrivate Sub StartTimer()\n m_dtNextTime = Now + m_dtInterval\n Application.OnTime m_dtNextTime, \"MacroName\"\nEnd Sub\n\nPublic Sub MacroName()\n On Error GoTo ErrHandler:\n ' ... do your stuff here\n\n ' Start timer again\n StartTimer\n Exit Sub\nErrHandler:\n ' Handle errors, restart timer if desired\nEnd Sub\n\nPublic Sub Disable()\n On Error Resume Next ' Ignore errors\n Dim dtZero As Date\n If m_dtNextTime <> dtZero Then\n ' Stop timer if it is running\n Application.OnTime m_dtNextTime, \"MacroName\", , False\n m_dtNextTime = dtZero\n End If\n m_dtInterval = dtZero\nEnd Sub\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9095/" ]
211,717
<p>Is there a function in Common Lisp that takes a string as an argument and returns a keyword?</p> <p>Example: <code>(keyword "foo")</code> -> <code>:foo</code></p>
[ { "answer_id": 211786, "author": "Jonathan Wright", "author_id": 28840, "author_profile": "https://Stackoverflow.com/users/28840", "pm_score": -1, "selected": false, "text": "(intern \"foo\" \"KEYWORD\") -> :foo\n" }, { "answer_id": 211806, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "make-keyword intern KEYWORD (defun make-keyword (name) (values (intern name \"KEYWORD\")))\n" }, { "answer_id": 556001, "author": "Leslie P. Polzer", "author_id": 19619, "author_profile": "https://Stackoverflow.com/users/19619", "pm_score": 5, "selected": false, "text": "CL-USER(4): (intern \"foo\" :keyword)\n\n:|foo|\nNIL\nCL-USER(5): (eq * :foo)\n\nNIL\n (defun make-keyword (name) (values (intern (string-upcase name) \"KEYWORD\")))\n" }, { "answer_id": 12118364, "author": "Samuel Edwin Ward", "author_id": 894885, "author_profile": "https://Stackoverflow.com/users/894885", "pm_score": 2, "selected": false, "text": "make-keyword" }, { "answer_id": 15658042, "author": "Paulo Tomé", "author_id": 2152558, "author_profile": "https://Stackoverflow.com/users/2152558", "pm_score": 1, "selected": false, "text": "(defun make-keyword (name) (values (intern (substitute #\\. #\\space (string-upcase name)) :keyword)))\n" }, { "answer_id": 55526783, "author": "I.Omar", "author_id": 5556374, "author_profile": "https://Stackoverflow.com/users/5556374", "pm_score": 1, "selected": false, "text": ": read-from-string make-keyword (defun make-keyword (name)\n (read-from-string (concatenate 'string \":\" name)))\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18480/" ]
211,718
<p>Why doesn't the code below work? The idea is that the page checks to see if the dropdown variable has changes since you last refreshed the page.</p> <pre><code> &lt;logic:equal name="Result" value = "-1"&gt; &lt;bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:equal&gt; &lt;logic:equal name="Result" value = "-1"&gt; &lt;bean:define id="DropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:equal&gt; &lt;-- when you fisrt access this page from the above are run --&gt; &lt;bean:define id="NewDropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "sess &lt;-- this happens everytime the page is refreshed--&gt; &lt;logic:equal name= DropDownValue value = NewDropDownValue&gt; &lt;bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:equal&gt; &lt;logic:notEqual name="DropDownValue" value = "NewDropDownValue"&gt; &lt;bean:define id="DropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:notEqual&gt; </code></pre>
[ { "answer_id": 211797, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 0, "selected": false, "text": "<logic:equal name= DropDownValue value = NewDropDownValue>\n" }, { "answer_id": 216926, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 1, "selected": false, "text": "toScope=\"sess\n <logic:equal name=\"DropDownValue\" value=\"<%=NewDropDownValue/>\">\n" }, { "answer_id": 269963, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "if result == -1\n define JOININGDATE\nend\nif result == -1\n define DropDownValue\nend\n if result == -1\n define JOININGDATE\n define DropDownValue\nend\n// otherwise don't define both values\n" }, { "answer_id": 271525, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 0, "selected": false, "text": "<logic:equal name=\"Result\" value = \"-1\">\n <bean:define id=\"JOININGDATE\" name=\"smlMoverDetailForm\" property=\"empFDJoiningDate\"\n type=\"java.lang.String\" toScope = \"session\" />\n </logic:equal> \n\n\n<logic:equal name=\"Result\" value = \"-1\">\n <bean:define id=\"DropDownValue\" name=\"smlMoverDetailForm\" property=\"moverChangeType\" \n type=\"java.lang.String\" toScope = \"session\" /> \n</logic:equal>\n\n<!-- when you fisrt access this page from the above are run -->\n\n<bean:define id=\"NewDropDownValue\" name=\"smlMoverDetailForm\"\n property=\"moverChangeType\" type=\"java.lang.String\" toScope = \"session\"/>\n\n<!-- this happens everytime the page is refreshed-->\n\n<logic:equal name=\"DropDownValue\" value=\"<%=request.getSession().getAttribute(\"NewDropDownValue\").toString()%>\">\n <bean:define id=\"JOININGDATE\" name=\"smlMoverDetailForm\"\n property=\"empFDJoiningDate\" type=\"java.lang.String\" toScope =\"session\" />\n</logic:equal>\n\n<logic:notEqual name=\"DropDownValue\" value=\"NewDropDownValue\">\n <bean:define id=\"DropDownValue\" name=\"smlMoverDetailForm\" \n property=\"moverChangeType\" type=\"java.lang.String\" toScope = \"session\"/> \n</logic:notEqual>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,741
<p>The string formatting concept found in <strong>sprintf</strong> can be found in almost any language today <em>(you know, smothering a string with %s %d %f etc. and providing a list of variables to fill their places)</em>. </p> <p><strong>Which langugage was it originally that had a library function or language construct which offered this functionality?</strong></p> <p>Please specify some kind of source reference to confirm your claim, so that we avoid pure speculation or guessing.</p> <p>Regards</p> <p>Robert</p>
[ { "answer_id": 211814, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "writef() %i2 %2d" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
211,758
<p>I have a sproc that returns a single line and column with a text, I need to set this text to a variable, something like:</p> <pre><code>declare @bla varchar(100) select @bla = sp_Name 9999, 99989999, 'A', 'S', null </code></pre> <p>but of course, this code doesn't work...</p> <p>thanks!</p>
[ { "answer_id": 211778, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": false, "text": "CREATE PROCEDURE dbo.sp_Name\n @In INT,\n @Out VARCHAR(100) OUTPUT\n\nAS\nBEGIN\n SELECT @Out = 'Test'\nEND\nGO\n DECLARE @OUT VARCHAR(100)\nEXEC sp_name 1, @Out OUTPUT\nPRINT @Out\n" }, { "answer_id": 211815, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 6, "selected": true, "text": "DECLARE @Output VARCHAR(100)\n\nCREATE TABLE #tmpTable\n(\n OutputValue VARCHAR(100)\n)\nINSERT INTO #tmpTable (OutputValue)\nEXEC dbo.sp_name 9999, 99989999, 'A', 'S', null\n\nSELECT\n @Output = OutputValue\nFROM \n #tmpTable\n\nDROP TABLE #tmpTable\n" }, { "answer_id": 211886, "author": "DiGi", "author_id": 12042, "author_profile": "https://Stackoverflow.com/users/12042", "pm_score": 4, "selected": false, "text": "DECLARE\n @out INT\n\nEXEC @out = sp_name 'param', 2, ...\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648/" ]
211,760
<p>Is there any way to run ASDoc on your project via the Flex Builder UI? Or, is there a good (preferably free) plugin that will do so?</p> <p>If there is no UI for it, does someone have a link to a tutorial on how to set it up to be automatic when I build my project, maybe via Ant (which I've never used, but am more than happy to try) or something? (sorry for the multi-part question)</p>
[ { "answer_id": 6752185, "author": "Will", "author_id": 852622, "author_profile": "https://Stackoverflow.com/users/852622", "pm_score": 2, "selected": false, "text": "${project_loc}" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5421/" ]
211,761
<p>For a Silverlight 2 webapp. I added a combobox. I have an IEnumerable as Itemsource to populate the combobox. Works fine.</p> <p>But I would like to add an extra item ("please select a....") to the combobox, anyone an idea how this can be done using the Silverlight 2 combobox.</p> <p>Any more info about using a template for the ComboxboxItems is welcome as well.</p>
[ { "answer_id": 313815, "author": "David Casey", "author_id": 36588, "author_profile": "https://Stackoverflow.com/users/36588", "pm_score": 0, "selected": false, "text": "List<> E.Result.Items.Insert(0, new object { param1 = \"\", Param2 = \"\"} );\n" }, { "answer_id": 2861205, "author": "Sitab Bhandari", "author_id": 344505, "author_profile": "https://Stackoverflow.com/users/344505", "pm_score": 0, "selected": false, "text": "SilverlightApplication1.ServiceReference1.Region item = \n new SilverlightApplication1.ServiceReference1.Region ();\nitem.RegionID = 0;\nitem.RegionDescription = \"-Select Region-\";\ne.Result.Insert(0, item);\n\ndrControl.ItemsSource = e.Result; ////////.Result; \ndrControl.SelectedIndex = 0; \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,769
<p>Coming from a Ruby background, I'm used to writing all my code using classes with methods and such. I do know javascript quite well, but I'm new to jQuery and its best practices.</p> <p>Obviously there are a million ways to simulate classes in javascript. But, what is the actual jQuery community REALLY using in the real world?</p> <p>Specific examples would be ideal. Or links to real production code. Links to fictional ideal code would also be helpful.</p> <p>Thanks!</p>
[ { "answer_id": 222278, "author": "Zac", "author_id": 5630, "author_profile": "https://Stackoverflow.com/users/5630", "pm_score": 2, "selected": false, "text": "var Widget = {\n\n sound:'bleep',\n\n load:function(){\n\n // do stuff here that doesn't need to wait until the DOM is ready.\n\n // Inside an anonymous function (such as the 'click' handler below),\n // 'this' loses its scope and no longer refers to the widget object.\n // To retain a reference to the widget object, assign 'this' to a\n // variable. I use an underscore... some people like 'self':\n var _ = this;\n\n // when the DOM is ready, run the init \"method\":\n $(document).ready(function(){\n _.init(); // the underscore now refers to the widget object\n });\n\n },\n\n init:function(){\n\n var _ = this;\n\n // whenever a <p class=\"noisy\"> element is clicked, call makeNoise()\n $(\"p.noisy\").click(function(){\n _.makeNoise();\n });\n\n },\n\n makeNoise:function(){\n\n alert(this.sound); // alert 'bleep'\n\n }\n\n};\n\nWidget.load();\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483628/" ]
211,795
<p>What are the established coding standards for JavaScript?</p>
[ { "answer_id": 214256, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 5, "selected": false, "text": "return // injected semicolon, therefore returns 'undefined'\n{\n javascript : \"fantastic\"\n}; // object constructs anonymously but nothing happens with it.\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25174/" ]
211,800
<p>I have no idea. This causes seemingly random time-outs. These in turn break the flash that i am loading it into. Has anyone seen anything like this before?</p> <pre><code>&lt;?php require_once("../includes/class.database.php"); require_once("../includes/dbConnectInfo.inc"); require_once("../includes/functions.php"); include("../includes/conn.php"); $cat = $_GET['category']; $result = mysql_query("SELECT * FROM media WHERE related_page_id=4 &amp;&amp; type='copy' ORDER BY id ASC LIMIT 6"); $media = "&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?&gt;\n"; $media .= "&lt;content&gt;\n"; while($row = mysql_fetch_array($result)) { $media .="&lt;member&gt;\n"; $body = $row[copy]; if($row[title] == "") { $media .= "&lt;title&gt;&lt;![CDATA["; $media .= "Team"; $media .="]]&gt;&lt;/title&gt;\n"; } elseif ($row['path']=="") { $name = explode("/",$row[title],2); $media .= "&lt;name&gt;&lt;![CDATA["; $media .= $name[0]; $media .="]]&gt;&lt;/name&gt;\n"; $media .= "&lt;job&gt;&lt;![CDATA["; $media .= $name[1]; $media .="]]&gt;&lt;/job&gt;\n"; } if($body !="") { $media .="&lt;bio&gt;&lt;![CDATA["; $media .= $body; $media .= "]]&gt;&lt;/bio&gt;\n"; } $something = $row['id']; $result1 = mysql_query("SELECT * FROM media WHERE assets='$something'"); $media .= "&lt;images&gt;"; while($row1 = mysql_fetch_array($result1)) { $img = explode("/",$row1[path],2); $media .= "&lt;image url='$img[1]' /&gt;"; } $media .= "&lt;/images&gt;\n"; $media .="&lt;/member&gt;\n"; } $media .= "&lt;/content&gt;"; echo $media; ?&gt; </code></pre>
[ { "answer_id": 211807, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": true, "text": "set_time_limit(0); set_time_limit" }, { "answer_id": 211823, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "related_page_id type assets set_time_limit(0);" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
211,819
<p>When doing a <code>cvs update</code>, you get a nice summary of the state of the repository, for example:</p> <pre><code>M src/file1.txt M src/file2.txt C src/file3.txt A src/file4.txt ? src/file5.txt </code></pre> <p>Is there a way to get this without actually updating? I know there is <code>cvs status</code>, but this is way to verbose:</p> <pre><code>=================================================================== File: file6.txt Status: Up-to-date Working revision: 1.2 Repository revision: 1.2 /var/cvs/cvsroot/file6.txt,v Sticky Tag: (none) Sticky Date: (none) Sticky Options: (none) </code></pre> <p>I could of course make a script to do the transformation from the latter to the former, but it seems a waste of time since cvs can obviously produce the former.</p>
[ { "answer_id": 211821, "author": "jmcnamara", "author_id": 10238, "author_profile": "https://Stackoverflow.com/users/10238", "pm_score": 6, "selected": true, "text": "cvs -q -n update\n" }, { "answer_id": 211915, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "cvs -q status \"$@\" | grep '^[?F]' | grep -v 'Up-to-date'\n" }, { "answer_id": 270760, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 2, "selected": false, "text": "cvs status -q cvs status -qq" }, { "answer_id": 20122122, "author": "Kiril Kirov", "author_id": 435800, "author_profile": "https://Stackoverflow.com/users/435800", "pm_score": 2, "selected": false, "text": "alias cvsstatus_command='cvs -q status | grep \"^[?F]\" | grep -v \"Up-to-date\" | \\\n grep -v \"\\.so\" | grep -v \"\\.[c]*project\"'\n\nalias cvsstatus_color='nawk '\"'\"'BEGIN \\\n { \\\n arr[\"Needs Merge\"] = \"0;31\"; \\\n arr[\"Needs Patch\"] = \"1;31\"; \\\n arr[\"conflicts\"] = \"1;33\"; \\\n arr[\"Locally Modified\"] = \"0;33\"; \\\n arr[\"Locally Added\"] = \"0;32\" \\\n } \\\n { \\\n l = $0; \\\n for (pattern in arr) { \\\n gsub(\".*\" pattern \".*\", \"\\033[\" arr[pattern] \"m&\\033[0m\", l); \\\n } \\\n print l; \\\n }'\"'\"\n\nalias cvsstatus='cvsstatus_command | cvsstatus_color'\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3102/" ]
211,834
<p>OK... I'm a VB.NET WinForms guy trying to understand WPF and all of its awesomeness. I'm writing a basic app as a learning experience, and have been reading lots of information and watching tutorial videos, but I just can't get off the ground with simple DataBinding, and I know I'm missing some basic concept. As much as I'd love it, I haven't had that "Aha!" moment when reviewing source code yet.</p> <p>So... In my Window class I defined a custom string Property. When I go into Blend, I try to databind my TextBox's Text to this property, but my Property doesn't show up in Blend as something that available for Binding to.</p> <p>Can someone tell me what I need to add to my code/XAML below... and most importantly why?</p> <p>My XAML:</p> <pre><code>&lt;Window x:Class="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;Grid&gt; &lt;TextBox Text="How do I Bind my SomeText property here?"&gt;&lt;/TextBox&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>My Window Code:</p> <pre><code>Class Window1 Private _sometext As String = "Hello World" Public Property SomeText() As String Get Return _sometext End Get Set(ByVal value As String) _sometext = value End Set End Property End Class </code></pre>
[ { "answer_id": 211990, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 4, "selected": true, "text": "<Window x:Class=\"Window1\" \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title=\"Window1\" Height=\"300\" Width=\"300\" \n DataContext=\"{Binding RelativeSource={RelativeSource Self}}\"> \n <Grid> \n <TextBox Text=\"{Binding SomeText}\">\n </TextBox> \n </Grid>\n </Window>\n" }, { "answer_id": 212015, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 3, "selected": false, "text": "<Window\n x:Class=\"WpfApplication2.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Name=\"theWindow\"\n Title=\"Window1\"\n Height=\"300\"\n Width=\"300\"\n>\n <Grid>\n <StackPanel>\n <TextBox Text=\"{Binding ElementName=theWindow, Path=SomeText}\"/>\n <Button\n Width=\"100\"\n Height=\"25\"\n Content=\"Change Text\"\n Click=\"Button_Click\"\n />\n </StackPanel>\n </Grid>\n</Window>\n /// <summary>\n/// Interaction logic for Window1.xaml\n/// </summary>\npublic partial class Window1 : Window, INotifyPropertyChanged\n{\n public Window1()\n {\n InitializeComponent();\n }\n\n private string _someText = \"Hello World!\";\n public string SomeText\n {\n get { return _someText; }\n set\n {\n _someText = value;\n OnNotifyPropertyChanged(\"SomeText\");\n }\n }\n\n #region INotifyPropertyChanged Members\n\n public event PropertyChangedEventHandler PropertyChanged;\n private void OnNotifyPropertyChanged(string propertyName)\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n #endregion\n\n private void Button_Click(object sender, RoutedEventArgs e)\n {\n this.SomeText = \"Goodbye World!\";\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641985/" ]
211,839
<p>We get this error in Visual Studio 2005 and TFS very often.</p> <p>Can anyone help us pinpoint the cause for this message?</p> <p>The full message is:</p> <blockquote> <p>There appears to be a discrepancy between the solution's source control information about some project(s) and the information in the project file(s).</p> <p>To resolve this discrepancy it will be necessary to check out the project file(s) and update them. If the check out fails, however, and the solution is closed without saving, you will see this warning again the next time you open the solution.</p> </blockquote> <p>Clicking OK eventually lead to a checkout box where it wants to check out a whole list of project files. However, the "Change source control" window doesn't show anything wrong, and saving everything and just checking it back in just ends up as "Nothing was changed, undoing everything" type of message.</p> <p><strong>Edit:</strong> You're right, <a href="https://stackoverflow.com/users/2915/adam-davis">@Adam</a>, we have converted from VSS, but we went through such a procedure to cleanup the bindings when we did this a while ago and everything was peachy. The error has started cropping up lately.</p>
[ { "answer_id": 14160013, "author": "user1948985", "author_id": 1948985, "author_profile": "https://Stackoverflow.com/users/1948985", "pm_score": 0, "selected": false, "text": "SccProjectUniqueName6 = Project1\\\\Project1.csproj\nSccProjectName6 = \\u0022$/Project1\\u0022,\\u0020HSBAAAAA\nSccLocalPath6 = Project1\n SccProjectUniqueName6 = Project1\\\\Project1.csproj\nSccLocalPath6 = .\nSccProjectFilePathRelativizedFromConnection6 = Project1\\\\\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
211,875
<p>I have a string column in a database table which maps to an Enum in code. In my dbml file when I set the "Type" to <code>MyTypes.EnumType</code> I get the following error:</p> <blockquote> <p>Error 1 DBML1005: Mapping between DbType 'VarChar(50) NOT NULL' and Type 'MyTypes.EnumType' in Column 'EnumCol' of Type 'Table1' is not supported.</p> </blockquote> <p>This question: <a href="https://stackoverflow.com/questions/4939/linq-to-sql-strings-to-enums">LINQ to SQL strings to enums</a> indicates that what I am trying to do is possible, but how is it done?</p>
[ { "answer_id": 211894, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "global:: namespace Foo.Bar\n{\n public enum MyEnum\n {\n France,\n Belgium,\n Brazil,\n Switzerland\n }\n}\n <Column Name=\"ShipCountry\" Type=\"Foo.Bar.MyEnum\" DbType=\"NVarChar(15)\" CanBeNull=\"true\" />\n private Foo.Bar.MyEnum _ShipCountry;\n//...\n[Column(Storage=\"_ShipCountry\", DbType=\"NVarChar(15)\", CanBeNull=true)]\npublic Foo.Bar.MyEnum ShipCountry\n{ get {...} set {...} }\n using (DataClasses1DataContext ctx = new DataClasses1DataContext())\n{\n var qry = from order in ctx.Orders\n where order.ShipCountry == Foo.Bar.MyEnum.Brazil\n || order.ShipCountry == Foo.Bar.MyEnum.Belgium\n select order;\n foreach (var order in qry.Take(10))\n {\n Console.WriteLine(\"{0}, {1}\", order.OrderID, order.ShipCountry);\n }\n}\n 10250, Brazil\n10252, Belgium\n10253, Brazil\n10256, Brazil\n10261, Brazil\n10287, Brazil\n10290, Brazil\n10291, Brazil\n10292, Brazil\n10299, Brazil\n" }, { "answer_id": 1583931, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 4, "selected": false, "text": "global::" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28889/" ]
211,885
<p>When a script runs under Apache, I insert <code>$_SERVER['SERVER_NAME']</code> value into an error reporting e-mail message.</p> <p>However, if a Web script forks a "worker" job with <code>nohup php ...</code>, <code>$_SERVER['SERVER_NAME']</code> appears to be empty there. Thus, if an error occurs, it's reported without a host name.</p> <p>Can I reliably get the host name by means of PHP, without calling Unix <code>hostname</code> command? </p>
[ { "answer_id": 216417, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "_GLOBALS['MACHINENAME'] globals array" }, { "answer_id": 17710031, "author": "ghbarratt", "author_id": 729759, "author_profile": "https://Stackoverflow.com/users/729759", "pm_score": 1, "selected": false, "text": "$hostname = gethostname(); $hostname = php_uname('n'); $hostname = getenv('HOSTNAME'); \n$hostname = trim(`hostname`); \n$hostname = preg_replace('#^\\w+\\s+(\\w+).*$#', '$1', exec('uname -a')); \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6430/" ]
211,934
<p>I'm sure this problem has been solved before and I'm curious how its done. I have code in which, when run, I want to scan the contents of a directory and load in functionality.</p> <p>Specifically, I am working with a scripting engine that I want to be able to add function calls to. I want the core engine to provide very limited functionality. The user should be able to add additional functions through 3rd party libraries, which I want the engine to scan for and load. How is this done?</p>
[ { "answer_id": 211949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "LoadLibrary GetProcAddress dlopen dlsym" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10093/" ]
211,958
<p><strong>EDIT: I missed a crucial point: .NET 2.0</strong></p> <p>Consider the case where I have a list of unsorted items, for the sake of simplicity of a type like this:</p> <pre><code>class TestClass { DateTime SomeTime; decimal SomePrice; // constructor } </code></pre> <p>I need to create a report-like output, where the total prices for each day are accumulated. There should be one line for each item, folled by the appropriate summary lines.</p> <p>Take this test data:</p> <pre><code>List&lt;TestClass&gt; testList = new List&lt;TestClass&gt; { new TestClass(new DateTime(2008,01,01), 12), new TestClass(new DateTime(2007,01,01), 20), new TestClass(new DateTime(2008,01,01), 18) }; </code></pre> <p>The desired output would be something like this:</p> <pre><code>2007-01-01: 20 Total: 20 2008-01-01: 12 18 Total: 30 </code></pre> <p>What's the best way to approach such scenarios? In the case of such a list, I would implement the IComparable interface for TestClass, so that the list can be sorted.</p> <p>To create the report itself, something like this could be used (let's assume that we have methods for tasks like accumulating the prices, keeping track of the current date etc):</p> <pre><code>for (int i=0;i&lt;testList.Count;i++) { if (IsNewDate(testList[i])) { CreateSummaryLine(); ResetValuesForNewDate(); } AddValues(testList[i]); } // a final summary line is needed to include the data for the last couple of items. CreateSummaryLine(); </code></pre> <p>This works alright, but I have a strange feeling as far as the second "CreateSummaryLines" is concerned.</p> <p>In what ways do you handle such situations (especially considering the fact, the we need to work with a List&lt;> of items rather than a pre-categorized Dictionary or something like that)?</p>
[ { "answer_id": 211978, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": " var groups = from row in testList\n group row by row.SomeTime;\n foreach (var group in groups.OrderBy(group => group.Key))\n {\n Console.WriteLine(group.Key);\n foreach(var item in group.OrderBy(item => item.SomePrice))\n {\n Console.WriteLine(item.SomePrice);\n }\n Console.WriteLine(\"Total\" + group.Sum(x=>x.SomePrice));\n }\n" }, { "answer_id": 211979, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "var days = from test in testList group test by test.SomeTime;\nforeach (var day in days) {\n var sum = day.Sum(x => x.SomePrice);\n Report(day, sum);\n}\n day" }, { "answer_id": 212000, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "var grouped = new SortedDictionary<DateTime, List<TestClass>>();\nforeach (TestClass entry in testList) {\n DateTime date = entry.SomeTime.Date;\n if (!grouped.ContainsKey(date)) {\n grouped[date] = new List<TestClass>();\n }\n grouped[date].Add(entry);\n}\n\nforeach (KeyValuePair<DateTime, List<TestClass>> pair in testList) {\n Console.WriteLine(\"{0}: \", pair.Key);\n Console.WriteLine(BuildSummaryLine(pair.Value));\n}\n" }, { "answer_id": 212218, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "public interface IReport\n{\n string GetTextReportDocument();\n byte[] GetPDFReportDocument(); // needing this triggers the development of interface\n}\n\npublic class SalesReport : IReport\n{\n public void AddSale( Sale newSale )\n {\n this.Sales.Add(newSale); // or however you implement it\n }\n\n public string GetTextReportDocument()\n {\n StringBuilder reportBuilder = new StringBuilder();\n var groups = from row in this.Sales\n group row by row.SomeTime.Date;\n foreach (var group in groups.OrderBy(group => group.Key))\n { \n reportBuilder.AppendLine(group.Key);\n foreach(var item in group.OrderBy(item => item.SomePrice)) \n {\n reportBuilder.AppendLine(item.SomePrice);\n }\n reportBuilder.AppendLine(\"Total\" + group.Sum(x=>x.SomePrice));\n }\n\n return reportBuilder.ToString();\n }\n\n public byte[] GetPDFReportDocument()\n {\n return PDFReporter.GenerateDocumentFromXML( this.ConvertSalesToXML() );\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17378/" ]
211,971
<p>WPF, Browserlike app.<br> I got one page containing a ListView. After calling a PageFunction I add a line to the ListView, and want to scroll the new line into view:</p> <pre><code> ListViewItem item = ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem; if (item != null) ScrollIntoView(item); </code></pre> <p>This works. As long as the new line is in view the line gets the focus like it should.</p> <p>Problem is, things don't work when the line is not visible.<br> If the line is not visible, there is no ListViewItem for the line generated, so ItemContainerGenerator.ContainerFromIndex returns null.</p> <p>But without the item, how do I scroll the line into view? Is there any way to scroll to the last line (or anywhere) without needing an ListViewItem?</p>
[ { "answer_id": 211984, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 5, "selected": true, "text": "null VirtualizingStackPanel vsp = \n (VirtualizingStackPanel)typeof(ItemsControl).InvokeMember(\"_itemsHost\",\n BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic, null, \n _listView, null);\n\ndouble scrollHeight = vsp.ScrollOwner.ScrollableHeight;\n\n// itemIndex_ is index of the item which we want to show in the middle of the view\ndouble offset = scrollHeight * itemIndex_ / _listView.Items.Count;\n\nvsp.SetVerticalOffset(offset);\n" }, { "answer_id": 213095, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 2, "selected": false, "text": "<ListView>\n ...\n <ListView.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel/>\n </ItemsPanelTemplate>\n </ListView.ItemsPanel>\n</ListView>\n" }, { "answer_id": 229259, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 5, "selected": false, "text": "public void ScrollToLastItem()\n{\n lv.SelectedItem = lv.Items.GetItemAt(rows.Count - 1);\n lv.ScrollIntoView(lv.SelectedItem);\n ListViewItem item = lv.ItemContainerGenerator.ContainerFromItem(lv.SelectedItem) as ListViewItem;\n item.Focus();\n}\n" }, { "answer_id": 686940, "author": "Echilon", "author_id": 30512, "author_profile": "https://Stackoverflow.com/users/30512", "pm_score": 2, "selected": false, "text": "if(currentRow >= 0 && currentRow < lstGrid.Items.Count) {\n lstGrid.SelectedIndex = currentRow;\n lstGrid.ScrollIntoView(lstGrid.SelectedItem);\n if(shouldFocusGrid) {\n ListViewItem item = lstGrid.ItemContainerGenerator.ContainerFromItem(lstGrid.SelectedItem) as ListViewItem;\n item.Focus();\n }\n} else if(shouldFocusGrid) {\n lstGrid.Focus();\n}\n" }, { "answer_id": 1305542, "author": "Joseph jun. Melettukunnel", "author_id": 123172, "author_profile": "https://Stackoverflow.com/users/123172", "pm_score": 3, "selected": false, "text": " public void ScrollToLastItem()\n {\n if (_mainViewModel.DisplayedList.Count > 0)\n {\n var listView = myListView;\n listView.SelectedItem = listView.Items.GetItemAt(_mainViewModel.DisplayedList.Count - 1);\n listView.ScrollIntoView(listView.Items[0]);\n listView.ScrollIntoView(listView.SelectedItem);\n //item.Focus();\n }\n }\n" }, { "answer_id": 2610968, "author": "Murali.S", "author_id": 313185, "author_profile": "https://Stackoverflow.com/users/313185", "pm_score": 2, "selected": false, "text": "private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n ScrollViewer scrollViewer = GetScrollViewer(lstVw) as ScrollViewer;\n scrollViewer.ScrollToHorizontalOffset(dataRowToFocus.RowIndex);\n if (dataRowToFocus.RowIndex < 2)\n lstVw.ScrollIntoView((Entity)lstVw.Items[0]);\n else\n lstVw.ScrollIntoView(e.AddedItems[0]);\n } \n\n public static DependencyObject GetScrollViewer(DependencyObject o)\n {\n if (o is ScrollViewer)\n { return o; }\n\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++)\n {\n var child = VisualTreeHelper.GetChild(o, i);\n\n var result = GetScrollViewer(child);\n if (result == null)\n {\n continue;\n }\n else\n {\n return result;\n }\n }\n return null;\n } \n\nprivate void Focus()\n{\n lstVw.SelectedIndex = dataRowToFocus.RowIndex;\n lstVw.SelectedItem = (Entity)dataRowToFocus.Row;\n\n ListViewItem lvi = (ListViewItem)lstVw.ItemContainerGenerator.ContainerFromItem(lstVw.SelectedItem);\nContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(lvi);\ncontentPresenter.Focus();\ncontentPresenter.BringIntoView();\n\n}\n" }, { "answer_id": 8410386, "author": "Ray Ackley", "author_id": 1084850, "author_profile": "https://Stackoverflow.com/users/1084850", "pm_score": 1, "selected": false, "text": "<ListBox.ItemsPanel> <phone:PhoneApplicationPage.Resources>\n <DataTemplate x:Key=\"StoryViewModelTemplate\">\n <StackPanel>\n <your datatemplated stuff here/>\n </StackPanel>\n </DataTemplate>\n</phone:PhoneApplicationPage.Resources>\n <Grid x:Name=\"ContentPanel\">\n <ListBox Name=\"lbResults\" ItemsSource=\"{Binding SearchResults}\" ItemTemplate=\"{StaticResource StoryViewModelTemplate}\">\n <ListBox.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel>\n </StackPanel>\n </ItemsPanelTemplate>\n </ListBox.ItemsPanel>\n </ListBox>\n</Grid>\n" }, { "answer_id": 13362285, "author": "Willi", "author_id": 1746253, "author_profile": "https://Stackoverflow.com/users/1746253", "pm_score": 2, "selected": false, "text": "void FocusLastOne(ListView lsv)\n{\n ObservableCollection<object> items= sender as ObservableCollection<object>;\n\n Decorator d = VisualTreeHelper.GetChild(lsv, 0) as Decorator;\n ScrollViewer v = d.Child as ScrollViewer;\n v.ScrollToEnd();\n\n lsv.SelectedItem = lsv.Items.GetItemAt(items.Count - 1);\n ListViewItem lvi = lsv.ItemContainerGenerator.ContainerFromIndex(items.Count - 1) as ListViewItem;\n lvi.Focus();\n}\n" }, { "answer_id": 15293188, "author": "ygoe", "author_id": 143684, "author_profile": "https://Stackoverflow.com/users/143684", "pm_score": 0, "selected": false, "text": "ScrollIntoView IsSelected <ListView Name=\"PersonsListView\" ItemsSource=\"{Binding PersonVMs}\">\n <ListView.ItemContainerStyle>\n <Style TargetType=\"{x:Type ListViewItem}\">\n <Setter Property=\"IsSelected\" Value=\"{Binding IsSelected, Mode=TwoWay}\" />\n </Style>\n </ListView.ItemContainerStyle>\n</ListView>\n var firstSelected = PersonsListView.Items\n .OfType<TreeViewItemViewModel>().FirstOrDefault(x => x.IsSelected);\nif (firstSelected != null)\n CoObjectsListView.ScrollIntoView(firstSelected);\n PersonsListView.SelectedItem null IsSelected DispatcherPriority PersonVMs.ForEach(vm => vm.IsSelected = false);\nPersonVMs.Add(newPersonVM);\nnewPersonVM.IsSelected = true;\nViewCommandManager.InvokeLoaded(\"ScrollToSelectedPerson\");\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
212,006
<p>I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file: </p> <pre><code>// example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(); }; void TestClass::testMethod(){ // some code here... } } // end namespace test_ns #endif </code></pre> <p>If inside the same project I include this header from more than one cpp file, I get an error saying "<code>multiple definition of test_ns::TestClass::testMethod()</code>", while if I put the method definition inside the class body this does not happen:</p> <pre><code>// example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(){ // some code here... } }; } // end namespace test_ns #endif </code></pre> <p>Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?</p>
[ { "answer_id": 212019, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 5, "selected": false, "text": "namespace test_ns{\n\nclass TestClass{\npublic:\n inline void testMethod();\n};\n\nvoid TestClass::testMethod(){\n // some code here...\n}\n\n} // end namespace test_ns\n" }, { "answer_id": 212022, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 6, "selected": true, "text": "#ifndef EXAMPLE_H\n#define EXAMPLE_H\n\n//define your class here\n\n#endif\n" }, { "answer_id": 213107, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "test_ns::TestClass::testMethod() TestClass::testMethod() inline" }, { "answer_id": 11502363, "author": "Mahendra", "author_id": 1528591, "author_profile": "https://Stackoverflow.com/users/1528591", "pm_score": -1, "selected": false, "text": "//Baseclass.h or .cpp\n\n#ifndef CDerivedclass\n#include \"Derivedclass.h\"\n#endif\n\nor\n//COthercls.h or .cpp\n\n#ifndef CCommonheadercls\n#include \"Commonheadercls.h\"\n#endif\n\nI think this suffice all instances.\n" }, { "answer_id": 30744937, "author": "sastanin", "author_id": 25450, "author_profile": "https://Stackoverflow.com/users/25450", "pm_score": 2, "selected": false, "text": "foobar.h #ifndef FOOBAR_H\n#define FOOBAR_H\n\n/* write declarations normally */\nvoid foo();\nvoid bar();\n\n/* use conditional compilation to disable definitions when necessary */\n#ifndef ONLY_DECLARATIONS\nvoid foo() {\n /* your code goes here */\n}\nvoid bar() {\n /* your code goes here */\n}\n#endif /* ONLY_DECLARATIONS */\n#endif /* FOOBAR_H */\n main.c #include \"foobar.h\"\n\nint main(int argc, char *argv[]) {\n foo();\n}\n foobar.h #define ONLY_DECLARATIONS use_bar.c #define ONLY_DECLARATIONS\n#include \"foobar.h\"\n\nvoid use_bar() {\n bar();\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15622/" ]
212,028
<p>I have a C# method which accepts a Predicate&lt;Foo&gt; and returns a list of matching items...</p> <pre><code>public static List&lt;Foo&gt; FindAll( Predicate&lt;Foo&gt; filter ) { ... } </code></pre> <p>The filter will often be one of a common set...</p> <pre><code>public static class FooPredicates { public static readonly Predicate&lt;Foo&gt; IsEligible = ( foo =&gt; ...) ... } </code></pre> <p>...but may be an anonymous delegate.</p> <p>I'd now like to have this method cache its results in the ASP.NET cache, so repeated calls with the same delegate just return the cached result. For this, I need to create a cache key from the delegate. Will Delegate.GetHashCode() produce sensible results for this purpose? Is there some other member of Delegate that I should look at? Would you do this another way entirely?</p>
[ { "answer_id": 215035, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 2, "selected": false, "text": "public override int GetHashCode()\n{\n return base.GetType().GetHashCode();\n}\n static Predicate<int> Test()\n{\n Predicate<int> test = delegate(int i) { return false; };\n return test;\n}\n\nstatic void Main()\n{\n Predicate<int> test1 = Test();\n Predicate<int> test2 = Test();\n Console.WriteLine(test1.Equals( test2 )); // True\n\n test1 = delegate(int i) { return false; };\n test2 = delegate(int i) { return false; };\n Console.WriteLine(test1.Equals( test2 )); // False\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25028/" ]
212,031
<p>I would like to break a long line of text assigned to the standard Label widget in GWT. I was experimenting with inline <code>&lt;br /&gt;</code> elements but with no success.</p> <p>Something like this: </p> <pre><code>label = "My very very very long&lt;br /&gt;long long text" </code></pre>
[ { "answer_id": 286593, "author": "smerten", "author_id": 37288, "author_profile": "https://Stackoverflow.com/users/37288", "pm_score": 2, "selected": false, "text": "<br/>" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6482/" ]
212,048
<p>I'm using the ListView control (ASP.NET 2008) to show a bunch of lines of data, and at the bottom I want some totals. I was initially going to define the header and footer in the LayoutTemplate and get the totals with some local function, i.e. &lt;%#GetTheSum()%>, but it appears that the LayoutTemplate does not process the &lt;%#...%> syntax.</p> <p>Another thought would be to put a Label in the LayoutTemplate and use FindControl to update it. Not sure if that's possible (will try shortly).</p> <p>What's the best way to show totals using a ListView?</p> <p>UPDATE: Solution <a href="https://stackoverflow.com/questions/212048/displaying-totals-in-the-listview-layouttemplate#212308">here</a>.</p>
[ { "answer_id": 212126, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 1, "selected": false, "text": "<asp:Literal ID=\"litTotal\" runat=\"server\" />\n litTotal.Text = GetTheSum();\n" }, { "answer_id": 212308, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 4, "selected": true, "text": "CType(MyListView.FindControl(\"litTotal\"), Literal).Text = GetTheSum()\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23935/" ]
212,050
<p>In a spring configuration, what is the difference between using name vs id? I'm aware that XML restricts the "id" attribute to be unique in a document and limits the characters for using in the id. But otherwise when declaring a bean, what is the difference between using the "name" attribute vs the "id" attribute?</p>
[ { "answer_id": 212126, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 1, "selected": false, "text": "<asp:Literal ID=\"litTotal\" runat=\"server\" />\n litTotal.Text = GetTheSum();\n" }, { "answer_id": 212308, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 4, "selected": true, "text": "CType(MyListView.FindControl(\"litTotal\"), Literal).Text = GetTheSum()\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
212,089
<p>This is the way I read file:</p> <pre><code> public static string readFile(string path) { StringBuilder stringFromFile = new StringBuilder(); StreamReader SR; string S; SR = File.OpenText(path); S = SR.ReadLine(); while (S != null) { stringFromFile.Append(SR.ReadLine()); } SR.Close(); return stringFromFile.ToString(); } </code></pre> <p>The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way?</p> <p><strong>Solution taken</strong></p> <pre><code> public static string readFile(string path) { return File.ReadAllText(path); } </code></pre> <p>Took less than 1 second... :)</p>
[ { "answer_id": 212102, "author": "pian0", "author_id": 5692, "author_profile": "https://Stackoverflow.com/users/5692", "pm_score": 3, "selected": false, "text": "return System.IO.File.ReadAllText(path);\n" }, { "answer_id": 212104, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "var str = System.IO.File.ReadAllText(path);\nreturn str.Replace(Environment.NewLine, \"\");\n" }, { "answer_id": 212105, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "StringBuilder" }, { "answer_id": 212128, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 3, "selected": false, "text": "S = SR.ReadLine();\nwhile (S != null)\n{\n stringFromFile.Append(SR.ReadLine());\n}\n S ReadLine() S != null S = SR.ReadLine();\nwhile (S != null)\n{\n stringFromFile.Append(S = SR.ReadLine());\n}\n" }, { "answer_id": 212150, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 2, "selected": false, "text": "\nS = SR.ReadLine();\nwhile (S != null){\n stringFromFile.Append(S);\n S = SR.ReadLine();\n}\n" }, { "answer_id": 212179, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "StringBuilder StringBuilder var info = new FileInfo(path);\nvar sb = new StringBuilder((int)info.Length);\n System.IO.FileInfo.Length long" }, { "answer_id": 13722128, "author": "Salim", "author_id": 1306836, "author_profile": "https://Stackoverflow.com/users/1306836", "pm_score": 1, "selected": false, "text": "string fileContent = System.IO.File.ReadAllText(txtFilePath.Text)\nstring[] arr = fileContent.Split('\\n');\n" }, { "answer_id": 37985301, "author": "Amit Kumawat", "author_id": 4140166, "author_profile": "https://Stackoverflow.com/users/4140166", "pm_score": -1, "selected": false, "text": "public static string ReadFileAndFetchStringInSingleLine(string file)\n {\n StringBuilder sb;\n try\n {\n sb = new StringBuilder();\n using (FileStream fs = File.Open(file, FileMode.Open))\n {\n using (BufferedStream bs = new BufferedStream(fs))\n {\n using (StreamReader sr = new StreamReader(bs))\n {\n string str;\n while ((str = sr.ReadLine()) != null)\n {\n sb.Append(str);\n }\n }\n }\n }\n return sb.ToString();\n }\n catch (Exception ex)\n {\n return \"\";\n }\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
212,115
<p>What is the best method for displaying major/minor versions in a C# console application?</p> <p>The <code>System.Windows.Forms</code> namespace includes a <code>ProductVersion</code> class that can be used to display the name/version information set via the Visual Studio project properties (Assembly Information). As such, here is my current mechanism:</p> <pre class="lang-cs prettyprint-override"><code>Console.WriteLine("{0} ({1})", System.Windows.Forms.Application.ProductName, System.Windows.Forms.Application.ProductVersion); </code></pre> <p>Why is this part of <code>Forms</code>? Is this appropriate for a Console application?</p>
[ { "answer_id": 212135, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "Assembly.GetExecutingAssembly().GetName().Version\n" }, { "answer_id": 213083, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "Assembly.GetExecutingAssembly().GetName().Version Application.ProductVersion Application.ProductVersion Assembly.GetEntryAssembly() GetEntryAssembly() Application.ProductVersion" }, { "answer_id": 68620594, "author": "tilli", "author_id": 2965054, "author_profile": "https://Stackoverflow.com/users/2965054", "pm_score": 0, "selected": false, "text": "Console.WriteLine(\"FileVersionInfo::ProductVersion : {0}\",\n System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ProductVersion);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644/" ]
212,124
<p>Some friends and colleagues of mine have a little running contest to find or write the longest class/variable/property/method names possible. Keep in mind, we try to be good boys and girls and keep the naming intelligible and concise, while still explaining what the thing does via its name.</p> <p>Sometimes it just doesn't happen though. Have you run in to this? I'd just like to see what's out there. (Maybe my friends and I aren't as crazy as we think)</p> <p>Note: I'm not looking for <strong>bad</strong> naming. That's already <a href="https://stackoverflow.com/questions/143701/what-is-the-worst-classvariablefunction-name-you-have-ever-encountered">here</a>. I'm looking for <strong>good</strong> naming that just got a little long.</p>
[ { "answer_id": 212132, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "NSString.completePathInfoString:caseSensitive:matchesToArray:filterType\nNSString.stringByAddingPercentEscapesUsingEncoding\n SetProcessWorkingSetSize" }, { "answer_id": 212136, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "testMapWithOneEntryAllowsDifferentEntryPreservingFirst\ntestMapWithOneEntryAllowsDuplicateEntryOverwritingFirst\n" }, { "answer_id": 212140, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 1, "selected": false, "text": "_synchronouslyTellServicesToRegisterAndSync()\n User.CanViewRestrictedItems()\n Profile.DisplayMyDraftOrPendingProfile()\nProfile.DisplayMyApprovedProfile()\n constraint ReportCompanyReportTemplateIDVersionID_ReportTemplateVersionReportTemplateIDVersionIDFk foreign key (ReportTemplateID, VersionID) references customer_ReportTemplateVersion (ReportTemplateID, VersionID)\n" }, { "answer_id": 212178, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "protected virtual OcrBarcodeSymbologies GetSupportedBarcodeSymbologies() { }\n" }, { "answer_id": 238599, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "threadedadaptivecommscomponent\n" }, { "answer_id": 1194341, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 1, "selected": false, "text": "public DataSet SelectAllUsersWhereDobIsGreaterThan1980AndIsMaleOrderByNameAndAge()\n" }, { "answer_id": 2162485, "author": "Albert", "author_id": 261870, "author_profile": "https://Stackoverflow.com/users/261870", "pm_score": 3, "selected": false, "text": "org.aspectj.weaver.patterns;\n\npublic class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor {\n boolean ohYesItHas = false;\n\n public boolean wellHasItThen/*?*/() {\n return ohYesItHas;\n }\n\n ... more methods...\n}\n" }, { "answer_id": 3670922, "author": "wsd", "author_id": 118096, "author_profile": "https://Stackoverflow.com/users/118096", "pm_score": 5, "selected": true, "text": "VirtualMachineDeviceRuntimeInfoVirtualEthernetCardRuntimeStateVmDirectPathGen2InactiveReasonOther\n" }, { "answer_id": 9917455, "author": "Karel", "author_id": 1299512, "author_profile": "https://Stackoverflow.com/users/1299512", "pm_score": 1, "selected": false, "text": "bool instrumentAreaDockWidgetVisibilityFollowsChildPresence;\n" }, { "answer_id": 10245748, "author": "Kostas", "author_id": 1346461, "author_profile": "https://Stackoverflow.com/users/1346461", "pm_score": 0, "selected": false, "text": "js" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8360/" ]
212,125
<p>Let's say I have a model like this</p> <pre><code>class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() </code></pre> <p>And I'm going a GqlQuery like this</p> <pre><code>foos = db.GqlQuery("SELECT * FROM Foo") </code></pre> <p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p> <hr> <p>Here's how I'm doing it now</p> <ol> <li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p> <pre><code>def toDict(self): return { 'id': self.id, 'bar': self.bar, 'baz': self'baz } </code></pre></li> <li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p> <pre><code>fooDict = {} for foo in foos: fooDict[foo.id] = foo.toDict() return simplejson.dumps(fooDict) </code></pre></li> </ol> <hr> <p>My approach above works but it feels kind of gross.</p> <p>Is there a cleaner, more "Pythonic" way to handle this?</p> <p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
[ { "answer_id": 212351, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "class Foo:\n id = db.StringProperty() # etc.\n json_attrs = 'id bar baz'.split()\n\n# Depending on how easy it is to identify string properties, there\n# might also be a way to assign json_attrs programmatically after the\n# definition of Foo, like this\nFoo.json_attrs = [attr for attr in dir(Foo)\n if isStringProperty(getattr(Foo, attr))]\n\nfooDict=dict((foo.id,dict(getattr(foo, attr)\n for attr in Foo.json_attrs))\n for foo in foos)\n" }, { "answer_id": 259334, "author": "massimo", "author_id": 24489, "author_profile": "https://Stackoverflow.com/users/24489", "pm_score": -1, "selected": false, "text": "db.define_table('foo',SQLField('bar'),SQLField('baz'))\nrows=db(db.foo.id>0).select()\n### rows is a list, rows.response is a list of tuples\nfor row in rows: print dict(row)\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
212,134
<p>I need to scale calls into Tomcat and it's been suggested to launch threads internally. Has anyone needed to do this and, if so, what solutions did they come up with?</p>
[ { "answer_id": 212156, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 1, "selected": false, "text": "java.util.concurrency" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,198
<p>What is the purpose of the <code>Using</code> block in C#? How is it different from a local variable?</p>
[ { "answer_id": 212204, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 7, "selected": false, "text": "Using Dispose() using using using (MyClass mine = new MyClass())\n{\n mine.Action();\n}\n MyClass mine = new MyClass();\ntry\n{\n mine.Action();\n}\nfinally\n{\n if (mine != null)\n mine.Dispose();\n}\n using" }, { "answer_id": 212210, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 10, "selected": true, "text": "public class SomeDisposableType : IDisposable\n{\n ...implmentation details...\n}\n SomeDisposableType t = new SomeDisposableType();\ntry {\n OperateOnType(t);\n}\nfinally {\n if (t != null) {\n ((IDisposable)t).Dispose();\n }\n}\n using (SomeDisposableType u = new SomeDisposableType()) {\n OperateOnType(u);\n}\n using using var x = new SomeDisposableType();\n { } string x = null;\nusing(var someReader = ...)\n{\n x = someReader.Read();\n}\n using var someReader = ...;\nstring x = someReader.Read();\n" }, { "answer_id": 212222, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 6, "selected": false, "text": "using using" }, { "answer_id": 212227, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 3, "selected": false, "text": "using (B a = new B())\n{\n DoSomethingWith(a);\n}\n B a = new B();\ntry\n{\n DoSomethingWith(a);\n}\nfinally\n{\n ((IDisposable)a).Dispose();\n}\n" }, { "answer_id": 8844163, "author": "Sunquick", "author_id": 1120346, "author_profile": "https://Stackoverflow.com/users/1120346", "pm_score": 5, "selected": false, "text": "IDisposable IDisposable Dispose using (SqlConnection conn = new SqlConnection())\n{\n\n}\n SqlConnection conn = new SqlConnection() \ntry\n{\n\n}\nfinally\n{\n // calls the dispose method of the conn object\n}\n" }, { "answer_id": 23912032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "using" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17715/" ]
212,201
<p>A little benchmark with ASP.NET MVC. Viewpage code:</p> <pre><code> public string Bechmark(Func&lt;string&gt; url) { var s = new Stopwatch(); var n = 1000; s.Reset(); s.Start(); for (int i = 0; i &lt; n; i++) { var u = url(); } s.Stop(); return s.ElapsedMilliseconds + &quot; ms, &quot; + ((s.ElapsedMilliseconds) / (float)n) + &quot; ms per link&lt;br/&gt;&quot;; } </code></pre> <p>View code:</p> <pre><code>&lt;%= Bechmark(() =&gt; Url.Action(&quot;Login&quot;, &quot;Account&quot;)) %&gt; &lt;%= Bechmark(() =&gt; Url.Action(&quot;Login&quot;, &quot;Account&quot;, new {username=&quot;bla&quot;, password=&quot;bla2&quot;, returnurl=&quot;blabla32&quot;, rememberme=false} )) %&gt; &lt;%= Bechmark(() =&gt; Html.BuildUrlFromExpression&lt;AccountController&gt;(a=&gt;a.ChangePassword(&quot;bla&quot;, &quot;bla&quot;, &quot;ya&quot;)) ) %&gt; </code></pre> <p>Running this on a typical Core2 notebook on the default new project template with ASP.NET MVC Beta yields these results:</p> <blockquote> <p>38 ms, 0,038 ms per link</p> <p>120 ms, 0,12 ms per link</p> <p>54 ms, 0,054 ms per link</p> </blockquote> <p>Running the same benchmark on a production project with about 10 controllers that have all in all around 100 methods and 30 routing table entries, the performance degrades greatly for the expression-based method:</p> <blockquote> <p>31 ms, 0,031 ms per link</p> <p>112 ms, 0,112 ms per link</p> <p>450 ms, 0,45 ms per link</p> </blockquote> <p>We use this method quite a lot (maintainability) and doing some performance benchmarking, this degrades the performance of the site greatly - pages quickly contain around 30 or more of such links, that means 10ms of additional overhead on a single page. Even 0.112ms per an URL is around 4ms of pure CPU overhead.</p> <p>It should be noted that performance of all the three URL generation calls between MVC Preview 3 and Beta (released yesterday) got improved by a factor of 5.</p> <p>Stack Overflow is supposedly powered by the same framework, how have you guys tackled this scaling problem? Liberal caching of the front page (lots of links) and pre-rendered controls?</p> <p>Any other production websites in ASP.NET MVC with performance issues or some good tips?</p>
[ { "answer_id": 212327, "author": "rudib", "author_id": 28917, "author_profile": "https://Stackoverflow.com/users/28917", "pm_score": 1, "selected": false, "text": "<%= Bechmark(() => Url.Action(\"Login\", \"Account\", new Dictionary<string, object> {{\"username\", \"bla\"}, {\"password\", \"bla2\"}, {\"returnurl\", \"blabla32\"}, {\"rememberme\", \"false\"}})) %>\n\n<%= Bechmark(() => Url.Action(\"Login\", \"Account\", new RouteValueDictionary(new Dictionary<string, object> {{\"username\", \"bla\"}, {\"password\", \"bla2\"}, {\"returnurl\", \"blabla32\"}, {\"rememberme\", \"false\"}}))) %>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28917/" ]
212,215
<p>I'm trying to display a loading icon while my iPhone app downloads a network resource, but I can't figure out how to make it show up correctly.</p> <p>I searched around and found some details on the <code>UIActivityView</code> class, but the available example source code didn't work, and the documentation is kind of terse.</p> <p>Could someone provide a simple example on how to use this class?</p>
[ { "answer_id": 212564, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 5, "selected": true, "text": "UIActivityIndicator indicator UIActivityIndicator *indicator;\n CGRect b = self.view.bounds;\nindicator = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle: \n UIActivityIndicatorStyleWhite];\n//center the indicator in the view\nindicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20); \n[self.view addSubview: indicator];\n[indicator release];\n[indicator startAnimating];\n [indicator removeFromSuperview];\nindicator = nil;\n" }, { "answer_id": 213243, "author": "Jablair", "author_id": 24168, "author_profile": "https://Stackoverflow.com/users/24168", "pm_score": 0, "selected": false, "text": "NSURLConnection" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,228
<p>I have read the GOLD Homepage ( <a href="http://www.devincook.com/goldparser/" rel="nofollow noreferrer">http://www.devincook.com/goldparser/</a> ) docs, FAQ and Wikipedia to find out what practical application there could possibly be for GOLD. I was thinking along the lines of having a programming language (easily) available to my systems such as ABAP on SAP or X++ on Axapta - but it doesn't look feasible to me, at least not easily - even if you use GOLD.</p> <p>The final use of the parsed result produced by GOLD escapes me - what do you do with the result of the parse?</p> <p>EDIT: A practical example (description) would be great.</p>
[ { "answer_id": 212529, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 4, "selected": true, "text": "public void execute_if_statment(ParseTreeNode node) {\n // We already know we have a IF_STATEMENT node\n Value value = evaluate_expression(node.getBooleanExpression());\n if (value.getBooleanResult() == true) {\n // we do the \"then\" part of the code\n }\n}\n\npublic Value evaluate_expression(ParseTreeNode node) {\n Value result = null;\n if (node.isConstant()) {\n result = evaluate_constant(node);\n return result;\n }\n if (node.isIdentifier()) {\n result = lookupIdentifier(node);\n return result;\n }\n Value leftSide = evaluate_expression(node.getLeftSide());\n Value rightSide = evaluate_expression(node.getRightSide());\n if (node.getOperator() == '+') {\n if (!leftSide.isNumber() || !rightSide.isNumber()) {\n throw new RuntimeError(\"Must have numbers for adding\");\n }\n int l = leftSide.getIntValue();\n int r = rightSide.getIntValue();\n int sum = l + r;\n return new Value(sum);\n }\n if (node.getOperator() == '>') {\n if (leftSide.getType() != rightSide.getType()) {\n throw new RuntimeError(\"You can only compare values of the same type\");\n }\n if (leftSide.isNumber()) {\n int l = leftSide.getIntValue();\n int r = rightSide.getIntValue();\n boolean greater = l > r;\n return new Value(greater);\n } else {\n // do string compare instead\n }\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
212,234
<p>I am building an MS Access application in which all the forms are modal. However, after data change in a form, I want to refresh the parent form of this form with newer data. Is there any way to do it. To elaborate further :</p> <p>Consider there are two forms, Form A and Form B. Both are modal form. From Form A, I initiate Form B, and now Form B has the user attention. But at the close of form B, I want to refresh the Form A. Is there a way to do it?</p>
[ { "answer_id": 212303, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": false, "text": "Forms!FormA.Requery\n" }, { "answer_id": 212482, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 4, "selected": true, "text": "Sub RunFormALoad()\n Forms!FormA.ToDoOnLoad\nEnd Sub\n Public Sub Form_Load()\n ToDoOnLoad\nEnd Sub \n\nSub ToDoOnLoad()\n txtText = \"Hi\"\nEnd Sub\n" }, { "answer_id": 15571032, "author": "tony gil", "author_id": 1166727, "author_profile": "https://Stackoverflow.com/users/1166727", "pm_score": 1, "selected": false, "text": "REQUERY Cmd.Close DoCmd.Close\nForms![Form_Name]![Combo_Box_Name].Requery\n Dim id As Integer\nid = Me.[Index_Field]\nDoCmd.Close\nForms![Form_Name]![Combo_Box_Name].Requery\nForms![Form_Name]![Combo_Box_Name] = id\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
212,237
<p>I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, not even the good books go on explaining what happens behind the curtains. </p> <p>For example, how does the compiler optimize a method that is declared const vs one that isn't but should be. What happens when you introduce mutable variables? Do they affect these optimizations of const methods?</p>
[ { "answer_id": 212304, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "void someType::somefunc();\n\nvoid MyFunc()\n{\n someType A(4); // \n Fling(A.m_val);\n A.someFunc();\n Flong(A.m_val);\n}\n" }, { "answer_id": 212517, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "const void f(Type dont_modify); // or\nvoid f(Type const& dont_modify);\n const const const" }, { "answer_id": 212612, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "class Test\n{\npublic:\n Test (int value) : m_value (value)\n {\n }\n\n void SetValue (int value) const\n {\n const_cast <Test&>(*this).MySetValue (value);\n }\n\n int Value () const\n {\n return m_value;\n }\n\nprivate:\n void MySetValue (int value)\n {\n m_value = value;\n }\n\n int\n m_value;\n};\n\nvoid modify (const Test &test, int value) \n{\n test.SetValue (value);\n}\n\nvoid main ()\n{\n const Test\n test (100);\n\n cout << test.Value () << endl;\n modify (test, 50);\n cout << test.Value () << endl;\n}\n 100\n50\n volatile const\n" }, { "answer_id": 213394, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": -1, "selected": false, "text": "const const_cast" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22247/" ]
212,239
<p>I am using Apache <a href="http://hc.apache.org/httpclient-3.x/" rel="noreferrer">HttpClient</a> and would like to communicate HTTP errors (400 Bad Request, 404 Not Found, 500 Server Error, etc.) via the Java exception mechanism to the calling code. Is there an exception in the Java standard library or in a widely used library that would be appropriate to use or to subclass for this purpose?</p> <p>The alternative is to check status return codes. This appears to be the HttpClient design philosophy, but since these errors are truly exceptional in my app, I would like to have the stack trace and other nice exception things set up for me when they happen.</p>
[ { "answer_id": 47058425, "author": "Paulo Merson", "author_id": 317522, "author_profile": "https://Stackoverflow.com/users/317522", "pm_score": 4, "selected": false, "text": "MyBusinessException HttpClientErrorException HttpClientErrorException HttpServerErrorException" }, { "answer_id": 54390878, "author": "Wendel", "author_id": 2057463, "author_profile": "https://Stackoverflow.com/users/2057463", "pm_score": 2, "selected": false, "text": "...\nimport org.apache.http.client.HttpResponseException;\n\n...\nStatusLine statusLine = response.getStatusLine();\nif(statusLine.getStatusCode() != 200) {\n throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());\n}\n...\n Exception in thread \"main\" org.apache.http.client.HttpResponseException: status code: 400, reason phrase: Bad Request\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28604/" ]
212,257
<p>It seems like this should be straightforward but I'm boggling. I've got my listview all setup and bound to my LINQ datasource. The source is dependent on a dropdown list which decides which branch information to show in the listview. My edit template works fine but my insert template won't work because it wants the branch ID which I want to get from the dropdownlist outside the listview but I don't know how to both bind that value and set it in my template. It looks like this:</p> <pre><code>&lt;InsertItemTemplate&gt; &lt;tr style=""&gt; &lt;td&gt; &lt;asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="RechargeRateTextBox" runat="server" Text='&lt;%# Bind("RechargeRate") %&gt;' /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Calendar SelectedDate='&lt;%# Bind("StartDate") %&gt;' ID="Calendar1" runat="server"&gt;&lt;/asp:Calendar&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/InsertItemTemplate&gt; </code></pre> <p>I need to get a label in there that binds to the value of a databound asp dropdownlist outside of the listview so that the insert will work.</p>
[ { "answer_id": 212341, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "protected void BranchDropDownList_OnSelectedIndexChanged( object sender, EventArgs e )\n{\n DropDownList ddl = (DropDownList)sender;\n RechargeRateTextBox.Text = BranchManager.GetRechargeRate( ddl.SelectedValue );\n}\n" }, { "answer_id": 212436, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 2, "selected": true, "text": "protected void ListView1_ItemInserting(object sender, System.Web.UI.WebControls.ListViewInsertEventArgs e)\n {\n e.Values[\"BranchID\"] = DropDownList1.SelectedValue;\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
212,270
<p>This is an often-asked question that has views on both side. Those in favour will argue:</p> <ul> <li>To design a system for coders you must understand how to code (and be coding)</li> <li>You can't design a system without being aware of what is happening at ground level</li> <li>Architecture is not just about broad stroke design but about adapting to changing needs at the code level</li> </ul> <p>on the other hand,</p> <ul> <li>Architecture is a high-level role and should be not be concerned about implementation details</li> <li>Coding is a detailed oriented, heads-down funtion which is at odds with the risk management, broad view nature of architecture</li> <li>Architecture is about technical risk management and not implementation</li> <li>Architecture is about leadership. It's difficult to lead from behind</li> </ul> <p>In my experience architects should not be spending a lot of time coding but must keep in touch with the code base primarily through lead developer communication, review and stand ups. If you spend a lot of time coding you lose sight of the high level issues and become ineffective at managing technical risk.</p>
[ { "answer_id": 1078128, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 1, "selected": false, "text": "* Coding is a detailed oriented, heads-down funtion which is at odds\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199234/" ]