qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
174,885
<p>I've got this code:</p> <pre><code>rs1 = getResults(sSQL1) rs2 = getResults(sSQL2) </code></pre> <p>rs1 and rs2 and 2D arrays. The first index represents the number of columns (static) and the second index represents the number of rows (dynamic).</p> <p>I need to join the two arrays and store them in rs3. I don't know what type rs1 and rs2 are though.</p>
[ { "answer_id": 174897, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Are you sure that the columns will match up? Because if that's not the case I don't know how you'd do it in a generic way in any language. If it is the case, then you could probably do it <em>very</em> simply like this:</p>\n\n<pre><code>rs1 = getResults(sSQL1 &amp; \" UNION \" sSQL2)\n</code></pre>\n" }, { "answer_id": 174974, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": true, "text": "<p>I've figured it out. Turns out I was doing it the right way all along, I was just off by one. You don't need a third array either.</p>\n\n<pre><code> aRS_RU = rowsQuery(sSQL &amp; \", 'RU'\")\n aRS_KR = rowsQuery(sSQL &amp; \", 'KR'\")\n\n uboundRU1 = UBound(aRS_RU, 1)\n uboundRU2 = UBound(aRS_RU, 2)\n uboundKR2 = Ubound(aRS_KR, 2)\n\n ' Redim original array\n ReDim Preserve aRS_RU(uboundRU1, uboundRU2 + uboundKR2 + 1 )\n uboundRU2 = UBound(aRS_RU, 2)\n\n ' Add the values from the second array \n For m = LBound(aRS_KR, 1) To UBound(aRS_KR, 1) 'Loop for 1st dimension\n For n = LBound(aRS_KR, 2) To UBound(aRS_KR, 2) 'Loop for 2nd dimension\n aRS_RU(m, uboundRU2 + n) = aRS_KR(m,n)\n Next\n Next \n</code></pre>\n" }, { "answer_id": 10805409, "author": "Fred", "author_id": 1424522, "author_profile": "https://Stackoverflow.com/users/1424522", "pm_score": 0, "selected": false, "text": "<p>I know this post is old, but I adapted the code to fix some errors I had during its execution. The following code sample works for me:</p>\n\n<pre><code>Sub ConcatRecordSets(ByRef avFirstRS As Variant, ByRef avSecondRS As Variant)\n\n Dim lIndex1 As Long, lIndex2 As Long\n Dim lFirstRSSize As Long, lSecondRSSize As Long\n\n ' Redim original array\n lFirstRSSize = UBound(avFirstRS, 2) - LBound(avFirstRS, 2) + 1\n lSecondRSSize = UBound(avSecondRS, 2) - LBound(avSecondRS, 2) + 1\n ReDim Preserve avFirstRS(LBound(avFirstRS, 1) To UBound(avFirstRS, 1), LBound(avFirstRS, 2) To UBound(avFirstRS, 2) + lSecondRSSize)\n\n ' Add the values from the second array\n For lIndex1 = LBound(avSecondRS, 1) To UBound(avSecondRS, 1) ' Loop for 1st dimension\n For lIndex2 = LBound(avSecondRS, 2) To UBound(avSecondRS, 2) ' Loop for 2nd dimension\n avFirstRS(lIndex1, lFirstRSSize + lIndex2) = avSecondRS(lIndex1, lIndex2)\n Next lIndex2\n Next lIndex1\n\nEnd Sub\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
I've got this code: ``` rs1 = getResults(sSQL1) rs2 = getResults(sSQL2) ``` rs1 and rs2 and 2D arrays. The first index represents the number of columns (static) and the second index represents the number of rows (dynamic). I need to join the two arrays and store them in rs3. I don't know what type rs1 and rs2 are though.
I've figured it out. Turns out I was doing it the right way all along, I was just off by one. You don't need a third array either. ``` aRS_RU = rowsQuery(sSQL & ", 'RU'") aRS_KR = rowsQuery(sSQL & ", 'KR'") uboundRU1 = UBound(aRS_RU, 1) uboundRU2 = UBound(aRS_RU, 2) uboundKR2 = Ubound(aRS_KR, 2) ' Redim original array ReDim Preserve aRS_RU(uboundRU1, uboundRU2 + uboundKR2 + 1 ) uboundRU2 = UBound(aRS_RU, 2) ' Add the values from the second array For m = LBound(aRS_KR, 1) To UBound(aRS_KR, 1) 'Loop for 1st dimension For n = LBound(aRS_KR, 2) To UBound(aRS_KR, 2) 'Loop for 2nd dimension aRS_RU(m, uboundRU2 + n) = aRS_KR(m,n) Next Next ```
174,888
<p>i want to find the mime-type for a given file extension on an IIS ASP.NET web-server from the code-behind file.</p> <p>i want to search the same list that the server itself uses when serving up a file. This means that any mime types a web-server administrator has added to the <em>Mime Map</em> will be included.</p> <p>i could blindly use</p> <pre><code>HKEY_CLASSES_ROOT\MIME\Database\Content Type </code></pre> <p>but that isn't documented as being the same list IIS uses, nor is it documented where the <em>Mime Map</em> is stored.</p> <p>i could blindly call <a href="http://msdn.microsoft.com/en-us/library/ms775107(VS.85).aspx" rel="noreferrer">FindMimeFromData</a>, but that isn't documented as being the same list IIS uses, nor can i guarantee that the IIS <em>Mime Map</em> will also be returned from that call.</p>
[ { "answer_id": 174963, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 1, "selected": false, "text": "<p>IIS stores the MIME information in its own database. Searching for \"MimeMap IIS\" on the internet will reveal how to read it or even change it. See for example <a href=\"http://blog.crowe.co.nz/archive/2006/06/02/647.aspx\" rel=\"nofollow noreferrer\">C# - How to display MimeMap entries to the console from an instance of IIS.</a></p>\n" }, { "answer_id": 174988, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<p>Here's one I made earlier:</p>\n\n<pre><code>public static string GetMimeTypeFromExtension(string extension)\n{\n using (DirectoryEntry mimeMap = \n new DirectoryEntry(\"IIS://Localhost/MimeMap\"))\n {\n PropertyValueCollection propValues = mimeMap.Properties[\"MimeMap\"];\n\n foreach (object value in propValues)\n {\n IISOle.IISMimeType mimeType = (IISOle.IISMimeType)value;\n\n if (extension == mimeType.Extension)\n {\n return mimeType.MimeType;\n }\n }\n\n return null;\n\n }\n}\n</code></pre>\n\n<p>Add a reference to <code>System.DirectoryServices</code> and a reference to <code>Active DS IIS Namespace Provider</code> under the COM tab. The extension needs to have the leading dot, i.e. <code>.flv</code>.</p>\n" }, { "answer_id": 2240821, "author": "Goyuix", "author_id": 243, "author_profile": "https://Stackoverflow.com/users/243", "pm_score": 4, "selected": false, "text": "<p>Here is another similar implementation, but doesn't require adding the COM reference - it retrieves the properties through reflection instead and stores them in a NameValueCollection for easy lookup:</p>\n\n<pre><code>using System.Collections.Specialized; //NameValueCollection\nusing System.DirectoryServices; //DirectoryEntry, PropertyValueCollection\nusing System.Reflection; //BindingFlags\n\nNameValueCollection map = new NameValueCollection();\nusing (DirectoryEntry entry = new DirectoryEntry(\"IIS://localhost/MimeMap\"))\n{\n PropertyValueCollection properties = entry.Properties[\"MimeMap\"];\n Type t = properties[0].GetType();\n\n foreach (object property in properties)\n {\n BindingFlags f = BindingFlags.GetProperty;\n string ext = t.InvokeMember(\"Extension\", f, null, property, null) as String;\n string mime = t.InvokeMember(\"MimeType\", f, null, property, null) as String;\n map.Add(ext, mime);\n }\n}\n</code></pre>\n\n<p>You can very easily cache that lookup table, and then reference it later:</p>\n\n<pre><code>Response.ContentType = map[ext] ?? \"binary/octet-stream\";\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
i want to find the mime-type for a given file extension on an IIS ASP.NET web-server from the code-behind file. i want to search the same list that the server itself uses when serving up a file. This means that any mime types a web-server administrator has added to the *Mime Map* will be included. i could blindly use ``` HKEY_CLASSES_ROOT\MIME\Database\Content Type ``` but that isn't documented as being the same list IIS uses, nor is it documented where the *Mime Map* is stored. i could blindly call [FindMimeFromData](http://msdn.microsoft.com/en-us/library/ms775107(VS.85).aspx), but that isn't documented as being the same list IIS uses, nor can i guarantee that the IIS *Mime Map* will also be returned from that call.
Here's one I made earlier: ``` public static string GetMimeTypeFromExtension(string extension) { using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap")) { PropertyValueCollection propValues = mimeMap.Properties["MimeMap"]; foreach (object value in propValues) { IISOle.IISMimeType mimeType = (IISOle.IISMimeType)value; if (extension == mimeType.Extension) { return mimeType.MimeType; } } return null; } } ``` Add a reference to `System.DirectoryServices` and a reference to `Active DS IIS Namespace Provider` under the COM tab. The extension needs to have the leading dot, i.e. `.flv`.
174,890
<p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p> <p>Can it be done?</p>
[ { "answer_id": 175016, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>It's not possible AFAIK... which is a pity. Basically, ElementTree modules assume that the reader is 100% XML compliant, so it shouldn't matter if they output a section as CDATA or some other format that generates the equivalent text.</p>\n\n<p>See <a href=\"https://web.archive.org/web/20141015120050/https://mail.python.org/pipermail/python-list/2005-June/304602.html\" rel=\"nofollow noreferrer\">this thread</a> on the Python mailing list for more info. Basically, they recommend some kind of DOM-based XML library instead.</p>\n" }, { "answer_id": 175101, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 6, "selected": true, "text": "<p>After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular elements.</p>\n\n<pre><code>def Comment(text=None):\n element = Element(Comment)\n element.text = text\n return element\n</code></pre>\n\n<p>Then in the <code>_write</code> function of ElementTree that actually outputs the XML, there's a special case handling for comments:</p>\n\n<pre><code>if tag is Comment:\n file.write(\"&lt;!-- %s --&gt;\" % _escape_cdata(node.text, encoding))\n</code></pre>\n\n<p>In order to support CDATA sections, I create a factory function called <code>CDATA</code>, extended the ElementTree class and changed the <code>_write</code> function to handle the CDATA elements.</p>\n\n<p>This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do.</p>\n\n<p>The implementation seems to work with both ElementTree and cElementTree.</p>\n\n<pre><code>import elementtree.ElementTree as etree\n#~ import cElementTree as etree\n\ndef CDATA(text=None):\n element = etree.Element(CDATA)\n element.text = text\n return element\n\nclass ElementTreeCDATA(etree.ElementTree):\n def _write(self, file, node, encoding, namespaces):\n if node.tag is CDATA:\n text = node.text.encode(encoding)\n file.write(\"\\n&lt;![CDATA[%s]]&gt;\\n\" % text)\n else:\n etree.ElementTree._write(self, file, node, encoding, namespaces)\n\nif __name__ == \"__main__\":\n import sys\n\n text = \"\"\"\n &lt;?xml version='1.0' encoding='utf-8'?&gt;\n &lt;text&gt;\n This is just some sample text.\n &lt;/text&gt;\n \"\"\"\n\n e = etree.Element(\"data\")\n cdata = CDATA(text)\n e.append(cdata)\n et = ElementTreeCDATA(e)\n et.write(sys.stdout, \"utf-8\")\n</code></pre>\n" }, { "answer_id": 202122, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://lxml.de/\" rel=\"noreferrer\">lxml</a> has support for <a href=\"http://lxml.de/api.html#cdata\" rel=\"noreferrer\">CDATA</a> and API like ElementTree.</p>\n" }, { "answer_id": 320876, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Actually this code has a bug, since you don't catch <code>]]&gt;</code> appearing in the data you are inserting as CDATA</p>\n\n<p>as per <a href=\"https://stackoverflow.com/questions/223652/is-there-a-way-to-escape-a-cdata-end-token-in-xml\">Is there a way to escape a CDATA end token in xml?</a></p>\n\n<p>you should break it into two CDATA's in that case, splitting the <code>]]&gt;</code> between the two.</p>\n\n<p>basically <code>data = data.replace(\"]]&gt;\", \"]]]]&gt;&lt;![CDATA[&gt;\")</code><br>\n(not necessarily correct, please verify)</p>\n" }, { "answer_id": 510324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The DOM has (atleast in level 2) an interface\nDATASection, and an operation Document::createCDATASection. They are\nextension interfaces, supported only if an implementation supports the\n\"xml\" feature.</p>\n\n<p>from xml.dom import minidom</p>\n\n<p>my_xmldoc=minidom.parse(xmlfile)</p>\n\n<p>my_xmldoc.createCDATASection(data)</p>\n\n<p>now u have cadata node add it wherever u want....</p>\n" }, { "answer_id": 8915039, "author": "Amaury", "author_id": 644863, "author_profile": "https://Stackoverflow.com/users/644863", "pm_score": 4, "selected": false, "text": "<p>Here is a variant of gooli's solution that works for python 3.2:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import xml.etree.ElementTree as etree\n\ndef CDATA(text=None):\n element = etree.Element('![CDATA[')\n element.text = text\n return element\n\netree._original_serialize_xml = etree._serialize_xml\ndef _serialize_xml(write, elem, qnames, namespaces):\n if elem.tag == '![CDATA[':\n write(\"\\n&lt;%s%s]]&gt;\\n\" % (\n elem.tag, elem.text))\n return\n return etree._original_serialize_xml(\n write, elem, qnames, namespaces)\netree._serialize_xml = etree._serialize['xml'] = _serialize_xml\n\n\nif __name__ == \"__main__\":\n import sys\n\n text = \"\"\"\n &lt;?xml version='1.0' encoding='utf-8'?&gt;\n &lt;text&gt;\n This is just some sample text.\n &lt;/text&gt;\n \"\"\"\n\n e = etree.Element(\"data\")\n cdata = CDATA(text)\n e.append(cdata)\n et = etree.ElementTree(e)\n et.write(sys.stdout.buffer.raw, \"utf-8\")\n</code></pre>\n" }, { "answer_id": 10440166, "author": "Michael", "author_id": 381493, "author_profile": "https://Stackoverflow.com/users/381493", "pm_score": 0, "selected": false, "text": "<p>Here's my version which is based on both gooli's and amaury's answers above. It works for both ElementTree 1.2.6 and 1.3.0, which use very different methods of doing this.</p>\n\n<p>Note that gooli's does not work with 1.3.0, which seems to be the current standard in Python 2.7.x.</p>\n\n<p>Also note that this version does not use the CDATA() method gooli used either.</p>\n\n<pre><code>import xml.etree.cElementTree as ET\n\nclass ElementTreeCDATA(ET.ElementTree):\n \"\"\"Subclass of ElementTree which handles CDATA blocks reasonably\"\"\"\n\n def _write(self, file, node, encoding, namespaces):\n \"\"\"This method is for ElementTree &lt;= 1.2.6\"\"\"\n\n if node.tag == '![CDATA[':\n text = node.text.encode(encoding)\n file.write(\"\\n&lt;![CDATA[%s]]&gt;\\n\" % text)\n else:\n ET.ElementTree._write(self, file, node, encoding, namespaces)\n\n def _serialize_xml(write, elem, qnames, namespaces):\n \"\"\"This method is for ElementTree &gt;= 1.3.0\"\"\"\n\n if elem.tag == '![CDATA[':\n write(\"\\n&lt;![CDATA[%s]]&gt;\\n\" % elem.text)\n else:\n ET._serialize_xml(write, elem, qnames, namespaces)\n</code></pre>\n" }, { "answer_id": 13919169, "author": "tom stratton", "author_id": 1039039, "author_profile": "https://Stackoverflow.com/users/1039039", "pm_score": 0, "selected": false, "text": "<p>I got here looking for a way to \"parse an XML with CDATA sections and then output it again with the CDATA sections\". </p>\n\n<p>I was able to do this (maybe lxml has been updated since this post?) with the following: (it is a little rough - sorry ;-). Someone else may have a better way to find the CDATA sections programatically but I was too lazy.</p>\n\n\n\n<pre class=\"lang-py prettyprint-override\"><code> parser = etree.XMLParser(encoding='utf-8') # my original xml was utf-8 and that was a lot of the problem\n tree = etree.parse(ppath, parser)\n\n for cdat in tree.findall('./ProjectXMPMetadata'): # the tag where my CDATA lives\n cdat.text = etree.CDATA(cdat.text)\n\n # other stuff here\n\n tree.write(opath, encoding=\"UTF-8\",)\n</code></pre>\n" }, { "answer_id": 14118042, "author": "elwc", "author_id": 1890474, "author_profile": "https://Stackoverflow.com/users/1890474", "pm_score": 1, "selected": false, "text": "<p>The accepted solution cannot work with <strong>Python 2.7</strong>. However, there is another package called <a href=\"http://lxml.de/\" rel=\"nofollow\">lxml</a> which (though slightly slower) shared a largely identical syntax with the <code>xml.etree.ElementTree</code>. <code>lxml</code> is able to both write and parse <code>CDATA</code>. Documentation <a href=\"http://lxml.de/\" rel=\"nofollow\">here</a></p>\n" }, { "answer_id": 16944089, "author": "zlalanne", "author_id": 565219, "author_profile": "https://Stackoverflow.com/users/565219", "pm_score": 2, "selected": false, "text": "<p>This ended up working for me in Python 2.7. Similar to Amaury's answer.</p>\n\n<pre><code>import xml.etree.ElementTree as ET\n\nET._original_serialize_xml = ET._serialize_xml\n\n\ndef _serialize_xml(write, elem, encoding, qnames, namespaces):\n if elem.tag == '![CDATA[':\n write(\"&lt;%s%s]]&gt;%s\" % (elem.tag, elem.text, elem.tail))\n return\n return ET._original_serialize_xml(\n write, elem, encoding, qnames, namespaces)\nET._serialize_xml = ET._serialize['xml'] = _serialize_xml\n</code></pre>\n" }, { "answer_id": 20894783, "author": "user3155571", "author_id": 3155571, "author_profile": "https://Stackoverflow.com/users/3155571", "pm_score": 2, "selected": false, "text": "<p>I've discovered a hack to get CDATA to work using comments:</p>\n\n<pre><code>node.append(etree.Comment(' --&gt;&lt;![CDATA[' + data.replace(']]&gt;', ']]]]&gt;&lt;![CDATA[&gt;') + ']]&gt;&lt;!-- '))\n</code></pre>\n" }, { "answer_id": 30019607, "author": "Kamil", "author_id": 4833927, "author_profile": "https://Stackoverflow.com/users/4833927", "pm_score": 3, "selected": false, "text": "<p><strong>Solution:</strong></p>\n\n<pre><code>import xml.etree.ElementTree as ElementTree\n\ndef CDATA(text=None):\n element = ElementTree.Element('![CDATA[')\n element.text = text\n return element\n\nElementTree._original_serialize_xml = ElementTree._serialize_xml\ndef _serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs):\n if elem.tag == '![CDATA[':\n write(\"\\n&lt;{}{}]]&gt;\\n\".format(elem.tag, elem.text))\n if elem.tail:\n write(_escape_cdata(elem.tail))\n else:\n return ElementTree._original_serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs)\n\nElementTree._serialize_xml = ElementTree._serialize['xml'] = _serialize_xml\n\nif __name__ == \"__main__\":\n import sys\n\ntext = \"\"\"\n&lt;?xml version='1.0' encoding='utf-8'?&gt;\n&lt;text&gt;\nThis is just some sample text.\n&lt;/text&gt;\n\"\"\"\n\ne = ElementTree.Element(\"data\")\ncdata = CDATA(text)\nroot.append(cdata)\n</code></pre>\n\n<p><strong>Background:</strong></p>\n\n<p>I don't know whether previous versions of proposed code worked very well and whether ElementTree module has been updated but I have faced problems with using this trick:</p>\n\n<pre><code>etree._original_serialize_xml = etree._serialize_xml\ndef _serialize_xml(write, elem, qnames, namespaces):\n if elem.tag == '![CDATA[':\n write(\"\\n&lt;%s%s]]&gt;\\n\" % (\n elem.tag, elem.text))\n return\n return etree._original_serialize_xml(\n write, elem, qnames, namespaces)\netree._serialize_xml = etree._serialize['xml'] = _serialize_xml\n</code></pre>\n\n<p>The problem with this approach is that after passing this exception, serializer is again treating it as normal tag afterwards. I was getting something like:</p>\n\n<pre><code>&lt;textContent&gt;\n&lt;![CDATA[this was the code I wanted to put inside of CDATA]]&gt;\n&lt;![CDATA[&gt;this was the code I wanted to put inside of CDATA&lt;/![CDATA[&gt;\n&lt;/textContent&gt;\n</code></pre>\n\n<p>And of course we know that will cause only plenty of errors. \nWhy that was happening though?</p>\n\n<p>The answer is in this little guy:</p>\n\n<pre><code>return etree._original_serialize_xml(write, elem, qnames, namespaces)\n</code></pre>\n\n<p>We don't want to examine code once again through original serialise function if we have trapped our CDATA and successfully passed it through.\nTherefore in the \"if\" block we have to return original serialize function only when CDATA was not there. We were missing \"else\" before returning original function.</p>\n\n<p>Moreover in my version ElementTree module, serialize function was desperately asking for \"short_empty_element\" argument. So the most recent version I would recommend looks like this(also with \"tail\"):</p>\n\n<pre><code>from xml.etree import ElementTree\nfrom xml import etree\n\n#in order to test it you have to create testing.xml file in the folder with the script\nxmlParsedWithET = ElementTree.parse(\"testing.xml\")\nroot = xmlParsedWithET.getroot()\n\ndef CDATA(text=None):\n element = ElementTree.Element('![CDATA[')\n element.text = text\n return element\n\nElementTree._original_serialize_xml = ElementTree._serialize_xml\n\ndef _serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs):\n\n if elem.tag == '![CDATA[':\n write(\"\\n&lt;{}{}]]&gt;\\n\".format(elem.tag, elem.text))\n if elem.tail:\n write(_escape_cdata(elem.tail))\n else:\n return ElementTree._original_serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs)\n\nElementTree._serialize_xml = ElementTree._serialize['xml'] = _serialize_xml\n\n\ntext = \"\"\"\n&lt;?xml version='1.0' encoding='utf-8'?&gt;\n&lt;text&gt;\nThis is just some sample text.\n&lt;/text&gt;\n\"\"\"\ne = ElementTree.Element(\"data\")\ncdata = CDATA(text)\nroot.append(cdata)\n\n#tests\nprint(root)\nprint(root.getchildren()[0])\nprint(root.getchildren()[0].text + \"\\n\\nyay!\")\n</code></pre>\n\n<p>The output I got was:</p>\n\n<pre><code>&lt;Element 'Database' at 0x10062e228&gt;\n&lt;Element '![CDATA[' at 0x1021cc9a8&gt;\n\n&lt;?xml version='1.0' encoding='utf-8'?&gt;\n&lt;text&gt;\nThis is just some sample text.\n&lt;/text&gt;\n\n\nyay!\n</code></pre>\n\n<p>I wish you the same result!</p>\n" }, { "answer_id": 52262907, "author": "Ryabchenko Alexander", "author_id": 6515755, "author_profile": "https://Stackoverflow.com/users/6515755", "pm_score": 2, "selected": false, "text": "<p>for python3 and ElementTree you can use next reciept </p>\n\n<pre><code>import xml.etree.ElementTree as ET\n\nET._original_serialize_xml = ET._serialize_xml\n\n\ndef serialize_xml_with_CDATA(write, elem, qnames, namespaces, short_empty_elements, **kwargs):\n if elem.tag == 'CDATA':\n write(\"&lt;![CDATA[{}]]&gt;\".format(elem.text))\n return\n return ET._original_serialize_xml(write, elem, qnames, namespaces, short_empty_elements, **kwargs)\n\n\nET._serialize_xml = ET._serialize['xml'] = serialize_xml_with_CDATA\n\n\ndef CDATA(text):\n element = ET.Element(\"CDATA\")\n element.text = text\n return element\n\n\nmy_xml = ET.Element(\"my_name\")\nmy_xml.append(CDATA(\"&lt;p&gt;some text&lt;/p&gt;\")\n\ntree = ElementTree(my_xml)\n</code></pre>\n\n<p>if you need xml as str, you can use </p>\n\n<pre><code>ET.tostring(tree)\n</code></pre>\n\n<p>or next hack (which almost same as code inside <code>tostring()</code>)</p>\n\n<pre><code>fake_file = BytesIO()\ntree.write(fake_file, encoding=\"utf-8\", xml_declaration=True)\nresult_xml_text = str(fake_file.getvalue(), encoding=\"utf-8\")\n</code></pre>\n\n<p>and get result </p>\n\n<pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;\n&lt;my_name&gt;\n &lt;![CDATA[&lt;p&gt;some text&lt;/p&gt;]]&gt;\n&lt;/my_name&gt;\n</code></pre>\n" }, { "answer_id": 58392720, "author": "Stas Chabarov", "author_id": 12219975, "author_profile": "https://Stackoverflow.com/users/12219975", "pm_score": 2, "selected": false, "text": "<p>You can override ElementTree <code>_escape_cdata</code> function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import xml.etree.ElementTree as ET\n\ndef _escape_cdata(text, encoding):\n try:\n if \"&amp;\" in text:\n text = text.replace(\"&amp;\", \"&amp;amp;\")\n # if \"&lt;\" in text:\n # text = text.replace(\"&lt;\", \"&amp;lt;\")\n # if \"&gt;\" in text:\n # text = text.replace(\"&gt;\", \"&amp;gt;\")\n return text\n except TypeError:\n raise TypeError(\n \"cannot serialize %r (type %s)\" % (text, type(text).__name__)\n )\n\nET._escape_cdata = _escape_cdata\n</code></pre>\n\n<p>Note that you may not need pass extra <code>encoding</code> param, depending on your library/python version.</p>\n\n<p>Now you can write CDATA into <code>obj.text</code> like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>root = ET.Element('root')\nbody = ET.SubElement(root, 'body')\nbody.text = '&lt;![CDATA[perform extra angle brackets escape for this text]]&gt;'\nprint(ET.tostring(root))\n</code></pre>\n\n<p>and get clear CDATA node:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;root&gt;\n &lt;body&gt;\n &lt;![CDATA[perform extra angle brackets escape for this text]]&gt;\n &lt;/body&gt;\n&lt;/root&gt;\n</code></pre>\n" }, { "answer_id": 62664137, "author": "Benjamin Smus", "author_id": 8468377, "author_profile": "https://Stackoverflow.com/users/8468377", "pm_score": 0, "selected": false, "text": "<h1>Simple way of making .xml file with CDATA sections</h1>\n<p>The main idea is that we covert the element tree to a string and call <a href=\"https://docs.python.org/3.8/library/xml.sax.utils.html#xml.sax.saxutils.unescape\" rel=\"nofollow noreferrer\">unescape</a> on it. Once we have the string we use standard python to write a string to a file.</p>\n<p>Based on:\n<a href=\"https://stackoverflow.com/questions/53691955/how-to-write-unescaped-string-to-a-xml-element-with-elementtree\">How to write unescaped string to a XML element with ElementTree?</a></p>\n<h2>Code that generates the XML file</h2>\n<pre><code>import xml.etree.ElementTree as ET\nfrom xml.sax.saxutils import unescape\n\n# defining the tree structure\nelement1 = ET.Element('test1')\nelement1.text = '&lt;![CDATA[Wired &amp; Forbidden]]&gt;'\n\n# &amp; and &lt;&gt; are in a weird format\nstring1 = ET.tostring(element1).decode()\nprint(string1)\n\n# now they are not weird anymore\n# more formally, we unescape '&amp;amp;', '&amp;lt;', and '&amp;gt;' in a string of data\n# from https://docs.python.org/3.8/library/xml.sax.utils.html#xml.sax.saxutils.unescape\nstring1 = unescape(string1)\nprint(string1)\n\nelement2 = ET.Element('test2')\nelement2.text = '&lt;![CDATA[Wired &amp; Forbidden]]&gt;'\nstring2 = unescape(ET.tostring(element2).decode())\nprint(string2)\n\n# make the xml file and open in append mode\nwith open('foo.xml', 'a') as f:\n f.write(string1 + '\\n')\n f.write(string2)\n</code></pre>\n<h2>Output foo.xml</h2>\n<pre><code>&lt;test1&gt;&lt;![CDATA[Wired &amp; Forbidden]]&gt;&lt;/test1&gt;\n&lt;test2&gt;&lt;![CDATA[Wired &amp; Forbidden]]&gt;&lt;/test2&gt;\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109/" ]
I've discovered that cElementTree is about 30 times faster than `xml.dom.minidom` and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree. Can it be done?
After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular elements. ``` def Comment(text=None): element = Element(Comment) element.text = text return element ``` Then in the `_write` function of ElementTree that actually outputs the XML, there's a special case handling for comments: ``` if tag is Comment: file.write("<!-- %s -->" % _escape_cdata(node.text, encoding)) ``` In order to support CDATA sections, I create a factory function called `CDATA`, extended the ElementTree class and changed the `_write` function to handle the CDATA elements. This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do. The implementation seems to work with both ElementTree and cElementTree. ``` import elementtree.ElementTree as etree #~ import cElementTree as etree def CDATA(text=None): element = etree.Element(CDATA) element.text = text return element class ElementTreeCDATA(etree.ElementTree): def _write(self, file, node, encoding, namespaces): if node.tag is CDATA: text = node.text.encode(encoding) file.write("\n<![CDATA[%s]]>\n" % text) else: etree.ElementTree._write(self, file, node, encoding, namespaces) if __name__ == "__main__": import sys text = """ <?xml version='1.0' encoding='utf-8'?> <text> This is just some sample text. </text> """ e = etree.Element("data") cdata = CDATA(text) e.append(cdata) et = ElementTreeCDATA(e) et.write(sys.stdout, "utf-8") ```
174,891
<p>Last week we released Omniture's analytics code onto a large volume of web sites after tinkering and testing for the last week or so.</p> <p>On almost all of our site templates, it works just fine. In a few scattered, unpredictable situations, there is a <em>crippling, browser-crashing experience</em> that <em>may</em> turn away some users.</p> <p>We're not able to see a relationship between the crashing templates at this time, and while there <em>are</em> many ways to troubleshoot, the one that's confuddling us is related to event listeners.</p> <p>The sites crash when any anchor on these templates is clicked. There isn't any inline JS, and while we firebug'ed our way through the attributes of the HTML, we couldn't find a discernable loop or issue that would cause this. (while we troubleshoot, you can experience this for yourself <a href="http://dv1.gatehousemedia.com/dev/omniture/index.html" rel="nofollow noreferrer">here</a> [<strong>warning</strong>! clicking any link in the page will cause your browser to crash!])</p> <p><strong>How do you determine if an object has a listener or not? How do you determine what will fire when event is triggered?</strong></p> <blockquote> <p>FYI, I'd love to set breakpoints, but <em>between Omnitures miserably obfuscated code and repeated browser crashes</em>, I'd like to research more thoroughly how I can approach this.</p> </blockquote>
[ { "answer_id": 175068, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 1, "selected": false, "text": "<p>DOM doesn't provide any means to introspecting through the events listeners' collections associated with a node.</p>\n\n<p>The only situation where listener can be identified is when it was added through setting a property or an attribute on the element - check on onxxx property or attribute.</p>\n\n<p>There have been a talk recently on WebAPI group at W3 on whether to add this functionality. Specialists seem to be against that. I share their arguments.</p>\n" }, { "answer_id": 175108, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 0, "selected": false, "text": "<p>A set of recommendations to the implementers of on-page analytics:</p>\n\n<ul>\n<li><p>Use document-level event capturing only, this is in almost every case (besides change/submit events) sufficient</p></li>\n<li><p>Do not execute computation-intensive code (as well as any IO operations) in the handlers, rather postpone execution with a timeout</p></li>\n</ul>\n\n<p>If this two simple rules are taken into account, I bet your browser will survive</p>\n" }, { "answer_id": 175146, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 3, "selected": true, "text": "<p>I did an \"inspect element\" on a link in that page with firebug, and in the DOM tab it says there is an onclick function (anonymous), and also some other function called \"s_onclick_0\".</p>\n\n<p>I coaxed firebug placing a watch like </p>\n\n<pre><code>alert(document.links[0].onclick)\n</code></pre>\n\n<p>to alert me the onclick function that omniture (i guess) attaches to links:</p>\n\n<pre><code>function anonymous(e) {\n var s = s_c_il[0], b = s.eh(this, \"onclick\");\n s.lnk = s.co(this);\n s.t();\n s.lnk = 0;\n if (b) {\n return this[b](e);\n }\n return true;\n}\n</code></pre>\n\n<p>Maybe in the same way you can see what it is really running after all that obfuscation.</p>\n" }, { "answer_id": 175371, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 0, "selected": false, "text": "<p>While traveling home I came to a solution that allows for introspection of event handlers on element added with AddEventListener. Run code before the inclusion of your analytics code. The code was not verified if works, but the idea, I guess is clear. It won't work in IE, however you can apply similar technique (of rewriting the API member) there as well.</p>\n\n<pre><code>(function(){\n var fAddEventListener = HTMLElement.prototype.addEventListener;\n HTMLElement.prototype.addEventListener = function() {\n if (!this._listeners)\n this._listeners = [];\n this._listeners.push(arguments);\n fAddEventListener.apply(this, arguments);\n }\n})();\n</code></pre>\n" }, { "answer_id": 177233, "author": "J5.", "author_id": 25380, "author_profile": "https://Stackoverflow.com/users/25380", "pm_score": 0, "selected": false, "text": "<p>I have some experience with Omniture and looking at your s_code.js, you have several things going on in the \"Link Tracking\" area, for example:</p>\n\n<pre><code>\n/* Link Tracking Config */\ns.trackDownloadLinks=true\ns.trackExternalLinks=true\ns.trackInlineStats=true\ns.linkDownloadFileTypes=\"exe,zip,wav,mp3,mov,mpg,avi,wmv,pdf,doc,docx,xls,xlsx,ppt,pptx\"\ns.linkInternalFilters=\"javascript:,gatehousemedia.com\"\ns.linkLeaveQueryString=false\ns.linkTrackVars=\"None\"\ns.linkTrackEvents=\"None\"\n</code></pre>\n\n<p>I would consult with the people at Omniture and verify that your link tracking configuration is set up correctly.</p>\n\n<p>Specifically, this template and the links inside seem to belong to morningsun.net and yet morningsun.net is not in the s.linkInternalFilters setting. If you are using the same s_code.js file for multiple domains, you can use javascript to set the configuration values for things like this (basing on the document.location.hostname for instance).</p>\n\n<p>I don't personally have experience with the link tracking configuration or I would give you more detail on how to configure it :)</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22491/" ]
Last week we released Omniture's analytics code onto a large volume of web sites after tinkering and testing for the last week or so. On almost all of our site templates, it works just fine. In a few scattered, unpredictable situations, there is a *crippling, browser-crashing experience* that *may* turn away some users. We're not able to see a relationship between the crashing templates at this time, and while there *are* many ways to troubleshoot, the one that's confuddling us is related to event listeners. The sites crash when any anchor on these templates is clicked. There isn't any inline JS, and while we firebug'ed our way through the attributes of the HTML, we couldn't find a discernable loop or issue that would cause this. (while we troubleshoot, you can experience this for yourself [here](http://dv1.gatehousemedia.com/dev/omniture/index.html) [**warning**! clicking any link in the page will cause your browser to crash!]) **How do you determine if an object has a listener or not? How do you determine what will fire when event is triggered?** > > FYI, I'd love to set breakpoints, but > *between Omnitures miserably obfuscated code and repeated browser > crashes*, I'd like to research more > thoroughly how I can approach this. > > >
I did an "inspect element" on a link in that page with firebug, and in the DOM tab it says there is an onclick function (anonymous), and also some other function called "s\_onclick\_0". I coaxed firebug placing a watch like ``` alert(document.links[0].onclick) ``` to alert me the onclick function that omniture (i guess) attaches to links: ``` function anonymous(e) { var s = s_c_il[0], b = s.eh(this, "onclick"); s.lnk = s.co(this); s.t(); s.lnk = 0; if (b) { return this[b](e); } return true; } ``` Maybe in the same way you can see what it is really running after all that obfuscation.
174,912
<p>I am a bit confused about the uses of these words. I have a table with he following columns: SITE, LAT, LONG, NAME, ......</p> <p>I want results with unique (or is it distinct) LAT, LONG. How do I achieve this?</p>
[ { "answer_id": 174941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>AFAIR both mean the same. To get unique vel distinct LAT &amp; LONG from your table just do:</p>\n\n<p>SELECT DISTINCT LAT, LONG FROM table;</p>\n" }, { "answer_id": 174952, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>UNIQUE is used for defining contraints on the data that can be stored in the table.</p>\n\n<p>DISTINCT is used in queries to remove duplicates from the result set, without affecting the underlying table data.</p>\n" }, { "answer_id": 174954, "author": "Michael OShea", "author_id": 13178, "author_profile": "https://Stackoverflow.com/users/13178", "pm_score": 4, "selected": false, "text": "<pre><code>select unique colA, colB from atable\n\nselect distinct colA, colB from atable\n</code></pre>\n\n<p>In this context, unique and distinct mean the same thing. </p>\n\n<p>Distinct however is ANSI standard, whereas unique is not.</p>\n\n<p>Please note that unique has many other meanings when used in other area's ie index creation etc.</p>\n" }, { "answer_id": 174992, "author": "Joe Moraca", "author_id": 23455, "author_profile": "https://Stackoverflow.com/users/23455", "pm_score": 1, "selected": false, "text": "<p>I always like to see a count of how many of each unique item there is so I would:</p>\n\n<p>select lat,long, count(lat) from table group by lat,long but thats just me</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am a bit confused about the uses of these words. I have a table with he following columns: SITE, LAT, LONG, NAME, ...... I want results with unique (or is it distinct) LAT, LONG. How do I achieve this?
``` select unique colA, colB from atable select distinct colA, colB from atable ``` In this context, unique and distinct mean the same thing. Distinct however is ANSI standard, whereas unique is not. Please note that unique has many other meanings when used in other area's ie index creation etc.
174,914
<p>Is there a recommended way to upgrade Quartz in JBoss 4.2.x?</p> <p>JBoss bundles quartz 1.5.2, but I have encountered issues (<a href="http://jira.opensymphony.com/browse/QUARTZ-399" rel="nofollow noreferrer">QUARTZ-399</a>, <a href="http://jira.opensymphony.com/browse/QUARTZ-520" rel="nofollow noreferrer">QUARTZ-520</a>) that I want to avoid.</p> <p>I would not want to patch quartz.jar in JBoss just to resolve the errors, but instead provide a new quartz.jar (plus associated configuration artifacts). The <a href="http://www.opensymphony.com/quartz/wikidocs/Quartz%201.6.0.html#Quartz1.6.0-MigrationNotes" rel="nofollow noreferrer">Quartz 1.6 migration notes</a> only contain information specific to Quartz, and I could not find any additional information during my search.</p> <p>It does not seem to work to just put the new quartz.jar into the EAR file, because the old version is loaded at the server level (in the server's lib directory).</p> <p>I am quite sure somebody has already tried that, and hope that this person could share or provide some links.</p>
[ { "answer_id": 174941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>AFAIR both mean the same. To get unique vel distinct LAT &amp; LONG from your table just do:</p>\n\n<p>SELECT DISTINCT LAT, LONG FROM table;</p>\n" }, { "answer_id": 174952, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>UNIQUE is used for defining contraints on the data that can be stored in the table.</p>\n\n<p>DISTINCT is used in queries to remove duplicates from the result set, without affecting the underlying table data.</p>\n" }, { "answer_id": 174954, "author": "Michael OShea", "author_id": 13178, "author_profile": "https://Stackoverflow.com/users/13178", "pm_score": 4, "selected": false, "text": "<pre><code>select unique colA, colB from atable\n\nselect distinct colA, colB from atable\n</code></pre>\n\n<p>In this context, unique and distinct mean the same thing. </p>\n\n<p>Distinct however is ANSI standard, whereas unique is not.</p>\n\n<p>Please note that unique has many other meanings when used in other area's ie index creation etc.</p>\n" }, { "answer_id": 174992, "author": "Joe Moraca", "author_id": 23455, "author_profile": "https://Stackoverflow.com/users/23455", "pm_score": 1, "selected": false, "text": "<p>I always like to see a count of how many of each unique item there is so I would:</p>\n\n<p>select lat,long, count(lat) from table group by lat,long but thats just me</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12039/" ]
Is there a recommended way to upgrade Quartz in JBoss 4.2.x? JBoss bundles quartz 1.5.2, but I have encountered issues ([QUARTZ-399](http://jira.opensymphony.com/browse/QUARTZ-399), [QUARTZ-520](http://jira.opensymphony.com/browse/QUARTZ-520)) that I want to avoid. I would not want to patch quartz.jar in JBoss just to resolve the errors, but instead provide a new quartz.jar (plus associated configuration artifacts). The [Quartz 1.6 migration notes](http://www.opensymphony.com/quartz/wikidocs/Quartz%201.6.0.html#Quartz1.6.0-MigrationNotes) only contain information specific to Quartz, and I could not find any additional information during my search. It does not seem to work to just put the new quartz.jar into the EAR file, because the old version is loaded at the server level (in the server's lib directory). I am quite sure somebody has already tried that, and hope that this person could share or provide some links.
``` select unique colA, colB from atable select distinct colA, colB from atable ``` In this context, unique and distinct mean the same thing. Distinct however is ANSI standard, whereas unique is not. Please note that unique has many other meanings when used in other area's ie index creation etc.
174,916
<p>I'm specifying my doctype as xhtml strict, but it's being sent over the wire as a content type of text/html. I'd like to specify that the content type is application/xhtml+xm, but I can't figure out where, or if, I can configure this from within my application</p>
[ { "answer_id": 174926, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>You can specify it in the @ page attributes section, like this:</p>\n\n<pre><code>&lt;%@ Page ContentType=\"application/xhtml+xm\" %&gt;\n</code></pre>\n\n<p>...more on <a href=\"http://msdn.microsoft.com/en-us/library/ydy4x04a(v=vs.100).aspx\" rel=\"noreferrer\">MSDN</a>.</p>\n" }, { "answer_id": 174932, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<p>In your code behind file, during the Page_Load event, try addind the following code:</p>\n\n<pre><code>Response.Clear()\nResponse.ContentType = \"application/xhtml+xm\"\n</code></pre>\n" }, { "answer_id": 6932768, "author": "apros", "author_id": 157666, "author_profile": "https://Stackoverflow.com/users/157666", "pm_score": 0, "selected": false, "text": "<p>=========aspx===============</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\"\nInherits=\"_Default\" %&gt;\n\n\n&lt;asp:literal runat=\"server\" id=\"dt\"&gt;&lt;/asp:literal&gt;\n\n\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head runat=\"server\"&gt;\n</code></pre>\n\n<p>==============code behind=========</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\nthis.dt.Text= \"&lt;!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0\nTransitional//EN\\\"\n\\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\\\"&gt;\";\n\n}\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm specifying my doctype as xhtml strict, but it's being sent over the wire as a content type of text/html. I'd like to specify that the content type is application/xhtml+xm, but I can't figure out where, or if, I can configure this from within my application
You can specify it in the @ page attributes section, like this: ``` <%@ Page ContentType="application/xhtml+xm" %> ``` ...more on [MSDN](http://msdn.microsoft.com/en-us/library/ydy4x04a(v=vs.100).aspx).
174,923
<p>I have a btnSave_Click() function in my code-behind. If a user clicks the save button (image) I created, it calls this function:</p> <pre><code>protected void btnSave_Click(object sender, EventArgs e) { this.saveForm(); txtMessages.Text = "Save Complete"; } </code></pre> <p>The saveForm() function obviously saves the form (through stored procedures). Will .NET wait until that save is complete before displaying the "Save Complete" message, or is there something else I should be doing to let the user know when the save is done.</p> <p>What's the best tutorial for this type of thing (i.e. spinner and notification of when save is complete)?</p>
[ { "answer_id": 174936, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 0, "selected": false, "text": "<p>It will only show \"Save Complete\" once the previous operation is complete.</p>\n\n<p>I typically put these types of messages in a statusbar. But it really depends on your application and UI.</p>\n" }, { "answer_id": 174938, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 0, "selected": false, "text": "<p>Yes. It is top down.</p>\n\n<p>I could add that if your save form logic could take awhile it might be better to spin it into a background thread to prevent locking up the GUI. Here is some good background reading on that. <a href=\"http://www.yoda.arachsys.com/csharp/threads/\" rel=\"nofollow noreferrer\">http://www.yoda.arachsys.com/csharp/threads/</a></p>\n" }, { "answer_id": 174939, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>Yes, unless you are doing something to start a secondary thread inside the \"SaveForm\" method the next line will not be rendered until the entire saveForm method is done.</p>\n" }, { "answer_id": 174940, "author": "Chad Moran", "author_id": 25416, "author_profile": "https://Stackoverflow.com/users/25416", "pm_score": 4, "selected": true, "text": "<p>This is a synchronous method. It's going to wait until the saveForm() method has returned (exited) it's completion before it can move on.</p>\n" }, { "answer_id": 174943, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 0, "selected": false, "text": "<p>Just about anything you will do inside the .Net framework is synchronous unless you specifically try to make it asynchronous.</p>\n\n<p>This means that the step will wait for the return (and the stored proc call will wait for the return from SQL) before moving to the next step.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
I have a btnSave\_Click() function in my code-behind. If a user clicks the save button (image) I created, it calls this function: ``` protected void btnSave_Click(object sender, EventArgs e) { this.saveForm(); txtMessages.Text = "Save Complete"; } ``` The saveForm() function obviously saves the form (through stored procedures). Will .NET wait until that save is complete before displaying the "Save Complete" message, or is there something else I should be doing to let the user know when the save is done. What's the best tutorial for this type of thing (i.e. spinner and notification of when save is complete)?
This is a synchronous method. It's going to wait until the saveForm() method has returned (exited) it's completion before it can move on.
174,933
<p>How can I get a single keyboard character from the terminal with Ruby without pressing enter? I tried <code>Curses::getch</code>, but that didn't really work for me.</p>
[ { "answer_id": 174967, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999\" rel=\"noreferrer\">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999</a></p>\n\n<pre><code>#!/usr/bin/ruby\n\nbegin\n system(\"stty raw -echo\")\n str = STDIN.getc\nensure\n system(\"stty -raw echo\")\nend\np str.chr\n</code></pre>\n\n<p>(Tested on my OS X system, may not be portable to all Ruby platforms). See <a href=\"http://www.rubyquiz.com/quiz5.html\" rel=\"noreferrer\">http://www.rubyquiz.com/quiz5.html</a> for some additional suggestions, including for Windows.</p>\n" }, { "answer_id": 3983726, "author": "mit", "author_id": 362951, "author_profile": "https://Stackoverflow.com/users/362951", "pm_score": 4, "selected": false, "text": "<h3>Note: This is and old answer and the solution no longer works on most systems.</h3>\n<p>But the answer could still be useful for some environments, where the other methods don't work. Please read the comments below.</p>\n<hr />\n<p>First you have to install highline:</p>\n<pre><code>gem install highline\n</code></pre>\n<p>Then try if the highline method works for you:</p>\n<pre><code>require &quot;highline/system_extensions&quot;\ninclude HighLine::SystemExtensions\n\nprint &quot;Press any key:&quot;\nk = get_character\nputs k.chr\n</code></pre>\n" }, { "answer_id": 8274275, "author": "AlexChaffee", "author_id": 190135, "author_profile": "https://Stackoverflow.com/users/190135", "pm_score": 4, "selected": false, "text": "<p>Raw mode (<code>stty raw -echo</code>) unfortunately causes control-C to get sent in as a character, not as a SIGINT. So if you want blocking input like above, but allow the user to hit control-C to stop the program while it's waiting, make sure to do this:</p>\n\n<pre><code>Signal.trap(\"INT\") do # SIGINT = control-C\n exit\nend\n</code></pre>\n\n<p>And if you want non-blocking input -- that is, periodically check if the user has pressed a key, but in the meantime, go do other stuff -- then you can do this:</p>\n\n<pre><code>require 'io/wait'\n\ndef char_if_pressed\n begin\n system(\"stty raw -echo\") # turn raw input on\n c = nil\n if $stdin.ready?\n c = $stdin.getc\n end\n c.chr if c\n ensure\n system \"stty -raw echo\" # turn raw input off\n end\nend\n\nwhile true\n c = char_if_pressed\n puts \"[#{c}]\" if c\n sleep 1\n puts \"tick\"\nend\n</code></pre>\n\n<p>Note that you don't need a special SIGINT handler for the non-blocking version since the tty is only in raw mode for a brief moment.</p>\n" }, { "answer_id": 13653636, "author": "lzap", "author_id": 299204, "author_profile": "https://Stackoverflow.com/users/299204", "pm_score": 0, "selected": false, "text": "<p>And if you are building <strong>curses</strong> application, you need to call </p>\n\n<pre><code>nocbreak\n</code></pre>\n\n<p><a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/curses/rdoc/Curses.html#method-c-cbreak\" rel=\"nofollow\">http://www.ruby-doc.org/stdlib-1.9.3/libdoc/curses/rdoc/Curses.html#method-c-cbreak</a></p>\n" }, { "answer_id": 14527475, "author": "Andrew", "author_id": 421010, "author_profile": "https://Stackoverflow.com/users/421010", "pm_score": 4, "selected": false, "text": "<p>@Jay gave a great answer, but there are two problems: </p>\n\n<ol>\n<li>You can mess up default tty state; </li>\n<li>You ignore control characters (^C for SIGINT, etc). </li>\n</ol>\n\n<p>A simple fix for that is to save previous tty state and use following parameters: </p>\n\n<ul>\n<li><code>-icanon</code> - disable canonical input (ERASE and KILL processing);</li>\n<li><code>isig</code> - enable the checking of characters against the special control characters INTR, QUIT, and SUSP.</li>\n</ul>\n\n<p>In the end you would have a function like this:</p>\n\n<pre><code>def get_char\n state = `stty -g`\n `stty raw -echo -icanon isig`\n\n STDIN.getc.chr\nensure\n `stty #{state}`\nend\n</code></pre>\n" }, { "answer_id": 27021816, "author": "iNecas", "author_id": 457560, "author_profile": "https://Stackoverflow.com/users/457560", "pm_score": 6, "selected": false, "text": "<p>Since ruby 2.0.0, there is a 'io/console' in the stdlib with this feature</p>\n\n<pre><code>require 'io/console'\nSTDIN.getch\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25017/" ]
How can I get a single keyboard character from the terminal with Ruby without pressing enter? I tried `Curses::getch`, but that didn't really work for me.
<http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999> ``` #!/usr/bin/ruby begin system("stty raw -echo") str = STDIN.getc ensure system("stty -raw echo") end p str.chr ``` (Tested on my OS X system, may not be portable to all Ruby platforms). See <http://www.rubyquiz.com/quiz5.html> for some additional suggestions, including for Windows.
174,986
<p>I create a TextArea in actionscript:</p> <pre><code>var textArea:TextArea = new TextArea(); </code></pre> <p>I want it to have a black background. I've tried</p> <pre><code>textArea.setStyle("backgroundColor", 0x000000); </code></pre> <p>and I've tried</p> <pre><code>textArea.opaqueBackground = 0x000000; </code></pre> <p>but the TextArea stays white. What should I do?</p>
[ { "answer_id": 175914, "author": "nerdabilly", "author_id": 8349, "author_profile": "https://Stackoverflow.com/users/8349", "pm_score": 4, "selected": true, "text": "<p>TextArea is a UI component built from TextField and other Flash built-in classes and UIComponents. As with most of the Adobe UI components, nothing is as it seems when setting properties. To set the color of the area behind the text in the TextArea, you need to actually set the opaque background of its internal TextField using the textField property:</p>\n\n<pre><code>var textArea:TextArea = new TextArea()\ntextArea.textField.opaqueBackground = 0x000000;\n</code></pre>\n\n<p>Of course now that the background is black, the text can't also be black, so we change its color using a new TextFormat:</p>\n\n<pre><code>var myFormat:TextFormat = new TextFormat();\nmyFormat.color = 0xffffff;\ntextArea.setStyle(\"textFormat\",myFormat);\n</code></pre>\n\n<p>then just set the text and add to stage:</p>\n\n<pre><code>textArea.text = \"hello\";\naddChild(textArea); \n</code></pre>\n\n<p>Also, if you want a little more control, there's a nice extension class here that fixes a lot of the problems with TextArea:</p>\n\n<p><a href=\"http://blog.bodurov.com/Post.aspx?postID=14\" rel=\"nofollow noreferrer\">http://blog.bodurov.com/Post.aspx?postID=14</a></p>\n" }, { "answer_id": 7822548, "author": "Rama", "author_id": 1003310, "author_profile": "https://Stackoverflow.com/users/1003310", "pm_score": 1, "selected": false, "text": "<p>Here is what worked for me, which I discovered on my own after reviewing updated AC3 documentation</p>\n\n<p><strong>TextArea - Background Color, 2011 AC3</strong></p>\n\n<p>Took me forever to realize that in AC3, as of now (2011), they officially tell you to use spark TextArea instead of mx </p>\n\n<p>(<code>s:TextArea</code> instead of <code>mx:TextArea</code>)</p>\n\n<pre><code>&lt;s:TextArea\nid=\"joy_text\"\ncolor=\"0xFF0000\"\ncontentBackgroundColor=\"0x000000\"\ntext = \"joy\"\n/&gt;\n</code></pre>\n\n<p><strong>Please Note</strong> </p>\n\n<p>color = font color</p>\n\n<p>make sure to include in your namespaces: (up at top of .mxml file)</p>\n\n<pre><code>xmlns:s=\"library://ns.adobe.com/flex/spark\"\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/174986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I create a TextArea in actionscript: ``` var textArea:TextArea = new TextArea(); ``` I want it to have a black background. I've tried ``` textArea.setStyle("backgroundColor", 0x000000); ``` and I've tried ``` textArea.opaqueBackground = 0x000000; ``` but the TextArea stays white. What should I do?
TextArea is a UI component built from TextField and other Flash built-in classes and UIComponents. As with most of the Adobe UI components, nothing is as it seems when setting properties. To set the color of the area behind the text in the TextArea, you need to actually set the opaque background of its internal TextField using the textField property: ``` var textArea:TextArea = new TextArea() textArea.textField.opaqueBackground = 0x000000; ``` Of course now that the background is black, the text can't also be black, so we change its color using a new TextFormat: ``` var myFormat:TextFormat = new TextFormat(); myFormat.color = 0xffffff; textArea.setStyle("textFormat",myFormat); ``` then just set the text and add to stage: ``` textArea.text = "hello"; addChild(textArea); ``` Also, if you want a little more control, there's a nice extension class here that fixes a lot of the problems with TextArea: <http://blog.bodurov.com/Post.aspx?postID=14>
175,042
<p>I have this solution for a single button:</p> <pre><code>myButton.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(myButton).ToString()); </code></pre> <p>Which works pretty well for one button, any ideas on how to expand this to 2 buttons?</p>
[ { "answer_id": 175060, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "<p>You could add an clientside onSubmit handler, or you could do this:</p>\n\n<pre><code>myButton.Attributes.Add(\"onclick\", \"this.disabled=true; document.getElementById('\" \n+ button2.ClientID + \"').disabled = true;\" \n+ GetPostBackEventReference(myButton).ToString());\n</code></pre>\n" }, { "answer_id": 175061, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 0, "selected": false, "text": "<p>Change the command to:</p>\n\n<pre><code>myButton.Attributes.Add(\"onclick\", \"this.disabled=true;document.getElementbyID(\"Button2\").disabled=true;\" + GetPostBackEventReference(myButton).ToString());\n</code></pre>\n" }, { "answer_id": 175072, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 1, "selected": false, "text": "<p>Change the javascript to reference the other button as well.</p>\n\n<pre><code>var btn1 = document.GetElementById('btn1ID');\nvar btn2 = this;\n\nbtn1.disabled = true;\nbtn2.disabled = true;\n</code></pre>\n\n<p>If the buttons are in a naming container, you'll need to use the .NET object's property called ClientID to get the html ID of the element.</p>\n\n<pre><code>var btn1 = document.GetElementById('&lt;%= btn1.ClientID %&gt;');\n</code></pre>\n\n<p>I suggest wrapping these in a script tag and a function, then just call the function from your .NET attribute addition.</p>\n\n<p><strong>CodeBehind</strong></p>\n\n<pre><code>btn2.Attributes.Add(\"onclick\", \"handleClick();\")\n</code></pre>\n\n<p><strong>ASPX</strong></p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function handleClick() {\n var btn1 = document.GetElementById('&lt;%= btn1.ClientID %&gt;');\n var btn2 = this;\n\n btn1.disabled = true;\n btn2.disabled = true;\n\n }\n&lt;/script&gt;\n\n&lt;asp:Button id=\"btn1\" runat=\"server\" text=\"Button 1\" /&gt;\n&lt;asp:Button id=\"btn2\" runat=\"server\" text=\"Button 2\" /&gt;\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I have this solution for a single button: ``` myButton.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(myButton).ToString()); ``` Which works pretty well for one button, any ideas on how to expand this to 2 buttons?
You could add an clientside onSubmit handler, or you could do this: ``` myButton.Attributes.Add("onclick", "this.disabled=true; document.getElementById('" + button2.ClientID + "').disabled = true;" + GetPostBackEventReference(myButton).ToString()); ```
175,055
<p>I am running a series of JUnits using Apache ANT using JDK 1.5.</p> <p>All JUnits that use an Oracle JDBC driver give the UnsatisfiedLinkError shown below.</p> <p>What native library is it looking for and how do I solve this? What should the PATH variable contain?</p> <pre><code>java.lang.UnsatisfiedLinkError: oracle/jdbc/driver/T2CConnection.t2cGetCharSet([CI[CI[CI[CII[SLoracle/jdbc/driver/GetCharSetError;)S at oracle.jdbc.driver.T2CConnection.getCharSetIds(T2CConnection.java:2957) at oracle.jdbc.driver.T2CConnection.logon(T2CConnection.java:320) at oracle.jdbc.driver.PhysicalConnection.&lt;init&gt;(PhysicalConnection.java:361) at oracle.jdbc.driver.T2CConnection.&lt;init&gt;(T2CConnection.java:142) at oracle.jdbc.driver.T2CDriverExtension.getConnection(T2CDriverExtension.java:79) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:595) at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:196) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:114) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:77) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:59) at oracle.jdbc.pool.OracleConnectionCacheImpl.getNewPoolOrXAConnection(OracleConnectionCacheImpl.java:401) at oracle.jdbc.pool.OracleConnectionCacheImpl.setMinLimit(OracleConnectionCacheImpl.java:752) </code></pre>
[ { "answer_id": 175092, "author": "Shachar", "author_id": 13897, "author_profile": "https://Stackoverflow.com/users/13897", "pm_score": 0, "selected": false, "text": "<p>Had this one, you should add classes12.jar or classes13.jar to your classpath (not sure about the name, it's been over a year, google these...)</p>\n" }, { "answer_id": 175902, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<p>You need to pass -Djava.library.path=YOUR_ORACLE_HOME\\bin to the JRE as a runtime parameter</p>\n\n<p>So....</p>\n\n<pre><code>java [other java switches + runtime parameters] -Djava.library.path=YOUR_ORACLE_HOME\\bin run-classname\n</code></pre>\n\n<p>Also, make sure the jar in the classpath is the same one as is in $ORACLE_HOME/jdbc/lib... overwrite the Eclipse one with the Oracle one if necessary.</p>\n\n<p>If this doesn't work it would help to know which version of Oracle you're running since this will affect whether you should be using classes12.jar or ojdbc14.jar</p>\n" }, { "answer_id": 176362, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>\"Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native. \"</p>\n\n<p>Means that it is looking for a DLL/so -- you probably are using THICK driver ? JDBC 2 driver ?</p>\n\n<p>If yes, then you might want to add OCI.DLL, etc.</p>\n" }, { "answer_id": 177704, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Resolved!</p>\n\n<p>It was actually an out-of-date ojdbc14.jar file causing this issue. All I did was update it and the problem is fixed now. The classes file </p>\n\n<p>Thanks</p>\n" }, { "answer_id": 50645559, "author": "Aamir", "author_id": 1225373, "author_profile": "https://Stackoverflow.com/users/1225373", "pm_score": 0, "selected": false, "text": "<p>Had the same problem; resolved by changing the connection url from jdbc:oracle:oci:@//localhost:1521/service_name to jdbc:oracle:thin:@//localhost:1521/service_name</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am running a series of JUnits using Apache ANT using JDK 1.5. All JUnits that use an Oracle JDBC driver give the UnsatisfiedLinkError shown below. What native library is it looking for and how do I solve this? What should the PATH variable contain? ``` java.lang.UnsatisfiedLinkError: oracle/jdbc/driver/T2CConnection.t2cGetCharSet([CI[CI[CI[CII[SLoracle/jdbc/driver/GetCharSetError;)S at oracle.jdbc.driver.T2CConnection.getCharSetIds(T2CConnection.java:2957) at oracle.jdbc.driver.T2CConnection.logon(T2CConnection.java:320) at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:361) at oracle.jdbc.driver.T2CConnection.<init>(T2CConnection.java:142) at oracle.jdbc.driver.T2CDriverExtension.getConnection(T2CDriverExtension.java:79) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:595) at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:196) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:114) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:77) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:59) at oracle.jdbc.pool.OracleConnectionCacheImpl.getNewPoolOrXAConnection(OracleConnectionCacheImpl.java:401) at oracle.jdbc.pool.OracleConnectionCacheImpl.setMinLimit(OracleConnectionCacheImpl.java:752) ```
Resolved! It was actually an out-of-date ojdbc14.jar file causing this issue. All I did was update it and the problem is fixed now. The classes file Thanks
175,056
<p>In a project I am working on, we have an ongoing discussion amongst the dev team - should the production environment be deployed as a checkout from the SVN repository or as an export?</p> <p>The development environment is obviously a checkout, since it is constantly updated. For the production, I'm personally for checking out the main trunk, since it makes future updates easier (just run svn update). However some of the devs are against it, as svn creates files with the group/owner and permissions of the svn process (this is on a linux OS, so those things matter), and also having the .svn directories on the production seem to them to be somewhat dirty.</p> <p>Also, if it is a checkout - how do you push individual features to the production without including in-development code? do you use tags or branch out for each feature? any alternatives?</p> <p><strong>EDIT:</strong> I might not have been clear - one of the requirement is to be able to constantly be able to push fixes to the production environment. We want to avoid a complete build (which takes much longer than a simple update) just for pushing critical fixes.</p>
[ { "answer_id": 175073, "author": "Shachar", "author_id": 13897, "author_profile": "https://Stackoverflow.com/users/13897", "pm_score": 3, "selected": false, "text": "<p>IMHO you should create a branch/tag where you have the (desired) subset of the dev env which you use for production. Someone should either maintain this manually or automatically using scripts. Then, you should export (rather than checkout). Incremental updates are a non-issue, unless you're changing files on your production environment and you don't want those files to be overwritten.</p>\n\n<p>Just my $0.02</p>\n" }, { "answer_id": 175079, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 2, "selected": false, "text": "<p>I would look into some deployment software like Capistrano (it's a ruby program)</p>\n\n<p>I would personally use exporting a tagged copy of trunk instead of just exporting trunk if you are going to use be rolling your own solution or manually. </p>\n" }, { "answer_id": 175081, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 3, "selected": false, "text": "<p>No question - export. </p>\n\n<p>You would not be making updates, so no reason to have a checkout. You would just be deploying junk out.</p>\n\n<p>I would say any environment should be only an export; you only use checkout locally when you are developing. Of course we are also using build scripts, so updating the deployment is as simple as running the script.</p>\n\n<p>As far as the in development code, create branches for any work being done. Only commit to the trunk when ready for deployment to the development environment.</p>\n" }, { "answer_id": 176053, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "<p>I deploy it as a copy. Not manual, of course.</p>\n\n<p>I use 'make' and 'checkinstall'. I create a small Makefile which uses the system command 'install' to copy all the needed files to the appropriate directories on the web server, and I have preinstall and postinstall shell scripts that will be run on the server. </p>\n\n<p>When time for deployment comes, I just run 'checkinstall' which creates a package (RPM, DEB or TGZ, depending on which Linux distribution I target). I install it using regular tools provided by a Linux distribution package manager (rpm, dpkg, pkgtool). Of course, if you want to track dependencies as well, you can use yum, apt-get, etc.</p>\n\n<p>It makes it really easy if you want to distribute a new version of your web app. to multiple target servers. And stuff like uninstall, reverting to an older version, etc. are very easy because you have a ready to use package for each version you deployed.</p>\n\n<p>This might not fit your 'push often' strategy though if you use some stuff that needs compiling. However, for scripting stuff (like PHP that I do), creating a package (of about 300+ PHP files) takes about 20 seconds on my machine. And about as much to install it on any target system.</p>\n\n<p>To separate the code 'for release' from the 'in-development' code, I use branching. With Git, it's really easy, since branching is cheap and fast.</p>\n" }, { "answer_id": 741472, "author": "jcelgin", "author_id": 26582, "author_profile": "https://Stackoverflow.com/users/26582", "pm_score": 3, "selected": false, "text": "<p>I've been struggling with this, and I think I finally decided on checkout. Yes, there is extra junk there, but... </p>\n\n<ul>\n<li>Export doesn't account for deleted files (unless your solution is to delete everything in the dir and THEN export, which I think is way worse). Checkout will remove deleted files.</li>\n<li>Checkout is faster. Period. Fewer files being updated means less down/transition time, and an export pulls down and overwrites EVERYTHING, not just files needing an update.</li>\n</ul>\n\n<p>Not saying it'll work for everyone, but these two things influenced my decision. Best of luck with your decision.</p>\n" }, { "answer_id": 741488, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": -1, "selected": false, "text": "<p><h2>EXPORT</h2> that's it. You don't have any good reason to put extra junk into production system.</p>\n\n<ul>\n<li>You'll expose your source code</li>\n<li>If this is web application it's even worse, your visitors can download your source code, how cool is that! very open :)</li>\n</ul>\n" }, { "answer_id": 1228320, "author": "Chris", "author_id": 150401, "author_profile": "https://Stackoverflow.com/users/150401", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://subversion.tigris.org/faq.html#website-auto-update\" rel=\"noreferrer\">The Subversion FAQ</a> seems to advocate deployment as a checkout, autoupdated with post-commit hook scripts. They prevent Apache from exporting .svn folders (probably a good idea) by adding the following in httpd.conf:</p>\n\n<pre><code># Disallow browsing of Subversion working copy administrative dirs.\n&lt;DirectoryMatch \"^/.*/\\.svn/\"&gt;\n Order deny,allow\n Deny from all\n&lt;/DirectoryMatch&gt;\n</code></pre>\n\n<p>I'm extremely new to svn myself, but maybe you could trigger a hook script when you create a new tag. That way, when you're ready to update the live site, you just commit your last changes to the trunk, create the new tag, and the script updates your live site with svn update.</p>\n" }, { "answer_id": 2629967, "author": "Andrea", "author_id": 315531, "author_profile": "https://Stackoverflow.com/users/315531", "pm_score": 1, "selected": false, "text": "<p>Personally I'm always in doubt about the solution of this problem,\nI prefer having no \".svn\" directories around my production environment, it's very dirty\nbut at the same time, export is very tedious with large web applications (especially if using some 3rd parties \"components\" like Extjs,FCKeditor etc..).</p>\n\n<p>I think there are not \"killer solutions\" at this moment.</p>\n" }, { "answer_id": 3148532, "author": "Michael Gerner Andreasen", "author_id": 379959, "author_profile": "https://Stackoverflow.com/users/379959", "pm_score": 1, "selected": false, "text": "<p>let me see..... ln -s ? what can that be used for?</p>\n\n<pre><code>/var/www/www.my-prod-site.com/public/\n/var/www/www.my-prod-site.com/builds/Rev 1/\n/var/www/www.my-prod-site.com/builds/Rev 2/\n/var/www/www.my-prod-site.com/builds/Rev 3/\n/var/www/www.my-prod-site.com/builds/Rev 99/\n</code></pre>\n\n<p>svn export to your builds directorys...... copy any config files over from /public that is your symbolic link to your former release build, and then just shift the symbolic link from public to point to your new build directory. it takes less time offline than any of the things i have seen posted here, and it also makes going back WAY FASTER unless you f<em>ck</em>p your db everytime by altering tables.</p>\n" }, { "answer_id": 13729022, "author": "Donny Nyamweya", "author_id": 1832928, "author_profile": "https://Stackoverflow.com/users/1832928", "pm_score": 1, "selected": false, "text": "<p>Here are some opinions - </p>\n\n<p>.svn files on production are dirty?\nIf the .svn directories are intact and not corrupt, they are far from dirty, they are actually a lifesaver. For security, you can tell apache to prevent browsing them. </p>\n\n<p>Checkout or export? my approach...\nI definitely use tags and branches - it is dangerous to attach a production server to trunk and pray that no one runs svn up just after someone commits faulty code into trunk to see what it does on DEV.\nI have a reusable tag (say _production and _staging) and at the beginning of my setup I checkout each one to the matching server. I then lockout all access to modify the contents of the live and staging server. Thereafter, the DEV server is tied to the trunk head. When code is stable enough for QA/staging, we create a tag and rename it to _staging to allow the staging server to sync to it (script runs 'svn up') whenever it sees changes to that tag. Once we are happy with _staging, we rename it to _production and that makes the code deploy to the live server.\nAlternatively, you can create tags/branches with different names and use 'svn switch URL' to point the server to a new tag/branch (fixed point). All the above make it very easy to deploy without downtime and if rollback is necessary, you can quickly rename the archived former tag or use 'svn switch OLD_URL' to immediately undo the new changes without worrying about each small file and line-changes.</p>\n\n<p>Permissions &amp; ownership\nIf you understand and know what the permissions should be for the files, you can have your script run after each deployment to set the CHOWN and CHMOD to what you want it to be.</p>\n\n<p>Fear vs Knowledge\nI have heard of many afraid people ruling out the presence of SVN on the production server. The opposite is actually very scary. How do you assure your product team and customers that the application will not collapse into a big pile or error messages without the ability to do dry-runs or 'svn status -u' to ensure that the deployment will modify just those files that need to change? checking the status allows me even know if anyone forced their way it and made a 'quick change' directly on the server - you know people tend to bypass rules for things that look quick to them.</p>\n\n<p>Imaging there is an error on the live server? with .svn, you can identify the exact version it is sync'd to (svn info) and then check if it is true to that url (sv status -u). Then you can build an honest replica of that setup by checking-out the same tag/version to a sandbox server where you can safely troubleshoot.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10585/" ]
In a project I am working on, we have an ongoing discussion amongst the dev team - should the production environment be deployed as a checkout from the SVN repository or as an export? The development environment is obviously a checkout, since it is constantly updated. For the production, I'm personally for checking out the main trunk, since it makes future updates easier (just run svn update). However some of the devs are against it, as svn creates files with the group/owner and permissions of the svn process (this is on a linux OS, so those things matter), and also having the .svn directories on the production seem to them to be somewhat dirty. Also, if it is a checkout - how do you push individual features to the production without including in-development code? do you use tags or branch out for each feature? any alternatives? **EDIT:** I might not have been clear - one of the requirement is to be able to constantly be able to push fixes to the production environment. We want to avoid a complete build (which takes much longer than a simple update) just for pushing critical fixes.
[The Subversion FAQ](http://subversion.tigris.org/faq.html#website-auto-update) seems to advocate deployment as a checkout, autoupdated with post-commit hook scripts. They prevent Apache from exporting .svn folders (probably a good idea) by adding the following in httpd.conf: ``` # Disallow browsing of Subversion working copy administrative dirs. <DirectoryMatch "^/.*/\.svn/"> Order deny,allow Deny from all </DirectoryMatch> ``` I'm extremely new to svn myself, but maybe you could trigger a hook script when you create a new tag. That way, when you're ready to update the live site, you just commit your last changes to the trunk, create the new tag, and the script updates your live site with svn update.
175,066
<p>My database contains three tables called <code>Object_Table</code>, <code>Data_Table</code> and <code>Link_Table</code>. The link table just contains two columns, the identity of an object record and an identity of a data record.</p> <p>I want to copy the data from <code>DATA_TABLE</code> where it is linked to one given object identity and insert corresponding records into <code>Data_Table</code> and <code>Link_Table</code> for a different given object identity.</p> <p>I <strong>can</strong> do this by selecting into a table variable and the looping through doing two inserts for each iteration.</p> <p>Is this the best way to do it?</p> <p><strong>Edit</strong> : I want to avoid a loop for two reason, the first is that I'm lazy and a loop/temp table requires more code, more code means more places to make a mistake and the second reason is a concern about performance.</p> <p>I can copy all the data in one insert but how do get the link table to link to the new data records where each record has a new id?</p>
[ { "answer_id": 175104, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 2, "selected": false, "text": "<p>If you want the actions to be more or less atomic, I would make sure to wrap them in a transaction. That way you can be sure both happened or both didn't happen as needed. </p>\n" }, { "answer_id": 175107, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 2, "selected": false, "text": "<p>Insert can only operate on one table at a time. Multiple Inserts have to have multiple statements.</p>\n\n<p>I don't know that you need to do the looping through a table variable - can't you just use a mass insert into one table, then the mass insert into the other?</p>\n\n<p>By the way - I am guessing you mean copy the data from Object_Table; otherwise the question does not make sense.</p>\n" }, { "answer_id": 175136, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": false, "text": "<p>You still need two <code>INSERT</code> statements, but it sounds like you want to get the <code>IDENTITY</code> from the first insert and use it in the second, in which case, you might want to look into <code>OUTPUT</code> or <code>OUTPUT INTO</code>: <a href=\"http://msdn.microsoft.com/en-us/library/ms177564.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms177564.aspx</a></p>\n" }, { "answer_id": 175138, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 8, "selected": false, "text": "<p>In one <em>statement</em>: No.</p>\n\n<p>In one <em>transaction</em>: Yes</p>\n\n<pre><code>BEGIN TRANSACTION\n DECLARE @DataID int;\n INSERT INTO DataTable (Column1 ...) VALUES (....);\n SELECT @DataID = scope_identity();\n INSERT INTO LinkTable VALUES (@ObjectID, @DataID);\nCOMMIT\n</code></pre>\n\n<p>The good news is that the above code is also guaranteed to be <em>atomic</em>, and can be sent to the server from a client application with one sql string in a single function call as if it were one statement. You could also apply a trigger to one table to get the effect of a single insert. However, it's ultimately still two statements and you probably don't want to run the trigger for <em>every</em> insert.</p>\n" }, { "answer_id": 175144, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 3, "selected": false, "text": "<p>It sounds like the Link table captures the many:many relationship between the Object table and Data table.</p>\n\n<p>My suggestion is to use a stored procedure to manage the transactions. When you want to insert to the Object or Data table perform your inserts, get the new IDs and insert them to the Link table.</p>\n\n<p>This allows all of your logic to remain encapsulated in one easy to call sproc.</p>\n" }, { "answer_id": 175160, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "<p>You might create a View selecting the column names required by your insert statement, add an INSTEAD OF INSERT Trigger, and insert into this view.</p>\n" }, { "answer_id": 175290, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?</p>\n" }, { "answer_id": 175756, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 6, "selected": true, "text": "<p>The following sets up the situation I had, using table variables.</p>\n\n<pre><code>DECLARE @Object_Table TABLE\n(\n Id INT NOT NULL PRIMARY KEY\n)\n\nDECLARE @Link_Table TABLE\n(\n ObjectId INT NOT NULL,\n DataId INT NOT NULL\n)\n\nDECLARE @Data_Table TABLE\n(\n Id INT NOT NULL Identity(1,1),\n Data VARCHAR(50) NOT NULL\n)\n\n-- create two objects '1' and '2'\nINSERT INTO @Object_Table (Id) VALUES (1)\nINSERT INTO @Object_Table (Id) VALUES (2)\n\n-- create some data\nINSERT INTO @Data_Table (Data) VALUES ('Data One')\nINSERT INTO @Data_Table (Data) VALUES ('Data Two')\n\n-- link all data to first object\nINSERT INTO @Link_Table (ObjectId, DataId)\nSELECT Objects.Id, Data.Id\nFROM @Object_Table AS Objects, @Data_Table AS Data\nWHERE Objects.Id = 1\n</code></pre>\n\n<p>Thanks to another <a href=\"https://stackoverflow.com/questions/175066/in-sql-server-is-it-possible-to-insert-into-two-tables-at-the-same-time#175136\">answer</a> that pointed me towards the OUTPUT clause I can demonstrate a solution:</p>\n\n<pre><code>-- now I want to copy the data from from object 1 to object 2 without looping\nINSERT INTO @Data_Table (Data)\nOUTPUT 2, INSERTED.Id INTO @Link_Table (ObjectId, DataId)\nSELECT Data.Data\nFROM @Data_Table AS Data INNER JOIN @Link_Table AS Link ON Data.Id = Link.DataId\n INNER JOIN @Object_Table AS Objects ON Link.ObjectId = Objects.Id \nWHERE Objects.Id = 1\n</code></pre>\n\n<p>It turns out however that it is not that simple in real life because of the following error</p>\n\n<blockquote>\n <p>the OUTPUT INTO clause cannot be on\n either side of a (primary key, foreign\n key) relationship</p>\n</blockquote>\n\n<p>I can still <code>OUTPUT INTO</code> a temp table and then finish with normal insert. So I can avoid my loop but I cannot avoid the temp table.</p>\n" }, { "answer_id": 5507458, "author": "Brion", "author_id": 686671, "author_profile": "https://Stackoverflow.com/users/686671", "pm_score": -1, "selected": false, "text": "<p>//if you want to insert the same as first table</p>\n\n<pre><code>$qry = \"INSERT INTO table (one, two, three) VALUES('$one','$two','$three')\";\n\n$result = @mysql_query($qry);\n\n$qry2 = \"INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')\";\n\n$result = @mysql_query($qry2);\n</code></pre>\n\n<hr>\n\n<p>//or if you want to insert certain parts of table one</p>\n\n<pre><code> $qry = \"INSERT INTO table (one, two, three) VALUES('$one','$two','$three')\";\n\n\n $result = @mysql_query($qry);\n\n $qry2 = \"INSERT INTO table2 (two) VALUES('$two')\";\n\n $result = @mysql_query($qry2);\n</code></pre>\n\n<p>//i know it looks too good to be right, but it works and you can keep adding query's just change the </p>\n\n<pre><code> \"$qry\"-number and number in @mysql_query($qry\"\")\n</code></pre>\n\n<hr>\n\n<p>I have 17 tables this has worked in.</p>\n" }, { "answer_id": 30102560, "author": "FakirPori", "author_id": 4875185, "author_profile": "https://Stackoverflow.com/users/4875185", "pm_score": -1, "selected": false, "text": "<pre><code>-- ================================================\n-- Template generated from Template Explorer using:\n-- Create Procedure (New Menu).SQL\n--\n-- Use the Specify Values for Template Parameters \n-- command (Ctrl-Shift-M) to fill in the parameter \n-- values below.\n--\n-- This block of comments will not be included in\n-- the definition of the procedure.\n-- ================================================\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n\nALTER PROCEDURE InsetIntoTwoTable\n\n(\n@name nvarchar(50),\n@Email nvarchar(50)\n)\n\nAS\nBEGIN\n\n SET NOCOUNT ON;\n\n\n insert into dbo.info(name) values (@name)\n insert into dbo.login(Email) values (@Email)\nEND\nGO\n</code></pre>\n" }, { "answer_id": 40353032, "author": "Sergei Zinovyev", "author_id": 5145258, "author_profile": "https://Stackoverflow.com/users/5145258", "pm_score": 4, "selected": false, "text": "<p>I want to stress on using </p>\n\n<pre><code>SET XACT_ABORT ON;\n</code></pre>\n\n<p>for the MSSQL transaction with multiple sql statements.</p>\n\n<p>See: <a href=\"https://msdn.microsoft.com/en-us/library/ms188792.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/ms188792.aspx</a>\nThey provide a very good example.</p>\n\n<p>So, the final code should look like the following:</p>\n\n<pre><code>SET XACT_ABORT ON;\n\nBEGIN TRANSACTION\n DECLARE @DataID int;\n INSERT INTO DataTable (Column1 ...) VALUES (....);\n SELECT @DataID = scope_identity();\n INSERT INTO LinkTable VALUES (@ObjectID, @DataID);\nCOMMIT\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
My database contains three tables called `Object_Table`, `Data_Table` and `Link_Table`. The link table just contains two columns, the identity of an object record and an identity of a data record. I want to copy the data from `DATA_TABLE` where it is linked to one given object identity and insert corresponding records into `Data_Table` and `Link_Table` for a different given object identity. I **can** do this by selecting into a table variable and the looping through doing two inserts for each iteration. Is this the best way to do it? **Edit** : I want to avoid a loop for two reason, the first is that I'm lazy and a loop/temp table requires more code, more code means more places to make a mistake and the second reason is a concern about performance. I can copy all the data in one insert but how do get the link table to link to the new data records where each record has a new id?
The following sets up the situation I had, using table variables. ``` DECLARE @Object_Table TABLE ( Id INT NOT NULL PRIMARY KEY ) DECLARE @Link_Table TABLE ( ObjectId INT NOT NULL, DataId INT NOT NULL ) DECLARE @Data_Table TABLE ( Id INT NOT NULL Identity(1,1), Data VARCHAR(50) NOT NULL ) -- create two objects '1' and '2' INSERT INTO @Object_Table (Id) VALUES (1) INSERT INTO @Object_Table (Id) VALUES (2) -- create some data INSERT INTO @Data_Table (Data) VALUES ('Data One') INSERT INTO @Data_Table (Data) VALUES ('Data Two') -- link all data to first object INSERT INTO @Link_Table (ObjectId, DataId) SELECT Objects.Id, Data.Id FROM @Object_Table AS Objects, @Data_Table AS Data WHERE Objects.Id = 1 ``` Thanks to another [answer](https://stackoverflow.com/questions/175066/in-sql-server-is-it-possible-to-insert-into-two-tables-at-the-same-time#175136) that pointed me towards the OUTPUT clause I can demonstrate a solution: ``` -- now I want to copy the data from from object 1 to object 2 without looping INSERT INTO @Data_Table (Data) OUTPUT 2, INSERTED.Id INTO @Link_Table (ObjectId, DataId) SELECT Data.Data FROM @Data_Table AS Data INNER JOIN @Link_Table AS Link ON Data.Id = Link.DataId INNER JOIN @Object_Table AS Objects ON Link.ObjectId = Objects.Id WHERE Objects.Id = 1 ``` It turns out however that it is not that simple in real life because of the following error > > the OUTPUT INTO clause cannot be on > either side of a (primary key, foreign > key) relationship > > > I can still `OUTPUT INTO` a temp table and then finish with normal insert. So I can avoid my loop but I cannot avoid the temp table.
175,091
<p>I'm trying to host a PHP web site that was given to me. I see this warning:</p> <blockquote> <p><strong>Warning:</strong> Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in <strong>Unknown</strong> on line <strong>0</strong></p> </blockquote> <p>What does this mean? How might I track down the source of this problem within the code?</p>
[ { "answer_id": 175145, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 8, "selected": true, "text": "<p>basically you have a variable with the same name as your session. ex:</p>\n\n<pre><code>$_SESSION['var1'] = null;\n$var1 = 'something';\n</code></pre>\n\n<p>which will reproduce this error. you can stop PHP from trying to find existing variables and warning you about them by adding these lines to your script:</p>\n\n<pre><code>ini_set('session.bug_compat_warn', 0);\nini_set('session.bug_compat_42', 0);\n</code></pre>\n\n<p>these values can be set in php.ini or .htaccess as well</p>\n" }, { "answer_id": 2262847, "author": "Kzqai", "author_id": 69993, "author_profile": "https://Stackoverflow.com/users/69993", "pm_score": 3, "selected": false, "text": "<p>There seem to be a few problematic possibilities here:</p>\n\n<p><a href=\"http://www.spiration.co.uk/post/1231/Your-script-possibly-relies-on-a-session-side-effect\" rel=\"nofollow noreferrer\" title=\"spiration.co.uk\">http://www.spiration.co.uk/post/1231/Your-script-possibly-relies-on-a-session-side-effect</a></p>\n\n<p>says that cases like this:</p>\n\n<pre><code>$_SESSION['firstname']=$_REQUEST['firstname'];\n</code></pre>\n\n<p>will trigger the warning.</p>\n\n<p>Additionally, I interpret this php bug content: <a href=\"http://bugs.php.net/bug.php?id=41540\" rel=\"nofollow noreferrer\">http://bugs.php.net/bug.php?id=41540</a> to mean that this error may also occur when you assign a variable to the session superglobal that is not yet initialized, e.g.</p>\n\n<pre><code>//Start of script\n$_SESSION['bob'] = $bob;\n</code></pre>\n" }, { "answer_id": 10351371, "author": "Praveen Kannan", "author_id": 1361196, "author_profile": "https://Stackoverflow.com/users/1361196", "pm_score": 2, "selected": false, "text": "<p>When you are making changes to the .htaccess ini_set does not work. You will need to do it as:</p>\n\n<pre><code>php_flag session.bug_compat_42 0\nphp_flag session.bug_compat_warn 0\n</code></pre>\n" }, { "answer_id": 10645071, "author": "Ian", "author_id": 755908, "author_profile": "https://Stackoverflow.com/users/755908", "pm_score": 3, "selected": false, "text": "<p>This is good information on finding out what's causing the warning, but I would recommend NOT shutting off the warnings Owen mentions. These runtime functions are <a href=\"http://php.net/manual/en/session.configuration.php\" rel=\"noreferrer\">removed in PHP 5.4.0</a> and the developer should get into the practice of avoiding such usage of variables.</p>\n\n<p>To fix this, it may be a pain on the developers end, but if you have </p>\n\n<pre><code>$_SESSION[\"user\"]\n$user;\n</code></pre>\n\n<p>rename the session to</p>\n\n<pre><code>$_SESSION[\"sessuser\"];\n</code></pre>\n\n<p>Or vise-versa just as long as the session name and the variable name are different. Think of it this way: when you upgrade to the latest build, you'll have to debug your code anyhow.</p>\n" }, { "answer_id": 29036541, "author": "TARA", "author_id": 4370606, "author_profile": "https://Stackoverflow.com/users/4370606", "pm_score": 1, "selected": false, "text": "<p>in my case, php.ini change from on to off </p>\n\n<p>like this : </p>\n\n<pre><code>session.bug_compat_42 = off\nsession.bug_compat_warn = off\n</code></pre>\n\n<p>if not working, restart apache </p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'm trying to host a PHP web site that was given to me. I see this warning: > > **Warning:** Unknown: Your script possibly > relies on a session side-effect which > existed until PHP 4.2.3. Please be > advised that the session extension > does not consider global variables as > a source of data, unless > register\_globals is enabled. You can > disable this functionality and this > warning by setting > session.bug\_compat\_42 or > session.bug\_compat\_warn to off, > respectively. in **Unknown** on line **0** > > > What does this mean? How might I track down the source of this problem within the code?
basically you have a variable with the same name as your session. ex: ``` $_SESSION['var1'] = null; $var1 = 'something'; ``` which will reproduce this error. you can stop PHP from trying to find existing variables and warning you about them by adding these lines to your script: ``` ini_set('session.bug_compat_warn', 0); ini_set('session.bug_compat_42', 0); ``` these values can be set in php.ini or .htaccess as well
175,099
<p>Does anyone have a good algorithm for re-sorting an array of values (already pre-sorted) so that they can be displayed in multiple (N) columns and be read vertically? This would be implemented in .Net but I'd prefer something portable and not some magic function.</p> <p>A good example of it working is the ASP.Net CheckBoxList control rendering as a table with the direction set to vertical. </p> <p>Here's an example of the input and output:</p> <p>Input: </p> <p>Columns = 4<br> Array = {"A", "B", "C", "D", "E", "F", "G"}</p> <p>Output:</p> <p>ACEG<br> BDF</p> <p>Thanks!</p> <p><b>Updated (More Info):</b></p> <p>I think I might have to give a little more information on what I'm trying to do... Mostly this problem came about from going from using a CheckBoxList's automatic binding (where you can specify the columns and direction to output and it would output a table of items in the correct order) to using jQuery/AJAX to create the checkbox grid. So I'm trying to duplicate that layout using css with div blocks with specified widths (inside a container div of a known width) so they wrap after N items (or columns.) This could also be rendered in a table (like how ASP.Net does it.) </p> <p>Everything works great except the order is horizontal and when you get a large number of items in the list it's easier to read vertical columns.</p> <p>If the array doesn't have enough items in it to make an even grid then it should output an empty spot in the correct row/column of the grid.</p> <p>And if an array doesn't have enough items to make even a single row then just output the items in their original order in one row.</p> <p>Some other input/ouput might be:</p> <p>Columns = 3<br> Array = {"A", "B", "C", "D"}</p> <p>ACD<br> B</p> <p>Columns = 5<br> Array = {"A", "B", "C", "D", "E", "F", "G", "H"}</p> <p>ACEGH<br> BDF</p> <p>Columns = 5<br> Array = {"A", "B", "C", "D"}</p> <p>ABCD</p>
[ { "answer_id": 175516, "author": "Eric", "author_id": 6367, "author_profile": "https://Stackoverflow.com/users/6367", "pm_score": 1, "selected": false, "text": "<p>This looks like homework assignments\nanyway</p>\n\n<pre><code>array&lt;String^&gt;^ sArray = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"};\ndouble Columns = 4;\ndouble dRowCount = Convert::ToDouble(sArray-&gt;Length) / Columns;\nint rowCount = (int) Math::Ceiling(dRowCount);\nint i = 0;\nint shift = 0;\nint printed = 0;\nwhile (printed &lt; sArray-&gt;Length){\n while (i &lt; sArray-&gt;Length){\n if (i % rowCount == shift){\n Console::Write(sArray[i]);\n printed++;\n }\n i++;\n }\n Console::Write(\"\\n\");\n i = 0;\n shift++;\n}\n</code></pre>\n" }, { "answer_id": 175587, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<h3>A small UPDATE:</h3>\n<p>The algorithm I'm using here is a modified one you'd use for painting images. I'm pretending the array entries to be pixel data of an image and then I'm painting the image from left to right (1. LtoR) and from top to bottom (2. TtoB), however, the image data is stored from top to bottom (1. TtoB) and then from left to right (2. LtoR); IOW in a different order. Since an image can't have <em>holes</em>, this is the reason why it will not work with 5 or 6 columns. With 4 columns the output is</p>\n<pre><code>ACEG\nBDF\n</code></pre>\n<p>As an image this looks like this</p>\n<pre><code>OOOO\nOOO.\n</code></pre>\n<p>With O being a pixel of the image and . being an undefined pixel (a missing one). Missing ones may only be at the end of the image, not in the middle of it. That means it could also look like this</p>\n<pre><code>OOO\nOO.\nOO.\nOO.\n</code></pre>\n<p>All missing pixels are always at the end, if you read <strong>first</strong> from top to bottom and <strong>then</strong> from left to right, because in that case all missing pixels follow directly each other at the end. If I read the diagram TtoB and then LtoR, it must read like this &quot;Pixel, Pixel, Pixel, Pixel, ..., Pixel, Missing, Missing, Missing, ..., Missing&quot;, it might never read &quot;Pixel, Missing, Pixel&quot; or &quot;Missing, Pixel, Missing&quot;. All pixels are together and all missings are, too.</p>\n<p>With 5 columns, as the comment suggests, it should look like this</p>\n<pre><code>ACEFG\nBD\n</code></pre>\n<p>However, as image this would look like this</p>\n<pre><code>OOOOO\nOO...\n</code></pre>\n<p>And this is not allowed by the algorithm. If I read it TtoB and then LtoR, it will read: &quot;Pixel, Pixel, Pixel, Pixel, Pixel, Missing, Pixel, Missing, Pixel, Missing&quot;. And as stated above, this is not allowed by the algorithm. So this simple pixel painting approach will not paint as many columns as requested if painting that many columns leads to holes in the image. In that case it will simply fill up the holes, however, this will cause less columns to be drawn.</p>\n<p>Let me think of a solution that will always paint the requested numbers of pixels (in a separate reply).</p>\n<hr />\n<p>You don't have to re-arrange the data in memory for that at all. Just print it in the desired order.</p>\n<p>Some C Code (I'm doing it extremely verbose, so everyone understands what I'm doing so. Of course this can be much more compact):</p>\n<pre><code>int Columns = 4;\nchar * Array[] = {&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;};\n\nint main (\n int argc,\n char ** argv\n) {\n // This is hacky C for quickly get the number of entries\n // in a static array, where size is known at compile time\n int arraySize = sizeof(Array) / sizeof(Array[0]);\n\n // How many rows are we going to paint?\n int rowsToPaint = (arraySize / Columns) + 1;\n\n int col;\n int row;\n \n for (row = 0; row &lt; rowsToPaint; row++) {\n for (col = 0; col &lt; Columns; col++) {\n int index = col * rowsToPaint + row;\n \n if (index &gt;= arraySize) {\n // Out of bounds\n continue;\n }\n\n printf(&quot;%s&quot;, Array[index]);\n }\n printf(&quot;\\n&quot;); // next row\n }\n printf(&quot;\\n&quot;);\n return 0;\n}\n</code></pre>\n<p>Note: This works fine with a value of 8 (so everything is painted within one row) and values of 4 and below (works fine with 3, 2 and 1), but it can't work with 5. This is not the fault of the algorithm, it is the fault of the constrain.</p>\n<pre><code>ACEFG\nBD\n</code></pre>\n<p>The constraint says the columns are read top to bottom to get the corrected sorted data. But above &quot;<em>EFG</em>&quot; is sorted and it's not top to bottom, it is left to right. Thus this algorithm has a problem. Using Columns = 3 will work</p>\n<pre><code>ADG\nBE\nCF\n</code></pre>\n<p>Using two will work as well</p>\n<pre><code>AE\nBF\nCG\nD\n</code></pre>\n<p>And one will put everything into one column.</p>\n" }, { "answer_id": 177916, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 4, "selected": true, "text": "<p>Okay, I'm sorry for my initial statement, but when you want it to work as you described in the comment to my first answer, you need in fact re-sort the data... well somewhat. It could maybe be done without the helper matrix, however the resulting code is probably very complex and as long as the matrix will only use a couple of bytes of memory, why not using this little helper construct?</p>\n\n<p>What my code does below is creating a matrix. We write the matrix from top to bottom and then from left to right (and stop filling up anything but the first row when we run out of elements to fill up all columns of the first row). Then we read it in a different order, left to right and top to bottom. Basically what we do here is <a href=\"http://en.wikipedia.org/wiki/Transposed_matrix\" rel=\"noreferrer\">transposing a matrix</a>, by writing it in one order, but reading it in another order. Transposing a matrix is a very elementary mathematical operation (lots of 3D programming works by using matrix calculations and transposing is actually a simple operation). The trick is how we initially fill up the matrix. To make sure we can fill up the first column in any case, independently of number of desired columns and size of the array, we must stop filling the matrix in the normal order if we run out of elements and reserve all elements left over for the first row. This will produce the output you have suggested in your comment.</p>\n\n<p>The whole thing is bit complicated to be honest, but the theory behind it should be sane and it works lovely :-D</p>\n\n<pre><code>int Columns;\nchar * Array[] = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"};\n\nint main (\n int argc,\n char ** argv\n) {\n // Lets thest this with all Column sizes from 1 to 7\n for (Columns = 1; Columns &lt;= 7; Columns++) {\n\n printf(\"Output when Columns is set to %d\\n\", Columns);\n\n // This is hacky C for quickly get the number of entries\n // in a static array, where size is known at compile time\n int arraySize = sizeof(Array) / sizeof(Array[0]);\n\n // How many rows we will have\n int rows = arraySize / Columns;\n\n // Below code is the same as (arraySize % Columns != 0), but\n // it's almost always faster\n if (Columns * rows != arraySize) {\n // We might have lost one row by implicit rounding\n // performed for integer division\n rows++;\n }\n\n // Now we create a matrix large enough for rows * Columns\n // references. Note that this array could be larger than arraySize!\n char ** matrix = malloc(sizeof(char *) * rows * Columns);\n\n // Something you only need in C, C# and Java do this automatically:\n // Set all elements in the matrix to NULL(null) references\n memset(matrix, 0, sizeof(char *) * rows * Columns );\n\n // We fill up the matrix from top to bottom and then from\n // left to right; the order how we fill it up is very important\n int matrixX;\n int matrixY;\n int index = 0;\n for (matrixX = 0; matrixX &lt; Columns; matrixX++) {\n for (matrixY = 0; matrixY &lt; rows; matrixY++) {\n // In case we just have enough elements left to only\n // fill up the first row of the matrix and we are not\n // in this first row, do nothing.\n if (arraySize + matrixX + 1 - (index + Columns) == 0 &amp;&amp;\n matrixY != 0) {\n continue;\n }\n\n // We just copy the next element normally\n matrix[matrixY + matrixX * rows] = Array[index];\n index++;\n //arraySize--;\n }\n }\n\n // Print the matrix exactly like you'd expect a matrix to be\n // printed to screen, that is from left to right and top to bottom;\n // Note: That is not the order how we have written it,\n // watch the order of the for-loops!\n for (matrixY = 0; matrixY &lt; rows; matrixY++) {\n for (matrixX = 0; matrixX &lt; Columns; matrixX++) {\n // Skip over unset references\n if (matrix[matrixY + matrixX * rows] == NULL)\n continue;\n\n printf(\"%s\", matrix[matrixY + matrixX * rows]);\n }\n // Next row in output\n printf(\"\\n\");\n }\n printf(\"\\n\");\n\n // Free up unused memory\n free(matrix);\n } \n return 0;\n}\n</code></pre>\n\n<p>Output is</p>\n\n<pre><code>Output when Columns is set to 1\nA\nB\nC\nD\nE\nF\nG\n\nOutput when Columns is set to 2\nAE\nBF\nCG\nD\n\nOutput when Columns is set to 3\nADG\nBE\nCF\n\nOutput when Columns is set to 4\nACEG\nBDF\n\nOutput when Columns is set to 5\nACEFG\nBD\n\nOutput when Columns is set to 6\nACDEFG\nB\n\nOutput when Columns is set to 7\nABCDEFG\n</code></pre>\n\n<p>This C code should be easy to port to PHP, C#, Java, etc., there's no big magic involved, so it's pretty much universal, portable and cross-platform.</p>\n\n<hr>\n\n<p>One important thing I should add:</p>\n\n<p>This code will crash if you set Columns to zero (division by zero, I don't check for that), but what sense would 0 Columns make? And it will also crash if you have more columns than elements in the array, I don't check for this either. You can easily check for either right after you got the arraySize:</p>\n\n<pre><code>if (Columns &lt;= 0) {\n // Having no column make no sense, we need at least one!\n Columns = 1;\n} else if (Columns &gt; arraySize) {\n // We can't have more columns than elements in the array!\n Columns = arraySize;\n}\n</code></pre>\n\n<p>Further you should also check for the arraySize being 0, in which case you can jump out straight away of the function, as in that case there is absolutely nothing to do for the function :) Adding these checks should make the code rock solid.</p>\n\n<p>Having NULL Elements in the Array will work, BTW, in that case there are no holes in the resulting output. NULL elements are just skipped like not being present. E.g. lets use</p>\n\n<pre><code>char * Array[] = {\"A\", \"B\", \"C\", \"D\", \"E\", NULL, \"F\", \"G\", \"H\", \"I\"};\n</code></pre>\n\n<p>The output will be</p>\n\n<pre><code>ADFI\nBEG\nCH\n</code></pre>\n\n<p>for Columns == 4. If you <em>want holes</em>, you need to create a hole element.</p>\n\n<pre><code>char hole = 0;\nchar * Array[] = {\"A\", \"B\", &amp;hole, \"C\", \"D\", \"E\", &amp;hole, \"F\", \"G\", \"H\", \"I\"};\n</code></pre>\n\n<p>and modify the painting code a bit</p>\n\n<pre><code> for (matrixY = 0; matrixY &lt; rows; matrixY++) {\n for (matrixX = 0; matrixX &lt; Columns; matrixX++) {\n // Skip over unset references\n if (matrix[matrixY + matrixX * rows] == NULL)\n continue;\n\n if (matrix[matrixY + matrixX * rows] == &amp;hole) {\n printf(\" \");\n } else {\n printf(\"%s\", matrix[matrixY + matrixX * rows]);\n }\n }\n // Next row in output\n printf(\"\\n\");\n }\n printf(\"\\n\");\n</code></pre>\n\n<p>Output samples:</p>\n\n<pre><code>Output when Columns is set to 2\nA \nBF\n G\nCH\nDI\nE\n\nOutput when Columns is set to 3\nADG\nBEH\n I\nCF\n\nOutput when Columns is set to 4\nAC H\nBDFI\n EG\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25549/" ]
Does anyone have a good algorithm for re-sorting an array of values (already pre-sorted) so that they can be displayed in multiple (N) columns and be read vertically? This would be implemented in .Net but I'd prefer something portable and not some magic function. A good example of it working is the ASP.Net CheckBoxList control rendering as a table with the direction set to vertical. Here's an example of the input and output: Input: Columns = 4 Array = {"A", "B", "C", "D", "E", "F", "G"} Output: ACEG BDF Thanks! **Updated (More Info):** I think I might have to give a little more information on what I'm trying to do... Mostly this problem came about from going from using a CheckBoxList's automatic binding (where you can specify the columns and direction to output and it would output a table of items in the correct order) to using jQuery/AJAX to create the checkbox grid. So I'm trying to duplicate that layout using css with div blocks with specified widths (inside a container div of a known width) so they wrap after N items (or columns.) This could also be rendered in a table (like how ASP.Net does it.) Everything works great except the order is horizontal and when you get a large number of items in the list it's easier to read vertical columns. If the array doesn't have enough items in it to make an even grid then it should output an empty spot in the correct row/column of the grid. And if an array doesn't have enough items to make even a single row then just output the items in their original order in one row. Some other input/ouput might be: Columns = 3 Array = {"A", "B", "C", "D"} ACD B Columns = 5 Array = {"A", "B", "C", "D", "E", "F", "G", "H"} ACEGH BDF Columns = 5 Array = {"A", "B", "C", "D"} ABCD
Okay, I'm sorry for my initial statement, but when you want it to work as you described in the comment to my first answer, you need in fact re-sort the data... well somewhat. It could maybe be done without the helper matrix, however the resulting code is probably very complex and as long as the matrix will only use a couple of bytes of memory, why not using this little helper construct? What my code does below is creating a matrix. We write the matrix from top to bottom and then from left to right (and stop filling up anything but the first row when we run out of elements to fill up all columns of the first row). Then we read it in a different order, left to right and top to bottom. Basically what we do here is [transposing a matrix](http://en.wikipedia.org/wiki/Transposed_matrix), by writing it in one order, but reading it in another order. Transposing a matrix is a very elementary mathematical operation (lots of 3D programming works by using matrix calculations and transposing is actually a simple operation). The trick is how we initially fill up the matrix. To make sure we can fill up the first column in any case, independently of number of desired columns and size of the array, we must stop filling the matrix in the normal order if we run out of elements and reserve all elements left over for the first row. This will produce the output you have suggested in your comment. The whole thing is bit complicated to be honest, but the theory behind it should be sane and it works lovely :-D ``` int Columns; char * Array[] = {"A", "B", "C", "D", "E", "F", "G"}; int main ( int argc, char ** argv ) { // Lets thest this with all Column sizes from 1 to 7 for (Columns = 1; Columns <= 7; Columns++) { printf("Output when Columns is set to %d\n", Columns); // This is hacky C for quickly get the number of entries // in a static array, where size is known at compile time int arraySize = sizeof(Array) / sizeof(Array[0]); // How many rows we will have int rows = arraySize / Columns; // Below code is the same as (arraySize % Columns != 0), but // it's almost always faster if (Columns * rows != arraySize) { // We might have lost one row by implicit rounding // performed for integer division rows++; } // Now we create a matrix large enough for rows * Columns // references. Note that this array could be larger than arraySize! char ** matrix = malloc(sizeof(char *) * rows * Columns); // Something you only need in C, C# and Java do this automatically: // Set all elements in the matrix to NULL(null) references memset(matrix, 0, sizeof(char *) * rows * Columns ); // We fill up the matrix from top to bottom and then from // left to right; the order how we fill it up is very important int matrixX; int matrixY; int index = 0; for (matrixX = 0; matrixX < Columns; matrixX++) { for (matrixY = 0; matrixY < rows; matrixY++) { // In case we just have enough elements left to only // fill up the first row of the matrix and we are not // in this first row, do nothing. if (arraySize + matrixX + 1 - (index + Columns) == 0 && matrixY != 0) { continue; } // We just copy the next element normally matrix[matrixY + matrixX * rows] = Array[index]; index++; //arraySize--; } } // Print the matrix exactly like you'd expect a matrix to be // printed to screen, that is from left to right and top to bottom; // Note: That is not the order how we have written it, // watch the order of the for-loops! for (matrixY = 0; matrixY < rows; matrixY++) { for (matrixX = 0; matrixX < Columns; matrixX++) { // Skip over unset references if (matrix[matrixY + matrixX * rows] == NULL) continue; printf("%s", matrix[matrixY + matrixX * rows]); } // Next row in output printf("\n"); } printf("\n"); // Free up unused memory free(matrix); } return 0; } ``` Output is ``` Output when Columns is set to 1 A B C D E F G Output when Columns is set to 2 AE BF CG D Output when Columns is set to 3 ADG BE CF Output when Columns is set to 4 ACEG BDF Output when Columns is set to 5 ACEFG BD Output when Columns is set to 6 ACDEFG B Output when Columns is set to 7 ABCDEFG ``` This C code should be easy to port to PHP, C#, Java, etc., there's no big magic involved, so it's pretty much universal, portable and cross-platform. --- One important thing I should add: This code will crash if you set Columns to zero (division by zero, I don't check for that), but what sense would 0 Columns make? And it will also crash if you have more columns than elements in the array, I don't check for this either. You can easily check for either right after you got the arraySize: ``` if (Columns <= 0) { // Having no column make no sense, we need at least one! Columns = 1; } else if (Columns > arraySize) { // We can't have more columns than elements in the array! Columns = arraySize; } ``` Further you should also check for the arraySize being 0, in which case you can jump out straight away of the function, as in that case there is absolutely nothing to do for the function :) Adding these checks should make the code rock solid. Having NULL Elements in the Array will work, BTW, in that case there are no holes in the resulting output. NULL elements are just skipped like not being present. E.g. lets use ``` char * Array[] = {"A", "B", "C", "D", "E", NULL, "F", "G", "H", "I"}; ``` The output will be ``` ADFI BEG CH ``` for Columns == 4. If you *want holes*, you need to create a hole element. ``` char hole = 0; char * Array[] = {"A", "B", &hole, "C", "D", "E", &hole, "F", "G", "H", "I"}; ``` and modify the painting code a bit ``` for (matrixY = 0; matrixY < rows; matrixY++) { for (matrixX = 0; matrixX < Columns; matrixX++) { // Skip over unset references if (matrix[matrixY + matrixX * rows] == NULL) continue; if (matrix[matrixY + matrixX * rows] == &hole) { printf(" "); } else { printf("%s", matrix[matrixY + matrixX * rows]); } } // Next row in output printf("\n"); } printf("\n"); ``` Output samples: ``` Output when Columns is set to 2 A BF G CH DI E Output when Columns is set to 3 ADG BEH I CF Output when Columns is set to 4 AC H BDFI EG ```
175,103
<p>I have a <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="noreferrer">URL</a>, and I'm trying to match it to a regular expression to pull out some groups. The problem I'm having is that the URL can either end <em>or</em> continue with a "/" and more URL text. I'd like to match URLs like this:</p> <ul> <li><a href="http://server/xyz/2008-10-08-4" rel="noreferrer">http://server/xyz/2008-10-08-4</a></li> <li><a href="http://server/xyz/2008-10-08-4/" rel="noreferrer">http://server/xyz/2008-10-08-4/</a></li> <li><a href="http://server/xyz/2008-10-08-4/123/more" rel="noreferrer">http://server/xyz/2008-10-08-4/123/more</a></li> </ul> <p>But not match something like this:</p> <ul> <li><a href="http://server/xyz/2008-10-08-4-1" rel="noreferrer">http://server/xyz/2008-10-08-4-1</a></li> </ul> <p>So, I thought my best bet was something like this: </p> <pre><code>/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)[/$] </code></pre> <p>where the character class at the end contained either the "/" or the end-of-line. The character class doesn't seem to be happy with the "$" in there though. How can I best discriminate between these URLs while still pulling back the correct groups?</p>
[ { "answer_id": 175141, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 7, "selected": true, "text": "<pre class=\"lang-none prettyprint-override\"><code>/(.+)/(\\d{4}-\\d{2}-\\d{2})-(\\d+)(/.*)?$\n</code></pre>\n<p><strong>1st Capturing Group <code>(.+)</code></strong></p>\n<p><code>.+</code> matches any character (except for line terminators)</p>\n<ul>\n<li><code>+</code> <strong>Quantifier</strong> — Matches between <strong>one</strong> and <strong>unlimited</strong> times, as many times as possible, giving back as needed <em>(greedy)</em></li>\n</ul>\n<p><strong>2nd Capturing Group <code>(\\d{4}-\\d{2}-\\d{2})</code></strong></p>\n<p><code>\\d{4}</code> matches a digit (equal to <code>[0-9]</code>)</p>\n<ul>\n<li><code>{4}</code> <strong>Quantifier</strong> — Matches exactly <strong>4</strong> times</li>\n</ul>\n<p><code>-</code> matches the character <code>-</code> literally <em>(case sensitive)</em></p>\n<p><code>\\d{2}</code> matches a digit (equal to <code>[0-9]</code>)</p>\n<ul>\n<li><code>{2}</code> <strong>Quantifier</strong> — Matches exactly <strong>2</strong> times</li>\n</ul>\n<p><code>-</code> matches the character <code>-</code> literally <em>(case sensitive)</em></p>\n<p><code>\\d{2}</code> matches a digit (equal to <code>[0-9]</code>)</p>\n<ul>\n<li><code>{2}</code> <strong>Quantifier</strong> — Matches exactly <strong>2</strong> times</li>\n</ul>\n<p><strong><code>-</code> matches the character <code>-</code> literally <em>(case sensitive)</em></strong></p>\n<p><strong>3rd Capturing Group <code>(\\d+)</code></strong></p>\n<p><code>\\d+</code> matches a digit (equal to <code>[0-9]</code>)</p>\n<ul>\n<li><code>+</code> <strong>Quantifier</strong> — Matches between <strong>one</strong> and <strong>unlimited</strong> times, as many times as possible, giving back as needed <em>(greedy)</em></li>\n</ul>\n<p><strong>4th Capturing Group <code>(.*)?</code></strong></p>\n<p><code>?</code> <strong>Quantifier</strong> — Matches between <strong>zero</strong> and <strong>one</strong> times, as many times as possible, giving back as needed <em>(greedy)</em></p>\n<p><code>.*</code> matches any character <em>(except for line terminators)</em></p>\n<ul>\n<li><code>*</code> <strong>Quantifier</strong> — Matches between <strong>zero</strong> and <strong>unlimited</strong> times, as many times as possible, giving back as needed <em>(greedy)</em></li>\n</ul>\n<p><strong><code>$</code> asserts position at the end of the string</strong></p>\n" }, { "answer_id": 175220, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 7, "selected": false, "text": "<p>To match either / or end of content, use <code>(/|\\z)</code></p>\n\n<p>This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).</p>\n\n<p><br/>\nTo put that with an updated version of what you had:</p>\n\n<pre><code>/(\\S+?)/(\\d{4}-\\d{2}-\\d{2})-(\\d+)(/|\\z)\n</code></pre>\n\n<p>Note that I've changed the start to be a non-greedy match for non-whitespace ( <code>\\S+?</code> ) rather than matching anything and everything ( <code>.*</code> )</p>\n" }, { "answer_id": 176078, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 6, "selected": false, "text": "<p>You've got a couple regexes now which will do what you want, so that's adequately covered. </p>\n\n<p>What hasn't been mentioned is why your attempt won't work: Inside a character class, <code>$</code> (as well as <code>^</code>, <code>.</code>, and <code>/</code>) has no special meaning, so <code>[/$]</code> matches either a literal <code>/</code> or a literal <code>$</code> rather than terminating the regex (<code>/</code>) or matching end-of-line (<code>$</code>).</p>\n" }, { "answer_id": 18995360, "author": "Sparhawk", "author_id": 1944384, "author_profile": "https://Stackoverflow.com/users/1944384", "pm_score": 5, "selected": false, "text": "<p>In Ruby and Bash, you can use <code>$</code> inside parentheses.</p>\n\n<pre><code>/(\\S+?)/(\\d{4}-\\d{2}-\\d{2})-(\\d+)(/|$)\n</code></pre>\n\n<p>(This solution is similar to Pete Boughton's, but preserves the usage of <code>$</code>, which means end of line, rather than using <code>\\z</code>, which means end of string.)</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
I have a [URL](http://en.wikipedia.org/wiki/Uniform_resource_locator), and I'm trying to match it to a regular expression to pull out some groups. The problem I'm having is that the URL can either end *or* continue with a "/" and more URL text. I'd like to match URLs like this: * <http://server/xyz/2008-10-08-4> * <http://server/xyz/2008-10-08-4/> * <http://server/xyz/2008-10-08-4/123/more> But not match something like this: * <http://server/xyz/2008-10-08-4-1> So, I thought my best bet was something like this: ``` /(.+)/(\d{4}-\d{2}-\d{2})-(\d+)[/$] ``` where the character class at the end contained either the "/" or the end-of-line. The character class doesn't seem to be happy with the "$" in there though. How can I best discriminate between these URLs while still pulling back the correct groups?
```none /(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$ ``` **1st Capturing Group `(.+)`** `.+` matches any character (except for line terminators) * `+` **Quantifier** — Matches between **one** and **unlimited** times, as many times as possible, giving back as needed *(greedy)* **2nd Capturing Group `(\d{4}-\d{2}-\d{2})`** `\d{4}` matches a digit (equal to `[0-9]`) * `{4}` **Quantifier** — Matches exactly **4** times `-` matches the character `-` literally *(case sensitive)* `\d{2}` matches a digit (equal to `[0-9]`) * `{2}` **Quantifier** — Matches exactly **2** times `-` matches the character `-` literally *(case sensitive)* `\d{2}` matches a digit (equal to `[0-9]`) * `{2}` **Quantifier** — Matches exactly **2** times **`-` matches the character `-` literally *(case sensitive)*** **3rd Capturing Group `(\d+)`** `\d+` matches a digit (equal to `[0-9]`) * `+` **Quantifier** — Matches between **one** and **unlimited** times, as many times as possible, giving back as needed *(greedy)* **4th Capturing Group `(.*)?`** `?` **Quantifier** — Matches between **zero** and **one** times, as many times as possible, giving back as needed *(greedy)* `.*` matches any character *(except for line terminators)* * `*` **Quantifier** — Matches between **zero** and **unlimited** times, as many times as possible, giving back as needed *(greedy)* **`$` asserts position at the end of the string**
175,109
<p>I'm doing some research into using log4net, and I found the <em>IObjectRenderer</em> interface interesting. It would allow us to control how types are logged and provide a different, possibly more user-friendly <code>ToString()</code> implementation. I just started looking at log4net though, and can't seem to find a logical way to programmatically set up the association between types and renderers.</p> <p>I found that this can be set up in the XML configuration file by reading the <a href="http://logging.apache.org/log4net/release/manual/configuration.html#HC-13011608" rel="nofollow noreferrer">manual</a>, but it didn't give me any hints about programmatically adding these. It seems to me that you'd rather have a programmatic object renderer in some cases, so I'm curious how to do this.</p>
[ { "answer_id": 175111, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 4, "selected": true, "text": "<p>I poked around with it some while writing the question and came up with this:</p>\n\n<pre><code>using System.IO;\nusing log4net;\nusing log4net.Config;\nusing log4net.ObjectRenderer;\nusing log4net.Util;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n BasicConfigurator.Configure();\n\n ILog log = LogManager.GetLogger(typeof(Program));\n var repo = LogManager.GetRepository();\n repo.RendererMap.Put(typeof(Foo), new FooRenderer());\n\n var fooInstance = new Foo() { Name = \"Test Foo\" };\n log.Info(fooInstance);\n }\n }\n\n internal class Foo\n {\n public string Name { get; set; }\n }\n\n internal class FooRenderer : log4net.ObjectRenderer.IObjectRenderer\n {\n public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)\n {\n if (obj == null)\n {\n writer.Write(SystemInfo.NullText);\n }\n\n var fooInstance = obj as Foo;\n if (fooInstance != null)\n {\n writer.Write(\"\", fooInstance.Name);\n }\n else\n {\n writer.Write(SystemInfo.NullText);\n }\n }\n }\n}</code></pre>\n\n<p>I am not certain if this is the correct way to do this, but I do know that it worked.</p>\n" }, { "answer_id": 11676271, "author": "Axle", "author_id": 1385801, "author_profile": "https://Stackoverflow.com/users/1385801", "pm_score": 2, "selected": false, "text": "<p>You can also add this line to the root of your log4net if you don't want to register your renderer programatically </p>\n\n<pre><code>&lt;renderer renderingClass=\"ConsoleApplication1.FooRenderer\" renderedClass=\"ConsoleApplication1.Foo\" /&gt;\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
I'm doing some research into using log4net, and I found the *IObjectRenderer* interface interesting. It would allow us to control how types are logged and provide a different, possibly more user-friendly `ToString()` implementation. I just started looking at log4net though, and can't seem to find a logical way to programmatically set up the association between types and renderers. I found that this can be set up in the XML configuration file by reading the [manual](http://logging.apache.org/log4net/release/manual/configuration.html#HC-13011608), but it didn't give me any hints about programmatically adding these. It seems to me that you'd rather have a programmatic object renderer in some cases, so I'm curious how to do this.
I poked around with it some while writing the question and came up with this: ``` using System.IO; using log4net; using log4net.Config; using log4net.ObjectRenderer; using log4net.Util; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { BasicConfigurator.Configure(); ILog log = LogManager.GetLogger(typeof(Program)); var repo = LogManager.GetRepository(); repo.RendererMap.Put(typeof(Foo), new FooRenderer()); var fooInstance = new Foo() { Name = "Test Foo" }; log.Info(fooInstance); } } internal class Foo { public string Name { get; set; } } internal class FooRenderer : log4net.ObjectRenderer.IObjectRenderer { public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) { if (obj == null) { writer.Write(SystemInfo.NullText); } var fooInstance = obj as Foo; if (fooInstance != null) { writer.Write("", fooInstance.Name); } else { writer.Write(SystemInfo.NullText); } } } } ``` I am not certain if this is the correct way to do this, but I do know that it worked.
175,115
<p>[edit] So I used one of the javascript tooltips suggested below. I got the tips to show when you stop and hide if you move. The only problem is it works when I do this:</p> <pre><code>document.onmousemove = (function() { var onmousestop = function() { Tip('Click to search here'); document.getElementById('MyDiv').onmousemove = function() { UnTip(); }; }, thread; return function() { clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); </code></pre> <p>But I want the function to only apply to a specific div and if I change the first line to "document.getElementById('MyDiv').onmousemove = (function() {" I get a javascript error document.getElementById('MyDiv') is null What am I missing....??</p> <p>[/edit]</p> <p>I want to display a balloon style message when the users mouse stops on an element from more than say 1.5 seconds. And then if they move the mouse I would like to hide the balloon. I am trying to use some JavaScript code I found posted out in the wild. Here is the code I am using to detect when the mouse has stopped:</p> <pre><code>document.onmousemove = (function() { var onmousestop = function() { //code to show the ballon }; }, thread; return function() { clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); </code></pre> <p>So I have two questions. One, does anyone have a recommended lightweight javascript balloon that will display at the cursor location. And two, the detect mouse stopped code works ok but I am stumped on how to detect that the mouse has started moving again and hide the balloon. Thanks...</p>
[ { "answer_id": 175139, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 2, "selected": false, "text": "<p>Here's a nifty jQuery plugin for a nice float over tool tip.</p>\n\n<p><a href=\"http://jqueryfordesigners.com/demo/coda-bubble.html\" rel=\"nofollow noreferrer\">http://jqueryfordesigners.com/demo/coda-bubble.html</a></p>\n\n<p>[edit]\nI guess without seeing the companion HTML it's hard to say what's wrong. I'd double check that the element has the appropriate ID specified in the tag. Apart from that, unless this is an academic exercise, I would suggest using something like the jQuery plugin that I referenced above. There are certainly many other pre-built tools like that which will have already dealt with all of the minutiae you're currently addressing.</p>\n" }, { "answer_id": 175188, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "<pre><code>document.onmousemove = (function() {\n if($('balloon').visible) {\n //mouse is moving again\n}....//your code follows\n</code></pre>\n\n<p>Using Prototype.js syntax you can determine that the mouse has moved once the balloon is visible.</p>\n" }, { "answer_id": 177534, "author": "NickV", "author_id": 8322, "author_profile": "https://Stackoverflow.com/users/8322", "pm_score": 2, "selected": false, "text": "<p>The jQuery plugin <a href=\"http://cherne.net/brian/resources/jquery.hoverIntent.html\" rel=\"nofollow noreferrer\">hoverIntent</a> provides a similar behaviour. It determines if the user 'meant' to hover over a particular element by checking if they slow the mouse down moving into the elements and spend a certain amount of time hovering over the element.</p>\n\n<p>It only fires the \"out\" event when the user leaves the element, which doesn't sound like exactly what you're looking for, but the code is pretty simple.</p>\n\n<p>Also watch out for binding things to mousemove when you don't need to be collecting the events, mousemove fires a lot of events quickly and can have serious effects on your site performance. hoverIntent only binds mousemove when the cursor enters the active element, and unbinds it afterwards.</p>\n\n<p>If you do try hoverIntent I have had some trouble with the minified version not firing \"out\" events, so I would recommend using the full, unminified source.</p>\n" }, { "answer_id": 2381581, "author": "Chauncey McAskill", "author_id": 140357, "author_profile": "https://Stackoverflow.com/users/140357", "pm_score": 4, "selected": true, "text": "<p>A bit late to be answering this, but this will be helpful for those in need.</p>\n\n<p>I needed this function to be able to detect when the mouse stopped moving for a certain time to hide an HTML/JS player controller when hovering over a video. This is the revised code for the tooltip:</p>\n\n<pre><code>document.getElementById('MyDiv').onmousemove = (function() {\n var onmousestop = function() {\n Tip('Click to search here');\n }, thread;\n\n return function() {\n UnTip();\n clearTimeout(thread);\n thread = setTimeout(onmousestop, 1500);\n };\n})();\n</code></pre>\n\n<p>In my case, I used a bit of jQuery for selecting the elements for my player controller:</p>\n\n<pre><code>$('div.video')[0].onmousemove = (function() {\n var onmousestop = function() {\n $('div.controls').fadeOut('fast');\n }, thread;\n\n return function() {\n $('div.controls').fadeIn('fast');\n clearTimeout(thread);\n thread = setTimeout(onmousestop, 1500);\n };\n})();\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
[edit] So I used one of the javascript tooltips suggested below. I got the tips to show when you stop and hide if you move. The only problem is it works when I do this: ``` document.onmousemove = (function() { var onmousestop = function() { Tip('Click to search here'); document.getElementById('MyDiv').onmousemove = function() { UnTip(); }; }, thread; return function() { clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); ``` But I want the function to only apply to a specific div and if I change the first line to "document.getElementById('MyDiv').onmousemove = (function() {" I get a javascript error document.getElementById('MyDiv') is null What am I missing....?? [/edit] I want to display a balloon style message when the users mouse stops on an element from more than say 1.5 seconds. And then if they move the mouse I would like to hide the balloon. I am trying to use some JavaScript code I found posted out in the wild. Here is the code I am using to detect when the mouse has stopped: ``` document.onmousemove = (function() { var onmousestop = function() { //code to show the ballon }; }, thread; return function() { clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); ``` So I have two questions. One, does anyone have a recommended lightweight javascript balloon that will display at the cursor location. And two, the detect mouse stopped code works ok but I am stumped on how to detect that the mouse has started moving again and hide the balloon. Thanks...
A bit late to be answering this, but this will be helpful for those in need. I needed this function to be able to detect when the mouse stopped moving for a certain time to hide an HTML/JS player controller when hovering over a video. This is the revised code for the tooltip: ``` document.getElementById('MyDiv').onmousemove = (function() { var onmousestop = function() { Tip('Click to search here'); }, thread; return function() { UnTip(); clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); ``` In my case, I used a bit of jQuery for selecting the elements for my player controller: ``` $('div.video')[0].onmousemove = (function() { var onmousestop = function() { $('div.controls').fadeOut('fast'); }, thread; return function() { $('div.controls').fadeIn('fast'); clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); ```
175,170
<p>What function can I use in Excel VBA to slice an array?</p>
[ { "answer_id": 175178, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 7, "selected": true, "text": "<blockquote>\n <p><strong>Application.WorksheetFunction.Index(array, row, column)</strong></p>\n</blockquote>\n\n<p>If you specify a zero value for row or column, then you'll get the entire column or row that is specified.</p>\n\n<p>Example:</p>\n\n<blockquote>\n <p>Application.WorksheetFunction.Index(array, 0, 3)</p>\n</blockquote>\n\n<p>This will give you the entire 3rd column.</p>\n\n<p>If you specify both row and column as non-zero, then you'll get only the specific element.\nThere is no easy way to get a smaller slice than a complete row or column.</p>\n\n<p><strong>Limitation</strong>: There is a limit to the array size that <code>WorksheetFunction.Index</code> can handle if you're using a newer version of Excel. If <code>array</code> has more than 65,536 rows or 65,536 columns, then it throws a \"Type mismatch\" error. If this is an issue for you, then see <a href=\"https://stackoverflow.com/a/24843721/119775\">this more complicated answer</a> which is not subject to the same limitation.</p>\n\n<p>Here's the function I wrote to do all my 1D and 2D slicing:</p>\n\n<pre><code>Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant\n\n' this function returns a slice of an array, Stype is either row or column\n' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire\n' row or column is taken), Sindex is the row or column to be sliced\n' (NOTE: 1 is always the first row or first column)\n' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljr\n\nDim vtemp() As Variant\nDim i As Integer\n\nOn Err GoTo ErrHandler\n\nSelect Case Sindex\n Case 0\n If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then\n vtemp = Sarray\n Else\n ReDim vtemp(1 To Sfinish - Sstart + 1)\n For i = 1 To Sfinish - Sstart + 1\n vtemp(i) = Sarray(i + Sstart - 1)\n Next i\n End If\n Case Else\n Select Case Stype\n Case \"row\"\n If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then\n vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0)\n Else\n ReDim vtemp(1 To Sfinish - Sstart + 1)\n For i = 1 To Sfinish - Sstart + 1\n vtemp(i) = Sarray(Sindex, i + Sstart - 1)\n Next i\n End If\n Case \"column\"\n If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then\n vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex)\n Else\n ReDim vtemp(1 To Sfinish - Sstart + 1)\n For i = 1 To Sfinish - Sstart + 1\n vtemp(i) = Sarray(i + Sstart - 1, Sindex)\n Next i\n End If\n End Select\nEnd Select\nGetArraySlice2D = vtemp\nExit Function\n\nErrHandler:\n Dim M As Integer\n M = MsgBox(\"Bad Array Input\", vbOKOnly, \"GetArraySlice2D\")\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 175291, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<p>You can use a combination of the Rows, Columns, Offset and Resize properties to get a subset of a range.</p>\n\n<p>For example if you have a range that is 5 columns by 3 rows:</p>\n\n<pre><code>Set rng = Range(\"A1:E3\")\n</code></pre>\n\n<p>You can get any subset by appropriately combining the above properties. For example, if you want to get the rightmost 3 cells on the second row (i.e. \"C2:E2\" in the above example), you could do something like:</p>\n\n<pre><code> Set rngSubset = rng.Rows(2).Offset(0, rng.Columns.Count - 3).Resize(1, 3)\n</code></pre>\n\n<p>You could then wrap this up in a VBA function.</p>\n" }, { "answer_id": 937942, "author": "Oorang", "author_id": 102270, "author_profile": "https://Stackoverflow.com/users/102270", "pm_score": 3, "selected": false, "text": "<p>Two things, VBA doesn't support array slicing so whatever you use, you'll have to roll your own. But since this is just for Excel, you can use the build in worksheet function index for array slicing.</p>\n\n<pre><code>Sub Test()\n 'All example return a 1 based 2D array.\n Dim myArr As Variant 'This var must be generic to work.\n 'Get whole range:\n myArr = ActiveSheet.UsedRange\n 'Get just column 1:\n myArr = WorksheetFunction.Index(ActiveSheet.UsedRange, 0, 1)\n 'Get just row 5\n myArr = WorksheetFunction.Index(ActiveSheet.UsedRange, 5, 0)\nEnd Sub\n</code></pre>\n" }, { "answer_id": 7504904, "author": "BitCoinBetter", "author_id": 805317, "author_profile": "https://Stackoverflow.com/users/805317", "pm_score": 2, "selected": false, "text": "<p>Lance's solution has a bug in that it does not respect an offset start value with a sub-arry of unspecified length, I also found how it works quite confusing. I offer a (hopefully) more transparent solution below.</p>\n\n<pre><code>Public Function GetSubTable(vIn As Variant, Optional ByVal iStartRow As Integer, Optional ByVal iStartCol As Integer, Optional ByVal iHeight As Integer, Optional ByVal iWidth As Integer) As Variant\n Dim vReturn As Variant\n Dim iInRowLower As Integer\n Dim iInRowUpper As Integer\n Dim iInColLower As Integer\n Dim iInColUpper As Integer\n Dim iEndRow As Integer\n Dim iEndCol As Integer\n Dim iRow As Integer\n Dim iCol As Integer\n\n iInRowLower = LBound(vIn, 1)\n iInRowUpper = UBound(vIn, 1)\n iInColLower = LBound(vIn, 2)\n iInColUpper = UBound(vIn, 2)\n\n If iStartRow = 0 Then\n iStartRow = iInRowLower\n End If\n If iStartCol = 0 Then\n iStartCol = iInColLower\n End If\n\n If iHeight = 0 Then\n iHeight = iInRowUpper - iStartRow + 1\n End If\n If iWidth = 0 Then\n iWidth = iInColUpper - iStartCol + 1\n End If\n\n iEndRow = iStartRow + iHeight - 1\n iEndCol = iStartCol + iWidth - 1\n\n ReDim vReturn(1 To iEndRow - iStartRow + 1, 1 To iEndCol - iStartCol + 1)\n\n For iRow = iStartRow To iEndRow\n For iCol = iStartCol To iEndCol\n vReturn(iRow - iStartRow + 1, iCol - iStartCol + 1) = vIn(iRow, iCol)\n Next\n Next\n\n GetSubTable = vReturn\nEnd Function\n</code></pre>\n" }, { "answer_id": 24843721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Below is a fast method to slice Excel variant arrays. Most of this was put together using the info from this excellent site <a href=\"http://bytecomb.com/vba-reference/\">http://bytecomb.com/vba-reference/</a></p>\n\n<p>Essentially the destination array is pre-built as an empty 1d or 2d variant and passed to the sub with the source array and element index to be sliced. Due to the way arrays are stored in memory it's much faster to slice a column than a row as the memory layout allows a single block to be copied.</p>\n\n<p>The good thing about this is it scales well beyond the Excel row limit.</p>\n\n<p><img src=\"https://i.stack.imgur.com/S4EnX.png\" alt=\"enter image description here\"></p>\n\n<pre><code>Option Explicit\n\n#If Win64 Then\n Public Const PTR_LENGTH As Long = 8\n Public Declare PtrSafe Function GetTickCount Lib \"kernel32\" () As Long\n Public Declare PtrSafe Sub Mem_Copy Lib \"kernel32\" Alias \"RtlMoveMemory\" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)\n Private Declare PtrSafe Function VarPtrArray Lib \"VBE7\" Alias \"VarPtr\" (ByRef Var() As Any) As LongPtr\n Private Declare PtrSafe Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" (Destination As Any, Source As Any, ByVal Length As Long)\n Private Declare PtrSafe Sub FillMemory Lib \"kernel32\" Alias \"RtlFillMemory\" (Destination As Any, ByVal Length As Long, ByVal Fill As Byte)\n#Else\n Public Const PTR_LENGTH As Long = 4\n Public Declare Function GetTickCount Lib \"kernel32\" () As Long\n Public Declare Sub Mem_Copy Lib \"kernel32\" Alias \"RtlMoveMemory\" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)\n Private Declare Function VarPtrArray Lib \"VBE7\" Alias \"VarPtr\" (ByRef Var() As Any) As LongPtr\n Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" (Destination As Any, Source As Any, ByVal Length As Long)\n Private Declare Sub FillMemory Lib \"kernel32\" Alias \"RtlFillMemory\" (Destination As Any, ByVal Length As Long, ByVal Fill As Byte)\n#End If\n\nPrivate Type SAFEARRAYBOUND\n cElements As Long\n lLbound As Long\nEnd Type\n\nPrivate Type SAFEARRAY_VECTOR\n cDims As Integer\n fFeatures As Integer\n cbElements As Long\n cLocks As Long\n pvData As LongPtr\n rgsabound(0) As SAFEARRAYBOUND\nEnd Type\n\nSub SliceColumn(ByVal idx As Long, ByRef arrayToSlice() As Variant, ByRef slicedArray As Variant)\n'slicedArray can be passed as a 1d or 2d array\n'sliceArray can also be part bound, eg slicedArray(1 to 100) or slicedArray(10 to 100)\nDim ptrToArrayVar As LongPtr\nDim ptrToSafeArray As LongPtr\nDim ptrToArrayData As LongPtr\nDim ptrToArrayData2 As LongPtr\nDim uSAFEARRAY As SAFEARRAY_VECTOR\nDim ptrCursor As LongPtr\nDim cbElements As Long\nDim atsBound1 As Long\nDim elSize As Long\n\n 'determine bound1 of source array (ie row Count)\n atsBound1 = UBound(arrayToSlice, 1)\n 'get pointer to source array Safearray\n ptrToArrayVar = VarPtrArray(arrayToSlice)\n CopyMemory ptrToSafeArray, ByVal ptrToArrayVar, PTR_LENGTH\n CopyMemory uSAFEARRAY, ByVal ptrToSafeArray, LenB(uSAFEARRAY)\n ptrToArrayData = uSAFEARRAY.pvData\n 'determine byte size of source elements\n cbElements = uSAFEARRAY.cbElements\n\n 'get pointer to destination array Safearray\n ptrToArrayVar = VarPtr(slicedArray) + 8 'Variant reserves first 8bytes\n CopyMemory ptrToSafeArray, ByVal ptrToArrayVar, PTR_LENGTH\n CopyMemory uSAFEARRAY, ByVal ptrToSafeArray, LenB(uSAFEARRAY)\n ptrToArrayData2 = uSAFEARRAY.pvData\n\n 'determine elements size\n elSize = UBound(slicedArray, 1) - LBound(slicedArray, 1) + 1\n 'determine start position of data in source array\n ptrCursor = ptrToArrayData + (((idx - 1) * atsBound1 + LBound(slicedArray, 1) - 1) * cbElements)\n 'Copy source array to destination array\n CopyMemory ByVal ptrToArrayData2, ByVal ptrCursor, cbElements * elSize\n\nEnd Sub\n\nSub SliceRow(ByVal idx As Long, ByRef arrayToSlice() As Variant, ByRef slicedArray As Variant)\n'slicedArray can be passed as a 1d or 2d array\n'sliceArray can also be part bound, eg slicedArray(1 to 100) or slicedArray(10 to 100)\nDim ptrToArrayVar As LongPtr\nDim ptrToSafeArray As LongPtr\nDim ptrToArrayData As LongPtr\nDim ptrToArrayData2 As LongPtr\nDim uSAFEARRAY As SAFEARRAY_VECTOR\nDim ptrCursor As LongPtr\nDim cbElements As Long\nDim atsBound1 As Long\nDim i As Long\n\n 'determine bound1 of source array (ie row Count)\n atsBound1 = UBound(arrayToSlice, 1)\n 'get pointer to source array Safearray\n ptrToArrayVar = VarPtrArray(arrayToSlice)\n CopyMemory ptrToSafeArray, ByVal ptrToArrayVar, PTR_LENGTH\n CopyMemory uSAFEARRAY, ByVal ptrToSafeArray, LenB(uSAFEARRAY)\n ptrToArrayData = uSAFEARRAY.pvData\n 'determine byte size of source elements\n cbElements = uSAFEARRAY.cbElements\n\n 'get pointer to destination array Safearray\n ptrToArrayVar = VarPtr(slicedArray) + 8 'Variant reserves first 8bytes\n CopyMemory ptrToSafeArray, ByVal ptrToArrayVar, PTR_LENGTH\n CopyMemory uSAFEARRAY, ByVal ptrToSafeArray, LenB(uSAFEARRAY)\n ptrToArrayData2 = uSAFEARRAY.pvData\n\n ptrCursor = ptrToArrayData + ((idx - 1) * cbElements)\n For i = LBound(slicedArray, 1) To UBound(slicedArray, 1)\n\n CopyMemory ByVal ptrToArrayData2, ByVal ptrCursor, cbElements\n ptrCursor = ptrCursor + (cbElements * atsBound1)\n ptrToArrayData2 = ptrToArrayData2 + cbElements\n Next i\n\nEnd Sub\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>Sub exampleUsage()\nDim sourceArr() As Variant\nDim destArr As Variant\nDim sliceIndex As Long\n\n On Error GoTo Err:\n\n sourceArr = Sheet1.Range(\"A1:D10000\").Value2\n sliceIndex = 2 'Slice column 2 / slice row 2\n\n 'Build target array\n ReDim destArr(20 To 10000) '1D array from row 20 to 10000\n' ReDim destArr(1 To 10000) '1D array from row 1 to 10000\n' ReDim destArr(20 To 10000, 1 To 1) '2D array from row 20 to 10000\n' ReDim destArr(1 To 10000, 1 To 1) '2D array from row 1 to 10000\n\n 'Slice Column\n SliceColumn sliceIndex, sourceArr, destArr\n\n 'Slice Row\n ReDim destArr(1 To 4)\n SliceRow sliceIndex, sourceArr, destArr\n\nErr:\n 'Tidy Up See ' http://stackoverflow.com/questions/16323776/copy-an-array-reference-in-vba/16343887#16343887\n FillMemory destArr, 16, 0\n\nEnd Sub\n</code></pre>\n\n<p>Timings were on an old dual core CPU using the following test</p>\n\n<pre><code>Sub timeMethods()\nConst trials As Long = 10\nConst rowsToCopy As Long = 1048576\nDim rng As Range\nDim Arr() As Variant\nDim newArr As Variant\nDim newArr2 As Variant\nDim t As Long, t1 As Long, t2 As Long, t3 As Long\nDim i As Long\n\n On Error GoTo Err\n\n 'Setup Conditions 1time only\n Sheet1.Cells.Clear\n Sheet1.Range(\"A1:D1\").Value = Split(\"A1,B1,C1,D1\", \",\") 'Strings\n' Sheet1.Range(\"A1:D1\").Value = Split(\"1,1,1,1\", \",\") 'Longs\n Sheet1.Range(\"A1:D1\").AutoFill Destination:=Sheet1.Range(\"A1:D\" &amp; rowsToCopy), Type:=xlFillDefault\n\n 'Build source data\n Arr = Sheet1.Range(\"A1:D\" &amp; rowsToCopy).Value\n Set rng = Sheet1.Range(\"A1:D\" &amp; rowsToCopy)\n\n 'Build target container\n ReDim newArr(1 To rowsToCopy)\n Debug.Print \"Trials=\" &amp; trials &amp; \" Rows=\" &amp; rowsToCopy\n 'Range\n t3 = 0\n For t = 1 To trials\n t1 = GetTickCount\n\n For i = LBound(newArr, 1) To UBound(newArr, 1)\n newArr(i) = rng(i, 2).Value2\n Next i\n\n t2 = GetTickCount\n t3 = t3 + (t2 - t1)\n Debug.Print \"Range: \" &amp; t2 - t1\n Next t\n Debug.Print \"Range Avg ms: \" &amp; t3 / trials\n\n 'Array\n t3 = 0\n For t = 1 To trials\n t1 = GetTickCount\n\n For i = LBound(newArr, 1) To UBound(newArr, 1)\n newArr(i) = Arr(i, 2)\n Next i\n\n t2 = GetTickCount\n t3 = t3 + (t2 - t1)\n Debug.Print \"Array: \" &amp; t2 - t1\n Next t\n Debug.Print \"Array Avg ms: \" &amp; t3 / trials\n\n 'Index\n t3 = 0\n For t = 1 To trials\n t1 = GetTickCount\n\n newArr2 = WorksheetFunction.Index(rng, 0, 2) 'newArr2 2d\n\n t2 = GetTickCount\n t3 = t3 + (t2 - t1)\n Debug.Print \"Index: \" &amp; t2 - t1\n Next t\n Debug.Print \"Index Avg ms: \" &amp; t3 / trials\n\n 'CopyMemBlock\n t3 = 0\n For t = 1 To trials\n t1 = GetTickCount\n\n SliceColumn 2, Arr, newArr\n\n t2 = GetTickCount\n t3 = t3 + (t2 - t1)\n Debug.Print \"CopyMem: \" &amp; t2 - t1\n Next t\n Debug.Print \"CopyMem Avg ms: \" &amp; t3 / trials\n\nErr:\n 'Tidy Up\n FillMemory newArr, 16, 0\n\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 33946145, "author": "Vikas Gautam", "author_id": 4850220, "author_profile": "https://Stackoverflow.com/users/4850220", "pm_score": 2, "selected": false, "text": "<p>Here is one other way.</p>\n\n<p>This is not multidimensional but would work single row and single column.</p>\n\n<p>f and t parameters are Zero based.</p>\n\n<pre><code>Function slice(ByVal arr, ByVal f, ByVal t)\n slice = Application.Index(arr, Evaluate(\"Transpose(Row(\" &amp; f + 1 &amp; \":\" &amp; t + 1 &amp; \"))\"))\nEnd Function\n</code></pre>\n" }, { "answer_id": 34549942, "author": "Ben", "author_id": 2146894, "author_profile": "https://Stackoverflow.com/users/2146894", "pm_score": 2, "selected": false, "text": "<p>Here's a nifty function I wrote to subset a 2d array</p>\n\n<pre><code>Function Subset2D(arr As Variant, Optional rowStart As Long = 1, Optional rowStop As Long = -1, Optional colIndices As Variant) As Variant\n 'Subset a 2d array (arr)\n 'If rowStop = -1, all rows are returned\n 'colIndices can be provided as a variant array like Array(1,3)\n 'if colIndices is not provided, all columns are returned\n\n Dim newarr() As Variant, newRows As Long, newCols As Long, i As Long, k As Long, refCol As Long\n\n 'Set the correct rowStop\n If rowStop = -1 Then rowStop = UBound(arr, 1)\n\n 'Set the colIndices if they were not provided\n If IsMissing(colIndices) Then\n ReDim colIndices(1 To UBound(arr, 2))\n For k = 1 To UBound(arr, 2)\n colIndices(k) = k\n Next k\n End If\n\n 'Get the dimensions of newarr\n newRows = rowStop - rowStart + 1\n newCols = UBound(colIndices) + 1\n ReDim newarr(1 To newRows, 1 To newCols)\n\n 'Loop through each empty element of newarr and set its value\n For k = 1 To UBound(newarr, 2) 'Loop through each column\n refCol = colIndices(k - 1) 'Get the corresponding reference column\n For i = 1 To UBound(newarr, 1) 'Loop through each row\n newarr(i, k) = arr(i + rowStart - 1, refCol) 'Set the value\n Next i\n Next k\n\n Subset2D = newarr\nEnd Function\n</code></pre>\n" }, { "answer_id": 50069592, "author": "Paulo Buchsbaum", "author_id": 1062727, "author_profile": "https://Stackoverflow.com/users/1062727", "pm_score": 1, "selected": false, "text": "<p>There is no direct <code>slice</code> function for arrays, different from many other recent languages.</p>\n\n<p>However, there is a short code snippet very handy for this. \nBelow, a complete solution for 1D arrays:</p>\n\n<pre><code>'*************************************************************\n'* Fill(N1,N2)\n'* Create 1 dimension array with values from N1 to N2 step 1\n'*************************************************************\nFunction Fill(N1 As Long, N2 As Long) As Variant\n Dim Arr As Variant\n If N2 &lt; N1 Then\n Fill = False\n Exit Function\n End If\n Fill = WorksheetFunction.Transpose(Evaluate(\"Row(\" &amp; N1 &amp; \":\" &amp; N2 &amp; \")\"))\nEnd Function\n\n'**********************************************************************\n'* Slice(AArray, [N1,N2])\n'* Slice an array between indices N1 to N2\n'***********************************************************************\nFunction Slice(VArray As Variant, Optional N1 As Long = 1, Optional N2 As Long = 0) As Variant\n Dim Indices As Variant\n If N2 = 0 Then N2 = UBound(VArray)\n If N1 = LBound(VArray) And N2 = UBound(VArray) Then\n Slice = VArray\n Else\n Indices = Fill(N1, N2)\n Slice = WorksheetFunction.Index(VArray, 1, Indices)\n End If\nEnd Function\n</code></pre>\n\n<p>For testing</p>\n\n<pre><code>Var V As Variant\nV = Fill(100,109)\nPrintArr(Slice(V,3,5))\n\n'************************************************\n'* PrintArr(VArr)\n'* Print the array VARR\n'**************************************************\nFunction PrintArr(VArray As Variant)\n Dim S As String\n S = Join(VArray, \", \")\n MsgBox (S)\nEnd Function\n</code></pre>\n\n<p>The results </p>\n\n<pre><code>102, 103, 104 \n</code></pre>\n" }, { "answer_id": 66672108, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 2, "selected": false, "text": "<p>It's an old question, but if you want to retrieve 1 row of a range into a 1 dimension array, you can do so by using Index and Transpose.</p>\n<pre><code>Sub test()\n Dim ar1\n Dim a As Object: Set a = Application\n\n ar1 = a.Transpose(a.Transpose(a.Index(Range(&quot;A1:C3&quot;), 2, 0))) 'get 2d row\n Debug.Print Join(ar1, &quot;|&quot;)\nEnd Sub\n</code></pre>\n<p>Combine that with OFFSET and you can quickly read a whole range, row by row.</p>\n" }, { "answer_id": 73693895, "author": "jzinna", "author_id": 6889133, "author_profile": "https://Stackoverflow.com/users/6889133", "pm_score": 1, "selected": false, "text": "<p>I would just create an array as long as the slice you need. Then loop through it copying the values from the full array. The index for the full array will be the position where the slice should begin (1 in my example).\nSo, if your full array is (&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;) and you need &quot;b&quot; and &quot;c&quot;:</p>\n<pre><code>Dim slice(1) as Variant\n\nFor i = 0 To 1\n slice(i) = fullArray( i + 1)\nNext\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
What function can I use in Excel VBA to slice an array?
> > **Application.WorksheetFunction.Index(array, row, column)** > > > If you specify a zero value for row or column, then you'll get the entire column or row that is specified. Example: > > Application.WorksheetFunction.Index(array, 0, 3) > > > This will give you the entire 3rd column. If you specify both row and column as non-zero, then you'll get only the specific element. There is no easy way to get a smaller slice than a complete row or column. **Limitation**: There is a limit to the array size that `WorksheetFunction.Index` can handle if you're using a newer version of Excel. If `array` has more than 65,536 rows or 65,536 columns, then it throws a "Type mismatch" error. If this is an issue for you, then see [this more complicated answer](https://stackoverflow.com/a/24843721/119775) which is not subject to the same limitation. Here's the function I wrote to do all my 1D and 2D slicing: ``` Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant ' this function returns a slice of an array, Stype is either row or column ' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire ' row or column is taken), Sindex is the row or column to be sliced ' (NOTE: 1 is always the first row or first column) ' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljr Dim vtemp() As Variant Dim i As Integer On Err GoTo ErrHandler Select Case Sindex Case 0 If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then vtemp = Sarray Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(i + Sstart - 1) Next i End If Case Else Select Case Stype Case "row" If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0) Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(Sindex, i + Sstart - 1) Next i End If Case "column" If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex) Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(i + Sstart - 1, Sindex) Next i End If End Select End Select GetArraySlice2D = vtemp Exit Function ErrHandler: Dim M As Integer M = MsgBox("Bad Array Input", vbOKOnly, "GetArraySlice2D") End Function ```
175,186
<p>Let's say I have this type in my application:</p> <pre><code>public class A { public int id; public B b; public boolean equals(Object another) { return this.id == ((A)another).id; } public int hashCode() { return 31 * id; //nice prime number } } </code></pre> <p>and a <code>Set<code>&lt;A</code>></code> structure. Now, I have an object of type <code>A</code> and want to do the following:</p> <ul> <li>If my <code>A</code> is within the set, update its field <code>b</code> to match my object.</li> <li>Else, add it to the set.</li> </ul> <p>So checking if it is in there is easy enough (<code>contains</code>), and adding to the set is easy too. My question is this: how do I get a handle to update the object within? Interface <code>Set</code> doesn't have a <code>get</code> method, and the best I could think of was to remove the object in the set and add mine. another, even worse, alternative is to traverse the set with an iterator to try and locate the object.</p> <p>I'll gladly take better suggestions... This includes the efficient use of other data structures.</p> <p>Yuval =8-)</p> <p><strong>EDIT</strong>: Thank you all for answering... Unfortunately I can't 'accept' the best answers here, those that suggest using a <code>Map</code>, because changing the type of the collection radically for this purpose only would be a little extreme (this collection is already mapped through Hibernate...)</p>
[ { "answer_id": 175211, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 5, "selected": false, "text": "<p>Since a Set can only contain one instance of an object (as defined by its <code>equals</code> and <code>hashCode</code> methods), just remove it and then add it. If there was one already, that other one will be removed from the Set and replaced by the one you want.</p>\n<p>I have code that does something similar - I am caching objects so that everywhere a particular object appears in a bunch of different places on the GUI, it's always the same one. In that case, instead of using a Set I'm using a Map, and then I get an update, I retrieve it from the Map and update it in place rather than creating a new instance.</p>\n" }, { "answer_id": 175212, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "<p>You really want to use a <code>Map&lt;Integer,A&gt;</code>, not a <code>Set&lt;A&gt;</code>.</p>\n\n<p>Then map the ID (even though it's also stored in <code>A</code>!) to the object. So storing new is this:</p>\n\n<pre><code>A a = ...;\nMap&lt;Integer,A&gt; map = new HashMap&lt;Integer,A&gt;();\nmap.put( a.id, a );\n</code></pre>\n\n<p>Your complete update algorithm is:</p>\n\n<pre><code>public static void update( Map&lt;Integer,A&gt; map, A obj ) {\n A existing = map.get( obj.id );\n if ( existing == null )\n map.put( obj.id, obj );\n else\n existing.b = obj.b;\n}\n</code></pre>\n\n<p><strong>However, it might be even simpler.</strong> I'm assuming you have more fields than that in <code>A</code> that what you gave. <em>If this is not the case</em>, just using a <code>Map&lt;Integer,B&gt;</code> is in fact what you want, then it collapses to nothing:</p>\n\n<pre><code>Map&lt;Integer,B&gt; map = new HashMap&lt;Integer,B&gt;();\n// The insert-or-update is just this:\nmap.put( id, b );\n</code></pre>\n" }, { "answer_id": 175317, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 0, "selected": false, "text": "<p>It's a bit outside scope, but you forgot to re-implement hashCode(). When you override equals please override hashCode(), even in an example. </p>\n\n<p>For example; contains() will very probably go wrong when you have a HashSet implementation of Set as the HashSet uses the hashCode of Object to locate the bucket (a number which has nothing to do with business logic), and only equals() the elements within that bucket.</p>\n\n<pre><code>public class A {\n public int id;\n public B b;\n public int hashCode() {return id;} // simple and efficient enough for small Sets \n public boolean equals(Object another) { \n if (object == null || ! (object instanceOf A) ) {\n return false;\n }\n return this.id == ((A)another).id; \n }\n}\npublic class Logic {\n /**\n * Replace the element in data with the same id as element, or add element\n * to data when the id of element is not yet used by any A in data. \n */\n public void update(Set&lt;A&gt; data, A element) {\n data.remove(element); // Safe even if the element is not in the Set\n data.add(element); \n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong> Yuvalindicated correctly that Set.add does not overwrite an existing element, but only adds if the element is not yet in the collection (with \"is\" implemented by equals)</p>\n" }, { "answer_id": 175533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>What about Map<code>&lt;A,A</code>> I know it's redundant, but I believe it will get you the behavior you'd like. Really I'd love to see Set have a get(Object o) method on it.</p>\n" }, { "answer_id": 175648, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "<p>You might want to generate a decorator called ASet and use an internal Map as the backing data structure</p>\n\n<pre><code>class ASet {\n private Map&lt;Integer, A&gt; map;\n public ASet() {\n map = new HashMap&lt;Integer, A&gt;();\n }\n\n public A updateOrAdd(Integer id, int delta) {\n A a = map.get(a);\n if(a == null) {\n a = new A(id);\n map.put(id,a);\n }\n a.setX(a.getX() + delta);\n }\n}\n</code></pre>\n\n<p>You can also take a look at the Trove API. While that is better for performance and for accounting that you are working with primitive variables, it exposes this feature very nicely (e.g. map.adjustOrPutValue(key, initialValue, deltaValue).</p>\n" }, { "answer_id": 175686, "author": "18Rabbit", "author_id": 12662, "author_profile": "https://Stackoverflow.com/users/12662", "pm_score": 4, "selected": false, "text": "<p>I don't think you can make it any easier than using remove/add if you are using a Set.</p>\n<pre><code>set.remove(a);\nset.add(a);\n</code></pre>\n<p>If a matching A was found it will be removed and then you add the new one, you don't even need the <code>if (set.contains(A))</code> conditional.</p>\n<p>If you have an object with an ID and an updated field <strong>and</strong> you don't really care about any other aspects of that object, just throw it out and replace it.</p>\n<p>If you need to do anything else to the A that matches that ID then you'll have to iterate through the Set to find it or use a different Container (like the Map as Jason suggested).</p>\n" }, { "answer_id": 177139, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 3, "selected": false, "text": "<p>No one has mentioned this yet, but basing <code>hashCode</code> or <code>equals</code> on a mutable property is one of those really, really big things that you shouldn't do. Don't muck about with object identity after you leave the constructor - doing so greatly increases your chances of having really difficult-to-figure out bugs down the road. Even if you don't get hit with bugs, the accounting work to make sure that you <em>always</em> properly update any and all data structures that relies on <code>equals</code> and <code>hashCode</code> being consistent will far outweigh any perceived benefits of being able to just change the id of the object as you run.</p>\n<p>Instead, I strongly recommend that you pass id in via the constructor, and if you need to change it, create a new instance of A. This will force users of your object (including yourself) to properly interact with the collection classes (and many others) that rely on immutable behavior in <code>equals</code> and <code>hashCode</code>.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2819/" ]
Let's say I have this type in my application: ``` public class A { public int id; public B b; public boolean equals(Object another) { return this.id == ((A)another).id; } public int hashCode() { return 31 * id; //nice prime number } } ``` and a `Set`<A`>` structure. Now, I have an object of type `A` and want to do the following: * If my `A` is within the set, update its field `b` to match my object. * Else, add it to the set. So checking if it is in there is easy enough (`contains`), and adding to the set is easy too. My question is this: how do I get a handle to update the object within? Interface `Set` doesn't have a `get` method, and the best I could think of was to remove the object in the set and add mine. another, even worse, alternative is to traverse the set with an iterator to try and locate the object. I'll gladly take better suggestions... This includes the efficient use of other data structures. Yuval =8-) **EDIT**: Thank you all for answering... Unfortunately I can't 'accept' the best answers here, those that suggest using a `Map`, because changing the type of the collection radically for this purpose only would be a little extreme (this collection is already mapped through Hibernate...)
Since a Set can only contain one instance of an object (as defined by its `equals` and `hashCode` methods), just remove it and then add it. If there was one already, that other one will be removed from the Set and replaced by the one you want. I have code that does something similar - I am caching objects so that everywhere a particular object appears in a bunch of different places on the GUI, it's always the same one. In that case, instead of using a Set I'm using a Map, and then I get an update, I retrieve it from the Map and update it in place rather than creating a new instance.
175,205
<p>Consider the following code:</p> <pre><code>$("a").attr("disabled", "disabled"); </code></pre> <p>In IE and FF, this will make anchors unclickable, but in WebKit based browsers (Google Chrome and Safari) this does nothing. The nice thing about the disabled attribute is that it is easily removed and does not effect the href and onclick attributes.</p> <p>Do you have any suggestions on how to get the desired result. Answers must be:</p> <ul> <li>Easily be revertable, since I want to disable form input controls while I have an AJAX call running.</li> <li>Must work in IE, FF, and WebKit</li> </ul>
[ { "answer_id": 175221, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 4, "selected": true, "text": "<p>I assume that you have an onclick event handler bound to these anchor elements. Just have your event handler check the \"disabled\" attribute and cancel the event if it is set. Your event handler would look something like this:</p>\n\n<pre><code>$(\"a\").click(function(event){\n if (this.disabled) {\n event.preventDefault();\n } else {\n // make your AJAX call or whatever else you want\n }\n});\n</code></pre>\n\n<p>You can also set a stylesheet rule to change the cursor.</p>\n\n<pre><code>a[disabled=disabled] { cursor: wait; }\n</code></pre>\n\n<p>Edit - simplified the \"disabled\" check as suggested in comments.</p>\n" }, { "answer_id": 15128693, "author": "hernant", "author_id": 722778, "author_profile": "https://Stackoverflow.com/users/722778", "pm_score": 2, "selected": false, "text": "<p>I had to fix this behavior in a site with a lot of anchors that were being enabled/disabled with this attribute according to other conditions, etc. Maybe not ideal, but in a situation like that, if you prefer not to fix each anchor's code individually, this will do the trick for all the anchors:</p>\n\n<pre><code>$('a').each(function () {\n $(this).click(function (e) {\n if ($(this).attr('disabled')) {\n e.preventDefault();\n e.stopImmediatePropagation();\n }\n });\n var events = $._data ? $._data(this, 'events') : $(this).data('events');\n events.click.splice(0, 0, events.click.pop());\n});\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>a[disabled] {\n color: gray;\n text-decoration: none;\n}\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19704/" ]
Consider the following code: ``` $("a").attr("disabled", "disabled"); ``` In IE and FF, this will make anchors unclickable, but in WebKit based browsers (Google Chrome and Safari) this does nothing. The nice thing about the disabled attribute is that it is easily removed and does not effect the href and onclick attributes. Do you have any suggestions on how to get the desired result. Answers must be: * Easily be revertable, since I want to disable form input controls while I have an AJAX call running. * Must work in IE, FF, and WebKit
I assume that you have an onclick event handler bound to these anchor elements. Just have your event handler check the "disabled" attribute and cancel the event if it is set. Your event handler would look something like this: ``` $("a").click(function(event){ if (this.disabled) { event.preventDefault(); } else { // make your AJAX call or whatever else you want } }); ``` You can also set a stylesheet rule to change the cursor. ``` a[disabled=disabled] { cursor: wait; } ``` Edit - simplified the "disabled" check as suggested in comments.
175,228
<p>Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious?</p> <p>For example, imagine I have this class in C++:</p> <pre><code> public class SomeClass { private: bool mIsVisible; public: void draw(); void erase(); } </code></pre> <p>I could add functions to get/set "mIsVisible" like this:</p> <p><pre><code> bool getVisible() { return mIsVisible; };</p> <p>void setVisible(bool visible) { if (!mIsVisible &amp;&amp; visible) { draw(); } else if (mIsVisible &amp;&amp; !visible) { erase(); }</p> <pre><code>mIsVisible = visible; </code></pre> <p>} </pre></code></p> <p>However, it would be equally possible to use the following methods instead:</p> <pre><code> bool isVisible() { return mIsVisible; }; void show() { if (!mIsVisible) { mIsVisible = true; draw(); } } void hide() { if (mIsVisible) { mIsVisible = false; erase(); } } </code></pre> <p>In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?</p>
[ { "answer_id": 175233, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>In the example you gave, <code>show()</code> and <code>hide()</code> make a lot of sense, at least to me. </p>\n\n<p>On the other hand, if you had a property <code>skinPigment</code> and you decided to make functions called <code>tanMe()</code> and <code>makeAlbino()</code> that would be a really poor, non-obvious choice.</p>\n\n<p>It is subjective, you have to try to think the way your users (the people utilizing this class) think. Whichever way you decide, it should be obvious to them, and <strong>well-documented.</strong></p>\n" }, { "answer_id": 175239, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Implicitly, the 'show' and 'hide' functions you list are both setters</p>\n\n<p>For booleans, I'd think that a single tool like you've shown would be good. However, a .show and .hide function also look like commands, not functions that change the state of the object.</p>\n" }, { "answer_id": 175243, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 5, "selected": true, "text": "<p>Have a read of the article \"<a href=\"http://www.pragprog.com/articles/tell-dont-ask\" rel=\"noreferrer\">Tell, Don't Ask</a>\" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go.</p>\n\n<p>Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely:</p>\n\n<ol>\n<li>get current visibility value,</li>\n<li>make decision based on value,</li>\n<li>update object.</li>\n</ol>\n" }, { "answer_id": 175266, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>In general, I think setters/getters should only set the values of properties. In your example, you are also performing an action based on the value of the isVisible property. In this case, I would argue that using functions to perform the action and update the state is better than having a setter/getter that performs an action as a side-effect of updating the property.</p>\n" }, { "answer_id": 175267, "author": "Julien Grenier", "author_id": 23051, "author_profile": "https://Stackoverflow.com/users/23051", "pm_score": 1, "selected": false, "text": "<p>I prefer the show() and hide() methods because they explicitly tell what you are going. The setVisible(boolean) doesn't tell you if the method is going to show/draw right away. Plus show() and hide() are better-named method for an interface (IMHO).</p>\n" }, { "answer_id": 175280, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>If switching mIsVisible really turns visibility of the object on and off immediately, than use the show/hide scenario. If it will stay in the old state a little longer (e.g. until something else triggers a redraw) then the set/get scenario would be the way to go.</p>\n" }, { "answer_id": 175337, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>I would go with the isVisible()/show()/hide() set.</p>\n\n<p>setVisible() implies that all it does it change the internal variable. show() and hide() make the side effects clear.</p>\n\n<p>On the other hand, if all getVisible()/setVisible() did <em>was</em> to change the internal variable, then you've just changed remarkably little from having them as public fields. </p>\n" }, { "answer_id": 175393, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 2, "selected": false, "text": "<p>setters actually have very little to do with object orientation, which is the programming idiom applied in the example. getters are marginally better, but can be lived without in many cases.\nIf everything can be gotten and set, what's the point of having an object? Operations should be called on objects to accomplish things, changing the internal state is merely a side-effect of this.\nThe bad thing about a setter in the presence of polymorphism - one of OO's cornerstones - is that you force every derived class to have a setter. What if the object in question has got no need for an internal state called mIsVisible? Sure he can ignore the call and implement as empty, but then you are left with a meaningless operation. OTOH, operations like show and hide can be easily overridden with different implementations, without revealing anything about the internal state.</p>\n" }, { "answer_id": 175467, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In the case you actually have to write code like </p>\n\n<pre><code>if (shouldBeShowingAccordingToBusinessLogic()) w.show();\nelse w.hide();\n</code></pre>\n\n<p>all over the place, you might be better off with</p>\n\n<pre><code>w.showIfAndOnlyIf(shouldBeShowingAccordingToBusinessLogic())\n</code></pre>\n\n<p>Or, for truly bizarre cases, when your logic can't decide whether to dhow or not till the end of some code stretch, you can try</p>\n\n<pre><code>w.setPostponedVisibility(shouldBeShowingAccordingToBusinessLogic());\n...\nw.realizeVisibility();\n</code></pre>\n\n<p>(Didn't I say it's bizzare?)</p>\n" }, { "answer_id": 175469, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 0, "selected": false, "text": "<p>An additional motivation to go for the display/hide solution is that as a setter, </p>\n\n<p>the <code>setVisible</code> method has a 'side effect', in that it also displays or hides <code>SomeClass</code>. The display/hide methods better convey the intent of what happens.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289/" ]
Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious? For example, imagine I have this class in C++: ``` public class SomeClass { private: bool mIsVisible; public: void draw(); void erase(); } ``` I could add functions to get/set "mIsVisible" like this: ``` bool getVisible() { return mIsVisible; }; ``` void setVisible(bool visible) { if (!mIsVisible && visible) { draw(); } else if (mIsVisible && !visible) { erase(); } ``` mIsVisible = visible; ``` } However, it would be equally possible to use the following methods instead: ``` bool isVisible() { return mIsVisible; }; void show() { if (!mIsVisible) { mIsVisible = true; draw(); } } void hide() { if (mIsVisible) { mIsVisible = false; erase(); } } ``` In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?
Have a read of the article "[Tell, Don't Ask](http://www.pragprog.com/articles/tell-dont-ask)" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go. Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely: 1. get current visibility value, 2. make decision based on value, 3. update object.
175,236
<p>Actually, I'm using this way. Do you have a better way?</p> <pre><code>private bool AcceptJson(HttpRequest request) { const string JsonType = "application/json"; if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith(JsonType)) { return true; } if (request.AcceptTypes.Select(t =&gt; t.ToLower(CultureInfo.InvariantCulture) == JsonType).Count() &gt; 0) { return true; } return false; } </code></pre>
[ { "answer_id": 175321, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 3, "selected": true, "text": "<p>That approach can lead to false positives (it doesn't account for q values or content types of which application/json is a substring).</p>\n\n<p>You can find a decent Accept header parser in <a href=\"http://www.dev-archive.net/articles/xhtml.html#content-negotiation\" rel=\"nofollow noreferrer\">this article about XHTML</a>. You'll have to port the algorithm to your language of choice and adapt it for the content-types you are using.</p>\n" }, { "answer_id": 178488, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 1, "selected": false, "text": "<p>It's tough to know what you mean by \"better\". Strictly speaking, you don't need to worry about the content type, so that can be removed. I guess technically a better way would be to remove the Select call and put the condition into the Count method.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683/" ]
Actually, I'm using this way. Do you have a better way? ``` private bool AcceptJson(HttpRequest request) { const string JsonType = "application/json"; if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith(JsonType)) { return true; } if (request.AcceptTypes.Select(t => t.ToLower(CultureInfo.InvariantCulture) == JsonType).Count() > 0) { return true; } return false; } ```
That approach can lead to false positives (it doesn't account for q values or content types of which application/json is a substring). You can find a decent Accept header parser in [this article about XHTML](http://www.dev-archive.net/articles/xhtml.html#content-negotiation). You'll have to port the algorithm to your language of choice and adapt it for the content-types you are using.
175,240
<p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p> <p>What is the best way to convert the entire file format using Python?</p>
[ { "answer_id": 175258, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 4, "selected": false, "text": "<p><em>I think this is a deeper issue than you realize</em>. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.</p>\n\n<p>This Python Unicode tutorial may give you a better idea of what happens to Unicode strings that are translated to ASCII: <a href=\"http://www.reportlab.com/i18n/python_unicode_tutorial.html\" rel=\"nofollow noreferrer\">http://www.reportlab.com/i18n/python_unicode_tutorial.html</a></p>\n\n<p><strong>Here's a useful quote from the site:</strong></p>\n\n<blockquote>\n <p>Python 1.6 also gets a \"unicode\"\n built-in function, to which you can\n specify the encoding:</p>\n</blockquote>\n\n<pre><code>&gt; &gt;&gt;&gt; unicode('hello') u'hello'\n&gt; &gt;&gt;&gt; unicode('hello', 'ascii') u'hello'\n&gt; &gt;&gt;&gt; unicode('hello', 'iso-8859-1') u'hello'\n&gt; &gt;&gt;&gt;\n</code></pre>\n\n<blockquote>\n <p>All three of these return the same\n thing, since the characters in 'Hello'\n are common to all three encodings.</p>\n \n <p>Now let's encode something with a\n European accent, which is outside of\n ASCII. What you see at a console may\n depend on your operating system\n locale; Windows lets me type in\n ISO-Latin-1.</p>\n</blockquote>\n\n<pre><code>&gt; &gt;&gt;&gt; a = unicode('André','latin-1')\n&gt; &gt;&gt;&gt; a u'Andr\\202'\n</code></pre>\n\n<blockquote>\n <p>If you can't type an acute letter e,\n you can enter the string 'Andr\\202',\n which is unambiguous.</p>\n \n <p>Unicode supports all the common\n operations such as iteration and\n splitting. We won't run over them\n here.</p>\n</blockquote>\n" }, { "answer_id": 175260, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>uc = open(filename).read().decode('utf8')\nascii = uc.decode('ascii')\n</code></pre>\n\n<p>Note, however, that this will <strong>fail</strong> with a <code>UnicodeDecodeError</code> exception if there are any characters that can't be converted to ASCII.</p>\n\n<p>EDIT: As Pete Karl just pointed out, there is no one-to-one mapping from Unicode to ASCII. So some characters simply can't be converted in an information-preserving way. Moreover, standard ASCII is more or less a subset of UTF-8, so you don't really even need to do any decoding.</p>\n" }, { "answer_id": 175270, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": true, "text": "<p>You can convert the file easily enough just using the <code>unicode</code> function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.</p>\n\n<p><a href=\"http://www.peterbe.com/plog/unicode-to-ascii\" rel=\"noreferrer\">This blog</a> recommends the <code><a href=\"http://www.python.org/doc/2.5.2/lib/module-unicodedata.html\" rel=\"noreferrer\">unicodedata </a></code> module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.</p>\n\n<pre><code>&gt;&gt;&gt; title = u\"Klüft skräms inför på fédéral électoral große\"\n</code></pre>\n\n<p>is typically converted to </p>\n\n<pre><code>Klft skrms infr p fdral lectoral groe\n</code></pre>\n\n<p>which is pretty wrong. However, using the <code>unicodedata</code> module, the result can be much closer to the original text:</p>\n\n<pre><code>&gt;&gt;&gt; import unicodedata\n&gt;&gt;&gt; unicodedata.normalize('NFKD', title).encode('ascii','ignore')\n'Kluft skrams infor pa federal electoral groe'\n</code></pre>\n" }, { "answer_id": 175286, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 2, "selected": false, "text": "<p>Here's some simple (and stupid) code to do encoding translation. I'm assuming (but you shouldn't) that the input file is in UTF-16 (Windows calls this simply 'Unicode').</p>\n\n<pre><code>input_codec = 'UTF-16'\noutput_codec = 'ASCII'\n\nunicode_file = open('filename')\nunicode_data = unicode_file.read().decode(input_codec)\nascii_file = open('new filename', 'w')\nascii_file.write(unicode_data.write(unicode_data.encode(output_codec)))\n</code></pre>\n\n<p>Note that this will not work if there are any characters in the Unicode file that are not also ASCII characters. You can do the following to turn unrecognized characters into '?'s:</p>\n\n<pre><code>ascii_file.write(unicode_data.write(unicode_data.encode(output_codec, 'replace')))\n</code></pre>\n\n<p>Check out <a href=\"http://docs.python.org/library/stdtypes.html#str.encode\" rel=\"nofollow noreferrer\">the docs</a> for more simple choices. If you need to do anything more sophisticated, you may wish to check out <a href=\"http://code.activestate.com/recipes/251871/\" rel=\"nofollow noreferrer\">The UNICODE Hammer</a> at the Python Cookbook.</p>\n" }, { "answer_id": 176044, "author": "Jerry Hill", "author_id": 12773, "author_profile": "https://Stackoverflow.com/users/12773", "pm_score": 0, "selected": false, "text": "<p>It's important to note that there is no 'Unicode' file format. Unicode can be encoded to bytes in several different ways. Most commonly UTF-8 or UTF-16. You'll need to know which one your 3rd-party tool is outputting. Once you know that, converting between different encodings is pretty easy:</p>\n\n<pre><code>in_file = open(\"myfile.txt\", \"rb\")\nout_file = open(\"mynewfile.txt\", \"wb\")\n\nin_byte_string = in_file.read()\nunicode_string = bytestring.decode('UTF-16')\nout_byte_string = unicode_string.encode('ASCII')\n\nout_file.write(out_byte_string)\nout_file.close()\n</code></pre>\n\n<p>As noted in the other replies, you're probably going to want to supply an error handler to the encode method. Using 'replace' as the error handler is simple, but will mangle your text if it contains characters that cannot be represented in ASCII.</p>\n" }, { "answer_id": 1906165, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 0, "selected": false, "text": "<p>As other posters have noted, ASCII is a subset of unicode. </p>\n\n<p>However if you:</p>\n\n<ul>\n<li>have a legacy app </li>\n<li>you don't control the code for that app</li>\n<li>you're sure your input falls into the ASCII subset</li>\n</ul>\n\n<p>Then the example below shows how to do it:</p>\n\n<pre><code>mystring = u'bar'\ntype(mystring)\n &lt;type 'unicode'&gt;\n\nmyasciistring = (mystring.encode('ASCII'))\ntype(myasciistring)\n &lt;type 'str'&gt;\n</code></pre>\n" }, { "answer_id": 6312083, "author": "Vijay", "author_id": 684799, "author_profile": "https://Stackoverflow.com/users/684799", "pm_score": 2, "selected": false, "text": "<p>For my problem where I just wanted to skip the Non-ascii characters and just output only ascii output, the below solution worked really well:</p>\n\n<pre><code> import unicodedata\n input = open(filename).read().decode('UTF-16')\n output = unicodedata.normalize('NFKD', input).encode('ASCII', 'ignore')\n</code></pre>\n" }, { "answer_id": 8543825, "author": "kev", "author_id": 348785, "author_profile": "https://Stackoverflow.com/users/348785", "pm_score": 2, "selected": false, "text": "<p>By the way, these is a linux command <code>iconv</code> to do this kind of job.</p>\n\n<pre><code>iconv -f utf8 -t ascii &lt;input.txt &gt;output.txt\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format. What is the best way to convert the entire file format using Python?
You can convert the file easily enough just using the `unicode` function, but you'll run into problems with Unicode characters without a straight ASCII equivalent. [This blog](http://www.peterbe.com/plog/unicode-to-ascii) recommends the `[unicodedata](http://www.python.org/doc/2.5.2/lib/module-unicodedata.html)` module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g. ``` >>> title = u"Klüft skräms inför på fédéral électoral große" ``` is typically converted to ``` Klft skrms infr p fdral lectoral groe ``` which is pretty wrong. However, using the `unicodedata` module, the result can be much closer to the original text: ``` >>> import unicodedata >>> unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe' ```
175,296
<p>I use TortoiseSVN 1.5.3 and VisualSVN 1.5.3 (Subversion 1.5.2)</p> <p>Suppose that I create a new branch (/branches/branch1) of the trunk(/trunk) then someone (also using TortoiseSVN 1.5.3) merges their branch back into the trunk. </p> <p>I try to merge from the trunk into the branch (to aquire all changes which might have beemn merged into the trunk by others)</p> <p>I do not specify any particular revision(s) because I want the merge-tracking to determine which revisions I need to merge. I expect these to be revisions after the one in which I created the branch.</p> <p>When I start the merge, the output dialog seems to merge every revision back to revision 1. this causes everything in the repository to be 'added'.</p> <p>What a I doing wrong?.... I expected a single revision to be targeted and for this to be a very quick operation.</p> <p>I have tried...</p> <pre><code>SVNAdmin Upgrade &lt;MyRepoPath&gt; </code></pre> <p>This resulted in a an instantaneous success message after which I repeated my experiment with no change in results</p> <p>Update: I have noticed that the TortoiseSVN dialog says "To merge all revisions, leave the box empty."... does this mean that TortoiseSVN is adding the 1-Head explicity and that there is no way to use Merge-Tracking? That would seem a bit strange.</p>
[ { "answer_id": 175524, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 0, "selected": false, "text": "<p>I think you need to use the Branch as your from URL. The reason is that your Trunk revision is now higher than your Branch, and so you need to start with the lowest revision.</p>\n" }, { "answer_id": 178004, "author": "Rory Becker", "author_id": 11356, "author_profile": "https://Stackoverflow.com/users/11356", "pm_score": 2, "selected": true, "text": "<p>SOLVED: The answer appears to be down to a workaround we implemented here for some previous bugs in Subversion.</p>\n\n<p>The workaround involved the use of SomeUserName@ being placed in the url. thus</p>\n\n<pre><code>http://SomeUsername@Myserver:8080/myrepo/trunk\n</code></pre>\n\n<p>...was being used instead of...</p>\n\n<pre><code>http://Myserver:8080/myrepo/trunk\n</code></pre>\n\n<p>It seems that the working copy of the branch was retrieved without this addition and the Merge was being done to a url with this addtion. this led Subversion to deduce that they were 2 different urls and naturally(ish) deduced they had no common history from which to locate the startpoint to merge from.</p>\n\n<p><strong>Thus the solution is to ensure the format of the 'from' url used for the merge matches the format of the url used by the working copy.</strong></p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
I use TortoiseSVN 1.5.3 and VisualSVN 1.5.3 (Subversion 1.5.2) Suppose that I create a new branch (/branches/branch1) of the trunk(/trunk) then someone (also using TortoiseSVN 1.5.3) merges their branch back into the trunk. I try to merge from the trunk into the branch (to aquire all changes which might have beemn merged into the trunk by others) I do not specify any particular revision(s) because I want the merge-tracking to determine which revisions I need to merge. I expect these to be revisions after the one in which I created the branch. When I start the merge, the output dialog seems to merge every revision back to revision 1. this causes everything in the repository to be 'added'. What a I doing wrong?.... I expected a single revision to be targeted and for this to be a very quick operation. I have tried... ``` SVNAdmin Upgrade <MyRepoPath> ``` This resulted in a an instantaneous success message after which I repeated my experiment with no change in results Update: I have noticed that the TortoiseSVN dialog says "To merge all revisions, leave the box empty."... does this mean that TortoiseSVN is adding the 1-Head explicity and that there is no way to use Merge-Tracking? That would seem a bit strange.
SOLVED: The answer appears to be down to a workaround we implemented here for some previous bugs in Subversion. The workaround involved the use of SomeUserName@ being placed in the url. thus ``` http://SomeUsername@Myserver:8080/myrepo/trunk ``` ...was being used instead of... ``` http://Myserver:8080/myrepo/trunk ``` It seems that the working copy of the branch was retrieved without this addition and the Merge was being done to a url with this addtion. this led Subversion to deduce that they were 2 different urls and naturally(ish) deduced they had no common history from which to locate the startpoint to merge from. **Thus the solution is to ensure the format of the 'from' url used for the merge matches the format of the url used by the working copy.**
175,323
<p>As I am coding my unit tests, I tend to find that I insert the following lines:</p> <pre><code>Console.WriteLine("Starting InteropApplication, with runInBackground set to true..."); try { InteropApplication application = new InteropApplication(true); application.Start(); Console.WriteLine("Application started correctly"); } catch(Exception e) { Assert.Fail(string.Format("InteropApplication failed to start: {0}", e.ToString())); } //test code continues ... </code></pre> <p>All of my tests are pretty much the same thing. They are displaying information as to why they failed, or they are displaying information about what they are doing. I haven't had any <em>formal</em> methods of how unit tests should be coded. Should they be displaying information as to what they are doing? Or should the tests be silent and not display any information at all as to what they are doing, and only display failure messages?</p> <p>NOTE: The language is C#, but I don't care about a language specific answer.</p>
[ { "answer_id": 175331, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "<p>I personally would recommend that you output only errors and a summary of the number of tests run and how many passed. This is a completely subjective view though. Display what suits your needs.</p>\n" }, { "answer_id": 175340, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Well, you should only know when a test failed and why it failed. It's no use to know what's going on, unless, for example, you have a loop and you want to know exactly where in the loop the test died.</p>\n" }, { "answer_id": 175345, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>I recommend against it - I think that the unit testing should work on the Unix tools philosophy - don't say anything when things are going well.\nI find that constructing tests to give meaningful information when they fail is best - that way you get nice short output when things work and it's easy to see what went wrong when there are problems - errors aren't lost to scroll blindness.</p>\n" }, { "answer_id": 175349, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "<p>I'm not sure why you would do that - if your unit test is named well, you already know what it's doing. If it fails, you know what test failed (and what assert failed). If it didn't fail you know that it succeeded.</p>\n\n<p>This seems completely subjective, but to me this seems like completely redundant information that just adds noise.</p>\n" }, { "answer_id": 175351, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "<p>I like to buffer the verbose log (about last 20 lines or so), but I don't display it until it gets to some error. When the error happens, it's nice to have some context.</p>\n\n<p>OTOH, unit tests should be small pieces of unrelated code with specific input and output requirements. In most cases, displaying input that caused the error (i.e. wrong output) is enough to trace the problem to its roots.</p>\n" }, { "answer_id": 175362, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": false, "text": "<p>I would actually suggest against it (though not militantly). It couples the user interface of your tests with the test implementation (what if the tests are run through GUI viewer?). As alternative I would suggest one of the following:</p>\n\n<ol>\n<li>I'm not familiar with NUnit, but PyUnit allows you to add a description of the test and when tests are run with the verbose option the description is printed. I would look into the NUnit documentation to see if this is something you can do.<br> </li>\n<li>Extend the TestCase class that you're inheriting from to add a function from which you call that logs what the test is trying to do. That way different implementations can handle messages in different ways.</li>\n</ol>\n" }, { "answer_id": 175367, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 1, "selected": false, "text": "<p>This might be a bit too language specific, but when I'm writing NUnit tests I tend to do this, only I use the System.Diagnostics.Trace library instead of the console, that way the information is only shown if I decide to watch the tracing.</p>\n" }, { "answer_id": 175369, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>I think your making far more work for yourself. The tests either pass or fail, the failure should hopefully be the exception to the rule and you should let the unit test runner handle and throw the exception. What you're doing is adding cruft, the exception logged by the test runner will tell you the same thing.</p>\n" }, { "answer_id": 175387, "author": "Sergey Volegov", "author_id": 9024, "author_profile": "https://Stackoverflow.com/users/9024", "pm_score": 2, "selected": false, "text": "<p>I'd say you should output whatever suits your needs, but showing too much can dilute output from test runner.<br>\nBTW, your example code hardly looks as a <a href=\"http://en.wikipedia.org/wiki/Unit_test\" rel=\"nofollow noreferrer\">unit test</a>, more of a integration/system test.</p>\n" }, { "answer_id": 175392, "author": "Illandril", "author_id": 17887, "author_profile": "https://Stackoverflow.com/users/17887", "pm_score": 0, "selected": false, "text": "<p>The only time I would display what's happening is if there was some aspect of it that would be easier to test non-automatically. For example, if you've got code that takes a little while to run, and might get stuck in an infinite loop, you might want to print out a message every so often to indicate that it is still making progress.</p>\n\n<p>Always make sure failure messages clearly stand out from other output, however.</p>\n" }, { "answer_id": 175438, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 1, "selected": false, "text": "<p>You don't need to, if the tests are running silently then that means there was no error. There is usually no reason for tests to give any output other than if the test failed. If it's running, then it is running indicated by the test runner that the test has passed, i.e. it is \"green\". Running the test (together with many tests with console output) through a test runner in an IDE, you'll be spamming the console log with messages nobody will care about.</p>\n\n<p>The test you've written is not a unit test, but looks more like an integration/system test because you seem to be running an application as a whole. A unit test will test a public method in a class, preferably keeping the class as isolated as possible.</p>\n" }, { "answer_id": 175456, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>You could have written the test method like this. It's up to your code-nose which style of test you prefer. I prefer not writing extra try-catches and Console.WriteLines.</p>\n\n<pre><code>public void TestApplicationStart()\n{\n InteropApplication application = new InteropApplication(true);\n application.Start();\n}\n</code></pre>\n\n<p>Test frameworks that I have worked with would interpret any unhandled (and unexpected) exception as a failed test.</p>\n\n<p>Think about the time you took to gold-plate this test and how many more meaningful tests you could have written with that time.</p>\n" }, { "answer_id": 175509, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 1, "selected": false, "text": "<p>Using console i/o kinda defies the whole purpose of a unit testing framework. you might as well code the whole test manually. If you are using a unit testing framework, your tests should be very malleable, tied to as few things as possible</p>\n" }, { "answer_id": 175531, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 1, "selected": false, "text": "<p>Displaying information can be useful; if you're trying to find out why a test failed, it can be useful to be able to see more than just a stack trace, and what happened before the program reached the point where it failed. </p>\n\n<p>However, in the \"normal\" case where everything succeeds, these messages are unnecessary clutter that distract from what you're really trying to do - ie. looking at an overview of which tests succeeded and failed.</p>\n\n<p>I'd suggest redirecting your debugging messages to a log file. You can either do this by writing all your log message code to call a special \"log print\" function, or if you're writing a console program, you should be able to redirect stdout to a different file (I know for a fact that you can do this in both Unix and Windows). This way, you get the high level overview but the details are there if you need them.</p>\n" }, { "answer_id": 175563, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 1, "selected": false, "text": "<p>I would avoid putting extra Try/Catch statements in Unit Tests. First of all, an expected exception in a unit test will already cause the test to Fail. That is the default behavior of NUnit. Essentitally, the test harness wraps each call to your test functions with that code already. Also, by just using the e.ToString() to display what happened, I believe you are losing a lot of information. By default, I believe NUnit will display not just the Exception type, but also the Call Stack, which I don't believe you're seeing with your method.</p>\n\n<p>Secondly, there are times when its necessary. For instance, you can use the [ExpectedException] attribute to actually say when it occurs. Just be sure that when you test non-exception related Asserts (for instance Asserting a list count > 0, etc) that you put in a good description as the argument to the assert. That is useful.</p>\n\n<p>Everything else is generally not needed. If your unit tests are so large that you start putting in WriteLines with what \"step\" of the test you're on, that is generally a sign that your test should really be broken out into multiple smaller tests. In other words, that you're not doing a unit test, but rather an integration test.</p>\n" }, { "answer_id": 176225, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 1, "selected": false, "text": "<p>Have you looked at the xUnit style of unit test frameworks?<br>\nSee <a href=\"http://www.xprogramming.com/software.htm\" rel=\"nofollow noreferrer\">Ron Jeffries</a> site for a rather large list. </p>\n\n<p>One of the principles of these frameworks is that they produce little or no output during the test run and only really an indicator of success at the end. In the case of failures its possible to get a more descriptive output of the reason for failure.<br>\nThe reason for this mode is that while everything is OK you don't want to be bothered by extra output, and certainly if there is a failure you don't want to miss it because of the noise of other output.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8505/" ]
As I am coding my unit tests, I tend to find that I insert the following lines: ``` Console.WriteLine("Starting InteropApplication, with runInBackground set to true..."); try { InteropApplication application = new InteropApplication(true); application.Start(); Console.WriteLine("Application started correctly"); } catch(Exception e) { Assert.Fail(string.Format("InteropApplication failed to start: {0}", e.ToString())); } //test code continues ... ``` All of my tests are pretty much the same thing. They are displaying information as to why they failed, or they are displaying information about what they are doing. I haven't had any *formal* methods of how unit tests should be coded. Should they be displaying information as to what they are doing? Or should the tests be silent and not display any information at all as to what they are doing, and only display failure messages? NOTE: The language is C#, but I don't care about a language specific answer.
I personally would recommend that you output only errors and a summary of the number of tests run and how many passed. This is a completely subjective view though. Display what suits your needs.
175,381
<p>I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control?</p> <pre><code>&lt;div id="formSpinner"&gt; &lt;img src="images/spinner.gif" /&gt; &lt;p&gt;Saving...&lt;/p&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 175402, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 2, "selected": false, "text": "<p>Add the runat=\"server\" attribute to the tag, then you can reference it from the codebehind.</p>\n" }, { "answer_id": 175407, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "<p>Make sure that your div is set to runat=\"server\", then simply reference it in the code-behind and set the \"class\" attribute.</p>\n\n<pre><code>&lt;div runat=\"server\" id=\"formSpinner\"&gt;\n ...content...\n&lt;/div&gt;\n</code></pre>\n\n<p>Code-behind</p>\n\n<pre><code>formSpinner.Attributes[\"class\"] = \"class-name\";\n</code></pre>\n" }, { "answer_id": 175408, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>Add runat to the element in the markup</p>\n\n<pre><code>&lt;div id=\"formSpinner\" runat=\"server\"&gt;\n &lt;img src=\"images/spinner.gif\"&gt;\n &lt;p&gt;Saving...&lt;/p&gt;\n&lt;/div\n</code></pre>\n\n<p>Then you can get to the control's class attributes by using \nformSpinner.Attributes(\"class\")\nIt will only be a string, but you should be able to edit it. </p>\n" }, { "answer_id": 175475, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 7, "selected": true, "text": "<p>Add the <code>runat=\"server\"</code> attribute to it so you have:</p>\n\n<pre><code>&lt;div id=\"formSpinner\" runat=\"server\"&gt;\n &lt;img src=\"images/spinner.gif\"&gt;\n &lt;p&gt;Saving...&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>That way you can access the class attribute by using:</p>\n\n<pre><code>formSpinner.Attributes[\"class\"] = \"classOfYourChoice\";\n</code></pre>\n\n<p>It's also worth mentioning that the <code>asp:Panel</code> control is virtually synonymous (at least as far as rendered markup is concerned) with <code>div</code>, so you could also do:</p>\n\n<pre><code>&lt;asp:Panel id=\"formSpinner\" runat=\"server\"&gt;\n &lt;img src=\"images/spinner.gif\"&gt;\n &lt;p&gt;Saving...&lt;/p&gt;\n&lt;/asp:Panel&gt;\n</code></pre>\n\n<p>Which then enables you to write:</p>\n\n<pre><code>formSpinner.CssClass = \"classOfYourChoice\";\n</code></pre>\n\n<p>This gives you more defined access to the property and there are others that may, or may not, be of use to you.</p>\n" }, { "answer_id": 175582, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>This question makes me nervous. It indicates that maybe you don't understand how using server-side code will impact you're page's DOM state. </p>\n\n<p>Whenever you run server-side code the entire page is rebuilt from scratch. This has several implications:</p>\n\n<ul>\n<li>A form is submitted from the client to the web server. This is about the slowest action that a web browser can take, especially in ASP.Net where the form might be padded with extra fields (ie: ViewState). Doing it too often for trivial activities will make your app appear to be sluggish, even if everything else is nice and snappy.</li>\n<li>It adds load to your server, in terms of bandwidth (up and down stream) and CPU/memory. Everything involved in rebuilding your page will have to happen again. If there are dynamic controls on the page, don't forget to create them.</li>\n<li><strong>Anything you've done to the DOM since the last request is lost, unless you remember to do it again for this request.</strong> Your page's DOM is <em>reset</em>.</li>\n</ul>\n\n<p>If you can get away with it, you might want to push this down to javascript and avoid the postback. Perhaps use an XmlHttpRequest() call to trigger any server-side action you need.</p>\n" }, { "answer_id": 176258, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>If all you want to do is conditionally show or hide a &lt;div>, then you could declare it as an &lt;asp:panel > (renders to html as a div tag) and set it's .Visible property.</p>\n" }, { "answer_id": 4998251, "author": "mokumaxCraig", "author_id": 572807, "author_profile": "https://Stackoverflow.com/users/572807", "pm_score": 2, "selected": false, "text": "<p>How do you do this without runat=\"server\"? For example, if you have a </p>\n\n<pre><code>&lt;body runat=\"server\" id=\"body1\"&gt;\n</code></pre>\n\n<p>...and try to update it from within an <strong>Updatepanel</strong> it will never get updated. </p>\n\n<p>However, if you keep it as an ordinary non-server HTML control you can. Here's the Jquery to update it:</p>\n\n<pre><code>$(\"#body1\").addClass('modalBackground');\n</code></pre>\n\n<p>How do you do this in codebehind though?</p>\n" }, { "answer_id": 5131231, "author": "Peri", "author_id": 636118, "author_profile": "https://Stackoverflow.com/users/636118", "pm_score": 2, "selected": false, "text": "<p>If you do not want to make your control runat server in case you need the ID or simply don't want to add it to the viewstate,</p>\n\n<pre><code>&lt;div id=\"formSpinner\" class=\"&lt;%= _css %&gt;\"&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>in the back-end:</p>\n\n<pre><code>protected string _css = \"modalBackground\";\n</code></pre>\n" }, { "answer_id": 14345960, "author": "RandomUs1r", "author_id": 1981471, "author_profile": "https://Stackoverflow.com/users/1981471", "pm_score": 1, "selected": false, "text": "<p>To expand on Peri's post &amp; why we may not want to use viewstate the following code:</p>\n\n<p><code>style=\"&lt;%= _myCSS %>\"</code><br /><br />\n<code>Protected _myCSS As String = \"display: none\"</code><br />\nIs the approach to look at if you're using AJAX, it allows for manipulating the display via asp.net back end code rather than jquery/jscript.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control? ``` <div id="formSpinner"> <img src="images/spinner.gif" /> <p>Saving...</p> </div> ```
Add the `runat="server"` attribute to it so you have: ``` <div id="formSpinner" runat="server"> <img src="images/spinner.gif"> <p>Saving...</p> </div> ``` That way you can access the class attribute by using: ``` formSpinner.Attributes["class"] = "classOfYourChoice"; ``` It's also worth mentioning that the `asp:Panel` control is virtually synonymous (at least as far as rendered markup is concerned) with `div`, so you could also do: ``` <asp:Panel id="formSpinner" runat="server"> <img src="images/spinner.gif"> <p>Saving...</p> </asp:Panel> ``` Which then enables you to write: ``` formSpinner.CssClass = "classOfYourChoice"; ``` This gives you more defined access to the property and there are others that may, or may not, be of use to you.
175,385
<p>When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?</p>
[ { "answer_id": 175394, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>I'd stay on the CSS side of the house, but I've done very little Javascript.</p>\n\n<p>CSS seems to be easier to standardize across browsers than Javascript, though that may be changing with the advent of Chrome's V8 and Firefox's upcoming new rendering tool.</p>\n" }, { "answer_id": 175411, "author": "Jon Smock", "author_id": 25538, "author_profile": "https://Stackoverflow.com/users/25538", "pm_score": 1, "selected": false, "text": "<p>Because it's an aspect of presentation, I'd say it's more standards based to do it with CSS. It used to be done in Javascript, simply because we couldn't do it with CSS (old browsers suck, and I don't think :hover was even added until CSS 2).</p>\n" }, { "answer_id": 175418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>It will still work in CSS if the browser happens to have Javascript disabled.</p>\n" }, { "answer_id": 175421, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 1, "selected": false, "text": "<p>Implementing a rollover with CSS uses the :hover pseudo-class to define the style of the target element when it is hovered over. This works great in many browsers but not in IE6 where it only works well with the anchor tag (i.e. a:hover). I used CSS hover to implement a tabbed navigation bar but had to use IE behaviors to get it working in IE6.</p>\n" }, { "answer_id": 175422, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 6, "selected": true, "text": "<p>CSS is fine for rollovers. They're implemented basically using the <code>:hover</code> pseudo-selector. Here's a really simple implementation:</p>\n\n<pre><code>a{\n background-image: url(non-hovered-state.png);\n}\na:hover{\n background-image: url(hovered-state.png);\n}\n</code></pre>\n\n<p>There are a few things you need to be aware of though:</p>\n\n<ul>\n<li>IE6 only supports <code>:hover</code> on <code>&lt;a&gt;</code> tags</li>\n<li>Images specified in CSS but not used on the page won't be loaded immediately (meaning the rollover state can take a second to appear first time)</li>\n</ul>\n\n<p>The <code>&lt;a&gt;</code>-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called <a href=\"http://alistapart.com/articles/sprites/\" rel=\"nofollow noreferrer\">CSS Sprites</a> that can prevent this problem, you can find an example of the technique in use to make <a href=\"http://www.wellstyled.com/css-nopreload-rollovers.html\" rel=\"nofollow noreferrer\">no-preload rollovers</a>. </p>\n\n<p>It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using <code>background-position</code> so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)):</p>\n\n<pre><code>a{\n background-image: url(rollover-sprites.png);\n background-position: 0 0; /* Added for clarity */\n height: 20px;\n}\na:hover{\n background-position: 0 -20px; /* move the image up 20px to show the hovered state below */\n}\n</code></pre>\n\n<p>Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support <code>background-position</code>)</p>\n" }, { "answer_id": 175508, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "<p>Isn't there a mnemonic for remembering the sequence of declarations in CSS?</p>\n" }, { "answer_id": 175975, "author": "Ionuț Staicu", "author_id": 23810, "author_profile": "https://Stackoverflow.com/users/23810", "pm_score": 1, "selected": false, "text": "<p>Yep, the best way to do this is <a href=\"http://alistapart.com/articles/sprites/\" rel=\"nofollow noreferrer\">css</a> <a href=\"http://css-tricks.com/css-sprites-what-they-are-why-theyre-cool-and-how-to-use-them/\" rel=\"nofollow noreferrer\">sprites</a>. An annoying problem occurs in IE6, when browser make a request every time an element is hovered. To fix this, <a href=\"http://www.mister-pixel.com/index.php?Content__state=is_that_simple\" rel=\"nofollow noreferrer\">take a look here</a>.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?
CSS is fine for rollovers. They're implemented basically using the `:hover` pseudo-selector. Here's a really simple implementation: ``` a{ background-image: url(non-hovered-state.png); } a:hover{ background-image: url(hovered-state.png); } ``` There are a few things you need to be aware of though: * IE6 only supports `:hover` on `<a>` tags * Images specified in CSS but not used on the page won't be loaded immediately (meaning the rollover state can take a second to appear first time) The `<a>`-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called [CSS Sprites](http://alistapart.com/articles/sprites/) that can prevent this problem, you can find an example of the technique in use to make [no-preload rollovers](http://www.wellstyled.com/css-nopreload-rollovers.html). It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using `background-position` so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)): ``` a{ background-image: url(rollover-sprites.png); background-position: 0 0; /* Added for clarity */ height: 20px; } a:hover{ background-position: 0 -20px; /* move the image up 20px to show the hovered state below */ } ``` Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support `background-position`)
175,415
<p>What is the best way to get the names of all of the tables in a specific database on SQL Server?</p>
[ { "answer_id": 175417, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 3, "selected": false, "text": "<pre><code>exec sp_msforeachtable 'print ''?'''\n</code></pre>\n" }, { "answer_id": 175423, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 3, "selected": false, "text": "<p><code>select * from sysobjects where xtype='U'</code></p>\n" }, { "answer_id": 175427, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT name \nFROM sysobjects \nWHERE xtype='U' \nORDER BY name;\n</code></pre>\n\n<p>(SQL Server 2000 standard; still supported in SQL Server 2005.)</p>\n" }, { "answer_id": 175429, "author": "Erikk Ross", "author_id": 18772, "author_profile": "https://Stackoverflow.com/users/18772", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT sobjects.name\nFROM sysobjects sobjects\nWHERE sobjects.xtype = 'U' \n</code></pre>\n" }, { "answer_id": 175433, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES \n</code></pre>\n\n<p>OR</p>\n\n<pre><code>SELECT * FROM Sys.Tables\n</code></pre>\n" }, { "answer_id": 175446, "author": "ScottStonehouse", "author_id": 2342, "author_profile": "https://Stackoverflow.com/users/2342", "pm_score": 12, "selected": true, "text": "<p>SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019:</p>\n<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'\n</code></pre>\n<p>To show only tables from a particular database</p>\n<pre><code>SELECT TABLE_NAME \nFROM [&lt;DATABASE_NAME&gt;].INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE = 'BASE TABLE'\n</code></pre>\n<p>Or,</p>\n<pre><code>SELECT TABLE_NAME \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE = 'BASE TABLE' \n AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' )\n</code></pre>\n<p>PS: For SQL Server 2000:</p>\n<pre><code>SELECT * FROM sysobjects WHERE xtype='U' \n</code></pre>\n" }, { "answer_id": 175450, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 8, "selected": false, "text": "<pre><code>SELECT sobjects.name\nFROM sysobjects sobjects\nWHERE sobjects.xtype = 'U'\n</code></pre>\n\n<p>Here is a list of other object types you can search for as well:</p>\n\n<ul>\n<li>AF: Aggregate function (CLR)</li>\n<li>C: CHECK constraint</li>\n<li>D: Default or DEFAULT constraint</li>\n<li>F: FOREIGN KEY constraint</li>\n<li>L: Log</li>\n<li>FN: Scalar function</li>\n<li>FS: Assembly (CLR) scalar-function</li>\n<li>FT: Assembly (CLR) table-valued function</li>\n<li>IF: In-lined table-function</li>\n<li>IT: Internal table</li>\n<li>P: Stored procedure</li>\n<li>PC: Assembly (CLR) stored-procedure</li>\n<li>PK: PRIMARY KEY constraint (type is K)</li>\n<li>RF: Replication filter stored procedure</li>\n<li>S: System table</li>\n<li>SN: Synonym</li>\n<li>SQ: Service queue</li>\n<li>TA: Assembly (CLR) DML trigger</li>\n<li>TF: Table function</li>\n<li>TR: SQL DML Trigger</li>\n<li>TT: Table type</li>\n<li>U: User table</li>\n<li>UQ: UNIQUE constraint (type is K)</li>\n<li>V: View</li>\n<li>X: Extended stored procedure</li>\n</ul>\n" }, { "answer_id": 18203391, "author": "Rasoul Zabihi", "author_id": 851784, "author_profile": "https://Stackoverflow.com/users/851784", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT * FROM information_schema.tables\nwhere TABLE_TYPE = 'BASE TABLE'\n</code></pre>\n\n<p>SQL Server 2012</p>\n" }, { "answer_id": 19157943, "author": "Vikash Singh", "author_id": 2767928, "author_profile": "https://Stackoverflow.com/users/2767928", "pm_score": 5, "selected": false, "text": "<pre><code>USE YourDBName\nGO \nSELECT *\nFROM sys.Tables\nGO\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>USE YourDBName\nGO\nSELECT * FROM INFORMATION_SCHEMA.TABLES \nGO\n</code></pre>\n" }, { "answer_id": 33692871, "author": "Demietra95", "author_id": 4926279, "author_profile": "https://Stackoverflow.com/users/4926279", "pm_score": 2, "selected": false, "text": "<pre><code>--for oracle\nselect tablespace_name, table_name from all_tables;\n</code></pre>\n\n<hr>\n\n<p>This link can provide much more information on this\n<a href=\"http://onewebsql.com/blog/list-all-tables\" rel=\"nofollow\">topic</a></p>\n" }, { "answer_id": 44962622, "author": "NoWar", "author_id": 196919, "author_profile": "https://Stackoverflow.com/users/196919", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT TABLE_NAME \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE='BASE TABLE' \nORDER BY TABLE_NAME\n</code></pre>\n" }, { "answer_id": 45745748, "author": "Frank", "author_id": 2372560, "author_profile": "https://Stackoverflow.com/users/2372560", "pm_score": 1, "selected": false, "text": "<p>Thanks to Ray Vega, whose response gives all user tables in a database...</p>\n\n<blockquote>\n <p>exec sp_msforeachtable 'print ''?'''</p>\n</blockquote>\n\n<p>sp_helptext shows the underlying query, which summarises to...</p>\n\n<pre><code>select * from dbo.sysobjects o \njoin sys.all_objects syso on o.id = syso.object_id \nwhere OBJECTPROPERTY(o.id, 'IsUserTable') = 1 \nand o.category &amp; 2 = 0 \n</code></pre>\n" }, { "answer_id": 46447731, "author": "Leon Bouquiet", "author_id": 843345, "author_profile": "https://Stackoverflow.com/users/843345", "pm_score": 3, "selected": false, "text": "<p>The downside of <code>INFORMATION_SCHEMA.TABLES</code> is that it also includes system tables such as <code>dtproperties</code> and the <code>MSpeer_...</code> tables, with no way to tell them apart from your own tables.</p>\n\n<p>I would recommend using <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-objects-transact-sql\" rel=\"noreferrer\"><code>sys.objects</code></a> (the new version of the deprecated <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/system-compatibility-views/sys-sysobjects-transact-sql\" rel=\"noreferrer\">sysobjects</a> view), which does support excluding the system tables:</p>\n\n<pre><code>select *\nfrom sys.objects\nwhere type = 'U' -- User tables\nand is_ms_shipped = 0 -- Exclude system tables\n</code></pre>\n" }, { "answer_id": 46721932, "author": "Scott Software", "author_id": 3174453, "author_profile": "https://Stackoverflow.com/users/3174453", "pm_score": 2, "selected": false, "text": "<p>In SSMS, to get all fully qualified table names in a specific database (E.g., \"MyDatabase\"):</p>\n\n<pre><code>SELECT [TABLE_CATALOG] + '.' + [TABLE_SCHEMA] + '.' + [TABLE_NAME]\nFROM MyDatabase.INFORMATION_SCHEMA.Tables\nWHERE [TABLE_TYPE] = 'BASE TABLE' and [TABLE_NAME] &lt;&gt; 'sysdiagrams'\nORDER BY [TABLE_SCHEMA], [TABLE_NAME]\n</code></pre>\n\n<p>Results:</p>\n\n<ul>\n<li>MyDatabase.dbo.MyTable1 </li>\n<li>MyDatabase.dbo.MyTable2</li>\n<li>MyDatabase.MySchema.MyTable3 </li>\n<li>MyDatabase.MySchema.MyTable4</li>\n<li>etc.</li>\n</ul>\n" }, { "answer_id": 47460840, "author": "Vikash", "author_id": 8351544, "author_profile": "https://Stackoverflow.com/users/8351544", "pm_score": 2, "selected": false, "text": "<p>Please use this. You will get table names along with schema names:</p>\n\n<pre><code>SELECT SYSSCHEMA.NAME, SYSTABLE.NAME\nFROM SYS.tables SYSTABLE\nINNER JOIN SYS.SCHEMAS SYSSCHEMA\nON SYSTABLE.SCHEMA_ID = SYSSCHEMA.SCHEMA_ID\n</code></pre>\n" }, { "answer_id": 54070318, "author": "Masoud Darvishian", "author_id": 1402749, "author_profile": "https://Stackoverflow.com/users/1402749", "pm_score": 1, "selected": false, "text": "<p>Using <code>SELECT * FROM INFORMATION_SCHEMA.COLUMNS</code> also shows you all tables and related columns.</p>\n" }, { "answer_id": 54721471, "author": "DarkRob", "author_id": 10837441, "author_profile": "https://Stackoverflow.com/users/10837441", "pm_score": 3, "selected": false, "text": "<p>Well you can use <i>sys.objects</i> to get all database objects.</p>\n\n<pre><code> GO\n select * from sys.objects where type_desc='USER_TABLE' order by name\n GO\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>-- For all tables\nselect * from INFORMATION_SCHEMA.TABLES \nGO \n\n --- For user defined tables\nselect * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'\nGO\n\n --- For Views\nselect * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='VIEW'\nGO\n</code></pre>\n" }, { "answer_id": 68838583, "author": "JoelF", "author_id": 2236804, "author_profile": "https://Stackoverflow.com/users/2236804", "pm_score": 0, "selected": false, "text": "<p>To remove tables added by replication and any other table Microsoft adds run this:</p>\n<pre><code>SELECT s.NAME SchemaName, t.NAME TableName\nFROM [dbname].SYS.tables t\nINNER JOIN [dbname].SYS.SCHEMAS s\nON t.SCHEMA_ID = s.SCHEMA_ID\nWHERE t.is_ms_shipped=0 and type_desc = 'USER_TABLE'\nORDER BY s.NAME, t.NAME\n</code></pre>\n" }, { "answer_id": 70776670, "author": "Hassan Munir", "author_id": 3079433, "author_profile": "https://Stackoverflow.com/users/3079433", "pm_score": 2, "selected": false, "text": "<pre><code>Any of the T-SQL code below will work in SQL Server 2019:\n\n-- here, you need to prefix the database name in INFORMATION_SCHEMA.TABLES\nSELECT TABLE_NAME FROM [MSSQL-TEST].INFORMATION_SCHEMA.TABLES;\n\n-- The next 2 ways will require you to point\n-- to the specific database you want to list the tables\n\nUSE [MSSQL-TEST];\n-- (1) Using sys.tables\nSELECT * FROM sys.tables;\n\n-- (2) Using sysobjects\nSELECT * FROM sysobjects\nWHERE type='U';\n\nHere’s a working example using [Skyvia] using sys.tables.\n\n[Skyvia] should be the link to https://skyvia.com/connectors/sql-server\n\n\n [1]: https://i.stack.imgur.com/o3qo9.png\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/OghPy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OghPy.png\" alt=\"enter image description here\" /></a></p>\n<pre><code>Your SQL GUI tool should also have a way to list down all the tables in a database like the one above.\n\nSo, whatever suits your need and taste, there’s a code or GUI tool for that.\n</code></pre>\n" }, { "answer_id": 74280587, "author": "Muneeb Ejaz", "author_id": 5122498, "author_profile": "https://Stackoverflow.com/users/5122498", "pm_score": 0, "selected": false, "text": "<p><strong>UPDATE 2022</strong>:\nYou can <strong>list/show</strong> the tables that you created with this simple query in <strong>Microsoft SQL SERVER</strong>.</p>\n<pre><code>select * from SYS.TABLES;\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
What is the best way to get the names of all of the tables in a specific database on SQL Server?
SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019: ``` SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' ``` To show only tables from a particular database ``` SELECT TABLE_NAME FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ``` Or, ``` SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' ) ``` PS: For SQL Server 2000: ``` SELECT * FROM sysobjects WHERE xtype='U' ```
175,454
<p>I am working on a web application and I have run into the following situation.</p> <pre><code>Dim a as Object Dim i as Integer = 0 Try For i=1 to 5 a = new Object() 'Do stuff ' a = Nothing Next Catch Finally a = Nothing End Try </code></pre> <p>Do i need to do the a=Nothing in the loop or will the garbage collector clean a up?</p>
[ { "answer_id": 175460, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 2, "selected": false, "text": "<p>No you don't need it. .NET has garbage collection. And since it looks like this code is in a method scope the garbage collection will clean up any local variables.</p>\n" }, { "answer_id": 175465, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>It is almost never necessary to explicitly assign Nothing to a variable. The garbage collector's job is to take care of memory allocation for you, specifically to relieve you of this responsibility. So no, you don't need to assign <code>a = Nothing</code> inside the loop.</p>\n\n<p>You also do not need the <code>try/finally</code> block that assigns Nothing around the whole thing. This is really just extra clutter that the runtime system will take care of anyway.</p>\n" }, { "answer_id": 175476, "author": "adrianh", "author_id": 13165, "author_profile": "https://Stackoverflow.com/users/13165", "pm_score": 0, "selected": false, "text": "<p>The GC will clean it up.</p>\n" }, { "answer_id": 175480, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": true, "text": "<p>In .NET, you generally do not <strong>need</strong> to set a variable reference = <code>Nothing</code> (<code>null</code> in C#). The garbage collector will clean up, eventually. The reference itself will be destroyed when it goes out of scope (either when your method exits or when the object of this class is finalized.) Note that this doesn't mean the <strong>object</strong> is destroyed, just the reference to it. The object will still be destroyed non-deterministically by the collector.</p>\n\n<p>However, setting your reference = <code>Nothing</code> will provide a hint to .NET that the object may be garbage, and doesn't necessarily hurt anything -- aside from code clutter. If you were to keep it in there, I'd recommend removing it from <code>Try</code> block; it's already in the <code>Finally</code> block and will therefore always be called. (Aside from certain catastrophic exceptions; but in those cases it wouldn't get called in the <code>Try</code> block either!)</p>\n\n<p>Finally, I have to admit that I agree with Greg: Your code would be cleaner without this. The hint to the runtime that you're done with the reference is nice, but certainly not critical. Honestly, if I saw this in a code review, I'd probably have the developer rewrite it thusly:</p>\n\n<pre><code>Dim a as Object\nDim i as Integer = 0\n\nFor i=1 to 5\n a = new Object()\n 'Do stuff\nNext\n</code></pre>\n" }, { "answer_id": 175640, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": 0, "selected": false, "text": "<p>Like everyone stated above you do not need to explicitly set your variables to nothing, as it is handled automatically. However, if for whatever reason you want to force the GC to collect, you can run this:</p>\n\n<pre><code>System.GC.Collect()\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1001650/" ]
I am working on a web application and I have run into the following situation. ``` Dim a as Object Dim i as Integer = 0 Try For i=1 to 5 a = new Object() 'Do stuff ' a = Nothing Next Catch Finally a = Nothing End Try ``` Do i need to do the a=Nothing in the loop or will the garbage collector clean a up?
In .NET, you generally do not **need** to set a variable reference = `Nothing` (`null` in C#). The garbage collector will clean up, eventually. The reference itself will be destroyed when it goes out of scope (either when your method exits or when the object of this class is finalized.) Note that this doesn't mean the **object** is destroyed, just the reference to it. The object will still be destroyed non-deterministically by the collector. However, setting your reference = `Nothing` will provide a hint to .NET that the object may be garbage, and doesn't necessarily hurt anything -- aside from code clutter. If you were to keep it in there, I'd recommend removing it from `Try` block; it's already in the `Finally` block and will therefore always be called. (Aside from certain catastrophic exceptions; but in those cases it wouldn't get called in the `Try` block either!) Finally, I have to admit that I agree with Greg: Your code would be cleaner without this. The hint to the runtime that you're done with the reference is nice, but certainly not critical. Honestly, if I saw this in a code review, I'd probably have the developer rewrite it thusly: ``` Dim a as Object Dim i as Integer = 0 For i=1 to 5 a = new Object() 'Do stuff Next ```
175,544
<p>I'm trying to write a tennis reservation system and I got stucked with this problem. Let's say you have players with their prefs regarding court number, day and hour. Also every player is ranked so if there is day/hour slot and there are several players with preferences for this slot the one with top priority should be chosen. I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use. Any advice? One more thing I would prefer to use Python but some language-agnostic advice would be welcome also. Thanks!</p> <p>edit:</p> <p>some clarifications-</p> <p>the one with better priority wins and loser is moved to nearest slot, rather flexible time slots question yes, maximizing the number of people getting their most highly preffered times </p>
[ { "answer_id": 175585, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<p>This is an NP-complete problem, I think, so it'll be impossible to have a very fast algorithm for any large data sets. </p>\n\n<p>There's also the problem where you might have a schedule that is impossible to make. Given that that's not the case, something like this pseudocode is probably your best bet:</p>\n\n<pre><code>sort players by priority, highest to lowest\nstart with empty schedule\nfor player in players:\n for timeslot in player.preferences():\n if timeslot is free:\n schedule.fillslot(timeslot, player)\n break\n else:\n #if we get here, it means this player couldn't be accomodated at all.\n #you'll have to go through the slots that were filled and move another (higher-priority) player's time slot\n</code></pre>\n" }, { "answer_id": 175612, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 1, "selected": false, "text": "<p>There are several questions I'd ask before answering this queston:</p>\n\n<ul>\n<li>what happens if there is a conflict, i.e. a worse player books first, then a better player books the same court? Who wins? what happens for the loser?</li>\n<li>do you let the best players play as long as the match runs, or do you have fixed time slots?</li>\n<li>how often is the scheduling run - is it run interactively - so potentially someone could be told they can play, only to be told they can't; or is it run in a more batch manner - you put in requests, then get told later if you can have your slot. Or do users <em>set up a number of preferred times, and then the system has to maximise the number of people getting their most highly preferred times?</em></li>\n</ul>\n\n<p>As an aside, you can make it slightly less complex by re-writing the times as integer indexes (so you're dealing with integers rather than times).</p>\n" }, { "answer_id": 175683, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": -1, "selected": false, "text": "<p>Money. Allocate time slots based on who pays the most. In case of a draw don't let any of them have the slot.</p>\n" }, { "answer_id": 175697, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 2, "selected": false, "text": "<p>You are describing a matching problem. Possible references are <a href=\"http://www.cs.sunysb.edu/~algorith/files/matching.shtml\" rel=\"nofollow noreferrer\">the Stony Brook algorithm repository</a> and <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321295358\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Algorithm Design by Kleinberg and Tardos</a>. If the number of players is equal to the number of courts you can reach a stable matching - <a href=\"http://en.wikipedia.org/wiki/Stable_marriage_problem\" rel=\"nofollow noreferrer\">The Stable Marriage Problem</a>. Other formulations become harder.</p>\n" }, { "answer_id": 175831, "author": "ARKBAN", "author_id": 11889, "author_profile": "https://Stackoverflow.com/users/11889", "pm_score": 1, "selected": false, "text": "<p>I would advise using a scoring algorithm. Basically construct a formula that pulls all the values you described into a single number. Who ever has the highest final score wins that slot. For example a simple formula might be:</p>\n\n<pre><code>FinalScore = ( PlayerRanking * N1 ) + ( PlayerPreference * N2 )\n</code></pre>\n\n<p>Where N1, N2 are weights to control the formula.</p>\n\n<p>This will allow you to get good (not perfect) results very quickly. We use this approach on a much more complex system with very good results.</p>\n\n<p>You can add more variety to this by adding in factors for how many times the player has won or lost slots, or (as someone suggested) how much the player paid.</p>\n\n<p>Also, you can use multiple passes to assign slots in the day. Use one strategy where it goes chronologically, one reverse chronologically, one that does the morning first, one that does the afternoon first, etc. Then sum the scores of the players that got the spots, and then you can decide strategy provided the best results.</p>\n" }, { "answer_id": 175941, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Basically, you have the advantage that players have priorities; therefore, you sort the players by descending priority, and then you start allocating slots to them. The first gets their preferred slot, then the next takes his preferred among the free ones and so on. It's a O(N) algorithm.</p>\n" }, { "answer_id": 178185, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<h2>The basic Algorithm</h2>\n<p>I'd sort the players by their rank, as the high ranked ones always push away the low ranked ones. Then you start with the player with the highest rank, give him what he asked for (if he really is the highest, he will always win, thus you can as well give him whatever he requested). Then I would start with the second highest one. If he requested something already taken by the highest, try to find a slot nearby and assign this slot to him. Now comes the third highest one. If he requested something already taken by the highest one, move him to a slot nearby. If this slot is already taken by the second highest one, move him to a slot some further away. Continue with all other players.</p>\n<h3>Some tunings to consider:</h3>\n<p>If multiple players can have the same rank, you may need to implement some &quot;fairness&quot;. All players with equal rank will have a random order to each other if you sort them e.g. using QuickSort. You can get some some fairness, if you don't do it player for player, but rank for rank. You start with highest rank and the first player of this rank. Process his first request. However, before you process his second request, process the first request of the next player having highest rank and then of the third player having highest rank. The algorithm is the same as above, but assuming you have 10 players and player 1-4 are highest rank and players 5-7 are low and players 8-10 are very low, and every player made 3 requests, you process them as</p>\n<pre><code>Player 1 - Request 1\nPlayer 2 - Request 1\nPlayer 3 - Request 1\nPlayer 4 - Request 1\nPlayer 1 - Request 2\nPlayer 2 - Request 2\n:\n</code></pre>\n<p>That way you have some fairness. You could also choose randomly within a ranking class each time, this could also provide some fairness.</p>\n<p>You could implement fairness even across ranks. E.g. if you have 4 ranks, you could say</p>\n<pre><code>Rank 1 - 50%\nRank 2 - 25%\nRank 3 - 12,5%\nRank 4 - 6,25%\n</code></pre>\n<p>(Just example values, you may use a different key than always multiplying by 0.5, e.g. multiplying by 0.8, causing the numbers to decrease slower)</p>\n<p>Now you can say, you start processing with Rank 1, however once 50% of all Rank 1 requests have been fulfilled, you move on to Rank 2 and make sure 25% of their requests are fulfilled and so on. This way even a Rank 4 user can win over a Rank 1 user, somewhat defeating the initial algorithm, however you offer some fairness. Even a Rank 4 player can sometimes gets his request, he won't &quot;run dry&quot;. Otherwise a Rank 1 player scheduling every request on the same time as a Rank 4 player will make sure a Rank 4 player has no chance to ever get a single request. This way there is at least a small chance he may get one.</p>\n<p>After you made sure everyone had their minimal percentage processed (and the higher the rank, the more this is), you go back to top, starting with Rank 1 again and process the rest of their requests, then the rest of the Rank 2 requests and so on.</p>\n<p><strong>Last but not least:</strong> You may want to define a maximum slot offset. If a slot is taken, the application should search for the nearest slot still free. However, what if this nearest slot is very far away? If I request a slot Monday at 4 PM and the application finds the next free one to be Wednesday on 9 AM, that's not really helpful for me, is it? I might have no time on Wednesday at all. So you may limit slot search to the same day and saying the slot might be at most 3 hours off. If no slot is found within that range, cancel the request. In that case you need to inform the player &quot;We are sorry, but we could not find any nearby slot for you; please request a slot on another date/time and we will see if we can find a suitable slot there for you&quot;.</p>\n" }, { "answer_id": 4594898, "author": "Betamoo", "author_id": 279691, "author_profile": "https://Stackoverflow.com/users/279691", "pm_score": 0, "selected": false, "text": "<p>I think you should use genetic algorithm because:</p>\n\n<ul>\n<li>It is best suited for large problem instances.</li>\n<li>It yields reduced time complexity on the price of inaccurate answer(Not the ultimate best)</li>\n<li>You can specify constraints &amp; preferences easily by adjusting fitness punishments for not met ones.</li>\n<li>You can specify time limit for program execution.</li>\n<li><p>The quality of solution depends on how much time you intend to spend solving the program..</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Genetic_algorithm\" rel=\"nofollow noreferrer\">Genetic Algorithms Definition</a></p>\n\n<p><a href=\"http://www.ai-junkie.com/ga/intro/gat1.html\" rel=\"nofollow noreferrer\">Genetic Algorithms Tutorial</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/recipes/GaClassSchedule.aspx\" rel=\"nofollow noreferrer\">Class scheduling project with GA</a></p></li>\n</ul>\n\n<p>Also take a look at :<a href=\"https://stackoverflow.com/questions/2746309/best-fit-scheduling-algorithm/2749869#2749869\">a similar question</a> and <a href=\"https://stackoverflow.com/questions/573670/which-algorithm-for-assigning-shifts-discrete-optimization-problem/4594818#4594818\">another one</a></p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25587/" ]
I'm trying to write a tennis reservation system and I got stucked with this problem. Let's say you have players with their prefs regarding court number, day and hour. Also every player is ranked so if there is day/hour slot and there are several players with preferences for this slot the one with top priority should be chosen. I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use. Any advice? One more thing I would prefer to use Python but some language-agnostic advice would be welcome also. Thanks! edit: some clarifications- the one with better priority wins and loser is moved to nearest slot, rather flexible time slots question yes, maximizing the number of people getting their most highly preffered times
This is an NP-complete problem, I think, so it'll be impossible to have a very fast algorithm for any large data sets. There's also the problem where you might have a schedule that is impossible to make. Given that that's not the case, something like this pseudocode is probably your best bet: ``` sort players by priority, highest to lowest start with empty schedule for player in players: for timeslot in player.preferences(): if timeslot is free: schedule.fillslot(timeslot, player) break else: #if we get here, it means this player couldn't be accomodated at all. #you'll have to go through the slots that were filled and move another (higher-priority) player's time slot ```
175,547
<p>How you fix the following Hibernate error:</p> <p>What does "Use of the same entity name twice".</p>
[ { "answer_id": 175599, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "<p>I think it means you have declared the same entity in more than one configuration file.</p>\n\n<p>Without more information, I would try commenting out chunks of your config file so that you don't see the error, and then slowly adding sections back in until you encounter the error?</p>\n\n<p>If its only a few config files, then why not post them here? When posting, if you add 4 spaces to the front of your XML, then it will be:</p>\n\n<pre><code>&lt;xml&gt;nicely formatted&lt;/xml&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 770732, "author": "Brandon Yarbrough", "author_id": 81491, "author_profile": "https://Stackoverflow.com/users/81491", "pm_score": 0, "selected": false, "text": "<p>One of the most common mistakes you could make to produce this error is to attempt to persist two different Java classes in identically-named tables. Hibernate likes there being exactly one kind of thing in each table (with some exceptions for subclasses and the like), and so if you were to create a class called maybe StudentRecord and a class called MusicRecords, and if you then told Hibernate to persist both of those classes into a table called \"records\", you could produce that kind of exception. With that particular wording, I suspect you're using annotations (in which case it's even easier to accidentally name two tables, described in two different Java classes, the same thing).</p>\n\n<p>Hope this helps! (although perhaps not, as I have noticed just now that you asked this question 7 months ago. I do hope you're not still stuck, sir!)</p>\n" }, { "answer_id": 781782, "author": "Adam Hawkes", "author_id": 6703, "author_profile": "https://Stackoverflow.com/users/6703", "pm_score": 2, "selected": false, "text": "<p>I've come across this error a few different times. The causes were as follows:</p>\n\n<ol>\n<li>I had a duplicate mapping in my hibernate configuration (check config file/code)</li>\n<li>Two threads were attempting to build the HibernateSessionFactory object at the same time. A synchronized lock on the initialization code fixed this.</li>\n<li>An attempt to build the HibernateSessionFactory failed, but is being called again. The Hibernate Configuration object didn't get cleared out, so the entities are being processed again.</li>\n<li>You have two entity classes being mapped to the same file. Hibernate will choke on this as well.</li>\n</ol>\n" }, { "answer_id": 23336677, "author": "Misha Zadorozhnyy", "author_id": 1915382, "author_profile": "https://Stackoverflow.com/users/1915382", "pm_score": 4, "selected": false, "text": "<p>This exception occures when you have more then one @Entity with the same class's name or explicit name.\nTo fix the issue you have to set different explicit names for each entity.</p>\n\n<p>Example of error case:</p>\n\n<pre><code>package A;\n\n@Entity\nclass Cell{\n ... \n}\n\n\npackage B;\n\n@Entity\nclass Cell{\n ... \n}\n</code></pre>\n\n<p>Solution example:\n package A;</p>\n\n<pre><code>@Entity(name=\"a.Cell\")\nclass Cell{\n ... \n}\n\n\npackage B;\n\n@Entity(name=\"b.Cell\")\nclass Cell{\n ... \n}\n</code></pre>\n\n<p>So, to use them in HQL you have to write</p>\n\n<pre><code>...createQuery(\"from a.Cell\")...\n</code></pre>\n" }, { "answer_id": 27919739, "author": "Maarten van Leunen", "author_id": 415848, "author_profile": "https://Stackoverflow.com/users/415848", "pm_score": 2, "selected": false, "text": "<p>Another common mistake, is that you recently moved one of your persistence classes (from one package to another), but your IDE failed to clean up your .class files properly.</p>\n\n<p>Or some .class files are still hanging around in your Application Server.</p>\n" }, { "answer_id": 45366073, "author": "amisiuryk", "author_id": 2378369, "author_profile": "https://Stackoverflow.com/users/2378369", "pm_score": 2, "selected": false, "text": "<p>I have this error (duplicate import) recently: two entities with the same name 'MyEntity' but from different packages/modules:\ncom.test1.MyEntity\ncom.test2.MyEntity</p>\n\n<p>I didn't use them but they were loaded by hibernate to jboss.\nI wasn't allowed to change entities so I had to do some workaround.</p>\n\n<ol>\n<li>Add <code>&lt;property name=\"hibernate.auto-import\" value=\"false\"/&gt;</code> to persistance.xml. It prevented of throwing duplicate exception while deploying to jboss. But exception was thrown when my query was called.</li>\n<li>Use JPQL query. In my case it was looked like:\n<code>entityManager.createQuery(\"Select a.Name, b.name from AEntity a,\nBEntity b where a.ID = b.parentID\")</code></li>\n</ol>\n\n<p>It's ugly but it's a workaround.</p>\n" }, { "answer_id": 69659098, "author": "mr nooby noob", "author_id": 2403836, "author_profile": "https://Stackoverflow.com/users/2403836", "pm_score": 0, "selected": false, "text": "<p>I had this issue because stuff that I had stashed was still being referenced, somehow (moved my entity from one package to another and both were being referenced). Re tarting my IDE, changing branches (which did not have these changes), etc, didn't work for me. I just ended up re-cloning the repo and the error went away.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How you fix the following Hibernate error: What does "Use of the same entity name twice".
This exception occures when you have more then one @Entity with the same class's name or explicit name. To fix the issue you have to set different explicit names for each entity. Example of error case: ``` package A; @Entity class Cell{ ... } package B; @Entity class Cell{ ... } ``` Solution example: package A; ``` @Entity(name="a.Cell") class Cell{ ... } package B; @Entity(name="b.Cell") class Cell{ ... } ``` So, to use them in HQL you have to write ``` ...createQuery("from a.Cell")... ```
175,554
<p>I need to convert an arbitrary amount of milliseconds into Days, Hours, Minutes Second.</p> <p>For example: 10 Days, 5 hours, 13 minutes, 1 second.</p>
[ { "answer_id": 175565, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 2, "selected": false, "text": "<p>I would suggest using whatever date/time functions/libraries your language/framework of choice provides. Also check out string formatting functions as they often provide easy ways to pass date/timestamps and output a human readable string format.</p>\n" }, { "answer_id": 175575, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 6, "selected": false, "text": "<p>Let A be the amount of milliseconds. Then you have:</p>\n\n<pre><code>seconds=(A/1000)%60\nminutes=(A/(1000*60))%60\nhours=(A/(1000*60*60))%24\n</code></pre>\n\n<p>and so on (<code>%</code> is the modulus operator).</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 175576, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": true, "text": "<p>Well, since nobody else has stepped up, I'll write the easy code to do this:</p>\n\n<pre><code>x = ms / 1000\nseconds = x % 60\nx /= 60\nminutes = x % 60\nx /= 60\nhours = x % 24\nx /= 24\ndays = x\n</code></pre>\n\n<p>I'm just glad you stopped at days and didn't ask for months. :)</p>\n\n<p>Note that in the above, it is assumed that <code>/</code> represents truncating integer division. If you use this code in a language where <code>/</code> represents floating point division, you will need to manually truncate the results of the division as needed.</p>\n" }, { "answer_id": 175581, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>Your choices are simple:</p>\n\n<ol>\n<li>Write the code to do the conversion (ie, divide by milliSecondsPerDay to get days and use the modulus to divide by milliSecondsPerHour to get hours and use the modulus to divide by milliSecondsPerMinute and divide by 1000 for seconds. milliSecondsPerMinute = 60000, milliSecondsPerHour = 60 * milliSecondsPerMinute, milliSecondsPerDay = 24 * milliSecondsPerHour.</li>\n<li>Use an operating routine of some kind. UNIX and Windows both have structures that you can get from a Ticks or seconds type value.</li>\n</ol>\n" }, { "answer_id": 175588, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 3, "selected": false, "text": "<p>You should use the datetime functions of whatever language you're using, but, just for fun here's the code:</p>\n\n<pre><code>int milliseconds = someNumber;\n\nint seconds = milliseconds / 1000;\n\nint minutes = seconds / 60;\n\nseconds %= 60;\n\nint hours = minutes / 60;\n\nminutes %= 60;\n\nint days = hours / 24;\n\nhours %= 24;\n</code></pre>\n" }, { "answer_id": 3943656, "author": "Krolique", "author_id": 189909, "author_profile": "https://Stackoverflow.com/users/189909", "pm_score": 2, "selected": false, "text": "<pre><code>Long serverUptimeSeconds = \n (System.currentTimeMillis() - SINCE_TIME_IN_MILLISECONDS) / 1000;\n\n\nString serverUptimeText = \nString.format(\"%d days %d hours %d minutes %d seconds\",\nserverUptimeSeconds / 86400,\n( serverUptimeSeconds % 86400) / 3600 ,\n((serverUptimeSeconds % 86400) % 3600 ) / 60,\n((serverUptimeSeconds % 86400) % 3600 ) % 60\n);\n</code></pre>\n" }, { "answer_id": 8069511, "author": "David Dossot", "author_id": 387927, "author_profile": "https://Stackoverflow.com/users/387927", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://commons.apache.org/lang\">Apache Commons Lang</a> has a <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/index.html?org/apache/commons/lang3/time/DurationFormatUtils.html\">DurationFormatUtils</a> that has very helpful methods like <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/time/DurationFormatUtils.html#formatDurationWords%28long,%20boolean,%20boolean%29\">formatDurationWords</a>.</p>\n" }, { "answer_id": 8795493, "author": "iTurki", "author_id": 543711, "author_profile": "https://Stackoverflow.com/users/543711", "pm_score": 2, "selected": false, "text": "<p>This is a method I wrote. It takes an <code>integer milliseconds value</code> and returns a <code>human-readable String</code>:</p>\n\n<pre><code>public String convertMS(int ms) {\n int seconds = (int) ((ms / 1000) % 60);\n int minutes = (int) (((ms / 1000) / 60) % 60);\n int hours = (int) ((((ms / 1000) / 60) / 60) % 24);\n\n String sec, min, hrs;\n if(seconds&lt;10) sec=\"0\"+seconds;\n else sec= \"\"+seconds;\n if(minutes&lt;10) min=\"0\"+minutes;\n else min= \"\"+minutes;\n if(hours&lt;10) hrs=\"0\"+hours;\n else hrs= \"\"+hours;\n\n if(hours == 0) return min+\":\"+sec;\n else return hrs+\":\"+min+\":\"+sec;\n\n}\n</code></pre>\n" }, { "answer_id": 12420737, "author": "Nick Grealy", "author_id": 782034, "author_profile": "https://Stackoverflow.com/users/782034", "pm_score": 5, "selected": false, "text": "<p>Both solutions below use <strong>javascript</strong> (I had no idea the solution was language agnostic!). Both solutions will need to be extended if capturing durations <code>&gt; 1 month</code>.</p>\n\n<h3>Solution 1: Use the Date object</h3>\n\n<pre class=\"lang-js prettyprint-override\"><code>var date = new Date(536643021);\nvar str = '';\nstr += date.getUTCDate()-1 + \" days, \";\nstr += date.getUTCHours() + \" hours, \";\nstr += date.getUTCMinutes() + \" minutes, \";\nstr += date.getUTCSeconds() + \" seconds, \";\nstr += date.getUTCMilliseconds() + \" millis\";\nconsole.log(str);\n</code></pre>\n\n<p>Gives:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis\"\n</code></pre>\n\n<p>Libraries are helpful, but why use a library when you can re-invent the wheel! :)</p>\n\n<h3>Solution 2: Write your own parser</h3>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getDuration = function(millis){\n var dur = {};\n var units = [\n {label:\"millis\", mod:1000},\n {label:\"seconds\", mod:60},\n {label:\"minutes\", mod:60},\n {label:\"hours\", mod:24},\n {label:\"days\", mod:31}\n ];\n // calculate the individual unit values...\n units.forEach(function(u){\n millis = (millis - (dur[u.label] = (millis % u.mod))) / u.mod;\n });\n // convert object to a string representation...\n var nonZero = function(u){ return dur[u.label]; };\n dur.toString = function(){\n return units\n .reverse()\n .filter(nonZero)\n .map(function(u){\n return dur[u.label] + \" \" + (dur[u.label]==1?u.label.slice(0,-1):u.label);\n })\n .join(', ');\n };\n return dur;\n};\n</code></pre>\n\n<p>Creates a \"duration\" object, with whatever fields you require.\nFormatting a timestamp then becomes simple...</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>console.log(getDuration(536643021).toString());\n</code></pre>\n\n<p>Gives:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis\"\n</code></pre>\n" }, { "answer_id": 12668818, "author": "AK Joshi", "author_id": 1670594, "author_profile": "https://Stackoverflow.com/users/1670594", "pm_score": 0, "selected": false, "text": "<p>Here is more precise method in JAVA , I have implemented this simple logic , hope this will help you:</p>\n\n<pre><code> public String getDuration(String _currentTimemilliSecond)\n {\n long _currentTimeMiles = 1; \n int x = 0;\n int seconds = 0;\n int minutes = 0;\n int hours = 0;\n int days = 0;\n int month = 0;\n int year = 0;\n\n try \n {\n _currentTimeMiles = Long.parseLong(_currentTimemilliSecond);\n /** x in seconds **/ \n x = (int) (_currentTimeMiles / 1000) ; \n seconds = x ;\n\n if(seconds &gt;59)\n {\n minutes = seconds/60 ;\n\n if(minutes &gt; 59)\n {\n hours = minutes/60;\n\n if(hours &gt; 23)\n {\n days = hours/24 ;\n\n if(days &gt; 30)\n {\n month = days/30;\n\n if(month &gt; 11)\n {\n year = month/12;\n\n Log.d(\"Year\", year);\n Log.d(\"Month\", month%12);\n Log.d(\"Days\", days % 30);\n Log.d(\"hours \", hours % 24);\n Log.d(\"Minutes \", minutes % 60);\n Log.d(\"Seconds \", seconds % 60); \n\n return \"Year \"+year + \" Month \"+month%12 +\" Days \" +days%30 +\" hours \"+hours%24 +\" Minutes \"+minutes %60+\" Seconds \"+seconds%60;\n }\n else\n {\n Log.d(\"Month\", month);\n Log.d(\"Days\", days % 30);\n Log.d(\"hours \", hours % 24);\n Log.d(\"Minutes \", minutes % 60);\n Log.d(\"Seconds \", seconds % 60); \n\n return \"Month \"+month +\" Days \" +days%30 +\" hours \"+hours%24 +\" Minutes \"+minutes %60+\" Seconds \"+seconds%60;\n }\n\n }\n else\n {\n Log.d(\"Days\", days );\n Log.d(\"hours \", hours % 24);\n Log.d(\"Minutes \", minutes % 60);\n Log.d(\"Seconds \", seconds % 60); \n\n return \"Days \" +days +\" hours \"+hours%24 +\" Minutes \"+minutes %60+\" Seconds \"+seconds%60;\n }\n\n }\n else\n {\n Log.d(\"hours \", hours);\n Log.d(\"Minutes \", minutes % 60);\n Log.d(\"Seconds \", seconds % 60);\n\n return \"hours \"+hours+\" Minutes \"+minutes %60+\" Seconds \"+seconds%60;\n }\n }\n else\n {\n Log.d(\"Minutes \", minutes);\n Log.d(\"Seconds \", seconds % 60);\n\n return \"Minutes \"+minutes +\" Seconds \"+seconds%60;\n }\n }\n else\n {\n Log.d(\"Seconds \", x);\n return \" Seconds \"+seconds;\n }\n }\n catch (Exception e) \n {\n Log.e(getClass().getName().toString(), e.toString());\n }\n return \"\";\n }\n\n private Class Log\n {\n public static void d(String tag , int value)\n {\n System.out.println(\"##### [ Debug ] ## \"+tag +\" :: \"+value);\n }\n }\n</code></pre>\n" }, { "answer_id": 13151858, "author": "Rajiv", "author_id": 302303, "author_profile": "https://Stackoverflow.com/users/302303", "pm_score": 2, "selected": false, "text": "<pre><code>function convertTime(time) { \n var millis= time % 1000;\n time = parseInt(time/1000);\n var seconds = time % 60;\n time = parseInt(time/60);\n var minutes = time % 60;\n time = parseInt(time/60);\n var hours = time % 24;\n var out = \"\";\n if(hours &amp;&amp; hours &gt; 0) out += hours + \" \" + ((hours == 1)?\"hr\":\"hrs\") + \" \";\n if(minutes &amp;&amp; minutes &gt; 0) out += minutes + \" \" + ((minutes == 1)?\"min\":\"mins\") + \" \";\n if(seconds &amp;&amp; seconds &gt; 0) out += seconds + \" \" + ((seconds == 1)?\"sec\":\"secs\") + \" \";\n if(millis&amp;&amp; millis&gt; 0) out += millis+ \" \" + ((millis== 1)?\"msec\":\"msecs\") + \" \";\n return out.trim();\n}\n</code></pre>\n" }, { "answer_id": 13376991, "author": "Rafal Pastuszak", "author_id": 969813, "author_profile": "https://Stackoverflow.com/users/969813", "pm_score": 1, "selected": false, "text": "<p>I'm not able to comment first answer to your question, but there's a small mistake. You should use parseInt or Math.floor to convert floating point numbers to integer, i</p>\n\n<pre><code>var days, hours, minutes, seconds, x;\nx = ms / 1000;\nseconds = Math.floor(x % 60);\nx /= 60;\nminutes = Math.floor(x % 60);\nx /= 60;\nhours = Math.floor(x % 24);\nx /= 24;\ndays = Math.floor(x);\n</code></pre>\n\n<p>Personally, I use CoffeeScript in my projects and my code looks like that:</p>\n\n<pre><code>getFormattedTime : (ms)-&gt;\n x = ms / 1000\n seconds = Math.floor x % 60\n x /= 60\n minutes = Math.floor x % 60\n x /= 60\n hours = Math.floor x % 24\n x /= 24\n days = Math.floor x\n formattedTime = \"#{seconds}s\"\n if minutes then formattedTime = \"#{minutes}m \" + formattedTime\n if hours then formattedTime = \"#{hours}h \" + formattedTime\n formattedTime \n</code></pre>\n" }, { "answer_id": 16715577, "author": "ssamuel68", "author_id": 1178789, "author_profile": "https://Stackoverflow.com/users/1178789", "pm_score": 1, "selected": false, "text": "<p>This is a solution. Later you can split by \":\" and take the values of the array</p>\n\n<pre><code>/**\n * Converts milliseconds to human readeable language separated by \":\"\n * Example: 190980000 --&gt; 2:05:3 --&gt; 2days 5hours 3min\n */\nfunction dhm(t){\n var cd = 24 * 60 * 60 * 1000,\n ch = 60 * 60 * 1000,\n d = Math.floor(t / cd),\n h = '0' + Math.floor( (t - d * cd) / ch),\n m = '0' + Math.round( (t - d * cd - h * ch) / 60000);\n return [d, h.substr(-2), m.substr(-2)].join(':');\n}\n\nvar delay = 190980000; \nvar fullTime = dhm(delay);\nconsole.log(fullTime);\n</code></pre>\n" }, { "answer_id": 17352661, "author": "Asit", "author_id": 2529686, "author_profile": "https://Stackoverflow.com/users/2529686", "pm_score": 2, "selected": false, "text": "<pre><code>Long expireTime = 69l;\nLong tempParam = 0l;\n\nLong seconds = math.mod(expireTime, 60);\ntempParam = expireTime - seconds;\nexpireTime = tempParam/60;\nLong minutes = math.mod(expireTime, 60);\ntempParam = expireTime - minutes;\nexpireTime = expireTime/60;\nLong hours = math.mod(expireTime, 24);\ntempParam = expireTime - hours;\nexpireTime = expireTime/24;\nLong days = math.mod(expireTime, 30);\n\nsystem.debug(days + '.' + hours + ':' + minutes + ':' + seconds);\n</code></pre>\n\n<p>This should print: 0.0:1:9</p>\n" }, { "answer_id": 24576327, "author": "dafunker", "author_id": 1765329, "author_profile": "https://Stackoverflow.com/users/1765329", "pm_score": 1, "selected": false, "text": "<p>Here's my solution using TimeUnit.</p>\n\n<p>UPDATE: I should point out that this is written in groovy, but Java is almost identical.</p>\n\n<pre><code>def remainingStr = \"\"\n\n/* Days */\nint days = MILLISECONDS.toDays(remainingTime) as int\nremainingStr += (days == 1) ? '1 Day : ' : \"${days} Days : \"\nremainingTime -= DAYS.toMillis(days)\n\n/* Hours */\nint hours = MILLISECONDS.toHours(remainingTime) as int\nremainingStr += (hours == 1) ? '1 Hour : ' : \"${hours} Hours : \"\nremainingTime -= HOURS.toMillis(hours)\n\n/* Minutes */\nint minutes = MILLISECONDS.toMinutes(remainingTime) as int\nremainingStr += (minutes == 1) ? '1 Minute : ' : \"${minutes} Minutes : \"\nremainingTime -= MINUTES.toMillis(minutes)\n\n/* Seconds */\nint seconds = MILLISECONDS.toSeconds(remainingTime) as int\nremainingStr += (seconds == 1) ? '1 Second' : \"${seconds} Seconds\"\n</code></pre>\n" }, { "answer_id": 28004110, "author": "yorg", "author_id": 3225970, "author_profile": "https://Stackoverflow.com/users/3225970", "pm_score": 1, "selected": false, "text": "<p>A flexible way to do it :<br>\n(Not made for current date but good enough for durations)</p>\n\n<pre><code>/**\nconvert duration to a ms/sec/min/hour/day/week array\n@param {int} msTime : time in milliseconds \n@param {bool} fillEmpty(optional) : fill array values even when they are 0.\n@param {string[]} suffixes(optional) : add suffixes to returned values.\n values are filled with missings '0'\n@return {int[]/string[]} : time values from higher to lower(ms) range.\n*/\nvar msToTimeList=function(msTime,fillEmpty,suffixes){\n suffixes=(suffixes instanceof Array)?suffixes:[]; //suffixes is optional\n var timeSteps=[1000,60,60,24,7]; // time ranges : ms/sec/min/hour/day/week\n timeSteps.push(1000000); //add very big time at the end to stop cutting\n var result=[];\n for(var i=0;(msTime&gt;0||i&lt;1||fillEmpty)&amp;&amp;i&lt;timeSteps.length;i++){\n var timerange = msTime%timeSteps[i];\n if(typeof(suffixes[i])==\"string\"){\n timerange+=suffixes[i]; // add suffix (converting )\n // and fill zeros :\n while( i&lt;timeSteps.length-1 &amp;&amp;\n timerange.length&lt;((timeSteps[i]-1)+suffixes[i]).length )\n timerange=\"0\"+timerange;\n }\n result.unshift(timerange); // stack time range from higher to lower\n msTime = Math.floor(msTime/timeSteps[i]);\n }\n return result;\n};\n</code></pre>\n\n<p>NB : you could also set <strong>timeSteps</strong> as parameter if you want to control the time ranges. </p>\n\n<p>how to use (copy an test):</p>\n\n<pre><code>var elsapsed = Math.floor(Math.random()*3000000000);\n\nconsole.log( \"elsapsed (labels) = \"+\n msToTimeList(elsapsed,false,[\"ms\",\"sec\",\"min\",\"h\",\"days\",\"weeks\"]).join(\"/\") );\n\nconsole.log( \"half hour : \"+msToTimeList(elsapsed,true)[3]&lt;30?\"first\":\"second\" );\n\nconsole.log( \"elsapsed (classic) = \"+\n msToTimeList(elsapsed,false,[\"\",\"\",\"\",\"\",\"\",\"\"]).join(\" : \") );\n</code></pre>\n" }, { "answer_id": 28065258, "author": "Pavel Blagodov", "author_id": 848524, "author_profile": "https://Stackoverflow.com/users/848524", "pm_score": 2, "selected": false, "text": "<p>Why just don't do something like this:</p>\n\n<p>var ms = 86400;</p>\n\n<p>var seconds = ms / 1000; //86.4</p>\n\n<p>var minutes = seconds / 60; //1.4400000000000002</p>\n\n<p>var hours = minutes / 60; //0.024000000000000004</p>\n\n<p>var days = hours / 24; //0.0010000000000000002</p>\n\n<p>And dealing with float precision e.g. Number(minutes.toFixed(5)) //1.44</p>\n" }, { "answer_id": 29181707, "author": "Vishal Makasana", "author_id": 2626901, "author_profile": "https://Stackoverflow.com/users/2626901", "pm_score": 1, "selected": false, "text": "<p>I suggest to use <a href=\"http://www.ocpsoft.org/prettytime/\" rel=\"nofollow\">http://www.ocpsoft.org/prettytime/</a> library..</p>\n\n<p>it's very simple to get time interval in human readable form like</p>\n\n<p><code>PrettyTime p = new PrettyTime();\n System.out.println(p.format(new Date()));</code></p>\n\n<p>it will print like \"moments from now\"</p>\n\n<p>other example </p>\n\n<p><code>PrettyTime p = new PrettyTime());\n Date d = new Date(System.currentTimeMillis());\n d.setHours(d.getHours() - 1);\n String ago = p.format(d);</code></p>\n\n<p>then string ago = \"1 hour ago\"</p>\n" }, { "answer_id": 38934961, "author": "Camilo Silva", "author_id": 766855, "author_profile": "https://Stackoverflow.com/users/766855", "pm_score": 2, "selected": false, "text": "<p>In java</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static String formatMs(long millis) {\n long hours = TimeUnit.MILLISECONDS.toHours(millis);\n long mins = TimeUnit.MILLISECONDS.toMinutes(millis);\n long secs = TimeUnit.MILLISECONDS.toSeconds(millis);\n return String.format(\"%dh %d min, %d sec\",\n hours,\n mins - TimeUnit.HOURS.toMinutes(hours),\n secs - TimeUnit.MINUTES.toSeconds(mins)\n );\n}\n</code></pre>\n\n<p>Gives something like this:</p>\n\n<pre><code>12h 1 min, 34 sec\n</code></pre>\n" }, { "answer_id": 64721281, "author": "bougui", "author_id": 1679629, "author_profile": "https://Stackoverflow.com/users/1679629", "pm_score": 0, "selected": false, "text": "<p>A solution using <code>awk</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ ms=10000001; awk -v ms=$ms 'BEGIN {x=ms/1000; \n s=x%60; x/=60;\n m=x%60; x/=60;\n h=x%60;\n printf(&quot;%02d:%02d:%02d.%03d\\n&quot;, h, m, s, ms%1000)}'\n02:46:40.001\n</code></pre>\n" }, { "answer_id": 64800061, "author": "keocra", "author_id": 2019601, "author_profile": "https://Stackoverflow.com/users/2019601", "pm_score": 1, "selected": false, "text": "<p>In python 3 you could achieve your goal by using the following snippet:</p>\n<pre><code>from datetime import timedelta\n\nms = 536643021\ntd = timedelta(milliseconds=ms)\n\nprint(str(td))\n# --&gt; 6 days, 5:04:03.021000\n</code></pre>\n<p>Timedelta documentation: <a href=\"https://docs.python.org/3/library/datetime.html#datetime.timedelta\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/datetime.html#datetime.timedelta</a></p>\n<p>Source of the __str__ method of timedelta str: <a href=\"https://github.com/python/cpython/blob/33922cb0aa0c81ebff91ab4e938a58dfec2acf19/Lib/datetime.py#L607\" rel=\"nofollow noreferrer\">https://github.com/python/cpython/blob/33922cb0aa0c81ebff91ab4e938a58dfec2acf19/Lib/datetime.py#L607</a></p>\n" }, { "answer_id": 68988002, "author": "Jonathan", "author_id": 2407212, "author_profile": "https://Stackoverflow.com/users/2407212", "pm_score": 0, "selected": false, "text": "<p>This one leaves out 0 values. With tests.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const toTimeString = (value, singularName) =&gt;\n `${value} ${singularName}${value !== 1 ? 's' : ''}`;\n\nconst readableTime = (ms) =&gt; {\n const days = Math.floor(ms / (24 * 60 * 60 * 1000));\n const daysMs = ms % (24 * 60 * 60 * 1000);\n const hours = Math.floor(daysMs / (60 * 60 * 1000));\n const hoursMs = ms % (60 * 60 * 1000);\n const minutes = Math.floor(hoursMs / (60 * 1000));\n const minutesMs = ms % (60 * 1000);\n const seconds = Math.round(minutesMs / 1000);\n\n const data = [\n [days, 'day'],\n [hours, 'hour'],\n [minutes, 'minute'],\n [seconds, 'second'],\n ];\n\n return data\n .filter(([value]) =&gt; value &gt; 0)\n .map(([value, name]) =&gt; toTimeString(value, name))\n .join(', ');\n};\n\n// Tests\nconst hundredDaysTwentyHoursFiftyMinutesThirtySeconds = 8715030000;\nconst oneDayTwoHoursEightMinutesTwelveSeconds = 94092000;\nconst twoHoursFiftyMinutes = 10200000;\nconst oneMinute = 60000;\nconst fortySeconds = 40000;\nconst oneSecond = 1000;\nconst oneDayTwelveSeconds = 86412000;\n\nconst test = (result, expected) =&gt; {\n console.log(expected, '- ' + (result === expected));\n};\n\ntest(readableTime(\n hundredDaysTwentyHoursFiftyMinutesThirtySeconds\n), '100 days, 20 hours, 50 minutes, 30 seconds');\n\ntest(readableTime(\n oneDayTwoHoursEightMinutesTwelveSeconds\n), '1 day, 2 hours, 8 minutes, 12 seconds');\n\ntest(readableTime(\n twoHoursFiftyMinutes\n), '2 hours, 50 minutes');\n\ntest(readableTime(\n oneMinute\n), '1 minute');\n\ntest(readableTime(\n fortySeconds\n), '40 seconds');\n\ntest(readableTime(\n oneSecond\n), '1 second');\n\ntest(readableTime(\n oneDayTwelveSeconds\n), '1 day, 12 seconds');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I need to convert an arbitrary amount of milliseconds into Days, Hours, Minutes Second. For example: 10 Days, 5 hours, 13 minutes, 1 second.
Well, since nobody else has stepped up, I'll write the easy code to do this: ``` x = ms / 1000 seconds = x % 60 x /= 60 minutes = x % 60 x /= 60 hours = x % 24 x /= 24 days = x ``` I'm just glad you stopped at days and didn't ask for months. :) Note that in the above, it is assumed that `/` represents truncating integer division. If you use this code in a language where `/` represents floating point division, you will need to manually truncate the results of the division as needed.
175,621
<p>I want completely automated integration testing for a Maven project. The integration tests require that an external (platform-dependent) program is started before running. Ideally, the external program would be killed after the unit tests are finished, but is not necessary. </p> <p>Is there a Maven plugin to accomplish this? Other ideas?</p>
[ { "answer_id": 175664, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "<p>You could use the <a href=\"http://maven.apache.org/plugins/maven-antrun-plugin/\" rel=\"nofollow noreferrer\">antrun</a> plugin. Inside you would use ant's <strike><a href=\"http://ant.apache.org/manual/Tasks/exec.html\" rel=\"nofollow noreferrer\">exec</a></strike> <a href=\"http://ant.apache.org/manual/Tasks/apply.html\" rel=\"nofollow noreferrer\">apply</a> task.</p>\n\n<p>Something like this.</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;\n &lt;version&gt;1.2&lt;/version&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt; &lt;!-- a lifecycle phase --&gt; &lt;/phase&gt;\n &lt;configuration&gt;\n\n &lt;tasks&gt;\n &lt;apply os=\"unix\" executable=\"cmd\"&gt;\n &lt;arg value=\"/c\"/&gt;\n &lt;arg value=\"ant.bat\"/&gt;\n &lt;arg value=\"-p\"/&gt;\n &lt;/apply&gt;\n &lt;apply os=\"windows\" executable=\"cmd.exe\"&gt;\n &lt;arg value=\"/c\"/&gt;\n &lt;arg value=\"ant.bat\"/&gt;\n &lt;arg value=\"-p\"/&gt;\n &lt;/apply&gt;\n &lt;/tasks&gt;\n\n &lt;/configuration&gt;\n &lt;goals&gt;\n &lt;goal&gt;run&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n</code></pre>\n\n<p><strike>Ant support os specific commands of course through the <a href=\"http://ant.apache.org/manual/Tasks/condition.html\" rel=\"nofollow noreferrer\">condition task</a>.</strike></p>\n" }, { "answer_id": 175790, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "<p>I'm currently working on a more specific plugin that could easily be \"degraded\" to be a simple external task executer but ... there are quite a few other things to consider.</p>\n\n<ol>\n<li>How do you know the process has actually started?</li>\n<li>What do you do with the return code?</li>\n<li>How do you make sure the executor plugin runs first (bind it to the test-compile phase)?</li>\n</ol>\n\n<p>I'm sure there would be more if I actually started developing the plugin, but is there really a need for a generic executer?</p>\n\n<p>UPDATE:</p>\n\n<p>I guess there is ... there's an excellent set of Maven plugins at CodeHaus. Here's the one you want: <a href=\"http://mojohaus.org/exec-maven-plugin/\" rel=\"nofollow noreferrer\">http://mojohaus.org/exec-maven-plugin/</a>.</p>\n" }, { "answer_id": 176308, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 0, "selected": false, "text": "<p>Do you want to start an application server ? Have a look at <a href=\"http://cargo.codehaus.org/\" rel=\"nofollow noreferrer\">Cargo</a> and its <a href=\"http://cargo.codehaus.org/Maven2+plugin\" rel=\"nofollow noreferrer\">Maven plugin</a>.</p>\n" }, { "answer_id": 176345, "author": "heckj", "author_id": 19477, "author_profile": "https://Stackoverflow.com/users/19477", "pm_score": 2, "selected": false, "text": "<p>The cargo maven plugin is a good way to go if you're doing servlet development and want to deploy the resulting WAR for integration testing.</p>\n\n<p>When I do this myself, I often set up a multi-module project (although that's not strictly nessecarily) and encapsulate all the integration testing into that one module. I then enable the module with profiles (or not) so that it's not blocking the immediate \"yeah, I know I broke it\" builds.</p>\n\n<p>Here's the pom from that functional test module - make of it what you will:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;&lt;project&gt;\n &lt;parent&gt;\n &lt;artifactId&gt;maven-example&lt;/artifactId&gt;\n &lt;groupId&gt;com.jheck&lt;/groupId&gt;\n &lt;version&gt;1.5.0.4-SNAPSHOT&lt;/version&gt;\n &lt;/parent&gt;\n &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;\n &lt;groupId&gt;com.jheck.example&lt;/groupId&gt;\n &lt;artifactId&gt;functional-test&lt;/artifactId&gt;\n &lt;name&gt;Example Functional Test&lt;/name&gt;\n &lt;packaging&gt;pom&lt;/packaging&gt;\n\n &lt;dependencies&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;com.jheck.example&lt;/groupId&gt;\n &lt;artifactId&gt;example-war&lt;/artifactId&gt;\n &lt;type&gt;war&lt;/type&gt;\n &lt;scope&gt;provided&lt;/scope&gt;\n &lt;version&gt;LATEST&lt;/version&gt;\n &lt;/dependency&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;httpunit&lt;/groupId&gt;\n &lt;artifactId&gt;httpunit&lt;/artifactId&gt;\n &lt;version&gt;1.6.1&lt;/version&gt;\n &lt;scope&gt;test&lt;/scope&gt;\n &lt;/dependency&gt;\n &lt;/dependencies&gt;\n\n &lt;build&gt;\n &lt;plugins&gt;\n\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;goals&gt;\n &lt;goal&gt;testCompile&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;integration-test&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;test&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n\n &lt;plugin&gt;\n &lt;groupId&gt;org.codehaus.cargo&lt;/groupId&gt;\n &lt;artifactId&gt;cargo-maven2-plugin&lt;/artifactId&gt;\n &lt;version&gt;0.3&lt;/version&gt;\n &lt;configuration&gt;\n &lt;wait&gt;false&lt;/wait&gt; &lt;!-- don't pause on launching tomcat... --&gt;\n &lt;container&gt;\n &lt;containerId&gt;tomcat5x&lt;/containerId&gt;\n &lt;log&gt;${project.build.directory}/cargo.log&lt;/log&gt;\n &lt;zipUrlInstaller&gt;\n &lt;!--\n &lt;url&gt;http://www.apache.org/dist/tomcat/tomcat-5/v5.0.30/bin/jakarta-tomcat-5.0.30.zip&lt;/url&gt;\n --&gt;\n &lt;!-- better be using Java 1.5... --&gt;\n &lt;url&gt;http://www.apache.org/dist/tomcat/tomcat-5/v5.5.26/bin/apache-tomcat-5.5.26.zip&lt;/url&gt;\n\n &lt;installDir&gt;${installDir}&lt;/installDir&gt;\n &lt;/zipUrlInstaller&gt;\n &lt;/container&gt;\n &lt;configuration&gt;\n &lt;!-- where the running instance will be deployed for testing --&gt;\n &lt;home&gt;${project.build.directory}/tomcat5x/container&lt;/home&gt;\n &lt;/configuration&gt;\n &lt;/configuration&gt;\n\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;start-container&lt;/id&gt;\n &lt;phase&gt;pre-integration-test&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;start&lt;/goal&gt;\n &lt;goal&gt;deploy&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;deployer&gt;\n &lt;deployables&gt;\n &lt;deployable&gt;\n &lt;groupId&gt;com.jheck.example&lt;/groupId&gt;\n &lt;artifactId&gt;example-war&lt;/artifactId&gt;\n &lt;type&gt;war&lt;/type&gt;\n &lt;!-- &lt;properties&gt;\n &lt;plan&gt;${basedir}/src/deployment/geronima.plan.xml&lt;/plan&gt;\n &lt;/properties&gt; --&gt;\n &lt;pingURL&gt;http://localhost:8080/example-war&lt;/pingURL&gt;\n &lt;/deployable&gt;\n &lt;/deployables&gt;\n &lt;/deployer&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;execution&gt;\n &lt;id&gt;stop-container&lt;/id&gt;\n &lt;phase&gt;post-integration-test&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;stop&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n\n&lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 7164868, "author": "Jared", "author_id": 745412, "author_profile": "https://Stackoverflow.com/users/745412", "pm_score": 1, "selected": false, "text": "<p>You probably want to bind your actual integration tests to the integration-test phase of the maven lifecycle. If you use a plugin that fails safe (like the aptly named failsafe plugin) to do the actual testing, you can then run your phases like this:</p>\n\n<p><strong>pre-integration-test</strong>: start external application (using the exec plugin or one of the other suggestions here)</p>\n\n<p><strong>integration-test</strong>: Run the actual integration tests using the failsafe plugin</p>\n\n<p><strong>post-integration-test</strong>: Shut down the external application and do any other necessary cleanup</p>\n\n<p><strong>verify</strong>: Have the failsafe plugin verify the results of the test and fail the build at this point</p>\n\n<p>It's fairly straightforward to use the exec plugin, the trick is to get your application started up <strong>in the background</strong>. You should be careful to make sure that the app is fully up before starting the tests in the next phase. Unfortunately, getting your application up and making sure it's up enough while running in the background is not always a trivial task, and the specifics of how to do that depend on your application. It often involves custom code in the application.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12880/" ]
I want completely automated integration testing for a Maven project. The integration tests require that an external (platform-dependent) program is started before running. Ideally, the external program would be killed after the unit tests are finished, but is not necessary. Is there a Maven plugin to accomplish this? Other ideas?
You could use the [antrun](http://maven.apache.org/plugins/maven-antrun-plugin/) plugin. Inside you would use ant's [exec](http://ant.apache.org/manual/Tasks/exec.html) [apply](http://ant.apache.org/manual/Tasks/apply.html) task. Something like this. ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.2</version> <executions> <execution> <phase> <!-- a lifecycle phase --> </phase> <configuration> <tasks> <apply os="unix" executable="cmd"> <arg value="/c"/> <arg value="ant.bat"/> <arg value="-p"/> </apply> <apply os="windows" executable="cmd.exe"> <arg value="/c"/> <arg value="ant.bat"/> <arg value="-p"/> </apply> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> ``` Ant support os specific commands of course through the [condition task](http://ant.apache.org/manual/Tasks/condition.html).
175,649
<p>I'm working on a project where I have 2 web services that need the same entity. The 2 web services are on the same server so on the back-end, they share the same classes. </p> <p>On the front-end side, my code consumes <em>both</em> web services and sees the entities from both services as separate (in different namespaces) so I can't use the entity across both services.</p> <p>Does anyone know of a way to allow this to work in .NET 2.0?</p> <p>I've done this with my entity: </p> <pre><code>[XmlType(TypeName = "Class1", Namespace = "myNamespace")] public class Class1 { public int field; } </code></pre> <p>Hoping that my IDE would somehow "know" that the class is the same on both web services so that it wouldn't create separate entities for both classes, but no luck.</p> <p>Is this possible to do with .NET 2.0 web services?</p>
[ { "answer_id": 175744, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "<p>I'm not sure about the implementation details with .NET 2.0, but I believe what you want to do is put the common classes in a seperate XSD file and refer to it from within your two WSDL's. This way, the common types have the same namespace between the two services.</p>\n\n<p>Now, how you do this in .NET 2.0 I couldn't give you the specifics on...</p>\n" }, { "answer_id": 175772, "author": "sajidnizami", "author_id": 9498, "author_profile": "https://Stackoverflow.com/users/9498", "pm_score": 0, "selected": false, "text": "<p>Can you check the namespace of the entity? Make sure it is the same in both the web services. </p>\n" }, { "answer_id": 175855, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "<p>I think that you can not do that from inside VS but you can manually use the <code>wsdl.exe</code> utility like this:</p>\n\n<pre><code>wsdl.exe /sharetypes http://localhost/MyService1.asmx?wsdl http://localhost/MyService2.asmx?wsdl\n</code></pre>\n\n<p>Notice the <code>/sharetypes</code> option which turns on the type sharing feature. This feature creates one code file with a single type definition for identical types shared between different services (the namespace, name, and wire signature must be identical). </p>\n\n<p>More info:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx\" rel=\"nofollow noreferrer\">Web Services Description Language tool</a></li>\n<li><a href=\"http://weblogs.asp.net/israelio/archive/2005/01/04/346337.aspx\" rel=\"nofollow noreferrer\">Framework 2.0 - WebServices Shared Types</a></li>\n</ul>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I'm working on a project where I have 2 web services that need the same entity. The 2 web services are on the same server so on the back-end, they share the same classes. On the front-end side, my code consumes *both* web services and sees the entities from both services as separate (in different namespaces) so I can't use the entity across both services. Does anyone know of a way to allow this to work in .NET 2.0? I've done this with my entity: ``` [XmlType(TypeName = "Class1", Namespace = "myNamespace")] public class Class1 { public int field; } ``` Hoping that my IDE would somehow "know" that the class is the same on both web services so that it wouldn't create separate entities for both classes, but no luck. Is this possible to do with .NET 2.0 web services?
I think that you can not do that from inside VS but you can manually use the `wsdl.exe` utility like this: ``` wsdl.exe /sharetypes http://localhost/MyService1.asmx?wsdl http://localhost/MyService2.asmx?wsdl ``` Notice the `/sharetypes` option which turns on the type sharing feature. This feature creates one code file with a single type definition for identical types shared between different services (the namespace, name, and wire signature must be identical). More info: * [Web Services Description Language tool](http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx) * [Framework 2.0 - WebServices Shared Types](http://weblogs.asp.net/israelio/archive/2005/01/04/346337.aspx)
175,655
<p>We recently had a problem where, after a series of commits had occurred, a backend process failed to run. Now, we were good little boys and girls and ran <code>rake test</code> after every check-in but, due to some oddities in Rails' library loading, it only occurred when we ran it directly from Mongrel in production mode.</p> <p>I tracked the bug down and it was due to a new Rails gem overwriting a method in the String class in a way that broke one narrow use in the runtime Rails code.</p> <p>Anyway, long story short, is there a way, at runtime, to ask Ruby where a method has been defined? Something like <code>whereami( :foo )</code> that returns <code>/path/to/some/file.rb line #45</code>? In this case, telling me that it was defined in class String would be unhelpful, because it was overloaded by some library. </p> <p>I cannot guarantee the source lives in my project, so grepping for <code>'def foo'</code> won't necessarily give me what I need, not to mention if I have <em>many</em> <code>def foo</code>'s, sometimes I don't know until runtime which one I may be using.</p>
[ { "answer_id": 175946, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 3, "selected": false, "text": "<p>This may help but you would have to code it yourself. Pasted from the blog:</p>\n\n<blockquote>\n <p>Ruby provides a method_added()\n callback that is invoked every time a\n method is added or redefined within a\n class. It’s part of the Module class,\n and every Class is a Module. There are\n also two related callbacks called\n method_removed() and\n method_undefined().</p>\n</blockquote>\n\n<p><a href=\"http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby\" rel=\"noreferrer\">http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby</a></p>\n" }, { "answer_id": 175947, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>If you can crash the method, you'll get a backtrace which will tell you exactly where it is.</p>\n\n<p>Unfortunately, if you can't crash it then you can't find out where it has been defined. If you attempt to monkey with the method by overwriting it or overriding it, then any crash will come from your overwritten or overridden method, and it won't be any use.</p>\n\n<p>Useful ways of crashing methods:</p>\n\n<ol>\n<li>Pass <code>nil</code> where it forbids it - a lot of the time the method will raise an <code>ArgumentError</code> or the ever-present <code>NoMethodError</code> on a nil class.</li>\n<li>If you have inside knowledge of the method, and you know that the method in turn calls some other method, then you can overrwrite the other method, and raise inside that.</li>\n</ol>\n" }, { "answer_id": 176006, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 2, "selected": false, "text": "<p>You might be able to do something like this:</p>\n\n<p>foo_finder.rb:</p>\n\n<pre><code> class String\n def String.method_added(name)\n if (name==:foo)\n puts \"defining #{name} in:\\n\\t\"\n puts caller.join(\"\\n\\t\")\n end\n end\n end\n</code></pre>\n\n<p>Then ensure foo_finder is loaded first with something like </p>\n\n<pre><code>ruby -r foo_finder.rb railsapp\n</code></pre>\n\n<p>(I've only messed with rails, so I don't know exactly, but I imagine there's a way to start it sort of like this.)</p>\n\n<p>This will show you all the re-definitions of String#foo. With a little meta-programming, you could generalize it for whatever function you want. But it does need to be loaded BEFORE the file that actually does the re-definition.</p>\n" }, { "answer_id": 177285, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can always get a backtrace of where you are by using <code>caller()</code>.</p>\n" }, { "answer_id": 660129, "author": "wesgarrison", "author_id": 62140, "author_profile": "https://Stackoverflow.com/users/62140", "pm_score": 10, "selected": true, "text": "<p>This is really late, but here's how you can find where a method is defined:</p>\n\n<p><a href=\"http://gist.github.com/76951\" rel=\"noreferrer\">http://gist.github.com/76951</a></p>\n\n<pre><code># How to find out where a method comes from.\n# Learned this from Dave Thomas while teaching Advanced Ruby Studio\n# Makes the case for separating method definitions into\n# modules, especially when enhancing built-in classes.\nmodule Perpetrator\n def crime\n end\nend\n\nclass Fixnum\n include Perpetrator\nend\n\np 2.method(:crime) # The \"2\" here is an instance of Fixnum.\n#&lt;Method: Fixnum(Perpetrator)#crime&gt;\n</code></pre>\n\n<p>If you're on Ruby 1.9+, you can use <a href=\"http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-source_location\" rel=\"noreferrer\"><code>source_location</code></a></p>\n\n<pre><code>require 'csv'\n\np CSV.new('string').method(:flock)\n# =&gt; #&lt;Method: CSV#flock&gt;\n\nCSV.new('string').method(:flock).source_location\n# =&gt; [\"/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb\", 180]\n</code></pre>\n\n<p>Note that this won't work on everything, like native compiled code. The <a href=\"http://www.ruby-doc.org/core-1.9.3/Method.html\" rel=\"noreferrer\">Method class</a> has some neat functions, too, like <a href=\"http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-owner\" rel=\"noreferrer\">Method#owner</a> which returns the file where the method is defined.</p>\n\n<p>EDIT: Also see the <code>__file__</code> and <code>__line__</code> and notes for REE in the other answer, they're handy too. -- wg</p>\n" }, { "answer_id": 2836679, "author": "tig", "author_id": 96823, "author_profile": "https://Stackoverflow.com/users/96823", "pm_score": 2, "selected": false, "text": "<p>Very late answer :) But earlier answers did not help me</p>\n\n<pre><code>set_trace_func proc{ |event, file, line, id, binding, classname|\n printf \"%8s %s:%-2d %10s %8s\\n\", event, file, line, id, classname\n}\n# call your method\nset_trace_func nil\n</code></pre>\n" }, { "answer_id": 3564633, "author": "James Adam", "author_id": 125773, "author_profile": "https://Stackoverflow.com/users/125773", "pm_score": 6, "selected": false, "text": "<p>You can actually go a bit further than the solution above. For Ruby 1.8 Enterprise Edition, there is the <code>__file__</code> and <code>__line__</code> methods on <code>Method</code> instances:</p>\n\n<pre><code>require 'rubygems'\nrequire 'activesupport'\n\nm = 2.days.method(:ago)\n# =&gt; #&lt;Method: Fixnum(ActiveSupport::CoreExtensions::Numeric::Time)#ago&gt;\n\nm.__file__\n# =&gt; \"/Users/james/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.8/lib/active_support/core_ext/numeric/time.rb\"\nm.__line__\n# =&gt; 64\n</code></pre>\n\n<p>For Ruby 1.9 and beyond, there is <code>source_location</code> (thanks Jonathan!):</p>\n\n<pre><code>require 'active_support/all'\nm = 2.days.method(:ago)\n# =&gt; #&lt;Method: Fixnum(Numeric)#ago&gt; # comes from the Numeric module\n\nm.source_location # show file and line\n# =&gt; [\"/var/lib/gems/1.9.1/gems/activesupport-3.0.6/.../numeric/time.rb\", 63]\n</code></pre>\n" }, { "answer_id": 9356057, "author": "Alex D", "author_id": 960828, "author_profile": "https://Stackoverflow.com/users/960828", "pm_score": 5, "selected": false, "text": "<p>I'm coming late to this thread, and am surprised that nobody mentioned <code>Method#owner</code>.</p>\n\n<pre><code>class A; def hello; puts \"hello\"; end end\nclass B &lt; A; end\nb = B.new\nb.method(:hello).owner\n=&gt; A\n</code></pre>\n" }, { "answer_id": 13015691, "author": "Laas", "author_id": 465345, "author_profile": "https://Stackoverflow.com/users/465345", "pm_score": 4, "selected": false, "text": "<p>Copying my answer from a newer <a href=\"https://stackoverflow.com/questions/13012109/get-class-location-from-class-object\">similar question</a> that adds new information to this problem.</p>\n\n<p>Ruby <strong>1.9</strong> has method called <a href=\"http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-source_location\" rel=\"noreferrer\">source_location</a>: </p>\n\n<blockquote>\n <p>Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)</p>\n</blockquote>\n\n<p>This has been backported to <strong>1.8.7</strong> by this gem:</p>\n\n<ul>\n<li><a href=\"https://github.com/ConradIrwin/ruby18_source_location\" rel=\"noreferrer\">ruby18_source_location</a></li>\n</ul>\n\n<p>So you can request for the method:</p>\n\n<pre><code>m = Foo::Bar.method(:create)\n</code></pre>\n\n<p>And then ask for the <code>source_location</code> of that method:</p>\n\n<pre><code>m.source_location\n</code></pre>\n\n<p>This will return an array with filename and line number.\nE.g for <code>ActiveRecord::Base#validates</code> this returns:</p>\n\n<pre><code>ActiveRecord::Base.method(:validates).source_location\n# =&gt; [\"/Users/laas/.rvm/gems/ruby-1.9.2-p0@arveaurik/gems/activemodel-3.2.2/lib/active_model/validations/validates.rb\", 81]\n</code></pre>\n\n<p>For classes and modules, Ruby does not offer built in support, but there is an excellent Gist out there that builds upon <code>source_location</code> to return file for a given method or first file for a class if no method was specified:</p>\n\n<ul>\n<li><a href=\"https://gist.github.com/1236979\" rel=\"noreferrer\">ruby where_is module</a></li>\n</ul>\n\n<p>In action:</p>\n\n<pre><code>where_is(ActiveRecord::Base, :validates)\n\n# =&gt; [\"/Users/laas/.rvm/gems/ruby-1.9.2-p0@arveaurik/gems/activemodel-3.2.2/lib/active_model/validations/validates.rb\", 81]\n</code></pre>\n\n<p>On Macs with TextMate installed, this also pops up the editor at the specified location.</p>\n" }, { "answer_id": 38368482, "author": "Samda", "author_id": 2547201, "author_profile": "https://Stackoverflow.com/users/2547201", "pm_score": 3, "selected": false, "text": "<p>Maybe the <code>#source_location</code> can help to find where is the method come from.</p>\n\n<p>ex: </p>\n\n<pre><code>ModelName.method(:has_one).source_location\n</code></pre>\n\n<p>Return</p>\n\n<pre><code>[project_path/vendor/ruby/version_number/gems/activerecord-number/lib/active_record/associations.rb\", line_number_of_where_method_is]\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>ModelName.new.method(:valid?).source_location\n</code></pre>\n\n<p>Return </p>\n\n<pre><code>[project_path/vendor/ruby/version_number/gems/activerecord-number/lib/active_record/validations.rb\", line_number_of_where_method_is]\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2590/" ]
We recently had a problem where, after a series of commits had occurred, a backend process failed to run. Now, we were good little boys and girls and ran `rake test` after every check-in but, due to some oddities in Rails' library loading, it only occurred when we ran it directly from Mongrel in production mode. I tracked the bug down and it was due to a new Rails gem overwriting a method in the String class in a way that broke one narrow use in the runtime Rails code. Anyway, long story short, is there a way, at runtime, to ask Ruby where a method has been defined? Something like `whereami( :foo )` that returns `/path/to/some/file.rb line #45`? In this case, telling me that it was defined in class String would be unhelpful, because it was overloaded by some library. I cannot guarantee the source lives in my project, so grepping for `'def foo'` won't necessarily give me what I need, not to mention if I have *many* `def foo`'s, sometimes I don't know until runtime which one I may be using.
This is really late, but here's how you can find where a method is defined: <http://gist.github.com/76951> ``` # How to find out where a method comes from. # Learned this from Dave Thomas while teaching Advanced Ruby Studio # Makes the case for separating method definitions into # modules, especially when enhancing built-in classes. module Perpetrator def crime end end class Fixnum include Perpetrator end p 2.method(:crime) # The "2" here is an instance of Fixnum. #<Method: Fixnum(Perpetrator)#crime> ``` If you're on Ruby 1.9+, you can use [`source_location`](http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-source_location) ``` require 'csv' p CSV.new('string').method(:flock) # => #<Method: CSV#flock> CSV.new('string').method(:flock).source_location # => ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180] ``` Note that this won't work on everything, like native compiled code. The [Method class](http://www.ruby-doc.org/core-1.9.3/Method.html) has some neat functions, too, like [Method#owner](http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-owner) which returns the file where the method is defined. EDIT: Also see the `__file__` and `__line__` and notes for REE in the other answer, they're handy too. -- wg
175,689
<p>I know you can use C++ keyword 'explicit' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method?</p> <p>I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function with an int, the compiler converted the param to a bool and called the wrong method. I know eventually I'll replace the bool, but for now don't want to break the other routines as this new routine is developed.</p>
[ { "answer_id": 175716, "author": "Superpolock", "author_id": 16496, "author_profile": "https://Stackoverflow.com/users/16496", "pm_score": 0, "selected": false, "text": "<p>Compiler gave \"ambiguous call\" warning, which will be sufficient. </p>\n\n<p>I was doing TDD development and didn't realize I forgot to implement the corresponding call in the mock object.</p>\n" }, { "answer_id": 175745, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": -1, "selected": false, "text": "<p>You could also write an int version that calls the bool one.</p>\n" }, { "answer_id": 175759, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 4, "selected": false, "text": "<p>No. <code>explicit</code> prevents automatic conversion between specific classes, irrespective of context. And of course you can't do it for built-in classes.</p>\n" }, { "answer_id": 175910, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 0, "selected": false, "text": "<p>bool IS an int that is limited to either 0 or 1. That is the whole concept of return 0;, it is logically the same as saying return false;(don't use this in code though). </p>\n" }, { "answer_id": 175926, "author": "Patrick Johnmeyer", "author_id": 363, "author_profile": "https://Stackoverflow.com/users/363", "pm_score": 7, "selected": true, "text": "<p>No, you can't use explicit, but you can use a templated function to catch the incorrect parameter types.</p>\n\n<p>With <strong>C++11</strong>, you can declare the templated function as <code>delete</code>d. Here is a simple example:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nstruct Thing {\n void Foo(int value) {\n std::cout &lt;&lt; \"Foo: value\" &lt;&lt; std::endl;\n }\n\n template &lt;typename T&gt;\n void Foo(T value) = delete;\n};\n</code></pre>\n\n<p>This gives the following error message if you try to call <code>Thing::Foo</code> with a <code>size_t</code> parameter:</p>\n\n<pre><code>error: use of deleted function\n ‘void Thing::Foo(T) [with T = long unsigned int]’\n</code></pre>\n\n<hr>\n\n<p>In <strong>pre-C++11</strong> code, it can be accomplished using an undefined private function instead.</p>\n\n<pre><code>class ClassThatOnlyTakesBoolsAndUIntsAsArguments\n{\npublic:\n // Assume definitions for these exist elsewhere\n void Method(bool arg1);\n void Method(unsigned int arg1);\n\n // Below just an example showing how to do the same thing with more arguments\n void MethodWithMoreParms(bool arg1, SomeType&amp; arg2);\n void MethodWithMoreParms(unsigned int arg1, SomeType&amp; arg2);\n\nprivate:\n // You can leave these undefined\n template&lt;typename T&gt;\n void Method(T arg1);\n\n // Below just an example showing how to do the same thing with more arguments\n template&lt;typename T&gt;\n void MethodWithMoreParms(T arg1, SomeType&amp; arg2);\n};\n</code></pre>\n\n<p>The disadvantage is that the code and the error message are less clear in this case, so the C++11 option should be selected whenever available.</p>\n\n<p>Repeat this pattern for every method that takes the <code>bool</code> or <code>unsigned int</code>. Do not provide an implementation for the templatized version of the method.</p>\n\n<p>This will force the user to always explicitly call the bool or unsigned int version.</p>\n\n<p>Any attempt to call <code>Method</code> with a type other than <code>bool</code> or <code>unsigned int</code> will fail to compile because the member is private, subject to the standard exceptions to visibility rules, of course (friend, internal calls, etc.). If something that does have access calls the private method, you will get a linker error.</p>\n" }, { "answer_id": 176181, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>Something that might work for you is to use templates. The following shows the template function <code>foo&lt;&gt;()</code> being specialized for <code>bool</code>, <code>unsigned int</code>, and <code>int</code>. The <code>main()</code> function shows how the calls get resolved. Note that the calls that use a constant <code>int</code> that don't specify a type suffix will resolve to <code>foo&lt;int&gt;()</code>, so you'll get an error calling <code>foo( 1)</code> if you don't specialize on <code>int</code>. If this is the case, callers using a literal integer constant will have to use the <code>\"U\"</code> suffix to get the call to resolve (this might be the behavior you want).</p>\n\n<p>Otherwise you'll have to specialize on <code>int</code> and use the <code>\"U\"</code> suffix or cast it to an <code>unsigned int</code> before passing it on to the <code>unsigned int</code> version (or maybe do an assert that the value isn't negative, if that's what you want).</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\ntemplate &lt;typename T&gt;\nvoid foo( T);\n\ntemplate &lt;&gt;\nvoid foo&lt;bool&gt;( bool x)\n{\n printf( \"foo( bool)\\n\");\n}\n\n\ntemplate &lt;&gt;\nvoid foo&lt;unsigned int&gt;( unsigned int x)\n{\n printf( \"foo( unsigned int)\\n\");\n}\n\n\ntemplate &lt;&gt;\nvoid foo&lt;int&gt;( int x)\n{\n printf( \"foo( int)\\n\");\n}\n\n\n\nint main () \n{\n foo( true);\n foo( false);\n foo( static_cast&lt;unsigned int&gt;( 0));\n foo( 0U);\n foo( 1U);\n foo( 2U);\n foo( 0);\n foo( 1);\n foo( 2);\n}\n</code></pre>\n" }, { "answer_id": 176248, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 3, "selected": false, "text": "<p>The following is a very basic wrapper that can be used to create a strong typedef:</p>\n\n<pre><code>template &lt;typename V, class D&gt; \nclass StrongType\n{\npublic:\n inline explicit StrongType(V const &amp;v)\n : m_v(v)\n {}\n\n inline operator V () const\n {\n return m_v;\n }\n\nprivate:\n V m_v; // use V as \"inner\" type\n};\n\nclass Tag1;\ntypedef StrongType&lt;int, Tag1&gt; Tag1Type;\n\n\nvoid b1 (Tag1Type);\n\nvoid b2 (int i)\n{\n b1 (Tag1Type (i));\n b1 (i); // Error\n}\n</code></pre>\n\n<p>One nice feature of this approach, is that you can also distinguish between different parameters with the same type. For example you could have the following:</p>\n\n<pre><code>class WidthTag;\ntypedef StrongType&lt;int, WidthTag&gt; Width; \nclass HeightTag;\ntypedef StrongType&lt;int, HeightTag&gt; Height; \n\nvoid foo (Width width, Height height);\n</code></pre>\n\n<p>It will be clear to the clients of 'foo' which argument is which.</p>\n" }, { "answer_id": 58020805, "author": "Apollys supports Monica", "author_id": 7022459, "author_profile": "https://Stackoverflow.com/users/7022459", "pm_score": 1, "selected": false, "text": "<p>The currently accepted <a href=\"https://stackoverflow.com/a/175926/7022459\">answer</a> (using a private templated function) is nice, but outdated. With C++11, we can use <code>delete</code>d functions instead:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nstruct Thing {\n void Foo(int value) {\n std::cout &lt;&lt; \"Foo: value\" &lt;&lt; std::endl;\n }\n\n template &lt;typename T&gt;\n void Foo(T value) = delete;\n};\n\nint main() {\n Thing t;\n int int_value = 1;\n size_t size_t_value = 2;\n\n t.Foo(int_value);\n\n // t.Foo(size_t_value); // fails with below error\n // error: use of deleted function\n // ‘void Thing::Foo(T) [with T = long unsigned int]’\n\n return 0;\n}\n</code></pre>\n\n<p>This conveys the intent of the source code more directly and supplies the user with a clearer error message when trying to use the function with disallowed parameter types.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16496/" ]
I know you can use C++ keyword 'explicit' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method? I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function with an int, the compiler converted the param to a bool and called the wrong method. I know eventually I'll replace the bool, but for now don't want to break the other routines as this new routine is developed.
No, you can't use explicit, but you can use a templated function to catch the incorrect parameter types. With **C++11**, you can declare the templated function as `delete`d. Here is a simple example: ``` #include <iostream> struct Thing { void Foo(int value) { std::cout << "Foo: value" << std::endl; } template <typename T> void Foo(T value) = delete; }; ``` This gives the following error message if you try to call `Thing::Foo` with a `size_t` parameter: ``` error: use of deleted function ‘void Thing::Foo(T) [with T = long unsigned int]’ ``` --- In **pre-C++11** code, it can be accomplished using an undefined private function instead. ``` class ClassThatOnlyTakesBoolsAndUIntsAsArguments { public: // Assume definitions for these exist elsewhere void Method(bool arg1); void Method(unsigned int arg1); // Below just an example showing how to do the same thing with more arguments void MethodWithMoreParms(bool arg1, SomeType& arg2); void MethodWithMoreParms(unsigned int arg1, SomeType& arg2); private: // You can leave these undefined template<typename T> void Method(T arg1); // Below just an example showing how to do the same thing with more arguments template<typename T> void MethodWithMoreParms(T arg1, SomeType& arg2); }; ``` The disadvantage is that the code and the error message are less clear in this case, so the C++11 option should be selected whenever available. Repeat this pattern for every method that takes the `bool` or `unsigned int`. Do not provide an implementation for the templatized version of the method. This will force the user to always explicitly call the bool or unsigned int version. Any attempt to call `Method` with a type other than `bool` or `unsigned int` will fail to compile because the member is private, subject to the standard exceptions to visibility rules, of course (friend, internal calls, etc.). If something that does have access calls the private method, you will get a linker error.
175,690
<p>I know I could just ask, but that would involve bureaucratic entanglements.</p>
[ { "answer_id": 175701, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 0, "selected": false, "text": "<p>I believe that on an AD network that is DNS enabled the root zone points at all the AD servers. So, for instance, if your official AD username is [email protected], doing an nslookup of company.ad from cmd.exe will tell you all the IPs of the controllers (and hence all the IPs you could use for LDAP).</p>\n\n<p>This is edited to change the zone name, but one my work system:</p>\n\n<pre><code>C:\\Documents and Settings\\jj33&gt;nslookup companyname.ad\nServer: palpatine.companyname.ad\nAddress: 172.19.1.3\n\nName: companyname.ad\nAddresses: 172.16.3.2, 172.16.6.2, 172.19.1.3, 172.16.7.9\n 172.19.1.14, 172.19.1.11\nC:\\Documents and Settings\\jj33&gt;\n</code></pre>\n\n<p>On my (XP) machine, this shows me my AD domain:</p>\n\n<ul>\n<li>Right click \"My Computer\"</li>\n<li>Select \"Computer Name\" tab</li>\n<li>See \"Domain:\" field</li>\n</ul>\n" }, { "answer_id": 175709, "author": "VolkA", "author_id": 25472, "author_profile": "https://Stackoverflow.com/users/25472", "pm_score": 2, "selected": false, "text": "<p>Try ping or nslookup _ldap._tcp. with your AD Domain (e.g. _ldap._tcp.test.com) in a console (cmd.exe) - this should give you the AD Server IP.</p>\n\n<pre><code>_ldap._tcp.*\n</code></pre>\n\n<p>Is a general SRV entry made by your active directory server for locating LDAP (AD) servers in your domain. Your domain itself should match your Windows Login Domain. If this isn't the case right-click on your \"My Computer\" Icon on your Desktop or in your Explorer and click Properties. In the System Properties there is a Tab showing your Computer Name and its Network ID, which also contains its DOMAIN/WORKGROUP name. This is what you should append to the resource locator above.</p>\n\n<p>Btw. how did you get access to that machine without your Domain Login? :)</p>\n\n<p>Edit: The FOOAD name would be the \"old\" Domain name, and foo.something.something the new DNS based name - this should give you the server address. Also try the suggestion by Almond, which is more specific regarding the requested service.</p>\n" }, { "answer_id": 176134, "author": "Almond", "author_id": 1603, "author_profile": "https://Stackoverflow.com/users/1603", "pm_score": 0, "selected": false, "text": "<p>Open command prompt if you can, type ipconfig /all look at the entry for primary dns suffix. This mostly likely the domain that your workstation is on. Another potenial way is to log out and look at the domain listed below username/password in the login window.</p>\n\n<p>Once you have your domain name open command prompt again and type the following:</p>\n\n<p>nslookup _LDAP._TCP.dc._msdcs.<strong>mydomain</strong></p>\n\n<p>this will give you a ip address for the domain controller.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
I know I could just ask, but that would involve bureaucratic entanglements.
Try ping or nslookup \_ldap.\_tcp. with your AD Domain (e.g. \_ldap.\_tcp.test.com) in a console (cmd.exe) - this should give you the AD Server IP. ``` _ldap._tcp.* ``` Is a general SRV entry made by your active directory server for locating LDAP (AD) servers in your domain. Your domain itself should match your Windows Login Domain. If this isn't the case right-click on your "My Computer" Icon on your Desktop or in your Explorer and click Properties. In the System Properties there is a Tab showing your Computer Name and its Network ID, which also contains its DOMAIN/WORKGROUP name. This is what you should append to the resource locator above. Btw. how did you get access to that machine without your Domain Login? :) Edit: The FOOAD name would be the "old" Domain name, and foo.something.something the new DNS based name - this should give you the server address. Also try the suggestion by Almond, which is more specific regarding the requested service.
175,695
<p>How can I represent the following in XSD.</p> <pre><code>&lt;price-update&gt; &lt;![CDATA[ arbitrary data goes here ]]&gt; &lt;/price-update&gt; </code></pre>
[ { "answer_id": 175706, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 5, "selected": false, "text": "<p>A CDATA tag is merely a means of escaping data as a text node. Therefore you cannot stipulate that you require a CDATA node.</p>\n\n<p>From a DOM perspective, the following documents are identical:</p>\n\n<pre><code>&lt;doc&gt;value&lt;/doc&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;doc&gt;&lt;![CDATA[value]]&gt;&lt;/doc&gt;\n</code></pre>\n" }, { "answer_id": 175866, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 6, "selected": true, "text": "<pre><code>&lt;element name=\"price-update\" type=\"string\"&gt;&lt;/element&gt; \n</code></pre>\n\n<p>is about as close as you can get.</p>\n\n<p>(I thought it best to move the answer out of the comments and into an actual answer).</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21297/" ]
How can I represent the following in XSD. ``` <price-update> <![CDATA[ arbitrary data goes here ]]> </price-update> ```
``` <element name="price-update" type="string"></element> ``` is about as close as you can get. (I thought it best to move the answer out of the comments and into an actual answer).
175,717
<p>This is something that I have never fully grasped in .NET as to the correct application of the .dispose() method.</p> <p>Say I have something like</p> <pre><code>Public Class someClass() sub someMethod ' do some stuff tying up resources end sub End Class public class mainApp dim _class as new SomeClass _class.someMethod() End Class </code></pre> <p>In all cases is it good practice to implement a dispose method, and if so what should go in there?</p> <p>If it is not the case that every class should have dispose method (which my gut feeling says the shouldn't) what classes should? I have always thought anything which may tie up a resource (i.e. connection, datareader etc) should have a .dispose() which would unallocate these resources. </p> <p>Also how would you enforce a calling into calling the .dispose() method?</p>
[ { "answer_id": 175722, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>The <code>Dispose()</code> method is used for cleaning up any resources early. Although the garbage collector reclaims any unused memory for you, it's up to you to do deal with things like network/database connections and file handles. Normally, you'd want these things freed up as soon as they're no longer needed, so you implement the disposable pattern and take advantage of the <code>Using</code> statment for calling it within a try/finally block behind the scenes.</p>\n" }, { "answer_id": 175731, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 4, "selected": true, "text": "<p>I highly recommend reading <a href=\"http://msdn.microsoft.com/en-us/library/498928w2(VS.80).aspx\" rel=\"nofollow noreferrer\">Cleaning Up Unmanaged Resources</a> on MSDN, it has articles touching on when to use Dispose and how to implement IDisposable correctly. Your gut instinct is mostly correct as you rarely have to implement IDisposable, unless your class uses unmanaged resources or is a container for an object that implements IDisposable.</p>\n\n<p>As to enforcing the calling of Dispose, when you properly implement the IDisposable interface you attach a finalizer which calls Dispose to catch those stragglers and deviant classes that forgot.</p>\n\n<p>Relevant articles:</p>\n\n<blockquote>\n <p><strong><a href=\"http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx\" rel=\"nofollow noreferrer\">Implementing a Dispose Method</a></strong></p>\n \n <p>Describes the implementation of the Dispose method for releasing unmanaged resources.</p>\n \n <p><strong><a href=\"http://msdn.microsoft.com/en-us/library/3bwa4xa9(VS.80).aspx\" rel=\"nofollow noreferrer\">Using Objects That Encapsulate Resources</a></strong></p>\n \n <p>Describes ways to ensure that the Dispose method is called, such as the C# using statement (Using in Visual Basic).</p>\n</blockquote>\n\n<p><em>(edit: additional information added)</em></p>\n\n<p>In your example you have <strong>SomeClass.SomeMethod</strong> which does some work, presumably with a resource. If this resource isn't a class member, you may be better served wrapping it in a <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"nofollow noreferrer\">using-statement</a>, and forgetting about the devilish details of IDisposable.</p>\n\n<pre><code>Public Class someClass()\n sub someMethod\n Using someResource As New ResourceType( arguments )\n ' no worries about IDisposable for someResource, as it is automatic\n End Using\n end sub\nEnd Class\n</code></pre>\n" }, { "answer_id": 175735, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "<p>In general, you should you implement IDisposable whenever your class intends to OPEN something. Whether its a handle to a file, a connection to a database, or some resource which will take up a sizable chunk of memory or which will leave your application in an unstable state, it's always a good idea implement IDisposable to specify the code that will CLOSE those resources.</p>\n\n<p>You really can't enforce other developers to call your dispose methods, but implementing IDisposable automatically means we can use the <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"nofollow noreferrer\">Using</a> statement; which, once you get into the habit, is hard to break :)</p>\n" }, { "answer_id": 175753, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": false, "text": "<p>It's a fairly long answer to cover everything fully, so hopefully nobody will mind if I link to <a href=\"http://gregbeech.com/blogs/tech/archive/2007/03/07/implementing-and-using-the-idisposable-interface.aspx\" rel=\"nofollow noreferrer\">a blog post which should hopefully answer everything</a>.</p>\n" }, { "answer_id": 175802, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 1, "selected": false, "text": "<p>There is a lot of misinformation out there about IDisposable. It is a PATTERN that helps to accomplish what used to be traditionally accomplished via a destructor in C++. The problem is that in .NET, destruction of an object is not deterministic (it doesn't happen automatically when an object goes out of scope, but rather occurs at the time of Garbage Collection which is on a seperate low priority thread).</p>\n\n<p>You do not need to implement Dispose unless you have a resource which needs to be released in some fashion. For instance, if any of your private data members implement Dispose, you should probably implement Dispose as well and call Dispose on those private members in your Dispose. Likewise, you should release any PInvoke handles in Dispose.</p>\n\n<p>Also, the Dispose method is NOT called automatically for you upon garbage collection. This is the biggest piece of misinformation. You have to call Dispose from your Destructor (C#) or Finalize (VB.NET). Here is a good pattern for implementing Dispose:</p>\n\n<pre><code>public class Foo : IDisposable\n{\n public Foo()\n {\n // Allocate some resource here\n }\n\n ~Foo()\n {\n Dispose( false );\n }\n\n public void Dispose()\n {\n Dispose( true );\n }\n\n private void Dispose( bool disposing )\n {\n // De-allocate resource here\n if ( disposing )\n GC.SuppressFinalize( this );\n }\n}\n</code></pre>\n\n<p>The reason that you call GC.SupressFinalize is that if your object has a finalizer, your object will actually get promoted to the next GC generation, because it has to call Finalize the first time the GC runs around, and can't release your object until finalization is finished, and therefore the memory is actually not released until the 2nd run through by the GC. If you call Dispose manually, then you can skip the finalizer, allowing your object to be released during the first pass of the GC.</p>\n\n<p>To get the most benefit out of Dispose, use the using keword:</p>\n\n<pre><code>using ( Foo f = new Foo() )\n{\n // Do something with Foo\n}\n</code></pre>\n\n<p>This is exactly the same as if you had written this:</p>\n\n<pre><code>Foo f;\ntry\n{\n f = new Foo();\n // Do something with Foo\n}\nfinally\n{\n f.Dispose();\n}\n</code></pre>\n\n<p>Some people like to set a boolean in their class called _disposed, and then check that bool during every method call, and throw an exception if you attempt to call a method on an object after Dispose is called. For internal project classes, I generally consider this overkill, but might be a good thing to do if you are creating a library for consumption by 3rd parties.</p>\n" }, { "answer_id": 175842, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 0, "selected": false, "text": "<p>You should implement IDisposable in a class if the class either:</p>\n\n<ul>\n<li>own some other objects which implement IDisposable </li>\n<li>allocates some ressources through an unmanaged interface like P/Invoke.</li>\n</ul>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
This is something that I have never fully grasped in .NET as to the correct application of the .dispose() method. Say I have something like ``` Public Class someClass() sub someMethod ' do some stuff tying up resources end sub End Class public class mainApp dim _class as new SomeClass _class.someMethod() End Class ``` In all cases is it good practice to implement a dispose method, and if so what should go in there? If it is not the case that every class should have dispose method (which my gut feeling says the shouldn't) what classes should? I have always thought anything which may tie up a resource (i.e. connection, datareader etc) should have a .dispose() which would unallocate these resources. Also how would you enforce a calling into calling the .dispose() method?
I highly recommend reading [Cleaning Up Unmanaged Resources](http://msdn.microsoft.com/en-us/library/498928w2(VS.80).aspx) on MSDN, it has articles touching on when to use Dispose and how to implement IDisposable correctly. Your gut instinct is mostly correct as you rarely have to implement IDisposable, unless your class uses unmanaged resources or is a container for an object that implements IDisposable. As to enforcing the calling of Dispose, when you properly implement the IDisposable interface you attach a finalizer which calls Dispose to catch those stragglers and deviant classes that forgot. Relevant articles: > > **[Implementing a Dispose Method](http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx)** > > > Describes the implementation of the Dispose method for releasing unmanaged resources. > > > **[Using Objects That Encapsulate Resources](http://msdn.microsoft.com/en-us/library/3bwa4xa9(VS.80).aspx)** > > > Describes ways to ensure that the Dispose method is called, such as the C# using statement (Using in Visual Basic). > > > *(edit: additional information added)* In your example you have **SomeClass.SomeMethod** which does some work, presumably with a resource. If this resource isn't a class member, you may be better served wrapping it in a [using-statement](http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx), and forgetting about the devilish details of IDisposable. ``` Public Class someClass() sub someMethod Using someResource As New ResourceType( arguments ) ' no worries about IDisposable for someResource, as it is automatic End Using end sub End Class ```
175,723
<p>I have a form where controls are dynamically added to a Panel. However, when they do so, they are many times added below the fold (bottom of the container). It's nice that the .NET Framework provides this ScrollControlIntoView method, however, for added usability, it would also be nice if there was an easy way to animate so that it is easy for the user to understand that the Panel was automatically scrolled.</p> <p>Has anyone ever encountered this or have any ideas as to how to tackle it?</p>
[ { "answer_id": 175722, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>The <code>Dispose()</code> method is used for cleaning up any resources early. Although the garbage collector reclaims any unused memory for you, it's up to you to do deal with things like network/database connections and file handles. Normally, you'd want these things freed up as soon as they're no longer needed, so you implement the disposable pattern and take advantage of the <code>Using</code> statment for calling it within a try/finally block behind the scenes.</p>\n" }, { "answer_id": 175731, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 4, "selected": true, "text": "<p>I highly recommend reading <a href=\"http://msdn.microsoft.com/en-us/library/498928w2(VS.80).aspx\" rel=\"nofollow noreferrer\">Cleaning Up Unmanaged Resources</a> on MSDN, it has articles touching on when to use Dispose and how to implement IDisposable correctly. Your gut instinct is mostly correct as you rarely have to implement IDisposable, unless your class uses unmanaged resources or is a container for an object that implements IDisposable.</p>\n\n<p>As to enforcing the calling of Dispose, when you properly implement the IDisposable interface you attach a finalizer which calls Dispose to catch those stragglers and deviant classes that forgot.</p>\n\n<p>Relevant articles:</p>\n\n<blockquote>\n <p><strong><a href=\"http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx\" rel=\"nofollow noreferrer\">Implementing a Dispose Method</a></strong></p>\n \n <p>Describes the implementation of the Dispose method for releasing unmanaged resources.</p>\n \n <p><strong><a href=\"http://msdn.microsoft.com/en-us/library/3bwa4xa9(VS.80).aspx\" rel=\"nofollow noreferrer\">Using Objects That Encapsulate Resources</a></strong></p>\n \n <p>Describes ways to ensure that the Dispose method is called, such as the C# using statement (Using in Visual Basic).</p>\n</blockquote>\n\n<p><em>(edit: additional information added)</em></p>\n\n<p>In your example you have <strong>SomeClass.SomeMethod</strong> which does some work, presumably with a resource. If this resource isn't a class member, you may be better served wrapping it in a <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"nofollow noreferrer\">using-statement</a>, and forgetting about the devilish details of IDisposable.</p>\n\n<pre><code>Public Class someClass()\n sub someMethod\n Using someResource As New ResourceType( arguments )\n ' no worries about IDisposable for someResource, as it is automatic\n End Using\n end sub\nEnd Class\n</code></pre>\n" }, { "answer_id": 175735, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "<p>In general, you should you implement IDisposable whenever your class intends to OPEN something. Whether its a handle to a file, a connection to a database, or some resource which will take up a sizable chunk of memory or which will leave your application in an unstable state, it's always a good idea implement IDisposable to specify the code that will CLOSE those resources.</p>\n\n<p>You really can't enforce other developers to call your dispose methods, but implementing IDisposable automatically means we can use the <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"nofollow noreferrer\">Using</a> statement; which, once you get into the habit, is hard to break :)</p>\n" }, { "answer_id": 175753, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": false, "text": "<p>It's a fairly long answer to cover everything fully, so hopefully nobody will mind if I link to <a href=\"http://gregbeech.com/blogs/tech/archive/2007/03/07/implementing-and-using-the-idisposable-interface.aspx\" rel=\"nofollow noreferrer\">a blog post which should hopefully answer everything</a>.</p>\n" }, { "answer_id": 175802, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 1, "selected": false, "text": "<p>There is a lot of misinformation out there about IDisposable. It is a PATTERN that helps to accomplish what used to be traditionally accomplished via a destructor in C++. The problem is that in .NET, destruction of an object is not deterministic (it doesn't happen automatically when an object goes out of scope, but rather occurs at the time of Garbage Collection which is on a seperate low priority thread).</p>\n\n<p>You do not need to implement Dispose unless you have a resource which needs to be released in some fashion. For instance, if any of your private data members implement Dispose, you should probably implement Dispose as well and call Dispose on those private members in your Dispose. Likewise, you should release any PInvoke handles in Dispose.</p>\n\n<p>Also, the Dispose method is NOT called automatically for you upon garbage collection. This is the biggest piece of misinformation. You have to call Dispose from your Destructor (C#) or Finalize (VB.NET). Here is a good pattern for implementing Dispose:</p>\n\n<pre><code>public class Foo : IDisposable\n{\n public Foo()\n {\n // Allocate some resource here\n }\n\n ~Foo()\n {\n Dispose( false );\n }\n\n public void Dispose()\n {\n Dispose( true );\n }\n\n private void Dispose( bool disposing )\n {\n // De-allocate resource here\n if ( disposing )\n GC.SuppressFinalize( this );\n }\n}\n</code></pre>\n\n<p>The reason that you call GC.SupressFinalize is that if your object has a finalizer, your object will actually get promoted to the next GC generation, because it has to call Finalize the first time the GC runs around, and can't release your object until finalization is finished, and therefore the memory is actually not released until the 2nd run through by the GC. If you call Dispose manually, then you can skip the finalizer, allowing your object to be released during the first pass of the GC.</p>\n\n<p>To get the most benefit out of Dispose, use the using keword:</p>\n\n<pre><code>using ( Foo f = new Foo() )\n{\n // Do something with Foo\n}\n</code></pre>\n\n<p>This is exactly the same as if you had written this:</p>\n\n<pre><code>Foo f;\ntry\n{\n f = new Foo();\n // Do something with Foo\n}\nfinally\n{\n f.Dispose();\n}\n</code></pre>\n\n<p>Some people like to set a boolean in their class called _disposed, and then check that bool during every method call, and throw an exception if you attempt to call a method on an object after Dispose is called. For internal project classes, I generally consider this overkill, but might be a good thing to do if you are creating a library for consumption by 3rd parties.</p>\n" }, { "answer_id": 175842, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 0, "selected": false, "text": "<p>You should implement IDisposable in a class if the class either:</p>\n\n<ul>\n<li>own some other objects which implement IDisposable </li>\n<li>allocates some ressources through an unmanaged interface like P/Invoke.</li>\n</ul>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21807/" ]
I have a form where controls are dynamically added to a Panel. However, when they do so, they are many times added below the fold (bottom of the container). It's nice that the .NET Framework provides this ScrollControlIntoView method, however, for added usability, it would also be nice if there was an easy way to animate so that it is easy for the user to understand that the Panel was automatically scrolled. Has anyone ever encountered this or have any ideas as to how to tackle it?
I highly recommend reading [Cleaning Up Unmanaged Resources](http://msdn.microsoft.com/en-us/library/498928w2(VS.80).aspx) on MSDN, it has articles touching on when to use Dispose and how to implement IDisposable correctly. Your gut instinct is mostly correct as you rarely have to implement IDisposable, unless your class uses unmanaged resources or is a container for an object that implements IDisposable. As to enforcing the calling of Dispose, when you properly implement the IDisposable interface you attach a finalizer which calls Dispose to catch those stragglers and deviant classes that forgot. Relevant articles: > > **[Implementing a Dispose Method](http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx)** > > > Describes the implementation of the Dispose method for releasing unmanaged resources. > > > **[Using Objects That Encapsulate Resources](http://msdn.microsoft.com/en-us/library/3bwa4xa9(VS.80).aspx)** > > > Describes ways to ensure that the Dispose method is called, such as the C# using statement (Using in Visual Basic). > > > *(edit: additional information added)* In your example you have **SomeClass.SomeMethod** which does some work, presumably with a resource. If this resource isn't a class member, you may be better served wrapping it in a [using-statement](http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx), and forgetting about the devilish details of IDisposable. ``` Public Class someClass() sub someMethod Using someResource As New ResourceType( arguments ) ' no worries about IDisposable for someResource, as it is automatic End Using end sub End Class ```
175,726
<p>c# windows forms: How do you create new settings at run time so that they are permanently saved as Settings.Default.-- values?</p>
[ { "answer_id": 175734, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>Since the Settings class is generated at build time (or, actually, whenever you update the settings file from within the designer), you can't use this mechanism for dynamic scenarios. You can, however, add some collection or dictionary to the application settings and modify that dynamically.</p>\n" }, { "answer_id": 175812, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<p>How would you access the new settings that you have created? The point of the Visual Studio settings designer is that you can write code that uses these settings with compile-time checking of your code. If you want to dynamically create new settings for your app to use, you will also need to dynamically load them. For dynamic settings, you may want to look at the System.Configuration assembly, notably <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx\" rel=\"nofollow noreferrer\">ConfigurationSection</a>. You can create a custom configuration section with that, which you could use for dynamic setting addition/removal. You might use a <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx\" rel=\"nofollow noreferrer\">ConfigurationCollection</a> for that dynamic addition/removal.</p>\n\n<p>INI files eh? Google turned up <a href=\"http://www.mentalis.org/soft/class.qpx?id=6\" rel=\"nofollow noreferrer\">this INI library</a> for .NET.</p>\n" }, { "answer_id": 175829, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I see how what I wanted was the wrong idea. I'm porting a c++ app over to c# and it has a lot of ini file settings and I was looking for a shortcut to add them in. I'm lazy.</p>\n" }, { "answer_id": 1236190, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>What you could do is create a new registry key.\nName the new key \"Your program settings\".</p>\n\n<pre><code>RegistryKey ProgSettings = Registry.CurrentUser.OpenSubKey(\"Software\", true);\nProgSettings.CreateSubKey(\"Your Program settings\"); \nProgSettings.Close();\n</code></pre>\n\n<p>Now you can add String Identifiers and values.</p>\n\n<pre><code>RegistryKey ProgSettings = Registry.CurrentUser.OpenSubKey(\"Software\\\\Your Program settings\", true);\nProgSettings.SetValue(\"Setting Name\", value); // store settings \nstring settings = ProgSettings.GetValue(\"Setting Name\", false); // retreave settings \nProgSettings.DeleteValue(\"Setting Name\", false);\n</code></pre>\n\n<p>Besure to close the registry key when you are done to avoid conflicts with other parts of your program that may write to the registry.</p>\n\n<p>Many comercial software applications use these methods.\nstackoverflow has many examples about writing and reading to the registry.\nThis is much easyer then modifying the appconfig.xml file that is used when you create settings.</p>\n" }, { "answer_id": 2143936, "author": "Tom Wilson", "author_id": 259706, "author_profile": "https://Stackoverflow.com/users/259706", "pm_score": 2, "selected": false, "text": "<p>You can't add settings directly (at least not without editing the config XML at runtime), but you can fake it.</p>\n\n<p>In my case, I had a group of identical custom controls on the form, and I wanted to store the runtime state of each control. I needed to store the state of each control, since each one had different data it.</p>\n\n<p>I created a new StringCollection setting named <strong>ControlData</strong> and placed my own data in there. I then load the data from that list and use it to initialize my controls.</p>\n\n<p>The list looks like this: </p>\n\n<pre><code>Box1Text=A\nBox1List=abc;def;foo;bar;\nBox2Text=hello\nBox2List=server1;server2;\n</code></pre>\n\n<p>In my startup code, I read through the key/value pairs like this:</p>\n\n<pre><code>foreach (string item in Properties.Settings.Default.ControlData) {\n string[] parts=item.split('=');\n</code></pre>\n\n<p>parts[0] will have the key and parts[1] will have the value. You can now do stuff based on this data.</p>\n\n<p>During the shutdown phase, I do the inverse to write the data back to the list. (Iterate through all the controls in the form and add their settings to ControlData.</p>\n" }, { "answer_id": 7608985, "author": "John", "author_id": 972892, "author_profile": "https://Stackoverflow.com/users/972892", "pm_score": 4, "selected": false, "text": "<p>Just in case that still matters to anyone:</p>\n\n<p>You can dynamically add settings through <code>Settings.Default.Properties.Add(...)</code> and have these also persisted in the local storage after saving (I had those entries reflected in the roaming file).</p>\n\n<p>Nevertheless it seems that the dynamically added settings keep missing in the <code>Settings.Default.Properties</code> collecion after loading again.</p>\n\n<p>I could work around this problem by adding the dynamic property before first accessing it.\nExample (notice that I \"create\" my dynamic setting from a base setting):</p>\n\n<pre><code>// create new setting from a base setting:\nvar property = new SettingsProperty(Settings.Default.Properties[\"&lt;baseSetting&gt;\"]);\nproperty.Name = \"&lt;dynamicSettingName&gt;\";\nSettings.Default.Properties.Add(property);\n// will have the stored value:\nvar dynamicSetting = Settings.Default[\"&lt;dynamicSettingName&gt;\"];\n</code></pre>\n\n<p>I don't know if this is supported by Microsoft as the documentation is very rare on this topic.</p>\n\n<p>Problem is also described here <a href=\"http://www.vbdotnetforums.com/vb-net-general-discussion/29805-my-settings-run-time-added-properties-dont-save.html#post88152\" rel=\"noreferrer\">http://www.vbdotnetforums.com/vb-net-general-discussion/29805-my-settings-run-time-added-properties-dont-save.html#post88152</a> with some solution offered here <a href=\"http://msdn.microsoft.com/en-us/library/saa62613(v=VS.100).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/saa62613(v=VS.100).aspx</a> (see Community Content - headline \"How to Create / Save / Load Dynamic (at Runtime) Settings\"). But this is VB.NET.</p>\n" }, { "answer_id": 10584286, "author": "Drew Ogle", "author_id": 1243932, "author_profile": "https://Stackoverflow.com/users/1243932", "pm_score": 4, "selected": false, "text": "<p>In addition to John's solution for saving, the proper method for loading is add the property, and then do a Reload() on your settings.</p>\n\n<p>Your dynamic setting will be there!</p>\n\n<p>For a full example, valid for using in library code, as you can pass the settings in ..<p></p>\n\n<pre><code>ApplicationSettingsBase settings = passed_in;\nSettingsProvider sp = settings.Providers[\"LocalFileSettingsProvider\"];\nSettingsProperty p = new SettingsProperty(\"your_prop_name\");\nyour_class conf = null;\np.PropertyType = typeof( your_class );\np.Attributes.Add(typeof(UserScopedSettingAttribute),new UserScopedSettingAttribute());\np.Provider = sp;\np.SerializeAs = SettingsSerializeAs.Xml;\nSettingsPropertyValue v = new SettingsPropertyValue( p );\nsettings.Properties.Add( p );\n\nsettings.Reload();\nconf = (your_class)settings[\"your_prop_name\"];\nif( conf == null )\n{\n settings[\"your_prop_name\"] = conf = new your_class();\n settings.Save();\n}\n</code></pre>\n" }, { "answer_id": 62154988, "author": "Girl Spider", "author_id": 5481566, "author_profile": "https://Stackoverflow.com/users/5481566", "pm_score": 1, "selected": false, "text": "<p>It took me a long time using the top two answers here plus this link (<a href=\"https://stackoverflow.com/questions/26018606/create-new-settings-on-runtime-and-read-after-restart/42052862#42052862\">Create new settings on runtime and read after restart</a>) to get it to finally work.</p>\n<p>First of all, set your expectations. The answer here will create a new user setting and you can get its value the next time you launch your app. However, the setting you created this way will not appear in the Settings designer. In fact, when you relaunch the app and try to access the setting in your code, it will not find it. However, the setting you have created through code is saved in the user.config file (say jDoe.config) somewhere in your file system. For you to access this value, you have to add the setting again.</p>\n<p>Here is a working example I have:</p>\n<pre><code> private void FormPersistence_Load(object sender, EventArgs e)\n {\n StartPosition = FormStartPosition.Manual;\n // Set window location\n var exists = Settings.Default.Properties.OfType&lt;SettingsProperty&gt;().Any(p =&gt; p.Name == Name + &quot;Location&quot;);\n if (exists)\n {\n this.Location = (Point)Settings.Default[Name + &quot;Location&quot;];\n }\n else\n {\n var property = new SettingsProperty(Settings.Default.Properties[&quot;baseLocation&quot;]);\n property.Name = Name + &quot;Location&quot;;\n Settings.Default.Properties.Add(property);\n Settings.Default.Reload();\n this.Location = (Point)Settings.Default[Name + &quot;Location&quot;];\n }\n }\n</code></pre>\n<p>Note:\nMy new setting's name will be resolved at run time. Name is really this.Name, which is the form's name. This is a base form that other forms can inherit from, so all the child forms will be able to remember their locations.<br />\nbaseLocation is a setting I have manually created in Settings designer. The new setting I have is the same type. This way I don't have to worry about things like provider, type, etc. in code.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
c# windows forms: How do you create new settings at run time so that they are permanently saved as Settings.Default.-- values?
Just in case that still matters to anyone: You can dynamically add settings through `Settings.Default.Properties.Add(...)` and have these also persisted in the local storage after saving (I had those entries reflected in the roaming file). Nevertheless it seems that the dynamically added settings keep missing in the `Settings.Default.Properties` collecion after loading again. I could work around this problem by adding the dynamic property before first accessing it. Example (notice that I "create" my dynamic setting from a base setting): ``` // create new setting from a base setting: var property = new SettingsProperty(Settings.Default.Properties["<baseSetting>"]); property.Name = "<dynamicSettingName>"; Settings.Default.Properties.Add(property); // will have the stored value: var dynamicSetting = Settings.Default["<dynamicSettingName>"]; ``` I don't know if this is supported by Microsoft as the documentation is very rare on this topic. Problem is also described here <http://www.vbdotnetforums.com/vb-net-general-discussion/29805-my-settings-run-time-added-properties-dont-save.html#post88152> with some solution offered here <http://msdn.microsoft.com/en-us/library/saa62613(v=VS.100).aspx> (see Community Content - headline "How to Create / Save / Load Dynamic (at Runtime) Settings"). But this is VB.NET.
175,733
<p>I have two tables in my database, called <em>ratings</em> and <em>movies</em>.</p> <p><strong>Ratings:</strong></p> <blockquote> <p><code>| id | movie_id | rating |</code></p> </blockquote> <p><strong>Movies:</strong></p> <blockquote> <p><code>| id | title |</code></p> </blockquote> <p>A typical movie record might be like this:</p> <blockquote> <p><code>| 4 | Cloverfield (2008) |</code></p> </blockquote> <p>and there may be several rating records for Cloverfield, like this:</p> <blockquote> <p><code>| 21 | 4 | 3 |</code> (rating number 21, on movie number 4, giving it a rating of 3)</p> <p><code>| 22 | 4 | 2 |</code> (rating number 22, on movie number 4, giving it a rating of 2)</p> <p><code>| 23 | 4 | 5 |</code> (rating number 23k on movie number 4, giving it a rating of 5)</p> </blockquote> <p><strong>The question:</strong></p> <p>How do I create a JOIN query for only selecting the rows in the movie table that have more than <code>x</code> number of ratings in the ratings table? For example, in the above example if Cloverfield only had one rating in the ratings table and <code>x</code> was 2, it would not be selected.</p> <p>Thanks for any help or advice!</p>
[ { "answer_id": 175740, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 2, "selected": false, "text": "<p>You'll probably want to use MySQL's HAVING clause</p>\n\n<p><a href=\"http://www.severnsolutions.co.uk/twblog/archive/2004/10/03/havingmysql\" rel=\"nofollow noreferrer\">http://www.severnsolutions.co.uk/twblog/archive/2004/10/03/havingmysql</a></p>\n" }, { "answer_id": 175743, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 4, "selected": true, "text": "<p>Use the HAVING clause. Something along these lines:</p>\n\n<pre><code>SELECT movies.id, movies.title, COUNT(ratings.id) AS num_ratings \n FROM movies \n LEFT JOIN ratings ON ratings.movie_id=movies.id \n GROUP BY movies.id \n HAVING num_ratings &gt; 5;\n</code></pre>\n" }, { "answer_id": 175798, "author": "Thorsten", "author_id": 25320, "author_profile": "https://Stackoverflow.com/users/25320", "pm_score": 0, "selected": false, "text": "<p>The above solutions are okay for the scenario you mentioned. My suggestion may be overkill for what you have in mind, but may be handy for other situations:</p>\n\n<ol>\n<li><p>Subquery only those from the ratings table having more than the number you need (again using tha group by having clause):</p>\n\n<p>select movie_id from ratings group by movie_id having count (*) > x</p></li>\n<li><p>Join that subquery with the movies table</p>\n\n<p>select movies.id\nfrom movies join \n as MoviesWRatings on movies.id = MoviesWRatings.movie_id</p></li>\n</ol>\n\n<p>When you're doing more stuff to the subquery, this might be helpful.\n(Not sure if the syntax is right for MySQL, please fix if necessary.)</p>\n" }, { "answer_id": 175801, "author": "Jeff Mc", "author_id": 25521, "author_profile": "https://Stackoverflow.com/users/25521", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT * FROM movies \nINNER JOIN\n(SELECT movie_id, COUNT(*) as num_ratings from ratings GROUP BY movie_id) as movie_counts\nON movies.id = movie_counts.movie_id\nWHERE num_ratings &gt; 3;\n</code></pre>\n\n<p>That will only get you the movies with more than 3 ratings, to actually get the ratings with it will take another join. The advantage of a subquery over HAVING is you can aggregate the ratings at the same time. Such as (SELECT movie_id, COUNT(*), AVG(rating) as average_move_rating ...)</p>\n\n<p>Edit: Oops, you can aggregate with the having method to. :)</p>\n" }, { "answer_id": 175824, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 2, "selected": false, "text": "<p>The JOIN method is somewhat stilted and confusing because that's not exactly what it was intended to do. The most direct (and in my opinion, easily human-parseable) method uses EXISTS:</p>\n\n<pre><code>SELECT whatever\n FROM movies m\n WHERE EXISTS( SELECT COUNT(*) \n FROM reviews\n WHERE movie_id = m.id\n HAVING COUNT(*) &gt; xxxxxxxx )\n</code></pre>\n\n<p>Read it out loud -- SELECT something FROM movies WHERE there EXIST rows in Reviews where the movie_id matches and there are > xxxxxx rows</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
I have two tables in my database, called *ratings* and *movies*. **Ratings:** > > `| id | movie_id | rating |` > > > **Movies:** > > `| id | title |` > > > A typical movie record might be like this: > > `| 4 | Cloverfield (2008) |` > > > and there may be several rating records for Cloverfield, like this: > > `| 21 | 4 | 3 |` (rating number 21, on movie number 4, giving it a rating of 3) > > > `| 22 | 4 | 2 |` (rating number 22, on movie number 4, giving it a rating of 2) > > > `| 23 | 4 | 5 |` (rating number 23k on movie number 4, giving it a rating of 5) > > > **The question:** How do I create a JOIN query for only selecting the rows in the movie table that have more than `x` number of ratings in the ratings table? For example, in the above example if Cloverfield only had one rating in the ratings table and `x` was 2, it would not be selected. Thanks for any help or advice!
Use the HAVING clause. Something along these lines: ``` SELECT movies.id, movies.title, COUNT(ratings.id) AS num_ratings FROM movies LEFT JOIN ratings ON ratings.movie_id=movies.id GROUP BY movies.id HAVING num_ratings > 5; ```
175,738
<p>Weird issue:</p> <ol> <li>Open a large notepad window</li> <li>create a toolwindow (style WS_EX_TOOLWINDOW)</li> <li>create 2 more windows (normal overlapped) (WS_OVERLAPPED)</li> <li>close those 2 overlapped windows (child of desktop or the toolwindow)</li> <li>the toolwindow jumps behind the notepad window</li> </ol> <p>Does anyone know why this is the case? Or what I could be doing wrong? I would say 'bug in windows', but that is rarely the case.</p> <p>To answer questions:</p> <p>It is not a dialog window, but a full window. If i make it have correct children (ie: not a child of desktop), the taskbar entry for the children do not appear (probably easily fixable), but either way, the bug still happens. </p> <p>I have included example code that shows the issue. I am hoping I am just creating the window wrong or required to respond to a message I am not responding to. </p> <p>In this example, a tool window will open (no task bar entry, which is what is wanted). Then you click on that window, a subwindow will open. You click on the subwindow, another window will open. Then close both new subwindows and the original window, instead of getting focus, jumps immediately to behind other windows (notepad, etc).</p> <p>Thanks for any help!</p> <p>Example code to clarify:</p> <pre><code>// WindowToback.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "WindowToback.h" // Global Variables: HINSTANCE g_instance; HWND g_mainWnd = NULL; wchar_t *szWindowClass = L"WindowToBackSub"; wchar_t *szWindowClass2 = L"WindowToBackSub2"; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK WndProc2(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); MSG msg; MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } // Main message loop: while (GetMessage(&amp;msg, NULL, 0, 0)) { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WINDOWTOBACK)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WINDOWTOBACK); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); RegisterClassEx(&amp;wcex); wcex.lpfnWndProc = WndProc2; wcex.lpszClassName = szWindowClass2; return RegisterClassEx(&amp;wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { g_instance = hInstance; g_mainWnd = CreateWindowEx(WS_EX_TOOLWINDOW,szWindowClass, szWindowClass,WS_OVERLAPPED, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!g_mainWnd) return FALSE; ShowWindow(g_mainWnd, nCmdShow); UpdateWindow(g_mainWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_LBUTTONDOWN: { HWND l_hwnd = CreateWindow(szWindowClass2, szWindowClass2, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, g_instance, NULL); ShowWindow(l_hwnd,SW_SHOW); break; } case WM_DESTROY: { PostQuitMessage(0); return 0; } } return DefWindowProc(hWnd, message, wParam, lParam); } LRESULT CALLBACK WndProc2(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_LBUTTONDOWN: { HWND l_hwnd = CreateWindow(szWindowClass2, szWindowClass2, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, g_instance, NULL); ShowWindow(l_hwnd,SW_SHOW); } break; } return DefWindowProc(hWnd, message, wParam, lParam); </code></pre> <p>}</p>
[ { "answer_id": 180689, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": "<p>Are the three windows dialogs to another main window or are they applications in their own right?</p>\n\n<p>If they are dialog windows then I would check that their parent window is correctly assigned. </p>\n\n<p>If they are application windows then I would check that they are appearing in the taskbar. </p>\n\n<p>Without more information about the problem it is hard to give a more meaningful answer.</p>\n" }, { "answer_id": 1493404, "author": "Adrian McCarthy", "author_id": 1386054, "author_profile": "https://Stackoverflow.com/users/1386054", "pm_score": 2, "selected": true, "text": "<p>This isn't surprising. In fact, it's exactly the behavior I'd expect.</p>\n\n<p>You're tool window isn't jumping down; rather Notepad is jumping up.</p>\n\n<p>You closed the window that had activation. The system is going to activate the next-highest top-level window in the z-order. Your tool window doesn't a count as a top-level window in this regard (that's part of what being a tool window means). So Notepad gets activated, and it comes to the top.</p>\n\n<p>If you want your tool window to get activated instead, you probably don't really want a tool window.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25602/" ]
Weird issue: 1. Open a large notepad window 2. create a toolwindow (style WS\_EX\_TOOLWINDOW) 3. create 2 more windows (normal overlapped) (WS\_OVERLAPPED) 4. close those 2 overlapped windows (child of desktop or the toolwindow) 5. the toolwindow jumps behind the notepad window Does anyone know why this is the case? Or what I could be doing wrong? I would say 'bug in windows', but that is rarely the case. To answer questions: It is not a dialog window, but a full window. If i make it have correct children (ie: not a child of desktop), the taskbar entry for the children do not appear (probably easily fixable), but either way, the bug still happens. I have included example code that shows the issue. I am hoping I am just creating the window wrong or required to respond to a message I am not responding to. In this example, a tool window will open (no task bar entry, which is what is wanted). Then you click on that window, a subwindow will open. You click on the subwindow, another window will open. Then close both new subwindows and the original window, instead of getting focus, jumps immediately to behind other windows (notepad, etc). Thanks for any help! Example code to clarify: ``` // WindowToback.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "WindowToback.h" // Global Variables: HINSTANCE g_instance; HWND g_mainWnd = NULL; wchar_t *szWindowClass = L"WindowToBackSub"; wchar_t *szWindowClass2 = L"WindowToBackSub2"; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK WndProc2(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); MSG msg; MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WINDOWTOBACK)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WINDOWTOBACK); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); RegisterClassEx(&wcex); wcex.lpfnWndProc = WndProc2; wcex.lpszClassName = szWindowClass2; return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { g_instance = hInstance; g_mainWnd = CreateWindowEx(WS_EX_TOOLWINDOW,szWindowClass, szWindowClass,WS_OVERLAPPED, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!g_mainWnd) return FALSE; ShowWindow(g_mainWnd, nCmdShow); UpdateWindow(g_mainWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_LBUTTONDOWN: { HWND l_hwnd = CreateWindow(szWindowClass2, szWindowClass2, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, g_instance, NULL); ShowWindow(l_hwnd,SW_SHOW); break; } case WM_DESTROY: { PostQuitMessage(0); return 0; } } return DefWindowProc(hWnd, message, wParam, lParam); } LRESULT CALLBACK WndProc2(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_LBUTTONDOWN: { HWND l_hwnd = CreateWindow(szWindowClass2, szWindowClass2, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, g_instance, NULL); ShowWindow(l_hwnd,SW_SHOW); } break; } return DefWindowProc(hWnd, message, wParam, lParam); ``` }
This isn't surprising. In fact, it's exactly the behavior I'd expect. You're tool window isn't jumping down; rather Notepad is jumping up. You closed the window that had activation. The system is going to activate the next-highest top-level window in the z-order. Your tool window doesn't a count as a top-level window in this regard (that's part of what being a tool window means). So Notepad gets activated, and it comes to the top. If you want your tool window to get activated instead, you probably don't really want a tool window.
175,739
<p>I'm hoping there's something in the same conceptual space as the old VB6 <code>IsNumeric()</code> function?</p>
[ { "answer_id": 175746, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 5, "selected": false, "text": "<p>Try the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\" rel=\"noreferrer\">isNan function</a>:</p>\n\n<blockquote>\n <p>The isNaN() function determines whether a value is an illegal number (Not-a-Number).</p>\n \n <p>This function returns true if the value equates to NaN. Otherwise it returns false.</p>\n \n <p>This function is different from the Number specific <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN\" rel=\"noreferrer\">Number.isNaN()</a> method.</p>\n \n <p>&nbsp; The global isNaN() function, converts the tested value to a Number, then tests it.</p>\n \n <p>Number.isNan() does not convert the values to a Number, and will not return true for any value that is not of the type Number...</p>\n</blockquote>\n" }, { "answer_id": 175754, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 2, "selected": false, "text": "<p>parseInt(), but be aware that this function is a bit different in the sense that it for example returns 100 for parseInt(\"100px\").</p>\n" }, { "answer_id": 175775, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 6, "selected": false, "text": "<p>And you could go the RegExp-way:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var num = &quot;987238&quot;;\n\nif(num.match(/^-?\\d+$/)){\n //valid integer (positive or negative)\n}else if(num.match(/^\\d+\\.\\d+$/)){\n //valid float\n}else{\n //not valid number\n}\n</code></pre>\n" }, { "answer_id": 175787, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 13, "selected": true, "text": "<p><strong>2nd October 2020:</strong> note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point &quot;<code>.</code>&quot;:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function isNumeric(str) {\n if (typeof str != &quot;string&quot;) return false // we only process strings! \n return !isNaN(str) &amp;&amp; // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...\n !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail\n}\n</code></pre>\n<hr />\n<h2>To check if a variable (including a string) is a number, check if it is not a number:</h2>\n<p>This works regardless of whether the variable content is a string or number.</p>\n<pre><code>isNaN(num) // returns true if the variable does NOT contain a valid number\n</code></pre>\n<h3>Examples</h3>\n<pre><code>isNaN(123) // false\nisNaN('123') // false\nisNaN('1e10000') // false (This translates to Infinity, which is a number)\nisNaN('foo') // true\nisNaN('10px') // true\nisNaN('') // false\nisNaN(' ') // false\nisNaN(false) // false\n</code></pre>\n<p>Of course, you can negate this if you need to. For example, to implement the <code>IsNumeric</code> example you gave:</p>\n<pre><code>function isNumeric(num){\n return !isNaN(num)\n}\n</code></pre>\n<h2>To convert a string containing a number into a number:</h2>\n<p>Only works if the string <em>only</em> contains numeric characters, else it returns <code>NaN</code>.</p>\n<pre><code>+num // returns the numeric value of the string, or NaN \n // if the string isn't purely numeric characters\n</code></pre>\n<h3>Examples</h3>\n<pre><code>+'12' // 12\n+'12.' // 12\n+'12..' // NaN\n+'.12' // 0.12\n+'..12' // NaN\n+'foo' // NaN\n+'12px' // NaN\n</code></pre>\n<h2>To convert a string loosely to a number</h2>\n<p>Useful for converting '12px' to 12, for example:</p>\n<pre><code>parseInt(num) // extracts a numeric value from the \n // start of the string, or NaN.\n</code></pre>\n<h3>Examples</h3>\n<pre><code>parseInt('12') // 12\nparseInt('aaa') // NaN\nparseInt('12px') // 12\nparseInt('foo2') // NaN These last three may\nparseInt('12a5') // 12 be different from what\nparseInt('0x10') // 16 you expected to see.\n</code></pre>\n<h2>Floats</h2>\n<p>Bear in mind that, unlike <code>+num</code>, <code>parseInt</code> (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use <code>parseInt()</code> <em>because of</em> this behaviour, <a href=\"https://parsebox.io/dthree/gyeveeygrngl\" rel=\"noreferrer\">you're probably better off using another method instead</a>):</p>\n<pre><code>+'12.345' // 12.345\nparseInt(12.345) // 12\nparseInt('12.345') // 12\n</code></pre>\n<h2>Empty strings</h2>\n<p>Empty strings may be a little counter-intuitive. <code>+num</code> converts empty strings or strings with spaces to zero, and <code>isNaN()</code> assumes the same:</p>\n<pre><code>+'' // 0\n+' ' // 0\nisNaN('') // false\nisNaN(' ') // false\n</code></pre>\n<p>But <code>parseInt()</code> does not agree:</p>\n<pre><code>parseInt('') // NaN\nparseInt(' ') // NaN\n</code></pre>\n" }, { "answer_id": 9776169, "author": "Rafael", "author_id": 1279325, "author_profile": "https://Stackoverflow.com/users/1279325", "pm_score": 2, "selected": false, "text": "<p>Well, I'm using this one I made...</p>\n<p>It's been working so far:</p>\n<pre><code>function checkNumber(value) {\n return value % 1 == 0;\n}\n</code></pre>\n<p>If you spot any problem with it, tell me, please.</p>\n" }, { "answer_id": 10844900, "author": "Siubear", "author_id": 711801, "author_profile": "https://Stackoverflow.com/users/711801", "pm_score": 2, "selected": false, "text": "<p>Quote:</p>\n\n<blockquote>\n <p>isNaN(num) // returns true if the variable does NOT contain a valid number</p>\n</blockquote>\n\n<p>is not entirely true if you need to check for leading/trailing spaces - for example when a certain quantity of digits is required, and you need to get, say, '1111' and not ' 111' or '111 ' for perhaps a PIN input.</p>\n\n<p>Better to use:</p>\n\n<pre><code>var num = /^\\d+$/.test(num)\n</code></pre>\n" }, { "answer_id": 19135863, "author": "mark", "author_id": 80002, "author_profile": "https://Stackoverflow.com/users/80002", "pm_score": 4, "selected": false, "text": "<p>Old question, but there are several points missing in the given answers.</p>\n\n<p><strong>Scientific notation.</strong></p>\n\n<p><code>!isNaN('1e+30')</code> is <code>true</code>, however in most of the cases when people ask for numbers, they do not want to match things like <code>1e+30</code>.</p>\n\n<p><strong>Large floating numbers may behave weird</strong></p>\n\n<p>Observe (using Node.js):</p>\n\n<pre><code>&gt; var s = Array(16 + 1).join('9')\nundefined\n&gt; s.length\n16\n&gt; s\n'9999999999999999'\n&gt; !isNaN(s)\ntrue\n&gt; Number(s)\n10000000000000000\n&gt; String(Number(s)) === s\nfalse\n&gt;\n</code></pre>\n\n<p>On the other hand:</p>\n\n<pre><code>&gt; var s = Array(16 + 1).join('1')\nundefined\n&gt; String(Number(s)) === s\ntrue\n&gt; var s = Array(15 + 1).join('9')\nundefined\n&gt; String(Number(s)) === s\ntrue\n&gt;\n</code></pre>\n\n<p>So, if one expects <code>String(Number(s)) === s</code>, then better limit your strings to 15 digits at most (after omitting leading zeros).</p>\n\n<p><strong>Infinity</strong></p>\n\n<pre><code>&gt; typeof Infinity\n'number'\n&gt; !isNaN('Infinity')\ntrue\n&gt; isFinite('Infinity')\nfalse\n&gt;\n</code></pre>\n\n<p>Given all that, checking that the given string is a number satisfying all of the following:</p>\n\n<ul>\n<li>non scientific notation</li>\n<li>predictable conversion to <code>Number</code> and back to <code>String</code></li>\n<li>finite</li>\n</ul>\n\n<p>is not such an easy task. Here is a simple version:</p>\n\n<pre><code> function isNonScientificNumberString(o) {\n if (!o || typeof o !== 'string') {\n // Should not be given anything but strings.\n return false;\n }\n return o.length &lt;= 15 &amp;&amp; o.indexOf('e+') &lt; 0 &amp;&amp; o.indexOf('E+') &lt; 0 &amp;&amp; !isNaN(o) &amp;&amp; isFinite(o);\n }\n</code></pre>\n\n<p>However, even this one is far from complete. Leading zeros are not handled here, but they do screw the length test.</p>\n" }, { "answer_id": 23389525, "author": "Predhin", "author_id": 1122656, "author_profile": "https://Stackoverflow.com/users/1122656", "pm_score": 2, "selected": false, "text": "<p>PFB the working solution:</p>\n\n<pre><code> function(check){ \n check = check + \"\";\n var isNumber = check.trim().length&gt;0? !isNaN(check):false;\n return isNumber;\n }\n</code></pre>\n" }, { "answer_id": 24457420, "author": "Gavin", "author_id": 2211053, "author_profile": "https://Stackoverflow.com/users/2211053", "pm_score": 7, "selected": false, "text": "<p>If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as <code>isNaN</code> are too complicated for something so simple.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function isNumeric(value) {\n return /^-?\\d+$/.test(value);\n}\n\nconsole.log(isNumeric('abcd')); // false\nconsole.log(isNumeric('123a')); // false\nconsole.log(isNumeric('1')); // true\nconsole.log(isNumeric('1234567890')); // true\nconsole.log(isNumeric('-23')); // true\nconsole.log(isNumeric(1234)); // true\nconsole.log(isNumeric(1234n)); // true\nconsole.log(isNumeric('123.4')); // false\nconsole.log(isNumeric('')); // false\nconsole.log(isNumeric(undefined)); // false\nconsole.log(isNumeric(null)); // false\n</code></pre>\n<p>To only allow <em>positive</em> whole numbers use this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function isNumeric(value) {\n return /^\\d+$/.test(value);\n}\n\nconsole.log(isNumeric('123')); // true\nconsole.log(isNumeric('-23')); // false\n</code></pre>\n" }, { "answer_id": 24635695, "author": "rwheadon", "author_id": 396988, "author_profile": "https://Stackoverflow.com/users/396988", "pm_score": 0, "selected": false, "text": "<p>In my application we are only allowing a-z A-Z and 0-9 characters. I found the answer above using \" <em>string</em> % 1 === 0\" worked unless the string began with 0xnn (like 0x10) and then it would return it as numeric when we didn't want it to. The following simple trap in my numeric check seems to do the trick in our specific cases. </p>\n\n<pre><code>function isStringNumeric(str_input){ \n //concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up \n //very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine \n return '1'.concat(str_input) % 1 === 0;}\n</code></pre>\n\n<p><strong>Warning</strong> : This might be exploiting a longstanding bug in Javascript and Actionscript [Number(\"1\" + the_string) % 1 === 0)], I can't speak for that, but it is exactly what we needed.</p>\n" }, { "answer_id": 25193433, "author": "GoTo", "author_id": 832370, "author_profile": "https://Stackoverflow.com/users/832370", "pm_score": 0, "selected": false, "text": "<p>My solution:</p>\n\n<pre><code>// returns true for positive ints; \n// no scientific notation, hexadecimals or floating point dots\n\nvar isPositiveInt = function(str) { \n var result = true, chr;\n for (var i = 0, n = str.length; i &lt; n; i++) {\n chr = str.charAt(i);\n if ((chr &lt; \"0\" || chr &gt; \"9\") &amp;&amp; chr != \",\") { //not digit or thousands separator\n result = false;\n break;\n };\n if (i == 0 &amp;&amp; (chr == \"0\" || chr == \",\")) { //should not start with 0 or ,\n result = false;\n break;\n };\n };\n return result;\n };\n</code></pre>\n\n<p>You can add additional conditions inside the loop, to fit you particular needs.</p>\n" }, { "answer_id": 26343042, "author": "Murray Lang", "author_id": 4138008, "author_profile": "https://Stackoverflow.com/users/4138008", "pm_score": -1, "selected": false, "text": "<p>I do it like this:</p>\n\n<pre><code>function isString(value)\n{\n return value.length !== undefined;\n}\nfunction isNumber(value)\n{\n return value.NaN !== undefined;\n}\n</code></pre>\n\n<p>Of course isString() will be tripped up here if you pass some other object that has 'length' defined.</p>\n" }, { "answer_id": 29028824, "author": "GibboK", "author_id": 379008, "author_profile": "https://Stackoverflow.com/users/379008", "pm_score": 4, "selected": false, "text": "<p>You can use the result of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"noreferrer\">Number</a> when passing an argument to its constructor.</p>\n\n<p>If the argument (a string) cannot be converted into a number, it returns NaN, so you can determinate if the string provided was a valid number or not.</p>\n\n<p>Notes: Note when passing empty string or <code>'\\t\\t'</code> and <code>'\\n\\t'</code> as Number will return 0; Passing true will return 1 and false returns 0.</p>\n\n<pre><code> Number('34.00') // 34\n Number('-34') // -34\n Number('123e5') // 12300000\n Number('123e-5') // 0.00123\n Number('999999999999') // 999999999999\n Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit)\n Number('0xFF') // 255\n Number('Infinity') // Infinity \n\n Number('34px') // NaN\n Number('xyz') // NaN\n Number('true') // NaN\n Number('false') // NaN\n\n // cavets\n Number(' ') // 0\n Number('\\t\\t') // 0\n Number('\\n\\t') // 0\n</code></pre>\n" }, { "answer_id": 32539708, "author": "Endless", "author_id": 1008999, "author_profile": "https://Stackoverflow.com/users/1008999", "pm_score": 0, "selected": false, "text": "<p>My attempt at a slightly confusing, Pherhaps not the best solution</p>\n\n<pre><code>function isInt(a){\n return a === \"\"+~~a\n}\n\n\nconsole.log(isInt('abcd')); // false\nconsole.log(isInt('123a')); // false\nconsole.log(isInt('1')); // true\nconsole.log(isInt('0')); // true\nconsole.log(isInt('-0')); // false\nconsole.log(isInt('01')); // false\nconsole.log(isInt('10')); // true\nconsole.log(isInt('-1234567890')); // true\nconsole.log(isInt(1234)); // false\nconsole.log(isInt('123.4')); // false\nconsole.log(isInt('')); // false\n\n// other types then string returns false\nconsole.log(isInt(5)); // false\nconsole.log(isInt(undefined)); // false\nconsole.log(isInt(null)); // false\nconsole.log(isInt('0x1')); // false\nconsole.log(isInt(Infinity)); // false\n</code></pre>\n" }, { "answer_id": 35759874, "author": "Michael", "author_id": 543873, "author_profile": "https://Stackoverflow.com/users/543873", "pm_score": 6, "selected": false, "text": "<p>If you really want to make sure that a string contains only a number, any number (integer or floating point), and exactly a number, you <em>cannot</em> use <code>parseInt()</code>/ <code>parseFloat()</code>, <code>Number()</code>, or <code>!isNaN()</code> by themselves. Note that <code>!isNaN()</code> is actually returning <code>true</code> when <code>Number()</code> would return a number, and <code>false</code> when it would return <code>NaN</code>, so I will exclude it from the rest of the discussion.</p>\n\n<p>The problem with <code>parseFloat()</code> is that it will return a number if the string contains any number, even if the string doesn't contain <em>only</em> and <em>exactly</em> a number:</p>\n\n<pre><code>parseFloat(\"2016-12-31\") // returns 2016\nparseFloat(\"1-1\") // return 1\nparseFloat(\"1.2.3\") // returns 1.2\n</code></pre>\n\n<p>The problem with <code>Number()</code> is that it will return a number in cases where the passed value is not a number at all!</p>\n\n<pre><code>Number(\"\") // returns 0\nNumber(\" \") // returns 0\nNumber(\" \\u00A0 \\t\\n\\r\") // returns 0\n</code></pre>\n\n<p>The problem with rolling your own regex is that unless you create the exact regex for matching a floating point number as Javascript recognizes it you are going to miss cases or recognize cases where you shouldn't. And even if you can roll your own regex, why? There are simpler built-in ways to do it.</p>\n\n<p>However, it turns out that <code>Number()</code> (and <code>isNaN()</code>) does the right thing for every case where <code>parseFloat()</code> returns a number when it shouldn't, and vice versa. So to find out if a string is really exactly and only a number, call both functions and see if they <em>both</em> return true:</p>\n\n<pre><code>function isNumber(str) {\n if (typeof str != \"string\") return false // we only process strings!\n // could also coerce to string: str = \"\"+str\n return !isNaN(str) &amp;&amp; !isNaN(parseFloat(str))\n}\n</code></pre>\n" }, { "answer_id": 41458529, "author": "The Dembinski", "author_id": 5689384, "author_profile": "https://Stackoverflow.com/users/5689384", "pm_score": 2, "selected": false, "text": "<p>If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (<a href=\"https://github.com/moment/moment\" rel=\"nofollow noreferrer\">https://github.com/moment/moment</a>). Here's something that I took away from it:</p>\n\n<pre><code>function isNumeric(val) {\n var _val = +val;\n return (val !== val + 1) //infinity check\n &amp;&amp; (_val === +val) //Cute coercion check\n &amp;&amp; (typeof val !== 'object') //Array/object check\n}\n</code></pre>\n\n<p>Handles the following cases:</p>\n\n<p>True! :</p>\n\n<pre><code>isNumeric(\"1\"))\nisNumeric(1e10))\nisNumeric(1E10))\nisNumeric(+\"6e4\"))\nisNumeric(\"1.2222\"))\nisNumeric(\"-1.2222\"))\nisNumeric(\"-1.222200000000000000\"))\nisNumeric(\"1.222200000000000000\"))\nisNumeric(1))\nisNumeric(0))\nisNumeric(-0))\nisNumeric(1010010293029))\nisNumeric(1.100393830000))\nisNumeric(Math.LN2))\nisNumeric(Math.PI))\nisNumeric(5e10))\n</code></pre>\n\n<p>False! :</p>\n\n<pre><code>isNumeric(NaN))\nisNumeric(Infinity))\nisNumeric(-Infinity))\nisNumeric())\nisNumeric(undefined))\nisNumeric('[1,2,3]'))\nisNumeric({a:1,b:2}))\nisNumeric(null))\nisNumeric([1]))\nisNumeric(new Date()))\n</code></pre>\n\n<p>Ironically, the one I am struggling with the most:</p>\n\n<pre><code>isNumeric(new Number(1)) =&gt; false\n</code></pre>\n\n<p>Any suggestions welcome. :]</p>\n" }, { "answer_id": 41546441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Maybe there are one or two people coming across this question who need a <strong>much stricter</strong> check than usual (like I did). In that case, this might be useful:</p>\n\n<pre><code>if(str === String(Number(str))) {\n // it's a \"perfectly formatted\" number\n}\n</code></pre>\n\n<p>Beware! This will reject strings like <code>.1</code>, <code>40.000</code>, <code>080</code>, <code>00.1</code>. It's very picky - the string must match the \"<strong>most minimal perfect form</strong>\" of the number for this test to pass.</p>\n\n<p>It uses the <code>String</code> and <code>Number</code> constructor to cast the string to a number and back again and thus checks if the JavaScript engine's \"perfect minimal form\" (the one it got converted to with the initial <code>Number</code> constructor) matches the original string.</p>\n" }, { "answer_id": 42356340, "author": "JohnP2", "author_id": 1691651, "author_profile": "https://Stackoverflow.com/users/1691651", "pm_score": 4, "selected": false, "text": "<p>I have tested and Michael's solution is best. Vote for his answer above (search this page for \"If you really want to make sure that a string\" to find it). In essence, his answer is this:</p>\n\n<pre><code>function isNumeric(num){\n num = \"\" + num; //coerce num to be a string\n return !isNaN(num) &amp;&amp; !isNaN(parseFloat(num));\n}\n</code></pre>\n\n<p>It works for every test case, which I documented here:\n<a href=\"https://jsfiddle.net/wggehvp9/5/\" rel=\"noreferrer\">https://jsfiddle.net/wggehvp9/5/</a></p>\n\n<p>Many of the other solutions fail for these edge cases:\n' ', null, \"\", true, and [].\nIn theory, you could use them, with proper error handling, for example:</p>\n\n<pre><code>return !isNaN(num);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>return (+num === +num);\n</code></pre>\n\n<p>with special handling for \n/\\s/, null, \"\", true, false, [] (and others?)</p>\n" }, { "answer_id": 43979827, "author": "Ultroman the Tacoman", "author_id": 1289974, "author_profile": "https://Stackoverflow.com/users/1289974", "pm_score": 3, "selected": false, "text": "<p>Why is jQuery's implementation not good enough?</p>\n\n<pre><code>function isNumeric(a) {\n var b = a &amp;&amp; a.toString();\n return !$.isArray(a) &amp;&amp; b - parseFloat(b) + 1 &gt;= 0;\n};\n</code></pre>\n\n<p>Michael suggested something like this (although I've stolen \"user1691651 - John\"'s altered version here):</p>\n\n<pre><code>function isNumeric(num){\n num = \"\" + num; //coerce num to be a string\n return !isNaN(num) &amp;&amp; !isNaN(parseFloat(num));\n}\n</code></pre>\n\n<p>The following is a solution with most likely bad performance, but solid results. It is a contraption made from the jQuery 1.12.4 implementation and Michael's answer, with an extra check for leading/trailing spaces (because Michael's version returns true for numerics with leading/trailing spaces):</p>\n\n<pre><code>function isNumeric(a) {\n var str = a + \"\";\n var b = a &amp;&amp; a.toString();\n return !$.isArray(a) &amp;&amp; b - parseFloat(b) + 1 &gt;= 0 &amp;&amp;\n !/^\\s+|\\s+$/g.test(str) &amp;&amp;\n !isNaN(str) &amp;&amp; !isNaN(parseFloat(str));\n};\n</code></pre>\n\n<p>The latter version has two new variables, though. One could get around one of those, by doing:</p>\n\n<pre><code>function isNumeric(a) {\n if ($.isArray(a)) return false;\n var b = a &amp;&amp; a.toString();\n a = a + \"\";\n return b - parseFloat(b) + 1 &gt;= 0 &amp;&amp;\n !/^\\s+|\\s+$/g.test(a) &amp;&amp;\n !isNaN(a) &amp;&amp; !isNaN(parseFloat(a));\n};\n</code></pre>\n\n<p>I haven't tested any of these very much, by other means than manually testing the few use-cases I'll be hitting with my current predicament, which is all very standard stuff. This is a \"standing-on-the-shoulders-of-giants\" situation.</p>\n" }, { "answer_id": 47333150, "author": "What Would Be Cool", "author_id": 753279, "author_profile": "https://Stackoverflow.com/users/753279", "pm_score": 0, "selected": false, "text": "<p>You could make use of types, like with the <a href=\"https://flow.org/en/docs/types/primitives/\" rel=\"nofollow noreferrer\">flow librar</a>y, to get static, compile time checking. Of course not terribly useful for user input.</p>\n\n<pre><code>// @flow\n\nfunction acceptsNumber(value: number) {\n // ...\n}\n\nacceptsNumber(42); // Works!\nacceptsNumber(3.14); // Works!\nacceptsNumber(NaN); // Works!\nacceptsNumber(Infinity); // Works!\nacceptsNumber(\"foo\"); // Error!\n</code></pre>\n" }, { "answer_id": 47515519, "author": "lifebalance", "author_id": 307454, "author_profile": "https://Stackoverflow.com/users/307454", "pm_score": 1, "selected": false, "text": "<p>Here's an elegant <strong>one-liner</strong> to check if <code>sNum</code> is a valid numeric value. The code has been tested for a wide variety of inputs as well.</p>\n<pre><code>// returns True if sNum is a numeric value \n!!sNum &amp;&amp; !isNaN(+sNum.replace(/\\s|\\$/g, '')); \n</code></pre>\n<p>Hat tip to <strong>@gman</strong> for catching the error.</p>\n" }, { "answer_id": 51056946, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "<p>I like the simplicity of this.</p>\n<pre><code>Number.isNaN(Number(value))\n</code></pre>\n<p>The above is regular Javascript, but I'm using this in conjunction with a typescript <a href=\"http://www.typescriptlang.org/docs/handbook/advanced-types.html\" rel=\"noreferrer\">typeguard</a> for smart type checking. This is very useful for the typescript compiler to give you correct intellisense, and no type errors.</p>\n<h3>Typescript typeguards</h3>\n<p><strong>Warning: See Jeremy's comment below.</strong> This has some issues with certain values and I don't have time to fix it now, but the idea of using a typescript typeguard is useful so I won't delete this section.</p>\n<pre><code>isNotNumber(value: string | number): value is string {\n return Number.isNaN(Number(this.smartImageWidth));\n}\nisNumber(value: string | number): value is number {\n return Number.isNaN(Number(this.smartImageWidth)) === false;\n}\n</code></pre>\n<p>Let's say you have a property <code>width</code> which is <code>number | string</code>. You may want to do logic based on whether or not it's a string.</p>\n<pre><code>var width: number|string;\nwidth = &quot;100vw&quot;;\n\nif (isNotNumber(width)) \n{\n // the compiler knows that width here must be a string\n if (width.endsWith('vw')) \n {\n // we have a 'width' such as 100vw\n } \n}\nelse \n{\n // the compiler is smart and knows width here must be number\n var doubleWidth = width * 2; \n}\n</code></pre>\n<p>The typeguard is smart enough to constrain the type of <code>width</code> within the <code>if</code> statement to be ONLY <code>string</code>. This permits the compiler to allow <code>width.endsWith(...)</code> which it wouldn't allow if the type was <code>string | number</code>.</p>\n<p>You can call the typeguard whatever you want <code>isNotNumber</code>, <code>isNumber</code>, <code>isString</code>, <code>isNotString</code> but I think <code>isString</code> is kind of ambiguous and harder to read.</p>\n" }, { "answer_id": 52710457, "author": "Travis Parks", "author_id": 984335, "author_profile": "https://Stackoverflow.com/users/984335", "pm_score": 2, "selected": false, "text": "<p>I recently wrote an article about ways to ensure a variable is a valid number: <a href=\"https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md\" rel=\"nofollow noreferrer\">https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md</a> The article explains how to ensure floating point or integer, if that's important (<code>+x</code> vs <code>~~x</code>).</p>\n\n<p>The article assumes the variable is a <code>string</code> or a <code>number</code> to begin with and <code>trim</code> is available/polyfilled. It wouldn't be hard to extend it to handle other types, as well. Here's the meat of it:</p>\n\n<pre><code>// Check for a valid float\nif (x == null\n || (\"\" + x).trim() === \"\"\n || isNaN(+x)) {\n return false; // not a float\n}\n\n// Check for a valid integer\nif (x == null\n || (\"\" + x).trim() === \"\"\n || ~~x !== +x) {\n return false; // not an integer\n}\n</code></pre>\n" }, { "answer_id": 52986361, "author": "Hamzeen Hameem", "author_id": 4947422, "author_profile": "https://Stackoverflow.com/users/4947422", "pm_score": 6, "selected": false, "text": "<p>The accepted answer for this question has quite a few flaws (as highlighted by couple of other users). This is one of the easiest &amp; proven way to approach it in javascript:</p>\n\n<pre><code>function isNumeric(n) {\n return !isNaN(parseFloat(n)) &amp;&amp; isFinite(n);\n}\n</code></pre>\n\n<p>Below are some good test cases:</p>\n\n<pre><code>console.log(isNumeric(12345678912345678912)); // true\nconsole.log(isNumeric('2 ')); // true\nconsole.log(isNumeric('-32.2 ')); // true\nconsole.log(isNumeric(-32.2)); // true\nconsole.log(isNumeric(undefined)); // false\n\n// the accepted answer fails at these tests:\nconsole.log(isNumeric('')); // false\nconsole.log(isNumeric(null)); // false\nconsole.log(isNumeric([])); // false\n</code></pre>\n" }, { "answer_id": 53875569, "author": "cdeutsch", "author_id": 346259, "author_profile": "https://Stackoverflow.com/users/346259", "pm_score": 2, "selected": false, "text": "<p>Save yourself the headache of trying to find a \"built-in\" solution.</p>\n\n<p>There isn't a good answer, and the hugely upvoted answer in this thread is wrong.</p>\n\n<p><code>npm install is-number</code></p>\n\n<blockquote>\n <p>In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:</p>\n</blockquote>\n\n<pre><code>console.log(+[]); //=&gt; 0\nconsole.log(+''); //=&gt; 0\nconsole.log(+' '); //=&gt; 0\nconsole.log(typeof NaN); //=&gt; 'number'\n</code></pre>\n" }, { "answer_id": 54442167, "author": "gvlax", "author_id": 988394, "author_profile": "https://Stackoverflow.com/users/988394", "pm_score": 2, "selected": false, "text": "<pre><code>function isNumberCandidate(s) {\n const str = (''+ s).trim();\n if (str.length === 0) return false;\n return !isNaN(+str);\n}\n\nconsole.log(isNumberCandidate('1')); // true\nconsole.log(isNumberCandidate('a')); // false\nconsole.log(isNumberCandidate('000')); // true\nconsole.log(isNumberCandidate('1a')); // false \nconsole.log(isNumberCandidate('1e')); // false\nconsole.log(isNumberCandidate('1e-1')); // true\nconsole.log(isNumberCandidate('123.3')); // true\nconsole.log(isNumberCandidate('')); // false\nconsole.log(isNumberCandidate(' ')); // false\nconsole.log(isNumberCandidate(1)); // true\nconsole.log(isNumberCandidate(0)); // true\nconsole.log(isNumberCandidate(NaN)); // false\nconsole.log(isNumberCandidate(undefined)); // false\nconsole.log(isNumberCandidate(null)); // false\nconsole.log(isNumberCandidate(-1)); // true\nconsole.log(isNumberCandidate('-1')); // true\nconsole.log(isNumberCandidate('-1.2')); // true\nconsole.log(isNumberCandidate(0.0000001)); // true\nconsole.log(isNumberCandidate('0.0000001')); // true\nconsole.log(isNumberCandidate(Infinity)); // true\nconsole.log(isNumberCandidate(-Infinity)); // true\n\nconsole.log(isNumberCandidate('Infinity')); // true\n\nif (isNumberCandidate(s)) {\n // use +s as a number\n +s ...\n}\n</code></pre>\n" }, { "answer_id": 54460006, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": -1, "selected": false, "text": "<p>Just use <code>isNaN()</code>, this will convert the string to a <strong>number</strong> and if get a valid <strong>number</strong>, will return <code>false</code>...</p>\n\n<pre><code>isNaN(\"Alireza\"); //return true\nisNaN(\"123\"); //return false\n</code></pre>\n" }, { "answer_id": 54997869, "author": "haxpanel", "author_id": 789076, "author_profile": "https://Stackoverflow.com/users/789076", "pm_score": -1, "selected": false, "text": "<p>I'm using the following:</p>\n\n<pre><code>const isNumber = s =&gt; !isNaN(+s)\n</code></pre>\n" }, { "answer_id": 55204768, "author": "Abtin Gramian", "author_id": 7003429, "author_profile": "https://Stackoverflow.com/users/7003429", "pm_score": 3, "selected": false, "text": "<p><strong>When guarding against empty strings and <code>null</code></strong></p>\n<pre><code>// Base cases that are handled properly\nNumber.isNaN(Number('1')); // =&gt; false\nNumber.isNaN(Number('-1')); // =&gt; false\nNumber.isNaN(Number('1.1')); // =&gt; false\nNumber.isNaN(Number('-1.1')); // =&gt; false\nNumber.isNaN(Number('asdf')); // =&gt; true\nNumber.isNaN(Number(undefined)); // =&gt; true\n\n// Special notation cases that are handled properly\nNumber.isNaN(Number('1e1')); // =&gt; false\nNumber.isNaN(Number('1e-1')); // =&gt; false\nNumber.isNaN(Number('-1e1')); // =&gt; false\nNumber.isNaN(Number('-1e-1')); // =&gt; false\nNumber.isNaN(Number('0b1')); // =&gt; false\nNumber.isNaN(Number('0o1')); // =&gt; false\nNumber.isNaN(Number('0xa')); // =&gt; false\n\n// Edge cases that will FAIL if not guarded against\nNumber.isNaN(Number('')); // =&gt; false\nNumber.isNaN(Number(' ')); // =&gt; false\nNumber.isNaN(Number(null)); // =&gt; false\n\n// Edge cases that are debatable\nNumber.isNaN(Number('-0b1')); // =&gt; true\nNumber.isNaN(Number('-0o1')); // =&gt; true\nNumber.isNaN(Number('-0xa')); // =&gt; true\nNumber.isNaN(Number('Infinity')); // =&gt; false \nNumber.isNaN(Number('INFINITY')); // =&gt; true \nNumber.isNaN(Number('-Infinity')); // =&gt; false \nNumber.isNaN(Number('-INFINITY')); // =&gt; true \n</code></pre>\n<p><strong>When NOT guarding against empty strings and <code>null</code></strong></p>\n<p>Using <code>parseInt</code>:</p>\n<pre><code>// Base cases that are handled properly\nNumber.isNaN(parseInt('1')); // =&gt; false\nNumber.isNaN(parseInt('-1')); // =&gt; false\nNumber.isNaN(parseInt('1.1')); // =&gt; false\nNumber.isNaN(parseInt('-1.1')); // =&gt; false\nNumber.isNaN(parseInt('asdf')); // =&gt; true\nNumber.isNaN(parseInt(undefined)); // =&gt; true\nNumber.isNaN(parseInt('')); // =&gt; true\nNumber.isNaN(parseInt(' ')); // =&gt; true\nNumber.isNaN(parseInt(null)); // =&gt; true\n\n// Special notation cases that are handled properly\nNumber.isNaN(parseInt('1e1')); // =&gt; false\nNumber.isNaN(parseInt('1e-1')); // =&gt; false\nNumber.isNaN(parseInt('-1e1')); // =&gt; false\nNumber.isNaN(parseInt('-1e-1')); // =&gt; false\nNumber.isNaN(parseInt('0b1')); // =&gt; false\nNumber.isNaN(parseInt('0o1')); // =&gt; false\nNumber.isNaN(parseInt('0xa')); // =&gt; false\n\n// Edge cases that are debatable\nNumber.isNaN(parseInt('-0b1')); // =&gt; false\nNumber.isNaN(parseInt('-0o1')); // =&gt; false\nNumber.isNaN(parseInt('-0xa')); // =&gt; false\nNumber.isNaN(parseInt('Infinity')); // =&gt; true \nNumber.isNaN(parseInt('INFINITY')); // =&gt; true \nNumber.isNaN(parseInt('-Infinity')); // =&gt; true \nNumber.isNaN(parseInt('-INFINITY')); // =&gt; true \n</code></pre>\n<p>Using <code>parseFloat</code>:</p>\n<pre><code>// Base cases that are handled properly\nNumber.isNaN(parseFloat('1')); // =&gt; false\nNumber.isNaN(parseFloat('-1')); // =&gt; false\nNumber.isNaN(parseFloat('1.1')); // =&gt; false\nNumber.isNaN(parseFloat('-1.1')); // =&gt; false\nNumber.isNaN(parseFloat('asdf')); // =&gt; true\nNumber.isNaN(parseFloat(undefined)); // =&gt; true\nNumber.isNaN(parseFloat('')); // =&gt; true\nNumber.isNaN(parseFloat(' ')); // =&gt; true\nNumber.isNaN(parseFloat(null)); // =&gt; true\n\n// Special notation cases that are handled properly\nNumber.isNaN(parseFloat('1e1')); // =&gt; false\nNumber.isNaN(parseFloat('1e-1')); // =&gt; false\nNumber.isNaN(parseFloat('-1e1')); // =&gt; false\nNumber.isNaN(parseFloat('-1e-1')); // =&gt; false\nNumber.isNaN(parseFloat('0b1')); // =&gt; false\nNumber.isNaN(parseFloat('0o1')); // =&gt; false\nNumber.isNaN(parseFloat('0xa')); // =&gt; false\n\n// Edge cases that are debatable\nNumber.isNaN(parseFloat('-0b1')); // =&gt; false\nNumber.isNaN(parseFloat('-0o1')); // =&gt; false\nNumber.isNaN(parseFloat('-0xa')); // =&gt; false\nNumber.isNaN(parseFloat('Infinity')); // =&gt; false \nNumber.isNaN(parseFloat('INFINITY')); // =&gt; true \nNumber.isNaN(parseFloat('-Infinity')); // =&gt; false \nNumber.isNaN(parseFloat('-INFINITY')); // =&gt; true\n</code></pre>\n<p><em>Notes:</em></p>\n<ul>\n<li><em>Only string, empty, and uninitialized values are considered in keeping with addressing the original question. Additional edge cases exist if arrays and objects are the values being considered.</em></li>\n<li><em>Characters in binary, octal, hexadecimal, and exponential notation are not case-sensitive (ie: '0xFF', '0XFF', '0xfF' etc. will all yield the same result in the test cases shown above).</em></li>\n<li><em>Unlike with <code>Infinity</code> (case-sensitive) in some cases, constants from the <code>Number</code> and <code>Math</code> objects passed as test cases in string format to any of the methods above will be determined to not be numbers.</em></li>\n<li><em>See <a href=\"http://www.ecma-international.org/ecma-262/7.0/#sec-tonumber\" rel=\"nofollow noreferrer\">here</a> for an explanation of how arguments are converted to a <code>Number</code> and why the edge cases for <code>null</code> and empty strings exist.</em></li>\n</ul>\n" }, { "answer_id": 56276861, "author": "Greg Wozniak", "author_id": 2170368, "author_profile": "https://Stackoverflow.com/users/2170368", "pm_score": 3, "selected": false, "text": "<p>It is not valid for TypeScript as:</p>\n\n<p><code>declare function isNaN(number: number): boolean;</code></p>\n\n<p>For TypeScript you can use:</p>\n\n<p><code>/^\\d+$/.test(key)</code></p>\n" }, { "answer_id": 57478170, "author": "c7x43t", "author_id": 9905358, "author_profile": "https://Stackoverflow.com/users/9905358", "pm_score": 0, "selected": false, "text": "<p>Here is a high-performance (2.5*10^7 iterations/s @3.8GHz Haswell) version of a isNumber implementation. It works for every testcase i could find (including Symbols):</p>\n\n<pre><code>var isNumber = (function () {\n var isIntegerTest = /^\\d+$/;\n var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];\n function hasLeading0s (s) {\n return !(typeof s !== 'string' ||\n s.length &lt; 2 ||\n s[0] !== '0' ||\n !isDigitArray[s[1]] ||\n isIntegerTest.test(s));\n }\n var isWhiteSpaceTest = /\\s/;\n return function isNumber (s) {\n var t = typeof s;\n var n;\n if (t === 'number') {\n return (s &lt;= 0) || (s &gt; 0);\n } else if (t === 'string') {\n n = +s;\n return !((!(n &lt;= 0) &amp;&amp; !(n &gt; 0)) || n === '0' || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));\n } else if (t === 'object') {\n return !(!(s instanceof Number) || ((n = +s), !(n &lt;= 0) &amp;&amp; !(n &gt; 0)));\n }\n return false;\n };\n})();\n</code></pre>\n" }, { "answer_id": 58550111, "author": "Jeremy", "author_id": 4888826, "author_profile": "https://Stackoverflow.com/users/4888826", "pm_score": 5, "selected": false, "text": "<h1>2019: Including ES3, ES6 and TypeScript Examples</h1>\n\n<p>Maybe this has been rehashed too many times, however I fought with this one today too and wanted to post my answer, as I didn't see any other answer that does it as simply or thoroughly:</p>\n\n<h2>ES3</h2>\n\n<pre><code>var isNumeric = function(num){\n return (typeof(num) === 'number' || typeof(num) === \"string\" &amp;&amp; num.trim() !== '') &amp;&amp; !isNaN(num); \n}\n</code></pre>\n\n<h2>ES6</h2>\n\n<pre><code>const isNumeric = (num) =&gt; (typeof(num) === 'number' || typeof(num) === \"string\" &amp;&amp; num.trim() !== '') &amp;&amp; !isNaN(num);\n</code></pre>\n\n<h2>Typescript</h2>\n\n<pre><code>const isNumeric = (num: any) =&gt; (typeof(num) === 'number' || typeof(num) === \"string\" &amp;&amp; num.trim() !== '') &amp;&amp; !isNaN(num as number);\n</code></pre>\n\n<p>This seems quite simple and covers all the bases I saw on the many other posts and thought up myself:</p>\n\n<pre><code>// Positive Cases\nconsole.log(0, isNumeric(0) === true);\nconsole.log(1, isNumeric(1) === true);\nconsole.log(1234567890, isNumeric(1234567890) === true);\nconsole.log('1234567890', isNumeric('1234567890') === true);\nconsole.log('0', isNumeric('0') === true);\nconsole.log('1', isNumeric('1') === true);\nconsole.log('1.1', isNumeric('1.1') === true);\nconsole.log('-1', isNumeric('-1') === true);\nconsole.log('-1.2354', isNumeric('-1.2354') === true);\nconsole.log('-1234567890', isNumeric('-1234567890') === true);\nconsole.log(-1, isNumeric(-1) === true);\nconsole.log(-32.1, isNumeric(-32.1) === true);\nconsole.log('0x1', isNumeric('0x1') === true); // Valid number in hex\n// Negative Cases\nconsole.log(true, isNumeric(true) === false);\nconsole.log(false, isNumeric(false) === false);\nconsole.log('1..1', isNumeric('1..1') === false);\nconsole.log('1,1', isNumeric('1,1') === false);\nconsole.log('-32.1.12', isNumeric('-32.1.12') === false);\nconsole.log('[blank]', isNumeric('') === false);\nconsole.log('[spaces]', isNumeric(' ') === false);\nconsole.log('null', isNumeric(null) === false);\nconsole.log('undefined', isNumeric(undefined) === false);\nconsole.log([], isNumeric([]) === false);\nconsole.log('NaN', isNumeric(NaN) === false);\n</code></pre>\n\n<p>You can also try your own <code>isNumeric</code> function and just past in these use cases and scan for \"true\" for all of them.</p>\n\n<p>Or, to see the values that each return:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4MTpf.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4MTpf.png\" alt=\"Results of each test against &lt;code&gt;isNumeric()&lt;/code&gt;\"></a></p>\n" }, { "answer_id": 58849715, "author": "J.P. Duvet", "author_id": 7807090, "author_profile": "https://Stackoverflow.com/users/7807090", "pm_score": 3, "selected": false, "text": "<h2>2019: Practical and tight numerical validity check</h2>\n\n<p>Often, a 'valid number' means a Javascript number excluding NaN and Infinity, ie a 'finite number'.</p>\n\n<p>To check the numerical validity of a value (from an external source for example), you can define in ESlint Airbnb style :</p>\n\n<pre><code>/**\n * Returns true if 'candidate' is a finite number or a string referring (not just 'including') a finite number\n * To keep in mind:\n * Number(true) = 1\n * Number('') = 0\n * Number(\" 10 \") = 10\n * !isNaN(true) = true\n * parseFloat('10 a') = 10\n *\n * @param {?} candidate\n * @return {boolean}\n */\nfunction isReferringFiniteNumber(candidate) {\n if (typeof (candidate) === 'number') return Number.isFinite(candidate);\n if (typeof (candidate) === 'string') {\n return (candidate.trim() !== '') &amp;&amp; Number.isFinite(Number(candidate));\n }\n return false;\n}\n</code></pre>\n\n<p>and use it this way:</p>\n\n<pre><code>if (isReferringFiniteNumber(theirValue)) {\n myCheckedValue = Number(theirValue);\n} else {\n console.warn('The provided value doesn\\'t refer to a finite number');\n}\n</code></pre>\n" }, { "answer_id": 60990380, "author": "Zoman", "author_id": 118195, "author_profile": "https://Stackoverflow.com/users/118195", "pm_score": 2, "selected": false, "text": "<p>This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const isNumRegEx = /^-?(\\d*\\.)?\\d+$/;\n\nfunction isNumeric(n, allowScientificNotation = false) {\n return allowScientificNotation ? \n !Number.isNaN(parseFloat(n)) &amp;&amp; Number.isFinite(n) :\n isNumRegEx.test(n);\n}\n</code></pre>\n" }, { "answer_id": 61108035, "author": "dsmith63", "author_id": 3645358, "author_profile": "https://Stackoverflow.com/users/3645358", "pm_score": 2, "selected": false, "text": "<p>This appears to catch the seemingly infinite number of edge cases:</p>\n\n<pre><code>function isNumber(x, noStr) {\n /*\n\n - Returns true if x is either a finite number type or a string containing only a number\n - If empty string supplied, fall back to explicit false\n - Pass true for noStr to return false when typeof x is \"string\", off by default\n\n isNumber(); // false\n isNumber([]); // false\n isNumber([1]); // false\n isNumber([1,2]); // false\n isNumber(''); // false\n isNumber(null); // false\n isNumber({}); // false\n isNumber(true); // false\n isNumber('true'); // false\n isNumber('false'); // false\n isNumber('123asdf'); // false\n isNumber('123.asdf'); // false\n isNumber(undefined); // false\n isNumber(Number.POSITIVE_INFINITY); // false\n isNumber(Number.NEGATIVE_INFINITY); // false\n isNumber('Infinity'); // false\n isNumber('-Infinity'); // false\n isNumber(Number.NaN); // false\n isNumber(new Date('December 17, 1995 03:24:00')); // false\n isNumber(0); // true\n isNumber('0'); // true\n isNumber(123); // true\n isNumber(123.456); // true\n isNumber(-123.456); // true\n isNumber(-.123456); // true\n isNumber('123'); // true\n isNumber('123.456'); // true\n isNumber('.123'); // true\n isNumber(.123); // true\n isNumber(Number.MAX_SAFE_INTEGER); // true\n isNumber(Number.MAX_VALUE); // true\n isNumber(Number.MIN_VALUE); // true\n isNumber(new Number(123)); // true\n */\n\n return (\n (typeof x === 'number' || x instanceof Number || (!noStr &amp;&amp; x &amp;&amp; typeof x === 'string' &amp;&amp; !isNaN(x))) &amp;&amp;\n isFinite(x)\n ) || false;\n};\n</code></pre>\n" }, { "answer_id": 63355463, "author": "ling", "author_id": 405042, "author_profile": "https://Stackoverflow.com/users/405042", "pm_score": 1, "selected": false, "text": "<p>I used this function as a form validation tool, and I didn't want users to be able to write exponential function, so I came up with this function:</p>\n<pre><code>&lt;script&gt;\n\n function isNumber(value, acceptScientificNotation) {\n\n if(true !== acceptScientificNotation){\n return /^-{0,1}\\d+(\\.\\d+)?$/.test(value);\n }\n\n if (true === Array.isArray(value)) {\n return false;\n }\n return !isNaN(parseInt(value, 10));\n }\n\n\n console.log(isNumber(&quot;&quot;)); // false\n console.log(isNumber(false)); // false\n console.log(isNumber(true)); // false\n console.log(isNumber(&quot;0&quot;)); // true\n console.log(isNumber(&quot;0.1&quot;)); // true\n console.log(isNumber(&quot;12&quot;)); // true\n console.log(isNumber(&quot;-12&quot;)); // true\n console.log(isNumber(-45)); // true\n console.log(isNumber({jo: &quot;pi&quot;})); // false\n console.log(isNumber([])); // false\n console.log(isNumber([78, 79])); // false\n console.log(isNumber(NaN)); // false\n console.log(isNumber(Infinity)); // false\n console.log(isNumber(undefined)); // false\n console.log(isNumber(&quot;0,1&quot;)); // false\n\n\n\n console.log(isNumber(&quot;1e-1&quot;)); // false\n console.log(isNumber(&quot;1e-1&quot;, true)); // true\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 64437101, "author": "lebobbi", "author_id": 1128552, "author_profile": "https://Stackoverflow.com/users/1128552", "pm_score": 2, "selected": false, "text": "<p>So, it will depend on the test cases that you want it to handle.</p>\n<pre><code>function isNumeric(number) {\n return !isNaN(parseFloat(number)) &amp;&amp; !isNaN(+number);\n}\n</code></pre>\n<p>What I was looking for was regular types of numbers in javascript.\n<code>0, 1 , -1, 1.1 , -1.1 , 1E1 , -1E1 , 1e1 , -1e1, 0.1e10, -0.1.e10 , 0xAF1 , 0o172, Math.PI, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY</code></p>\n<p>And also they're representations as strings:<br />\n<code>'0', '1', '-1', '1.1', '-1.1', '1E1', '-1E1', '1e1', '-1e1', '0.1e10', '-0.1.e10', '0xAF1', '0o172'</code></p>\n<p>I did want to leave out and not mark them as numeric\n<code>'', ' ', [], {}, null, undefined, NaN</code></p>\n<p>As of today, all other answers seemed to failed one of these test cases.</p>\n" }, { "answer_id": 67266686, "author": "vitoboski", "author_id": 15621907, "author_profile": "https://Stackoverflow.com/users/15621907", "pm_score": 2, "selected": false, "text": "<p>Checking the number in JS:</p>\n<ol>\n<li><p>Best way for check if it's a number:</p>\n<pre><code>isFinite(20)\n//True\n</code></pre>\n</li>\n<li><p>Read a value out of a string. CSS *:</p>\n<pre><code>parseInt('2.5rem')\n//2\nparseFloat('2.5rem')\n//2.5 \n</code></pre>\n</li>\n<li><p>For an integer:</p>\n<pre><code>isInteger(23 / 0)\n//False\n</code></pre>\n</li>\n<li><p>If value is NaN:</p>\n<pre><code>isNaN(20)\n//False\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 68417450, "author": "ekerner", "author_id": 233060, "author_profile": "https://Stackoverflow.com/users/233060", "pm_score": 0, "selected": false, "text": "<p>Test if a string or number is a number</p>\n<pre><code>const isNumeric = stringOrNumber =&gt;\n stringOrNumber == 0 || !!+stringOrNumber;\n</code></pre>\n<p>Or if you want to convert a string or number to a number</p>\n<pre><code>const toNumber = stringOrNumber =&gt;\n stringOrNumber == 0 || +stringOrNumber ? +stringOrNumber : NaN;\n</code></pre>\n" }, { "answer_id": 68821383, "author": "Hasan Nahiyan Nobel", "author_id": 6606776, "author_profile": "https://Stackoverflow.com/users/6606776", "pm_score": 4, "selected": false, "text": "<h2>TL;DR</h2>\n<p>It depends largely on what <em>you</em> want to parse as a number.</p>\n<h2>Comparison Between Built-in Functions</h2>\n<p>As none of the existing sources satisfied my soul, I tried to figure out what actually was happening with these functions.</p>\n<p>Three immediate answers to this question felt like:</p>\n<ol>\n<li><code>!isNaN(input)</code> (which gives the same output as <code>+input === +input</code>)</li>\n<li><code>!isNaN(parseFloat(input))</code></li>\n<li><code>isFinite(input)</code></li>\n</ol>\n<p>But are any of them correct in <em>every</em> scenario?</p>\n<p>I tested these functions in several cases, and generated output as markdown. This is what it looks like:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\"><code>input</code></th>\n<th style=\"text-align: center;\"><code>!isNaN(input)</code> or <br><code>+input===+input</code></th>\n<th style=\"text-align: center;\"><code>!isNaN(</code><br><code>parseFloat(</code><br><code>input))</code></th>\n<th style=\"text-align: center;\"><code>isFinite(</code><br><code>input)</code></th>\n<th style=\"text-align: left;\">Comment</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">123</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">-</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'123'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">-</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">12.3</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">-</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'12.3'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">-</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'   12.3   '</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Empty whitespace trimmed, as expected.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1_000_000</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Numeric separator understood, also expected.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'1_000_000'</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: left;\">Surprise! JS just won't parse numeric separator inside a string. For details, check <a href=\"https://github.com/tc39/proposal-numeric-separator/issues/32\" rel=\"noreferrer\">this</a> issue. (Why then parsing as float worked though? Well, it didn't. )</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'0b11111111'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Binary form understood, as it should've.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'0o377'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Octal form understood too.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'0xFF'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Of course hex is understood. Did anybody think otherwise? </td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">''</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Should empty string be a number?</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'    '</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Should a whitespace-only string be a number?</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'abc'</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: left;\">Everybody agrees, not a number.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'12.34Ab!@#$'</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: left;\">Ah! Now it's quite understandable what <code>parseFloat()</code> does. Not impressive to me, but may come handy in certain cases.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'10e100'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">10<sup>100</sup> is a number indeed. <br><strong>But caution!</strong> It's way more larger than the maximum safe integer value 2<sup>53</sup> (about 9×10<sup>15</sup>). Read <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER\" rel=\"noreferrer\">this</a> for details.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">'10e1000'</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: left;\">Say with me, <a href=\"https://www.youtube.com/watch?v=2Q_ZzBGPdqE\" rel=\"noreferrer\">help!</a> <br>Though not as crazy as it may seem. In JavaScript, a value larger than ~10<sup>308</sup> is rounded to infinity, that's why. Look <a href=\"https://stackoverflow.com/a/10838069\">here</a> for details. <br>And yes, <code>isNaN()</code> considers infinity as a number, and <code>parseFloat()</code> parses infinity as infinity.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">null</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: left;\">Now this is awkward. In JS, when a conversion is needed, null becomes zero, and we get a finite number. <br>Then why <code>parseFloat(null)</code> should return a <code>NaN</code> here? Someone please explain this design concept to me.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">undefined</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: left;\">As expected.</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">Infinity</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">✔️</td>\n<td style=\"text-align: center;\">❌</td>\n<td style=\"text-align: left;\">As explained before, <code>isNaN()</code> considers infinity as a number, and <code>parseFloat()</code> parses infinity as infinity.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>So...which of them is &quot;correct&quot;?</p>\n<p>Should be clear by now, <strong>it depends largely on what we need</strong>. For example, we may want to consider a null input as 0. In that case <code>isFinite()</code> will work fine.</p>\n<p>Again, perhaps we will take a little help from <code>isNaN()</code> when 10<sup>10000000000</sup> is needed to be considered a valid number (although the question remains—why would it be, and how would we handle that)!</p>\n<p>Of course, we can manually exclude any of the scenarios.</p>\n<p>Like in my case, I needed exactly the outputs of <code>isFinite()</code>, except for the null case, the empty string case, and the whitespace-only string case. Also I had no headache about <em>really huge</em> numbers. So my code looked like this:</p>\n<pre><code>/**\n * My necessity was met by the following code.\n */\n\nif (input === null) {\n // Null input\n} else if (input.trim() === '') {\n // Empty or whitespace-only string\n} else if (isFinite(input)) {\n // Input is a number\n} else {\n // Not a number\n}\n</code></pre>\n<p>And also, this was my JavaScript to generate the table:</p>\n<pre><code>/**\n * Note: JavaScript does not print numeric separator inside a number.\n * In that single case, the markdown output was manually corrected.\n * Also, the comments were manually added later, of course.\n */\n\nlet inputs = [\n 123, '123', 12.3, '12.3', ' 12.3 ',\n 1_000_000, '1_000_000',\n '0b11111111', '0o377', '0xFF',\n '', ' ',\n 'abc', '12.34Ab!@#$',\n '10e100', '10e1000',\n null, undefined, Infinity];\n\nlet markdownOutput = `| \\`input\\` | \\`!isNaN(input)\\` or &lt;br&gt;\\`+input === +input\\` | \\`!isNaN(parseFloat(input))\\` | \\`isFinite(input)\\` | Comment |\n| :---: | :---: | :---: | :---: | :--- |\\n`;\n\nfor (let input of inputs) {\n let outputs = [];\n outputs.push(!isNaN(input));\n outputs.push(!isNaN(parseFloat(input)));\n outputs.push(isFinite(input));\n\n if (typeof input === 'string') {\n // Output with quotations\n console.log(`'${input}'`);\n markdownOutput += `| '${input}'`;\n } else {\n // Output without quotes\n console.log(input);\n markdownOutput += `| ${input}`;\n }\n\n for (let output of outputs) {\n console.log('\\t' + output);\n if (output === true) {\n markdownOutput += ` | &lt;div style=&quot;color:limegreen&quot;&gt;true&lt;/div&gt;`;\n // markdownOutput += ` | ✔️`; // for stackoverflow\n } else {\n markdownOutput += ` | &lt;div style=&quot;color:orangered&quot;&gt;false&lt;/div&gt;`;\n // markdownOutput += ` | ❌`; // for stackoverflow\n }\n }\n\n markdownOutput += ` ||\\n`;\n}\n\n// Replace two or more whitespaces with $nbsp;\nmarkdownOutput = markdownOutput.replaceAll(` `, `&amp;nbsp;&amp;nbsp;`);\n\n// Print markdown to console\nconsole.log(markdownOutput);\n</code></pre>\n" }, { "answer_id": 69402873, "author": "Stefan Bracke", "author_id": 2316698, "author_profile": "https://Stackoverflow.com/users/2316698", "pm_score": -1, "selected": false, "text": "<p>If you are looking for a positive number (housenumber for example), just use:</p>\n<pre><code>if (mystring &gt; 0) ...\n</code></pre>\n" }, { "answer_id": 70052447, "author": "Emrah Tuncel", "author_id": 2138283, "author_profile": "https://Stackoverflow.com/users/2138283", "pm_score": 2, "selected": false, "text": "<p>This way it works for me.</p>\n<pre><code>function isNumeric(num){\n let value1 = num.toString();\n let value2 = parseFloat(num).toString();\n return (value1 === value2);\n}\n</code></pre>\n<hr />\n<pre><code>console.log(\n isNumeric(123), //true\n isNumeric(-123), //true\n isNumeric('123'), //true\n isNumeric('-123'), //true\n isNumeric(12.2), //true\n isNumeric(-12.2), //true\n isNumeric('12.2'), //true\n isNumeric('-12.2'), //true\n isNumeric('a123'), //false\n isNumeric('123a'), //false\n isNumeric(' 123'), //false\n isNumeric('123 '), //false\n isNumeric('a12.2'), //false\n isNumeric('12.2a'), //false\n isNumeric(' 12.2'), //false\n isNumeric('12.2 '), //false\n)\n</code></pre>\n" }, { "answer_id": 70408790, "author": "chickens", "author_id": 1602301, "author_profile": "https://Stackoverflow.com/users/1602301", "pm_score": 4, "selected": false, "text": "<p>Someone may also benefit from a regex based answer. Here it is:</p>\n<p><strong>One liner isInteger:</strong></p>\n<pre><code>const isInteger = num =&gt; /^-?[0-9]+$/.test(num+'');\n</code></pre>\n<p><strong>One liner isNumeric:</strong> Accepts integers and decimals</p>\n<pre><code>const isNumeric = num =&gt; /^-?[0-9]+(?:\\.[0-9]+)?$/.test(num+'');\n</code></pre>\n" }, { "answer_id": 70628230, "author": "Karwan E. Othman", "author_id": 6523910, "author_profile": "https://Stackoverflow.com/users/6523910", "pm_score": 0, "selected": false, "text": "<p>I used this function in Angular</p>\n<pre><code> isNumeric(value: string): boolean {\n let valueToNumber = Number(value);\n var result = typeof valueToNumber == 'number' ;\n if(valueToNumber.toString() == 'NaN')\n {\n result = false;\n }\n return result;\n }\n</code></pre>\n" }, { "answer_id": 72620343, "author": "Christian Vincenzo Traina", "author_id": 1850851, "author_profile": "https://Stackoverflow.com/users/1850851", "pm_score": -1, "selected": false, "text": "<p>If you like a tricky way and you like getting your coworkers confused, you can use:</p>\n<pre><code>const isNumeric = str =&gt; parseFloat(str) === parseFloat(str)\n</code></pre>\n<p>Proof:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> const isNumeric = str =&gt; parseFloat(str) === parseFloat(str)\n \nconsole.log(isNumeric('10'))\nconsole.log(isNumeric('-10.2'))\nconsole.log(isNumeric('15abc'))\nconsole.log(isNumeric('0.0001'))\nconsole.log(isNumeric('abc'))\nconsole.log(isNumeric('abc123'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72719062, "author": "yusung lee", "author_id": 7275648, "author_profile": "https://Stackoverflow.com/users/7275648", "pm_score": -1, "selected": false, "text": "<p>How about the following?</p>\n<pre class=\"lang-js prettyprint-override\"><code>const a = '1'\n\nconst isNumber = (a) =&gt; Number(a) === +a\n\n</code></pre>\n" }, { "answer_id": 72770816, "author": "Musaib Mushtaq", "author_id": 17860991, "author_profile": "https://Stackoverflow.com/users/17860991", "pm_score": 4, "selected": false, "text": "<p>I Think isFinite() is best for all.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let a = isFinite('abc') // false;\nlet b = isFinite('123')//true;\nlet c = isFinite('12a') // false;\nconsole.log(a,b,c)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72831311, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 1, "selected": false, "text": "<p>This is a possible way to check whether a variable is NOT numerical:</p>\n<pre><code>(isNaN(foo) || ((foo !== 0) &amp;&amp; (!foo)))\n</code></pre>\n<p>Which means that <code>foo</code> is either falsy but different from 0 or <code>isNaN(foo)</code> is true.</p>\n<p>Another way to perform such a check is</p>\n<pre><code>!isNaN(parseFloat(foo))\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I'm hoping there's something in the same conceptual space as the old VB6 `IsNumeric()` function?
**2nd October 2020:** note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point "`.`": ```js function isNumeric(str) { if (typeof str != "string") return false // we only process strings! return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)... !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail } ``` --- To check if a variable (including a string) is a number, check if it is not a number: ------------------------------------------------------------------------------------- This works regardless of whether the variable content is a string or number. ``` isNaN(num) // returns true if the variable does NOT contain a valid number ``` ### Examples ``` isNaN(123) // false isNaN('123') // false isNaN('1e10000') // false (This translates to Infinity, which is a number) isNaN('foo') // true isNaN('10px') // true isNaN('') // false isNaN(' ') // false isNaN(false) // false ``` Of course, you can negate this if you need to. For example, to implement the `IsNumeric` example you gave: ``` function isNumeric(num){ return !isNaN(num) } ``` To convert a string containing a number into a number: ------------------------------------------------------ Only works if the string *only* contains numeric characters, else it returns `NaN`. ``` +num // returns the numeric value of the string, or NaN // if the string isn't purely numeric characters ``` ### Examples ``` +'12' // 12 +'12.' // 12 +'12..' // NaN +'.12' // 0.12 +'..12' // NaN +'foo' // NaN +'12px' // NaN ``` To convert a string loosely to a number --------------------------------------- Useful for converting '12px' to 12, for example: ``` parseInt(num) // extracts a numeric value from the // start of the string, or NaN. ``` ### Examples ``` parseInt('12') // 12 parseInt('aaa') // NaN parseInt('12px') // 12 parseInt('foo2') // NaN These last three may parseInt('12a5') // 12 be different from what parseInt('0x10') // 16 you expected to see. ``` Floats ------ Bear in mind that, unlike `+num`, `parseInt` (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use `parseInt()` *because of* this behaviour, [you're probably better off using another method instead](https://parsebox.io/dthree/gyeveeygrngl)): ``` +'12.345' // 12.345 parseInt(12.345) // 12 parseInt('12.345') // 12 ``` Empty strings ------------- Empty strings may be a little counter-intuitive. `+num` converts empty strings or strings with spaces to zero, and `isNaN()` assumes the same: ``` +'' // 0 +' ' // 0 isNaN('') // false isNaN(' ') // false ``` But `parseInt()` does not agree: ``` parseInt('') // NaN parseInt(' ') // NaN ```
175,742
<p>I want to allocate a 2 D Array in Java Script. </p> <p>I want do some thing similar to this in JavaScript</p> <pre><code>typedef struct { int itemA, int itemB, string testC } myStruc; myStruct MyArray [100]; </code></pre> <p>How to do this ? </p>
[ { "answer_id": 175764, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "<p>There are a few ways of creating arrays in Javascript, the method closest to what you want to do should be:</p>\n\n<pre><code>var myArray = new Array(\"someString1\", \"someString2\", \"someString3\", ...);\n</code></pre>\n\n<p>You can replace <code>\"someString1\"</code> with actual objects.</p>\n\n<p>You can also use the Array constructor to set up the initial length:</p>\n\n<pre><code>var myArray = new Array(5);\nmyArray[0] = ...;\nmyArray[1] = ...;\n</code></pre>\n\n<p>Arrays in Javascript are pretty loose actually - you don't even need to define the length before you access an element that would normally be outside the bounds of the array.</p>\n\n<p>Take a look at <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\">the Mozilla documentation on Arrays</a>.</p>\n" }, { "answer_id": 175769, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 1, "selected": false, "text": "<p>It sounds like you want properties for an array of objects, but I may be misinterpreting.</p>\n\n<p>You may just need something like...</p>\n\n<pre><code>function Person(first, last) {\n this.first = first;\n this.last = last;\n}\n\nvar person = new Person(\"John\", \"Dough\");\n</code></pre>\n\n<p><a href=\"http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm\" rel=\"nofollow noreferrer\">http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm</a></p>\n" }, { "answer_id": 175781, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 1, "selected": false, "text": "<pre><code>function Sample(value1, value2) {\n this.value1 = value1;\n this.value2 = value2;\n}\n\nvar test = new Array();\n\ntest[0] = new Sample(\"a\",\"aa\");\ntest[1] = new Sample(\"b\",\"bb\");\n</code></pre>\n\n<p>PS: There are several ways to accomplish this in Java Script.</p>\n" }, { "answer_id": 175792, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 3, "selected": false, "text": "<pre><code>var arr = []\narr[0] = { \"itemA\": \"A\", \"itemB\": \"B\", \"itemC\": \"C\" }\narr[1] = { \"itemA\": \"A\", \"itemB\": \"B\", \"itemC\": \"C\" }\n</code></pre>\n\n<p>I think you are trying to apply static language constructs to the dynamic and different world of Javascript. Javascript doesn't really have the notion of arrays in the sense that many languages do.</p>\n\n<p>In Javascript, an array is simpl a special kind of object (itself just a hash) which has a special length property. The integer \"indexes\" that you see above (ie, the 0 in arr[0]) are just has lookups. The special length property is defined to be one greater than the greatest integer key. In my example above, arr.length is 2. But if I were to assign:</p>\n\n<pre><code>arr[100] = { \"itemA\": \"A\", \"itemB\": \"B\", \"itemC\": \"C\" }\n</code></pre>\n\n<p>Then arr.length would be 101, even though I've done nothing to assign any of the elements from 2 to 99.</p>\n\n<p>Similarly, we generally don't predefine objects like structs in Javascript, and thus anonymous objects will largely accomplish what you want (or use a documented factory function such as in the example from Ken).</p>\n\n<p>\"new Array()\" isn't necessary as the concise \"var a = [];\" syntax is quicker. :)</p>\n" }, { "answer_id": 175985, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 1, "selected": false, "text": "<p>If you really like to <em>allocate</em> 100 elements array of a particular structure, you can do following:</p>\n\n<pre><code>arr = [];\n\nfor (i=0; i&lt;100; i++) {\n arr[i] = {itemA: &lt;value&gt;, itemB: &lt;value&gt;, textC: &lt;string&gt;, ... };\n}\n</code></pre>\n" }, { "answer_id": 6485303, "author": "jBrushFX", "author_id": 816321, "author_profile": "https://Stackoverflow.com/users/816321", "pm_score": 2, "selected": false, "text": "<p>If i have understand you need to dynamically create an array of a specified length filled with your own struct.</p>\n\n<p>In js a struct is an [object Object] like</p>\n\n<pre>\n // typedef struct { type prop1 , ... , type propN } myStructName;\n function myStructName(){}\n\n myStructName.prototype = {\n 'constructor' : myStructname,\n 'prop1' : defaultVal1,\n // ...\n 'propN' : defaultValN\n };\n</pre>\n\n<p>We can make a function who dinamycally create a struct type but is not this case.\nNow we just have to create a function that create an array of a specific length filled with all myStruct object instances.\nThis is my way</p>\n\n<p><pre>\n/*\n Copyrights (c) 2011 - Matteo Giordani &lt; [email protected] >\n MIT-Style License\n typedef struct{ int itemA , int itemB , string testC } myStruct\n myStruct arr[10];</p>\n\n<pre><code> JS way\n\n function myStruct( a , b , c )\n @param {int} a\n @param {int} b\n @param {string} c\n @return {object}\n</code></pre>\n\n<p>*/\n function myStruct(){</p>\n\n<code> // arguments\n var a = arguments[0] , b = arguments[1] , c = arguments[2];\n\n // check INT type for argument a\n if( typeof a == \"number\" &amp;&amp; (a + \"\").indexOf('.') == -1 ){ this['itemA'] = a; }\n // check INT type for argument b\n if( typeof b == \"number\" &amp;&amp; (b + \"\").indexOf('.') == -1 ){ this['itemB'] = b; }\n // check INT type for argument b\n if( typeof c == \"string\" /*check for string length?!*/){ this['testC'] = c; }\n}\n\n// myStruct prototype\nmyStruct.prototype = {\n // constructor\n 'constructor' : myStruct,\n // default value for itemA\n 'itemA' : 0,\n // default value for itemB\n 'itemB' : 0,\n // default value for testC\n 'testC' : ''\n};\n\n/*\n static function defaultLength([, length])\n Set/Get the defaultLength value.\n @param {unsigned int|void} length\n @return {void|unsigned int}\n*/\n\nmyStruct.defaultLength = function(){\n // return the default value\n if( arguments.length == 0 ){\n return myStruct._default;\n }else{\n // set the default value\n var l = arguments[0];\n myStruct._default = ( typeof l == \"number\" &amp;&amp; (l + \"\").indexOf('.') == -1 ) ? Math.abs( l ) : 0;\n }\n};\n\n// @var {unsigned int} myStruct._default = 0\nmyStruct._default = 0;\n\n/*\n static function makeArray( length )\n @param {unsigned int} length the length of the array\n @return {array}\n*/\nmyStruct.makeArray = function( length ){\n // Check if length is unsigned int\n length = ( typeof length == \"number\" &amp;&amp; (length + \"\").indexOf('.') == -1 ) ? Math.abs( length ) : myStruct.defaultLength();\n\n // local array\n var array = [] , i = 0;\n\n // populate the array\n for( ; i &lt; length; i++){\n array[ i ] = new myStruct();\n }\n\n // return\n return array;\n};\n\n// MAKE IT!\nmyStruct.defaultLength(10); // set the default length == 10\nvar arr = myStruct.makeArray(); // [myStruct, myStruct, myStruct, myStruct, myStruct, myStruct, myStruct, myStruct, myStruct, myStruct]\narr.length; // 10\nObject.prototype.toString.call( arr ); // [object Array]\n\n/* ANOTHER EXAMPLE */\nvar arr2 = []; // make an empty array\narr2[0] = new myStruct(1,1,'test1'); // make a first myStruct object\narr2[1] = new myStruct(2,2,'test2'); // make a second myStruct object\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to allocate a 2 D Array in Java Script. I want do some thing similar to this in JavaScript ``` typedef struct { int itemA, int itemB, string testC } myStruc; myStruct MyArray [100]; ``` How to do this ?
``` var arr = [] arr[0] = { "itemA": "A", "itemB": "B", "itemC": "C" } arr[1] = { "itemA": "A", "itemB": "B", "itemC": "C" } ``` I think you are trying to apply static language constructs to the dynamic and different world of Javascript. Javascript doesn't really have the notion of arrays in the sense that many languages do. In Javascript, an array is simpl a special kind of object (itself just a hash) which has a special length property. The integer "indexes" that you see above (ie, the 0 in arr[0]) are just has lookups. The special length property is defined to be one greater than the greatest integer key. In my example above, arr.length is 2. But if I were to assign: ``` arr[100] = { "itemA": "A", "itemB": "B", "itemC": "C" } ``` Then arr.length would be 101, even though I've done nothing to assign any of the elements from 2 to 99. Similarly, we generally don't predefine objects like structs in Javascript, and thus anonymous objects will largely accomplish what you want (or use a documented factory function such as in the example from Ken). "new Array()" isn't necessary as the concise "var a = [];" syntax is quicker. :)
175,835
<p>I'm trying add a tab to my web page that looks like this: <img src="https://i.stack.imgur.com/DT3e7.png" alt="alt text"></p> <p>Using <a href="http://mattberseth.com/blog/2007/09/using_css_image_sprites_with_t.html" rel="nofollow noreferrer">this example</a> as a basis, I've gotten it partially working. My case differs because I want the text section to be a fixed with, but the tail section to dynamically resize to take up the rest of the tab's container.</p> <p>It looks good in IE 6, but doesn't really take up the full width of the container. In Firefox 3 it doesn't render well at all:<img src="https://i.stack.imgur.com/Zeypv.png" alt="alt text"> (the red is a blank area between the spans).</p> <p>How do I get this to render properly in both IE6 and Firefox to take up the full width specified for #Tab? #Tab4 is the area I'd like to size to take up as much room as possible.</p> <pre><code> &lt;style type="text/css"&gt; #Tab { width: 300px; } #Tab1 { background: #000 url(BlueTabSprite.png) no-repeat 0 -136px; display: inline-block; height: 23px; padding-left: 4px; } #Tab2 { background: #000 url(BlueTabSprite.png) repeat-x 0 -242px; display: inline-block; overflow: hidden; padding-top: 4px; height: 19px; width: 100px; } #Tab3 { background: #000 url(BlueTabSprite.png) no-repeat right -30px; display: inline-block; height: 23px; padding-right: 6px; } #Tab4 { background: #000 url(BlueTabSprite.png) repeat-x 0 -83px; display: inline-block; height: 23px; width:60% } #Tab5 { background: #000 url(BlueTabSprite.png) no-repeat right -189px; display: inline-block; height: 23px; padding-right:6px; } &lt;/style&gt; &lt;div id="Tab"&gt; &lt;span id="Tab1"&gt; &lt;span id="Tab3"&gt; &lt;span id="Tab2"&gt;Test Tab&lt;/span&gt; &lt;/span&gt; &lt;/span&gt; &lt;span id="Tab5"&gt; &lt;span id="Tab4"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 175844, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 2, "selected": false, "text": "<p>I think the <a href=\"http://alistapart.com/articles/slidingdoors/\" rel=\"nofollow noreferrer\">Sliding Doors Technique</a> may be what you're looking for.</p>\n" }, { "answer_id": 175900, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": true, "text": "<p>This is a simplified version that works:</p>\n\n<pre><code>&lt;div style=\"background: url('BlueTabSprite.png') no-repeat; width: 290px; min-width: 120px; max-width: 290px; height: 23px;\"&gt;\n&lt;div style=\"float: right; background: url('BlueTabSprite.png') top right no-repeat; width: 10px; height: 23px;\"&gt;&lt;/div&gt;\nTest\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 501991, "author": "unigogo", "author_id": 61145, "author_profile": "https://Stackoverflow.com/users/61145", "pm_score": 1, "selected": false, "text": "<p>This <a href=\"http://www.pagecolumn.com/tool/top_tabs_generator.htm\" rel=\"nofollow noreferrer\">tool</a> may be a help.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12601/" ]
I'm trying add a tab to my web page that looks like this: ![alt text](https://i.stack.imgur.com/DT3e7.png) Using [this example](http://mattberseth.com/blog/2007/09/using_css_image_sprites_with_t.html) as a basis, I've gotten it partially working. My case differs because I want the text section to be a fixed with, but the tail section to dynamically resize to take up the rest of the tab's container. It looks good in IE 6, but doesn't really take up the full width of the container. In Firefox 3 it doesn't render well at all:![alt text](https://i.stack.imgur.com/Zeypv.png) (the red is a blank area between the spans). How do I get this to render properly in both IE6 and Firefox to take up the full width specified for #Tab? #Tab4 is the area I'd like to size to take up as much room as possible. ``` <style type="text/css"> #Tab { width: 300px; } #Tab1 { background: #000 url(BlueTabSprite.png) no-repeat 0 -136px; display: inline-block; height: 23px; padding-left: 4px; } #Tab2 { background: #000 url(BlueTabSprite.png) repeat-x 0 -242px; display: inline-block; overflow: hidden; padding-top: 4px; height: 19px; width: 100px; } #Tab3 { background: #000 url(BlueTabSprite.png) no-repeat right -30px; display: inline-block; height: 23px; padding-right: 6px; } #Tab4 { background: #000 url(BlueTabSprite.png) repeat-x 0 -83px; display: inline-block; height: 23px; width:60% } #Tab5 { background: #000 url(BlueTabSprite.png) no-repeat right -189px; display: inline-block; height: 23px; padding-right:6px; } </style> <div id="Tab"> <span id="Tab1"> <span id="Tab3"> <span id="Tab2">Test Tab</span> </span> </span> <span id="Tab5"> <span id="Tab4"></span> </span> </div> ```
This is a simplified version that works: ``` <div style="background: url('BlueTabSprite.png') no-repeat; width: 290px; min-width: 120px; max-width: 290px; height: 23px;"> <div style="float: right; background: url('BlueTabSprite.png') top right no-repeat; width: 10px; height: 23px;"></div> Test </div> ```
175,836
<p>When using the .NET WebBrowser control how do you open a link in a new window using the the same session (ie.. do not start a new ASP.NET session on the server), or how do you capture the new window event to open the URL in the same WebBrowser control?</p>
[ { "answer_id": 175851, "author": "Greg Bray", "author_id": 17373, "author_profile": "https://Stackoverflow.com/users/17373", "pm_score": 5, "selected": true, "text": "<p>I just spent an hour looking for the answer, so I though I would post the results here. You can use the SHDocVwCtl.WebBrowser_V1 object to capture the NewWindow event.</p>\n\n<p>NOTE: Code from <a href=\"http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_21484555.html#discussion\" rel=\"noreferrer\">http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_21484555.html#discussion</a></p>\n\n<pre><code>//-------------------------------VB.NET Version:-------------------------------\n\nDim WithEvents Web_V1 As SHDocVwCtl.WebBrowser_V1\n\nPrivate Sub Form_Load()\n Set Web_V1 = WebBrowser1.Object\nEnd Sub\n\nPrivate Sub Web_V1_NewWindow(ByVal URL As String, ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, Processed As Boolean)\n Processed = True\n WebBrowser1.Navigate URL\nEnd Sub\n\n\n//-------------------------------C# Version-------------------------------\n\nprivate SHDocVw.WebBrowser_V1 Web_V1; //Interface to expose ActiveX methods\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n //Setup Web_V1 interface and register event handler\n Web_V1 = (SHDocVw.WebBrowser_V1)this.webBrowser1.ActiveXInstance;\n Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow);\n}\n\nprivate void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData,string Headers, ref bool Processed)\n{\n Processed = true; //Stop event from being processed\n\n //Code to open in same window\n this.webBrowser1.Navigate(URL);\n\n //Code to open in new window instead of same window\n //Form1 Popup = new Form1();\n //Popup.webBrowser1.Navigate(URL);\n //Popup.Show();\n}\n</code></pre>\n" }, { "answer_id": 16401565, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 2, "selected": false, "text": "<p>Slightly cleaned up version of Greg's answer. It modifies the passed-in control's behavior rather than relying on a global variable. Usage:</p>\n\n<pre><code>InlinePopups(webBrowser1);\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>// interface to expose ActiveX methods\nprivate SHDocVw.WebBrowser_V1 Web_V1;\nprivate void InlinePopups(WebBrowser browser)\n{\n // hooks to force new windows to open in the current instance\n Web_V1 = (SHDocVw.WebBrowser_V1)browser.ActiveXInstance;\n Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler((string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed) =&gt;\n {\n Processed = true; // stop event from being processed\n\n // open in the existing window\n browser.Navigate(URL);\n });\n}\n</code></pre>\n\n<p>Still needs the reference to %WINDIR%\\system32\\shdocvw.dll, of course.</p>\n" }, { "answer_id": 63039164, "author": "Chris Raisin", "author_id": 5316401, "author_profile": "https://Stackoverflow.com/users/5316401", "pm_score": 1, "selected": false, "text": "<p>After adding the reference to shdocvw.dll to your project\nif you are not adding the actuasl object to your toolbox (shwos as &quot;Microsoft Browser&quot;)\nthen define the object at the top of your code with:</p>\n<p>Dim WithEvents Web_V1 As SHDocVw.WebBrowser_V1</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17373/" ]
When using the .NET WebBrowser control how do you open a link in a new window using the the same session (ie.. do not start a new ASP.NET session on the server), or how do you capture the new window event to open the URL in the same WebBrowser control?
I just spent an hour looking for the answer, so I though I would post the results here. You can use the SHDocVwCtl.WebBrowser\_V1 object to capture the NewWindow event. NOTE: Code from <http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_21484555.html#discussion> ``` //-------------------------------VB.NET Version:------------------------------- Dim WithEvents Web_V1 As SHDocVwCtl.WebBrowser_V1 Private Sub Form_Load() Set Web_V1 = WebBrowser1.Object End Sub Private Sub Web_V1_NewWindow(ByVal URL As String, ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, Processed As Boolean) Processed = True WebBrowser1.Navigate URL End Sub //-------------------------------C# Version------------------------------- private SHDocVw.WebBrowser_V1 Web_V1; //Interface to expose ActiveX methods private void Form1_Load(object sender, EventArgs e) { //Setup Web_V1 interface and register event handler Web_V1 = (SHDocVw.WebBrowser_V1)this.webBrowser1.ActiveXInstance; Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow); } private void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData,string Headers, ref bool Processed) { Processed = true; //Stop event from being processed //Code to open in same window this.webBrowser1.Navigate(URL); //Code to open in new window instead of same window //Form1 Popup = new Form1(); //Popup.webBrowser1.Navigate(URL); //Popup.Show(); } ```
175,845
<p>I have a repeater control where in the footer I have a DropDownList. In my code-behind I have:</p> <pre><code>protected void ddMyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // Item binding code } else if (e.Item.ItemType == ListItemType.Footer) { DropDownList ddl = e.Item.FindDropDownList("ddMyDropDownList"); // Fill the list control ddl.SelectedIndexChanged += new EventHandler(ddMyDropDownList_SelectedIndexChanged); ddl.AutoPostBack = true; } } </code></pre> <p>The page appear to PostBack however my EventHandler does not get called. Any ideas?</p>
[ { "answer_id": 175888, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>I think it's because you're probably not databinding on postbacks. I haven't tested this, but try hooking that code up to the ItemCreated event for your repeater instead.</p>\n" }, { "answer_id": 175945, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "<p>Is the AutoPostBack property set to True on the DropDownLists on the ASPX side? I know sometimes this property doesn't get set initially and it will prevent the SelectedIndexChanged event from firing.</p>\n" }, { "answer_id": 176003, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 5, "selected": true, "text": "<p>If you just want to fire the OnSelectedIndexChanged, this is how it should look: </p>\n\n<p><strong>Page.aspx - Source</strong> </p>\n\n<pre><code>&lt;FooterTemplate&gt;\n &lt;asp:DropDownList ID=\"ddlOptions\"\n runat=\"server\" \n AutoPostBack=\"true\" \n onselectedindexchanged=\"ddlOptions_SelectedIndexChanged\"&gt;\n &lt;asp:ListItem&gt;Option1&lt;/asp:ListItem&gt;\n &lt;asp:ListItem&gt;Option2&lt;/asp:ListItem&gt;\n &lt;/asp:DropDownList&gt;\n&lt;/FooterTemplate&gt;\n</code></pre>\n\n<p><strong>Page.aspx.cs - Code-behind</strong> </p>\n\n<pre><code>protected void ddlOptions_SelectedIndexChanged(object sender, EventArgs e)\n {\n //Event Code here.\n }\n</code></pre>\n\n<p>And that's it. Nothing more is needed.</p>\n" }, { "answer_id": 176112, "author": "Chad Braun-Duin", "author_id": 5458, "author_profile": "https://Stackoverflow.com/users/5458", "pm_score": 1, "selected": false, "text": "<p>In this case your parent repeater (ddMyRepeater) must databind itself in page_load on every postback. This is the only way I've found to get nested controls to fire their events. </p>\n\n<p>This may not be the ideal scenario for you, though. Depending on what your page is doing, you may have to databind this control, twice. Once to get the events to fire and a second time if a fired event causes the repeater's data to change in any way.</p>\n" }, { "answer_id": 782137, "author": "Florjon", "author_id": 86653, "author_profile": "https://Stackoverflow.com/users/86653", "pm_score": 2, "selected": false, "text": "<p>I think the problem comes from the fact that the dropdownlist control is not inside the repeter, but on the footer. I don't think that the envent of the reperter fires for the controls that are on the footer. You should try to put the dropdowncontrol out of the repeater control.</p>\n" }, { "answer_id": 1040308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Make sure ViewState is enabled for dropdownlist</p>\n" }, { "answer_id": 2317302, "author": "KevinUK", "author_id": 1469, "author_profile": "https://Stackoverflow.com/users/1469", "pm_score": 3, "selected": false, "text": "<p>If the DropDownList is within a Repeater then to make the SelectIndexChanged event fire, you need to disable EnableViewState on the GridView / Repeater.</p>\n\n<p>e.g.</p>\n\n<pre><code>EnableViewState=\"false\"\n</code></pre>\n\n<p>You also need to databind the GridView / Repeater on each postback so databind it in the Page Load method.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3111/" ]
I have a repeater control where in the footer I have a DropDownList. In my code-behind I have: ``` protected void ddMyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // Item binding code } else if (e.Item.ItemType == ListItemType.Footer) { DropDownList ddl = e.Item.FindDropDownList("ddMyDropDownList"); // Fill the list control ddl.SelectedIndexChanged += new EventHandler(ddMyDropDownList_SelectedIndexChanged); ddl.AutoPostBack = true; } } ``` The page appear to PostBack however my EventHandler does not get called. Any ideas?
If you just want to fire the OnSelectedIndexChanged, this is how it should look: **Page.aspx - Source** ``` <FooterTemplate> <asp:DropDownList ID="ddlOptions" runat="server" AutoPostBack="true" onselectedindexchanged="ddlOptions_SelectedIndexChanged"> <asp:ListItem>Option1</asp:ListItem> <asp:ListItem>Option2</asp:ListItem> </asp:DropDownList> </FooterTemplate> ``` **Page.aspx.cs - Code-behind** ``` protected void ddlOptions_SelectedIndexChanged(object sender, EventArgs e) { //Event Code here. } ``` And that's it. Nothing more is needed.
175,847
<p>I am writing a fairly basic script using jQuery. However, the script behaves differently depending on whether I am running it on my local Web server (localhost) or on a production server.</p> <p>On development, the following code returns the HTML I'm expecting: </p> <pre><code>$('#objID').siblings('.mAddress').html(); </code></pre> <p>On production, the same statement returns <code>undefined</code>.</p> <p>The document structures are the same on both machines. The only difference I can find is when I use Firebug to step through the script. On the development machine, putting a watch on $('#objID').siblings('.mAddress') results in <code>[ span#object ]</code> while on production the same watch results in <code>[ [ span#object ] ]</code><br> (Notice the double sets of square brackets).</p> <p>Any ideas?</p> <p>Added:</p> <p>I've verified that the two libraries are identical.</p> <p>I've done some more experimenting using Firebug. Another part of the script grabs a set of elements using the statement:</p> <pre><code>$('.ParentColumn2').each(function(i) { ... }) </code></pre> <p>Within the body of that function, if I set a watch on <code>this</code>, on development the value of <code>this</code> is what I expect: <code>div.ParentColumn2</code> , but on production the value of <code>this</code> returns what looks like an array: <code>[ div.ParentColumn2, div.ParentColumn2, div.ParentColumn2, .....]</code></p> <p>The HTML is basically a table (I've stripped out irrelevant HTML, and the rows repeat):</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="ItemTemplate"&gt; &lt;div class="ParentColumn2"&gt; &lt;div&gt;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_Address" class="lbl_Address mAddress"&gt;111 W Wacker Dr, &lt;/span&gt;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_City" class="lbl_Address mCity"&gt;Chicago&lt;/span&gt;&amp;nbsp;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_PostalCode" class="lbl_Address mPostalCode"&gt;60601&lt;/span&gt;&amp;nbsp;&lt;a href="javascript:MapMe(this);" id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_hypMap" class="hypMap"&gt;Map&lt;/a&gt;&amp;nbsp;&amp;nbsp;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_Area" class="mArea"&gt;Loop&lt;/span&gt;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lt" class="mLt"&gt;41.8868010285473&lt;/span&gt;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lg" class="mLg"&gt;-87.6312860701286&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="ItemTemplate"&gt; &lt;div class="ParentColumn2"&gt; &lt;div&gt;&lt;span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl03_lbl_Address" class="lbl_Address mAddress"&gt;...&lt;/span&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>The HTML is as identical between the two machines as can be possible given that it's all generated by .Net (don't get me started).</p>
[ { "answer_id": 175865, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": -1, "selected": false, "text": "<p><del>I don't regularly use jQuery but my first suspicion is that your libraries are out of sync.</del></p>\n" }, { "answer_id": 176443, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": 1, "selected": false, "text": "<p>Given that you have different behaviour, it's reasonable to assume that <em>something</em> is different between the two pages, so my suggestion is to reduce both pages to the minimum that keeps the current behaviour and then see what is different.</p>\n" }, { "answer_id": 176768, "author": "Bruce Aldridge", "author_id": 21460, "author_profile": "https://Stackoverflow.com/users/21460", "pm_score": 1, "selected": false, "text": "<p>i don't use .siblings() ... (or haven't needed to) ... </p>\n\n<p>according to jquery docs .... running .siblings() on the div (below) would wouldn't return anything, but on one of the p's $('p:first') would return the other</p>\n\n<pre><code>&lt;div&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;/div&gt;\n</code></pre>\n\n<p>try using</p>\n\n<pre><code>$('#objID').find('.mAddress').html();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$('#objID').children('.mAddress').html();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$('#objID .mAddress').html();\n</code></pre>\n\n<p>seems odd that it would work of dev but not on production ... but try that.</p>\n\n<p>-bruce</p>\n" }, { "answer_id": 185049, "author": "Marcus", "author_id": 9574, "author_profile": "https://Stackoverflow.com/users/9574", "pm_score": 0, "selected": false, "text": "<p>I'd say a couple areas to look are at the caching, in your development environment everything probably gets reloaded with every request, try putting a \"?asdfasfrandom\" at the end of your javascript include tag to make sure it all gets updated.</p>\n\n<p>If it's not that, are your javascript files getting combined when you serve them? In Rails, for example, the default behavior is to throw them all into one file, that can mess with things.</p>\n\n<p>If it's not that, then it could be that the javascript files on the server are getting loaded in a different order, or executing in a different order than locally because of the download time. Try making sure the dom is ready before executing your code.</p>\n\n<p>Basically it seems like it's probably not a problem with your code (assuming you're using the same browser and have the same HTML), but a problem with the order things are occurring in.</p>\n" }, { "answer_id": 185489, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 0, "selected": false, "text": "<p>Put same data in dev as in prod, then dump view source for both and make do a diff.</p>\n\n<p>Why use siblings property and not just:</p>\n\n<pre><code>$('#objID .mAddress').html();\n</code></pre>\n\n<p>Also I would think that both siblings and the above returns an array of items and not just one item alone, so I'd probably go with something like this instead:</p>\n\n<pre><code>$($('#objID .mAddress').get(0)).html();\n</code></pre>\n\n<p>To only return the html for the first item.</p>\n" }, { "answer_id": 188660, "author": "Ed Wells", "author_id": 26598, "author_profile": "https://Stackoverflow.com/users/26598", "pm_score": 1, "selected": false, "text": "<p>Is your code within a $(document).ready(function() { ... }); ?</p>\n\n<p>If not, this could lead to different behavior. On your local development machine perhaps everything gets loaded so quickly that the DOM tree is complete by the type your Javascript is called, but on the production server perhaps things are not yet complete. </p>\n\n<p>Doesn't explain the extra nested brackets showing up in FireBug though.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13449/" ]
I am writing a fairly basic script using jQuery. However, the script behaves differently depending on whether I am running it on my local Web server (localhost) or on a production server. On development, the following code returns the HTML I'm expecting: ``` $('#objID').siblings('.mAddress').html(); ``` On production, the same statement returns `undefined`. The document structures are the same on both machines. The only difference I can find is when I use Firebug to step through the script. On the development machine, putting a watch on $('#objID').siblings('.mAddress') results in `[ span#object ]` while on production the same watch results in `[ [ span#object ] ]` (Notice the double sets of square brackets). Any ideas? Added: I've verified that the two libraries are identical. I've done some more experimenting using Firebug. Another part of the script grabs a set of elements using the statement: ``` $('.ParentColumn2').each(function(i) { ... }) ``` Within the body of that function, if I set a watch on `this`, on development the value of `this` is what I expect: `div.ParentColumn2` , but on production the value of `this` returns what looks like an array: `[ div.ParentColumn2, div.ParentColumn2, div.ParentColumn2, .....]` The HTML is basically a table (I've stripped out irrelevant HTML, and the rows repeat): ``` <table> <tr> <td> <div class="ItemTemplate"> <div class="ParentColumn2"> <div><span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_Address" class="lbl_Address mAddress">111 W Wacker Dr, </span><span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_City" class="lbl_Address mCity">Chicago</span>&nbsp;<span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_PostalCode" class="lbl_Address mPostalCode">60601</span>&nbsp;<a href="javascript:MapMe(this);" id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_hypMap" class="hypMap">Map</a>&nbsp;&nbsp;<span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lbl_Area" class="mArea">Loop</span><span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lt" class="mLt">41.8868010285473</span><span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl02_lg" class="mLg">-87.6312860701286</span> </div> </div> </div> </td> </tr> <tr> <td> <div class="ItemTemplate"> <div class="ParentColumn2"> <div><span id="dnn_ctr45874_ViewProjectGrid_GridView1_ctl03_lbl_Address" class="lbl_Address mAddress">...</span> ... </div> </div> </div> </td> </tr> </table> ``` The HTML is as identical between the two machines as can be possible given that it's all generated by .Net (don't get me started).
Given that you have different behaviour, it's reasonable to assume that *something* is different between the two pages, so my suggestion is to reduce both pages to the minimum that keeps the current behaviour and then see what is different.
175,858
<p>Has anyone found a way to save a FlowDocument as BAML or other compressed format? I can import XML with images to create a new FlowDocument:</p> <pre><code>&lt;TextRange class instance&gt;.Load(fs, DataFormats.Rtf) </code></pre> <p>However, I haven't found a good way to save it in a 'native' compressed format. Uncompressed XAML is easy to generate using:</p> <pre><code>&lt;TextRange class instance&gt;.Save(fs, DataFormats.Xaml); </code></pre> <p>But is there any programmatic method to save it to a compressed format?</p> <p>If there isn't an existing method, does anyone know where to find a programmatic XAML compiler? Or even just the BAML specifications? I could programmatically generate an entire XAML window with the FlowDocument embedded, but I'd still want to convert the XAML to BAML for faster load times. I'm using relatively large rtf documents and conversion time using DataFormats.Rtf is significant.</p>
[ { "answer_id": 177362, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 2, "selected": true, "text": "<p>I do not think it is possible... The BamlWriter is marked as internal, this will hopefully open up soon!</p>\n\n<p>I unfortunatly do not know of any XAML compilers</p>\n" }, { "answer_id": 184151, "author": "Fred", "author_id": 177, "author_profile": "https://Stackoverflow.com/users/177", "pm_score": 0, "selected": false, "text": "<p>Well, it turns out you can run Visual C# 2008 Express w/o the GUI. And you can modify the final program name via code before you compile as well. I'm sure you can do it via APIs, but here's the hack I found:</p>\n\n<ol>\n<li>The program's is name determined in .csproj, in the xml tag.</li>\n<li>Run via code or batch file: \"\\Common7\\IDE\\vcsexpress\" \".sln\" /rebuild Release /projectconfig Release /out errors.txt</li>\n</ol>\n\n<p>I like to examine and then delete the errors.txt after each run to make it easier to see if I got a clean build. This isn't ideal because you have to have a full bought version of Visual C# 2008 on each machine you use this way, but it is a way to create a new executable to display each flow document in a programatic way. Also if you have an error in your XAML, you may generate a program that won't run.</p>\n\n<p>Note that the BAML format does NOT compress the text, only the tags and other 'plumbing'. Even the Margin and Padding information is saved in clear ASCII. This is inherited by the end .exe leaving the text clearly visible in sections to notepad or similar.</p>\n" }, { "answer_id": 320737, "author": "Fred", "author_id": 177, "author_profile": "https://Stackoverflow.com/users/177", "pm_score": 0, "selected": false, "text": "<p>The XamlPackage format is compressed:</p>\n\n<pre><code>&lt;TextRange class instance&gt;.Save(fs, DataFormats.Xaml);\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177/" ]
Has anyone found a way to save a FlowDocument as BAML or other compressed format? I can import XML with images to create a new FlowDocument: ``` <TextRange class instance>.Load(fs, DataFormats.Rtf) ``` However, I haven't found a good way to save it in a 'native' compressed format. Uncompressed XAML is easy to generate using: ``` <TextRange class instance>.Save(fs, DataFormats.Xaml); ``` But is there any programmatic method to save it to a compressed format? If there isn't an existing method, does anyone know where to find a programmatic XAML compiler? Or even just the BAML specifications? I could programmatically generate an entire XAML window with the FlowDocument embedded, but I'd still want to convert the XAML to BAML for faster load times. I'm using relatively large rtf documents and conversion time using DataFormats.Rtf is significant.
I do not think it is possible... The BamlWriter is marked as internal, this will hopefully open up soon! I unfortunatly do not know of any XAML compilers
175,891
<p>Lets assume we have this xml: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;tns:RegistryResponse status="urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure" xmlns:tns="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0" xmlns:rim="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0"&gt; &lt;tns:RegistryErrorList highestSeverity=""&gt; &lt;tns:RegistryError codeContext="XDSInvalidRequest - DcoumentId is not unique." errorCode="XDSInvalidRequest" severity="urn:oasis:names:tc:ebxml-regrep:ErrorSeverityType:Error"/&gt; &lt;/tns:RegistryErrorList&gt; &lt;/tns:RegistryResponse&gt; </code></pre> <p>To retrieve RegistryErrorList element, we can do </p> <pre><code>XDocument doc = XDocument.Load(&lt;path to xml file&gt;); XNamespace ns = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"; XElement errorList = doc.Root.Elements( ns + "RegistryErrorList").SingleOrDefault(); </code></pre> <p>but not like this</p> <pre><code>XElement errorList = doc.Root.Elements("RegistryErrorList").SingleOrDefault(); </code></pre> <p>Is there a way to do the query without the namespace of the element. Basicly is there something conceptially similiar to using local-name() in XPath (i.e. //*[local-name()='RegistryErrorList'])</p>
[ { "answer_id": 175920, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "<pre><code>var q = from x in doc.Root.Elements()\n where x.Name.LocalName==\"RegistryErrorList\"\n select x;\n\nvar errorList = q.SingleOrDefault();\n</code></pre>\n" }, { "answer_id": 178373, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 2, "selected": false, "text": "<p>In the \"method\" syntax the query would look like: </p>\n\n<pre><code>XElement errorList = doc.Root.Elements().Where(o =&gt; o.Name.LocalName == \"RegistryErrorList\").SingleOrDefault();\n</code></pre>\n" }, { "answer_id": 33830922, "author": "Paul Shepard", "author_id": 4487589, "author_profile": "https://Stackoverflow.com/users/4487589", "pm_score": 1, "selected": false, "text": "<p>The following extension will return a collection of matching elements from any level of an XDocument (or any XContainer).</p>\n\n<pre><code> public static IEnumerable&lt;XElement&gt; GetElements(this XContainer doc, string elementName)\n {\n return doc.Descendants().Where(p =&gt; p.Name.LocalName == elementName);\n }\n</code></pre>\n\n<p>Your code would now look like this:</p>\n\n<pre><code>var errorList = doc.GetElements(\"RegistryErrorList\").SingleOrDefault();\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4795/" ]
Lets assume we have this xml: ``` <?xml version="1.0" encoding="UTF-8"?> <tns:RegistryResponse status="urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure" xmlns:tns="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0" xmlns:rim="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0"> <tns:RegistryErrorList highestSeverity=""> <tns:RegistryError codeContext="XDSInvalidRequest - DcoumentId is not unique." errorCode="XDSInvalidRequest" severity="urn:oasis:names:tc:ebxml-regrep:ErrorSeverityType:Error"/> </tns:RegistryErrorList> </tns:RegistryResponse> ``` To retrieve RegistryErrorList element, we can do ``` XDocument doc = XDocument.Load(<path to xml file>); XNamespace ns = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"; XElement errorList = doc.Root.Elements( ns + "RegistryErrorList").SingleOrDefault(); ``` but not like this ``` XElement errorList = doc.Root.Elements("RegistryErrorList").SingleOrDefault(); ``` Is there a way to do the query without the namespace of the element. Basicly is there something conceptially similiar to using local-name() in XPath (i.e. //\*[local-name()='RegistryErrorList'])
``` var q = from x in doc.Root.Elements() where x.Name.LocalName=="RegistryErrorList" select x; var errorList = q.SingleOrDefault(); ```
175,892
<p>I'm trying to resize an embedded object. The issue is that when the mouse hovers over the object, it takes "control" of the mouse, swallowing up movement events. The result being that you can expand the div containing the object, but when you try to shrink it, if the mouse enters the area of the object the resize halts. </p> <p>Currently, I hide the object while moving. I'm wondering if there's a way to just prevent the object from capturing the mouse. Perhaps overlaying another element on top of it that prevents mouse events from reaching the embedded object?</p> <hr> <p>using ghosting on the resize doesn't work for embedded objects, btw.</p> <hr> <p>Adding a bounty, as I can't ever seem to get this working. To collect, simply do the following:</p> <p>Provide a webpage with a PDF embedded in it, centered on the page. The pdf can't take up the entire page; make its width/height 50% the width of the browser window or something.</p> <p>Use jQuery 1.2.6 to add resize to every side and corner of the pdf. </p> <p>The pdf MUST NOT CAPTURE THE MOUSE and stop dragging WHEN SHRINKING THE PDF. That means when I click on the edge of the pdf and drag, when the mouse enters the display box of the pdf, the resize operation continues.</p> <p>This must work in IE 7. Conditional CSS (if gte ie7 or whatever) hacks are fine.</p> <hr> <p>Hmmm... I'm thinking it might be an issue with iframe...</p> <pre><code> &lt;div style="text-align:center; padding-top:50px;"&gt; &lt;div id="doc" style="width:384px;height:512px;"&gt; &lt;iframe id="docFrame" style="width: 100%; height: 100%;" src='http://www.ready.gov/america/_downloads/sampleplan.pdf'&gt; &lt;/iframe&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="data"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var obj = $('#docFrame'); $('#doc').resizable({handles:'all', resize: function(e, ui) { $('#data').html(ui.size.width + 'x' + ui.size.height); obj.attr({width: ui.size.width, height: ui.size.height}); }}); }); &lt;/script&gt; </code></pre> <p>This doesn't work. When your mouse strays into the iframe the resize operation stops.</p> <hr> <p>There are some good answers; if the bounty runs out before I can get around to vetting them all I'll reinstate the bounty (same 150 points).</p>
[ { "answer_id": 175904, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>Overlay.</p>\n\n<p>One word answers prohibited, this sentence no verb.</p>\n" }, { "answer_id": 177198, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 1, "selected": false, "text": "<p>I would answer overlay, but will provide actual code :P</p>\n\n<p>I call it \"follower\" instead of overlay and is used in my ThreeSixty plug-in for jQuery (kinda simple source code provided, you will understand reading what's happens to the \"follower\" div.</p>\n\n<p><a href=\"http://www.mathieusavard.info/threesixty\" rel=\"nofollow noreferrer\">http://www.mathieusavard.info/threesixty</a></p>\n" }, { "answer_id": 486265, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": true, "text": "<p>Well I was utterly unable to find a XPS Document Viewer example or whatnot, but I was able to come up with <a href=\"http://www.rootspot.com/stackoverflow/box.php\" rel=\"nofollow noreferrer\"><code>this working sample</code></a>. It doesn't use the overlay idea, but it's a pdf that you can resize...</p>\n\n<p><strong>edit</strong> the thing that made this work without the overlay was the <code>wmode</code> param being set to <code>transparent</code>. I'm not really familiar with the details but it made it play nice on IE7. Also works on Firefox, Chrome, Safari and Opera.</p>\n\n<p><strong>new edit</strong> having serious trouble getting it to work with frames. Some information I've found is not very encouraging. Is it impossible to have it with an <code>&lt;object&gt;</code>? Or an <code>&lt;object&gt;</code> inside the iframe?</p>\n" }, { "answer_id": 491963, "author": "roborourke", "author_id": 42147, "author_profile": "https://Stackoverflow.com/users/42147", "pm_score": 0, "selected": false, "text": "<p>Perhaps <a href=\"http://issuu.com/smartlook\" rel=\"nofollow noreferrer\">SmartLook</a> is an alternative. It's like those lightbox scripts but for embedded content such as pdfs.</p>\n" }, { "answer_id": 497044, "author": "Jab", "author_id": 29676, "author_profile": "https://Stackoverflow.com/users/29676", "pm_score": 0, "selected": false, "text": "<p>Here is what works for me, though is does hide the iframe while resizing. Is that an issue for you?</p>\n\n<pre><code>$(document).ready(function() {\n var obj = $('#docFrame');\n $('#doc').resizable(\n { \n handles: 'all', \n resize: function(e, ui) {\n $('#data').html(ui.size.width + 'x' + ui.size.height);\n obj.attr({ width: ui.size.width, height: ui.size.height });\n },\n start: function(e, ui) { $('#docFrame').hide(); },\n stop: function(e, ui) { $('#docFrame').show(); }\n });\n});\n</code></pre>\n" }, { "answer_id": 497112, "author": "Andrey Shchekin", "author_id": 39068, "author_profile": "https://Stackoverflow.com/users/39068", "pm_score": 0, "selected": false, "text": "<p>With IE you can call setCapture()/releaseCapture(), it worked great with iframes for me.</p>\n\n<p>With Firefox -- transparent overlay, as already suggested.</p>\n" }, { "answer_id": 497968, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>Thanks to StackOverflow's new \"Recent Activity\" feature, I saw that you asked me to provide a code example. I did only minor testing (can't seem to get your code to inline the PDF in IE, presumably it requires a PDF plugin, which I don't have installed), so this may not work. But it's a start.</p>\n\n<pre><code>&lt;div style=\"text-align: center; padding-top: 50px;\"&gt;\n &lt;div id=\"doc\" style=\"width: 384px; height: 512px; position: relative;\"&gt;\n &lt;div id=\"overlay\" style=\"position: absolute; top: -5px; left: -5px;\n padding: 5px; width: 100%; height: 100%; background: red;\n opacity: 0.5; z-index: 1; display: none;\"&gt;&lt;/div&gt;\n &lt;iframe id=\"docFrame\" style=\"width: 100%; height: 100%; position: relative; z-index: 0;\"\n src='http://www.ready.gov/america/_downloads/sampleplan.pdf'&gt;&lt;/iframe&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div id=\"data\"&gt;&lt;/div&gt;\n&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js\" type=\"text/javascript\" charset=\"utf-8\"&gt;&lt;/script&gt;\n&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.3/jquery-ui.js\" type=\"text/javascript\" charset=\"utf-8\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n $(document).ready(function() {\n var obj = $('#docFrame'), overlay = $('#overlay');\n $('#doc').resizable({\n handles: 'all',\n start: function() {\n overlay.show();\n },\n resize: function(e, ui) {\n $('#data').html(ui.size.width + 'x' + ui.size.height);\n obj.attr({\n width: ui.size.width,\n height: ui.size.height\n });\n },\n stop: function(e, ui) {\n overlay.hide();\n }\n });\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 23929782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>var dframe = $(\"#docFrame\");\n\n$(document).ready(function () {\n var b = dframe;\n $(\"#doc\").e({\n b: \"all\",\n resize: function (c, a) {\n $(\"#data\").html(a.size.width + \"x\" + a.size.height);\n object.attr({\n width: a.size.width,\n height: a.size.height\n });\n },\n start: function () {\n dframe.hide();\n },\n stop: function () {\n dframe.show();\n }\n });\n});\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to resize an embedded object. The issue is that when the mouse hovers over the object, it takes "control" of the mouse, swallowing up movement events. The result being that you can expand the div containing the object, but when you try to shrink it, if the mouse enters the area of the object the resize halts. Currently, I hide the object while moving. I'm wondering if there's a way to just prevent the object from capturing the mouse. Perhaps overlaying another element on top of it that prevents mouse events from reaching the embedded object? --- using ghosting on the resize doesn't work for embedded objects, btw. --- Adding a bounty, as I can't ever seem to get this working. To collect, simply do the following: Provide a webpage with a PDF embedded in it, centered on the page. The pdf can't take up the entire page; make its width/height 50% the width of the browser window or something. Use jQuery 1.2.6 to add resize to every side and corner of the pdf. The pdf MUST NOT CAPTURE THE MOUSE and stop dragging WHEN SHRINKING THE PDF. That means when I click on the edge of the pdf and drag, when the mouse enters the display box of the pdf, the resize operation continues. This must work in IE 7. Conditional CSS (if gte ie7 or whatever) hacks are fine. --- Hmmm... I'm thinking it might be an issue with iframe... ``` <div style="text-align:center; padding-top:50px;"> <div id="doc" style="width:384px;height:512px;"> <iframe id="docFrame" style="width: 100%; height: 100%;" src='http://www.ready.gov/america/_downloads/sampleplan.pdf'> </iframe></div></div> <div id="data"></div> <script type="text/javascript"> $(document).ready(function() { var obj = $('#docFrame'); $('#doc').resizable({handles:'all', resize: function(e, ui) { $('#data').html(ui.size.width + 'x' + ui.size.height); obj.attr({width: ui.size.width, height: ui.size.height}); }}); }); </script> ``` This doesn't work. When your mouse strays into the iframe the resize operation stops. --- There are some good answers; if the bounty runs out before I can get around to vetting them all I'll reinstate the bounty (same 150 points).
Well I was utterly unable to find a XPS Document Viewer example or whatnot, but I was able to come up with [`this working sample`](http://www.rootspot.com/stackoverflow/box.php). It doesn't use the overlay idea, but it's a pdf that you can resize... **edit** the thing that made this work without the overlay was the `wmode` param being set to `transparent`. I'm not really familiar with the details but it made it play nice on IE7. Also works on Firefox, Chrome, Safari and Opera. **new edit** having serious trouble getting it to work with frames. Some information I've found is not very encouraging. Is it impossible to have it with an `<object>`? Or an `<object>` inside the iframe?
175,951
<p>Among other text and visual aids on a form submission, post-validation, I'm coloring my input boxes red to signify the interactive area needing attention.</p> <p>On Chrome (and for Google Toolbar users) the auto-fill feature re-colors my input forms yellow. Here's the complex issue: I want auto-complete allowed on my forms, as it speeds users logging in. I am going to check into the ability to turn the autocomplete attribute to off if/when there's an error triggered, but it is a complex bit of coding to programmatically turn off the auto-complete for the single affected input on a page. This, to put it simply, would be a major headache.</p> <p>So to try to avoid that issue, is there any simpler method of stopping Chrome from re-coloring the input boxes?</p> <p>[edit] I tried the !important suggestion below and it had no effect. I have not yet checked Google Toolbar to see if the !important attribute would work for that.</p> <p>As far as I can tell, there isn't any means other than using the autocomplete attribute (which does appear to work).</p>
[ { "answer_id": 175963, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": -1, "selected": false, "text": "<p>If I remember correctly, an !important rule in the stylesheet for the background color of the inputs will override the Google toolbar autocomplete - presumably the same would be true of Chrome.</p>\n" }, { "answer_id": 175972, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 2, "selected": false, "text": "<p>Yes, it would be a major headache, which in my opinion isnt worth the return. Maybe you could tweak your UI strategy a bit, and instead of coloring the box red, you could color the borders red, or put a small red tape beside it (like the gmails \"Loading\" tape) which fades away when the box is in focus.</p>\n" }, { "answer_id": 175980, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 7, "selected": true, "text": "<p>I know in Firefox you can use the attribute autocomplete=\"off\" to disable the autocomplete functionality. If this works in Chrome (haven't tested), you could set this attribute when an error is encountered.</p>\n\n<p>This can be used for both a single element</p>\n\n<pre><code>&lt;input type=\"text\" name=\"name\" autocomplete=\"off\"&gt;\n</code></pre>\n\n<p>...as well as for an entire form</p>\n\n<pre><code>&lt;form autocomplete=\"off\" ...&gt;\n</code></pre>\n" }, { "answer_id": 582741, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 7, "selected": false, "text": "<p>Set the CSS outline property to none.</p>\n\n<pre><code>input[type=\"text\"], input[type=\"password\"], textarea, select { \n outline: none;\n}\n</code></pre>\n\n<p>In cases where the browser may add a background color as well this can be fixed by something like </p>\n\n<pre><code>:focus { background-color: #fff; }\n</code></pre>\n" }, { "answer_id": 4261239, "author": "Benjamin", "author_id": 518077, "author_profile": "https://Stackoverflow.com/users/518077", "pm_score": 4, "selected": false, "text": "<p>By using a bit of jQuery you can remove Chrome's styling while keeping the autocomplete functionality intact. I wrote a short post about it here:\n<a href=\"http://www.benjaminmiles.com/2010/11/22/fixing-google-chromes-yellow-autocomplete-styles-with-jquery/\">http://www.benjaminmiles.com/2010/11/22/fixing-google-chromes-yellow-autocomplete-styles-with-jquery/</a></p>\n\n<pre><code>if (navigator.userAgent.toLowerCase().indexOf(\"chrome\") &gt;= 0) {\n$(window).load(function(){\n $('input:-webkit-autofill').each(function(){\n var text = $(this).val();\n var name = $(this).attr('name');\n $(this).after(this.outerHTML).remove();\n $('input[name=' + name + ']').val(text);\n });\n});}\n</code></pre>\n" }, { "answer_id": 4646436, "author": "Kita", "author_id": 569779, "author_profile": "https://Stackoverflow.com/users/569779", "pm_score": 3, "selected": false, "text": "<p>To remove the border for all fields you can use the following:</p>\n\n<p><code>*:focus { outline:none; }</code></p>\n\n<p>To remove the border for select fields just apply this class to the input fields you want:</p>\n\n<p><code>.nohighlight:focus { outline:none; }</code></p>\n\n<p>You can of course change the border as you desire as well:</p>\n\n<p><code>.changeborder:focus { outline:Blue Solid 4px; }</code></p>\n\n<p>(From Bill Beckelman: <a href=\"http://beckelman.net/post/2008/09/15/Override-Chromes-Automatic-Border-Around-Active-Fields-Using-CSS.aspx\">Override Chrome's Automatic Border Around Active Fields Using CSS</a>)</p>\n" }, { "answer_id": 6243894, "author": "Tim", "author_id": 181971, "author_profile": "https://Stackoverflow.com/users/181971", "pm_score": 1, "selected": false, "text": "<p>The simpler way in my opinion is:</p>\n\n<ol>\n<li>Get <a href=\"http://www.quirksmode.org/js/detect.html\" rel=\"nofollow\">http://www.quirksmode.org/js/detect.html</a></li>\n<li><p>Use this code:</p>\n\n<pre><code>if (BrowserDetect.browser == \"Chrome\") {\n jQuery('form').attr('autocomplete','off');\n};\n</code></pre></li>\n</ol>\n" }, { "answer_id": 6329149, "author": "NewFangSol", "author_id": 795741, "author_profile": "https://Stackoverflow.com/users/795741", "pm_score": 0, "selected": false, "text": "<pre><code>input:focus { outline:none; }\n</code></pre>\n\n<p>That worked great for me but more than likely to keep things uniform on your site your going to want to also include this in your CSS for textareas:</p>\n\n<pre><code>textarea:focus { outline:none; }\n</code></pre>\n\n<p>Also it may seem obvious to most but for beginners you can also set it to a color as such:</p>\n\n<pre><code>input:focus { outline:#HEXCOD SOLID 2px ; }\n</code></pre>\n" }, { "answer_id": 9152101, "author": "hohner", "author_id": 427992, "author_profile": "https://Stackoverflow.com/users/427992", "pm_score": 2, "selected": false, "text": "<p>It's a piece of cake with jQuery:</p>\n\n<pre><code>if ($.browser.webkit) {\n $(\"input\").attr('autocomplete','off');\n}\n</code></pre>\n\n<p>Or if you want to be a bit more selective, add a class name for a selector.</p>\n" }, { "answer_id": 15957374, "author": "321X", "author_id": 243493, "author_profile": "https://Stackoverflow.com/users/243493", "pm_score": 1, "selected": false, "text": "<p>After applying @Benjamin his solution I found out that pressing the back button would still give me the yellow highlight.</p>\n\n<p>My solution <em>somehow</em> to prevent this yellow highlight to come back is by applying the following jQuery javascript:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(function() {\n if (navigator.userAgent.toLowerCase().indexOf(\"chrome\") &gt;= 0) {\n var intervalId = 0;\n $(window).load(function() {\n intervalId = setInterval(function () { // &lt;&lt; somehow this does the trick!\n if ($('input:-webkit-autofill').length &gt; 0) {\n clearInterval(intervalId);\n $('input:-webkit-autofill').each(function () {\n var text = $(this).val();\n var name = $(this).attr('name');\n $(this).after(this.outerHTML).remove();\n $('input[name=' + name + ']').val(text);\n });\n }\n }, 1);\n });\n }\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>Hope it helps anyone!!</p>\n" }, { "answer_id": 20671898, "author": "Vin", "author_id": 1982454, "author_profile": "https://Stackoverflow.com/users/1982454", "pm_score": 1, "selected": false, "text": "<p>This works. Best of all, you can use rgba values (the box-shadow inset hack doesn't work with rgba). This is a slight tweak of @Benjamin's answer. I am using $(document).ready() instead of $(window).load(). It seems to work better for me - now there's much less FOUC. I don't believe there are and disadvantages to using $(document).ready().</p>\n\n<pre><code>if (navigator.userAgent.toLowerCase().indexOf(\"chrome\") &gt;= 0) {\n $(document).ready(function() {\n $('input:-webkit-autofill').each(function(){\n var text = $(this).val();\n var name = $(this).attr('name');\n $(this).after(this.outerHTML).remove();\n $('input[name=' + name + ']').val(text);\n });\n });\n};\n</code></pre>\n" }, { "answer_id": 25881221, "author": "JStormThaKid", "author_id": 1935762, "author_profile": "https://Stackoverflow.com/users/1935762", "pm_score": 6, "selected": false, "text": "<p>this is exactly what your looking for!</p>\n\n<pre><code>// Just change \"red\" to any color\ninput:-webkit-autofill {\n -webkit-box-shadow: 0 0 0px 1000px red inset;\n}\n</code></pre>\n" }, { "answer_id": 36440039, "author": "hsobhy", "author_id": 1030977, "author_profile": "https://Stackoverflow.com/users/1030977", "pm_score": 1, "selected": false, "text": "<p>for today's versions, This works too if placed in one of the two login inputs. Also fix the version 40+ and late Firefox issue.</p>\n\n<pre><code>&lt;input readonly=\"readonly\" onfocus=\"this.removeAttribute('readonly');\" /&gt;\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486915/" ]
Among other text and visual aids on a form submission, post-validation, I'm coloring my input boxes red to signify the interactive area needing attention. On Chrome (and for Google Toolbar users) the auto-fill feature re-colors my input forms yellow. Here's the complex issue: I want auto-complete allowed on my forms, as it speeds users logging in. I am going to check into the ability to turn the autocomplete attribute to off if/when there's an error triggered, but it is a complex bit of coding to programmatically turn off the auto-complete for the single affected input on a page. This, to put it simply, would be a major headache. So to try to avoid that issue, is there any simpler method of stopping Chrome from re-coloring the input boxes? [edit] I tried the !important suggestion below and it had no effect. I have not yet checked Google Toolbar to see if the !important attribute would work for that. As far as I can tell, there isn't any means other than using the autocomplete attribute (which does appear to work).
I know in Firefox you can use the attribute autocomplete="off" to disable the autocomplete functionality. If this works in Chrome (haven't tested), you could set this attribute when an error is encountered. This can be used for both a single element ``` <input type="text" name="name" autocomplete="off"> ``` ...as well as for an entire form ``` <form autocomplete="off" ...> ```
175,961
<blockquote> <pre><code>List&lt;tinyClass&gt; ids = new List&lt;tinyClass(); ids.Add(new tinyClass(1, 2)); bool b = ids.IndexOf(new tinyClass(1, 2)) &gt;= 0; //true or false? </code></pre> </blockquote> <p>If it compares by value, it should return true; if by reference, it will return false.<br> If it compares by reference, and I make tinyClass a struct - will that make a difference?</p>
[ { "answer_id": 175988, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 5, "selected": true, "text": "<p>From MSDN:</p>\n<blockquote>\n<p>This method determines equality using the default equality comparer EqualityComparer&lt;T&gt;.Default for T, the type of values in the list.</p>\n<p>The Default property checks whether type T implements the System.IEquatable&lt;T&gt; generic interface and if so returns an EqualityComparer&lt;T&gt; that uses that implementation. Otherwise it returns an EqualityComparer&lt;T&gt; that uses the overrides of Object.Equals and Object.GetHashCode provided by T.</p>\n</blockquote>\n<p>It seems like it uses the Equals method, unless the stored class implements the IEquatable&lt;T&gt; interface.</p>\n" }, { "answer_id": 176002, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 2, "selected": false, "text": "<p>It depends on the object's implementation of .Equals(..). By default for an object, the references are compared. If you did change it to a struct, then I believe it would evaluate to true based on the equality of the private members, but it would still be more programmically sound to implement IEquatable.</p>\n" }, { "answer_id": 176029, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>For a class, with the default implementation of Equals - it will compare by reference.</p>\n\n<p>If you change it to a tinyStruct, it will compare it by value.</p>\n" }, { "answer_id": 768451, "author": "John Gibb", "author_id": 99046, "author_profile": "https://Stackoverflow.com/users/99046", "pm_score": 0, "selected": false, "text": "<p>Be sure to implement .Equals(..) for your struct, as the default implementation may use reflection to compare each field, which is very expensive. </p>\n\n<p>Read more at: <a href=\"http://blogs.microsoft.co.il/blogs/sasha/archive/2007/08.aspx\" rel=\"nofollow noreferrer\">http://blogs.microsoft.co.il/blogs/sasha/archive/2007/08.aspx</a></p>\n" }, { "answer_id": 1021132, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It also may be related to which of the class or struct instance is kept in the list, because of structs' <em>equal</em> implementation is based on values' equality.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8435/" ]
> > > ``` > List<tinyClass> ids = new List<tinyClass(); > ids.Add(new tinyClass(1, 2)); > > bool b = ids.IndexOf(new tinyClass(1, 2)) >= 0; //true or false? > > ``` > > If it compares by value, it should return true; if by reference, it will return false. If it compares by reference, and I make tinyClass a struct - will that make a difference?
From MSDN: > > This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list. > > > The Default property checks whether type T implements the System.IEquatable<T> generic interface and if so returns an EqualityComparer<T> that uses that implementation. Otherwise it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T. > > > It seems like it uses the Equals method, unless the stored class implements the IEquatable<T> interface.
175,962
<p>How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+:</p> <pre><code>DECLARE @count int SET @count = 20 SELECT TOP @count * FROM SomeTable </code></pre>
[ { "answer_id": 175965, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 10, "selected": true, "text": "<pre><code>SELECT TOP (@count) * FROM SomeTable\n</code></pre>\n\n<p>This will only work with SQL 2005+</p>\n" }, { "answer_id": 175978, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 5, "selected": false, "text": "<p>The syntax \"select top (@var) ...\" only works in SQL SERVER 2005+. For SQL 2000, you can do:</p>\n\n<pre><code>set rowcount @top\n\nselect * from sometable\n\nset rowcount 0 \n</code></pre>\n\n<p>Hope this helps</p>\n\n<p>Oisin.</p>\n\n<p>(edited to replace @@rowcount with rowcount - thanks augustlights)</p>\n" }, { "answer_id": 176262, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 4, "selected": false, "text": "<p>In x0n's example, it should be:</p>\n\n<pre><code>SET ROWCOUNT @top\n\nSELECT * from sometable\n\nSET ROWCOUNT 0\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188774.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms188774.aspx</a></p>\n" }, { "answer_id": 177626, "author": "Jan", "author_id": 25727, "author_profile": "https://Stackoverflow.com/users/25727", "pm_score": 2, "selected": false, "text": "<p>Its also possible to use dynamic SQL and execute it with the exec command:</p>\n\n<pre><code>declare @sql nvarchar(200), @count int\nset @count = 10\nset @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'\nexec (@sql)\n</code></pre>\n" }, { "answer_id": 34663655, "author": "ShawnThompson", "author_id": 5759395, "author_profile": "https://Stackoverflow.com/users/5759395", "pm_score": 3, "selected": false, "text": "<p>Or you just put the variable in parenthesis</p>\n\n<pre><code>DECLARE @top INT = 10;\n\nSELECT TOP (@Top) *\nFROM &lt;table_name&gt;;\n</code></pre>\n" }, { "answer_id": 42775624, "author": "David Castro", "author_id": 3199531, "author_profile": "https://Stackoverflow.com/users/3199531", "pm_score": 3, "selected": false, "text": "<pre><code>declare @rows int = 10\n\nselect top (@rows) *\nfrom Employees\norder by 1 desc -- optional to get the last records using the first column of the table\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+: ``` DECLARE @count int SET @count = 20 SELECT TOP @count * FROM SomeTable ```
``` SELECT TOP (@count) * FROM SomeTable ``` This will only work with SQL 2005+
175,982
<p>I have a copy of emacs that I use on a couple of different (windows) computers from a thumb drive, and I am wondering if it is possible to create something that is sort of the equivalent of a bash alias or symlink within emacs? Something that I could use within find-file is the main thing that i'm looking for, so for example: <code>C-f &lt;some link&gt;</code> would take me somewhere. Currently I have to add a new defun every time i get to a new computer, which is just kind of a pain and I would <em>swear</em> i've seen this somewhere, but months of googling have turned up nothing.</p> <p>What i've got right now is something like:</p> <pre><code>(defun go-awesome () "Find my way to my work home" (interactive) (find-file "c:/cygwin/home/awesome")) </code></pre> <p>But that feels increadibly overdone and hacky for just visiting a fairly hacky for just visiting a file that i visit semi-regularly. And it requires a lot of effort to set up a new file.</p> <p>The biggest problem with it though, in my opinion is that it doesn't fit in my workflow. When i want to visit a file i always do <code>C-x C-f</code>, and if i realize that "hey i'm at work" i then have to <code>C-g M-x go-awesome</code>. Perhaps it would be more clear if i said that i wanted to be able to do something that is the equivalent of an <code>ln -s /some/awesome/dir</code> but internal to emacs, instead of built into the OS, so that <code>C-x C-f ~/awesome/some/sub/dir</code> would work on windows or anywhere else.</p>
[ { "answer_id": 176194, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 5, "selected": true, "text": "<p>I'm not really clear on what you're asking for. I store my commonly-used files in registers in my .emacs:</p>\n\n<pre><code>(set-register ?c '(file . \"c:/data/common.txt\"))\n(set-register ?f '(file . \"c:/data/frequent.txt\"))\n</code></pre>\n\n<p>Then I can jump to a file with <code>jump-to-register</code> (<code>C-x r j</code>):</p>\n\n<p>For example, \"<code>C-x r j c</code>\" takes me to <code>c:/data/common.txt</code> (loading it if necessary).</p>\n\n<p>Is that what you're looking for?</p>\n" }, { "answer_id": 177314, "author": "quodlibetor", "author_id": 25616, "author_profile": "https://Stackoverflow.com/users/25616", "pm_score": -1, "selected": false, "text": "<p><strong><em>I Moved this into the original question, but i'm leaving it here because people responded to it already</em></strong></p>\n\n<p>That's way better than what i've got, but what i feel like probably exists is something that would replace, for example:</p>\n\n<pre><code>(defun nuke ()\n \"alias delete-trailing-whitespace\"\n (interactive)\n (delete-trailing-whitespace))\n</code></pre>\n\n<p>and feel less hacky, and like it was actually doing what it was supposed to be doing, instead of doing something really heavy for what feels like something that should be really light.</p>\n\n<p>Does that make sense?</p>\n\n<p>Your assign to registers might actually be better than what i'm looking for, though.</p>\n" }, { "answer_id": 177345, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<p>If you want an alias to a function, you use <code>defalias</code>:</p>\n\n<pre><code>(defalias 'nuke 'delete-trailing-whitespace)\n</code></pre>\n\n<p>But if you're complaining that Emacs's function names are too long, you should look into <code>partial-completion-mode</code>. With that turned on,</p>\n\n<pre><code>M-x d-t-w [RET]\n</code></pre>\n\n<p>will run <code>delete-trailing-whitespace</code>.</p>\n" }, { "answer_id": 200489, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": 0, "selected": false, "text": "<p>I what you want is open a given file with just a command you can define a keyboard macro.\nThis macro open the file ~/.bashrc</p>\n\n<pre><code> C-x( # start defining the macro\n C-x C-f ~/.bashrc \n C-x ) # end definition\n</code></pre>\n\n<p>Then you can name this macro</p>\n\n<pre><code>M-x name-last-kbd-macro\nvisitbashrc #give it a name\n</code></pre>\n\n<p>then you can call it by name\nM-x visitbashrc</p>\n\n<p>You can save the definition to a file, .emacs for instance by visiting this file \nand inserting the definition in it, with</p>\n\n<pre><code>M-x insert-kbd-macro\n</code></pre>\n" }, { "answer_id": 365543, "author": "polyglot", "author_id": 45383, "author_profile": "https://Stackoverflow.com/users/45383", "pm_score": 0, "selected": false, "text": "<p>I have this setup below. So for example, if I want to find a file on my desktop (D:/Desktop), I type F3 j F3, and no matter what path I started with, the minibuffer now says \"D:\\Desktop\\\" and I'm ready to type any filename on the Desktop. I set my shortcut to j, k, l, i b/c those are close to where my left hand is, but with this setup, any shortcut up to 4 letters will work. So you can add an entry for your \"awsome\" file, say \"awe\", and you can type F3 awe F3 enter to visit your file. Don't know whether this is what you are looking for; but this save me a lots of typing ;)</p>\n\n<pre><code>(global-set-key [f3] 'ffap)\n\n;comcplete shortcut in minibuffer\n(define-key minibuffer-local-completion-map (kbd \"&lt;f3&gt;\")\n 'complete-minibuffer-path) \n\n(defun complete-minibuffer-path ()\n \"Extension to the complete word facility of the minibuffer by\nreplacing matching strings to a specific path\"\n (interactive)\n (setq found t)\n (cond\n ; just add new entries if needed; shortcut up to 4 letters will work\n ((looking-back \"j\" 5 nil) (setq directory \"D:/Desktop/\"))\n ((looking-back \"k\" 5 nil) (setq directory \"D:/Documents/\"))\n ((looking-back \"l\" 5 nil) (setq directory home-dir))\n ((looking-back \"i\" 5 nil) (setq directory \"D:/Programs/\"))\n (t (setq found nil)))\n (cond (found (beginning-of-line)\n (kill-line)\n (insert directory))\n (t (minibuffer-complete)))) \n</code></pre>\n" }, { "answer_id": 1934276, "author": "quodlibetor", "author_id": 25616, "author_profile": "https://Stackoverflow.com/users/25616", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"http://scottfrazersblog.blogspot.com/2009/12/emacs-using-bookmarked-directories.html\" rel=\"nofollow noreferrer\" title=\"hey scott frazer where have you been all my life?\">blog entry</a> defines almost <em>exactly</em> what I wanted, basically let's me hit <code>$</code> in the minibuffer and then presents me with a list of my bookmarks that I can jump to. I might tweak it so that if I specify a file bookmark it takes me to the file instead of the directory, but that's a nit, especially considering that the file the bookmark is of tends to be at the top of the list anyway.</p>\n" }, { "answer_id": 7984228, "author": "Drew", "author_id": 729907, "author_profile": "https://Stackoverflow.com/users/729907", "pm_score": 2, "selected": false, "text": "<p>Here's what you need --</p>\n\n<ul>\n<li><p>Define bookmarks that correspond to contexts you want to revisit. With <a href=\"http://www.emacswiki.org/emacs/BookmarkPlus\" rel=\"nofollow\"><strong><em>Bookmark+</em></strong></a> this need not be just a file. It can also be a whole Emacs desktop or a Dired buffer with its markings (saved), a set of other bookmarks,...</p></li>\n<li><p>Use <a href=\"http://www.emacswiki.org/cgi-bin/wiki/Icicles\" rel=\"nofollow\"><strong><em>Icicles</em></strong></a> together with <strong>Bookmark+</strong>. Whenever you use <kbd>C-x C-f</kbd> etc. to visit a file, you can also <a href=\"http://www.emacswiki.org/emacs/Icicles_-_File-Name_Input#icicle-bookmark-file-other-window\" rel=\"nofollow\">visit a file or directory bookmark</a> (complete against the bookmark name). Just hit <kbd>C-x m</kbd> when you are in the minibuffer for file-name completion. </p></li>\n</ul>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25616/" ]
I have a copy of emacs that I use on a couple of different (windows) computers from a thumb drive, and I am wondering if it is possible to create something that is sort of the equivalent of a bash alias or symlink within emacs? Something that I could use within find-file is the main thing that i'm looking for, so for example: `C-f <some link>` would take me somewhere. Currently I have to add a new defun every time i get to a new computer, which is just kind of a pain and I would *swear* i've seen this somewhere, but months of googling have turned up nothing. What i've got right now is something like: ``` (defun go-awesome () "Find my way to my work home" (interactive) (find-file "c:/cygwin/home/awesome")) ``` But that feels increadibly overdone and hacky for just visiting a fairly hacky for just visiting a file that i visit semi-regularly. And it requires a lot of effort to set up a new file. The biggest problem with it though, in my opinion is that it doesn't fit in my workflow. When i want to visit a file i always do `C-x C-f`, and if i realize that "hey i'm at work" i then have to `C-g M-x go-awesome`. Perhaps it would be more clear if i said that i wanted to be able to do something that is the equivalent of an `ln -s /some/awesome/dir` but internal to emacs, instead of built into the OS, so that `C-x C-f ~/awesome/some/sub/dir` would work on windows or anywhere else.
I'm not really clear on what you're asking for. I store my commonly-used files in registers in my .emacs: ``` (set-register ?c '(file . "c:/data/common.txt")) (set-register ?f '(file . "c:/data/frequent.txt")) ``` Then I can jump to a file with `jump-to-register` (`C-x r j`): For example, "`C-x r j c`" takes me to `c:/data/common.txt` (loading it if necessary). Is that what you're looking for?
175,994
<p>I have written an HTML Application (hta file) and am wondering if there is a way to embed an icon file into the hta file itself.</p> <p>I have seen html emails that include embedded graphic files, is there any way to do this with html applications and icons?</p> <p>HTA files have an HTA:APPLICATION tag that allows you to specify an icon, but I want to have only a single file for download. I don't want to have an external icon file. Is this possible?</p> <p>More info on hta files here: <a href="http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx" rel="noreferrer">HTA files</a>.</p>
[ { "answer_id": 176049, "author": "Buzz", "author_id": 13113, "author_profile": "https://Stackoverflow.com/users/13113", "pm_score": 2, "selected": false, "text": "<p>Quite possibly ... there is a way to embed images directly into an html file that may work for this <a href=\"http://www.sveinbjorn.org/news/2005-11-28-02-39-23\" rel=\"nofollow noreferrer\">http://www.sveinbjorn.org/news/2005-11-28-02-39-23</a></p>\n" }, { "answer_id": 176065, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": false, "text": "<p>I remember seeing <a href=\"http://www.websiteoptimization.com/speed/tweak/inline-images/\" rel=\"noreferrer\">this</a> a looong time ago:</p>\n\n<pre><code>&lt;img src=\"data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7\"width=\"16\" height=\"14\" alt=\"embedded folder icon\"&gt;\n</code></pre>\n\n<p>I've never tried it myself though.</p>\n" }, { "answer_id": 184054, "author": "seisyll", "author_id": 21815, "author_profile": "https://Stackoverflow.com/users/21815", "pm_score": 1, "selected": false, "text": "<p>IE doesn't support data URIs, so you're going to have to use an external file if you use the <strong>img</strong> tag.</p>\n\n<p>The only thing I can think of is to use VML, which has been around since IE5. It's an SVG-like vector image format that can be used inline. For example, draw something using <a href=\"http://www.dynamicdrive.com/dynamicindex11/editor.htm\" rel=\"nofollow noreferrer\">this VML editor</a> and click \"Get code\". You can plop that in your HTA. I'm not aware of anything that will convert your image to VML directly, but I believe there is a way to export to VML from some Office products.</p>\n" }, { "answer_id": 185470, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 1, "selected": false, "text": "<p>It's a pretty far-fetched answer, but you could embed the icon as base64-encoded XML in the HTA, then use JavaScript onload and save the icon file to a temporary location. The ActiveX Object <code>MSXML.DomDocument</code> can encode and decode base64 nodes.</p>\n" }, { "answer_id": 1052110, "author": "Bob77", "author_id": 126278, "author_profile": "https://Stackoverflow.com/users/126278", "pm_score": 1, "selected": false, "text": "<p>As soon as you need an &lt;<code>iframe</code>> or other HTML dialog you're going to want additional files anyway. You'll generaly find that .CSS and .VBS files separate from the .HTA make programming and support a lot easier for any non-trivial HTA too.</p>\n\n<p>One alternative for doing this as \"a single EXE\" is to wrap everything up as a self-extracting archive or via IExpress. When the user \"runs your program\" it extracts everything from your archive into a temp directory and runs the item of your choice.</p>\n\n<p>There are 3rd party alternatives like <a href=\"http://www.htmlapp.com/\" rel=\"nofollow noreferrer\">HTMLApp</a> too.</p>\n" }, { "answer_id": 1138939, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Consider using one of the applications in System32 for your icon.</p>\n\n<p>This won't change the icon for an HTA file that's on the desktop, but once it's running it will add some personality to the task bar and such.</p>\n\n<p>I often use the following to add a bit of charm to my HTAs.</p>\n\n<pre><code>&lt;hta:application icon=\"magnify.exe\" /&gt;\n</code></pre>\n\n<p>I don't believe it's possible to use icons from a library, but just open System32 in Explorer and change it to icon view and see if there are any icons that catch your fancy at all.</p>\n" }, { "answer_id": 1871411, "author": "Alex Jasmin", "author_id": 162407, "author_profile": "https://Stackoverflow.com/users/162407", "pm_score": 6, "selected": true, "text": "<p>I've found an hack to set the icon.</p>\n\n<p>Prepare an icon file <em>icon.ico</em> and an hta file <em>source.hta</em> with the following contents:</p>\n\n<pre><code>&lt;HTML&gt;\n&lt;HEAD&gt;\n &lt;SCRIPT&gt;\n path = document.URL;\n document.write(\n '&lt;HTA:APPLICATION ID=\"oHTA\" APPLICATIONNAME=\"myApp\" ICON=\"'+path+'\"&gt;');\n &lt;/SCRIPT&gt;\n&lt;/HEAD&gt;\n&lt;BODY SCROLL=\"no\"&gt;\n Hello, World!\n&lt;/BODY&gt;\n&lt;/HTML&gt;\n</code></pre>\n\n<p>Open a command prompt and type:</p>\n\n<pre><code>copy /b icon.ico+source.hta iconapp.hta\n</code></pre>\n\n<p>That will concatenate the icon and hta into a single file.</p>\n\n<p>In my test case Internet explorer skipped over the icon data and display the HTML correctly.</p>\n\n<p>The path of the icon is then set to that of the .hta file itself using javascript and the icon is loaded.</p>\n\n<p>I have tested this on Windows XP SP3, Internet explorer 8.</p>\n" }, { "answer_id": 10403321, "author": "Gilles Maisonneuve", "author_id": 1368495, "author_profile": "https://Stackoverflow.com/users/1368495", "pm_score": 2, "selected": false, "text": "<p>Another possible solution, but not completely compliant with the exact phrasing of the question, would be to convert the HTA into an .EXE file using the \"HTAedit\" application (http://www.htaedit.com/).</p>\n\n<p>They offer a trial version that is compltely functional (just some startup nag screen and no history/recent files) without blocking creation of .EXE from the HTA source, with no time limit.</p>\n\n<p>You can then declare your icon with the ICON=\"myicon.ico\" statement in the HTA header block, then when it \"compiles\" (according to my opinion it's more likely rather a packager than a real compiler but that's not the point here) it ask you for additional resource files. If your icon file is not already listed there, then just add it into the list, \"et voilà !\". You get a nice executable with it's version number and embedded icon.</p>\n\n<p>Actually that's what I did with the Microsoft Scripting Guys tools (HTA_HELPOMATIC.HTA and SCRIPTOMATIC.HTA): I just changed them in EXE adding an icon from some %windir%\\system32 exe/dll I found matching more or less the meaning of the tools, and it worked perfectly.</p>\n\n<p>On the run it might be more portable than just embedding the icon into the HTA (HTAedit tool seems to be able to produce W7/64 executables but I did not test it that way, I'm still under XP32-SP2...) and it keeps your source hta file readable and editable by a text editor.</p>\n" }, { "answer_id": 21924835, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 2, "selected": false, "text": "<p>I know it's not exactly what the OP requested, but, instead of embedding an icon in the <code>.hta</code>, have you consider a URL to an icon file? Many websites have a website icon <code>favicon.ico</code> which works in HTA applications:</p>\n<pre><code>&lt;HTML&gt;\n&lt;HEAD&gt;\n &lt;HTA:APPLICATION\n ID=&quot;oHTA&quot;\n APPLICATIONNAME=&quot;myApp&quot;\n ICON=&quot;https://stackoverflow.com/favicon.ico&quot;&gt;\n&lt;/HEAD&gt;\n&lt;BODY SCROLL=&quot;no&quot;&gt;\n Hello, World!\n&lt;/BODY&gt;\n&lt;/HTML&gt;\n</code></pre>\n<p>This gives you limitless choices in icons without the need to deploy one with your HTA application.</p>\n" }, { "answer_id": 35108628, "author": "user2707695", "author_id": 2707695, "author_profile": "https://Stackoverflow.com/users/2707695", "pm_score": 0, "selected": false, "text": "<p>Another solution, but not completely compliant with the exact phrasing of the question, is to create a simple shortcut. For 64-bit systems you should enter:</p>\n\n<p>target: C:\\Windows\\SysWOW64\\mshta.exe C:\\path+filename.hta</p>\n\n<p>start in: C:\\Windows\\SysWOW64</p>\n\n<p>You can manually change the icon of the shortcut.\nThe user can drag the shortcut to the taskbar.</p>\n\n<p>The extention of the hta file is of no importance to mshta.exe. So if you give it a custom extension, then the hta files will show with the corresponding custom icon.</p>\n" }, { "answer_id": 41581844, "author": "Kerry Johnson", "author_id": 7402315, "author_profile": "https://Stackoverflow.com/users/7402315", "pm_score": 0, "selected": false, "text": "<p>You could embed a base64 encoded image into the HTA and create the file locally on the first execution.</p>\n\n<p>Below is a HTA that creates a \"favicon.ico\" (<a href=\"https://stackoverflow.com/favicon.ico\">https://stackoverflow.com/favicon.ico</a>) file from a base64 string. It can encode an image file also (with code adapted from <a href=\"https://stackoverflow.com/questions/496751/base64-encode-string-in-vbscript\">Base64 Encode String in VBScript</a> and <a href=\"https://stackoverflow.com/questions/21559775/vbscript-to-open-a-dialog-to-select-a-filepath\">VBScript to open a dialog to select a filepath</a>).</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;HTA:APPLICATION\n ID=\"oHta\"\n APPLICATIONNAME=\"Icon test...\"\n ICON=\"favicon.ico\"\n /&gt;\n&lt;LINK id=shortcutlink REL=\"SHORTCUT ICON\" HREF=\"favicon.ico\"&gt;\n&lt;META http-equiv=\"x-ua-compatible\" content=\"text/html; charset=utf-8\"&gt;\n&lt;TITLE&gt;Icon test&lt;/TITLE&gt;\n&lt;/head&gt;\n\n&lt;script language=vbscript&gt;\n\nFunction fBase64Encode(sourceStr)\n\n Dim rarr()\n\n carr = Array( \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", _\n \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\" ,\"P\", _\n \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", _\n \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", _\n \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", _\n \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", _\n \"w\", \"x\", \"y\", \"z\", \"0\", \"1\", \"2\", \"3\", _\n \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"+\", \"/\") \n\n n = Len(sourceStr)-1\n\n ReDim rarr(n\\3)\n\n For i=0 To n Step 3\n a = Asc(Mid(sourceStr,i+1,1))\n If i &lt; n Then\n b = Asc(Mid(sourceStr,i+2,1))\n Else\n b = 0\n End If\n If i &lt; n-1 Then\n c = Asc(Mid(sourceStr,i+3,1))\n Else\n c = 0\n End If\n rarr(i\\3) = carr(a\\4) &amp; carr((a And 3) * 16 + b\\16) &amp; carr((b And 15) * 4 + c\\64) &amp; carr(c And 63)\n Next\n\n i = UBound(rarr)\n If n Mod 3 = 0 Then\n rarr(i) = Left(rarr(i),2) &amp; \"==\"\n ElseIf n Mod 3 = 1 Then\n rarr(i) = Left(rarr(i),3) &amp; \"=\"\n End If\n\n fBase64Encode = Join(rarr,\"\")\n\nEnd Function\n'-------------------------------------------------------------------------------\n\nfunction fBase64Decode(str)\n\n fBase64Decode = \"\"\n\n table = fGenerateBase64Table\n\n bits = 0\n\n for x = 1 to len(str) step 1\n c = table(1+asc(mid(str,x,1)))\n if (c &lt;&gt; -1) then\n if (bits = 0) then\n outword = c*4\n bits = 6\n elseif (bits = 2) then\n outword = c+outword\n strBase64 = strBase64 &amp; chr(clng(\"&amp;H\" &amp; hex(outword mod 256)))\n bits = 0\n elseif (bits = 4) then\n outword = outword + int(c/4)\n strBase64 = strBase64 &amp; chr(clng(\"&amp;H\" &amp; hex(outword mod 256)))\n outword = c*64\n bits = 2\n else\n outword = outword + int(c/16)\n strBase64 = strBase64 &amp; chr(clng(\"&amp;H\" &amp; hex(outword mod 256)))\n outword = c*16\n bits = 4\n end if\n end if\n next\n\n fBase64Decode = strBase64\n\nend function\n'---------------------------------------------------\n\nfunction fGenerateBase64Table()\n\n r64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n\n 'set up decode table\n dim table(256)\n for x = 1 to 256 step 1\n table(x) = -1\n next\n for x = 1 to 64 step 1\n table(1+asc(mid(r64,x,1))) = x - 1\n next\n\n fGenerateBase64Table = table\n\nend function\n'---------------------------------------------------\n\nfunction fSelectFile()\n\n fSelectFile = \"\"\n strMSHTA = \"mshta.exe \"\"about:&lt;input type=file id=FILE&gt;\" &amp; _\n \"&lt;\"&amp;\"script&gt;FILE.click();new ActiveXObject('Scripting.FileSystemObject')\" &amp; _\n \".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);&lt;\"&amp;\"/script&gt;\"\"\"\n\n Set wshShell = CreateObject( \"WScript.Shell\" )\n Set objExec = wshShell.Exec( strMSHTA )\n fSelectFile = objExec.StdOut.ReadLine( )\n Set objExec = Nothing\n Set wshShell = Nothing\n\nend function\n\n'-------------------------------------------------------------------------\n\nsub getBase64()\n\n 'this can be BMP, PNG, ICO\n REM sImgFile = \"favicon.ico\"\n sImgFile = fSelectFile()\n\n if sImgFile = \"\" then exit sub\n\n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n Set f = fso.GetFile(sImgFile)\n filesize = f.size\n set f = fso.opentextfile(sImgFile,1,0) 'open as ascii\n strBinFile = f.read(filesize)\n f.close\n set fso = nothing\n\n strPNGFile = fBase64Encode(strBinFile)\n s = s &amp; \"Base64 encoding of \"&amp;sImgFile&amp;\"&lt;br&gt;&lt;br&gt;\" &amp; strPNGFile &amp; \"&lt;br&gt;&lt;br&gt;\"\n s = s &amp; \"&lt;img src=\"\"data:image/bmp;base64,\" &amp; strPNGFile &amp; \"\"\"&gt;&lt;br&gt;&lt;br&gt;\" &amp; vbcrlf\n\n imgbase64.innerhtml = s\n\nend sub\n'-------------------------------------------------------------------------\n\nsub setup()\n\n 'https://stackoverflow.com/favicon.ico in base64 \n base64Icon=\"AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv8AAAAAAAAAAAAAAAAAAAAAAAAAAKmjnv8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACpo57/AAAAAAAAAAAAAAAAAAAAAAAAAACpo57/AAAAAAlw8v8JcPL/CXDy/wlw8v8JcPL/CXDy/wlw8v8AAAAAqaOe/wAAAAAAAAAAAAAAAAAAAAAAAAAAqaOe/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlw8hMJcPI2AAAAAKmjnv8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACXDyLwlw8l0JcPKJCXDytglw8uIJcPLvCXDyvQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlw8sIJcPKlCXDydwlw8kkJcPIdCXDyEwlw8nEJcPIvAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJcPI9CXDypQlw8u8JcPKgCXDyLwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACXDyDwlw8nEJcPLWCXDy0wlw8msJcPIPCXDyPQlw8uIJcPInAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlw8iMJcPKgCXDyOgAAAAAAAAAACXDydwlw8ugJcPJGCXDyUQlw8oIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJcPITCXDytglw8sIJcPIdCXDyGAlw8ugJcPI2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJcPI6CXDy4glw8okJcPIDAAAAAAlw8rYJcPJ+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACXDyZAlw8kkAAAAAAAAAAAlw8msJcPLICXDyAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlw8icJcPLoCXDyIwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJcPLCCXDyZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACXDyHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AADABwAA3/cAANAXAADflwAA8B8AAPAPAAD+DwAA8AcAAPGDAAD+AwAA/CcAAPzHAAD/jwAA/58AAP+/AAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAKmjngCpo54AqaOeAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCpo54AqaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po54A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AKmjngCpo57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjnv+po57/qaOe/6mjngD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AqaOeAKmjnv+po57/JID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0AKmjnv+po57/JID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wCpo54AqaOe/6mjnv8kgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAqaOe/6mjnv8kgPQAJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AKmjngCpo57/qaOe/ySA9AAkgPQAJID0/ySA9P8kgPT/JID0/ySA9P8kgPT/JID0/ySA9P8kgPT/JID0/ySA9P8kgPT/JID0ACSA9ACpo57/qaOe/ySA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8AqaOeAKmjnv+po57/JID0ACSA9AAkgPT/JID0/ySA9P8kgPT/JID0/ySA9P8kgPT/JID0/ySA9P8kgPT/JID0/ySA9P8kgPQAJID0AKmjnv+po57/JID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wCpo54AqaOe/6mjnv8kgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAqaOe/6mjnv8kgPQAJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AKmjngCpo57/qaOe/ySA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9B4kgPRRJID0gSSA9LQkgPTjJID0EiSA9ACpo57/qaOe/ySA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8AqaOeAKmjngCpo54AJID0ACSA9AAkgPQAJID0AiSA9CYkgPRXJID0iSSA9LokgPTtJID0/ySA9P8kgPT/JID0/ySA9P8kgPRKJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAkgPQAJID0ACSA9LgkgPTxJID0/ySA9P8kgPT/JID0/ySA9P8kgPT/JID0+SSA9M0kgPSaJID0aiSA9CQkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////ACSA9AAkgPQAJID0vSSA9P8kgPT/JID09CSA9MUkgPSUJID0YiSA9DEkgPQFJID0ACSA9DQkgPSjJID05iSA9A0kgPQAJID0ACSA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AJID0ACSA9AAkgPRKJID0WySA9CkkgPQDJID0ACSA9AAkgPQAJID0BSSA9FgkgPTHJID0/ySA9P8kgPT/JID0eCSA9AAkgPQAJID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0FSSA9HwkgPTkJID0/ySA9P8kgPT/JID02SSA9GwkgPQ9JID0LCSA9AAkgPQAJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0MiSA9J8kgPT4JID0/ySA9P8kgPT+JID0tySA9EkkgPQCJID0YiSA9PckgPTjJID0HCSA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AJID0ACSA9AAkgPQAJID0KiSA9MIkgPT/JID0/ySA9P8kgPTyJID0lCSA9CYkgPQAJID0CCSA9J8kgPT/JID0/ySA9OkkgPRGJID0IySA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAkgPQAJID0ACSA9AAkgPQPJID07iSA9P8kgPTcJID0cCSA9A8kgPQAJID0ACSA9CQkgPTPJID0/ySA9P8kgPTDJID0HCSA9K4kgPTzJID0ZiSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////ACSA9AAkgPQAJID0ACSA9AAkgPRaJID0TCSA9AIkgPQAJID0ACSA9AAkgPRQJID07ySA9P8kgPT+JID0jiSA9AUkgPR+JID0/ySA9P8kgPSOJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQEJID0iCSA9P4kgPT/JID08SSA9FQkgPQAJID0TSSA9P4kgPT/JID0uySA9AMkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0GCSA9MAkgPT/JID0/ySA9NMkgPQmJID0ACSA9CgkgPTwJID0/ySA9N4kgPQUJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9B8kgPTnJID0/ySA9P8kgPSiJID0CiSA9AAkgPQPJID02CSA9P8kgPT1JID0LiSA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9JYkgPT4JID0ZySA9AAkgPQAJID0AiSA9LQkgPT/JID0/iSA9FYkgPQAJID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0AySA9CokgPQAJID0ACSA9AAkgPSCJID0/ySA9P8kgPSIJID0ACSA9AAkgPQAJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0UySA9P4kgPT/JID0tySA9AMkgPQAJID0ACSA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9A8kgPTvJID0/ySA9NskgPQQJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9DQkgPTIJID0LCSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0ACSA9AAkgPQAJID0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAD/8AAA//P//P/z//z/8wAM//MADP/z//z/8/4E//+AB///AAf//wBD//8OA///+AH//+AA//+AQH//gYA//8cAP//8CD//+BB///Ag///4wf//+cP///+D////B////4///////////////////////\" \n\n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n if not fso.fileexists(\"favicon.ico\") then\n strBin = fBase64Decode(base64Icon)\n set outfile = fso.createtextfile(\"favicon.ico\")\n outfile.write strBin\n outfile.close\n\n document.title = \"Need to refresh to see the new icon\"\n\n end if \n set fso = nothing\n\nend sub \n\n&lt;/script&gt;\n\n&lt;style type=\"text/css\"&gt;\n\n body {font-family:\"CONSOLAS\";font-size:\"10pt\";}\n input {font-family:\"CONSOLAS\";font-size:\"8pt\";}\n\n&lt;/style&gt;\n\n&lt;body onLoad=setup()&gt;\n\n&lt;input type=button value=\"Encode an image file...\" \ndata-tooltip title=\"Choose a PNG, BMP, ICO file to encode in base64\" \nonclick=getBase64&gt;\n\n&lt;br&gt;&lt;br&gt;\n\n&lt;div id=imgbase64 style=\"word-wrap: break-word;\"&gt;&lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p></p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/175994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20848/" ]
I have written an HTML Application (hta file) and am wondering if there is a way to embed an icon file into the hta file itself. I have seen html emails that include embedded graphic files, is there any way to do this with html applications and icons? HTA files have an HTA:APPLICATION tag that allows you to specify an icon, but I want to have only a single file for download. I don't want to have an external icon file. Is this possible? More info on hta files here: [HTA files](http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx).
I've found an hack to set the icon. Prepare an icon file *icon.ico* and an hta file *source.hta* with the following contents: ``` <HTML> <HEAD> <SCRIPT> path = document.URL; document.write( '<HTA:APPLICATION ID="oHTA" APPLICATIONNAME="myApp" ICON="'+path+'">'); </SCRIPT> </HEAD> <BODY SCROLL="no"> Hello, World! </BODY> </HTML> ``` Open a command prompt and type: ``` copy /b icon.ico+source.hta iconapp.hta ``` That will concatenate the icon and hta into a single file. In my test case Internet explorer skipped over the icon data and display the HTML correctly. The path of the icon is then set to that of the .hta file itself using javascript and the icon is loaded. I have tested this on Windows XP SP3, Internet explorer 8.
176,051
<p>I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.</p> <pre><code>package sotring; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import com.sun.org.apache.bcel.internal.generic.INEG; public class storeing { public static void storeMail(Message[] mail){ try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser")); out.writeObject(mail); out.flush(); out.close(); } catch (IOException e) { } } public static Message[] getStoredMails(){ try { ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser")); Message[] array = (Message[]) in.readObject() ; for (int i=0; i&lt; array.length;i++) System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent()); System.out.println("Size: "+array.length); //return array; in.close(); return array; } catch(IOException ex) { ex.printStackTrace(); return null; } catch(ClassNotFoundException ex) { ex.printStackTrace(); return null; } } public static void main(String[] args) { User user1 = new User("User1", "geheim"); User user2 = new User("User2", "geheim"); Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar"); Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo"); Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) "); Message [] mails = {email1, email2, email3}; storeMail(mails); Message[] restored = getStoredMails();; } } </code></pre> <p>Here are the user and message class</p> <pre><code>public class Message implements Serializable{ static final long serialVersionUID = -1L; private String receiver; //Empfänger private String sender; //Absender private String Betreff; private String content; private String timestamp; private String getDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } Message (String receiver, String sender, String Betreff, String content) { this.Betreff= Betreff; this.receiver = receiver; this.sender = sender; this.content = content; this.timestamp = getDateTime(); } Message() { // Just for loaded msg } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getBetreff() { return Betreff; } public void setBetreff(String betreff) { Betreff = betreff; } public String getContent() { return content; } public String getTime() { return timestamp; } public void setContent(String content) { this.content = content; } } public class User implements Serializable{ static final long serialVersionUID = -1L; private String username; //unique Username private String ipadress; //changes everytime private String password; //Password private int unreadMsg; //Unread Messages private static int usercount; private boolean online; public String getName(){ return username; } public boolean Status() { return online; } public void setOnline() { this.online = true; } public void setOffline() { this.online = false; } User(String username,String password){ if (true){ this.username = username; this.password = password; usercount++; } else System.out.print("Username not availiable"); } public void changePassword(String newpassword){ password = newpassword; } public void setIP(String newip){ ipadress = newip; } public String getIP(){ if (ipadress.length() &gt;= 7){ return ipadress; } else return "ip address not set."; } public int getUnreadMsg() { return unreadMsg; } } </code></pre> <p>Here is the exception:</p> <p><code>exception in thread "main" java.lang.Error: Unresolved compilation problem: This method must return a result of type Message[] at sotring.storeing.getStoredMails(storeing.java:22) at sotring.storeing.main(storeing.java:57)</code></p> <p>THANK YOU FOR YOUR HELP!!!!!!!!!!!</p>
[ { "answer_id": 176063, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": true, "text": "<p>If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.</p>\n\n<p>Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.</p>\n" }, { "answer_id": 176068, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "<p>The catch clauses need to return something.</p>\n\n<pre><code>public static Message[] getStoredMails(){\n\n try\n {\n\n ObjectInputStream in = new ObjectInputStream(new FileInputStream(\"mail.ser\"));\n Message[] array = (Message[]) in.readObject() ;\n System.out.println(\"Size: \"+array.length); //return array;\n in.close();\n return array; \n }\n catch(IOException ex)\n {\n ex.printStackTrace();\n }\n catch(ClassNotFoundException ex)\n {\n ex.printStackTrace();\n } \n return null; //fix \n}\n</code></pre>\n" }, { "answer_id": 176085, "author": "wellenreiter", "author_id": 25128, "author_profile": "https://Stackoverflow.com/users/25128", "pm_score": 0, "selected": false, "text": "<p>I modified the source. I added \"return null\" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.</p>\n" }, { "answer_id": 176099, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 2, "selected": false, "text": "<p>On a different note, have you considered a third-party serializer library?</p>\n\n<p>I'm using <a href=\"http://simple.sourceforge.net/\" rel=\"nofollow noreferrer\">Simple</a> right now for a project, and it seems to do stuff just fine with very little effort.</p>\n" }, { "answer_id": 176157, "author": "Declan Shanaghy", "author_id": 21297, "author_profile": "https://Stackoverflow.com/users/21297", "pm_score": 1, "selected": false, "text": "<p>in the exception handling blocks of the getStoredMails method you do not return anything.</p>\n\n<p>Suggested modification:</p>\n\n<pre><code>public static Message[] getStoredMails(){\n\n try\n {\n\n ObjectInputStream in = new ObjectInputStream(new FileInputStream(\"mail.ser\"));\n Message[] array = (Message[]) in.readObject() ;\n System.out.println(\"Size: \"+array.length); //return array;\n in.close();\n return array; \n }\n catch(IOException ex)\n {\n ex.printStackTrace();\n }\n catch(ClassNotFoundException ex)\n {\n ex.printStackTrace();\n } \n\n return null; \n }\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25128/" ]
I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is. ``` package sotring; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import com.sun.org.apache.bcel.internal.generic.INEG; public class storeing { public static void storeMail(Message[] mail){ try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser")); out.writeObject(mail); out.flush(); out.close(); } catch (IOException e) { } } public static Message[] getStoredMails(){ try { ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser")); Message[] array = (Message[]) in.readObject() ; for (int i=0; i< array.length;i++) System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent()); System.out.println("Size: "+array.length); //return array; in.close(); return array; } catch(IOException ex) { ex.printStackTrace(); return null; } catch(ClassNotFoundException ex) { ex.printStackTrace(); return null; } } public static void main(String[] args) { User user1 = new User("User1", "geheim"); User user2 = new User("User2", "geheim"); Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar"); Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo"); Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) "); Message [] mails = {email1, email2, email3}; storeMail(mails); Message[] restored = getStoredMails();; } } ``` Here are the user and message class ``` public class Message implements Serializable{ static final long serialVersionUID = -1L; private String receiver; //Empfänger private String sender; //Absender private String Betreff; private String content; private String timestamp; private String getDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } Message (String receiver, String sender, String Betreff, String content) { this.Betreff= Betreff; this.receiver = receiver; this.sender = sender; this.content = content; this.timestamp = getDateTime(); } Message() { // Just for loaded msg } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getBetreff() { return Betreff; } public void setBetreff(String betreff) { Betreff = betreff; } public String getContent() { return content; } public String getTime() { return timestamp; } public void setContent(String content) { this.content = content; } } public class User implements Serializable{ static final long serialVersionUID = -1L; private String username; //unique Username private String ipadress; //changes everytime private String password; //Password private int unreadMsg; //Unread Messages private static int usercount; private boolean online; public String getName(){ return username; } public boolean Status() { return online; } public void setOnline() { this.online = true; } public void setOffline() { this.online = false; } User(String username,String password){ if (true){ this.username = username; this.password = password; usercount++; } else System.out.print("Username not availiable"); } public void changePassword(String newpassword){ password = newpassword; } public void setIP(String newip){ ipadress = newip; } public String getIP(){ if (ipadress.length() >= 7){ return ipadress; } else return "ip address not set."; } public int getUnreadMsg() { return unreadMsg; } } ``` Here is the exception: `exception in thread "main" java.lang.Error: Unresolved compilation problem: This method must return a result of type Message[] at sotring.storeing.getStoredMails(storeing.java:22) at sotring.storeing.main(storeing.java:57)` THANK YOU FOR YOUR HELP!!!!!!!!!!!
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error. Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
176,062
<p>I have the following unmanaged C++ code:</p> <pre><code>MessageBox( NULL, strMessage, "Cool Product", MB_RETRYCANCEL | MB_ICONEXCLAMATION); </code></pre> <p>I want to disable the RETRY button for 10 seconds (for example), then enable it.</p> <p>How can I do this?</p>
[ { "answer_id": 176082, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "<p>With the standard MessageBox call, you can't. You'd need to implement your own MessageBox in order to do this.</p>\n" }, { "answer_id": 176086, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>I don't believe this is possible with the standard message box call.</p>\n\n<p>You would probably be better off writing your own message box that includes this functionality.</p>\n\n<p>(Or, you could write a separate thread that continually watches the screen waiting for that message box to appear, disable the retry button, wait 10 seconds and reenable it. Not fun. Seriously, do it the other way.)</p>\n" }, { "answer_id": 176091, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": true, "text": "<p>Like <a href=\"https://stackoverflow.com/questions/176062/how-do-i-disable-and-then-enable-the-retry-button-in-a-messagebox-c#176082\">@ffpf</a> says, you need to make your own dialog to do this, using MFC, ATL, raw Win32, etc.</p>\n\n<p>Then create a timer that would enable and disable the button.</p>\n" }, { "answer_id": 176124, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 0, "selected": false, "text": "<p>Since Vista you can use taskdialog -- a more sophisticated dialog than a simple message box. More info and links <a href=\"http://shellrevealed.com/blogs/shellblog/archive/2006/09/19/So-long-MessageBox-and-thanks-for-all-the-memories.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 176149, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 1, "selected": false, "text": "<p>You cannot directly manipulate the MessageBox controls, but you can use a hack. Install a WH<code>_</code>CBT hook just before displaying the dialog and handle the HCBT<code>_</code>ACTIVATE event. This will give you the HWND of the message box, so that you can do whatever you want with it (subclass it, manage its buttons and set a timer).</p>\n\n<p>You can find a <a href=\"http://www.catch22.net/tuts/msgbox\" rel=\"nofollow noreferrer\">Custom MessageBox</a> tutorial with demo code in James Brown's site.</p>\n" }, { "answer_id": 176227, "author": "Dan Cristoloveanu", "author_id": 24873, "author_profile": "https://Stackoverflow.com/users/24873", "pm_score": 0, "selected": false, "text": "<p>I agree with efotinis, it's not impossible, once you have the HWND you can do whatever you want with it. It is just a matter of \"do you really need the hacks or are you better off with just creating your own message box dialog\"?</p>\n\n<p>Another not so nice way of finding the HWND (which would obviously give you access to eveything in the message box) would be to start a thread and ciclically poll for the message box handle by using EnumChildWindows. But I personally would prefer the WH_CBT hook also.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
I have the following unmanaged C++ code: ``` MessageBox( NULL, strMessage, "Cool Product", MB_RETRYCANCEL | MB_ICONEXCLAMATION); ``` I want to disable the RETRY button for 10 seconds (for example), then enable it. How can I do this?
Like [@ffpf](https://stackoverflow.com/questions/176062/how-do-i-disable-and-then-enable-the-retry-button-in-a-messagebox-c#176082) says, you need to make your own dialog to do this, using MFC, ATL, raw Win32, etc. Then create a timer that would enable and disable the button.
176,084
<p>When writing the string "¿" out using</p> <pre><code>System.out.println(new String("¿".getBytes("UTF-8"))); </code></pre> <p>¿ is written instead of just ¿.</p> <p>WHY? And how do we fix it?</p>
[ { "answer_id": 176089, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>Sounds like the system console isn't in UTF-8</p>\n" }, { "answer_id": 176105, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 2, "selected": false, "text": "<p>You need to specify the Charset in the String constructor (see the <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String%28byte[],%20java.nio.charset.Charset%29\" rel=\"nofollow noreferrer\">API docs</a>).</p>\n" }, { "answer_id": 176154, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 4, "selected": true, "text": "<p>You don't have to use UTF-16 to solve this:</p>\n\n<pre><code>new String(\"¿\".getBytes(\"UTF-8\"), \"UTF-8\");\n</code></pre>\n\n<p>works just fine. As long as the encoding given to the <code>getBytes()</code> method is the same as the encoding you pass to the String constructor, you should be fine!</p>\n" }, { "answer_id": 176162, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>System.out.println(new String(\"¿\".getBytes(\"UTF-8\"), \"UTF-8\"));\n</code></pre>\n\n<p>You need to specify the encoding both when converting the string to bytes and when converting the bytes back to a string. </p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9518/" ]
When writing the string "¿" out using ``` System.out.println(new String("¿".getBytes("UTF-8"))); ``` ¿ is written instead of just ¿. WHY? And how do we fix it?
You don't have to use UTF-16 to solve this: ``` new String("¿".getBytes("UTF-8"), "UTF-8"); ``` works just fine. As long as the encoding given to the `getBytes()` method is the same as the encoding you pass to the String constructor, you should be fine!
176,088
<p>Is it possible to open an HTML page using navigateToURL and specifying a named frame in your HTML document? For instance, if you have an iframe on the page called "Steven", can you call</p> <pre><code>navigateToURL("someURL","Steven"); </code></pre> <p>instead of something like</p> <pre><code>navigateToURL("someURL","_self"); </code></pre> <p>I have tried this and it opens the URL in a new window.</p>
[ { "answer_id": 176108, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>I'm not sure, but you can use JavaScript:</p>\n\n<pre><code>navigateToURL(\"javascript:loadFrame(someURL)\");\n</code></pre>\n\n<p>Then in your HTML page:</p>\n\n<pre><code>function loadFrame(url) {\n documents.frames[1].src=url\n}\n</code></pre>\n" }, { "answer_id": 177138, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 2, "selected": true, "text": "<p>Did you test this on local files saved to your hard drive? If so, then there are some security restrictions that you may be running in to. See the security note <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/package.html#navigateToURL()\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>But if you're testing this with files on a web server, and there are no cross-domain issues, then <code>navigateToURL()</code> should work exactly the way you're using it - if your iframe's name is \"Steven\" then the content should be opening in that iframe.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25280/" ]
Is it possible to open an HTML page using navigateToURL and specifying a named frame in your HTML document? For instance, if you have an iframe on the page called "Steven", can you call ``` navigateToURL("someURL","Steven"); ``` instead of something like ``` navigateToURL("someURL","_self"); ``` I have tried this and it opens the URL in a new window.
Did you test this on local files saved to your hard drive? If so, then there are some security restrictions that you may be running in to. See the security note [here](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/package.html#navigateToURL()). But if you're testing this with files on a web server, and there are no cross-domain issues, then `navigateToURL()` should work exactly the way you're using it - if your iframe's name is "Steven" then the content should be opening in that iframe.
176,093
<p>Is there a way to use a Graphics object's 'setClip()' method to clip using a Line-ish shape? Right now I'm trying to use a Polygon shape but I'm having problems simulating the "width" of the line. I basically draw the line, and when I reach the end, I redraw it but this time subtract the line width from y-coordinate:</p> <pre><code>Polygon poly = new Polygon(); for(int i = 0; i &lt; points.length; i++) poly.addPoint(points.[i].x, points.[i].y); // Retrace line to add 'width' for(int i = points.length - 1; i &gt;=0; i--) poly.addPoint(points[i].x, points[i].y - lineHeight); </code></pre> <p>It almost works but the width of the line varies based upon its slope. </p> <p>I can't use the BrushStroke and drawLine() methods because the line can change color once it passes some arbitrary reference line. Is there some implementation of Shape that I overlooked, or an easy one I can create, that will let me do this more easily?</p>
[ { "answer_id": 176169, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 1, "selected": false, "text": "<p>If there is a better way, I've never run across it. The best I can think of is to use some trigonometry to make the line width more consistent.</p>\n" }, { "answer_id": 176399, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 1, "selected": false, "text": "<p>OK, I managed to come up with a pretty nice solution without using the setClip() method. It involves drawing my background to an intermediate Graphics2D object, using setComposite() to specify how I want to mask the pixels, THEN drawing my line using drawLine() on top. Once I have this line, I draw it back on top of my original Graphics object via drawImage. Here's an example:</p>\n\n<pre><code>BufferedImage mask = g2d.getDeviceConfiguration().createCompatibleImage(width, height, BufferedImage.TRANSLUCENT);\nGraphics2D maskGraphics = (Graphics2D) mask.getGraphics();\nmaskGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n\nmaskGraphics.setStroke(new BasicStroke(lineWidth));\nmaskGraphics.setPaint(Color.BLACK);\n\n// Draw line onto mask surface first.\nPoint prev = line.get(0);\nfor(int i = 1; i &lt; line.size(); i++)\n{\n Point current = line.get(i);\n maskGraphics.drawLine(prev.x, prev.y, current.x, current.y);\n prev = current;\n}\n\n// AlphaComposite.SrcIn: \"If pixels in the source and the destination overlap, only the source pixels\n// in the overlapping area are rendered.\"\nmaskGraphics.setComposite(AlphaComposite.SrcIn);\n\nmaskGraphics.setPaint(top);\nmaskGraphics.fillRect(0, 0, width, referenceY);\n\nmaskGraphics.setPaint(bottom);\nmaskGraphics.fillRect(0, referenceY, width, height);\n\ng2d.drawImage(mask, null, 0, 0);\nmaskGraphics.dispose();\n</code></pre>\n" }, { "answer_id": 4995233, "author": "tofarr", "author_id": 470062, "author_profile": "https://Stackoverflow.com/users/470062", "pm_score": 0, "selected": false, "text": "<p>Maybe you could use a Stroke.createClippedShape to do this? (May need to use an Area to add subtract the stroked shape from/to your original shape depending on what exactly you are trying to do.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471/" ]
Is there a way to use a Graphics object's 'setClip()' method to clip using a Line-ish shape? Right now I'm trying to use a Polygon shape but I'm having problems simulating the "width" of the line. I basically draw the line, and when I reach the end, I redraw it but this time subtract the line width from y-coordinate: ``` Polygon poly = new Polygon(); for(int i = 0; i < points.length; i++) poly.addPoint(points.[i].x, points.[i].y); // Retrace line to add 'width' for(int i = points.length - 1; i >=0; i--) poly.addPoint(points[i].x, points[i].y - lineHeight); ``` It almost works but the width of the line varies based upon its slope. I can't use the BrushStroke and drawLine() methods because the line can change color once it passes some arbitrary reference line. Is there some implementation of Shape that I overlooked, or an easy one I can create, that will let me do this more easily?
If there is a better way, I've never run across it. The best I can think of is to use some trigonometry to make the line width more consistent.
176,106
<p>I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction. </p> <p>I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible?</p> <p>[C# and .net 3.5 by the way]</p> <p><a href="https://www.usps.com/send/official-abbreviations.htm" rel="noreferrer">List of USPS State Abbreviations</a></p>
[ { "answer_id": 176127, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": false, "text": "<p>Here's a regex. Enjoy!</p>\n\n<pre><code>^(?-i:A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$\n</code></pre>\n" }, { "answer_id": 176128, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 4, "selected": false, "text": "<p>I'd populate a hashtable with valid abbreviations and then check it with the input for validation. It's much cleaner and probably faster if you have more than one check per dictionary build.</p>\n" }, { "answer_id": 176146, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>A HashSet&lt;string> is the cleanest way I can think of using the built-in types in .NET 3.5. (You could easily make it case-insensitive as well, or change it into a Dictionary&lt;string, string&gt; where the value is the full name. That would also be the most appropriate solution for .NET 2.0/3.0.)</p>\n\n<p>As for speed - do you really believe this will be a bottleneck in your code? A HashSet is likely to perform \"pretty well\" (many millions of lookups a second). I'm sure alternatives would be even faster - but dirtier. I'd stick to the simplest thing that works until you have reason to believe it'll be a bottleneck.</p>\n\n<p>(Edited to explicitly mention Dictionary&lt;,>.)</p>\n" }, { "answer_id": 176291, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 6, "selected": true, "text": "<p>I like something like this:</p>\n\n<pre><code>private static String states = \"|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|\";\n\npublic static bool isStateAbbreviation (String state)\n{\n return state.Length == 2 &amp;&amp; states.IndexOf( state ) &gt; 0;\n}\n</code></pre>\n\n<p>This method has the advantage of using an optimized system routine that is probably using a single machine instruction to do the search. If I was dealing with non-fixed length words, then I'd check for \"|\" + state + \"|\" to ensure that I hadn't hit a substring instead of full match. That would take a wee bit longer, due to the string concatenation, but it would still match in a fixed amount of time. If you want to validate lowercase abbreviations as well as uppercase, then either check for state.UpperCase(), or double the 'states' string to include the lowercase variants.</p>\n\n<p>I'll guarantee that this will beat the Regex or Hashtable lookups every time, no matter how many runs you make, and it will have the least memory usage.</p>\n" }, { "answer_id": 69489334, "author": "kbrannen", "author_id": 908522, "author_profile": "https://Stackoverflow.com/users/908522", "pm_score": 0, "selected": false, "text": "<p>I know this is really old, but I came to see if there was a better solution than I came up with back in the 80's. In C it'd be something like (untested code):</p>\n<pre class=\"lang-c prettyprint-override\"><code>/* assumes 2 letter code is in upper case, returns 1 if valid or 0 if not */\nint validate_state( const char *state )\n{\n if (state[0] == ' ' || state[1] == ' ' || state[2] != '\\0') return 0;\n return strstr(&quot;WVALAKSCARIDE CTNVTX NHINMNCOKY MSD MIA MOR WIL GAZ FL ME MD MA MT NE NJ NY ND OH PA UT WA WY&quot;, state) ? 1 : 0;\n}\n</code></pre>\n<p>That could be written like this in C#:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/* assumes 2 letter code is in upper case */\nbool ValidateState(string state)\n{\n const string ValidStatesMerged = &quot;WVALAKSCARIDE CTNVTX NHINMNCOKY MSD MIA MOR WIL GAZ FL ME MD MA MT NE NJ NY ND OH PA UT WA WY&quot;;\n\n if (state == null)\n throw new ArgumentNullException(nameof(state));\n if (state.Length != 2 || state[0] == ' ' || state[1] == ' ')\n return false;\n return ValidStatesMerged.IndexOf(state) &gt;= 0;\n}\n</code></pre>\n<p>As long as the <code>state</code> string is in all caps, this uses no regex but only simple string functions. The trick is to make sure there are no invalid combos in there, but that's easy enough if you start with the list and re-arrange them so the end of one is the beginning of the next, like <code>&quot;WV&quot;</code> then <code>&quot;VA&quot;</code>, then remove the dupe letter so you end up with <code>&quot;WVA&quot;</code> ... continue until they're all in and hopefully the shortest string you can make.</p>\n<p>It's not hard to adapt that to other languages; I need it in a bash script and will use a Perl command to do that with the above &quot;search string&quot;.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/506/" ]
I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction. I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible? [C# and .net 3.5 by the way] [List of USPS State Abbreviations](https://www.usps.com/send/official-abbreviations.htm)
I like something like this: ``` private static String states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|"; public static bool isStateAbbreviation (String state) { return state.Length == 2 && states.IndexOf( state ) > 0; } ``` This method has the advantage of using an optimized system routine that is probably using a single machine instruction to do the search. If I was dealing with non-fixed length words, then I'd check for "|" + state + "|" to ensure that I hadn't hit a substring instead of full match. That would take a wee bit longer, due to the string concatenation, but it would still match in a fixed amount of time. If you want to validate lowercase abbreviations as well as uppercase, then either check for state.UpperCase(), or double the 'states' string to include the lowercase variants. I'll guarantee that this will beat the Regex or Hashtable lookups every time, no matter how many runs you make, and it will have the least memory usage.
176,137
<p>Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? I'm currently looking at Geotools but unfortunately the solution is not obvious.</p>
[ { "answer_id": 176925, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 5, "selected": true, "text": "<p>I was able to use Geotools 2.4 to get something that works, based on some <a href=\"http://svn.geotools.org/trunk/demo/referencing/src/main/java/org/geotools/demo/referencing/CTSTutorial.java\" rel=\"noreferrer\">example code</a>.</p>\n\n<pre><code>double utmZoneCenterLongitude = ... // Center lon of zone, example: zone 10 = -123\nint zoneNumber = ... // zone number, example: 10\ndouble latitude, longitude = ... // lat, lon in degrees\n\nMathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null);\nReferencingFactoryContainer factories = new ReferencingFactoryContainer(null);\n\nGeographicCRS geoCRS = org.geotools.referencing.crs.DefaultGeographicCRS.WGS84;\nCartesianCS cartCS = org.geotools.referencing.cs.DefaultCartesianCS.GENERIC_2D;\n\nParameterValueGroup parameters = mtFactory.getDefaultParameters(\"Transverse_Mercator\");\nparameters.parameter(\"central_meridian\").setValue(utmZoneCenterLongitude);\nparameters.parameter(\"latitude_of_origin\").setValue(0.0);\nparameters.parameter(\"scale_factor\").setValue(0.9996);\nparameters.parameter(\"false_easting\").setValue(500000.0);\nparameters.parameter(\"false_northing\").setValue(0.0);\n\nMap properties = Collections.singletonMap(\"name\", \"WGS 84 / UTM Zone \" + zoneNumber);\nProjectedCRS projCRS = factories.createProjectedCRS(properties, geoCRS, null, parameters, cartCS);\n\nMathTransform transform = CRS.findMathTransform(geoCRS, projCRS);\n\ndouble[] dest = new double[2];\ntransform.transform(new double[] {longitude, latitude}, 0, dest, 0, 1);\n\nint easting = (int)Math.round(dest[0]);\nint northing = (int)Math.round(dest[1]);\n</code></pre>\n" }, { "answer_id": 28224544, "author": "user2548538", "author_id": 2548538, "author_profile": "https://Stackoverflow.com/users/2548538", "pm_score": 6, "selected": false, "text": "<p>No Library, No Nothing. Copy This!</p>\n\n<p>Using These Two Classes , You can Convert Degree(latitude/longitude) to UTM and Vice Versa!</p>\n\n<pre><code>private class Deg2UTM\n{\n double Easting;\n double Northing;\n int Zone;\n char Letter;\n private Deg2UTM(double Lat,double Lon)\n {\n Zone= (int) Math.floor(Lon/6+31);\n if (Lat&lt;-72) \n Letter='C';\n else if (Lat&lt;-64) \n Letter='D';\n else if (Lat&lt;-56)\n Letter='E';\n else if (Lat&lt;-48)\n Letter='F';\n else if (Lat&lt;-40)\n Letter='G';\n else if (Lat&lt;-32)\n Letter='H';\n else if (Lat&lt;-24)\n Letter='J';\n else if (Lat&lt;-16)\n Letter='K';\n else if (Lat&lt;-8) \n Letter='L';\n else if (Lat&lt;0)\n Letter='M';\n else if (Lat&lt;8) \n Letter='N';\n else if (Lat&lt;16) \n Letter='P';\n else if (Lat&lt;24) \n Letter='Q';\n else if (Lat&lt;32) \n Letter='R';\n else if (Lat&lt;40) \n Letter='S';\n else if (Lat&lt;48) \n Letter='T';\n else if (Lat&lt;56) \n Letter='U';\n else if (Lat&lt;64) \n Letter='V';\n else if (Lat&lt;72) \n Letter='W';\n else\n Letter='X';\n Easting=0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180))/(1-Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180)))*0.9996*6399593.62/Math.pow((1+Math.pow(0.0820944379, 2)*Math.pow(Math.cos(Lat*Math.PI/180), 2)), 0.5)*(1+ Math.pow(0.0820944379,2)/2*Math.pow((0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180))/(1-Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180)))),2)*Math.pow(Math.cos(Lat*Math.PI/180),2)/3)+500000;\n Easting=Math.round(Easting*100)*0.01;\n Northing = (Math.atan(Math.tan(Lat*Math.PI/180)/Math.cos((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))-Lat*Math.PI/180)*0.9996*6399593.625/Math.sqrt(1+0.006739496742*Math.pow(Math.cos(Lat*Math.PI/180),2))*(1+0.006739496742/2*Math.pow(0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))/(1-Math.cos(Lat*Math.PI/180)*Math.sin((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))),2)*Math.pow(Math.cos(Lat*Math.PI/180),2))+0.9996*6399593.625*(Lat*Math.PI/180-0.005054622556*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+4.258201531e-05*(3*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2))/4-1.674057895e-07*(5*(3*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2))/4+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2)*Math.pow(Math.cos(Lat*Math.PI/180),2))/3);\n if (Letter&lt;'M')\n Northing = Northing + 10000000;\n Northing=Math.round(Northing*100)*0.01;\n }\n}\n\nprivate class UTM2Deg\n{\n double latitude;\n double longitude;\n private UTM2Deg(String UTM)\n {\n String[] parts=UTM.split(\" \");\n int Zone=Integer.parseInt(parts[0]);\n char Letter=parts[1].toUpperCase(Locale.ENGLISH).charAt(0);\n double Easting=Double.parseDouble(parts[2]);\n double Northing=Double.parseDouble(parts[3]); \n double Hem;\n if (Letter&gt;'M')\n Hem='N';\n else\n Hem='S'; \n double north;\n if (Hem == 'S')\n north = Northing - 10000000;\n else\n north = Northing;\n latitude = (north/6366197.724/0.9996+(1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)-0.006739496742*Math.sin(north/6366197.724/0.9996)*Math.cos(north/6366197.724/0.9996)*(Math.atan(Math.cos(Math.atan(( Math.exp((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*( 1 - 0.006739496742*Math.pow((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996 )/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996)))*Math.tan((north-0.9996*6399593.625*(north/6366197.724/0.9996 - 0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996 )*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))-north/6366197.724/0.9996)*3/2)*(Math.atan(Math.cos(Math.atan((Math.exp((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996)))*Math.tan((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))-north/6366197.724/0.9996))*180/Math.PI;\n latitude=Math.round(latitude*10000000);\n latitude=latitude/10000000;\n longitude =Math.atan((Math.exp((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*( north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2* north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3)) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))*180/Math.PI+Zone*6-183;\n longitude=Math.round(longitude*10000000);\n longitude=longitude/10000000; \n } \n}\n</code></pre>\n" }, { "answer_id": 28626334, "author": "negora", "author_id": 117374, "author_profile": "https://Stackoverflow.com/users/117374", "pm_score": 1, "selected": false, "text": "<p>For my projects I've using the library <a href=\"https://sites.google.com/site/ahmdalitaha2/latlonglib\" rel=\"nofollow\">LatLongLib</a>, from Ahmed Taha. I think that it's very easy to convert coordinates from the UTM system to the Latitude-Longitude system and vice-versa. You just need to play with the classes UTMUtils, UTMPoint and LatLonPoint.</p>\n\n<p>Time ago I also considered choosing <a href=\"http://www.jstott.me.uk/jcoord/\" rel=\"nofollow\">Jcoord</a>. It was easy and straight to the point too. However, I needed to use the WGS84 ellipsoid and, at that time, only LatLongLib seemed to have that feature.</p>\n" }, { "answer_id": 33806387, "author": "russellhoff", "author_id": 828551, "author_profile": "https://Stackoverflow.com/users/828551", "pm_score": 1, "selected": false, "text": "<p>You can use this project <a href=\"https://github.com/Berico-Technologies/Geo-Coordinate-Conversion-Java/\" rel=\"nofollow\">https://github.com/Berico-Technologies/Geo-Coordinate-Conversion-Java/</a>, adding it to your existing pom.xml using jitpack.</p>\n\n<p>I've successfully been able to convert UTM coordinates (30N, this is, 30 zone and northern hemisphere) to Latitude and Longitude. See my example below:</p>\n\n<pre><code>public void setPunto(Point punto) {\n this.punto = punto;\n LatLon latlon = UTMCoord.locationFromUTMCoord(30, AVKey.NORTH, punto.getX(), punto.getY());\n this.latitud = latlon.getLatitude().degrees;\n this.longitud = latlon.getLongitude().degrees;\n}\n</code></pre>\n\n<p>Note that Point class is of com.vividsolutions.jts.geom.Point class type.</p>\n" }, { "answer_id": 38399170, "author": "Dominic", "author_id": 3049015, "author_profile": "https://Stackoverflow.com/users/3049015", "pm_score": 3, "selected": false, "text": "<p>The transformation of a coordinate can actually be done in only a few lines of code:</p>\n\n<pre><code>Coordinate coordinate = new Coordinate(x, y);\nMathTransform transform = CRS.findMathTransform(CRS.decode(\"EPSG:4326\"), CRS.decode(\"EPSG:3857\"), false);\nJTS.transform(coordinate, coordinate, transform); \n</code></pre>\n\n<p>This will transform a longitude/latitude coordinate (EPSG:4326) into Web Mercator projection (EPSG:3857) coordinate.</p>\n\n<p>You just need to depend on the following two GeoTools libraries in your build tool (e.g. maven):</p>\n\n<pre><code>&lt;repositories&gt;\n &lt;repository&gt;\n &lt;id&gt;osgeo&lt;/id&gt;\n &lt;name&gt;Open Source Geospatial Foundation Repository&lt;/name&gt;\n &lt;url&gt;http://download.osgeo.org/webdav/geotools/&lt;/url&gt;\n &lt;/repository&gt;\n&lt;/repositories&gt;\n\n&lt;dependencies&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;org.geotools&lt;/groupId&gt;\n &lt;artifactId&gt;gt-api&lt;/artifactId&gt;\n &lt;version&gt;${geotools.version}&lt;/version&gt;\n &lt;/dependency&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;org.geotools&lt;/groupId&gt;\n &lt;artifactId&gt;gt-epsg-hsql&lt;/artifactId&gt;\n &lt;version&gt;${geotools.version}&lt;/version&gt;\n &lt;/dependency&gt;\n&lt;/dependencies&gt;\n</code></pre>\n\n<p>This answer builds on a <a href=\"https://gis.stackexchange.com/questions/151565/what-simple-and-light-java-library-to-use-for-wgs84-to-utm-conversion\">question/reply</a> on gis.stackexchange.com. Posted my reply because the current answers here seem to be quite verbose.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? I'm currently looking at Geotools but unfortunately the solution is not obvious.
I was able to use Geotools 2.4 to get something that works, based on some [example code](http://svn.geotools.org/trunk/demo/referencing/src/main/java/org/geotools/demo/referencing/CTSTutorial.java). ``` double utmZoneCenterLongitude = ... // Center lon of zone, example: zone 10 = -123 int zoneNumber = ... // zone number, example: 10 double latitude, longitude = ... // lat, lon in degrees MathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null); ReferencingFactoryContainer factories = new ReferencingFactoryContainer(null); GeographicCRS geoCRS = org.geotools.referencing.crs.DefaultGeographicCRS.WGS84; CartesianCS cartCS = org.geotools.referencing.cs.DefaultCartesianCS.GENERIC_2D; ParameterValueGroup parameters = mtFactory.getDefaultParameters("Transverse_Mercator"); parameters.parameter("central_meridian").setValue(utmZoneCenterLongitude); parameters.parameter("latitude_of_origin").setValue(0.0); parameters.parameter("scale_factor").setValue(0.9996); parameters.parameter("false_easting").setValue(500000.0); parameters.parameter("false_northing").setValue(0.0); Map properties = Collections.singletonMap("name", "WGS 84 / UTM Zone " + zoneNumber); ProjectedCRS projCRS = factories.createProjectedCRS(properties, geoCRS, null, parameters, cartCS); MathTransform transform = CRS.findMathTransform(geoCRS, projCRS); double[] dest = new double[2]; transform.transform(new double[] {longitude, latitude}, 0, dest, 0, 1); int easting = (int)Math.round(dest[0]); int northing = (int)Math.round(dest[1]); ```
176,150
<p>I'm working with a combobox in a Swing-based application, and I'm having a hard time figuring out what to do to differentiate between an ItemEvent that is generated from a user event vs one caused by the application. </p> <p>For instance, Lets say I have a combobox, '<code>combo</code>' and I'm listening for itemStateChanged events with my ItemListener, '<code>listener</code>'. When either a user changes the selection to item 2 or I execute the line (pseudocode):</p> <p><code>combo.setSelection(2)</code></p> <p>.. it seems like I'm not able to tell these events apart. </p> <p>That said, I'm no Swing expert by any means, so I thought I would ask. </p> <p>Thanks!</p>
[ { "answer_id": 176214, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "<p>You can set a flag in your code before you set the selection, and then check for this flag in the listener (and unset the flag if it is set)...</p>\n\n<p>There may be a better way since Java 6, but this is the way I always used to do it...</p>\n\n<p><strong>[Edit]</strong>: As David points out, you will need to set the flag (and update the combo) in the EDT using SwingUtilities.invokeLater or similar (you should do this anyway, as you are changing a UI control)</p>\n" }, { "answer_id": 176288, "author": "David Koelle", "author_id": 2197, "author_profile": "https://Stackoverflow.com/users/2197", "pm_score": 2, "selected": false, "text": "<p>Whether the user selects Item 2, or the API calls setSelection(2), <b>the event will appear the same</b>.</p>\n\n<p>The solution to your problem might be in re-thinking what you want the itemStateChanged code to do when the selection changes. Why would your app work differently under each condition? Maybe there are similarities that you can use to your advantage.</p>\n\n<p><b>Be careful when using flags</b>. The itemStateChanged event will occur on the Event Dispatch Thread, which is a different thread than the one on which you'd set the state of the flag. This would mean that using a flag may not be 100% reliable.</p>\n" }, { "answer_id": 177123, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 0, "selected": false, "text": "<p>If you need to tell the events apart, then there is probably something about your design that needs a rethink. The whole point of MVC is to decouple changes to the model from the actual mouse clicks of the user.</p>\n\n<p>Perhaps you should restate the question in terms of <em>why</em> you would ever want to differentiate between these two situations. We could then provide some guidance on a different way of achieving the goal.</p>\n" }, { "answer_id": 177636, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 3, "selected": true, "text": "<p>The Action and Reaction law is quite clear :). If you try to react on change there is no need to distinguish between user and application. I can imagine only one use case where you need to \"distinguish\". The case where application is displaying some data. In this case you have, probably, data model for your application. And also there are some change listener in this model and application GUI will react by setting values to components. And also. If user selects anything into GUI component. The data model will react by changing value. In this case it is easy to set up some sort of read-only state on data model which will notify model to ignore ANY event coming from observed objects. This notification set should run in EDT and there is no problem with flagging. Small example:</p>\n\n<pre><code>class ApplicationDataModel {\n\n private Flag current = Flag.RW;\n\n public void setData(ApplicationData data) {\n current = Flag.RO;\n setDataImpl(data);\n notifyObservers();\n current = Flag.RW;\n }\n\n public void reaction(Event e) {\n if (flag = Flag.RO) return;\n ...\n }\n\n}\n</code></pre>\n\n<p>Be careful with flagging and don't forget about threading. If you are calling setData from another thread then EDT you are going into trouble. Of course. The extraction of <code>ApplicationData</code> object has to be run in different thread ;). In general, rethink design of your application.</p>\n" }, { "answer_id": 178579, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "<p>So I'm guessing you want the user selection to perform some action rather than just a plain old direct state change. This is an issue caused by limited flexibility (flexibility is always going to be limited, particularly if you have flexibility in other directions).</p>\n\n<p>My suggestion:</p>\n\n<p>Firstly, always go straight to using model in Swing. The widgets are way to complicated and you want different concerns to be split up. Fortunately Swing is already there with its models.</p>\n\n<p>A common pattern is to have delegation between models. So in this case you have the \"real\" default model that holds your data. Insert between the JComboBox and real ComboBoxModel and delegating ComboBoxModel that performs actions on state change instructions. Your application code should ignore the JComboBox and go straight for the real ComboBoxModel bypassing the delegating model. So in a diagram:</p>\n\n<pre>\nUser -- JComboBox -- ActionComboBoxModel -- DefaultComboBoxModel -- Application code\n</pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812/" ]
I'm working with a combobox in a Swing-based application, and I'm having a hard time figuring out what to do to differentiate between an ItemEvent that is generated from a user event vs one caused by the application. For instance, Lets say I have a combobox, '`combo`' and I'm listening for itemStateChanged events with my ItemListener, '`listener`'. When either a user changes the selection to item 2 or I execute the line (pseudocode): `combo.setSelection(2)` .. it seems like I'm not able to tell these events apart. That said, I'm no Swing expert by any means, so I thought I would ask. Thanks!
The Action and Reaction law is quite clear :). If you try to react on change there is no need to distinguish between user and application. I can imagine only one use case where you need to "distinguish". The case where application is displaying some data. In this case you have, probably, data model for your application. And also there are some change listener in this model and application GUI will react by setting values to components. And also. If user selects anything into GUI component. The data model will react by changing value. In this case it is easy to set up some sort of read-only state on data model which will notify model to ignore ANY event coming from observed objects. This notification set should run in EDT and there is no problem with flagging. Small example: ``` class ApplicationDataModel { private Flag current = Flag.RW; public void setData(ApplicationData data) { current = Flag.RO; setDataImpl(data); notifyObservers(); current = Flag.RW; } public void reaction(Event e) { if (flag = Flag.RO) return; ... } } ``` Be careful with flagging and don't forget about threading. If you are calling setData from another thread then EDT you are going into trouble. Of course. The extraction of `ApplicationData` object has to be run in different thread ;). In general, rethink design of your application.
176,158
<p>Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements?</p> <p>For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find&#95;if, count&#95;if, or sort directly on this array.</p> <p>Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.</p>
[ { "answer_id": 176167, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/array.html\" rel=\"nofollow noreferrer\">Boost.Array</a> to create a C++ array type with STL semantics.</p>\n\n<p>using arrays:</p>\n\n<pre><code>int a[100];\nfor (int i = 0; i &lt; 100; ++i)\n a[i] = 0;\n</code></pre>\n\n<p>using boost.arrays:</p>\n\n<pre><code>boost::array&lt;int,100&gt; a;\nfor (boost::array&lt;int,100&gt;::iterator i = a.begin(); i != a.end(); ++i)\n *i = 0;\n</code></pre>\n\n<p><strong>Update:</strong> With C++11, you can now use <code>std::array</code>.</p>\n" }, { "answer_id": 176173, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "<p>You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,:</p>\n\n<pre><code>int ary[100];\n// init ...\n\nstd::sort(ary, ary+100); // sorts the array\nstd::find(ary, ary+100, pred); find some element\n</code></pre>\n\n<p>I think you'll find that most stuff works just as you would expect.</p>\n" }, { "answer_id": 176177, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<p>All the STL algorithms use iterators.<br>\nA pointer is a valid iterator into an array of objects.<br></p>\n\n<p><b>N.B.</b>The end iterator must be one element past the end of the array. Hence the data+5 in the following code.</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n\nint main()\n{\n int data[] = {4,3,7,5,8};\n std::sort(data,data+5);\n\n std::copy(data,data+5,std::ostream_iterator&lt;int&gt;(std::cout,\"\\t\"));\n}\n</code></pre>\n" }, { "answer_id": 176207, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 2, "selected": false, "text": "<p>A pointer is a valid model of an iterator:</p>\n\n<pre><code>struct Bob\n{ int val; };\n\nbool operator&lt;(const Bob&amp; lhs, const Bob&amp; rhs)\n{ return lhs.val &lt; rhs.val; }\n\n// let's do a reverse sort\nbool pred(const Bob&amp; lhs, const Bob&amp; rhs)\n{ return lhs.val &gt; rhs.val; }\n\nbool isBobNumberTwo(const Bob&amp; bob) { return bob.val == 2; }\n\nint main()\n{\n Bob bobs[4]; // ok, so we have 4 bobs!\n const size_t size = sizeof(bobs)/sizeof(Bob);\n bobs[0].val = 1; bobs[1].val = 4; bobs[2].val = 2; bobs[3].val = 3;\n\n // sort using std::less&lt;Bob&gt; wich uses operator &lt;\n std::sort(bobs, bobs + size);\n std::cout &lt;&lt; bobs[0].val &lt;&lt; std::endl;\n std::cout &lt;&lt; bobs[1].val &lt;&lt; std::endl;\n std::cout &lt;&lt; bobs[2].val &lt;&lt; std::endl;\n std::cout &lt;&lt; bobs[3].val &lt;&lt; std::endl;\n\n // sort using pred\n std::sort(bobs, bobs + size, pred);\n std::cout &lt;&lt; bobs[0].val &lt;&lt; std::endl;\n std::cout &lt;&lt; bobs[1].val &lt;&lt; std::endl;\n std::cout &lt;&lt; bobs[2].val &lt;&lt; std::endl;\n std::cout &lt;&lt; bobs[3].val &lt;&lt; std::endl;\n\n //Let's find Bob number 2\n Bob* bob = std::find_if(bobs, bobs + size, isBobNumberTwo);\n if (bob-&gt;val == 2)\n std::cout &lt;&lt; \"Ok, found the right one!\\n\";\n else \n std::cout &lt;&lt; \"Whoops!\\n\";\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 176270, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 3, "selected": false, "text": "<p>You can use an inline function template so that you don't have to duplicate the array index</p>\n\n<pre><code>template &lt;typename T, int I&gt;\ninline T * array_begin (T (&amp;t)[I])\n{\n return t;\n}\n\ntemplate &lt;typename T, int I&gt;\ninline T * array_end (T (&amp;t)[I])\n{\n return t + I;\n}\n\nvoid foo ()\n{\n int array[100];\n std::find (array_begin (array)\n , array_end (array)\n , 10);\n}\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3561/" ]
Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements? For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find\_if, count\_if, or sort directly on this array. Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.
You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,: ``` int ary[100]; // init ... std::sort(ary, ary+100); // sorts the array std::find(ary, ary+100, pred); find some element ``` I think you'll find that most stuff works just as you would expect.
176,171
<p>I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix.</p> <p>Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work.</p> <p>In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages.</p> <p><strong>Master Page Script Reference</strong></p> <pre><code>&lt;script src=&quot;scripts.js&quot; language=&quot;javascript&quot; type=&quot;text/javascript&quot; /&gt; </code></pre> <p><strong>Single Page</strong></p> <pre><code>&lt;script&gt; MakePretty(&quot;elementID&quot;); &lt;/script&gt; </code></pre> <p>As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to &quot;MakePretty&quot; will change dependant on content.</p> <p><strong>Content Pages</strong></p> <p>Now, due to the content page not having a <code>&lt;head&gt;</code> element, I have been using the following code to add it to the master pages <code>&lt;head&gt;</code> element:</p> <pre><code>HtmlGenericControl ctl = new HtmlGenericControl(&quot;script&quot;); ctl.Attributes.Add(&quot;language&quot;, &quot;javascript&quot;); ctl.InnerHtml = @&quot;MakePretty(&quot;&quot;elementID&quot;&quot;)&quot;; Master.Page.Header.Controls.Add(ctl); </code></pre> <p>Now, this <strong>fails to work</strong>. However, if I replace with something simple like <code>alert(&quot;HI!&quot;)</code>, all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing..</p> <p>Now, having done some digging, I have learned that th content page's <code>Load</code> event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once?</p> <p>Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario.</p> <p><strong>How can I get content pages to call javascript code which is referenced in the Master page?</strong></p> <p>Thanks for any/all help on this guys, you will really be helping me out with this work problem.</p> <h2>NOTES:</h2> <ul> <li><code>RegisterStartupScript</code> and the like does not seem to work at any level..</li> <li>The control ID's are being set fine, even in the MasterPage environment and are rendering as expected.</li> </ul> <hr /> <p>Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.</p>
[ { "answer_id": 176208, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 2, "selected": false, "text": "<p>Isn't it possible to do with clean javascript ?-)</p>\n\n<p>-- just add something similar to this inside the body-tag:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n window.onload = function(){\n MakePretty(\"elementID\");\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>By the way the script-tag has to have an end-tag:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"myScript.js\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 176212, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": true, "text": "<p>Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way.</p>\n\n<p>Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of \"elementID\" as expected, it may be outputting \"ctl00_MainContentPlaceHolder_elementID\" View your source or use firebug to inspect your form elements to see what the IDs outputted are.</p>\n" }, { "answer_id": 176217, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>Once you use Master Pages, the ids of controls on the client side aren't what you think they are. You should use Control.ClientID when you generate the script.</p>\n" }, { "answer_id": 176389, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "<p>Why not use jQuery to find all the controls? Something like this:</p>\n\n<pre><code>$(document).ready(function(){\n $(\"input[type='text'], input[type='radio'], input[type='checkbox'], select, textarea\").each(function(){\n MakePretty(this);\n });\n});\n</code></pre>\n\n<p>This way you'll get all elements on the page, you can wait until the page is ready (so you don't modify the DOM illigally). The jQuery selector can get the elements in a bit more of a specific format if you need (ie, add a root element, like the ID of the body div).</p>\n\n<p>It'd also be best to modify the MakePretty method so it takes the element not the ID as the parameter to reduce processing overhead.</p>\n" }, { "answer_id": 176453, "author": "Mario", "author_id": 8426, "author_profile": "https://Stackoverflow.com/users/8426", "pm_score": 0, "selected": false, "text": "<p>When using master pages, you need to be careful with the html attribute ID, since .NET will modify this value as it needs to keep ids unique.</p>\n\n<p>I would assume your javascript is applying css styles via ID, and when you are using master pages the ID is different than what is in your aspx. If you verify your javascript is always being added, your answer needs to take into account the following:</p>\n\n<ul>\n<li>ALWAYS set your master page id in page load (this.ID = \"myPrefix\";)</li>\n<li>Any HTML element in your master page will be prefixed by the master page id (i.e.: on the rendered page will be \"myPrefix_myDiv\")</li>\n<li>Any HTML element in your content place holder id will be prefixed with an additional prefix (i.e. myPrefix_ContentPlaceHolderId1_myDiv)</li>\n</ul>\n\n<p>Please let me know if I can clarify anything. Hope this helps!</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix. Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work. In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages. **Master Page Script Reference** ``` <script src="scripts.js" language="javascript" type="text/javascript" /> ``` **Single Page** ``` <script> MakePretty("elementID"); </script> ``` As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to "MakePretty" will change dependant on content. **Content Pages** Now, due to the content page not having a `<head>` element, I have been using the following code to add it to the master pages `<head>` element: ``` HtmlGenericControl ctl = new HtmlGenericControl("script"); ctl.Attributes.Add("language", "javascript"); ctl.InnerHtml = @"MakePretty(""elementID"")"; Master.Page.Header.Controls.Add(ctl); ``` Now, this **fails to work**. However, if I replace with something simple like `alert("HI!")`, all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing.. Now, having done some digging, I have learned that th content page's `Load` event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once? Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario. **How can I get content pages to call javascript code which is referenced in the Master page?** Thanks for any/all help on this guys, you will really be helping me out with this work problem. NOTES: ------ * `RegisterStartupScript` and the like does not seem to work at any level.. * The control ID's are being set fine, even in the MasterPage environment and are rendering as expected. --- Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.
Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way. Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of "elementID" as expected, it may be outputting "ctl00\_MainContentPlaceHolder\_elementID" View your source or use firebug to inspect your form elements to see what the IDs outputted are.
176,196
<p>Why is the following displayed different in Linux vs Windows?</p> <pre><code>System.out.println(new String("¿".getBytes("UTF-8"), "UTF-8")); </code></pre> <p>in Windows:</p> <p>¿</p> <p>in Linux:</p> <p>¿</p>
[ { "answer_id": 176211, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>It's hard to know exactly which bytes your source code contains, or the string which getBytes() is being called on, due to your editor and compiler encodings.</p>\n\n<p>Can you produce a short but complete program containing only ASCII (and the relevant \\uxxxx escaping in the string) which still shows the problem?</p>\n\n<p>I suspect the problem may well be with the console output on either Windows or Linux, but it would be good to get a reproducible program first.</p>\n" }, { "answer_id": 176238, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 3, "selected": false, "text": "<p>Not sure where the problem is exactly, but it's worth noting that </p>\n\n<p>¿ ( 0xc2,0xbf)</p>\n\n<p>is the result of encoding with UTF-8 </p>\n\n<p>0xbf, </p>\n\n<p>which is the Unicode codepoint for ¿ </p>\n\n<p>So, it looks like in the linux case, the output is not being displayed as utf-8, but as a single-byte string </p>\n" }, { "answer_id": 176243, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 3, "selected": false, "text": "<p>Check what encoding your linux terminal has.</p>\n\n<p>For gnome-terminal in ubuntu - go to the \"Terminal\" menu and select \"Set Character Encoding\".</p>\n\n<p>For putty, Configuration -> Window -> Translation -> UTF-8 (and if that doesn't work, see <a href=\"http://planetozh.com/blog/2007/08/how-to-display-utf8-in-your-putty-bash-shell/\" rel=\"noreferrer\">this post</a>).</p>\n" }, { "answer_id": 176289, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<p>Run this code to help determine if it is a compiler or console issue:</p>\n\n<pre><code>public static void main(String[] args) throws Exception {\n String s = \"¿\";\n printHex(Charset.defaultCharset(), s);\n\n Charset utf8 = Charset.forName(\"UTF-8\");\n printHex(utf8, s);\n}\n\npublic static void printHex(Charset encoding, String s)\n throws UnsupportedEncodingException {\n System.out.print(encoding + \"\\t\" + s + \"\\t\");\n\n byte[] barr = s.getBytes(encoding);\n for (int i = 0; i &lt; barr.length; i++) {\n int n = barr[i] &amp; 0xFF;\n String hex = Integer.toHexString(n);\n if (hex.length() == 1) {\n System.out.print('0');\n }\n System.out.print(hex);\n }\n System.out.println();\n}\n</code></pre>\n\n<p>If the encoded bytes for UTF-8 are different on each platform (it should be <em>c2bf</em>), it is a compiler issue.</p>\n\n<p>If it is a compiler issue, replace \"¿\" with <a href=\"http://www.unicode.org/charts/PDF/U0080.pdf\" rel=\"nofollow noreferrer\">\"\\u00bf\"</a>.</p>\n" }, { "answer_id": 176724, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 5, "selected": true, "text": "<p>System.out.println() outputs the text in the system default encoding, but the console interprets that output according to its own encoding (or \"codepage\") setting. On your Windows machine the two encodings seem to match, but on the Linux box the output is apparently in UTF-8 while the console is decoding it as a single-byte encoding like ISO-8859-1. Or maybe, as Jon suggested, the source file is being saved as UTF-8 and <code>javac</code> is reading it as something else, a problem that can be avoided by using Unicode escapes. </p>\n\n<p>When you need to output anything other than ASCII text, your best bet is to write it to a file using an appropriate encoding, then read the file with a text editor--consoles are too limited and too system-dependent. By the way, this bit of code:</p>\n\n<pre><code>new String(\"¿\".getBytes(\"UTF-8\"), \"UTF-8\")\n</code></pre>\n\n<p>...has no effect on the output. All that does is encode the contents of the string to a byte array and decode it again, reproducing the original string--an expensive no-op. If you want to output text in a particular encoding, you need to use an OutputStreamWriter, like so:</p>\n\n<pre><code>FileOutputStream fos = new FileOutputStream(\"out.txt\");\nOutputStreamWriter osw = new OutputStreamWriter(fos, \"UTF-8\");\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9518/" ]
Why is the following displayed different in Linux vs Windows? ``` System.out.println(new String("¿".getBytes("UTF-8"), "UTF-8")); ``` in Windows: ¿ in Linux: ¿
System.out.println() outputs the text in the system default encoding, but the console interprets that output according to its own encoding (or "codepage") setting. On your Windows machine the two encodings seem to match, but on the Linux box the output is apparently in UTF-8 while the console is decoding it as a single-byte encoding like ISO-8859-1. Or maybe, as Jon suggested, the source file is being saved as UTF-8 and `javac` is reading it as something else, a problem that can be avoided by using Unicode escapes. When you need to output anything other than ASCII text, your best bet is to write it to a file using an appropriate encoding, then read the file with a text editor--consoles are too limited and too system-dependent. By the way, this bit of code: ``` new String("¿".getBytes("UTF-8"), "UTF-8") ``` ...has no effect on the output. All that does is encode the contents of the string to a byte array and decode it again, reproducing the original string--an expensive no-op. If you want to output text in a particular encoding, you need to use an OutputStreamWriter, like so: ``` FileOutputStream fos = new FileOutputStream("out.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); ```
176,284
<p>Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL thats fed into it can be anything from <a href="http://www.domain.com" rel="noreferrer">http://www.domain.com</a> to www.domain.com/path/script.php?=whatever</p> <p>Whats the best way to go about doing this?</p>
[ { "answer_id": 176300, "author": "davidmytton", "author_id": 2183, "author_profile": "https://Stackoverflow.com/users/2183", "pm_score": 4, "selected": false, "text": "<p>You can use <a href=\"http://www.php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\">parse_url()</a> to do this:</p>\n\n<pre><code>$url = 'http://www.example.com';\n$domain = parse_url($url, PHP_URL_HOST);\n$domain = str_replace('www.','',$domain);\n</code></pre>\n\n<p>In this example, $domain should contain example.com, irrespective of it having www or not. It also works for a domain such as .co.uk</p>\n" }, { "answer_id": 176341, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://www.php.net/manual/en/function.parse-url.php\" rel=\"noreferrer\">parse_url</a> turns a URL into an associative array:</p>\n\n<pre><code>php &gt; $foo = \"http://www.example.com/foo/bar?hat=bowler&amp;accessory=cane\";\nphp &gt; $blah = parse_url($foo);\nphp &gt; print_r($blah);\nArray\n(\n [scheme] =&gt; http\n [host] =&gt; www.example.com\n [path] =&gt; /foo/bar\n [query] =&gt; hat=bowler&amp;accessory=cane\n)\n</code></pre>\n" }, { "answer_id": 190721, "author": "firstresponder", "author_id": 26088, "author_profile": "https://Stackoverflow.com/users/26088", "pm_score": 4, "selected": false, "text": "<p>You can also write a regular expression to get exactly what you want.</p>\n\n<p>Here is my attempt at it:</p>\n\n<pre><code>$pattern = '/\\w+\\..{2,3}(?:\\..{2,3})?(?:$|(?=\\/))/i';\n$url = 'http://www.example.com/foo/bar?hat=bowler&amp;accessory=cane';\nif (preg_match($pattern, $url, $matches) === 1) {\n echo $matches[0];\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>example.com\n</code></pre>\n\n<p>This pattern also takes into consideration domains such as 'example.com.au'.</p>\n\n<p>Note: I have not consulted the relevant RFC.</p>\n" }, { "answer_id": 3561064, "author": "livingtech", "author_id": 18961, "author_profile": "https://Stackoverflow.com/users/18961", "pm_score": 0, "selected": false, "text": "<p>I spent some time thinking about whether it makes sense to use a regular expression for this, but in the end I think not. </p>\n\n<p>firstresponder's regexp came close to convincing me it was the best way, but it didn't work on anything missing a trailing slash (so <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a>, for instance). I fixed that with the following: <code>'/\\w+\\..{2,3}(?:\\..{2,3})?(?=[\\/\\W])/i'</code>, but then I realized that matches twice for urls like '<a href=\"http://example.com/index.htm\" rel=\"nofollow noreferrer\">http://example.com/index.htm</a>'. Oops. That wouldn't be so bad (just use the first one), but it also matches twice on something like this: '<a href=\"http://abc.ed.fg.hij.kl.mn/\" rel=\"nofollow noreferrer\">http://abc.ed.fg.hij.kl.mn/</a>', and the first match isn't the right one. :(</p>\n\n<p>A co-worker suggested just getting the host (via <code>parse_url()</code>), and then just taking the last two or three array bits (<code>split()</code> on '.') The two or three would be based on a list of domains, like 'co.uk', etc. Making up that list becomes the hard part.</p>\n" }, { "answer_id": 4354145, "author": "z3ro", "author_id": 530504, "author_profile": "https://Stackoverflow.com/users/530504", "pm_score": 1, "selected": false, "text": "<p>Solved this... </p>\n\n<p>Say we're calling dev.mysite.com and we want to extract 'mysite.com'</p>\n\n<pre><code>$requestedServerName = $_SERVER['SERVER_NAME']; // = dev.mysite.com\n\n$thisSite = explode('.', $requestedServerName); // site name now an array\n\narray_shift($thisSite); //chop off the first array entry eg 'dev'\n\n$thisSite = join('.', $thisSite); //join it back together with dots ;)\n\necho $thisSite; //outputs 'mysite.com'\n</code></pre>\n\n<p>Works with mysite.co.uk too so should work everywhere :)</p>\n" }, { "answer_id": 8388380, "author": "Mark Shust at M.academy", "author_id": 832719, "author_profile": "https://Stackoverflow.com/users/832719", "pm_score": 2, "selected": false, "text": "<p>Here are a couple simple functions to get the root domain (example.com) from a normal or long domain (test.sub.domain.com) or url (http://www.example.com).</p>\n\n<pre><code>/**\n * Get root domain from full domain\n * @param string $domain\n */\npublic function getRootDomain($domain)\n{\n $domain = explode('.', $domain);\n\n $tld = array_pop($domain);\n $name = array_pop($domain);\n\n $domain = \"$name.$tld\";\n\n return $domain;\n}\n\n/**\n * Get domain name from url\n * @param string $url\n */\npublic function getDomainFromUrl($url)\n{\n $domain = parse_url($url, PHP_URL_HOST);\n $domain = $this-&gt;getRootDomain($domain);\n\n return $domain;\n}\n</code></pre>\n" }, { "answer_id": 38047898, "author": "Oleksandr Fediashov", "author_id": 6488546, "author_profile": "https://Stackoverflow.com/users/6488546", "pm_score": 0, "selected": false, "text": "<p>There is only one correct way to extract domain parts, it's use <a href=\"https://publicsuffix.org/\" rel=\"nofollow\">Public Suffix List</a> (database of TLDs). I recomend <a href=\"https://github.com/layershifter/TLDExtract\" rel=\"nofollow\">TLDExtract</a> package, here is sample code:</p>\n\n<pre><code>$extract = new LayerShifter\\TLDExtract\\Extract();\n\n$result = $extract-&gt;parse('www.domain.com/path/script.php?=whatever');\n$result-&gt;getSubdomain(); // will return (string) 'www'\n$result-&gt;getHostname(); // will return (string) 'domain'\n$result-&gt;getSuffix(); // will return (string) 'com'\n</code></pre>\n" }, { "answer_id": 60327194, "author": "Mohamad Hamouday", "author_id": 4110122, "author_profile": "https://Stackoverflow.com/users/4110122", "pm_score": 0, "selected": false, "text": "<p>This function should work:</p>\n\n<pre><code>function Delete_Domain_From_Url($Url = false)\n{\n if($Url)\n {\n $Url_Parts = parse_url($Url);\n $Url = isset($Url_Parts['path']) ? $Url_Parts['path'] : '';\n $Url .= isset($Url_Parts['query']) ? \"?\".$Url_Parts['query'] : '';\n }\n\n return $Url;\n}\n</code></pre>\n\n<p>To use it:</p>\n\n<pre><code>$Url = \"https://stackoverflow.com/questions/176284/how-do-you-strip-out-the-domain-name-from-a-url-in-php\";\necho Delete_Domain_From_Url($Url);\n\n# Output: \n#/questions/176284/how-do-you-strip-out-the-domain-name-from-a-url-in-php\n</code></pre>\n" }, { "answer_id": 63489368, "author": "AndreyP", "author_id": 1414555, "author_profile": "https://Stackoverflow.com/users/1414555", "pm_score": 3, "selected": false, "text": "<p>Following code will trim protocol, domain and port from absolute URL:</p>\n<pre><code>$urlWithoutDomain = preg_replace('#^.+://[^/]+#', '', $url);\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL thats fed into it can be anything from <http://www.domain.com> to www.domain.com/path/script.php?=whatever Whats the best way to go about doing this?
[parse\_url](http://www.php.net/manual/en/function.parse-url.php) turns a URL into an associative array: ``` php > $foo = "http://www.example.com/foo/bar?hat=bowler&accessory=cane"; php > $blah = parse_url($foo); php > print_r($blah); Array ( [scheme] => http [host] => www.example.com [path] => /foo/bar [query] => hat=bowler&accessory=cane ) ```
176,295
<p>I've tried these, and they did not work (Access opens, but it does not wait:</p> <pre><code>start "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb start /WAIT "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb start /W "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb start filename.mdb start msaccess.exe filename.mdb </code></pre>
[ { "answer_id": 176297, "author": "pc1oad1etter", "author_id": 525, "author_profile": "https://Stackoverflow.com/users/525", "pm_score": 3, "selected": true, "text": "<pre><code>start /WAIT msaccess.exe filename.mdb\n</code></pre>\n\n<p>does the trick.</p>\n\n<p>I don't know why adding the full path makes it fail.</p>\n" }, { "answer_id": 6817094, "author": "James whatley", "author_id": 861678, "author_profile": "https://Stackoverflow.com/users/861678", "pm_score": 1, "selected": false, "text": "<pre><code>PATH=\"C:\\Program Files\\Microsoft Office\\OFFICE11\\; C:\\Windows\\Command\"\nSTART /WAIT MSACCESS.exe \"path to mdb file\" /X \"name of macro\"\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525/" ]
I've tried these, and they did not work (Access opens, but it does not wait: ``` start "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb start /WAIT "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb start /W "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb start filename.mdb start msaccess.exe filename.mdb ```
``` start /WAIT msaccess.exe filename.mdb ``` does the trick. I don't know why adding the full path makes it fail.
176,319
<p>It seems MySQL does not support the flag "NO_ WRITE_ TO_ BINLOG" for TRUNCATE. So I have to wait until delay is 0, then stop the replication, make the TRUNCATE of the table/s, reset the master, and then start replication again. Really painful. Any other suggestion?</p>
[ { "answer_id": 178091, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<p>TRUNCATE is pretty heavy-handed. Can you get by with just a DELETE query?</p>\n" }, { "answer_id": 178642, "author": "Harrison Fisk", "author_id": 16111, "author_profile": "https://Stackoverflow.com/users/16111", "pm_score": 2, "selected": false, "text": "<p>You can use the command to disable binary logging for a session to do what you want.</p>\n\n<pre>\nSET SQL_LOG_BIN = 0;\nTRUNCATE TABLE ;\nSET SQL_LOG_BIN = 1;\n</pre>\n\n<p>This does require that you have the SUPER privilege since you are effectively breaking replication by not sending the TRUNCATE to the slave.</p>\n" }, { "answer_id": 178658, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>TRUNCATE is not to be used lightly, since it essentially just drops the data on the floor without logging the fact that it did it. It's transactionally unsafe and impossible to recover from, and as a result it's not compatible with replication. Even if you manage to use TRUNCATE in a replication setup, your replicated data will be corrupt, or at best invalid.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It seems MySQL does not support the flag "NO\_ WRITE\_ TO\_ BINLOG" for TRUNCATE. So I have to wait until delay is 0, then stop the replication, make the TRUNCATE of the table/s, reset the master, and then start replication again. Really painful. Any other suggestion?
You can use the command to disable binary logging for a session to do what you want. ``` SET SQL_LOG_BIN = 0; TRUNCATE TABLE ; SET SQL_LOG_BIN = 1; ``` This does require that you have the SUPER privilege since you are effectively breaking replication by not sending the TRUNCATE to the slave.
176,331
<p>I've developed a windows application that uses shared memory---that is---memory mapped files for interprocess communication. I have a windows service that does some processing and periodically writes data to the memory mapped file. I have a separate windows application that reads from the memory mapped file and displays the information. The application works as expected on Windows XP, XP Pro and Server 2003, but NOT on Vista.</p> <p>I can see that the data being written to the memory mapped file is happening correctly by the windows service because I can open the file with a text editor and see the stored messages, but the "consumer" application can't read from the file. One interesting thing to note here, is that if I close the consumer application and restart it, it consumes the messages that were previously written to the memory mapped file. </p> <p>Also, another strange thing is that I get the same behavior when I connect to the windows host using Remote Desktop and invoke/use the consumer application through remote desktop. However, if I invoke the Remote Desktop and connect to the target host's console session with the following command: <code>mstsc -v:servername /F -console</code>, everything works perfectly. </p> <p>So that's why I think the problem is related to permissions. Can anyone comment on this?</p> <p>EDIT:</p> <p>The ACL that I'm using to create the memory mapped file and the Mutex objects that sychronize access is as follows:</p> <pre class="lang-cpp prettyprint-override"><code>TCHAR * szSD = TEXT("D:") TEXT("(A;;RPWPCCDCLCSWRCWDWOGAFA;;;S-1-1-0)") TEXT("(A;;GA;;;BG)") TEXT("(A;;GA;;;AN)") TEXT("(A;;GA;;;AU)") TEXT("(A;;GA;;;LS)") TEXT("(A;;GA;;;RD)") TEXT("(A;;GA;;;WD)") TEXT("(A;;GA;;;BA)"); </code></pre> <p>I think this may be part of the issue.</p>
[ { "answer_id": 176424, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 0, "selected": false, "text": "<p>Have you tried moving the file to a different location. Try putting it in the 'Shared Documents' folder, this seems to be the most freely accessible folder in Vista.</p>\n" }, { "answer_id": 176426, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>What access are you opening the shared memory section with? Try with <code>FILE_MAP_ALL_ACCESS</code> and work your way down. Also make sure you don't have a race condition between the producer and consumers - which one is creating the shared memory? Make sure ths is created before the other one tries to open it. One method is to create the section in the parent before you start the child process - if you are using a parent/child architecture.</p>\n\n<p>Your child may need to run elevated on Vista in order to be allowed access to the shared memory. It may also be related to the window session your are using. Services run in session 0 (I think) while other apps (especially if you log in via remote desktop) may run in another session.</p>\n" }, { "answer_id": 184748, "author": "James Whetstone", "author_id": 25636, "author_profile": "https://Stackoverflow.com/users/25636", "pm_score": 3, "selected": false, "text": "<p>So I found the solution to my problem:</p>\n\n<p>On Windows XP, all named kernel objects such as mutex, semaphore and memory mapped objects are stored in the same namespace. So when different processes in different user sessions reference a particular object using it's name, they obtain a handle to that object. However, as a security precaution, Windows terminal services creates a separate namespace for kernel objects referenced from processes started in it's session. Windows Vista has this behavior built into it as well, so that's why my app didn't work correctly on Vista. To elaborate, I have a Windows service that runs in the null session and an application that runs in a user session, so my named objects were being created in separate namespaces.</p>\n\n<p>The quick fix for this issue was to <strong>use the Global namespace by prepending \"Global\\\" to each kernel object name</strong> that I used and that did the trick.</p>\n" }, { "answer_id": 185545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The prefix \"Global\\\" may not work on shared memory. See <a href=\"http://msdn.microsoft.com/en-us/windows/hardware/gg463353\" rel=\"nofollow noreferrer\">\"Impact of Session 0 Isolation on Services and Drivers in Windows Vista\"</a> for solution.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25636/" ]
I've developed a windows application that uses shared memory---that is---memory mapped files for interprocess communication. I have a windows service that does some processing and periodically writes data to the memory mapped file. I have a separate windows application that reads from the memory mapped file and displays the information. The application works as expected on Windows XP, XP Pro and Server 2003, but NOT on Vista. I can see that the data being written to the memory mapped file is happening correctly by the windows service because I can open the file with a text editor and see the stored messages, but the "consumer" application can't read from the file. One interesting thing to note here, is that if I close the consumer application and restart it, it consumes the messages that were previously written to the memory mapped file. Also, another strange thing is that I get the same behavior when I connect to the windows host using Remote Desktop and invoke/use the consumer application through remote desktop. However, if I invoke the Remote Desktop and connect to the target host's console session with the following command: `mstsc -v:servername /F -console`, everything works perfectly. So that's why I think the problem is related to permissions. Can anyone comment on this? EDIT: The ACL that I'm using to create the memory mapped file and the Mutex objects that sychronize access is as follows: ```cpp TCHAR * szSD = TEXT("D:") TEXT("(A;;RPWPCCDCLCSWRCWDWOGAFA;;;S-1-1-0)") TEXT("(A;;GA;;;BG)") TEXT("(A;;GA;;;AN)") TEXT("(A;;GA;;;AU)") TEXT("(A;;GA;;;LS)") TEXT("(A;;GA;;;RD)") TEXT("(A;;GA;;;WD)") TEXT("(A;;GA;;;BA)"); ``` I think this may be part of the issue.
So I found the solution to my problem: On Windows XP, all named kernel objects such as mutex, semaphore and memory mapped objects are stored in the same namespace. So when different processes in different user sessions reference a particular object using it's name, they obtain a handle to that object. However, as a security precaution, Windows terminal services creates a separate namespace for kernel objects referenced from processes started in it's session. Windows Vista has this behavior built into it as well, so that's why my app didn't work correctly on Vista. To elaborate, I have a Windows service that runs in the null session and an application that runs in a user session, so my named objects were being created in separate namespaces. The quick fix for this issue was to **use the Global namespace by prepending "Global\" to each kernel object name** that I used and that did the trick.
176,338
<p>I have an ASP.NET 2.0 [no ajax...yet] web site that will be deployed in compiled form on multiple customer sites. Typically the site will be intranet only. Some customers trust all of their people and don't care about limiting access to the site and/or page functions, others trust no one and want only certain people and/or groups to be able to view certain pages, click certain buttons, et al.</p> <p>i could do some home-grown solution, possibly drive the access permissions from a database table, but before i go down that road i thought i'd ask in SO: what is a good solution for this situation? preferably one that can be controlled completedly in the web.config file and/or database, since rebuilding the web site is not possible (for the client, and i don't want to have to do it for them over and over). Active Directory integration would be a bonus, but not a requirement (unless that's just easier).</p> <p>as a starting point, i'm thinking that each page/function point in the site be given an identity and associated with a permission group...</p> <p>EDIT: web.config authorization section to allow/deny access by role and user is good, but that is only half of the problem - the other half is controlling access to the individual methods (buttons, whatever) on each page. For example, some users can view whatchamacallits while others are allowed to edit, create, delete, or disable/enable them. All of these buttons/links/actions are on the view page...</p> <p>[ideally i would make the disabled buttons invisible, but that is not important here]</p> <p>EDIT: some good suggestions so far, but no complete solution yet - still leaning towards a database-driven solution...</p> <ul> <li>security permission demand attributes will throw exceptions when buttons are clicked, which is not a friendly thing to do; i'd much rather hide buttons that the user is not allowed to use</li> <li>the LoginView control is also interesting, but would require replicating most of the page content several times (once for each role) and may not handle the case where a user is in more than one role - i cannot assume that the roles are hierarchical since they will be defined by the customer</li> </ul> <p>EDIT: platform is Win2K/XP, Sql Server 2005, ASP.NET 2.0, not using AJAX</p>
[ { "answer_id": 176384, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 2, "selected": true, "text": "<p>I prefer to grant access rights to AD groups rather than specific users. I find it's much more flexible.</p>\n\n<p>I don't know much about your application, but you might want to look at the authorization tag in the web.config file:</p>\n\n<pre><code>&lt;authorization&gt;\n &lt;!-- \n &lt;deny users=\"?\" /&gt;\n &lt;allow users=\"[comma separated list of users]\"\n roles=\"[comma separated list of roles]\"/&gt;\n &lt;deny users=\"[comma separated list of users]\"\n roles=\"[comma separated list of roles]\"/&gt;\n --&gt;\n&lt;/authorization&gt;\n</code></pre>\n\n<p>You can separate web.config files each directory within your web application, and you can nest directories. Each web.config file can have it's own authorization section. If you put different pages in each directory you can effectively tightly manage security by allowing a specific role in each web.config, and denying everything else. Then you can manage members of each role in active directory. I've found this to be an affective solution because it makes good use of Microsoft's Active Directory and ASP.NET security framework without writing your own custom stuff, and if you use roles, it's possible to offload the management of role membership to someone who doesn't ever have to touch the web.config file they just need to know how to use the AD management console.</p>\n" }, { "answer_id": 177346, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": 1, "selected": false, "text": "<p>While I've never used this before in practice and cannot argue its merits, I know that .NET has role based code security which allows you to declaratively lock methods down by role or user. For example:</p>\n\n<pre><code>[PrincipalPermissionAttribute(SecurityAction.Demand, Name = \"MyUser\", Role = \"User\")]\npublic static void PrivateInfo()\n{ \n //Print secret data.\n Console.WriteLine(\"\\n\\nYou have access to the private data!\");\n}\n</code></pre>\n\n<p>Role based security is covered in more detail <a href=\"http://msdn.microsoft.com/en-us/library/52kd59t0.aspx\" rel=\"nofollow noreferrer\">here</a>. I don't know that it will help you much though considering it will require a recompile to change it; however slapping labels on methods is faster than building logic to show/hide buttons or do security validation in code.</p>\n\n<p>Additionally, you'll want to <a href=\"http://msdn.microsoft.com/en-us/library/ms998358.aspx\" rel=\"nofollow noreferrer\">read up</a> on Integrated Windows authentication to gain the Active Directory possibility.</p>\n" }, { "answer_id": 177358, "author": "martin", "author_id": 8421, "author_profile": "https://Stackoverflow.com/users/8421", "pm_score": 1, "selected": false, "text": "<p>It sounds like you could use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.loginview.aspx\" rel=\"nofollow noreferrer\">LoginView</a> control, which can show panels of controls to only certain users or roles. \nRoles are most flexible- if no security is required, put all users in all roles.</p>\n\n<p>Use in combination with standard web.config security (integrated windows with active directory, or forms authentication (the asp 2 Sql server schema or your own).</p>\n\n<pre><code>&lt;asp:LoginView id=\"LoginView1\" runat=\"server\"&gt;\n &lt;RoleGroups&gt;\n &lt;asp:RoleGroup Roles=\"Admin\"&gt;\n &lt;ContentTemplate&gt;\n &lt;asp:LoginName id=\"LoginName2\" runat=\"Server\"&gt;&lt;/asp:LoginName&gt;, you\n are logged in as an administrator.\n &lt;/ContentTemplate&gt;\n &lt;/asp:RoleGroup&gt;\n &lt;asp:RoleGroup Roles=\"User\"&gt;\n &lt;ContentTemplate&gt;\n &lt;asp:Button id=\"Button1\" runat=\"Server\" OnClick=\"AllUserClick\"&gt;\n &lt;/ContentTemplate&gt;\n &lt;/asp:RoleGroup&gt;\n &lt;/RoleGroups&gt;\n &lt;/asp:LoginView&gt;\n</code></pre>\n" }, { "answer_id": 211186, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>i think i'm going to have to combine AD authorization with 'features and permissions' tables in the database in order to get the fine-grained control that we need -</p>\n\n<ul>\n<li>use the web.config file to allow only authorized users (via AD groups) to visit the web site</li>\n<li>make a 'features' table listing each page and feature that can be affected, e.g. page 1 edit button, page 2 delete button, page 3 detail grid, etc.</li>\n<li>make a 'permissions' table specfying a feature and an AD group that is allowed to use the feature</li>\n<li>alter the site pages to check feature-permissions on page-load (or prerender, as appropriate) to disable/hide forbidden features as appropriate</li>\n</ul>\n\n<p>examples: </p>\n\n<ul>\n<li>Administrators can use all features of the site</li>\n<li>Developers can use all features of the site</li>\n<li>Managers can view all pages, but can only add and edit information, no deletions</li>\n<li>Supervisors can view summaries for all departments, but see and edit details only for their own department (there is an AD group for each department and dept-supervisor)</li>\n<li>Staff can view details only for their department</li>\n<li>etc.</li>\n</ul>\n\n<p>The final solution reduced the notion of 'feature' to a binary can-use or cannot-use decision, and added a 'permissive/not-permissive' flag to each feature. This allows features that most everyone can use to be defined as 'permissive', and then the permissions table only has to record the groups that are denied permission to use that feature. For a feature defined as not-permissive, by default no one can use the feature and you have to create permission table entries for the groups that are allowed to use the feature. This seems to give a best-of-both-worlds solution in that it reduces the number of permission records required for each feature.</p>\n" }, { "answer_id": 382235, "author": "JoshRivers", "author_id": 23276, "author_profile": "https://Stackoverflow.com/users/23276", "pm_score": 2, "selected": false, "text": "<p>I think what you need to do here is implement a set of permissions query methods in either your business objects or your controller. Examples: CanRead(), CanEdit(), CanDelete()</p>\n\n<p>When the page renders, it needs to query the business object and determine the users authorized capabilities and enable or disable functionality based on this information. The business object can, in turn, use Roles or additional database queries to determine the active user's permissions.</p>\n\n<p>I can't think of a way to declaratively define these permissions centrally. They need to be distributed into the implementation of the functions. If you want do improve the design, however, you could use dependency injection to insert authorizers into your business objects and thus keep the implementations separate.</p>\n\n<p>There's some code that uses this model in Rocky Lhotka's book. The new version isn't in <a href=\"http://books.google.com/books?id=AS7zAQaKt-oC&amp;pg=PA303&amp;lpg=PA303&amp;dq=ApplyAuthorizationRules()&amp;source=web&amp;ots=KAM2jFW5DR&amp;sig=CH2iXpBw1K5i5zSnyA8sEJWjKlM&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=7&amp;ct=result\" rel=\"nofollow noreferrer\">Google</a> yet.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
I have an ASP.NET 2.0 [no ajax...yet] web site that will be deployed in compiled form on multiple customer sites. Typically the site will be intranet only. Some customers trust all of their people and don't care about limiting access to the site and/or page functions, others trust no one and want only certain people and/or groups to be able to view certain pages, click certain buttons, et al. i could do some home-grown solution, possibly drive the access permissions from a database table, but before i go down that road i thought i'd ask in SO: what is a good solution for this situation? preferably one that can be controlled completedly in the web.config file and/or database, since rebuilding the web site is not possible (for the client, and i don't want to have to do it for them over and over). Active Directory integration would be a bonus, but not a requirement (unless that's just easier). as a starting point, i'm thinking that each page/function point in the site be given an identity and associated with a permission group... EDIT: web.config authorization section to allow/deny access by role and user is good, but that is only half of the problem - the other half is controlling access to the individual methods (buttons, whatever) on each page. For example, some users can view whatchamacallits while others are allowed to edit, create, delete, or disable/enable them. All of these buttons/links/actions are on the view page... [ideally i would make the disabled buttons invisible, but that is not important here] EDIT: some good suggestions so far, but no complete solution yet - still leaning towards a database-driven solution... * security permission demand attributes will throw exceptions when buttons are clicked, which is not a friendly thing to do; i'd much rather hide buttons that the user is not allowed to use * the LoginView control is also interesting, but would require replicating most of the page content several times (once for each role) and may not handle the case where a user is in more than one role - i cannot assume that the roles are hierarchical since they will be defined by the customer EDIT: platform is Win2K/XP, Sql Server 2005, ASP.NET 2.0, not using AJAX
I prefer to grant access rights to AD groups rather than specific users. I find it's much more flexible. I don't know much about your application, but you might want to look at the authorization tag in the web.config file: ``` <authorization> <!-- <deny users="?" /> <allow users="[comma separated list of users]" roles="[comma separated list of roles]"/> <deny users="[comma separated list of users]" roles="[comma separated list of roles]"/> --> </authorization> ``` You can separate web.config files each directory within your web application, and you can nest directories. Each web.config file can have it's own authorization section. If you put different pages in each directory you can effectively tightly manage security by allowing a specific role in each web.config, and denying everything else. Then you can manage members of each role in active directory. I've found this to be an affective solution because it makes good use of Microsoft's Active Directory and ASP.NET security framework without writing your own custom stuff, and if you use roles, it's possible to offload the management of role membership to someone who doesn't ever have to touch the web.config file they just need to know how to use the AD management console.
176,343
<p>Perl 6 seems to have an explosion of equality operators. What is <code>=:=</code>? What's the difference between <code>leg</code> and <code>cmp</code>? Or <code>eqv</code> and <code>===</code>?</p> <p>Does anyone have a good summary?</p>
[ { "answer_id": 176381, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 7, "selected": true, "text": "<p><a href=\"http://doc.perl6.org/routine/%3D%3A%3D\" rel=\"noreferrer\">=:=</a> tests if two containers (variables or items of arrays or hashes) are aliased, ie if one changes, does the other change as well?</p>\n\n<pre><code>my $x;\nmy @a = 1, 2, 3;\n# $x =:= @a[0] is false\n$x := @a[0];\n# now $x == 1, and $x =:= @a[0] is true\n$x = 4;\n# now @a is 4, 2, 3 \n</code></pre>\n\n<p>As for the others: <a href=\"http://doc.perl6.org/routine/%3D%3D%3D\" rel=\"noreferrer\">===</a> tests if two references point to the same object, and <a href=\"http://doc.perl6.org/routine/eqv\" rel=\"noreferrer\">eqv</a> tests if two things are structurally equivalent. So <code>[1, 2, 3] === [1, 2, 3]</code> will be false (not the same array), but <code>[1, 2, 3] eqv [1, 2, 3]</code> will be true (same structure).</p>\n\n<p><code>leg</code> compares strings like Perl 5's <code>cmp</code>, while Perl 6's <code>cmp</code> is smarter and will compare numbers like <code>&lt;=&gt;</code> and strings like <code>leg</code>.</p>\n\n<pre><code>13 leg 4 # -1, because 1 is smaller than 4, and leg converts to string\n13 cmp 4 # +1, because both are numbers, so use numeric comparison.\n</code></pre>\n\n<p>Finally <code>~~</code> is the \"smart match\", it answers the question \"does <code>$x</code> match <code>$y</code>\". If <code>$y</code> is a type, it's type check. If <code>$y</code> is a regex, it's regex match - and so on.</p>\n" }, { "answer_id": 177306, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": false, "text": "<p>Does the summary in <a href=\"http://design.perl6.org/S03.html#Comparison_semantics\" rel=\"noreferrer\">Synopsis 3: Comparison semantics</a> do what you want, or were you already reading that? The design docs link to the test files where those features are used, so you can see examples of their use and their current test state.</p>\n\n<p>Perl 6's comparison operators are much more suited to a dynamic language and all of the things going on. Instead of just comparing strings or numbers (or turning things into strings or numbers), now you can test things precisely with an operator that does what you want. You can test the value, the container, the type, and so on.</p>\n\n<p>In one of the comments, you ask about <code>eqv</code> and <code>cmp</code>. In the old days of Perl 5, <code>cmp</code> was there for sorting and returns one of three magic values (-1,0,1), and it did that with string semantics always. In Perl 6, <code>cmp</code> returns one of three types of <code>Order</code> objects, so you don't have to remember what -1, 0, or 1 means. Also, the new <code>cmp</code> doesn't force string semantics, so it can be smarter when handed numbers (unlike Perl 5's which would sort like 1, 10, 11, 2, 20, 21 ...).</p>\n\n<p>The <code>leg</code> (<b>l</b>ess than, <b>e</b>qual, <b>g</b>reater than) is <code>cmp</code> with string semantics. It's defined as Perl 6's <code>~$a cmp ~$b</code>, where <code>~</code> is the new \"string contextualizer\" that forces string semantics. With <code>leg</code>, you are always doing a string comparison, just like the old Perl 5 <code>cmp</code>.</p>\n\n<p>If you still have questions on the other operators, let's break them down into separate questions. :)</p>\n" }, { "answer_id": 2638341, "author": "Ether", "author_id": 40468, "author_profile": "https://Stackoverflow.com/users/40468", "pm_score": 2, "selected": false, "text": "<p>This is also a handy reference guide:</p>\n\n<p><a href=\"http://www.ozonehouse.com/mark/periodic/\" rel=\"nofollow noreferrer\">Perl6 Periodic Table of Operators</a></p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Perl 6 seems to have an explosion of equality operators. What is `=:=`? What's the difference between `leg` and `cmp`? Or `eqv` and `===`? Does anyone have a good summary?
[=:=](http://doc.perl6.org/routine/%3D%3A%3D) tests if two containers (variables or items of arrays or hashes) are aliased, ie if one changes, does the other change as well? ``` my $x; my @a = 1, 2, 3; # $x =:= @a[0] is false $x := @a[0]; # now $x == 1, and $x =:= @a[0] is true $x = 4; # now @a is 4, 2, 3 ``` As for the others: [===](http://doc.perl6.org/routine/%3D%3D%3D) tests if two references point to the same object, and [eqv](http://doc.perl6.org/routine/eqv) tests if two things are structurally equivalent. So `[1, 2, 3] === [1, 2, 3]` will be false (not the same array), but `[1, 2, 3] eqv [1, 2, 3]` will be true (same structure). `leg` compares strings like Perl 5's `cmp`, while Perl 6's `cmp` is smarter and will compare numbers like `<=>` and strings like `leg`. ``` 13 leg 4 # -1, because 1 is smaller than 4, and leg converts to string 13 cmp 4 # +1, because both are numbers, so use numeric comparison. ``` Finally `~~` is the "smart match", it answers the question "does `$x` match `$y`". If `$y` is a type, it's type check. If `$y` is a regex, it's regex match - and so on.
176,347
<p>I read some of the answers on here re: testing views and controllers, and mocking, but I still can't figure out how to test an ASP.NET MVC controller that reads and sets Session values (or any other context based variables.) How do I provide a (Session) context for my test methods? Is mocking the answer? Anybody have examples? Basically, I'd like to fake a session before I call the controller method and have the controller use that session. Any ideas?</p>
[ { "answer_id": 176390, "author": "chadmyers", "author_id": 10862, "author_profile": "https://Stackoverflow.com/users/10862", "pm_score": 4, "selected": false, "text": "<p>The ASP.NET MVC framework is not very mock-friendly (or rather, requires too much setup to mock properly, and causes too much friction when testing, IMHO) due to it's use of abstract base classes instead of interfaces. We've had good luck writing abstractions for per-request and session-based storage. We keep those abstractions very light and then our controllers depend upon those abstractions for per-request or per-session storage.</p>\n\n<p>For example, here's how we manage the forms auth stuff. We have an ISecurityContext:</p>\n\n<pre><code>public interface ISecurityContext\n{\n bool IsAuthenticated { get; }\n IIdentity CurrentIdentity { get; }\n IPrincipal CurrentUser { get; set; }\n}\n</code></pre>\n\n<p>With a concrete implementation like:</p>\n\n<pre><code>public class SecurityContext : ISecurityContext\n{\n private readonly HttpContext _context;\n\n public SecurityContext()\n {\n _context = HttpContext.Current;\n }\n\n public bool IsAuthenticated\n {\n get { return _context.Request.IsAuthenticated; }\n }\n\n public IIdentity CurrentIdentity\n {\n get { return _context.User.Identity; }\n }\n\n public IPrincipal CurrentUser\n {\n get { return _context.User; }\n set { _context.User = value; }\n }\n}\n</code></pre>\n" }, { "answer_id": 176447, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 2, "selected": false, "text": "<p>Scott Hanselman has a post about how to <a href=\"http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx\" rel=\"nofollow noreferrer\">create a file upload</a> quickapp with MVC and discusses moking and specifically addresses \"How to mock things that aren't mock friendly.\"</p>\n" }, { "answer_id": 176554, "author": "Korbin", "author_id": 17902, "author_profile": "https://Stackoverflow.com/users/17902", "pm_score": 3, "selected": false, "text": "<p>I found mocking to be fairly easy. Here is an example of mocking the httpContextbase (that contains the request, session and response objects) using moq.</p>\n\n<pre><code>[TestMethod]\n public void HowTo_CheckSession_With_TennisApp() {\n var request = new Mock&lt;HttpRequestBase&gt;();\n request.Expect(r =&gt; r.HttpMethod).Returns(\"GET\"); \n\n var httpContext = new Mock&lt;HttpContextBase&gt;();\n var session = new Mock&lt;HttpSessionStateBase&gt;();\n\n httpContext.Expect(c =&gt; c.Request).Returns(request.Object);\n httpContext.Expect(c =&gt; c.Session).Returns(session.Object);\n\n session.Expect(c =&gt; c.Add(\"test\", \"something here\")); \n\n var playerController = new NewPlayerSignupController();\n memberController.ControllerContext = new ControllerContext(new RequestContext(httpContext.Object, new RouteData()), playerController); \n\n session.VerifyAll(); // function is trying to add the desired item to the session in the constructor\n //TODO: Add Assertions \n }\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 238370, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 6, "selected": true, "text": "<p>Check out Stephen Walther's post on Faking the Controller Context:</p>\n\n<p><a href=\"http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx\" rel=\"noreferrer\">ASP.NET MVC Tip #12 – Faking the Controller Context</a></p>\n\n<pre><code>[TestMethod]\npublic void TestSessionState()\n{\n // Create controller\n var controller = new HomeController();\n\n\n // Create fake Controller Context\n var sessionItems = new SessionStateItemCollection();\n sessionItems[\"item1\"] = \"wow!\";\n controller.ControllerContext = new FakeControllerContext(controller, sessionItems);\n var result = controller.TestSession() as ViewResult;\n\n\n // Assert\n Assert.AreEqual(\"wow!\", result.ViewData[\"item1\"]);\n\n // Assert\n Assert.AreEqual(\"cool!\", controller.HttpContext.Session[\"item2\"]);\n}\n</code></pre>\n" }, { "answer_id": 558006, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 3, "selected": false, "text": "<p>With MVC RC 1 the ControllerContext wraps the HttpContext and exposes it as a property. This makes mocking much easier. To mock a session variable with Moq do the following:</p>\n\n<pre><code>var controller = new HomeController();\nvar context = MockRepository.GenerateStub&lt;ControllerContext&gt;();\ncontext.Expect(x =&gt; x.HttpContext.Session[\"MyKey\"]).Return(\"MyValue\");\ncontroller.ControllerContext = context;\n</code></pre>\n\n<p>See <a href=\"http://weblogs.asp.net/scottgu/archive/2009/01/27/asp-net-mvc-1-0-release-candidate-now-available.aspx\" rel=\"noreferrer\">Scott Gu's post</a> for more details.</p>\n" }, { "answer_id": 785056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Because HttpContext is static, I use Typemock Isolator to mock it, Typemock also has an Add-in custom built for <a href=\"http://www.typemock.com/ASP.NET_unit_testing_page.php\" rel=\"nofollow noreferrer\">ASP.NET unit testing</a> called <a href=\"http://sm-art.biz/Ivonna.aspx\" rel=\"nofollow noreferrer\">Ivonna</a> .</p>\n" }, { "answer_id": 9860514, "author": "Mathias Lykkegaard Lorenzen", "author_id": 553609, "author_profile": "https://Stackoverflow.com/users/553609", "pm_score": 2, "selected": false, "text": "<p>I used the following solution - making a controller that all my other controllers inherit from.</p>\n\n<pre><code>public class TestableController : Controller\n{\n\n public new HttpSessionStateBase Session\n {\n get\n {\n if (session == null)\n {\n session = base.Session ?? new CustomSession();\n }\n return session;\n }\n }\n private HttpSessionStateBase session;\n\n public class CustomSession : HttpSessionStateBase\n {\n\n private readonly Dictionary&lt;string, object&gt; dictionary; \n\n public CustomSession()\n {\n dictionary = new Dictionary&lt;string, object&gt;();\n }\n\n public override object this[string name]\n {\n get\n {\n if (dictionary.ContainsKey(name))\n {\n return dictionary[name];\n } else\n {\n return null;\n }\n }\n set\n {\n if (!dictionary.ContainsKey(name))\n {\n dictionary.Add(name, value);\n }\n else\n {\n dictionary[name] = value;\n }\n }\n }\n\n //TODO: implement other methods here as needed to forefil the needs of the Session object. the above implementation was fine for my needs.\n\n }\n\n}\n</code></pre>\n\n<p>Then use the code as follows:</p>\n\n<pre><code>public class MyController : TestableController { }\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
I read some of the answers on here re: testing views and controllers, and mocking, but I still can't figure out how to test an ASP.NET MVC controller that reads and sets Session values (or any other context based variables.) How do I provide a (Session) context for my test methods? Is mocking the answer? Anybody have examples? Basically, I'd like to fake a session before I call the controller method and have the controller use that session. Any ideas?
Check out Stephen Walther's post on Faking the Controller Context: [ASP.NET MVC Tip #12 – Faking the Controller Context](http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx) ``` [TestMethod] public void TestSessionState() { // Create controller var controller = new HomeController(); // Create fake Controller Context var sessionItems = new SessionStateItemCollection(); sessionItems["item1"] = "wow!"; controller.ControllerContext = new FakeControllerContext(controller, sessionItems); var result = controller.TestSession() as ViewResult; // Assert Assert.AreEqual("wow!", result.ViewData["item1"]); // Assert Assert.AreEqual("cool!", controller.HttpContext.Session["item2"]); } ```
176,373
<p>We are trying to make a project template, but the documentation on this is spotty or non-existent.</p> <p>Doing some reverse-engineering on some template files, we have come up with the following. However, it doen't actually work!</p> <p>First of all, we have figured out that project templates should be installed inside:</p> <p>~/Library/Application Support/Developer/Shared/Xcode/Project Templates</p> <p>We have made project and installed it here, and this part works - we see this show up in the "User Templates" section of the Xcode "New Project" chooser.</p> <p>The project folder contains the following files. As you can see, I want the file names to be subsituted (that part works) but as you will see, I also want the contents of the files to be substituted; this doesn't happen.</p> <ul> <li>___PROJECTNAME___.xcodeproj </li> <li>___PROJECTNAMEASIDENTIFIER____Prefix.pch </li> <li>___PROJECTNAMEASIDENTIFIER___.icns </li> <li>___PROJECTNAMEASIDENTIFIER___Delegate.h </li> <li>___PROJECTNAMEASIDENTIFIER___Delegate.m </li> <li>___PROJECTNAMEASIDENTIFIER___Template.html </li> <li>Debug.xcconfig </li> <li>en.lproj </li> <li>Info.plist </li> <li>Release.xcconfig </li> </ul> <p>I have put in two special files into the ___PROJECTNAME___.xcodeproj package:</p> <ul> <li>TemplateInfo.plist </li> <li>TemplateIcon.icns - the icon to show up in the New Project window</li> </ul> <p>If I create a new project (called "Foo &amp; Bar" as a stress test) using this template, these are the files it creates:</p> <ul> <li>Debug.xcconfig</li> <li>en.lproj</li> <li>Foo &amp; Bar.xcodeproj</li> <li>Foo___Bar_Prefix.pch</li> <li>Foo___Bar.icns</li> <li>Foo___BarDelegate.h</li> <li>Foo___BarDelegate.m</li> <li>Foo___BarTemplate.html</li> <li>Info.plist</li> <li>Release.xcconfig</li> </ul> <p>So far so good! </p> <p>But looking in the file contents, I get things like this. Here is the contents of Foo___BarDelegate.m:</p> <pre><code>// // «PROJECTNAMEASIDENTIFIER»Delegate.m // «PROJECTNAME» // // Created by «FULLUSERNAME» on «DATE». // Copyright «ORGANIZATIONNAME» «YEAR» . All rights reserved. // #import "«PROJECTNAMEASIDENTIFIER»Delegate.h" @implementation «PROJECTNAMEASIDENTIFIER»Delegate @end </code></pre> <p>The apparent issue is that somehow I'm doing the TemplateInfo.plist wrong. But then again, notice how not only are my special items not being substitued, but the standard items don't even get replaced! So maybe it's a deeper issue.</p> <p>But with a problematic TemplateInfo.plist being my best hypothesis, I present a couple of variations I have tried. Neither work.</p> <p>Either:</p> <pre><code>{ FilesToMacroExpand = ( "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_\_Prefix.pch", "en.lproj/InfoPlist.strings", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_\_Prefix.pch", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_.icns", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Delegate.h", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Delegate.m", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Template.html", "Info.plist" ); Description = "This project builds a cocoa-based \"element\" plugin for Sandvox."; } </code></pre> <p>or:</p> <pre><code>{ FilesToMacroExpand = ( "«PROJECTNAMEASIDENTIFIER»\_Prefix.pch", "en.lproj/InfoPlist.strings", "«PROJECTNAMEASIDENTIFIER»\_Prefix.pch", "«PROJECTNAMEASIDENTIFIER».icns", "«PROJECTNAMEASIDENTIFIER»Delegate.h", "«PROJECTNAMEASIDENTIFIER»Delegate.m", "«PROJECTNAMEASIDENTIFIER»Template.html", "Info.plist" ); Description = "This project builds a cocoa-based \"element\" plugin for Sandvox."; } </code></pre> <p><strong>Update</strong>: I've also tried adding the "FilesToRename" key, even though the ___ seems to be automatically causing renaming to happen. This is the plist contents with that in, in XML format (since some people were worried about that UTF-8 nature of things -- yes, it's a valid plist):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Description&lt;/key&gt; &lt;string&gt;This project builds a cocoa-based "element" plugin for Sandvox.&lt;/string&gt; &lt;key&gt;FilesToMacroExpand&lt;/key&gt; &lt;array&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»_Prefix.pch&lt;/string&gt; &lt;string&gt;en.lproj/InfoPlist.strings&lt;/string&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER».icns&lt;/string&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Delegate.h&lt;/string&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Delegate.m&lt;/string&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Template.html&lt;/string&gt; &lt;string&gt;Info.plist&lt;/string&gt; &lt;/array&gt; &lt;key&gt;FilesToRename&lt;/key&gt; &lt;dict&gt; &lt;key&gt;___PROJECTNAMEASIDENTIFIER___.icns&lt;/key&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER».icns&lt;/string&gt; &lt;key&gt;___PROJECTNAMEASIDENTIFIER___Delegate.h&lt;/key&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Delegate.h&lt;/string&gt; &lt;key&gt;___PROJECTNAMEASIDENTIFIER___Delegate.m&lt;/key&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Delegate.m&lt;/string&gt; &lt;key&gt;___PROJECTNAMEASIDENTIFIER___Template.html&lt;/key&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Template.html&lt;/string&gt; &lt;key&gt;___PROJECTNAMEASIDENTIFIER____Prefix.pch&lt;/key&gt; &lt;string&gt;«PROJECTNAMEASIDENTIFIER»_Prefix.pch&lt;/string&gt; &lt;key&gt;___PROJECTNAME___.xcodeproj&lt;/key&gt; &lt;string&gt;«PROJECTNAME».xcodeproj&lt;/string&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre>
[ { "answer_id": 176420, "author": "bbum", "author_id": 25646, "author_profile": "https://Stackoverflow.com/users/25646", "pm_score": 2, "selected": false, "text": "<p>You likely want to use a \"FilesToRename\" section. The following is from the PyObjC Cocoa Document Based Application template. It works fine.</p>\n\n<pre><code> &lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"&gt;\n&lt;plist version=\"1.0\"&gt;\n&lt;dict&gt;\n &lt;key&gt;Description&lt;/key&gt;\n &lt;string&gt;This project builds a Cocoa-based application written in Python that uses the NSDocument architecture.&lt;/string&gt;\n &lt;key&gt;FilesToMacroExpand&lt;/key&gt;\n &lt;array&gt;\n &lt;string&gt;«PROJECTNAME»_Prefix.pch&lt;/string&gt;\n &lt;string&gt;Info.plist&lt;/string&gt;\n &lt;string&gt;English.lproj/InfoPlist.strings&lt;/string&gt;\n &lt;string&gt;English.lproj/MainMenu.xib&lt;/string&gt;\n &lt;string&gt;English.lproj/«PROJECTNAMEASIDENTIFIER»Document.xib&lt;/string&gt;\n &lt;string&gt;main.py&lt;/string&gt;\n &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Document.py&lt;/string&gt;\n &lt;string&gt;main.m&lt;/string&gt;\n &lt;/array&gt;\n &lt;key&gt;FilesToRename&lt;/key&gt;\n &lt;dict&gt;\n &lt;key&gt;CocoaAppDocument.py&lt;/key&gt;\n &lt;string&gt;«PROJECTNAMEASIDENTIFIER»Document.py&lt;/string&gt;\n &lt;key&gt;CocoaDocApp_Prefix.pch&lt;/key&gt;\n &lt;string&gt;«PROJECTNAMEASIDENTIFIER»_Prefix.pch&lt;/string&gt;\n &lt;key&gt;English.lproj/CocoaAppDocument.xib&lt;/key&gt;\n &lt;string&gt;English.lproj/«PROJECTNAMEASIDENTIFIER»Document.xib&lt;/string&gt;\n &lt;/dict&gt;\n&lt;/dict&gt;\n&lt;/plist&gt;\n</code></pre>\n" }, { "answer_id": 176515, "author": "rentzsch", "author_id": 5260, "author_profile": "https://Stackoverflow.com/users/5260", "pm_score": 2, "selected": false, "text": "<p>Another resource is Jesse Grosjean's <a href=\"http://hogbaysoftware.com/products/xcodetemplatefactory\" rel=\"nofollow noreferrer\">XcodeTemplateFactory</a>. It's free and open source and may save you future headaches.</p>\n" }, { "answer_id": 180642, "author": "cdespinosa", "author_id": 25972, "author_profile": "https://Stackoverflow.com/users/25972", "pm_score": 2, "selected": false, "text": "<p>There are two styles of templates, distinguished by the template macro delimiters: old-style uses MacRoman guillamots in a UTF-8 file, and the new style uses triple underbars throughout. You can't mix and match. The new style is for 3.1 and later only, and you must use the triple underbars in the file names to be substituted as well.</p>\n" }, { "answer_id": 181758, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 2, "selected": false, "text": "<p>Further to Chris' answer (\"There are two styles of templates...\"), you can find examples of the new style in the templates for another platform...</p>\n\n<p>The following excerpt shows examples of a few typical substitution variables using triple underbars; if you use these in place of the guillamot-based variables in your Foo___BarDelegate.m, it should work.</p>\n\n<pre><code>//\n// ___PROJECTNAMEASIDENTIFIER___AppDelegate.m\n// ___PROJECTNAME___\n//\n// Created by ___FULLUSERNAME___ on ___DATE___.\n// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.\n//\n\n#import \"___PROJECTNAMEASIDENTIFIER___AppDelegate.h\"\n\n@implementation ___PROJECTNAMEASIDENTIFIER___AppDelegate\n</code></pre>\n" }, { "answer_id": 1469219, "author": "Puneet Madaan", "author_id": 178168, "author_profile": "https://Stackoverflow.com/users/178168", "pm_score": 0, "selected": false, "text": "<p>Why are you missing those \"&lt;&lt;\" like symbols? Thats the reason why <code>xcode</code> is not recognizing and replacing template tags..</p>\n" }, { "answer_id": 1471351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was just bangin my head on same problem!</p>\n\n<p>For me, adding files in plist works, I changed html file with php file and it is parsed. \nBut now it does parse only few first items from list. \nOld html file is still: «PROJECTNAME»\nLike this program does not count how many items there is in a list... </p>\n\n<p>But where is the place in code, where it doesn't do that... ?</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25560/" ]
We are trying to make a project template, but the documentation on this is spotty or non-existent. Doing some reverse-engineering on some template files, we have come up with the following. However, it doen't actually work! First of all, we have figured out that project templates should be installed inside: ~/Library/Application Support/Developer/Shared/Xcode/Project Templates We have made project and installed it here, and this part works - we see this show up in the "User Templates" section of the Xcode "New Project" chooser. The project folder contains the following files. As you can see, I want the file names to be subsituted (that part works) but as you will see, I also want the contents of the files to be substituted; this doesn't happen. * \_\_\_PROJECTNAME\_\_\_.xcodeproj * \_\_\_PROJECTNAMEASIDENTIFIER\_\_\_\_Prefix.pch * \_\_\_PROJECTNAMEASIDENTIFIER\_\_\_.icns * \_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Delegate.h * \_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Delegate.m * \_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Template.html * Debug.xcconfig * en.lproj * Info.plist * Release.xcconfig I have put in two special files into the \_\_\_PROJECTNAME\_\_\_.xcodeproj package: * TemplateInfo.plist * TemplateIcon.icns - the icon to show up in the New Project window If I create a new project (called "Foo & Bar" as a stress test) using this template, these are the files it creates: * Debug.xcconfig * en.lproj * Foo & Bar.xcodeproj * Foo\_\_\_Bar\_Prefix.pch * Foo\_\_\_Bar.icns * Foo\_\_\_BarDelegate.h * Foo\_\_\_BarDelegate.m * Foo\_\_\_BarTemplate.html * Info.plist * Release.xcconfig So far so good! But looking in the file contents, I get things like this. Here is the contents of Foo\_\_\_BarDelegate.m: ``` // // «PROJECTNAMEASIDENTIFIER»Delegate.m // «PROJECTNAME» // // Created by «FULLUSERNAME» on «DATE». // Copyright «ORGANIZATIONNAME» «YEAR» . All rights reserved. // #import "«PROJECTNAMEASIDENTIFIER»Delegate.h" @implementation «PROJECTNAMEASIDENTIFIER»Delegate @end ``` The apparent issue is that somehow I'm doing the TemplateInfo.plist wrong. But then again, notice how not only are my special items not being substitued, but the standard items don't even get replaced! So maybe it's a deeper issue. But with a problematic TemplateInfo.plist being my best hypothesis, I present a couple of variations I have tried. Neither work. Either: ``` { FilesToMacroExpand = ( "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_\_Prefix.pch", "en.lproj/InfoPlist.strings", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_\_Prefix.pch", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_.icns", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Delegate.h", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Delegate.m", "\_\_\_PROJECTNAMEASIDENTIFIER\_\_\_Template.html", "Info.plist" ); Description = "This project builds a cocoa-based \"element\" plugin for Sandvox."; } ``` or: ``` { FilesToMacroExpand = ( "«PROJECTNAMEASIDENTIFIER»\_Prefix.pch", "en.lproj/InfoPlist.strings", "«PROJECTNAMEASIDENTIFIER»\_Prefix.pch", "«PROJECTNAMEASIDENTIFIER».icns", "«PROJECTNAMEASIDENTIFIER»Delegate.h", "«PROJECTNAMEASIDENTIFIER»Delegate.m", "«PROJECTNAMEASIDENTIFIER»Template.html", "Info.plist" ); Description = "This project builds a cocoa-based \"element\" plugin for Sandvox."; } ``` **Update**: I've also tried adding the "FilesToRename" key, even though the \_\_\_ seems to be automatically causing renaming to happen. This is the plist contents with that in, in XML format (since some people were worried about that UTF-8 nature of things -- yes, it's a valid plist): ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Description</key> <string>This project builds a cocoa-based "element" plugin for Sandvox.</string> <key>FilesToMacroExpand</key> <array> <string>«PROJECTNAMEASIDENTIFIER»_Prefix.pch</string> <string>en.lproj/InfoPlist.strings</string> <string>«PROJECTNAMEASIDENTIFIER».icns</string> <string>«PROJECTNAMEASIDENTIFIER»Delegate.h</string> <string>«PROJECTNAMEASIDENTIFIER»Delegate.m</string> <string>«PROJECTNAMEASIDENTIFIER»Template.html</string> <string>Info.plist</string> </array> <key>FilesToRename</key> <dict> <key>___PROJECTNAMEASIDENTIFIER___.icns</key> <string>«PROJECTNAMEASIDENTIFIER».icns</string> <key>___PROJECTNAMEASIDENTIFIER___Delegate.h</key> <string>«PROJECTNAMEASIDENTIFIER»Delegate.h</string> <key>___PROJECTNAMEASIDENTIFIER___Delegate.m</key> <string>«PROJECTNAMEASIDENTIFIER»Delegate.m</string> <key>___PROJECTNAMEASIDENTIFIER___Template.html</key> <string>«PROJECTNAMEASIDENTIFIER»Template.html</string> <key>___PROJECTNAMEASIDENTIFIER____Prefix.pch</key> <string>«PROJECTNAMEASIDENTIFIER»_Prefix.pch</string> <key>___PROJECTNAME___.xcodeproj</key> <string>«PROJECTNAME».xcodeproj</string> </dict> </dict> </plist> ```
You likely want to use a "FilesToRename" section. The following is from the PyObjC Cocoa Document Based Application template. It works fine. ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Description</key> <string>This project builds a Cocoa-based application written in Python that uses the NSDocument architecture.</string> <key>FilesToMacroExpand</key> <array> <string>«PROJECTNAME»_Prefix.pch</string> <string>Info.plist</string> <string>English.lproj/InfoPlist.strings</string> <string>English.lproj/MainMenu.xib</string> <string>English.lproj/«PROJECTNAMEASIDENTIFIER»Document.xib</string> <string>main.py</string> <string>«PROJECTNAMEASIDENTIFIER»Document.py</string> <string>main.m</string> </array> <key>FilesToRename</key> <dict> <key>CocoaAppDocument.py</key> <string>«PROJECTNAMEASIDENTIFIER»Document.py</string> <key>CocoaDocApp_Prefix.pch</key> <string>«PROJECTNAMEASIDENTIFIER»_Prefix.pch</string> <key>English.lproj/CocoaAppDocument.xib</key> <string>English.lproj/«PROJECTNAMEASIDENTIFIER»Document.xib</string> </dict> </dict> </plist> ```
176,403
<p>In C++/CLI , you can use native types in a managed class by it is not allowed to hold a member of a native class in a managed class : you need to use pointers in that case.</p> <p>Here is an example :</p> <pre><code>class NativeClass { .... }; public ref class ManagedClass { private: NativeClass mNativeClass; // Not allowed ! NativeClass * mNativeClass; // OK auto_ptr&lt;NativeClass&gt; mNativeClass; //Not allowed ! boost::shared_ptr&lt;NativeClass&gt; mNativeClass; //Not allowed ! }; </code></pre> <p>Does anyone know of an equivalent of shared_ptr in the C++/CLI world?</p> <p>Edit: Thanks for your suggestion, "1800-Information". Following your suggestion, I checked about STL.Net but it is only available with Visual Studio 2008, and it provides containers + algorithms, but no smart pointers.</p>
[ { "answer_id": 176450, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms379600.aspx\" rel=\"nofollow noreferrer\">STL.Net is documented here</a>. I don't know what state it is in or what use it might be for you.</p>\n" }, { "answer_id": 176654, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 3, "selected": true, "text": "<p>I found the answer on <a href=\"http://www.codeproject.com\" rel=\"nofollow noreferrer\">codeproject</a> :</p>\n\n<p>Nishant Sivakumar posted an article about this at <a href=\"http://www.codeproject.com/KB/mcpp/CAutoNativePtr.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/mcpp/CAutoNativePtr.aspx</a></p>\n\n<p>On this page, also look for the comment by Denis N. Shevchenko : he provides a stl-like implementation that works quite well.</p>\n" }, { "answer_id": 12643978, "author": "chillitom", "author_id": 56679, "author_profile": "https://Stackoverflow.com/users/56679", "pm_score": 2, "selected": false, "text": "<p>I haven't thoroughly tested this but how about something like the following:</p>\n\n<pre><code>#pragma once\n\n#include &lt;memory&gt;\n\ntemplate &lt;class T&gt;\npublic ref class m_shared_ptr sealed\n{\n std::shared_ptr&lt;T&gt;* pPtr;\n\npublic:\n m_shared_ptr() \n : pPtr(nullptr) \n {}\n\n m_shared_ptr(T* t) {\n pPtr = new std::shared_ptr&lt;T&gt;(t);\n }\n\n m_shared_ptr(std::shared_ptr&lt;T&gt; t) {\n pPtr = new std::shared_ptr&lt;T&gt;(t);\n }\n\n m_shared_ptr(const m_shared_ptr&lt;T&gt;% t) {\n pPtr = new std::shared_ptr&lt;T&gt;(*t.pPtr);\n }\n\n !m_shared_ptr() {\n delete pPtr;\n }\n\n ~m_shared_ptr() {\n delete pPtr;\n }\n\n operator std::shared_ptr&lt;T&gt;() {\n return *pPtr;\n }\n\n m_shared_ptr&lt;T&gt;% operator=(T* ptr) {\n pPtr = new std::shared_ptr&lt;T&gt;(ptr);\n return *this;\n }\n\n T* operator-&gt;() {\n return (*pPtr).get();\n }\n};\n</code></pre>\n\n<p>This should let you use C++11/Boost's shared_ptrs interchangebly in ref classes.</p>\n" }, { "answer_id": 71784151, "author": "Lars", "author_id": 42809, "author_profile": "https://Stackoverflow.com/users/42809", "pm_score": 0, "selected": false, "text": "<p>For those who come here and looking for a managed <code>auto_ptr</code>:</p>\n<pre><code>#include &lt;msclr/auto_gcroot.h&gt;\n\n...\n{\n msclr::auto_gcroot&lt;ManagedType^&gt; item(gcnew ManagedType());\n ...\n}\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/en-us/cpp/dotnet/auto-gcroot-class\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/cpp/dotnet/auto-gcroot-class</a></p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19816/" ]
In C++/CLI , you can use native types in a managed class by it is not allowed to hold a member of a native class in a managed class : you need to use pointers in that case. Here is an example : ``` class NativeClass { .... }; public ref class ManagedClass { private: NativeClass mNativeClass; // Not allowed ! NativeClass * mNativeClass; // OK auto_ptr<NativeClass> mNativeClass; //Not allowed ! boost::shared_ptr<NativeClass> mNativeClass; //Not allowed ! }; ``` Does anyone know of an equivalent of shared\_ptr in the C++/CLI world? Edit: Thanks for your suggestion, "1800-Information". Following your suggestion, I checked about STL.Net but it is only available with Visual Studio 2008, and it provides containers + algorithms, but no smart pointers.
I found the answer on [codeproject](http://www.codeproject.com) : Nishant Sivakumar posted an article about this at <http://www.codeproject.com/KB/mcpp/CAutoNativePtr.aspx> On this page, also look for the comment by Denis N. Shevchenko : he provides a stl-like implementation that works quite well.
176,411
<p>A question about different methods of outputting html from PHP; what are the performance differences between these:</p> <p>Method 1 - variable concatenation</p> <pre><code>$html = ''; $html .= '&lt;ul&gt;'; for ($k = 1; $k &lt; = 1000; $k++){ $html .= '&lt;li&gt; This is list item #'.$k.'&lt;/li&gt;'; } $html .= '&lt;/ul&gt;'; echo $html; </code></pre> <p>Method 2 - output buffering</p> <pre><code>ob_start(); echo '&lt;ul&gt;'; for ($k = 1; $k &lt; = 1000; $k++){ echo '&lt;li&gt; This is list item #',$k,'&lt;/li&gt;'; } echo '&lt;/ul&gt;'; </code></pre> <p>I suspect you get some performance hit from continually modifying and enlarging a variable; is that correct?</p> <p>Cheers!</p> <p>Thanks GaryF, but I don't want an answer about architecture - this question is about performance. There seem to be some different opinions / testing about which one is faster, which is why there is not an accepted answer as yet.</p>
[ { "answer_id": 176434, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<p>I typically use method #1 so I can put that HTML any where in a template file that contains static HTML. I try to keep as much HMTL out of my PHP. It makes for much cleaner and shorter PHP, as the template is usually a separate file.</p>\n\n<p>Regarding speed/performance, I'm thinking the difference will be very minor. With output buffering, it's also enlarging a variable all the time, although that variable isn't accessible, but it has to be stored somewhere.</p>\n\n<p>I have often wondered if open and closing <code>&lt;?php</code> is slower than just putting it all inside <code>&lt;?php</code> and then echo'ing all at once.</p>\n\n<p>I think in the end we are talking milliseconds in extremely complex scripts.</p>\n\n<p>Oh yeah, method #1 is a lot more flexible as you can <code>echo $html;</code> anywhere.</p>\n" }, { "answer_id": 176436, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>It's true that there is a slight overhead in constantly modifying a variable and reprinting it. However, <em>not</em> doing that means that at some point the script may finish running (due to an interruption or similar), and the sequential echo statements will have partially printed the page rather than nothing.</p>\n" }, { "answer_id": 176458, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 1, "selected": false, "text": "<p>I was going to type out a long reply about how PHP strings are mutable (opposed to immutable strings like in C or C#), but I think I'll just link to <a href=\"https://stackoverflow.com/questions/124067/php-string-concatenation-performance#124109\">an older post I came across</a>. I basically deals with what you're asking, in respect to the Java and C# solution of using a stringbuilder.</p>\n\n<p>sidenote: the stringbuilder solution would be similar to (untested):</p>\n\n<pre><code>$html = array();\n$html[] = '&lt;ul&gt;';\nfor ($k = 1; $k &lt; = 1000; $k++){\n $html[] = '&lt;li&gt; This is list item #';\n $html[] = $k;\n $html[] = '&lt;/li&gt;';\n}\n$html[] = '&lt;/ul&gt;';\necho implode('',$html);\n</code></pre>\n" }, { "answer_id": 176465, "author": "Paul Wicks", "author_id": 85, "author_profile": "https://Stackoverflow.com/users/85", "pm_score": 1, "selected": false, "text": "<p>Just a couple of thoughts:</p>\n\n<ul>\n<li><p>Output buffering can make you pages look slow, since the user sees nothing until the entire script has run (although the way you have #1 setup the same would hold true).</p></li>\n<li><p>Strings in php are muteable, so concatenation is not nearly as bad as in some other languages. That being said, Output buffering might be just a tiny bit faster, as the space allocated for the input is fairly large by default (40K according to <a href=\"http://phplens.com/lens/php-book/optimizing-debugging-php.php\" rel=\"nofollow noreferrer\">this</a>)</p></li>\n</ul>\n\n<p>In the end I'd say it's really more a question of style. If you like what output buffering buys you, then it is probably the way to go. </p>\n" }, { "answer_id": 176489, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>Answers to your question can also be found here: <a href=\"https://stackoverflow.com/questions/111282/php-output-w-join-vs-output\">php: output[] w/ join vs $output .=</a></p>\n\n<p>String concatenation is the fastest way to build strings. </p>\n\n<p>I haven't tested \"echo\" vs string building, but as long as you're not using buffered output echo should be the fastest due to sequential writes to a self-flushing buffer. ( only slowdown being in the flush, which you won't really avoid even if you do string-concatenation in advance ) </p>\n" }, { "answer_id": 176499, "author": "GaryF", "author_id": 1035, "author_profile": "https://Stackoverflow.com/users/1035", "pm_score": 3, "selected": false, "text": "<p>The idea of string concatenation itself aside, you're really asking (I think) how you should be building up web pages, and it strikes me that any form of explicit concatentation is probably the wrong thing to do.</p>\n\n<p>Try using the <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"noreferrer\">Model-View-Control pattern</a> to build up your data, and passing it to a simple templating library (like <a href=\"http://www.smarty.net/\" rel=\"noreferrer\">Smarty</a>), and let it worry about how to build your view.</p>\n\n<p>Better separation, fewer concerns.</p>\n" }, { "answer_id": 176904, "author": "Adriano Varoli Piazza", "author_id": 22184, "author_profile": "https://Stackoverflow.com/users/22184", "pm_score": 0, "selected": false, "text": "<p>Something I haven't seen mentioned is that, usually, the PHP guy has to work with design people that need to class the HTML or add styles some other way, so the solution must bear that in mind.</p>\n" }, { "answer_id": 419195, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 3, "selected": true, "text": "<p>It's a bit old, but <a href=\"http://blog.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html\" rel=\"nofollow noreferrer\">this post</a> by Sara Golemon will probably help. AFAIK the output buffering functions are quite fast and efficient and so is <code>echo</code>, so that's what I would use.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2027/" ]
A question about different methods of outputting html from PHP; what are the performance differences between these: Method 1 - variable concatenation ``` $html = ''; $html .= '<ul>'; for ($k = 1; $k < = 1000; $k++){ $html .= '<li> This is list item #'.$k.'</li>'; } $html .= '</ul>'; echo $html; ``` Method 2 - output buffering ``` ob_start(); echo '<ul>'; for ($k = 1; $k < = 1000; $k++){ echo '<li> This is list item #',$k,'</li>'; } echo '</ul>'; ``` I suspect you get some performance hit from continually modifying and enlarging a variable; is that correct? Cheers! Thanks GaryF, but I don't want an answer about architecture - this question is about performance. There seem to be some different opinions / testing about which one is faster, which is why there is not an accepted answer as yet.
It's a bit old, but [this post](http://blog.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html) by Sara Golemon will probably help. AFAIK the output buffering functions are quite fast and efficient and so is `echo`, so that's what I would use.
176,440
<p>I have a filter in a combobox with a number of entries. Instead of filtering the datagrid with an exact match, I would like to take the selected value and only display records where the selected value is contained in the datafield. For example: the user selects a value of "New" and the datagrid displays records where the contents of the record could be "New User", "New Person", "This one is New" etc. I think that I need to use RegExp, but I cant work out how to get it to work. Thanks in advance, S... </p>
[ { "answer_id": 176606, "author": "JustLogic", "author_id": 21664, "author_profile": "https://Stackoverflow.com/users/21664", "pm_score": 2, "selected": false, "text": "<p>Something like this should work:</p>\n\n<pre><code> public function filter(item:Object):Boolean{\n var result:Boolean=false;\n if (item.name.toUpperCase().indexOf(cbo.selectedLabel.toUpperCase()) &gt;= 0)\n result=true;\n return result;\n }\n</code></pre>\n\n<p>This filter function will search the name attribute(or whatever you want to filter on) of the object passed in with the combobox's currently selected label and if it finds that value it will return true. So if it finds the word \"New\" anywhere in the string it will show up in the datagrid. IE: \"New Person\", \"New User\" will both show up once filtered.</p>\n\n<p>Hope this is what you are looking for.</p>\n" }, { "answer_id": 2140343, "author": "Big 'B'", "author_id": 242171, "author_profile": "https://Stackoverflow.com/users/242171", "pm_score": 2, "selected": false, "text": "<p>You can modify this to produce drop down filtering functionality.\ncurrently textbox filtering is working. so i am posting it here.</p>\n\n<p>declare 2 string variables\ntempString and tempString_Name\nthen... </p>\n\n<p><strong>Use the following 2 functions</strong></p>\n\n<pre><code> private function filterByTerritory(item:Object):Boolean{\n tempString = item.name;\n tempString_Name = item.territory;\n if( (tempString.indexOf(sampleFilter.text,0) != -1) &amp;&amp; \n (tempString_Name.indexOf(terrFilterTxt.text,0) != -1)){\n return true;\n }\n else{\n return false;\n }\n } \n private function doFilter():void{\n if( (sampleFilter.text.length == 0) &amp;&amp; \n (terrFilterTxt.text.length == 0)) {\n myData.filterFunction == null;\n }\n else{\n myData.filterFunction = filterByTerritory;\n }\n myData.refresh();\n }\n</code></pre>\n\n<p><strong>Accept data thru these 2 textboxes</strong> </p>\n\n<pre><code>&lt;mx:TextInput id=\"sampleFilter\" change=\"doFilter()\"/&gt;\n &lt;mx:TextInput id=\"terrFilterTxt\" change=\"doFilter()\"/&gt;\n</code></pre>\n\n<p>nutshell: call doFilter on some event on which u want filtering to happen.</p>\n\n<p>Soon i will post filtering a datagrid based on combo box.\nTill then bye. I will become a member soon :)</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25463/" ]
I have a filter in a combobox with a number of entries. Instead of filtering the datagrid with an exact match, I would like to take the selected value and only display records where the selected value is contained in the datafield. For example: the user selects a value of "New" and the datagrid displays records where the contents of the record could be "New User", "New Person", "This one is New" etc. I think that I need to use RegExp, but I cant work out how to get it to work. Thanks in advance, S...
Something like this should work: ``` public function filter(item:Object):Boolean{ var result:Boolean=false; if (item.name.toUpperCase().indexOf(cbo.selectedLabel.toUpperCase()) >= 0) result=true; return result; } ``` This filter function will search the name attribute(or whatever you want to filter on) of the object passed in with the combobox's currently selected label and if it finds that value it will return true. So if it finds the word "New" anywhere in the string it will show up in the datagrid. IE: "New Person", "New User" will both show up once filtered. Hope this is what you are looking for.
176,446
<p>Why do I get compiler errors with this Java code?</p> <pre><code>1 public List&lt;? extends Foo&gt; getFoos() 2 { 3 List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;(); 4 foos.add(new SubFoo()); 5 return foos; 6 }</code></pre> <p>Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.</p> <p>Errors I get with this code:</p> <ul> <li>On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;"</li> <li>On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"</li> </ul> <p><b>Update:</b> Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();". But I'm still having the issue with Line 4.</p>
[ { "answer_id": 176478, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 6, "selected": true, "text": "<p>Use this instead:</p>\n\n<pre><code>1 public List&lt;? extends Foo&gt; getFoos()\n2 {\n3 List&lt;Foo&gt; foos = new ArrayList&lt;Foo&gt;(); /* Or List&lt;SubFoo&gt; */\n4 foos.add(new SubFoo());\n5 return foos;\n6 }\n</code></pre>\n\n<p>Once you declare foos as <code>List&lt;? extends Foo&gt;</code>, the compiler doesn't know that it's safe to add a SubFoo. What if an <code>ArrayList&lt;AltFoo&gt;</code> had been assigned to <code>foos</code>? That would be a valid assignment, but adding a SubFoo would pollute the collection.</p>\n" }, { "answer_id": 176484, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 2, "selected": false, "text": "<p>The following will work fine:</p>\n\n<pre><code>public List&lt;? extends Foo&gt; getFoos() {\n List&lt;Foo&gt; foos = new ArrayList&lt;Foo&gt;();\n foos.add(new SubFoo());\n return foos;\n}\n</code></pre>\n" }, { "answer_id": 176490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>public List&lt;Foo&gt; getFoos() {\n List&lt;Foo&gt; foos = new ArrayList&lt;Foo&gt;();\n foos.add(new SubFoo());\n return foos;\n}\n</code></pre>\n\n<p>The generic ArrayList constructor needs to have a specific type to be parameterized on, you cannot use the '?' wildcard there. Changing the instantiation to \"new ArrayList&lt;Foo&gt;()' would solve the first compilation error.</p>\n\n<p>The declaration of the 'foos' variable can have wildcards, but since you know the precise type, it makes more sense to reference the same type info there. What you have now says that foos holds some specific subtype of Foo, but we don't know which. Adding a SubFoo may not be allowed, since a SubFoo is not \"all subtypes of Foo\". Changing the declaration to 'List&lt;Foo&gt; foos = ' solves the second compilation error.</p>\n\n<p>Finally, I would change the return type to 'List&lt;Foo&gt;' since clients of this method won't be able to do much with the returned value as currently defined. You should rarely use wildcards in return types. Use a parameterized method signature if needed, but prefer bounded types to only appear in method arguments, as that leaves it up to the caller who can pass in specific types and operate and them accordingly.</p>\n" }, { "answer_id": 5406268, "author": "zslevi", "author_id": 95899, "author_profile": "https://Stackoverflow.com/users/95899", "pm_score": 2, "selected": false, "text": "<p>To get an idea of how generics works check out this example:</p>\n\n<pre><code> List&lt;SubFoo&gt; sfoo = new ArrayList&lt;SubFoo&gt;();\n List&lt;Foo&gt; foo;\n List&lt;? extends Foo&gt; tmp;\n\n tmp = sfoo;\n foo = (List&lt;Foo&gt;) tmp;\n</code></pre>\n\n<p>The thing is, that wasn't designed for local/member variables, but for function signatures, that's why it's so ass-backwards.</p>\n" }, { "answer_id": 11501363, "author": "Glen Best", "author_id": 1528401, "author_profile": "https://Stackoverflow.com/users/1528401", "pm_score": 4, "selected": false, "text": "<p>Just thought I'd add to this old thread, by summarising the properties of List parameters instantiated with types or wildcards....</p>\n\n<p>When a method has a parameter/result which is a List, the use of type instantiation or wildcards determines </p>\n\n<ol>\n<li>Types of List which can be passed to the method as an argument</li>\n<li>Types of List which can be populated from the method result</li>\n<li>Types of elements which can be written to list within the method</li>\n<li>Types which can be populated when reading elements from list within the method</li>\n</ol>\n\n<h2>Param/Return type: <code>List&lt; Foo&gt;</code></h2>\n\n<ol>\n<li>Types of List which can be passed to the method as an argument: \n\n<ul>\n<li><code>List&lt; Foo&gt;</code></li>\n</ul></li>\n<li>Types of List which can be populated from the method result: \n\n<ul>\n<li><code>List&lt; Foo&gt;</code></li>\n<li><code>List&lt; ? super Foo&gt;</code></li>\n<li><code>List&lt; ? super SubFoo&gt;</code></li>\n<li><code>List&lt; ? extends Foo&gt;</code></li>\n<li><code>List&lt; ? extends SuperFoo&gt;</code></li>\n</ul></li>\n<li>Types of elements which can be written to list within the method: \n\n<ul>\n<li><code>Foo</code> &amp; subtypes</li>\n</ul></li>\n<li>Types which can be populated when reading elements from list within the method: \n\n<ul>\n<li><code>Foo</code> &amp; supertypes (up to <code>Object</code>)</li>\n</ul></li>\n</ol>\n\n<h2>Param/Return type: <code>List&lt; ? extends Foo&gt;</code></h2>\n\n<ol>\n<li>Types of List which can be passed to the method as an argument: \n\n<ul>\n<li><code>List&lt; Foo&gt;</code></li>\n<li><code>List&lt; Subfoo&gt;</code></li>\n<li><code>List&lt; SubSubFoo&gt;</code></li>\n<li><code>List&lt; ? extends Foo&gt;</code></li>\n<li><code>List&lt; ? extends SubFoo&gt;</code></li>\n<li><code>List&lt; ? extends SubSubFoo&gt;</code></li>\n</ul></li>\n<li>Types of List which can be populated from the method result: \n\n<ul>\n<li><code>List&lt; ? extends Foo&gt;</code></li>\n<li><code>List&lt; ? extends SuperFoo&gt;</code></li>\n<li><code>List&lt; ? extends SuperSuperFoo&gt;</code></li>\n</ul></li>\n<li>Types of elements which can be written to list within the method: \n\n<ul>\n<li>None! Not possible to add.</li>\n</ul></li>\n<li>Types which can be populated when reading elements from list within the method: \n\n<ul>\n<li><code>Foo</code> &amp; supertypes (up to <code>Object</code>)</li>\n</ul></li>\n</ol>\n\n<h2>Param/Return type: <code>List&lt;? super Foo&gt;</code></h2>\n\n<ol>\n<li>Types of List which can be passed to the method as an argument:\n\n<ul>\n<li><code>List&lt; Foo&gt;</code></li>\n<li><code>List&lt; Superfoo&gt;</code></li>\n<li><code>List&lt; SuperSuperFoo&gt;</code></li>\n<li><code>List&lt; ? super Foo&gt;</code></li>\n<li><code>List&lt; ? super SuperFoo&gt;</code></li>\n<li><code>List&lt; ? super SuperSuperFoo&gt;</code></li>\n</ul></li>\n<li>Types of List which can be populated from the method result:\n\n<ul>\n<li><code>List&lt; ? super Foo&gt;</code></li>\n<li><code>List&lt; ? super SubFoo&gt;</code></li>\n<li><code>List&lt; ? super SubSubFoo&gt;</code></li>\n</ul></li>\n<li>Types of elements which can be written to list within the method:\n\n<ul>\n<li><code>Foo</code> &amp; supertypes</li>\n</ul></li>\n<li>Types which can be populated when reading elements from list within the method:\n\n<ul>\n<li><code>Foo</code> &amp; supertypes (up to <code>Object</code>)</li>\n</ul></li>\n</ol>\n\n<h2>Interpretation/Comment</h2>\n\n<ul>\n<li>needs of external callers drive the design of the method declaration i.e. the public API (normally the primary consideration)</li>\n<li>needs of internal method logic drive any additional decisions re actual data types declared and constructed internally (normally the secondary consideration)</li>\n<li>use <code>List&lt;Foo&gt;</code> if caller code is always focused on manipulating the Foo class, as it maximises flexibility for both read and write</li>\n<li>use <code>List&lt;? extends UpperMostFoo&gt;</code> if there could be many different types of caller, focused on manipulating a different class (not always Foo) and there is a single uppermost class in the Foo type hierarchy, and if the method is to internally write to the list and caller list manipulation is reading. Here the method may internally use <code>List&lt; UpperMostFoo&gt;</code> and add elements to it, before returning <code>List&lt; ? extends UpperMostFoo&gt;</code> </li>\n<li>if there could be many different types of caller, focused on manipulating a different class (not always Foo) and if reading and writing to list is required and there is a single lowest class in the Foo type hierarchy, then it makes sense to use <code>List&lt; ? super LowerMostFoo&gt;</code></li>\n</ul>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
Why do I get compiler errors with this Java code? ``` 1 public List<? extends Foo> getFoos() 2 { 3 List<? extends Foo> foos = new ArrayList<? extends Foo>(); 4 foos.add(new SubFoo()); 5 return foos; 6 } ``` Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface. Errors I get with this code: * On Line 3: "Cannot instantiate ArrayList<? extends Foo>" * On Line 4: "The method add(capture#1-of ? extends Foo) in the type List<capture#1-of ? extends Foo> is not applicable for the arguments (SubFoo)" **Update:** Thanks to Jeff C, I can change Line 3 to say "new ArrayList<Foo>();". But I'm still having the issue with Line 4.
Use this instead: ``` 1 public List<? extends Foo> getFoos() 2 { 3 List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */ 4 foos.add(new SubFoo()); 5 return foos; 6 } ``` Once you declare foos as `List<? extends Foo>`, the compiler doesn't know that it's safe to add a SubFoo. What if an `ArrayList<AltFoo>` had been assigned to `foos`? That would be a valid assignment, but adding a SubFoo would pollute the collection.
176,459
<p>Here are the declarations of the variables:</p> <pre><code>string strFirstName; string strLastName; string strAddress; string strCity; string strState; double dblSalary; string strGender; int intAge; </code></pre> <p>...Do some "cin" statements to get data...</p> <pre><code>retcode = SQLPrepare(StatementHandle, (SQLCHAR *)"INSERT INTO EMPLOYEE ([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES (?,?,?,?,?,?,?,?)", SQL_NTS); retcode = SQLBindParameter(StatementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0 &amp;strFirstName,0, NULL); retcode = SQLBindParameter(StatementHandle, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0, &amp;strLastName,0, NULL); retcode = SQLBindParameter(StatementHandle, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 30, 0, &amp;strAddress,0, NULL); retcode = SQLBindParameter(StatementHandle, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 30, 0, &amp;strCity,0, NULL); retcode = SQLBindParameter(StatementHandle, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 3, 0, &amp;strState,0, NULL); retcode = SQLBindParameter(StatementHandle, 6, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_DOUBLE, 0, 0, &amp;dblSalary,0, NULL); retcode = SQLBindParameter(StatementHandle, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 2, 0, &amp;strGender,0, NULL); retcode = SQLBindParameter(StatementHandle, 8, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &amp;intAge,0, NULL); retcode = SQLExecute(StatementHandle); </code></pre> <p>The int and double work fine and get stored in the table...but I can't figure out how to get the strings to store...</p>
[ { "answer_id": 176466, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>It looks like the api, wants an <strong>unsigned char *</strong>\ntry passing in a c string, using the <strong>c_str()</strong> method call.</p>\n" }, { "answer_id": 176509, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms710963.aspx\" rel=\"noreferrer\">MSDN documentation for SQLBindParameter</a> says you are meant to pass a buffer containing the data for <code>ParameterValuePtr</code> and the length of the buffer in bytes for <code>BufferLength</code>:</p>\n\n<pre><code>retcode = SQLBindParameter(StatementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR,\n SQL_LONGVARCHAR, 50, 0, strFirstName.c_str(), strFirstName.length(), NULL);\n</code></pre>\n\n<blockquote>\n <p>ParameterValuePtr [Deferred Input] A\n pointer to a buffer for the\n parameter's data. For more\n information, see \"ParameterValuePtr\n Argument\" in \"Comments.\"</p>\n \n <p>BufferLength [Input/Output] Length of\n the ParameterValuePtr buffer in bytes.\n For more information, see\n \"BufferLength Argument\" in \"Comments.\"</p>\n</blockquote>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25642/" ]
Here are the declarations of the variables: ``` string strFirstName; string strLastName; string strAddress; string strCity; string strState; double dblSalary; string strGender; int intAge; ``` ...Do some "cin" statements to get data... ``` retcode = SQLPrepare(StatementHandle, (SQLCHAR *)"INSERT INTO EMPLOYEE ([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES (?,?,?,?,?,?,?,?)", SQL_NTS); retcode = SQLBindParameter(StatementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0 &strFirstName,0, NULL); retcode = SQLBindParameter(StatementHandle, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0, &strLastName,0, NULL); retcode = SQLBindParameter(StatementHandle, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 30, 0, &strAddress,0, NULL); retcode = SQLBindParameter(StatementHandle, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 30, 0, &strCity,0, NULL); retcode = SQLBindParameter(StatementHandle, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 3, 0, &strState,0, NULL); retcode = SQLBindParameter(StatementHandle, 6, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_DOUBLE, 0, 0, &dblSalary,0, NULL); retcode = SQLBindParameter(StatementHandle, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 2, 0, &strGender,0, NULL); retcode = SQLBindParameter(StatementHandle, 8, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &intAge,0, NULL); retcode = SQLExecute(StatementHandle); ``` The int and double work fine and get stored in the table...but I can't figure out how to get the strings to store...
[MSDN documentation for SQLBindParameter](http://msdn.microsoft.com/en-us/library/ms710963.aspx) says you are meant to pass a buffer containing the data for `ParameterValuePtr` and the length of the buffer in bytes for `BufferLength`: ``` retcode = SQLBindParameter(StatementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0, strFirstName.c_str(), strFirstName.length(), NULL); ``` > > ParameterValuePtr [Deferred Input] A > pointer to a buffer for the > parameter's data. For more > information, see "ParameterValuePtr > Argument" in "Comments." > > > BufferLength [Input/Output] Length of > the ParameterValuePtr buffer in bytes. > For more information, see > "BufferLength Argument" in "Comments." > > >
176,479
<p>I have a image upload form that should take image types (PNG, JPEG, GIF), resize it and then save it to a path. </p> <p>For some reason I can't get the PNG file types to work, it works fine with JPEG/GIF and the file is copied so it looks like it's something to do with how I'm creating the PNG. </p> <p>Does PNG creation in PHP require different parameters or options? Some sample code of lines that do image creation:</p> <pre><code>$src = imagecreatefrompng($uploadedfile); imagecreatetruecolor($newWidth,$newHeight) imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$width,$height); imagepng($tmp,$destinationPath."/".$destinationFile,100); </code></pre> <p>The same commands work for JPG and GIF.</p>
[ { "answer_id": 176513, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 2, "selected": false, "text": "<p>You need to look how your PHP is built.. Eg:</p>\n\n<pre><code>GD Support enabled\nGD Version bundled (2.0.28 compatible) \nPNG Support enabled \n</code></pre>\n\n<p>If you don't have PNG support compiled in, you'll need to have that updated.</p>\n" }, { "answer_id": 176538, "author": "Chris Bartow", "author_id": 497, "author_profile": "https://Stackoverflow.com/users/497", "pm_score": 0, "selected": false, "text": "<p>Are you starting with PNG-8 images? There are some issues with PNG-8 vs PNG-24 when working with PHP. Make sure PNG support is compiled in, then take a <a href=\"http://www.php.net/manual/en/function.imagecreatefrompng.php#71091\" rel=\"nofollow noreferrer\">look at this persons solution to the PNG-8 problem</a>.</p>\n" }, { "answer_id": 176544, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>checked and I have PNG support:</p>\n\n<p>'GIF Read Support' => boolean true\n 'GIF Create Support' => boolean true\n 'JPG Support' => boolean true\n 'PNG Support' => boolean true</p>\n\n<p>thanks for the reply though... thought that would be it</p>\n" }, { "answer_id": 176610, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I figured out the problem, just a problem of me not reading the API :P.</p>\n\n<p>unlike <code>imagejpg()</code> or <code>imagegif()</code>, <code>imagepng()</code> accepts an integer of 0-9 for compression. so I was passing 100 as a parameter thinking the quality would be higher but instead I guess I treated it as maximum compression. Passing 0 solved the problem.</p>\n\n<p>Maybe the API has changed from PHP versions? </p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a image upload form that should take image types (PNG, JPEG, GIF), resize it and then save it to a path. For some reason I can't get the PNG file types to work, it works fine with JPEG/GIF and the file is copied so it looks like it's something to do with how I'm creating the PNG. Does PNG creation in PHP require different parameters or options? Some sample code of lines that do image creation: ``` $src = imagecreatefrompng($uploadedfile); imagecreatetruecolor($newWidth,$newHeight) imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$width,$height); imagepng($tmp,$destinationPath."/".$destinationFile,100); ``` The same commands work for JPG and GIF.
You need to look how your PHP is built.. Eg: ``` GD Support enabled GD Version bundled (2.0.28 compatible) PNG Support enabled ``` If you don't have PNG support compiled in, you'll need to have that updated.
176,512
<p>In short, how do you unit test an error condition such as EINTR on a system call.</p> <p>One particular example I'm working on, which could be a case all by itself, is whether it's necessary to call fclose again when it returns EOF with (errno==EINTR). The behavior depends on the implementation of fclose:</p> <pre><code>// Given an open FILE *fp while (fclose(fp)==EOF &amp;&amp; errno==EINTR) { errno = 0; } </code></pre> <p>This call can be unsafe if fp freed when EINTR occurs. How can I test the error handling for when (errno==EINTR)?</p>
[ { "answer_id": 176761, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "<p>I don't think there is an easy way to actually test this at will.</p>\n\n<p>EINTR will be generated if the fclose operation is interrupted by a signal.\nThis implies that fclose was in a background thread which received a signal as it was processing the close request.</p>\n\n<p>Good luck trying to reproduce that set of circumstances.</p>\n" }, { "answer_id": 176786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Use a struct of function pointers to abstract out the system functions. Replace the call to flcose(fp) with something like sys->fclose(fp). In your unit test, create an implementation of fclose that always returns EINTR then set sys->fclose to that version.</p>\n" }, { "answer_id": 176797, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 2, "selected": false, "text": "<p>In this particular case, it's not safe to call fclose() again, as the C standard says the stream is disassociated from the file (and becomes indeterminate) even if the call fails. </p>\n" }, { "answer_id": 176821, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 2, "selected": false, "text": "<p>Looking at the linux kernel source code, I'm unable to find any drivers that even return EINTR upon file close.</p>\n\n<p>If you absosmurfly had to reproduce this case, you could write your own driver in Linux to return -EINTR on the .release method. Take a look at the <a href=\"http://examples.oreilly.com/linuxdrive3/examples.tar.gz\" rel=\"nofollow noreferrer\">example code</a> from O'Reilly's Linux Device Drivers book. The scull project is one of the simplest ones. You'd change it to be like this:</p>\n\n<pre><code>int scull_release(struct inode *inode, struct file *filp)\n{\n return -EINTR;\n}\n</code></pre>\n\n<p>Again though, grepping through the linux source tree, I can't find any driver that would return EINTR on close.</p>\n\n<p><strong>EDIT</strong> - ok it looks like fuse - the userspace filesystem might be able to. This is used for things like sshfs. Still an edge case though.</p>\n" }, { "answer_id": 177001, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 1, "selected": false, "text": "<p>As Kris suggests, temporarily replace calls to the \"real\" <code>fclose()</code> with your own implementation defined in your unit test code. Your implementation could do something as simple as:</p>\n\n<pre><code>int my_fclose(FILE *fp)\n{\n errno = EINTR;\n return EOF;\n}\n</code></pre>\n\n<p>But, as fizzer points out, you shouldn't call <code>fclose()</code> again as the behavior is undefined, so you needn't bother even checking for the condition.</p>\n\n<p>The other question to ask is whether you really need to worry about this; if your application code were to block all possible signals (except SIGKILL and SIGSTOP) during your <code>fclose()</code> then you wouldn't get a EINTR and wouldn't need to worry at all.</p>\n" }, { "answer_id": 277880, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 1, "selected": false, "text": "<p>Here is how I would test it, just for the sake of testing since fizzer reminded us calling <code>fclose()</code> twice is unsafe. </p>\n\n<p>It is possible to <strong>redefine</strong> <code>fclose()</code> (or any other function of libc) in your program <em>with your own behavior</em>. On Unix-like systems, the linker does not complain - never tried on Windows but with cygwin. Of course this prevents your other tests to use the real <code>fclose()</code>, therefore such a test has to be put in a separate test executable. </p>\n\n<p>Here is an all-in-one example with <a href=\"http://www.jera.com/techinfo/jtns/jtn002.html\" rel=\"nofollow noreferrer\">minunit</a>. </p>\n\n<pre><code>#include &lt;errno.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdbool.h&gt;\n\n/* from minunit.h : http://www.jera.com/techinfo/jtns/jtn002.html */\n #define mu_assert(message, test) do { if (!(test)) return message; } while (0)\n #define mu_run_test(test) do { char *message = test(); tests_run++; \\\n if (message) return message; } while (0)\n\nint tests_run = 0;\nbool fclose_shall_fail_on_EINTR = false;\n\n//--- our implemention of fclose()\nint fclose(FILE *fp) {\n if (fclose_shall_fail_on_EINTR) {\n errno = EINTR;\n fclose_shall_fail_on_EINTR = false; //--- reset for next call \n return EOF;\n } else { return 0; }\n}\n\n//--- this is the \"production\" function to be tested \nvoid uninterruptible_close(FILE *fp) {\n // Given an open FILE *fp\n while (fclose(fp)==EOF &amp;&amp; errno==EINTR) {\n errno = 0;\n }\n}\n\nchar *test_non_interrupted_fclose(void) {\n FILE *theHandle = NULL; //--- don't care here\n uninterruptible_close(theHandle);\n mu_assert(\"test fclose wo/ interruption\", 0 == errno);\n return 0;\n}\n\nchar *test_interrupted_fclose(void) {\n FILE *theHandle = NULL; //--- don't care here\n fclose_shall_fail_on_EINTR = true;\n\n uninterruptible_close(theHandle);\n mu_assert(\"test fclose wo/ interruption\", 0 == errno);\n return 0;\n}\n\nchar *test_suite(void)\n{\n mu_run_test(test_non_interrupted_fclose);\n mu_run_test(test_interrupted_fclose);\n return 0;\n}\n\nint main(int ac, char **av)\n{\n char *result = test_suite();\n\n printf(\"number of tests run: %d\\n\", tests_run);\n if (result) { printf(\"FAIL: %s\\n\", result); } \n\n return 0 != result;\n}\n</code></pre>\n" }, { "answer_id": 1072048, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Um, I think all of you are ignoring something pretty important.</p>\n\n<p>fclose() cannot return EINTR.\nNeither can fopen(), fwrite(), fread(), or any of the standard C I/O functions.</p>\n\n<p>It is only when you dabble in the low-level I/O calls like open(2), write(2), and select(2) that you need to handle EINTR.</p>\n\n<p>Read the [funny] man pages</p>\n" }, { "answer_id": 5124279, "author": "Taher Hassan", "author_id": 616130, "author_profile": "https://Stackoverflow.com/users/616130", "pm_score": 1, "selected": false, "text": "<p>I think that there might be an issue with the simultaneous processing of signals and confirming error conditions.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24310/" ]
In short, how do you unit test an error condition such as EINTR on a system call. One particular example I'm working on, which could be a case all by itself, is whether it's necessary to call fclose again when it returns EOF with (errno==EINTR). The behavior depends on the implementation of fclose: ``` // Given an open FILE *fp while (fclose(fp)==EOF && errno==EINTR) { errno = 0; } ``` This call can be unsafe if fp freed when EINTR occurs. How can I test the error handling for when (errno==EINTR)?
I don't think there is an easy way to actually test this at will. EINTR will be generated if the fclose operation is interrupted by a signal. This implies that fclose was in a background thread which received a signal as it was processing the close request. Good luck trying to reproduce that set of circumstances.
176,527
<p>I need to enumerate all classes in a package and add them to a List. The non-dynamic version for a single class goes like this:</p> <pre><code>List allClasses = new ArrayList(); allClasses.add(String.class); </code></pre> <p>How can I do this dynamically to add all classes in a package and all its subpackages?</p> <hr> <p><strong><em>Update:</em></strong> Having read the early answers, it's absolutely true that I'm trying to solve another secondary problem, so let me state it. And I know this is possible since other tools do it. See new question <a href="https://stackoverflow.com/questions/176913/how-can-i-run-all-unit-tests-except-those-ending-in-integrationtest-in-my-intel">here</a>. </p> <p><strong><em>Update:</em></strong> Reading this again, I can see how it's being misread. I'm looking to enumerate all of MY PROJECT'S classes from the file system after compilation. </p>
[ { "answer_id": 176694, "author": "G B", "author_id": 25662, "author_profile": "https://Stackoverflow.com/users/25662", "pm_score": 2, "selected": false, "text": "<p>I'm afraid you'll have to manually scan the classpath and the other places where java searches for classes (e.g., the ext directory or the boot classpath).\nSince java uses lazy loading of classes, it may not even know about additional classes in your packages that haven't been loaded yet.\nAlso check the notion of \"sealed\" packages.</p>\n" }, { "answer_id": 176721, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 2, "selected": false, "text": "<p>It's funny that this question comes up every once in a while. The problem is that this keyword would have been more appropriately named \"namespace\". The Java package does not delineate a concrete container that holds all the classes in the package at any one time. It simply defines a token that classes can use to declare that they are a member of that package. You'd have to search through the entire classpath (as another reply indicated) to determine all the classes in a package.</p>\n" }, { "answer_id": 189515, "author": "thvo", "author_id": 13041, "author_profile": "https://Stackoverflow.com/users/13041", "pm_score": 2, "selected": false, "text": "<p>I figured out how to do this. Here's the procedure:</p>\n\n<ol>\n<li>Start with a class in the root package, and get the folder it's in from the class loader</li>\n<li>Recursively enumerate all .class files in this folder</li>\n<li>Convert the file names to fully qualified class names</li>\n<li>Use Class.forName() to get the classes</li>\n</ol>\n\n<p>There are a few nasty tricks here that make me a bit uneasy, but it works - for example:</p>\n\n<ol>\n<li>Converting path names to package names using string manipulation</li>\n<li>Hard-coding the root package name to enable stripping away the path prefix</li>\n</ol>\n\n<p>Too bad that stackoverflow doesn't allow me to accept my own answer...</p>\n" }, { "answer_id": 189525, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 0, "selected": false, "text": "<p>Look at what java.net.URLClassLoader is doing. It never enumerates classes, it just tries to find classes when asked for one. If you want to enumerate the classes, then you will need to get the classpath, split it into directories and jar files. Scan the directories (and their subdirectories) and jar files for files with the name *.class.\n<P>It may be worth looking at open source projects which seem to do the enumeration you want (like <a href=\"http://www.eclipse.org/\" rel=\"nofollow noreferrer\">Eclipse</a>) for inspiration.</p>\n" }, { "answer_id": 3527428, "author": "Dave Dopson", "author_id": 407731, "author_profile": "https://Stackoverflow.com/users/407731", "pm_score": 6, "selected": true, "text": "<p>****UPDATE 1 (2012)****</p>\n\n<p>OK, I've finally gotten around to cleaning up the code snippet below. I stuck it into it's own github project and even added tests.</p>\n\n<p><a href=\"https://github.com/ddopson/java-class-enumerator\" rel=\"nofollow noreferrer\">https://github.com/ddopson/java-class-enumerator</a></p>\n\n<p>****UPDATE 2 (2016)****</p>\n\n<p>For an even more robust and feature-rich classpath scanner, see <a href=\"https://github.com/classgraph/classgraph\" rel=\"nofollow noreferrer\">https://github.com/classgraph/classgraph</a> . I'd recommend first reading my code snippet to gain a high level understanding, then using lukehutch's tool for production purposes.</p>\n\n<p>****Original Post (2010)****</p>\n\n<p>Strictly speaking, it isn't possible to list the classes in a <em>package</em>. This is because a package is really nothing more than a namespace (eg com.epicapplications.foo.bar), and any jar-file in the classpath could potentially add classes into a package. Even worse, the classloader will load classes on demand, and part of the classpath might be on the other side of a network connection.</p>\n\n<p>It is possible to solve a more restrictive problem. eg, all classes in a JAR file, or all classes that a JAR file defines within a particular package. This is the more common scenario anyways.</p>\n\n<p>Unfortunately, there isn't any framework code to make this task easy. You have to scan the filesystem in a manner similar to how the ClassLoader would look for class definitions.</p>\n\n<p>There are a lot of samples on the web for class files in plain-old-directories. Most of us these days work with JAR files.</p>\n\n<p>To get things working with JAR files, try this...</p>\n\n<pre><code>private static ArrayList&lt;Class&lt;?&gt;&gt; getClassesForPackage(Package pkg) {\n String pkgname = pkg.getName();\n ArrayList&lt;Class&lt;?&gt;&gt; classes = new ArrayList&lt;Class&lt;?&gt;&gt;();\n // Get a File object for the package\n File directory = null;\n String fullPath;\n String relPath = pkgname.replace('.', '/');\n System.out.println(\"ClassDiscovery: Package: \" + pkgname + \" becomes Path:\" + relPath);\n URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);\n System.out.println(\"ClassDiscovery: Resource = \" + resource);\n if (resource == null) {\n throw new RuntimeException(\"No resource for \" + relPath);\n }\n fullPath = resource.getFile();\n System.out.println(\"ClassDiscovery: FullPath = \" + resource);\n\n try {\n directory = new File(resource.toURI());\n } catch (URISyntaxException e) {\n throw new RuntimeException(pkgname + \" (\" + resource + \") does not appear to be a valid URL / URI. Strange, since we got it from the system...\", e);\n } catch (IllegalArgumentException e) {\n directory = null;\n }\n System.out.println(\"ClassDiscovery: Directory = \" + directory);\n\n if (directory != null &amp;&amp; directory.exists()) {\n // Get the list of the files contained in the package\n String[] files = directory.list();\n for (int i = 0; i &lt; files.length; i++) {\n // we are only interested in .class files\n if (files[i].endsWith(\".class\")) {\n // removes the .class extension\n String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);\n System.out.println(\"ClassDiscovery: className = \" + className);\n try {\n classes.add(Class.forName(className));\n } \n catch (ClassNotFoundException e) {\n throw new RuntimeException(\"ClassNotFoundException loading \" + className);\n }\n }\n }\n }\n else {\n try {\n String jarPath = fullPath.replaceFirst(\"[.]jar[!].*\", \".jar\").replaceFirst(\"file:\", \"\");\n JarFile jarFile = new JarFile(jarPath); \n Enumeration&lt;JarEntry&gt; entries = jarFile.entries();\n while(entries.hasMoreElements()) {\n JarEntry entry = entries.nextElement();\n String entryName = entry.getName();\n if(entryName.startsWith(relPath) &amp;&amp; entryName.length() &gt; (relPath.length() + \"/\".length())) {\n System.out.println(\"ClassDiscovery: JarEntry: \" + entryName);\n String className = entryName.replace('/', '.').replace('\\\\', '.').replace(\".class\", \"\");\n System.out.println(\"ClassDiscovery: className = \" + className);\n try {\n classes.add(Class.forName(className));\n } \n catch (ClassNotFoundException e) {\n throw new RuntimeException(\"ClassNotFoundException loading \" + className);\n }\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(pkgname + \" (\" + directory + \") does not appear to be a valid package\", e);\n }\n }\n return classes;\n}\n</code></pre>\n" }, { "answer_id": 7019929, "author": "Christian Bongiorno", "author_id": 889053, "author_profile": "https://Stackoverflow.com/users/889053", "pm_score": 2, "selected": false, "text": "<p>There is a caveat to this: ApplicationEngines/servlet containers like <strong>tomcat and JBoss have hierarchical class loaders</strong>. Getting the system class loader will not do.</p>\n\n<p>The way <strong>Tomcat</strong> works (things may have changed, but my current experience doesn't lead me to believe otherwise) but each application context has it's own class loader so that classes for application 'foo' don't collide with classes for application 'fooV2'</p>\n\n<p>Just as an example. If all the classes got munged into one uber class context then you would have no idea if you were using classes appropriate for version 1 or version 2. </p>\n\n<p>In addition, each one needs access to system classes like java.lang.String. This is the hierarchy. It checks the local app context first and moves it's way up (this is my current situation BTW).</p>\n\n<p>To manage this, a better approach would be: <strong>this.getClass().getClassloader()</strong></p>\n\n<p>In my case I have a webservice that needs to do self-discovery on some modules and they obviously reside in 'this' webservice context or the system context. By doing the above I get to check both. By just getting the system classloader I don't get access to any of the application classes (and thus my resources are null).</p>\n" }, { "answer_id": 32764815, "author": "Luke Hutchison", "author_id": 3950982, "author_profile": "https://Stackoverflow.com/users/3950982", "pm_score": 3, "selected": false, "text": "<p>The most robust mechanism for listing all classes in a given package is currently <a href=\"https://github.com/classgraph/classgraph/wiki/Code-examples\" rel=\"noreferrer\">ClassGraph</a>, because it handles the <a href=\"https://github.com/classgraph/classgraph/wiki/Classpath-Specification-Mechanisms\" rel=\"noreferrer\">widest possible array of classpath specification mechanisms</a>, including the new JPMS module system. (I am the author.)</p>\n\n<pre><code>List&lt;String&gt; classNames;\ntry (ScanResult scanResult = new ClassGraph().whitelistPackages(\"my.package\")\n .enableClassInfo().scan()) {\n classNames = scanResult.getAllClasses().getNames();\n}\n</code></pre>\n" }, { "answer_id": 46575028, "author": "Rodney P. Barbati", "author_id": 1588303, "author_profile": "https://Stackoverflow.com/users/1588303", "pm_score": 0, "selected": false, "text": "<p>If you are merely looking to load a group of related classes, then Spring can help you.</p>\n\n<p>Spring can instantiate a list or map of all classes that implement a given interface in one line of code. The list or map will contain instances of all the classes that implement that interface.</p>\n\n<p>That being said, as an alternative to loading the list of classes out of the file system, instead just implement the same interface in all the classes you want to load, regardless of package. That way, you can load (and instantiate) all the classes you desire regardless of what package they are in.</p>\n\n<p>On the other hand, if having them all in a package is what you want, then simply have all the classes in that package implement a given interface.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13041/" ]
I need to enumerate all classes in a package and add them to a List. The non-dynamic version for a single class goes like this: ``` List allClasses = new ArrayList(); allClasses.add(String.class); ``` How can I do this dynamically to add all classes in a package and all its subpackages? --- ***Update:*** Having read the early answers, it's absolutely true that I'm trying to solve another secondary problem, so let me state it. And I know this is possible since other tools do it. See new question [here](https://stackoverflow.com/questions/176913/how-can-i-run-all-unit-tests-except-those-ending-in-integrationtest-in-my-intel). ***Update:*** Reading this again, I can see how it's being misread. I'm looking to enumerate all of MY PROJECT'S classes from the file system after compilation.
\*\*\*\*UPDATE 1 (2012)\*\*\*\* OK, I've finally gotten around to cleaning up the code snippet below. I stuck it into it's own github project and even added tests. <https://github.com/ddopson/java-class-enumerator> \*\*\*\*UPDATE 2 (2016)\*\*\*\* For an even more robust and feature-rich classpath scanner, see <https://github.com/classgraph/classgraph> . I'd recommend first reading my code snippet to gain a high level understanding, then using lukehutch's tool for production purposes. \*\*\*\*Original Post (2010)\*\*\*\* Strictly speaking, it isn't possible to list the classes in a *package*. This is because a package is really nothing more than a namespace (eg com.epicapplications.foo.bar), and any jar-file in the classpath could potentially add classes into a package. Even worse, the classloader will load classes on demand, and part of the classpath might be on the other side of a network connection. It is possible to solve a more restrictive problem. eg, all classes in a JAR file, or all classes that a JAR file defines within a particular package. This is the more common scenario anyways. Unfortunately, there isn't any framework code to make this task easy. You have to scan the filesystem in a manner similar to how the ClassLoader would look for class definitions. There are a lot of samples on the web for class files in plain-old-directories. Most of us these days work with JAR files. To get things working with JAR files, try this... ``` private static ArrayList<Class<?>> getClassesForPackage(Package pkg) { String pkgname = pkg.getName(); ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); // Get a File object for the package File directory = null; String fullPath; String relPath = pkgname.replace('.', '/'); System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath); URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); System.out.println("ClassDiscovery: Resource = " + resource); if (resource == null) { throw new RuntimeException("No resource for " + relPath); } fullPath = resource.getFile(); System.out.println("ClassDiscovery: FullPath = " + resource); try { directory = new File(resource.toURI()); } catch (URISyntaxException e) { throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e); } catch (IllegalArgumentException e) { directory = null; } System.out.println("ClassDiscovery: Directory = " + directory); if (directory != null && directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // we are only interested in .class files if (files[i].endsWith(".class")) { // removes the .class extension String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); System.out.println("ClassDiscovery: className = " + className); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } else { try { String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> entries = jarFile.entries(); while(entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); if(entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) { System.out.println("ClassDiscovery: JarEntry: " + entryName); String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); System.out.println("ClassDiscovery: className = " + className); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } catch (IOException e) { throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); } } return classes; } ```
176,545
<p>I am going to be starting a javascript reporting engine for my website, and have started some prototyping using MooTools. I really like being able to do things like this:</p> <pre><code>function showLeagues(leagues) { var leagueList = $("leagues"); leagueList.empty(); for(var i = 0; i&lt;leagues.length; ++i) { var listItem = getLeagueListElement(leagues[i]); leagueList.adopt(listItem); } } function getLeagueListElement(league) { var listItem = new Element('li'); var newElement = new Element('a', { 'html': league.name, 'href': '?league='+league.key, 'events': { 'click': function() { showLeague(league); return false; } } }); listItem.adopt(newElement); return listItem; } </code></pre> <p>From what I've seen, jQuery's "adopt" type methods only take html strings or DOM Elements. Is there any jQuery equivalent to MooTools' <a href="http://mootools.net/docs/Element/Element#Element:constructor" rel="nofollow noreferrer">Element</a>? <hr/> EDIT: The big thing I'm looking for here is the programmatic attachment of my click event to the link.</p>
[ { "answer_id": 176567, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Here's that same thing in jQuery. Basically to create a new element, you just put in the HTML you want.</p>\n\n<pre><code>function showLeagues(leagues) {\n var $leagueList = $(\"#leagues\");\n $leagueList.empty();\n $.each(leagues, function (index, league) {\n $leagueList.append(getLeagueListElement(league));\n });\n}\n\nfunction getLeagueListElement(league) {\n return $('&lt;li&gt;&lt;/li&gt;')\n .append($('&lt;a&gt;&lt;/a&gt;')\n .html(league.name)\n .attr('href', '?league=' + league.key)\n .click(function() {\n showLeague(league);\n return false;\n })\n )\n ;\n}\n</code></pre>\n" }, { "answer_id": 176744, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<p>syntactically, it may be nicer to use jQuery to do it, but its probably more efficient to use</p>\n\n<pre><code> document.createElement('li')\n</code></pre>\n\n<p>And eliminate the need for at the bare minimum a string comparison test and a minor token parse. </p>\n\n<p><a href=\"http://flydom.socianet.com/\" rel=\"noreferrer\">flydom</a> may also tickle your interest if you insist on generating a lot of dom nodes. ( It should be faster in theory, but have not tested it )</p>\n\n<hr>\n\n<p>Note: Internally, jQuery(\"&lt;html>&lt;/html>\") looks like it effectively does this(oversimplified):</p>\n\n<pre><code>jQuery(matcher) --&gt; function(matcher)\n{\n return jQuery.fn.init(matcher) --&gt; function(matcher)\n {\n return this.setArray(\n jQuery.makeArray(\n jQuery.clean(matcher) --&gt; function(matcher)\n { \n div = document.createElement('div');\n div.innerHTML = matcher;\n return div.childNodes;\n }\n )\n );\n }\n}\n</code></pre>\n\n<p>So one would presume \"<code>document.createElement</code>\" is thus a \"requirement\", and if you <em>know</em> what you want out ( ie: not parising some 3rd party data with <code>$( datahere )</code> ) then <code>document.createElement</code> would imho be just as logical and with a speed boost to avoid the numerous regexps and slow string manipulations. </p>\n\n<p>By comparison: <code>jQuery(document.createElement('div'))</code> \nlooks like it effectively does this(oversimplified):</p>\n\n<pre><code>jQuery(matcher) --&gt; function(matcher)\n{\n return jQuery.fn.init(matcher) --&gt; function(matcher)\n {\n this[0] = matcher; \n this.length = 1; \n return this; \n }\n}\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
I am going to be starting a javascript reporting engine for my website, and have started some prototyping using MooTools. I really like being able to do things like this: ``` function showLeagues(leagues) { var leagueList = $("leagues"); leagueList.empty(); for(var i = 0; i<leagues.length; ++i) { var listItem = getLeagueListElement(leagues[i]); leagueList.adopt(listItem); } } function getLeagueListElement(league) { var listItem = new Element('li'); var newElement = new Element('a', { 'html': league.name, 'href': '?league='+league.key, 'events': { 'click': function() { showLeague(league); return false; } } }); listItem.adopt(newElement); return listItem; } ``` From what I've seen, jQuery's "adopt" type methods only take html strings or DOM Elements. Is there any jQuery equivalent to MooTools' [Element](http://mootools.net/docs/Element/Element#Element:constructor)? --- EDIT: The big thing I'm looking for here is the programmatic attachment of my click event to the link.
syntactically, it may be nicer to use jQuery to do it, but its probably more efficient to use ``` document.createElement('li') ``` And eliminate the need for at the bare minimum a string comparison test and a minor token parse. [flydom](http://flydom.socianet.com/) may also tickle your interest if you insist on generating a lot of dom nodes. ( It should be faster in theory, but have not tested it ) --- Note: Internally, jQuery("<html></html>") looks like it effectively does this(oversimplified): ``` jQuery(matcher) --> function(matcher) { return jQuery.fn.init(matcher) --> function(matcher) { return this.setArray( jQuery.makeArray( jQuery.clean(matcher) --> function(matcher) { div = document.createElement('div'); div.innerHTML = matcher; return div.childNodes; } ) ); } } ``` So one would presume "`document.createElement`" is thus a "requirement", and if you *know* what you want out ( ie: not parising some 3rd party data with `$( datahere )` ) then `document.createElement` would imho be just as logical and with a speed boost to avoid the numerous regexps and slow string manipulations. By comparison: `jQuery(document.createElement('div'))` looks like it effectively does this(oversimplified): ``` jQuery(matcher) --> function(matcher) { return jQuery.fn.init(matcher) --> function(matcher) { this[0] = matcher; this.length = 1; return this; } } ```
176,569
<p>I have a C# console app "App1" that reads a row of data from a table in a SQL Server 2005 DB. I want App1 to pass all the data in this row to App2, another C# console app. What is the best way to do this?</p> <p>My first (naive) attempt was to do this:</p> <pre><code>object[] o = myrow.ItemArray; // make a string that separates each item by a space... for example "1 2 myVar". // pass this string to App2 via command line. </code></pre> <p>This has some flaws: what if one of the entries in the row was "my var" instead of "myVar"? Also, the order of the items would be hardcoded in the receiving app (App2).</p> <p>So what's the best way to do this? Would it be appropriate to pass an xml string to App2 via command line?</p> <p>Cheers!</p>
[ { "answer_id": 176595, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>The space-separated approach is fine if you are using Process.Start - you just need to wrap items containing spaces with quotes - same as at the command line: cd \"c:\\program files\"</p>\n\n<p>If the data is more complex than a few values, then IPC approaches such as remoting, sockets, WCF, etc might help. Or simpler: write the data (perhaps as xml) to a file, and have the second app load the data from the file.</p>\n" }, { "answer_id": 176601, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": true, "text": "<p>One approach would be to serialize the row to XML and use that, except that DataRow (lacking a default constructor) can't be serialized. Instead you'd have to create a new DataTable and add that row to it.</p>\n\n<p>Then you could simply serialize the entire DataTable to XML and pass it to the other application, either as a command-line argument or by saving the XML to a file and passing the filename.</p>\n\n<p>Serializing a DataTable to XML is quite trivial thanks to the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml.aspx\" rel=\"nofollow noreferrer\">DataTable.WriteXml</a> method.</p>\n" }, { "answer_id": 176607, "author": "tbreffni", "author_id": 637, "author_profile": "https://Stackoverflow.com/users/637", "pm_score": 1, "selected": false, "text": "<p>You could use a serialized DataSet to easily get the data from one place to another without having to write a lot of custom code, as the default DataSet already provides the necessary methods ( .WriteXML for example will serialize the DataSet to XML and write to a file). Your other application could then poll the appropriate directory for new files.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I have a C# console app "App1" that reads a row of data from a table in a SQL Server 2005 DB. I want App1 to pass all the data in this row to App2, another C# console app. What is the best way to do this? My first (naive) attempt was to do this: ``` object[] o = myrow.ItemArray; // make a string that separates each item by a space... for example "1 2 myVar". // pass this string to App2 via command line. ``` This has some flaws: what if one of the entries in the row was "my var" instead of "myVar"? Also, the order of the items would be hardcoded in the receiving app (App2). So what's the best way to do this? Would it be appropriate to pass an xml string to App2 via command line? Cheers!
One approach would be to serialize the row to XML and use that, except that DataRow (lacking a default constructor) can't be serialized. Instead you'd have to create a new DataTable and add that row to it. Then you could simply serialize the entire DataTable to XML and pass it to the other application, either as a command-line argument or by saving the XML to a file and passing the filename. Serializing a DataTable to XML is quite trivial thanks to the [DataTable.WriteXml](http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml.aspx) method.
176,625
<p>I have the following query in iSeries SQL which I output to a file.</p> <pre><code>SELECT SSLOTMAK, SSLOTMDL, SSLOTYER, sum(SSCOUNT) FROM prqhdrss GROUP BY SSLOTMAK, SSLOTMDL, SSLotyer HAVING sum(SSCOUNT) &gt; 4 ORDER BY SSLOTMAK, SSLOTMDL, SSLOTYER </code></pre> <p>When I run it, the field created be the sum(SSCOUNT) is a 31 Packed field. This does not allow me to send it to my PC. How can I force SQL to create the field as a non-packed field.</p>
[ { "answer_id": 177098, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 0, "selected": false, "text": "<p>How are you trying to bring it to your PC? Most iSeries methods I know will automatically convert that to a PC-readable format.</p>\n" }, { "answer_id": 177635, "author": "pmg", "author_id": 25324, "author_profile": "https://Stackoverflow.com/users/25324", "pm_score": 3, "selected": true, "text": "<p>Try this</p>\n\n<pre><code>SELECT SSLOTMAK, SSLOTMDL, SSLOTYER, cast(sum(SSCOUNT) as integer)\nFROM prqhdrss\nGROUP BY SSLOTMAK, SSLOTMDL, SSLotyer\nHAVING sum(SSCOUNT) &gt; 4\nORDER BY SSLOTMAK, SSLOTMDL, SSLOTYER\n</code></pre>\n\n<p>I've casted to integer because of the name of the column \"count\". If the column has floating-point values you can use <code>numeric(8, 2)</code> instead.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11270/" ]
I have the following query in iSeries SQL which I output to a file. ``` SELECT SSLOTMAK, SSLOTMDL, SSLOTYER, sum(SSCOUNT) FROM prqhdrss GROUP BY SSLOTMAK, SSLOTMDL, SSLotyer HAVING sum(SSCOUNT) > 4 ORDER BY SSLOTMAK, SSLOTMDL, SSLOTYER ``` When I run it, the field created be the sum(SSCOUNT) is a 31 Packed field. This does not allow me to send it to my PC. How can I force SQL to create the field as a non-packed field.
Try this ``` SELECT SSLOTMAK, SSLOTMDL, SSLOTYER, cast(sum(SSCOUNT) as integer) FROM prqhdrss GROUP BY SSLOTMAK, SSLOTMDL, SSLotyer HAVING sum(SSCOUNT) > 4 ORDER BY SSLOTMAK, SSLOTMDL, SSLOTYER ``` I've casted to integer because of the name of the column "count". If the column has floating-point values you can use `numeric(8, 2)` instead.
176,626
<p>I'm writing an article about editing pages in order to hand pick what you really want to print. There are many tools (like "Print What you like") but I also found this script. Anyone knows anything about it? I haven't found any kind of documentation or references.</p> <pre><code>javascript:document.body.contentEditable='true'; document.designMode='on'; void 0 </code></pre> <p>Thanks!</p>
[ { "answer_id": 176644, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 1, "selected": false, "text": "<p>document.designMode is supported in IE 4+ (which started it apparently) and FireFox 1.3+.\nYou turn it on and you can edit the content right in the browser, it's pretty trippy.\nI've never used it before but it sounds like it would be pretty perfect for hand picking printable information.</p>\n\n<p>Edited to say: It also appears to work in Google Chrome. I've only tested it in Chrome and Firefox, as those are the browsers in which I have a javascript console, so I can't guarantee it works in Internet Explorer as I've never personally used it. My understanding is that this was an IE-only property that the other browsers picked up and isn't currently in any standards, so I'd be surprised if Firefox and Chrome support it but IE stopped.</p>\n" }, { "answer_id": 176700, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 4, "selected": true, "text": "<p>The contentEditable property is what you want -- It's supported by IE, Safari (and by chrome as a byproduct), and I <em>think</em> firefox 3 (alas not FFX2). And hey, it's also part of HTML5 :D</p>\n\n<p>Firefox 2 supports designMode, but that is restricted to individual frames, whereas the contentEditable property applies applies to individual elements, so you can have your editable content play more nicely with your page :D</p>\n\n<p>[Edit (olliej): Removed example as contentEditable attribute doesn't get past SO's output filters (despite working in the preview) :( ]</p>\n\n<p>[Edit (olliej): I've banged up a very simple <a href=\"http://www.nerget.com/contentEditableDemo.html\" rel=\"noreferrer\">demo</a> to illustrate how it behaves]</p>\n\n<p>[Edit (olliej): So yes, the contentEditable attribute in the linked demo works fine in IE, Firefox, and Safari. Alas resizing is a css3 feature only webkit seems to support, and IE is doing its best to fight almost all of the CSS. <em>sigh</em>]</p>\n" }, { "answer_id": 176751, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>It enables the browser's in-built editing functionality where available. As is mentioned above, designMode is Gecko and contentEditable is everyone else (and added to Gecko 1.9). These features are used as the basis of (nearly?) every WYSIWYG editor built with HTML/Javascript. If you're simply typing/deleting, nothing more should be necessary than the script you provided. (Everything from 'void' on is superfluous though.)</p>\n\n<p>For documentation on how these features can be used in an application, the best reference is Mozilla's <a href=\"http://www.mozilla.org/editor/midas-spec.html\" rel=\"nofollow noreferrer\">Midas specification</a> (<a href=\"http://msdn.microsoft.com/en-us/library/aa969729(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a> may be of some use as well...).</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1657/" ]
I'm writing an article about editing pages in order to hand pick what you really want to print. There are many tools (like "Print What you like") but I also found this script. Anyone knows anything about it? I haven't found any kind of documentation or references. ``` javascript:document.body.contentEditable='true'; document.designMode='on'; void 0 ``` Thanks!
The contentEditable property is what you want -- It's supported by IE, Safari (and by chrome as a byproduct), and I *think* firefox 3 (alas not FFX2). And hey, it's also part of HTML5 :D Firefox 2 supports designMode, but that is restricted to individual frames, whereas the contentEditable property applies applies to individual elements, so you can have your editable content play more nicely with your page :D [Edit (olliej): Removed example as contentEditable attribute doesn't get past SO's output filters (despite working in the preview) :( ] [Edit (olliej): I've banged up a very simple [demo](http://www.nerget.com/contentEditableDemo.html) to illustrate how it behaves] [Edit (olliej): So yes, the contentEditable attribute in the linked demo works fine in IE, Firefox, and Safari. Alas resizing is a css3 feature only webkit seems to support, and IE is doing its best to fight almost all of the CSS. *sigh*]
176,673
<p>If I have a datetime field, how do I get just records created later than a certain time, ignoring the date altogether?</p> <p>It's a logging table, it tells when people are connecting and doing something in our application. I want to find out how often people are on later than 5pm. </p> <p>(Sorry - it is SQL Server. But this could be useful for other people for other databases)</p>
[ { "answer_id": 176682, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>The best thing I can think would be: don't use a DateTime field; well, you could use a lot of DATEADD/DATEPART etc, but it will be slow if you have a lot of data, as it can't really use an index here. Your DB may offer a suitable type natively - such as the TIME type in SQL Server 2008 - but you could just as easily store the time offset in minutes (for example).</p>\n" }, { "answer_id": 176684, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 3, "selected": false, "text": "<p>What database system are you using? Date/time functions vary widely.</p>\n\n<p>For Oracle, you could say</p>\n\n<pre><code>SELECT * FROM TABLE \n WHERE TO_CHAR(THE_DATE, 'HH24:MI:SS') BETWEEN '17:00:00' AND '23:59:59';\n</code></pre>\n\n<p>Also, you probably need to roll-over into the next day and also select times between midnight and, say, 6am.</p>\n" }, { "answer_id": 176686, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 5, "selected": true, "text": "<p>For SQL Server:</p>\n\n<pre><code>select * from myTable where datepart(hh, myDateField) &gt; 17\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx</a>.</p>\n" }, { "answer_id": 176689, "author": "thursdaysgeek", "author_id": 22523, "author_profile": "https://Stackoverflow.com/users/22523", "pm_score": 0, "selected": false, "text": "<p>Ok, I've got it.</p>\n\n<pre><code>select myfield1, \n myfield2, \n mydatefield\n from mytable\n where datename(hour, mydatefield) &gt; 17\n</code></pre>\n\n<p>This will get me records with a mydatefield with a time later than 5pm.</p>\n" }, { "answer_id": 176909, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>Another Oracle method for simple situations:</p>\n\n<pre><code>select ...\nfrom ...\nwhere EXTRACT(HOUR FROM my_date) &gt;= 17\n/\n</code></pre>\n\n<p><a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions050.htm#SQLRF00639\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions050.htm#SQLRF00639</a></p>\n\n<p>Tricky for some questions though, like all records with the time between 15:03:21 and 15:25:45. I'd also use the TO_CHAR method there.</p>\n" }, { "answer_id": 176997, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>In MySQL, this would be</p>\n\n<pre><code>where time(datetimefield) &gt; '17:00:00'\n</code></pre>\n" }, { "answer_id": 193162, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>In Informix, assuming that you use a DATETIME YEAR TO SECOND field to hold the full date, you'd write:</p>\n\n<pre><code>WHERE EXTEND(dt_column, HOUR TO SECOND) &gt; DATETIME(17:00:00) HOUR TO SECOND\n</code></pre>\n\n<p>'EXTEND' can indeed contract the set of fields (as well as extend it, as the name suggests).</p>\n\n<p>As Thilo noted, this is an area of extreme variability between DBMS (and Informix is certainly one of the variant ones).</p>\n" }, { "answer_id": 38336513, "author": "Zaxxon", "author_id": 4351706, "author_profile": "https://Stackoverflow.com/users/4351706", "pm_score": 1, "selected": false, "text": "<p>For MSSQL use the CONVERT method:</p>\n\n<pre><code>\nDECLARE @TempDate datetime = '1/2/2016 6:28:03 AM'\nSELECT \n @TempDate as PassedInDate, \n CASE \n WHEN CONVERT(nvarchar(30), @TempDate, 108) &lt; '06:30:00' then 'Before 6:30am'\n ELSE 'On or after 6:30am'\n END,\n CASE \n WHEN CONVERT(nvarchar(30), @TempDate, 108) &gt;= '10:30:00' then 'On or after 10:30am'\n ELSE 'Before 10:30am'\n END \n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22523/" ]
If I have a datetime field, how do I get just records created later than a certain time, ignoring the date altogether? It's a logging table, it tells when people are connecting and doing something in our application. I want to find out how often people are on later than 5pm. (Sorry - it is SQL Server. But this could be useful for other people for other databases)
For SQL Server: ``` select * from myTable where datepart(hh, myDateField) > 17 ``` See <http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx>.
176,695
<p>The attached screenshot is from OS X/Firefox 3. Note that the center tab (an image) has a dotted line around it, apparently because it was the most-recently selected tab. Is there a way I can eliminate this dotted line in CSS or JavaScript? (Hmmm...the free image hosting service has reduced the size of the image. But if you could see it, you'd notice a dotted-line select area around the block.)</p> <p><a href="http://www.freeimagehosting.net/uploads/th.fadf78173b.png" rel="nofollow noreferrer">Screen Shot http://www.freeimagehosting.net/uploads/th.fadf78173b.png</a></p>
[ { "answer_id": 176701, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>In your onclick event, this.blur()</p>\n\n<p>or, specifically set focus somewhere else.</p>\n" }, { "answer_id": 176702, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<p>You can start by looking at the :focus and :active pseudo classes, although you probably <em>shouldn't</em> be completely removing any formatting from these cases, since they are an invaluable usability aid.</p>\n" }, { "answer_id": 176719, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 5, "selected": true, "text": "<p>You'll want to add the following line to your css:</p>\n\n<pre><code>a:active, a:focus { outline-style: none; -moz-outline-style:none; }\n</code></pre>\n\n<p>(Assuming your tabs are done using the a element, of course.)</p>\n\n<p><em>[edit] On request from everyone else, for future viewers of this it should be noted that the outline is essential for keyboard-navigators as it designates where your selection is and, so, gives a hint to where your next 'tab' might go. Thus, it's inadvisable to remove this dotted-line selection. But it is still useful to know how you would do it, if you deem it necessary.</em></p>\n\n<p><em>And as mentioned in a comment, if you are only dealing with FF > v1.5, feel free to leave out the -moz-outline-style:none;</em></p>\n" }, { "answer_id": 176725, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>For starters, try this </p>\n\n<pre><code>*,*:hover,*:focus,*:active { outline: 0px none; } \n</code></pre>\n\n<p>This will however decrease usability. </p>\n\n<p>You'll want to selectively apply alternative effects where relevant to give people such as those whom navigate primarily with the TAB key have an idea of what currently has focus. </p>\n\n<pre><code>div.foo:active, \ndiv.foo:focus, \ndiv.foo:hover\n{ \n /* Alternative Style */\n}\n</code></pre>\n" }, { "answer_id": 15012369, "author": "AshAndrien", "author_id": 1934951, "author_profile": "https://Stackoverflow.com/users/1934951", "pm_score": 0, "selected": false, "text": "<p>using </p>\n\n<pre><code>*:focus {outline:0px;} \n</code></pre>\n\n<p>will remove styling for inputs and textareas when selected with the mouse. Make sure you append these styles with a border for these form items if you choose to remove all outlines on :focus.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17307/" ]
The attached screenshot is from OS X/Firefox 3. Note that the center tab (an image) has a dotted line around it, apparently because it was the most-recently selected tab. Is there a way I can eliminate this dotted line in CSS or JavaScript? (Hmmm...the free image hosting service has reduced the size of the image. But if you could see it, you'd notice a dotted-line select area around the block.) [Screen Shot http://www.freeimagehosting.net/uploads/th.fadf78173b.png](http://www.freeimagehosting.net/uploads/th.fadf78173b.png)
You'll want to add the following line to your css: ``` a:active, a:focus { outline-style: none; -moz-outline-style:none; } ``` (Assuming your tabs are done using the a element, of course.) *[edit] On request from everyone else, for future viewers of this it should be noted that the outline is essential for keyboard-navigators as it designates where your selection is and, so, gives a hint to where your next 'tab' might go. Thus, it's inadvisable to remove this dotted-line selection. But it is still useful to know how you would do it, if you deem it necessary.* *And as mentioned in a comment, if you are only dealing with FF > v1.5, feel free to leave out the -moz-outline-style:none;*
176,709
<p>I have a set of configuration items I need to persist to a "human readable" file. These items are in a hierarchy:</p> <pre> Device 1 Name Channel 1 Name Size ... Channel N Name ... Device M Name Channel 1 </pre> <p>Each of these item could be stored in a Dictionary with a string Key and a value. They could also be in a structure/DTO.</p> <p>I don't care about the format of the file as long as it's human readable. It could be XML or it could have something more like INI format</p> <pre> [Header] Key=value Key2=value ... </pre> <p>Is there a way to minimize the amount of boiler plate code I would need to write to manage storing/reading configuration items?</p> <p>Should I just create Data Transfer Objects (DTO)/structures and mark them serializable (Does that generate bloated XML still human readable?)</p> <p>Is there other suggestions?</p> <p>Edit: Not that the software has to <strong>write</strong> as well as <strong>read</strong> the config. That leaves app.config out.</p>
[ { "answer_id": 176713, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/yaml\" rel=\"nofollow noreferrer\">YAML for .NET</a></p>\n" }, { "answer_id": 176715, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 1, "selected": false, "text": "<p>I suspect that what you'll want to use is an app.config file which contains your settings in an XML format that .NET will be able to load in using the System.Configuration namesapce.</p>\n<p>More info here: <a href=\"https://web.archive.org/web/20200810043157/http://geekswithblogs.net:80/akraus1/articles/64871.aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 176727, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 0, "selected": false, "text": "<p>I've generally used the registry for storing configurations (I know, bad me!), but using System.Xml to read/write a lightweight XML file isn't hard. In fact, I've done just that recently for a plugin project that uses XML documents to communicate with its host as well as store its own persistent settings.</p>\n\n<p>There is also the System.Configuration namespace, but I've not really dealt with it.</p>\n" }, { "answer_id": 176731, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "<p>I think both the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx\" rel=\"nofollow noreferrer\">XmlSerializer</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx\" rel=\"nofollow noreferrer\">NetDataContractSerializer</a> create human readable XML. <a href=\"https://stackoverflow.com/questions/109318/using-c-what-limitations-if-any-are-there-in-using-the-xmlserializer#109393\">I prefer</a> the NetDataContractSerializer because it can do things the XmlSerializer cannot, but those extra features are probably more than you need for this. If you already have classes written for your configurations, one of these two are probably your shortest path to victory.</p>\n\n<p>You could also write your configurations to the local app.config file, or a sub-config file using custom <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection(VS.80).aspx\" rel=\"nofollow noreferrer\">ConfigSections</a> and the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx\" rel=\"nofollow noreferrer\">Configuration class</a>.</p>\n" }, { "answer_id": 176776, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 0, "selected": false, "text": "<p>My preference in this situation is to create a DataSet with DataTables for the configuration data arranged in a nice relational way - then use DataSet.WriteXML() to save it to a configuration file.</p>\n\n<p>Then to load it again, you just use DataSet.ReadXML() and it's back in a nice query-able object.</p>\n\n<p>This is an example config file that my app allows the user to edit in a Text Editor window: </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n&lt;!--****************************************************************\n Config File: FileToExcel_test.cfg\n Author: Ron Savage\n Date: 06/20/2008\n\n Description: \n File to test parsing a file into an Excel workbook.\n\n Modification History: \n Date Init Comment\n 06/20/2008 RS Created.\n******************************************************************--&gt;\n\n&lt;!--********************************************************************\n Global Key Definitions\n********************************************************************--&gt;\n &lt;config key=\"sqlTimeout\" value=\"1800\"/&gt;\n &lt;config key=\"emailSMTPServer\" value=\"smtp-server.austin.rr.com\"/&gt;\n &lt;config key=\"LogFile\" value=\"FiletoExcel_test_{yyyy}{mm}{hh}.log\"/&gt;\n &lt;config key=\"MaxEntries\" value=\"1\"/&gt;\n\n&lt;!--********************************************************************\n Delimiter Configurations\n********************************************************************--&gt;\n &lt;config key=\"pipe\" value=\"|\"/&gt;\n\n\n&lt;!--********************************************************************\n Source / Target Entries\n********************************************************************--&gt;\n &lt;config key=\"source_1\" value=\"FILE, c:\\inetpub\\ftproot\\filetoexcel.txt, pipe, , , , , \"/&gt;\n &lt;config key=\"target_1\" value=\"XLS, REPLACE, c:\\inetpub\\ftproot\\filetoexcel1.xls, , , , , , , ,c:\\inetpub\\ftproot\\filetoexcel_template.xls, ,3\"/&gt;\n &lt;config key=\"notify_1\" value=\"store_error, store_success\"/&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>When I load it into the DataSet, all the non-comment tags reside in a table named <strong>Config</strong> with fields <strong>Key</strong> &amp; <strong>value</strong>. Very easy to search.</p>\n" }, { "answer_id": 176845, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 2, "selected": false, "text": "<p>If you serialize your structure to JSON you get a simpler representation of your object than in XML. </p>\n\n<p>Here's a sample from James Netwon-King's JSON.Net site:</p>\n\n<pre><code>Product product = new Product(); \nproduct.Name = \"Apple\"; \nproduct.Expiry = new DateTime(2008, 12, 28); \nproduct.Price = 3.99M; \nproduct.Sizes = new string[] { \"Small\", \"Medium\", \"Large\" }; \n\nstring json = JavaScriptConvert.SerializeObject(product);\n//{\n// \"Name\": \"Apple\",\n// \"Expiry\": new Date(1230422400000),\n// \"Price\": 3.99,\n// \"Sizes\": [\n// \"Small\",\n// \"Medium\",\n// \"Large\"\n// ]\n//} \n\nProduct deserializedProduct = JavaScriptConvert.DeserializeObject&lt;Product&gt;(json);\n</code></pre>\n\n<p>You can read his blog and download JSON.Net <a href=\"http://james.newtonking.com/pages/json-net.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 176847, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": true, "text": "<p>See the <a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow noreferrer\">FileHelpers</a> library. It's got tons of stuff for reading from and writing to a lot of different formats - and all you have to do is mark up your objects with attributes and call Save(). Sort of like ORM for flat files.</p>\n" }, { "answer_id": 176891, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>I'd use a data structure that can be serialized into XML - in fact, since I'm lazy, I'd use an ADO.NET DataSet, since it has a simple serialization format that you can produce without having to think terribly hard.</p>\n\n<p>As far as making it human-readable goes: if it just has to be human-readable (and not human-modifiable, which I think is what you're describing here), I'd build an XSLT transform and use it to produce an HTML version of the configuration data whenever I wrote out the XML. That gives you as fine-grained control over the visual presentation of the data as you could possibly ask for.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
I have a set of configuration items I need to persist to a "human readable" file. These items are in a hierarchy: ``` Device 1 Name Channel 1 Name Size ... Channel N Name ... Device M Name Channel 1 ``` Each of these item could be stored in a Dictionary with a string Key and a value. They could also be in a structure/DTO. I don't care about the format of the file as long as it's human readable. It could be XML or it could have something more like INI format ``` [Header] Key=value Key2=value ... ``` Is there a way to minimize the amount of boiler plate code I would need to write to manage storing/reading configuration items? Should I just create Data Transfer Objects (DTO)/structures and mark them serializable (Does that generate bloated XML still human readable?) Is there other suggestions? Edit: Not that the software has to **write** as well as **read** the config. That leaves app.config out.
See the [FileHelpers](http://filehelpers.sourceforge.net/) library. It's got tons of stuff for reading from and writing to a lot of different formats - and all you have to do is mark up your objects with attributes and call Save(). Sort of like ORM for flat files.
176,712
<p>I'd like to find the base url of my application, so I can automatically reference other files in my application tree...</p> <p>So given a file config.php in the base of my application, if a file in a subdirectory includes it, knows what to prefix a url with. </p> <pre><code>application/config.php application/admin/something.php application/css/style.css </code></pre> <p>So given that <code>http://www.example.com/application/admin/something.php</code> is accessed, I want it to be able to know that the css file is in <code>$approot/css/style.css</code>. In this case, <code>$approot</code> is "<code>/application</code>" but I'd like it to know if the application is installed elsewhere.</p> <p>I'm not sure if it's possible, many applications (phpMyAdmin, Squirrelmail I think) have to set a config variable to begin with. It would be more user friendly if it just knew.</p>
[ { "answer_id": 176729, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 1, "selected": false, "text": "<p>Unless you track this yourself, I don't believe this would have a definition. Or rather, you're asking PHP to track something that you're somewhat arbitrarily defining.</p>\n\n<p>The long and short of it is, if I'm understanding your question correctly, I don't believe what you're asking for exists, at least not as \"core\" PHP; a given framework may provide a \"root\" URL relative to a directory structure that <em>it</em> understands.</p>\n\n<p>Does that make sense?</p>\n" }, { "answer_id": 176730, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "<p>The REQUEST_URI combined with <a href=\"http://us2.php.net/manual/en/function.dirname.php\" rel=\"nofollow noreferrer\">dirname()</a> can tell you your current directory, relevant to the URL path:</p>\n\n<pre><code>&lt;?php\n echo dirname($_SERVER[\"REQUEST_URI\"]);\n?&gt;\n</code></pre>\n\n<p>So <a href=\"http://example.com/test/test.php\" rel=\"nofollow noreferrer\">http://example.com/test/test.php</a> prints \"/test\" or <a href=\"http://example.com/\" rel=\"nofollow noreferrer\">http://example.com/</a> prints \"/\" which you can use for generating links to refer to other pages relative to the current path.</p>\n\n<p><strong>EDIT</strong>: just realized on re-reading that you might be asking about the on-disk path as opposed to the URL path. In that case, you want PHP's <a href=\"http://us2.php.net/getcwd\" rel=\"nofollow noreferrer\">getcwd()</a> function instead:</p>\n\n<pre><code>&lt;?php\n echo getcwd();\n?&gt;\n</code></pre>\n" }, { "answer_id": 176736, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>Put this in your config.php (which is in your app's root dir):</p>\n\n<pre><code>$approot = substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']));\n</code></pre>\n\n<p>I think that'll do it.</p>\n" }, { "answer_id": 176756, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 0, "selected": false, "text": "<p>One solution would be to use relative paths for everything, that way it does not matter where the app is installed. For example, to get to your style sheet, use this:</p>\n\n<pre><code>../css/style.css\n</code></pre>\n" }, { "answer_id": 176760, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "<p>If you want the path on the filesystem you can use <code>$_SERVER['DOCUMENT_ROOT']</code> <br />\nIf you just want the path of the file that appears in the URL after the domain use <code>$_SERVER['REQUEST_URI']</code></p>\n" }, { "answer_id": 177143, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 0, "selected": false, "text": "<p>I've never found a way to make it so.</p>\n\n<p>I always end up setting a config variable with the server path to one level above web root. Then it's:</p>\n\n<ul>\n<li>$configVar . 'public/whatever/' for stuff inside root, </li>\n<li>but you can also include from outside with $configVar . 'phpInc/db.inc.php/' etc.</li>\n</ul>\n" }, { "answer_id": 177368, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 0, "selected": false, "text": "<p>This works like a charm for me, anywhere I deploy, with or without rewrite rules:</p>\n\n<p>$baseDir = 'http://'.$_SERVER['HTTP_HOST'].(dirname($_SERVER['SCRIPT_NAME']) != '/' ? dirname($_SERVER[\"SCRIPT_NAME\"]).'/' : '/');</p>\n" }, { "answer_id": 185725, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 5, "selected": true, "text": "<p>I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it.</p>\n\n<pre><code>define('ABSPATH', str_replace('\\\\', '/', dirname(__FILE__)) . '/');\n\n$tempPath1 = explode('/', str_replace('\\\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));\n$tempPath2 = explode('/', substr(ABSPATH, 0, -1));\n$tempPath3 = explode('/', str_replace('\\\\', '/', dirname($_SERVER['PHP_SELF'])));\n\nfor ($i = count($tempPath2); $i &lt; count($tempPath1); $i++)\n array_pop ($tempPath3);\n\n$urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);\n\nif ($urladdr{strlen($urladdr) - 1}== '/')\n define('URLADDR', 'http://' . $urladdr);\nelse\n define('URLADDR', 'http://' . $urladdr . '/');\n\nunset($tempPath1, $tempPath2, $tempPath3, $urladdr);\n</code></pre>\n\n<p>The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod_rewrite situations.</p>\n" }, { "answer_id": 4152728, "author": "rakesh sadaka", "author_id": 504269, "author_profile": "https://Stackoverflow.com/users/504269", "pm_score": 1, "selected": false, "text": "<p>url root of the application can be found by </p>\n\n<pre><code>$protocol = (strstr('https',$_SERVER['SERVER_PROTOCOL']) === false)?'http':'https';\n$url = $protocol.'://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['REQUEST_URI']);\n</code></pre>\n\n<p>this code will return url path of any application whether be online or on offline server.</p>\n\n<p>I've not made proper check for proper '/'. Please modify it for slashes.</p>\n\n<p>this file should be placed in root.</p>\n\n<p>example : \nif \napplication url : </p>\n\n<pre><code>http://localhost/test/test/test.php\n</code></pre>\n\n<p>then this code will return </p>\n\n<pre><code>http://localhost/test/test\n</code></pre>\n\n<p>Thanks</p>\n" }, { "answer_id": 12583387, "author": "Murtaza Baig", "author_id": 1697315, "author_profile": "https://Stackoverflow.com/users/1697315", "pm_score": 3, "selected": false, "text": "<p>You can find the base url with the folowing code:</p>\n\n<pre><code>define('SITE_BASE_PATH','http://'.preg_replace('/[^a-zA-Z0-9]/i','',$_SERVER['HTTP_HOST']).'/'.str_replace('\\\\','/',substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']))).'/');\n</code></pre>\n\n<p>Short and best.</p>\n" }, { "answer_id": 38683743, "author": "Richard Leishman", "author_id": 6659928, "author_profile": "https://Stackoverflow.com/users/6659928", "pm_score": 0, "selected": false, "text": "<p>This is what I have used in my app which works fine, I also use a custom port so I had to allow for this also.</p>\n\n<pre><code>define('DOC_URL', ($_SERVER['HTTPS']=='on'?'https':'http').'://'.$_SERVER['SERVER_NAME'].(!in_array($_SERVER['SERVER_PORT'], array(80,443))?':'.$_SERVER['SERVER_PORT']:'')).dirname($_SERVER['REQUEST_URI']);\n</code></pre>\n\n<p>Then I use it by typing the following...</p>\n\n<pre><code>&lt;img src=\"&lt;?php echo DOC_URL; ?&gt;/_img/logo.png\" /&gt;\n</code></pre>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14253/" ]
I'd like to find the base url of my application, so I can automatically reference other files in my application tree... So given a file config.php in the base of my application, if a file in a subdirectory includes it, knows what to prefix a url with. ``` application/config.php application/admin/something.php application/css/style.css ``` So given that `http://www.example.com/application/admin/something.php` is accessed, I want it to be able to know that the css file is in `$approot/css/style.css`. In this case, `$approot` is "`/application`" but I'd like it to know if the application is installed elsewhere. I'm not sure if it's possible, many applications (phpMyAdmin, Squirrelmail I think) have to set a config variable to begin with. It would be more user friendly if it just knew.
I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it. ``` define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/'); $tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME']))); $tempPath2 = explode('/', substr(ABSPATH, 0, -1)); $tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF']))); for ($i = count($tempPath2); $i < count($tempPath1); $i++) array_pop ($tempPath3); $urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3); if ($urladdr{strlen($urladdr) - 1}== '/') define('URLADDR', 'http://' . $urladdr); else define('URLADDR', 'http://' . $urladdr . '/'); unset($tempPath1, $tempPath2, $tempPath3, $urladdr); ``` The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod\_rewrite situations.
176,720
<p>What is the easiest way to do this? Is it possible with managed code?</p>
[ { "answer_id": 176734, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 6, "selected": true, "text": "<pre><code>this.BackgroundImage = //Image\nthis.FormBorderStyle = FormBorderStyle.None;\nthis.Width = this.BackgroundImage.Width;\nthis.Height = this.BackgroundImage.Height;\nthis.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color\n</code></pre>\n\n<p>This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular.</p>\n" }, { "answer_id": 176748, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 3, "selected": false, "text": "<p>@Geoff shows the right way in winforms. </p>\n\n<p>But If you are planning to use WPF instead of Winforms then WPF(.NET3.0+) gives very flexible ways to create anyshape custom windows. Check out this article also <a href=\"http://www.codeproject.com/KB/WPF/wpfpopup.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/WPF/wpfpopup.aspx</a></p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
What is the easiest way to do this? Is it possible with managed code?
``` this.BackgroundImage = //Image this.FormBorderStyle = FormBorderStyle.None; this.Width = this.BackgroundImage.Width; this.Height = this.BackgroundImage.Height; this.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color ``` This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular.
176,743
<p>I'm writing a .NET forms control to edit HTML using MSHTML. I am creating some custom elements and want to make them effectively read-only. I thought I could go about this by focusing on the entire element any time focus entered anywhere in that element but the HtmlElement.Focus() doesn't select the entire element and I don't seem to be able to capture entry of the cursor.</p> <p>Another option would be to raise an event whenever the text of the element is changed (on KeyDown I expect) but I can't get that event to fire, either. Any ideas about why my expectations about event behavior is wrong or alternate suggestions for implementation?</p>
[ { "answer_id": 177798, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 0, "selected": false, "text": "<p>In case you are trying to apply readonly behavior to an User Input control, you can try using @readonly attribute of that control. Otherwise you could also add event listeners for appropriate UI events (keydown, mousedown) and prevent their default behavior (return false, or event.returnValue = false). As for custom events dispatch, you can indeed do that. Use event name that is known to IE. And another hint could be: register an onchange event handler and revert value of control to the value of defaultValue (property of any input controls).</p>\n\n<p>Hope some of ideas will help.</p>\n" }, { "answer_id": 179506, "author": "dmo", "author_id": 1807, "author_profile": "https://Stackoverflow.com/users/1807", "pm_score": 2, "selected": true, "text": "<p>I found that setting the attribute:</p>\n\n<pre><code>contentEditable=false\n</code></pre>\n\n<p>Resulted in the desired behavior.</p>\n" } ]
2008/10/06
[ "https://Stackoverflow.com/questions/176743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ]
I'm writing a .NET forms control to edit HTML using MSHTML. I am creating some custom elements and want to make them effectively read-only. I thought I could go about this by focusing on the entire element any time focus entered anywhere in that element but the HtmlElement.Focus() doesn't select the entire element and I don't seem to be able to capture entry of the cursor. Another option would be to raise an event whenever the text of the element is changed (on KeyDown I expect) but I can't get that event to fire, either. Any ideas about why my expectations about event behavior is wrong or alternate suggestions for implementation?
I found that setting the attribute: ``` contentEditable=false ``` Resulted in the desired behavior.
176,749
<p>I have a web service that uses Python's SimpleJSON to serialize JSON, and a javascript/ client that uses Google's Visualization <a href="http://code.google.com/apis/visualization/documentation/reference.html" rel="nofollow noreferrer">API</a>. When I try to read in the JSON response using Google Data Table's Query method, I am getting a "invalid label" error. </p> <p>I noticed that Google spreadsheet outputs JSON without quotes around the object keys. I tried reading in JSON without the quotes and that works. I was wondering what was the best way to get SimpleJSON output to be read into Google datable using </p> <p><code>query = new google.visualization.Query("http://www.myuri.com/api/")</code>. </p> <p>I could use a regex to remove the quotes, but that seems sloppy. The javascript JSON parsing libraries I've tried won't read in JSON syntax without quotes around the object keys.</p> <p>Here's some good background reading re: quotes around object keys: </p> <p><a href="http://simonwillison.net/2006/Oct/11/json/" rel="nofollow noreferrer">http://simonwillison.net/2006/Oct/11/json/</a>.</p>
[ { "answer_id": 176780, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "<p>Are you certain the Google API is expecting JSON? In my experience Google's APIs tend not to be massively broken in a manner you're describing -- it could be that they're actually expecting a different format that merely resembles JSON.</p>\n\n<hr>\n\n<p>Further poking around reveals instructions for retrieving data in the format Google expects:</p>\n\n<blockquote>\n <p>For example, to get the dataSourceUrl\n from a Google Spreadsheet, do the\n following:</p>\n \n <ol>\n <li>In your spreadsheet, select the range of cells.</li>\n <li>Select 'Insert' and then 'Gadget' from the menu.</li>\n <li>Open the gadget's menu by clicking on the top-right selector.</li>\n <li>Select menu option 'Get data source URL'.</li>\n </ol>\n</blockquote>\n\n<p>I did this and opened the URL in my browser. The data it was returning was certainly not JSON:</p>\n\n<pre><code>google.visualization.Query.setResponse(\n{requestId:'0',status:'ok',signature:'1464883469881501252',\ntable:{cols: [{id:'A',label:'',type:'t',pattern:''},\n{id:'B',label:'',type:'t',pattern:''}],\nrows: [[{v:'a'},{v:'h'}],[{v:'b'},{v:'i'}],[{v:'c'},{v:'j'}],[{v:'d'},{v:'k'}],[{v:'e'},{v:'l'}],[{v:'f'},{v:'m'}],[{v:'g'},{v:'n'}]]}});\n</code></pre>\n\n<p>It looks like the result is intended to be directly executed by the browser. Try modifying your code to do something like this:</p>\n\n<pre><code># old\nreturn simplejson.dumps ({\"requestId\": 1, \"status\": \"ok\", ...})\n\n# new\njson = simplejson.dumps ({\"requestId\": 1, \"status\": \"ok\", ...})\nreturn \"google.visualization.Query.setResponse(%r);\" % json\n</code></pre>\n" }, { "answer_id": 176814, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "<p>The \"invalid label\" error is usually due to a blind eval() on the JSON string, resulting in property names being mistaken as labels (because they have the same syntax -- \"foo:\").</p>\n\n<pre><code>eval(\"{ foo: 42, bar: 43 }\"); // Results in invalid label\n</code></pre>\n\n<p>The quick remedy is to make sure your JSON string has parenthesis enclosing the curly braces:</p>\n\n<pre><code>eval(\"({ foo: 42, bar: 43 })\"); // Works\n</code></pre>\n\n<p>Try enclosing your JSON string in parenthesis to see if the \"invalid label\" error goes away.</p>\n" }, { "answer_id": 12973868, "author": "nickl-", "author_id": 1522117, "author_profile": "https://Stackoverflow.com/users/1522117", "pm_score": 0, "selected": false, "text": "<p>As it turns out <strong>:mod:json</strong> would also choke at strings in single quotes. This will sort things out though:</p>\n\n<h1>Parse JavaScript object as JSON in python:</h1>\n\n<h2>solution:</h2>\n\n<pre><code>&gt;&gt;&gt; from re import sub\n&gt;&gt;&gt; import json\n&gt;&gt;&gt; js = \"{ a: 'a' }\"\n&gt;&gt;&gt; json.loads(sub(\"'\", '\"', sub('\\s(\\w+):', r' \"\\1\":', js)))\n{u'a': u'a'}\n</code></pre>\n\n<p><strong>Edit:</strong> (edge cases reviewed)</p>\n\n<p>So it was brought up that the suggested solution would not cope with all cases and specifically with something like</p>\n\n<blockquote>\n <p>e.g. {foo: \"a sentence: right here!\"} will get changed to {\"foo\": \"a \"sentence\": right here!\"}<br>\n – Jason S Apr 12 at 18:03</p>\n</blockquote>\n\n<p>To resolve that we simply need to ensure that we are in fact working with a key and not simply a colon in a string so we do a little look behind magic to hint at a comma(,) or a curly brace({) presence to ensure we have it proper, like so:</p>\n\n<h2>colon in string:</h2>\n\n<pre><code>&gt;&gt;&gt; js = \"{foo: 'a sentence: right here!'}\"\n&gt;&gt;&gt; json.loads(sub(\"'\", '\"', sub('(?&lt;={|,)\\s*(\\w+):', r' \"\\1\":', js)))\n{u'foo': u'a sentence: right here!'}\n</code></pre>\n\n<p>Which of course is the same as doing:</p>\n\n<pre><code>&gt;&gt;&gt; js = \"{foo: 'a sentence: right here!'}\"\n&gt;&gt;&gt; json.loads(sub('(?&lt;={|,)\\s*(\\w+):', r' \"\\1\":', js).replace(\"'\",'\"'))\n{u'foo': u'a sentence: right here!'} \n</code></pre>\n\n<p>But then I pointed out that this is not the only flaw because what about quotes:</p>\n\n<p>If we are also concerned about escaped quotes we will have to be slightly more specific as to what constitutes a string. The first quote will follow either a curly brace({) a space(\\s) or a colon(:) while the last matching quote will come before either a comma(,) or a closing curly brace(}) then we can consider everything in between as part of the same string, like so:</p>\n\n<h2>additional quotes in string:</h2>\n\n<pre><code>&gt;&gt;&gt; js = \"{foo: 'a sentence: it\\'s right here!'}\"\n&gt;&gt;&gt; json.loads(\n... sub(\"(?&lt;=\\s|{|:)'(.*?)'(?=,|})\", \n... r'\"\\1\"', \n... sub('(?&lt;={|,)\\s*(\\w+):', r' \"\\1\":', js))\n... )\n{u'foo': u\"a sentence: it's right here!\"}\n</code></pre>\n\n<p>Watch this space as more edge cases are revealed and solved. Can you spot another? </p>\n\n<p>Or for something more complex perhaps, a real world example as returned by <code>npm view</code>:</p>\n\n<h2>From:</h2>\n\n<blockquote class=\"spoiler\">\n <p> <pre>{ name: 'chuck',\n description: 'Chuck Norris joke dispenser.',\n 'dist-tags': { latest: '0.0.3' },\n versions: '0.0.3',\n maintainers: 'qard ',\n time: { '0.0.3': '2011-08-19T22:00:54.744Z' },\n author: 'Stephen Belanger ',\n repository: \n { type: 'git',\n url: 'git://github.com/qard/chuck.git' },\n version: '0.0.3',\n dependencies: { 'coffee-script': '>= 1.1.1' },\n keywords: \n [ 'chuck',\n 'norris',\n 'jokes',\n 'funny',\n 'fun' ],\n bin: { chuck: './bin/chuck' },\n main: 'index',\n engines: { node: '>= 0.4.1 &lt; 0.5.0' },\n devDependencies: {},\n dist: \n { shasum: '3af700056794400218f99b7da1170a4343f355ec',\n tarball: '<a href=\"http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz\" rel=\"nofollow\">http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz</a>' },\n scripts: {},\n directories: {},\n optionalDependencies: {} }</pre></p>\n</blockquote>\n\n<h2>To:</h2>\n\n<blockquote class=\"spoiler\">\n <p> <pre>{u'author': u'Stephen Belanger ',\n u'bin': {u'chuck': u'./bin/chuck'},\n u'dependencies': {u'coffee-script': u'>= 1.1.1'},\n u'description': u'Chuck Norris joke dispenser.',\n u'devDependencies': {},\n u'directories': {},\n u'dist': {u'shasum': u'3af700056794400218f99b7da1170a4343f355ec',\n u'tarball': u'<a href=\"http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz\" rel=\"nofollow\">http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz</a>'},\n u'dist-tags': {u'latest': u'0.0.3'},\n u'engines': {u'node': u'>= 0.4.1 &lt; 0.5.0'},\n u'keywords': [u'chuck', u'norris', u'jokes', u'funny', u'fun'],\n u'main': u'index',\n u'maintainers': u'qard ',\n u'name': u'chuck',\n u'optionalDependencies': {},\n u'repository': {u'type': u'git', u'url': u'git://github.com/qard/chuck.git'},\n u'scripts': {},\n u'time': {u'0.0.3': u'2011-08-19T22:00:54.744Z'},\n u'version': u'0.0.3',\n u'versions': u'0.0.3'}</pre></p>\n</blockquote>\n\n<p>Works for me =)</p>\n\n<p>nJoy!</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/176749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
I have a web service that uses Python's SimpleJSON to serialize JSON, and a javascript/ client that uses Google's Visualization [API](http://code.google.com/apis/visualization/documentation/reference.html). When I try to read in the JSON response using Google Data Table's Query method, I am getting a "invalid label" error. I noticed that Google spreadsheet outputs JSON without quotes around the object keys. I tried reading in JSON without the quotes and that works. I was wondering what was the best way to get SimpleJSON output to be read into Google datable using `query = new google.visualization.Query("http://www.myuri.com/api/")`. I could use a regex to remove the quotes, but that seems sloppy. The javascript JSON parsing libraries I've tried won't read in JSON syntax without quotes around the object keys. Here's some good background reading re: quotes around object keys: <http://simonwillison.net/2006/Oct/11/json/>.
Are you certain the Google API is expecting JSON? In my experience Google's APIs tend not to be massively broken in a manner you're describing -- it could be that they're actually expecting a different format that merely resembles JSON. --- Further poking around reveals instructions for retrieving data in the format Google expects: > > For example, to get the dataSourceUrl > from a Google Spreadsheet, do the > following: > > > 1. In your spreadsheet, select the range of cells. > 2. Select 'Insert' and then 'Gadget' from the menu. > 3. Open the gadget's menu by clicking on the top-right selector. > 4. Select menu option 'Get data source URL'. > > > I did this and opened the URL in my browser. The data it was returning was certainly not JSON: ``` google.visualization.Query.setResponse( {requestId:'0',status:'ok',signature:'1464883469881501252', table:{cols: [{id:'A',label:'',type:'t',pattern:''}, {id:'B',label:'',type:'t',pattern:''}], rows: [[{v:'a'},{v:'h'}],[{v:'b'},{v:'i'}],[{v:'c'},{v:'j'}],[{v:'d'},{v:'k'}],[{v:'e'},{v:'l'}],[{v:'f'},{v:'m'}],[{v:'g'},{v:'n'}]]}}); ``` It looks like the result is intended to be directly executed by the browser. Try modifying your code to do something like this: ``` # old return simplejson.dumps ({"requestId": 1, "status": "ok", ...}) # new json = simplejson.dumps ({"requestId": 1, "status": "ok", ...}) return "google.visualization.Query.setResponse(%r);" % json ```
176,777
<p>I'm trying to build a proxy module for .NET, but I'm having trouble copying the Headers from the current request to the new request. I am setting the headers of the new request, because I want the proxy to support SOAP requests. Here is a portion of my code. I can post everything if need, but this is the only part that seems related to the issue I am having:</p> <pre> <code> HttpApplication app = (HttpApplication)sender; // sender from context.BeginRequest event HttpRequest crntReq = app.Request; // set a reference to request object for easier access HttpWebRequest proxyReq = (HttpWebRequest)HttpWebRequest.Create(crntReq.Url.AbsoluteUri); // parse headers from current httpcontext.request.headers and add each name->value to the // new request object foreach (string header in crntReq.Headers) { proxyReq.Headers.Add(header, crntReq.Headers[header]); // throws exception :( } </code> </pre> <p><br /></p> <p>When my code hits the foreach loop, it throws an exception for the Headers.Add function. I'm assuming the collection has access restrictions, for security purposes. It appears that some of the header values are accessible with properties for the HttpWebRequest object itself. However in this case I'd rather get rid of the abstraction and set the properties manually. The exception that I'm receiving is:<br /><i>{"This header must be modified using the appropriate property.\r\nParameter name: name"}</i></p> <p><hr> Thanks in advance for your help,</p> <p>CJAM</p>
[ { "answer_id": 176788, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 3, "selected": true, "text": "<p>Some of the headers are actually exposed as properties directly on the HttpWebRequest object. These headers you are not allowed to set directly. e.g HttpWebRequest,ContentType and HttpWebRequest.UserAgent</p>\n\n<p>You will need to update these properties directly and avoid setting them via the Headers property.</p>\n" }, { "answer_id": 187891, "author": "regex", "author_id": 23869, "author_profile": "https://Stackoverflow.com/users/23869", "pm_score": 0, "selected": false, "text": "<p>So I am understanding your response as \"It's not possible to set the collection explicitly.\" I was hoping there was a way to add names and values to the NameValueDictionary, but I guess I'll need to just determine which fields I need to set and use the properties to access specific name/value objects. I guess I could use inheritance and roll my own version of the HttpWebRequest object, but I'm sure the folks at Microsoft had a reason behind encapsulating the collection, so I'll probably just leave things the way they are.</p>\n\n<p>Thanks for your help on this.</p>\n" }, { "answer_id": 11146923, "author": "Jimmy Schementi", "author_id": 5721, "author_profile": "https://Stackoverflow.com/users/5721", "pm_score": 0, "selected": false, "text": "<p>Though this is an old post, I needed to do this recently for an HTTP proxy written in .NET, and here's how I copied headers between two different requests. Feedback welcome, and I hope it helps someone.</p>\n\n<pre><code>static void CopyHeaders (HttpRequest sourceRequest, HttpWebRequest targetRequest) {\n foreach (string key in sourceRequest.Headers) {\n var value = sourceRequest.Headers[key];\n object objectValue = value;\n var propName = key.Replace(\"-\", string.Empty);\n switch (key) {\n case \"Host\":\n case \"Content-Length\":\n // Do not propogate Host and Content-Length.\n continue;\n case \"Connection\":\n // Cannot set the following values ...\n if (value == \"Keep-Alive\" || value == \"Close\") {\n continue;\n }\n break;\n case \"If-Modified-Since\":\n objectValue = DateTime.Parse(value);\n break;\n }\n var prop = targetRequest.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.Instance);\n if (null != prop &amp;&amp; prop.CanWrite) {\n prop.SetValue(targetRequest, objectValue, null);\n } else {\n targetRequest.Headers[key] = Convert.ToString(value);\n }\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/176777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23869/" ]
I'm trying to build a proxy module for .NET, but I'm having trouble copying the Headers from the current request to the new request. I am setting the headers of the new request, because I want the proxy to support SOAP requests. Here is a portion of my code. I can post everything if need, but this is the only part that seems related to the issue I am having: ``` HttpApplication app = (HttpApplication)sender; // sender from context.BeginRequest event HttpRequest crntReq = app.Request; // set a reference to request object for easier access HttpWebRequest proxyReq = (HttpWebRequest)HttpWebRequest.Create(crntReq.Url.AbsoluteUri); // parse headers from current httpcontext.request.headers and add each name->value to the // new request object foreach (string header in crntReq.Headers) { proxyReq.Headers.Add(header, crntReq.Headers[header]); // throws exception :( } ``` When my code hits the foreach loop, it throws an exception for the Headers.Add function. I'm assuming the collection has access restrictions, for security purposes. It appears that some of the header values are accessible with properties for the HttpWebRequest object itself. However in this case I'd rather get rid of the abstraction and set the properties manually. The exception that I'm receiving is: *{"This header must be modified using the appropriate property.\r\nParameter name: name"}* --- Thanks in advance for your help, CJAM
Some of the headers are actually exposed as properties directly on the HttpWebRequest object. These headers you are not allowed to set directly. e.g HttpWebRequest,ContentType and HttpWebRequest.UserAgent You will need to update these properties directly and avoid setting them via the Headers property.
176,827
<p>I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up tag is not preferred).</p> <p>How do I prevent it from posting back to the server?</p>
[ { "answer_id": 176829, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>In C#, you'd do something like this:</p>\n\n<pre><code>MyButton.Attributes.Add(\"onclick\", \"put your javascript here including... return false;\");\n</code></pre>\n" }, { "answer_id": 176841, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": -1, "selected": false, "text": "<p>You might also want to have the client-side function return false.</p>\n\n<pre><code>&lt;asp:LinkButton runat=\"server\" id=\"button\" Text=\"Click Me\" OnClick=\"myfunction();return false;\" AutoPostBack=\"false\" /&gt;\n</code></pre>\n\n<p>You might also consider:</p>\n\n<pre><code>&lt;span runat=\"server\" id=\"clickableSpan\" onclick=\"myfunction();\" class=\"clickable\"&gt;Click Me&lt;/span&gt;\n</code></pre>\n\n<p>I use the clickable class to set things like pointer, color, etc. so that its appearance is similar to an anchor tag, but I don't have to worry about it getting posted back or having to do the href=\"javascript:void(0);\" trick.</p>\n" }, { "answer_id": 176889, "author": "Russell Myers", "author_id": 18194, "author_profile": "https://Stackoverflow.com/users/18194", "pm_score": 7, "selected": true, "text": "<p>ASPX code:</p>\n\n<pre><code>&lt;asp:LinkButton ID=\"someID\" runat=\"server\" Text=\"clicky\"&gt;&lt;/asp:LinkButton&gt;\n</code></pre>\n\n<p>Code behind:</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page \n{\n protected void Page_Load(object sender, EventArgs e)\n {\n someID.Attributes.Add(\"onClick\", \"return false;\");\n }\n}\n</code></pre>\n\n<p>What renders as HTML is:</p>\n\n<pre><code>&lt;a onclick=\"return false;\" id=\"someID\" href=\"javascript:__doPostBack('someID','')\"&gt;clicky&lt;/a&gt;\n</code></pre>\n\n<p>In this case, what happens is the onclick functionality becomes your validator. If it is false, the \"href\" link is not executed; however, if it is true the href will get executed. This eliminates your post back.</p>\n" }, { "answer_id": 176969, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": false, "text": "<p>This may sound like an unhelpful answer ... But why are you using a LinkButton for something purely client-side? Use a standard HTML anchor tag and set its <code>onclick</code> action to your Javascript.</p>\n\n<p>If you need the server to generate the text of that link, then use an <code>asp:Label</code> as the content between the anchor's start and end tags.</p>\n\n<p>If you need to dynamically change the script behavior based on server-side code, consider <code>asp:Literal</code> as a technique.</p>\n\n<p>But unless you're doing server-side activity from the Click event of the LinkButton, there just doesn't seem to be much point to using it here.</p>\n" }, { "answer_id": 176976, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>I think you should investigate using a HyperLink control. It's a server-side control (so you can manipulate visibility and such from code), but it omits a regular ol' anchor tag and doesn't cause a postback.</p>\n" }, { "answer_id": 2244797, "author": "Peter", "author_id": 271108, "author_profile": "https://Stackoverflow.com/users/271108", "pm_score": 0, "selected": false, "text": "<p>No one seems to be doing it like this:</p>\n\n<pre><code>createEventLinkButton.Attributes.Add(\"onClick\", \" if (this.innerHTML == 'Please Wait') { return false; } else { this.innerHTML='Please Wait'; }\");\n</code></pre>\n\n<p>This seems to be the only way that works.</p>\n" }, { "answer_id": 2795172, "author": "MisterMarc", "author_id": 336319, "author_profile": "https://Stackoverflow.com/users/336319", "pm_score": 0, "selected": false, "text": "<p>Why not use an empty ajax update panel and wire the linkbutton's click event to it? This way only the update panel will get updated, thus avoiding a postback and allowing you to run your javascript</p>\n" }, { "answer_id": 3812539, "author": "Rizwan Majeed", "author_id": 460566, "author_profile": "https://Stackoverflow.com/users/460566", "pm_score": 1, "selected": false, "text": "<p> </p>\n\n<p>call java script function on onclick event. </p>\n" }, { "answer_id": 3970312, "author": "Jaider", "author_id": 480700, "author_profile": "https://Stackoverflow.com/users/480700", "pm_score": 2, "selected": false, "text": "<p>Instead of implement the attribute:</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page{\n protected void Page_Load(object sender, EventArgs e)\n {\n someID.Attributes.Add(\"onClick\", \"return false;\");\n }}\n</code></pre>\n\n<p>Use: </p>\n\n<pre><code>OnClientClick=\"return false;\"\n</code></pre>\n\n<p>inside of asp:LinkButton tag</p>\n" }, { "answer_id": 4507022, "author": "ahmet", "author_id": 550916, "author_profile": "https://Stackoverflow.com/users/550916", "pm_score": -1, "selected": false, "text": "<p>use html link instead of asp link and you can use label in between html link for server side \ncontrol</p>\n" }, { "answer_id": 4867416, "author": "Denis", "author_id": 599013, "author_profile": "https://Stackoverflow.com/users/599013", "pm_score": 5, "selected": false, "text": "<p>You can do it too</p>\n\n<pre><code>...LinkButton ID=\"BtnForgotPassword\" runat=\"server\" OnClientClick=\"ChangeText('1');<b>return false\"</b>...</code></pre>\n\n<p>And it stop the link button postback </p>\n" }, { "answer_id": 6061477, "author": "Stefan Hakansson", "author_id": 761405, "author_profile": "https://Stackoverflow.com/users/761405", "pm_score": 1, "selected": false, "text": "<p>Have you tried to use the <code>OnClientClick</code>?</p>\n\n<pre><code>var myLinkButton = new LinkButton { Text = \"Click Here\", OnClientClick = \"JavaScript: return false;\" };\n\n&lt;asp:LinkButton ID=\"someID\" runat=\"server\" Text=\"clicky\" OnClientClick=\"JavaScript: return false;\"&gt;&lt;/asp:LinkButton&gt;\n</code></pre>\n" }, { "answer_id": 10559633, "author": "Randall Sutton", "author_id": 91177, "author_profile": "https://Stackoverflow.com/users/91177", "pm_score": 4, "selected": false, "text": "<p>Just set href=\"#\"</p>\n\n<pre><code>&lt;asp:LinkButton ID=\"myLink\" runat=\"server\" href=\"#\"&gt;Click Me&lt;/asp:LinkButton&gt;\n</code></pre>\n" }, { "answer_id": 12642809, "author": "Adam", "author_id": 1073205, "author_profile": "https://Stackoverflow.com/users/1073205", "pm_score": 3, "selected": false, "text": "<p>Just been through this, the correct way to do it is to use:</p>\n<ol>\n<li><code>OnClientClick</code></li>\n<li><code>return false</code></li>\n</ol>\n<p>as in the following example line of code:</p>\n<pre><code>&lt;asp:LinkButton ID=&quot;lbtnNext&quot; runat=&quot;server&quot; OnClientClick=&quot;findAllOccurences(); return false;&quot; /&gt;\n</code></pre>\n" }, { "answer_id": 19863910, "author": "Andrew Gray", "author_id": 1404206, "author_profile": "https://Stackoverflow.com/users/1404206", "pm_score": 1, "selected": false, "text": "<p>Something else you can do, if you want to preserve your scroll position is this:</p>\n\n<pre><code>&lt;asp:LinkButton runat=\"server\" id=\"someId\" href=\"javascript: void;\" Text=\"Click Me\" /&gt;\n</code></pre>\n" }, { "answer_id": 21441300, "author": "Senthilkumar baliah", "author_id": 3250501, "author_profile": "https://Stackoverflow.com/users/3250501", "pm_score": 0, "selected": false, "text": "<p>In the jquery ready function you can do something like below -</p>\n\n<pre><code>var hrefcode = $('a[id*=linkbutton]').attr('href').split(':');\nvar onclickcode = \"javascript: if`(Condition()) {\" + hrefcode[1] + \";}\";\n$('a[id*=linkbutton]').attr('href', onclickcode);\n</code></pre>\n" }, { "answer_id": 52829886, "author": "Deepu Reghunath", "author_id": 6597375, "author_profile": "https://Stackoverflow.com/users/6597375", "pm_score": 2, "selected": false, "text": "<p>To avoid refresh of page, if the <code>return false</code> is not working with <code>asp:LinkButton</code> use </p>\n\n<pre><code>href=\"javascript: void;\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>href=\"#\"\n</code></pre>\n\n<p>along with <code>OnClientClick=\"return false;\"</code></p>\n\n<pre><code>&lt;asp:LinkButton ID=\"linkPrint\" runat=\"server\" CausesValidation=\"False\" href=\"javascript: void;\"\n OnClientClick=\"javascript:self.print();return false;\"&gt;Print&lt;/asp:LinkButton&gt;\n</code></pre>\n\n<p>Above is code will call the browser print without refresh the page. </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/176827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417/" ]
I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up tag is not preferred). How do I prevent it from posting back to the server?
ASPX code: ``` <asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton> ``` Code behind: ``` public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { someID.Attributes.Add("onClick", "return false;"); } } ``` What renders as HTML is: ``` <a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a> ``` In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.
176,831
<p>I have a modal popup that initially shows some content but expands a div if a checkbox is selected. The modal expands correctly but doesn't recenter unless you scroll up or down. Is there a javascript event I can tack on to my javascript function to recenter the entire modal?</p>
[ { "answer_id": 176837, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>Whatever event you have bound to the scrolling to get it to re-center, bind that event to the checkbox/div expanding event as well (or call it from within the other event). Hard to say more without seeing some code.</p>\n" }, { "answer_id": 198284, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>Be careful that this isn't tied to the resize event of the window. If it is, your recentering could trigger a resize event in IE, which would cause an infinte loop.</p>\n\n<p>If it is tied to the resize event, allow 1 or 2 resize events to occur, but then ignore the rest. (I say 2, because in IE, a \"restore\" event on the window will trigger at least 2 resize events (3 in IE6).</p>\n" }, { "answer_id": 481797, "author": "Luke", "author_id": 14275, "author_profile": "https://Stackoverflow.com/users/14275", "pm_score": 4, "selected": true, "text": "<p>Here is what it is:</p>\n\n<pre><code>$find('ModalPopupExtenderClientID')._layout();\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>$find('detailsPopUpExtenderId')._layout();\n</code></pre>\n\n<p>and in aspx:</p>\n\n<pre><code>&lt;ccl:ModalPopupExtender runat=\"server\" ID=\"MyPopUpExtender\" TargetControlID=\"pop\" PopupControlID=\"PopUp\" BehaviorID=\"detailsPopUpExtenderId\" BackgroundCssClass=\"ModalBackground\" /&gt;\n</code></pre>\n\n<p><code>BehaviorID</code> being the property where to set the clientside id.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/176831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14275/" ]
I have a modal popup that initially shows some content but expands a div if a checkbox is selected. The modal expands correctly but doesn't recenter unless you scroll up or down. Is there a javascript event I can tack on to my javascript function to recenter the entire modal?
Here is what it is: ``` $find('ModalPopupExtenderClientID')._layout(); ``` For example: ``` $find('detailsPopUpExtenderId')._layout(); ``` and in aspx: ``` <ccl:ModalPopupExtender runat="server" ID="MyPopUpExtender" TargetControlID="pop" PopupControlID="PopUp" BehaviorID="detailsPopUpExtenderId" BackgroundCssClass="ModalBackground" /> ``` `BehaviorID` being the property where to set the clientside id.