qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
334,770 | <p>I am trying to make a Kiosk application more accessible by increasing the size of fonts.<br>
No problem on the main Form.<br>
I'm having a problem replacing MessageBoxes (for which I believe there is no way to increase the font size) with small forms with the same message.</p>
<p>This is where I'm running into the problem. The main Form can't <em>see</em> the error form and its Label to set the text. I have tried setting a property for the private Label on the error form, but it's still not working.</p>
<p>I would be very grateful for any assistance. I have been trying to apply what I've learned in reading several threads from various C# sources.</p>
<p>Two strange things I have noticed: </p>
<ol>
<li>In the MainForm, when I type ErrorForm, Intellisense list of suggested code pops up but the variable <code>LblNotCheckedInBecause</code> does not appear on the list.</li>
<li>The compiler error says something about the <code>LBlNotCheckedInBecause</code>.get statement and it seems like to me it should be refering to the set statement since I'm trying to set that value.</li>
</ol>
<p>Here are the parts of the code that I believe are involved:</p>
<p>From <code>ErrorForm.Designer.cs</code>:<br></p>
<pre><code>private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label lblNotCheckedInBecause;
// property I created to try to be able to change the label
public string LblNotCheckedInBecause
{
get { return this.lblNotCheckedInBecause.Text; }
set { this.lblNotCheckedInBecause.Text = value; }
}
</code></pre>
<p>From <code>MainForm.cs</code>:<br></p>
<pre><code>// this is what I'm trying to replace
MessageBox.Show("You were not checked in because of the following reasons:" + sErrors);
// this line is causing a compiler error
ErrorForm.LblNotCheckInBecause = "You were not checked in because of the following reasons:" + sErrors;
</code></pre>
<p>Compiler error:<br></p>
<blockquote>
<p>Error 1 An object reference is required for the nonstatic field,
method, or property
'LogisticsKiosk.ErrorForm.LblNotCheckInBecause.get' C:\Documents and
Settings\My Documents\Visual Studio
2005\Projects\LogisticsKiosk\Forms\MainForm.cs 107 17 LogisticsKiosk</p>
</blockquote>
| [
{
"answer_id": 334785,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 2,
"selected": false,
"text": "ErrorForm errorFrm = new ErrorForm();\nerrorFrm.Show();\n errorFrm.LblNotCheckedInBecause = \"Some Reason\";\n // Doesn't work\nErrorForm.LblNotCheckedInBecause = \"Some Reason\";\n"
},
{
"answer_id": 334792,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "ErrorForm ef = new ErrorForm();\nef.LblNotCheckedInBecause = \"Your error text\";\nef.Show();\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42524/"
] |
334,774 | <p>I'm not sure, will the visual c ++ compiler express edition work for compiling c and if not can someone link me to an easy c compiler to use. Thanks in advance.</p>
| [
{
"answer_id": 334789,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": ".c /Tc /TC /Tp /TP"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33061/"
] |
334,776 | <p>I am writing a set of database-driven applications in PHP. These applications will run on a Linux server as its own user. Other users will likely be on the system at times, but have very controlled access. Other servers they will not have access to at all. I will also expose a limit stored procedure API to developers who need to write Perl scripts that access the database using a DBI and a set of functions I write.</p>
<p>My question is what the best way to secure the config files that have connection strings in them? </p>
<p>Is a different user with [4+]00 permissions on the file sufficient? Should I encrypt them? That seems to just shift the problem elsewhere so that I worry about where to store an encryption key. I realize the Perl developers will need to have a connection string of their own as they will only have execute database permissions. </p>
| [
{
"answer_id": 334929,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "sudo"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28714/"
] |
334,786 | <p>Velocity DisplayTool has a useful method:</p>
<pre><code>$display.list($list)
</code></pre>
<p>That will format a collection or array into the form "A, B and C". </p>
<p>The problem is lets say I have an ArrayList of objects, how do I output a specific object field instead of the whole object?
For example the regular loop would look like this:</p>
<pre><code>#foreach($obj in $list)
${obj.title}
#end
</code></pre>
<p>For now I just made obj.toString() to return obj.title, but what if I will need another field?</p>
<p>Thanks.</p>
<p><strong>UPDATE</strong> Ended up implementing this method myself and committing it to DisplayTools. So it is a part of Tools 2.0 now.</p>
| [
{
"answer_id": 347004,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 2,
"selected": false,
"text": "#set($titles = [])\n#foreach($obj in $list)\n $titles.add($obj.title)\n#end\n$display.list($titles)\n #macro(retrieveProperty $list $property $newList)\n #foreach($obj in $list)\n $newList.add(${obj.${property}})\n #end\n#end\n\n#set($titles = [])\nretrieveProperty($list 'title' $titles)\n$display.list($titles)\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
] |
334,813 | <p>If I have the code:</p>
<pre><code>int f(int a) { return a; }
double f(double g) { return g; }
int main()
{
int which = f(1.0f);
}
</code></pre>
<p>Which overload of <em>f</em> is called, and why?</p>
| [
{
"answer_id": 337232,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "int bar = f(g(h(foo)));\n std::cout << \"int i = \" << i << std::endl;\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42543/"
] |
334,816 | <p>I need to put an LDAP contextSource into my Java EE container's JNDI tree so it can be used by applications inside the container.</p>
<p>I'm using Spring-LDAP to perform queries against ORACLE OVD. For development, I simply set up the contextSource in the Spring xml configuration file. For production, however, I need to be able to use a JNDI lookup to grab the connection/context from the container (as suggested here: <a href="http://forum.springframework.org/showthread.php?t=35122&highlight=jndi" rel="noreferrer">http://forum.springframework.org/showthread.php?t=35122&highlight=jndi</a>). I'm not allowed to have access to the URL/username/pwd for the production OVD instance, so that seems to rule out putting it in a jndi.properties file.</p>
<p>Ideally, I'd like to have a pool of connections (just like JDBC), as my application may have many LDAP queries executing at the same time. Grabbing the object from a JNDI lookup and injecting it into my SimpleLdapTemplate seems pretty straightforward, but I'm at a loss as to how to get the connection/context/pool into the JNDI tree. Would I need to construct it and package it into a RAR? If so, what are some options for letting the operations team specify the URL/username/pwd in a way that they are not accessible to the developers?</p>
<p>The specific container I'm using is OAS/OC4J, though I welcome strategies that have worked on other containers as well.</p>
| [
{
"answer_id": 415270,
"author": "Nicholas",
"author_id": 43786,
"author_profile": "https://Stackoverflow.com/users/43786",
"pm_score": 4,
"selected": true,
"text": "DirContext"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765/"
] |
334,827 | <p>I would like to do the equivalent off <a href="http://www.bigdumbdev.com/2007/08/build-better-skimmer-part-2.html" rel="nofollow noreferrer">this</a> (ruby code) in python for a Django project I am working on. I want to make a <a href="http://designvigilante.com/files/photoSkim/filmStrip.jpg" rel="nofollow noreferrer">filmstrip image</a> of X number of images in a folder. </p>
| [
{
"answer_id": 335323,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 2,
"selected": true,
"text": "#!/usr/bin/env python\n\nimport os, os.path\nfrom contactsheet import make_contact_sheet\n\ndef make_film_strip(fnames,\n (photow,photoh),\n (marl,mart,marr,marb),\n padding):\n return make_contact_sheet(fnames,\n (1, len(fnames)),\n (photow,photoh),\n (marl,mart,marr,marb),\n padding)\n contactsheet.py fstrip = filmstrip.make_film_strip(filmstrip.fnames, (120, 120), (0,0,0,0), 0)\nfstrip.save('/path/to/file.format')\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
334,836 | <p>I have a request that returns a JSON object with a single property which is an array. How can I test if the array is empty?</p>
<p>With jQuery code like:</p>
<pre><code> $.getJSON(
jsonUrl,
function(data) {
if (data.RoleOwners == [ ]) {
$('<tr><td>' + noRoleOwnersText + '</td></tr>').appendTo("#roleOwnersTable tbody");
return;
}
$.each(data.RoleOwners, function(i, roleOwner) {
var tblRow =
"<tr>"
+ "<td>" + roleOwner.FirstName + "</td>"
+ "<td>" + roleOwner.LastName + "</td>"
+ "</tr>"
$(tblRow).appendTo("#roleOwnersTable tbody");
});
</code></pre>
<p>what can I put instead of if(data.RoleOwners == [ ]) to test if the RoleOwners is an empty array?</p>
<p>Thanks,
Matt</p>
| [
{
"answer_id": 334864,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 6,
"selected": true,
"text": "(data.RoleOwners.length === 0)\n"
},
{
"answer_id": 6911328,
"author": "Sadiksha Gautam",
"author_id": 596757,
"author_profile": "https://Stackoverflow.com/users/596757",
"pm_score": 5,
"selected": false,
"text": "jQuery.isEmptyObject(data.RoleOwners)"
},
{
"answer_id": 10593950,
"author": "John Middlemas",
"author_id": 1387389,
"author_profile": "https://Stackoverflow.com/users/1387389",
"pm_score": 0,
"selected": false,
"text": "function isEmptyObject(obj) {\n // This works for arrays too.\n for(var name in obj) {\n return false\n }\n return true\n}\n"
},
{
"answer_id": 18872057,
"author": "Arun Pratap Singh",
"author_id": 2131816,
"author_profile": "https://Stackoverflow.com/users/2131816",
"pm_score": 2,
"selected": false,
"text": " // anyObjectIncludingJSON i tried for JSON object.\n\n if(jQuery.isEmptyObject(anyObjectIncludingJSON))\n {\n return;\n }\n"
},
{
"answer_id": 49444135,
"author": "Sameera Prasad Jayasinghe",
"author_id": 5901608,
"author_profile": "https://Stackoverflow.com/users/5901608",
"pm_score": 1,
"selected": false,
"text": "JSON.parse(data).length > 0\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12459/"
] |
334,842 | <p>I wrote a program using AutoIT to fetch information from a number of websites using Internet Explorer. AutoIT is capable of hiding the window so that it is not visible, however when I navigate to a new website on that hidden window I still get the IE navigation sounds (button click sound, etc.).</p>
<p>How can I disable the sounds from playing using AutoIT?
(Muting the computer, or altering settings in the control panel would not be ideal).</p>
| [
{
"answer_id": 334864,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 6,
"selected": true,
"text": "(data.RoleOwners.length === 0)\n"
},
{
"answer_id": 6911328,
"author": "Sadiksha Gautam",
"author_id": 596757,
"author_profile": "https://Stackoverflow.com/users/596757",
"pm_score": 5,
"selected": false,
"text": "jQuery.isEmptyObject(data.RoleOwners)"
},
{
"answer_id": 10593950,
"author": "John Middlemas",
"author_id": 1387389,
"author_profile": "https://Stackoverflow.com/users/1387389",
"pm_score": 0,
"selected": false,
"text": "function isEmptyObject(obj) {\n // This works for arrays too.\n for(var name in obj) {\n return false\n }\n return true\n}\n"
},
{
"answer_id": 18872057,
"author": "Arun Pratap Singh",
"author_id": 2131816,
"author_profile": "https://Stackoverflow.com/users/2131816",
"pm_score": 2,
"selected": false,
"text": " // anyObjectIncludingJSON i tried for JSON object.\n\n if(jQuery.isEmptyObject(anyObjectIncludingJSON))\n {\n return;\n }\n"
},
{
"answer_id": 49444135,
"author": "Sameera Prasad Jayasinghe",
"author_id": 5901608,
"author_profile": "https://Stackoverflow.com/users/5901608",
"pm_score": 1,
"selected": false,
"text": "JSON.parse(data).length > 0\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
334,846 | <p>I have a mx:Canvas element that contains several mx:Panel elements. I want to be able to draw a line connecting two such mx:Panel's in such a way that the line continues to connect the two mx:Panels when one or both get dragged around. It seems like something that should be trivial to do, but I haven't been able to figure it out.</p>
<p>In effect, this is the problem. </p>
<p><a href="http://img150.imageshack.us/img150/5656/ishot1eu3.jpg" rel="nofollow noreferrer">alt text http://img150.imageshack.us/img150/5656/ishot1eu3.jpg</a></p>
<p>Since the updates only occur when the Panel reaches it's final position, as soon as you start dragging the "B" panel, you are left with a dangling line:</p>
<p><a href="http://img212.imageshack.us/img212/4296/ishot2qi6.jpg" rel="nofollow noreferrer">alt text http://img212.imageshack.us/img212/4296/ishot2qi6.jpg</a></p>
<p>A possible solution, as suggested below, would be to override the updateDisplayList() method of the mx:Canvas component. Unfortunately, that only updates the drawing after the dragging, and not while in motion.
Listening to the "xChanged" and "yChanged" events in the Panel produces the same results as overriding the updateDisplayList().</p>
<p>The final solution, as pointed out below, requires dispatching the move events from the moving Panel to the Canvas on which it is moving. This forces the lines to get redrawn throughout the whole motion.</p>
<p>Thanks for all the help!</p>
| [
{
"answer_id": 335905,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 3,
"selected": true,
"text": "MoveEvent.MOVE MouseEvent.MOUSE_MOVE MOVE MouseEvent.MOUSE_DOWN MouseEvent.MOUSE_UP MOUSE_UP private function attachListeners():void\n{\n this.addEventListener(MouseEvent.MOUSE_DOWN, selfMouseDownHandler, false,0,true);\n this.addEventListener(MoveEvent.MOVE, selfMoveHandler, false,0,true);\n}\n\nprivate function selfMoveHandler(event:MoveEvent):void\n{\n redrawConnectedLinks();\n}\n\nprivate function selfMouseDownHandler(event:MouseEvent):void\n{\n stage.addEventListener(MouseEvent.MOUSE_UP, stageMouseUpHandler, false,0,true);\n stage.addEventListener(MouseEvent.MOUSE_MOVE, stageMouseMoveHandler, false,0,true);\n}\n\nprivate function stageMouseUpHandler(event:MouseEvent):void\n{\n stage.removeEventListener(MouseEvent.MOUSE_UP, stageMouseUpHandler, false);\n stage.removeEventListener(MouseEvent.MOUSE_MOVE, stageMouseMoveHandler, false);\n}\n\nprivate function stageMouseMoveHandler(event:MouseEvent):void\n{\n dispatchEvent(new MoveEvent(MoveEvent.MOVE));\n}\n"
},
{
"answer_id": 2093861,
"author": "Ben",
"author_id": 254034,
"author_profile": "https://Stackoverflow.com/users/254034",
"pm_score": 0,
"selected": false,
"text": " import flash.display.DisplayObject;\nimport flash.display.Sprite;\nimport flash.events.Event;\n\npublic class Association extends Sprite\n{\n private var t1:DisplayObject;\n private var t2:DisplayObject;\n //Connects two objects\n public function Association(t1:DisplayObject, t2:DisplayObject)\n {\n this.t1=t1;\n this.t2=t2;\n this.addEventListener(Event.ENTER_FRAME, redraw)\n super();\n }\n\n public function redraw(event:Event):void\n {\n graphics.clear();\n graphics.lineStyle(2,0x000000);\n graphics.moveTo(t1.x,t1.y);\n graphics.lineTo(t2.x,t2.y);\n }\n\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/280/"
] |
334,850 | <p>My post below asked what the curly quotation marks were and why my app wouldn't work with them, my question now is how can I replace them when my program comes across them, how can I do this in C#? Are they special characters?</p>
<p><a href="https://stackoverflow.com/questions/334119/curly-quotation-marks-vs-square-quotation-marks-what-gives">curly-quotation-marks-vs-square-quotation-marks-what-gives</a></p>
<p>Thanks</p>
| [
{
"answer_id": 334894,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "String.Replace(0x201c, '\"');\nString.Replace(0x201d, '\"');\n"
},
{
"answer_id": 335091,
"author": "Matthew Ruston",
"author_id": 506,
"author_profile": "https://Stackoverflow.com/users/506",
"pm_score": 5,
"selected": false,
"text": "public static class StringExtensions\n{\n public static string StripIncompatableQuotes(this string inputStr)\n {\n if (string.IsNullOrWhiteSpace(inputStr))\n {\n return inputStr;\n }\n \n return inputStr.Replace('\\u2018', '\\'').Replace('\\u2019', '\\'').Replace('\\u201c', '\\\"').Replace('\\u201d', '\\\"');\n }\n}\n"
},
{
"answer_id": 2205075,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "string.Replace(\"\\342\\200\\230\", \"'\")\nstring.Replace(\"\\342\\200\\231\", \"'\")\n string.Replace(\"\\342\\200\\234\", '\"')\nstring.Replace(\"\\342\\200\\235\", '\"')\n"
},
{
"answer_id": 2205826,
"author": "Nick van Esch",
"author_id": 266878,
"author_profile": "https://Stackoverflow.com/users/266878",
"pm_score": 6,
"selected": false,
"text": "if (buffer.IndexOf('\\u2013') > -1) buffer = buffer.Replace('\\u2013', '-');\nif (buffer.IndexOf('\\u2014') > -1) buffer = buffer.Replace('\\u2014', '-');\nif (buffer.IndexOf('\\u2015') > -1) buffer = buffer.Replace('\\u2015', '-');\nif (buffer.IndexOf('\\u2017') > -1) buffer = buffer.Replace('\\u2017', '_');\nif (buffer.IndexOf('\\u2018') > -1) buffer = buffer.Replace('\\u2018', '\\'');\nif (buffer.IndexOf('\\u2019') > -1) buffer = buffer.Replace('\\u2019', '\\'');\nif (buffer.IndexOf('\\u201a') > -1) buffer = buffer.Replace('\\u201a', ',');\nif (buffer.IndexOf('\\u201b') > -1) buffer = buffer.Replace('\\u201b', '\\'');\nif (buffer.IndexOf('\\u201c') > -1) buffer = buffer.Replace('\\u201c', '\\\"');\nif (buffer.IndexOf('\\u201d') > -1) buffer = buffer.Replace('\\u201d', '\\\"');\nif (buffer.IndexOf('\\u201e') > -1) buffer = buffer.Replace('\\u201e', '\\\"');\nif (buffer.IndexOf('\\u2026') > -1) buffer = buffer.Replace(\"\\u2026\", \"...\");\nif (buffer.IndexOf('\\u2032') > -1) buffer = buffer.Replace('\\u2032', '\\'');\nif (buffer.IndexOf('\\u2033') > -1) buffer = buffer.Replace('\\u2033', '\\\"');\n"
},
{
"answer_id": 16109185,
"author": "cjbarth",
"author_id": 271351,
"author_profile": "https://Stackoverflow.com/users/271351",
"pm_score": 2,
"selected": false,
"text": "Public Module StringExtensions\n\n <Extension()>\n Public Function StripIncompatableQuotes(BadString As String) As String\n If Not String.IsNullOrEmpty(BadString) Then\n Return BadString.Replace(ChrW(&H2018), \"'\").Replace(ChrW(&H2019), \"'\").Replace(ChrW(&H201C), \"\"\"\").Replace(ChrW(&H201D), \"\"\"\")\n Else\n Return BadString\n End If\n End Function\nEnd Module\n"
},
{
"answer_id": 30262676,
"author": "Barbara from Boston",
"author_id": 945371,
"author_profile": "https://Stackoverflow.com/users/945371",
"pm_score": 4,
"selected": false,
"text": "if (buffer.IndexOf('\\u2013') > -1) buffer = buffer.Replace('\\u2013', '-'); // en dash\nif (buffer.IndexOf('\\u2014') > -1) buffer = buffer.Replace('\\u2014', '-'); // em dash\nif (buffer.IndexOf('\\u2015') > -1) buffer = buffer.Replace('\\u2015', '-'); // horizontal bar\nif (buffer.IndexOf('\\u2017') > -1) buffer = buffer.Replace('\\u2017', '_'); // double low line\nif (buffer.IndexOf('\\u2018') > -1) buffer = buffer.Replace('\\u2018', '\\''); // left single quotation mark\nif (buffer.IndexOf('\\u2019') > -1) buffer = buffer.Replace('\\u2019', '\\''); // right single quotation mark\nif (buffer.IndexOf('\\u201a') > -1) buffer = buffer.Replace('\\u201a', ','); // single low-9 quotation mark\nif (buffer.IndexOf('\\u201b') > -1) buffer = buffer.Replace('\\u201b', '\\''); // single high-reversed-9 quotation mark\nif (buffer.IndexOf('\\u201c') > -1) buffer = buffer.Replace('\\u201c', '\\\"'); // left double quotation mark\nif (buffer.IndexOf('\\u201d') > -1) buffer = buffer.Replace('\\u201d', '\\\"'); // right double quotation mark\nif (buffer.IndexOf('\\u201e') > -1) buffer = buffer.Replace('\\u201e', '\\\"'); // double low-9 quotation mark\nif (buffer.IndexOf('\\u2026') > -1) buffer = buffer.Replace(\"\\u2026\", \"...\"); // horizontal ellipsis\nif (buffer.IndexOf('\\u2032') > -1) buffer = buffer.Replace('\\u2032', '\\''); // prime\nif (buffer.IndexOf('\\u2033') > -1) buffer = buffer.Replace('\\u2033', '\\\"'); // double prime\n"
},
{
"answer_id": 43512481,
"author": "Asif Ghanchi",
"author_id": 4999045,
"author_profile": "https://Stackoverflow.com/users/4999045",
"pm_score": 0,
"selected": false,
"text": "string replacedstring = (\"your string with smart quotes\").Replace('\\u201d', '\\'');\n"
},
{
"answer_id": 51214178,
"author": "Taylor Wallgren",
"author_id": 4270933,
"author_profile": "https://Stackoverflow.com/users/4270933",
"pm_score": 2,
"selected": false,
"text": "input = \"shmB6BhLe0gdGU8OxYykZ21vuxLjBo5I1ZTJjxWfyRTTlqQlgz0yUtPu8iNCCcsx78EPsObiPkCpRT8nqRtvM3Bku1f9nStmigaw\";\ninput.Replace('\\u2013', '-'); // en dash\ninput.Replace('\\u2014', '-'); // em dash\ninput.Replace('\\u2015', '-'); // horizontal bar\ninput.Replace('\\u2017', '_'); // double low line\ninput.Replace('\\u2018', '\\''); // left single quotation mark\ninput.Replace('\\u2019', '\\''); // right single quotation mark\ninput.Replace('\\u201a', ','); // single low-9 quotation mark\ninput.Replace('\\u201b', '\\''); // single high-reversed-9 quotation mark\ninput.Replace('\\u201c', '\\\"'); // left double quotation mark\ninput.Replace('\\u201d', '\\\"'); // right double quotation mark\ninput.Replace('\\u201e', '\\\"'); // double low-9 quotation mark\ninput.Replace(\"\\u2026\", \"...\"); // horizontal ellipsis\ninput.Replace('\\u2032', '\\''); // prime\ninput.Replace('\\u2033', '\\\"'); // double prime\n input = \"shmB6BhLe0gdGU8OxYykZ21vuxLjBo5I1ZTJjxWfyRTTlqQlgz0yUtPu8iNCCcsx78EPsObiPkCpRT8nqRtvM3Bku1f9nStmigaw\";\nvar inputArray = input.ToCharArray();\nfor (int i = 0; i < inputArray.Length; i++)\n{\n switch (inputArray[i])\n {\n case '\\u2013':\n inputArray[i] = '-';\n break;\n // en dash\n case '\\u2014':\n inputArray[i] = '-';\n break;\n // em dash\n case '\\u2015':\n inputArray[i] = '-';\n break;\n // horizontal bar\n case '\\u2017':\n inputArray[i] = '_';\n break;\n // double low line\n case '\\u2018':\n inputArray[i] = '\\'';\n break;\n // left single quotation mark\n case '\\u2019':\n inputArray[i] = '\\'';\n break;\n // right single quotation mark\n case '\\u201a':\n inputArray[i] = ',';\n break;\n // single low-9 quotation mark\n case '\\u201b':\n inputArray[i] = '\\'';\n break;\n // single high-reversed-9 quotation mark\n case '\\u201c':\n inputArray[i] = '\\\"';\n break;\n // left double quotation mark\n case '\\u201d':\n inputArray[i] = '\\\"';\n break;\n // right double quotation mark\n case '\\u201e':\n inputArray[i] = '\\\"';\n break;\n // double low-9 quotation mark\n case '\\u2026':\n inputArray[i] = '.';\n break;\n // horizontal ellipsis\n case '\\u2032':\n inputArray[i] = '\\'';\n break;\n // prime\n case '\\u2033':\n inputArray[i] = '\\\"';\n break;\n // double prime\n }\n}\ninput = new string(inputArray);\n"
},
{
"answer_id": 58867897,
"author": "Ed Cayce",
"author_id": 5977531,
"author_profile": "https://Stackoverflow.com/users/5977531",
"pm_score": 1,
"selected": false,
"text": " public static string ReplaceWordChars(this string text)\n {\n var s = text;\n // smart single quotes and apostrophe, single low-9 quotation mark, single high-reversed-9 quotation mark, prime\n s = Regex.Replace(s, \"[\\u2018\\u2019\\u201A\\u201B\\u2032]\", \"'\");\n // smart double quotes, double prime\n s = Regex.Replace(s, \"[\\u201C\\u201D\\u201E\\u2033]\", \"\\\"\");\n // ellipsis\n s = Regex.Replace(s, \"\\u2026\", \"...\");\n // em dashes\n s = Regex.Replace(s, \"[\\u2013\\u2014]\", \"-\");\n // horizontal bar\n s = Regex.Replace(s, \"\\u2015\", \"-\");\n // double low line\n s = Regex.Replace(s, \"\\u2017\", \"-\");\n // circumflex\n s = Regex.Replace(s, \"\\u02C6\", \"^\");\n // open angle bracket\n s = Regex.Replace(s, \"\\u2039\", \"<\");\n // close angle bracket\n s = Regex.Replace(s, \"\\u203A\", \">\");\n // weird tilde and nonblocking space\n s = Regex.Replace(s, \"[\\u02DC\\u00A0]\", \" \");\n // half\n s = Regex.Replace(s, \"[\\u00BD]\", \"1/2\");\n // quarter\n s = Regex.Replace(s, \"[\\u00BC]\", \"1/4\");\n // dot\n s = Regex.Replace(s, \"[\\u2022]\", \"*\");\n // degrees \n s = Regex.Replace(s, \"[\\u00B0]\", \" degrees\");\n\n return s;\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
334,851 | <p>I'd like to be able to print the definition code of a lambda function.</p>
<p>Example if I define this function through the lambda syntax:</p>
<pre><code>>>>myfunction = lambda x: x==2
>>>print_code(myfunction)
</code></pre>
<p>I'd like to get this output:</p>
<pre><code>x==2
</code></pre>
| [
{
"answer_id": 335081,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 3,
"selected": false,
"text": ">>> lambda_func = lambda x: x==2\n>>> def def_func(x): return x == 2\n...\n >>> import dis\n>>> dis.dis(lambda_func)\n 1 0 LOAD_FAST 0 (x)\n 3 LOAD_CONST 1 (2)\n 6 COMPARE_OP 2 (==)\n 9 RETURN_VALUE\n>>> dis.dis(def_func)\n 1 0 LOAD_FAST 0 (x)\n 3 LOAD_CONST 1 (2)\n 6 COMPARE_OP 2 (==)\n 9 RETURN_VALUE\n"
},
{
"answer_id": 335089,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "class MyLambda( object ):\n def __init__( self, body ):\n self.body= body\n def __call__( self, arg ):\n x = arg\n return eval( self.body )\n def __str__( self ):\n return self.body\n\nf= MyLambda( \"x == 2\" )\nprint f(1)\nprint f(2)\nprint f\n"
},
{
"answer_id": 335159,
"author": "pcn",
"author_id": 42590,
"author_profile": "https://Stackoverflow.com/users/42590",
"pm_score": 7,
"selected": true,
"text": "myfunction = lambda x: x==2\n >>>from lamtest import myfunc\n>>>import inspect\n>>>inspect.getsource(myfunc)\n 'myfunc = lambda x: x==2\\n'\n"
},
{
"answer_id": 3081433,
"author": "asmeurer",
"author_id": 161801,
"author_profile": "https://Stackoverflow.com/users/161801",
"pm_score": 5,
"selected": false,
"text": "Lambda() >>> from sympy import *\n>>> x = Symbol('x')\n>>> l = Lambda(x, x**2)\n>>> l\nLambda(_x, _x**2)\n>>> l(3)\n9\n >>> pprint(l)\n ⎛ 2⎞\nΛ⎝x, x ⎠\n >>> l1 = Lambda(x, Eq(x, 2))\n>>> l1\nLambda(_x, _x == 2)\n>>> l1(2)\nTrue\n >>> y = Symbol('y')\n>>> l2 = Lambda((x, y), x*y + x)\n>>> l2(1)\nLambda(_y, 1 + _y)\n>>> l2(1, 2)\n3\n >>> l3 = Lambda(x, sin(x*pi/3))\n>>> pprint(l3(1))\n ⎽⎽⎽\n╲╱ 3 \n─────\n 2 \n"
},
{
"answer_id": 21339223,
"author": "Mike McKerns",
"author_id": 2379433,
"author_profile": "https://Stackoverflow.com/users/2379433",
"pm_score": 4,
"selected": false,
"text": "inspect dill.source.getsource dill >>> from dill.source import getsource\n>>> \n>>> def add(x,y):\n... return x+y\n... \n>>> squared = lambda x:x**2\n>>> \n>>> print getsource(add)\ndef add(x,y):\n return x+y\n\n>>> print getsource(squared)\nsquared = lambda x:x**2\n\n>>> \n>>> class Foo(object):\n... def bar(self, x):\n... return x*x+x\n... \n>>> f = Foo()\n>>> \n>>> print getsource(f.bar)\ndef bar(self, x):\n return x*x+x\n\n>>> \n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28165/"
] |
334,852 | <p>I'm trying to write a simple query involving two tables. The "person" table has a unique <code>person_id</code> and a <code>name</code>, and the "friends" table has a <code>person_id</code> and a <code>friend_id</code> which is a FK to a <code>person_id</code> in the person table.</p>
<pre><code>person:
<PK> int person_id
varchar[45] name
friends:
<PK> int person_id
<PK> int friend_id
</code></pre>
<p>I want to select the name of all of person 1's friends.</p>
<p>I can do this easily using an <code>IN</code> statement:</p>
<pre><code>SELECT p.name FROM person p WHERE p.person_id IN (SELECT f.friend_id FROM friends f WHERE f.person_id = 1);
</code></pre>
<p>However, I am not proficient at writing <code>JOIN</code> statements. Can somebody help me write the equivalent join?</p>
<p>Clearly this is a contrived example, but I have tried with my real data and am conceptually missing something. Thanks.</p>
| [
{
"answer_id": 334869,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "SELECT p.name, f.friend_id\nFROM person AS p\nINNER JOIN friends AS f ON p.person_id = f.person_id\nWHERE p.person_id = 1\n p.person_id = f.person_id friend_id SELECT p.name AS person_name, friend.name AS friend_name\nFROM person AS p -- Our person\nINNER JOIN friends AS f ON p.person_id = f.person_id -- the join table\nINNER JOIN person AS friend on f.friend_id = friend.id -- Join back on person again\nWHERE p.person_id = 1\n SELECT p.name, f.friend_id\nFROM person AS p\nINNER JOIN friends AS f ON p.person_id = f.friend_id\nWHERE f.person_id = 1\n"
},
{
"answer_id": 334870,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 1,
"selected": false,
"text": "SELECT p.name FROM person p \nINNER JOIN friends f ON f.friend_id = p.person_id\nWHERE f.person_id = 1;\n"
},
{
"answer_id": 334885,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 3,
"selected": false,
"text": "select \n p.name,\n p2.name as friend_name,\nfrom\n person p \n inner join friends f on p.person_id = f.person_id\n inner join person p2 on f.friend_id = p2.person_id -- friends\nwhere\n p.person_id = <your criteria>\n"
},
{
"answer_id": 334911,
"author": "jkinter",
"author_id": 10405,
"author_profile": "https://Stackoverflow.com/users/10405",
"pm_score": 0,
"selected": false,
"text": "SELECT p.name FROM person p \nINNER JOIN friends f ON p.person_id = f.friend_id\nWHERE f.person_id = 1\n [person.name] [person.person_id] [friends.friend_id] [friends.person_id] friends.person_id=[1]"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
334,856 | <p>What are the benefits of passing by pointer over passing by reference in C++?</p>
<p>Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?</p>
<p>Example:</p>
<pre><code>func(SPRITE *x);
</code></pre>
<p>with a call of</p>
<pre><code>func(&mySprite);
</code></pre>
<p>vs.</p>
<pre><code>func(SPRITE &x);
</code></pre>
<p>with a call of</p>
<pre><code>func(mySprite);
</code></pre>
| [
{
"answer_id": 334866,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": false,
"text": "nothing string s = &str1 + &str2; void f(const T& t); ... f(T(a, b, c));"
},
{
"answer_id": 334873,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 9,
"selected": true,
"text": "// Is mySprite passed by value or by reference? You can't tell \n// without looking at the definition of func()\nfunc(mySprite);\n\n// func2 passes \"by pointer\" - no need to look up function definition\nfunc2(&mySprite);\n"
},
{
"answer_id": 334944,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": false,
"text": "120. Reference arguments should always be `const`\n121. Never use references as outputs, use pointers\n const const"
},
{
"answer_id": 335897,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": 3,
"selected": false,
"text": "bool test( int & a)\n{\n return (&a) == (int *) NULL;\n}\n\nint\nmain()\n{\n int * i = (int *)NULL;\n cout << ( test(*i) ) << endl;\n};\n"
},
{
"answer_id": 61784374,
"author": "themeeman",
"author_id": 8278966,
"author_profile": "https://Stackoverflow.com/users/8278966",
"pm_score": 3,
"selected": false,
"text": "foo(new int) nullptr & int a = 5; foo(a); std::optional<T&> T* T* template <typename T>\nstruct optional_ref {\n optional_ref() : ptr(nullptr) {}\n optional_ref(T* t) : ptr(t) {}\n optional_ref(std::nullptr_t) : ptr(nullptr) {}\n\n T& get() const {\n return *ptr;\n }\n\n explicit operator bool() const {\n return bool(ptr);\n }\n\nprivate:\n T* ptr;\n};\n void foo(optional_ref<int> x) {\n if (x) {\n auto y = x.get();\n // use y here\n }\n}\n\nint x = 5;\nfoo(&x); // explicit indirection here\nfoo(nullptr); // nullability\n nullptr optional_ref get_or map constexpr"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
] |
334,860 | <p>I have my main GUI thread, and a second thread running inside it's own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method on my 2nd thread from my GUI thread, but if I just call thread.Method(); it seems to be running on my main GUI thread and causes my GUI to become unresponsive. What is the best way to call methods on different threads?</p>
<p><strong>Update:</strong>
What I'm really looking to do here is communicate between 2 threads, not communicate with a GUI. The GUI just happens to be one of the threads that will need to communicate with my 2nd thread.</p>
<p><strong>Update #2:</strong>
Ok, I must really be missing something. I created an event and a delegate and had my worker thread subscribe to the event. But when I call Invoke(MyEvent); from my GUI thread the work that the worker thread does ends up being on the GUI thread and hangs the GUI thread until it's done processing. Is what I'm trying to do even possible, without polling on a static object?</p>
| [
{
"answer_id": 334920,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 5,
"selected": true,
"text": "System.ComponentModel.BackgroundWorker"
},
{
"answer_id": 335357,
"author": "Lee",
"author_id": 42609,
"author_profile": "https://Stackoverflow.com/users/42609",
"pm_score": 2,
"selected": false,
"text": "\n\n//delegate with same prototype as the method to call asynchrously\ndelegate void ProcessItemDelegate(object item);\n\n//method to call asynchronously\nprivate void ProcessItem(object item) { ... }\n\n//method in the GUI thread\nprivate void DoWork(object itemToProcess)\n{\n //create delegate to call asynchronously...\n ProcessItemDelegate d = new ProcessItemDelegate(this.ProcessItem);\n IAsyncResult result = d.BeginInvoke(itemToProcess,\n new AsyncCallback(this.CallBackMethod),\n d); \n}\n\n//method called when the async operation has completed\nprivate void CallbackMethod(IAsyncResult ar)\n{\n ProcessItemDelegate d = (ProcessItemDelegate)ar.AsyncState;\n //EndInvoke must be called on any delegate called asynchronously!\n d.EndInvoke(ar);\n}\n \n//shared state\nprivate Queue workQueue;\nprivate EventWaitHandle eventHandle;\n\n//method running in gui thread\nprivate void DoWork(Item itemToProcess)\n{\n //use a private lock object instead of lock...\n lock(this.workQueue)\n {\n this.workQueue.Add(itemToProcess);\n this.eventHandle.Set();\n }\n}\n\n//method that runs on the background thread\nprivate void QueueMonitor()\n{\n while(keepRunning)\n {\n //if the event handle is not signalled the processing thread will sleep here until it is signalled or the timeout expires\n if(this.eventHandle.WaitOne(optionalTimeout))\n {\n lock(this.workQueue)\n {\n while(this.workQueue.Count > 0)\n {\n Item itemToProcess = this.workQueue.Dequeue();\n //do something with item...\n }\n }\n //reset wait handle - note that AutoResetEvent resets automatically\n this.eventHandle.Reset();\n }\n }\n}\n"
},
{
"answer_id": 335771,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Threading;\nusing System.Windows.Forms;\n\npublic partial class frmWorker : Form {\n public frmWorker() {\n // Start the worker thread\n Thread t = new Thread(new ParameterizedThreadStart(WorkerThread));\n t.IsBackground = true;\n t.Start(this);\n }\n public void Stop() {\n // Synchronous thread stop\n this.Invoke(new MethodInvoker(stopWorker), null);\n }\n private void stopWorker() {\n this.Close();\n }\n private static void WorkerThread(object frm) {\n // Start the message loop\n frmWorker f = frm as frmWorker;\n f.CreateHandle();\n Application.Run(f);\n }\n protected override void SetVisibleCore(bool value) {\n // Shouldn't become visible\n value = false;\n base.SetVisibleCore(value);\n }\n}\n public partial class Form1 : Form {\n private frmWorker mWorker;\n public Form1() {\n InitializeComponent();\n mWorker = new frmWorker();\n }\n\n private void button1_Click(object sender, EventArgs e) {\n Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);\n mWorker.BeginInvoke(new MethodInvoker(RunThisOnThread));\n }\n private void RunThisOnThread() {\n Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);\n }\n\n private void button2_Click(object sender, EventArgs e) {\n mWorker.Stop();\n }\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343/"
] |
334,879 | <p>I am running a program and want to see what its return code is (since it returns different codes based on different errors).</p>
<p>I know in Bash I can do this by running</p>
<blockquote>
<p>echo $?</p>
</blockquote>
<p>What do I do when using cmd.exe on Windows?</p>
| [
{
"answer_id": 334890,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": 11,
"selected": true,
"text": "errorlevel echo Exit Code is %errorlevel%\n if if errorlevel\n if /? @echo off\nmy_nifty_exe.exe\nif errorlevel 1 (\n echo Failure Reason Given is %errorlevel%\n exit /b %errorlevel%\n)\n errorlevel %errorlevel% set errorlevel= errorlevel %errorlevel%"
},
{
"answer_id": 334893,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 7,
"selected": false,
"text": "echo %ERRORLEVEL%\n"
},
{
"answer_id": 3119934,
"author": "dmihailescu",
"author_id": 376495,
"author_profile": "https://Stackoverflow.com/users/376495",
"pm_score": 4,
"selected": false,
"text": "#include \"stdafx.h\"\n#include \"windows.h\"\n#include \"stdio.h\"\n#include \"tchar.h\"\n#include \"stdio.h\"\n#include \"shellapi.h\"\n\nint _tmain( int argc, TCHAR *argv[] )\n{\n\n CString cmdline(GetCommandLineW());\n cmdline.TrimLeft('\\\"');\n CString self(argv[0]);\n self.Trim('\\\"');\n CString args = cmdline.Mid(self.GetLength()+1);\n args.TrimLeft(_T(\"\\\" \"));\n printf(\"Arguments passed: '%ws'\\n\",args);\n STARTUPINFO si;\n PROCESS_INFORMATION pi;\n\n ZeroMemory( &si, sizeof(si) );\n si.cb = sizeof(si);\n ZeroMemory( &pi, sizeof(pi) );\n\n if( argc < 2 )\n {\n printf(\"Usage: %s arg1,arg2....\\n\", argv[0]);\n return -1;\n }\n\n CString strCmd(args);\n // Start the child process. \n if( !CreateProcess( NULL, // No module name (use command line)\n (LPTSTR)(strCmd.GetString()), // Command line\n NULL, // Process handle not inheritable\n NULL, // Thread handle not inheritable\n FALSE, // Set handle inheritance to FALSE\n 0, // No creation flags\n NULL, // Use parent's environment block\n NULL, // Use parent's starting directory \n &si, // Pointer to STARTUPINFO structure\n &pi ) // Pointer to PROCESS_INFORMATION structure\n ) \n {\n printf( \"CreateProcess failed (%d)\\n\", GetLastError() );\n return GetLastError();\n }\n else\n printf( \"Waiting for \\\"%ws\\\" to exit.....\\n\", strCmd );\n\n // Wait until child process exits.\n WaitForSingleObject( pi.hProcess, INFINITE );\n int result = -1;\n if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))\n { \n printf(\"GetExitCodeProcess() failed (%d)\\n\", GetLastError() );\n }\n else\n printf(\"The exit code for '%ws' is %d\\n\",(LPTSTR)(strCmd.GetString()), result );\n // Close process and thread handles. \n CloseHandle( pi.hProcess );\n CloseHandle( pi.hThread );\n return result;\n}\n"
},
{
"answer_id": 11476681,
"author": "Gary",
"author_id": 236365,
"author_profile": "https://Stackoverflow.com/users/236365",
"pm_score": 8,
"selected": false,
"text": "ErrorLevel ErrorLevel START /WAIT ErrorLevel start /wait something.exe\necho %errorlevel%\n"
},
{
"answer_id": 25019949,
"author": "Curtis Yallop",
"author_id": 854342,
"author_profile": "https://Stackoverflow.com/users/854342",
"pm_score": 5,
"selected": false,
"text": "@echo off\nmy_nify_exe.exe\nif %ERRORLEVEL% EQU 0 (\n echo Success\n) else (\n echo Failure Reason Given is %errorlevel%\n exit /b %errorlevel%\n)\n if errorlevel 0 errorlevel if /? if %ERRORLEVEL% NEQ 0 (\n echo Failed with exit-code: %errorlevel%\n exit /b %errorlevel%\n)\n"
},
{
"answer_id": 28785952,
"author": "jonretting",
"author_id": 2083509,
"author_profile": "https://Stackoverflow.com/users/2083509",
"pm_score": 0,
"selected": false,
"text": "usage: logit.sh [-h] [-p] [-i=n] [-s] <description>\nexample: logit.sh -p error -i 501 -s myscript.sh \"failed to run the mount command\"\n LGT_TEMP_FILE=\"$(mktemp --suffix .cmd)\"\ncat<<EOF>$LGT_TEMP_FILE\n @echo off\n set LGT_EXITCODE=\"$LGT_ID\"\n exit /b %LGT_ID%\nEOF\nunix2dos \"$LGT_TEMP_FILE\"\n __create_event () {\n local cmd=\"eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D \"\n if [[ \"$1\" == *';'* ]]; then\n local IFS=';'\n for i in \"$1\"; do\n $cmd \"$i\" &>/dev/null\n done\n else\n $cmd \"$LGT_DESC\" &>/dev/null\n fi\n}\n cmd /c \"$(cygpath -wa \"$LGT_TEMP_FILE\")\"\n__create_event\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3218/"
] |
334,882 | <pre><code>void some_func(int param = get_default_param_value());
</code></pre>
| [
{
"answer_id": 335289,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 7,
"selected": true,
"text": "// Code 1: Valid and invalid default parameters\nint global = 0;\nint free_function( int x );\n\nclass Test\n{\npublic:\n static int static_member_function();\n int member_function();\n\n // Valid default parameters\n void valid1( int x = free_function( 5 ) );\n void valid2( int x = free_function( global ) );\n void valid3( int x = free_function( static_int ) );\n void valid4( int x = static_member_function() );\n\n // Invalid default parameters\n void invalid1( int x = free_function( member_attribute ) ); \n void invalid2( int x = member_function() );\nprivate:\n int member_attribute;\n static int static_int;\n};\n\nint Test::static_int = 0;\n\n// Code 2: Variable scope\nint x = 5;\nvoid f( int a );\nvoid g( int a = f( x ) ); // x is bound to the previously defined x\nvoid h()\n{\n int x = 10; // shadows ::x\n g(); // g( 5 ) is called: even if local x values 10, global x is 5.\n}\n"
},
{
"answer_id": 59823120,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "David Rodríguez - dribeas void some_func(int param);\nvoid some_func() {\n some_func(get_default_param_value());\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12151/"
] |
334,896 | <p>I am using a makefile system with the pvcs compiler (using Microsoft Visual C++, 2008 compiler) and I am getting several link errors of the form:</p>
<blockquote>
<p><code>error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main</code></p>
</blockquote>
<p>This is happening DESPITE using the <code>extern "C"</code> declaration, viz.:</p>
<pre><code>extern "C" int CLRDUMP_API RegisterFilter( LPCWSTR pDumpFileName, unsigned long DumpType );
</code></pre>
<p>Also, in the makeexe.mak, the library is being linked in as:</p>
<p>$(COMPILEBASE)\lib\clrdump.lib \</p>
<p>To be honest, I am not an expert at makefiles, and I am changing over a system from Microsoft Visual C++ 6.0 to 2008. This change-over may have something to do with the link errors, as the system used to work before.</p>
<p>Any help would really be appreciated.</p>
<p>Thanks in Advance,</p>
<p>Sincerely,
Joseph</p>
<p><strong>-- Edit 1 --</strong></p>
<p>Does anyone know how to turn verbose on in the makefile system of pvcs?</p>
<p>Note that the above function is already a compiler-decorated version, having</p>
<pre><code>__imp__RegisterFilter@8
</code></pre>
<p>whereas the C++ function is just</p>
<pre><code>RegisterFilter
</code></pre>
<p>Thanks for the help, but if anyone can post a more complete solution, that would also be very appreciated.</p>
<p>Sincerely, Joseph</p>
<p><strong>-- Edit 2 --</strong></p>
<p>Some kind person posted this, but when I signed in it disappeared:</p>
<p>The imp prefix indicates that this function is imported from a DLL. Check the definition of <code>CLRDUMP_API</code> - is it <code>__declspec(dllimport)</code>? See this article for more information.</p>
<p>There was a working link, but I've lost that, however I suppose one can always search the topic.</p>
<p>Thanks, whoever you were!</p>
<p><strong>-- Edit 3 --</strong></p>
<p>Thanks ChrisN (I'm not yet allowed to vote). Despite using the refresh button, your answer disappeared, but then re-appeared after I posted a cut-n-paste.</p>
<p>This is my definition of that:</p>
<pre><code>define CLRDUMP_API __declspec(dllimport) __stdcall
</code></pre>
<p>I assume that the __stdcall is OK?</p>
<p><strong>-- Edit 4 --</strong></p>
<p>While I appreciate the efforts of those who answered, particularly ChrisN, at least on my particular system, the link error remains. So if anyone has any further insight, I'd appreciate it. Thanks again.</p>
| [
{
"answer_id": 335478,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 4,
"selected": false,
"text": "__imp_ extern \"C\" dumpbin /exports clrdump.lib\n RegisterFilter ?RegisterFilter@@YGHPBGK@Z (int __stdcall RegisterFilter(unsigned short const *,unsigned long)) #include <windows.h>\n#include \"ClrDump.h\"\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n RegisterFilter(L\"\", 0);\n return 0;\n}\n LNK2019: unresolved external symbol \"__declspec(dllimport) int __stdcall RegisterFilter(wchar_t const *,unsigned long)\" (__imp_?RegisterFilter@@YGHPB_WK@Z) dumpbin RegisterFilter unsigned short const * wchar_t const * wchar_t unsigned short /Zc:wchar_t-"
},
{
"answer_id": 2552230,
"author": "antonymken",
"author_id": 305927,
"author_profile": "https://Stackoverflow.com/users/305927",
"pm_score": 3,
"selected": true,
"text": "LNK2019: unresolved external symbol __imp__somefunction\n \"C:\\Program Files\\Microsoft Visual Studio 8\\VC\\PlatformSDK\\Lib\" ComCtl32.Lib ComDlg32.Lib"
},
{
"answer_id": 6962826,
"author": "Tanguy",
"author_id": 293527,
"author_profile": "https://Stackoverflow.com/users/293527",
"pm_score": 1,
"selected": false,
"text": "// project.def\nLIBRARY project\nEXPORTS\n ulDataInDll CONSTANT\n Keyword Emits in the import library Exports\nCONSTANT _imp_ulDataInDll _ulDataInDll\n _ulDataInDll \n\nDATA _imp_ulDataInDll _ulDataInDll\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42552/"
] |
334,907 | <p>I want to match any line that does not end with 'CA' or 'CA[any number]'. How can I do that using rlike in MySQL? (Note it doesn't support ?! etc).</p>
<p>Here's the regex for a positive match, I just need a way to negate it: <code>'^.*[C][A][0-9]?$'</code></p>
<p>(Due to an embarrassing architecture limitation, I don't want to use <code>not rlike ...</code>)</p>
| [
{
"answer_id": 336339,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": true,
"text": "rlike '[^A0-9]$|[^A][0-9]$|[^C]A[0-9]$|[^C]A$|^A[0-9]$|^[A0-9]$|^$'\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
334,916 | <p>We have an application where our clients are connecting to a SQL Server 2005 database - via a SQL Native Client ODBC data source. We are having some difficulties with the ODBC connection getting severed during program execution. After questioning a tech support person, he said that he had seen this type of error before, but they fixed the issue by configuring the clients to connect using Named Pipes (primarily), rather than TCP/IP.</p>
<p>So I did some research and found where to configure client access on the server - via the SQL Server Configuration Manager. However, there does not appear to be a way to configure the SQL Native Client ODBC data source on the client machine itself. The older SQL Server ODBC driver did allow you to configure it to use Named Pipes, or TCP/IP, but the SQL Native Client does not. </p>
<p>Does the SQL Native Client data source automatically decided which method to use to connect to the database? Is there a way to configure it?…and is there a way to find out which method a particular client machine is using to connect?</p>
<p>Any help would be appreciated.</p>
<p>--Thanks
Mike C.</p>
| [
{
"answer_id": 7018768,
"author": "Matt Neerincx",
"author_id": 888883,
"author_profile": "https://Stackoverflow.com/users/888883",
"pm_score": 3,
"selected": false,
"text": "Server=tcp:myserver Server=np:myserver tcp: np: Network=dbmssocn Network=dbnmpntw"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14947/"
] |
334,919 | <p>I am attempting to insert a mass of records into SQL Server 2005 from Vb.Net. Although the insertion is working fine, I am doing my best to try to make it as fast as possible. Currently, it takes ~ 11 mins for 100,000 records. What would be the suggested approach to inserting a large number of records into SQL Server from an Application?</p>
<p>My current apporach is basically opening the connection, iterating through my list of information and firing off individual sql insert statments, and then closing the connection. Anyone have a better suggestion on how to do this?</p>
<p>Current Function:</p>
<pre><code>Public Sub BatchInsert(ByVal ParamCollections As List(Of SqlParameter()))
Dim Conn As SqlConnection = New SqlConnection(DBHelper.DatabaseConnection)
Using scope As TransactionScope = New TransactionScope()
Using Conn
Dim cmd As SqlCommand = New SqlCommand("sproc_name", Conn)
Conn.Open()
cmd.CommandType = CommandType.StoredProcedure
For i = 0 To ParamCollections.Count - 1
cmd.Parameters.Clear()
cmd.Parameters.AddRange(ParamCollections(i))
cmd.ExecuteNonQuery()
Next
Conn.Close()
scope.Complete()
End Using
End Using
End Sub
</code></pre>
| [
{
"answer_id": 334926,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": true,
"text": "IEnumerable<T> yield return INSERT INTO"
},
{
"answer_id": 335112,
"author": "Nathan",
"author_id": 5800,
"author_profile": "https://Stackoverflow.com/users/5800",
"pm_score": 4,
"selected": false,
"text": " Public Sub PerformBulkCopy(ByVal dt As DataTable)\n\n Using Conn As SqlConnection = New SqlConnection(DBHelper.DatabaseConnection)\n Conn.Open()\n\n Using s As SqlBulkCopy = New SqlBulkCopy(Conn)\n\n s.DestinationTableName = \"TableName\"\n s.WriteToServer(dt)\n s.Close()\n\n End Using\n\n Conn.Close()\n End Using\nEnd Sub\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5800/"
] |
334,928 | <p>I have been up and down this site and found a lot of info on the Screen class and how to count the number of monitors and such but how do I determine which montitor a form is currently in?</p>
| [
{
"answer_id": 335055,
"author": "jvberg",
"author_id": 34514,
"author_profile": "https://Stackoverflow.com/users/34514",
"pm_score": 1,
"selected": false,
"text": " foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)\n {\n if (screen.Bounds.Contains(this.Location))\n {\n this.textBox1.Text = screen.DeviceName;\n }\n }\n"
},
{
"answer_id": 335065,
"author": "Matt Hanson",
"author_id": 5473,
"author_profile": "https://Stackoverflow.com/users/5473",
"pm_score": 2,
"selected": false,
"text": "private Screen FindCurrentMonitor(Form form) \n{ \n return Windows.Forms.Screen.FromRectangle(new Rectangle( _\n form.Location, form.Size)); \n} \n return Windows.Forms.Screen.FromPoint(Form.Location);\n"
},
{
"answer_id": 336050,
"author": "Dan R",
"author_id": 24222,
"author_profile": "https://Stackoverflow.com/users/24222",
"pm_score": 6,
"selected": true,
"text": "Screen.FromControl(this)\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34514/"
] |
334,933 | <p>I am inside the IDE and I can run all the unit tests in a file but is there any way to run all test in a project or solution at once?</p>
| [
{
"answer_id": 1056115,
"author": "Alconja",
"author_id": 68727,
"author_profile": "https://Stackoverflow.com/users/68727",
"pm_score": 4,
"selected": false,
"text": "Tools --> Options --> Keyboard"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
334,939 | <p>I'm working on a legacy application that has a C++ extended stored procedure. This xsproc uses ODBC to connect to the database, which means it requires a DSN to be configured.</p>
<p>I'm updating the installer (created using Visual Studio 2008 setup project), and want to have a custom action that can create the ODBC DSN entry, but am struggling to find useful information on Google.</p>
<p>Can anyone help?</p>
| [
{
"answer_id": 334958,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 2,
"selected": false,
"text": " private const string ODBC_LOC_IN_REGISTRY = \"SOFTWARE\\\\ODBC\\\\\";\n private const string ODBC_INI_LOC_IN_REGISTRY =\n ODBC_LOC_IN_REGISTRY + \"ODBC.INI\\\\\";\n\n private const string DSN_LOC_IN_REGISTRY =\n ODBC_INI_LOC_IN_REGISTRY + \"ODBC Data Sources\\\\\";\n\n private const string ODBCINST_INI_LOC_IN_REGISTRY =\n ODBC_LOC_IN_REGISTRY + \"ODBCINST.INI\\\\\";\n\n private const string ODBC_DRIVERS_LOC_IN_REGISTRY =\n ODBCINST_INI_LOC_IN_REGISTRY + \"ODBC Drivers\\\\\";\n"
},
{
"answer_id": 336815,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 6,
"selected": true,
"text": "///<summary>\n/// Class to assist with creation and removal of ODBC DSN entries\n///</summary>\npublic static class ODBCManager\n{\n private const string ODBC_INI_REG_PATH = \"SOFTWARE\\\\ODBC\\\\ODBC.INI\\\\\";\n private const string ODBCINST_INI_REG_PATH = \"SOFTWARE\\\\ODBC\\\\ODBCINST.INI\\\\\";\n\n /// <summary>\n /// Creates a new DSN entry with the specified values. If the DSN exists, the values are updated.\n /// </summary>\n /// <param name=\"dsnName\">Name of the DSN for use by client applications</param>\n /// <param name=\"description\">Description of the DSN that appears in the ODBC control panel applet</param>\n /// <param name=\"server\">Network name or IP address of database server</param>\n /// <param name=\"driverName\">Name of the driver to use</param>\n /// <param name=\"trustedConnection\">True to use NT authentication, false to require applications to supply username/password in the connection string</param>\n /// <param name=\"database\">Name of the datbase to connect to</param>\n public static void CreateDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database)\n {\n // Lookup driver path from driver name\n var driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName);\n if (driverKey == null) throw new Exception(string.Format(\"ODBC Registry key for driver '{0}' does not exist\", driverName));\n string driverPath = driverKey.GetValue(\"Driver\").ToString();\n\n // Add value to odbc data sources\n var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + \"ODBC Data Sources\");\n if (datasourcesKey == null) throw new Exception(\"ODBC Registry key for datasources does not exist\");\n datasourcesKey.SetValue(dsnName, driverName);\n\n // Create new key in odbc.ini with dsn name and add values\n var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName);\n if (dsnKey == null) throw new Exception(\"ODBC Registry key for DSN was not created\");\n dsnKey.SetValue(\"Database\", database);\n dsnKey.SetValue(\"Description\", description);\n dsnKey.SetValue(\"Driver\", driverPath);\n dsnKey.SetValue(\"LastUser\", Environment.UserName);\n dsnKey.SetValue(\"Server\", server);\n dsnKey.SetValue(\"Database\", database);\n dsnKey.SetValue(\"Trusted_Connection\", trustedConnection ? \"Yes\" : \"No\");\n }\n\n /// <summary>\n /// Removes a DSN entry\n /// </summary>\n /// <param name=\"dsnName\">Name of the DSN to remove.</param>\n public static void RemoveDSN(string dsnName)\n {\n // Remove DSN key\n Registry.LocalMachine.DeleteSubKeyTree(ODBC_INI_REG_PATH + dsnName);\n\n // Remove DSN name from values list in ODBC Data Sources key\n var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + \"ODBC Data Sources\");\n if (datasourcesKey == null) throw new Exception(\"ODBC Registry key for datasources does not exist\");\n datasourcesKey.DeleteValue(dsnName);\n }\n\n ///<summary>\n /// Checks the registry to see if a DSN exists with the specified name\n ///</summary>\n ///<param name=\"dsnName\"></param>\n ///<returns></returns>\n public static bool DSNExists(string dsnName)\n {\n var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + \"ODBC Drivers\");\n if (driversKey == null) throw new Exception(\"ODBC Registry key for drivers does not exist\");\n\n return driversKey.GetValue(dsnName) != null;\n }\n\n ///<summary>\n /// Returns an array of driver names installed on the system\n ///</summary>\n ///<returns></returns>\n public static string[] GetInstalledDrivers()\n {\n var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + \"ODBC Drivers\");\n if (driversKey == null) throw new Exception(\"ODBC Registry key for drivers does not exist\");\n\n var driverNames = driversKey.GetValueNames();\n\n var ret = new List<string>();\n\n foreach (var driverName in driverNames)\n {\n if (driverName != \"(Default)\")\n {\n ret.Add(driverName);\n }\n }\n\n return ret.ToArray();\n }\n}\n"
},
{
"answer_id": 1428739,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "driverName OpenSubKey CreateSubKey // Lookup driver path from driver name\nvar driverKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n ODBCINST_INI_REG_PATH + driverName);\n requestedPrivileges <requestedExecutionLevel level=\"requireAdministrator\" uiAccess=\"false\"/>\n OpenSubKey"
},
{
"answer_id": 2066677,
"author": "dlchambers",
"author_id": 210758,
"author_profile": "https://Stackoverflow.com/users/210758",
"pm_score": 2,
"selected": false,
"text": "public static bool DSNExists(string dsnName) \n{ \n var sourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + \"ODBC Data Sources\"); \n if (sourcesKey == null) throw new Exception(\"ODBC Registry key for sources does not exist\"); \n\n return sourcesKey.GetValue(dsnName) != null; \n} \n"
},
{
"answer_id": 2806390,
"author": "Edgar",
"author_id": 337676,
"author_profile": "https://Stackoverflow.com/users/337676",
"pm_score": 0,
"selected": false,
"text": " var dsnKeyEng = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName + \"\\\\Engines\");\n var dsnKeyExl = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName + \"\\\\Engines\\\\Excel\");\n\n dsnKeyExl.SetValue(\"FirstRowHasNames\", 01);\n dsnKeyExl.SetValue(\"MaxScanRows\", 8);\n dsnKeyExl.SetValue(\"Threads\",3);\n dsnKeyExl.SetValue(\"UserCommitSync\", \"Yes\")\n"
},
{
"answer_id": 3142336,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 3,
"selected": false,
"text": "[DllImport(\"ODBCCP32.DLL\", CharSet = CharSet.Unicode, SetLastError = true)]\nstatic extern bool SQLConfigDataSourceW(UInt32 hwndParent, RequestFlags fRequest, string lpszDriver, string lpszAttributes);\n\nenum RequestFlags : int\n{\n ODBC_ADD_DSN = 1,\n ODBC_CONFIG_DSN = 2,\n ODBC_REMOVE_DSN = 3,\n ODBC_ADD_SYS_DSN = 4,\n ODBC_CONFIG_SYS_DSN = 5,\n ODBC_REMOVE_SYS_DSN = 6,\n ODBC_REMOVE_DEFAULT_DSN = 7\n}\n\nbool UpdateDsnServer(string name, string server)\n{\n var flag = RequestFlags.ODBC_CONFIG_SYS_DSN;\n string dsnNameLine = \"DSN=\" + name;\n string serverLine = \"Server=\" + server;\n\n string configString = new[] { dsnNameLine, serverLine }.Aggregate(\"\", (str, line) => str + line + \"\\0\");\n\n return SQLConfigDataSourceW(0, flag, \"SQL Server\", configString);\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26414/"
] |
334,948 | <p>I am using slideDown animation to show some divs in a newly added table row:</p>
<pre><code>$("div", newRow).slideDown(10000, UpdateHours(response.d.Hours));
</code></pre>
<p>however the UpdateHours() function is called long before the divs are finished animating. This is causing me a problem because the Updated Hours then get covered by the sliding divs.</p>
<p>I made the slide very slow to illustrate the issue better.</p>
| [
{
"answer_id": 334982,
"author": "Tracy Hurley",
"author_id": 31240,
"author_profile": "https://Stackoverflow.com/users/31240",
"pm_score": 6,
"selected": true,
"text": "$(\"div\", newRow).slideDown(10000, function () { UpdateHours(response.d.Hours) });\n"
},
{
"answer_id": 334984,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "$(\"div\", newRow).slideDown(10000, function() { UpdateHours(response.d.Hours); }); UpdateHours"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18349/"
] |
334,951 | <p>I'm writing a unit test for a method that packs boolean values into a byte. The various bit locations are determined by the value of an enum, which only has 5 values right now, but it's conceivable (though extremely unlikely) that this number could go to 9.</p>
<p>I'd like a simple test along the lines of:</p>
<p>private byte m_myNum;
enum MyEnum {...}</p>
<p>assert(sizeof(m_myNum) <= MyEnum.values().length);</p>
<p>I'm under the impression that there's not a sizeof function in Java. What's the most elegant workaround?</p>
<p>---EDIT</p>
<p>I don't think I was clear. I'm not concerned about normal runtime. My issue is that I can write this code now with a byte that stores all the information, but as the Enum grows in an unrelated part of code, I could reach a point where my bitmasking code breaks. Rather than having this in a deployed application, I'd like to have a unit test that fails when the number of states in the enum exceeds the number of bits in the storage variable, so when a programmer adds that ninth enum, they can adjust the type of the variable to something with more than eight bits.</p>
| [
{
"answer_id": 335000,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 0,
"selected": false,
"text": "Integer.highestOneBit(m_myNum & 0xFF) byte int int long"
},
{
"answer_id": 335093,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 3,
"selected": true,
"text": "public void testEnumSizeLessThanOneByte() throws Exception \n{ \n assertTrue(\"MyEnum must have 8 or less values.\", \n MyEnum.values().length <= 8);\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42562/"
] |
334,952 | <p>I have a class that inherits QTreeWidget. How can I find the currently selected row?
Usually I connect signals to slots this way:</p>
<pre><code>connect(myButton, SIGNAL(triggered(bool)), this, SLOT(myClick()));
</code></pre>
<p>However, I can't find anything similar for <code>QTreeWidget->QTreeWidgetItem</code>.
The only way I found is to redefine the mousePressEvent of the QTreeWidget class like this:</p>
<pre><code>void MyQTreeWidget::mousePressEvent(QMouseEvent *e){
QTreeView::mousePressEvent(e);
const QModelIndex index = indexAt(e->pos());
if (!index.isValid())
{
const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
if (!(modifiers & Qt::ShiftModifier) && !(modifiers & Qt::ControlModifier))
clearSelection();
}
}
</code></pre>
<p>I didn't try it yet. Is the only solution or is there any easier way?</p>
| [
{
"answer_id": 335187,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 4,
"selected": false,
"text": "QList<QTreeWidgetItem *> QTreeWidget::selectedItems() const\n"
},
{
"answer_id": 335219,
"author": "JuanDeLosMuertos",
"author_id": 39339,
"author_profile": "https://Stackoverflow.com/users/39339",
"pm_score": 0,
"selected": false,
"text": "connect(this,SIGNAL(itemClicked(QTreeWidgetItem*, int)), SLOT(mySlot()));\n"
},
{
"answer_id": 29473726,
"author": "Sofiane",
"author_id": 4755024,
"author_profile": "https://Stackoverflow.com/users/4755024",
"pm_score": 2,
"selected": false,
"text": "QString word = treeWidget->currentItem()->text(treeWidget->currentColumn());\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39339/"
] |
334,992 | <p>I'm trying to make some types in Django that map to standard Django types. The <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow noreferrer">custom model field documentation</a> goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.</p>
<p>For example, if I were storing playing cards, I want something like:</p>
<pre><code>class Card(object):
""" A playing card. """
def as_number(self):
""" returns a number from 1 (Ace of Clubs) and 52 (King of Spades)."""
return self.number + self.suit_rank() * 13
def __unicode(self): ...
def is_highest(self, other_cards, trump=None):...
def __init__(self, number, suit): ...
...
</code></pre>
<p>I want my models to have something like:</p>
<pre><code>class my_game(models.Model):
ante = models.IntegerField()
bonus_card = Card() # Really stored as an models.IntegerField()
....
</code></pre>
<p>I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming <strong>init</strong>(). Does anyone have sample code or better documentation?</p>
| [
{
"answer_id": 335215,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "class Card(models.Model):\n \"\"\" A playing card. \"\"\"\n self.suit = models.PositiveIntegerField()\n self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES )\n def as_number(self):\n \"\"\" returns a number from 1 (Ace of Clubs) and 52 (King of Spades).\"\"\"\n return self.number + self.suit * 13\n def __unicode__(self):\n return ...\n def is_highest(self, other_cards, trump=None):...\n"
},
{
"answer_id": 335312,
"author": "jpwatts",
"author_id": 21279,
"author_profile": "https://Stackoverflow.com/users/21279",
"pm_score": 3,
"selected": true,
"text": "from django.db import models\n\nclass Card(object):\n \"\"\"The ``Card`` class you described.\"\"\"\n ...\n\nclass CardField(models.PositiveIntegerField):\n __metaclass__ = models.SubfieldBase\n\n def get_db_prep_value(self, value):\n \"\"\"Return the ``int`` equivalent of ``value``.\"\"\"\n if value is None: return None\n try:\n int_value = value.as_number()\n except AttributeError:\n int_value = int(value)\n return int_value\n\n def to_python(self, value):\n \"\"\"Return the ``Card`` equivalent of ``value``.\"\"\"\n if value is None or isinstance(value, Card):\n return value\n return Card(int(value))\n get_db_prep_value value int None to_python value Card None SubfieldBase to_python"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/334992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320510/"
] |
335,008 | <p>At my current job, we're looking to implement our own odbc driver to allow many different applications to be able to connect to our own app as a datasource. Right now we are trying to weigh the options of developing our own driver to the implementation spec, which is massive, <em>or</em> using an SDK that allows for programmers to 'fill in' the data specific parts and allow higher levels of abstraction.</p>
<p>Has anyone else implemented a custom odbc driver? What pitfalls did you run into? What benefits did you see from doing it yourself? How many manhours would you approximate it took? Did you use an SDK, and if so, what benefits/downsides did you see from that approach?</p>
<p>Any comments and answers would be greatly appreciated. Thanks!</p>
<p><strong>EDIT:</strong> We are trying to maintain portability with our code, which is written in C.</p>
| [
{
"answer_id": 13685364,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 5,
"selected": false,
"text": "psql -h localhost -p 9876 import SocketServer\nimport struct\n\ndef char_to_hex(char):\n retval = hex(ord(char))\n if len(retval) == 4:\n return retval[-2:]\n else:\n assert len(retval) == 3\n return \"0\" + retval[-1]\n\ndef str_to_hex(inputstr):\n return \" \".join(char_to_hex(char) for char in inputstr)\n\nclass Handler(SocketServer.BaseRequestHandler):\n def handle(self):\n print \"handle()\"\n self.read_SSLRequest()\n self.send_to_socket(\"N\")\n\n self.read_StartupMessage()\n self.send_AuthenticationClearText()\n self.read_PasswordMessage()\n self.send_AuthenticationOK()\n self.send_ReadyForQuery()\n self.read_Query()\n self.send_queryresult()\n\n def send_queryresult(self):\n fieldnames = ['abc', 'def']\n HEADERFORMAT = \"!cih\"\n fields = ''.join(self.fieldname_msg(name) for name in fieldnames)\n rdheader = struct.pack(HEADERFORMAT, 'T', struct.calcsize(HEADERFORMAT) - 1 + len(fields), len(fieldnames))\n self.send_to_socket(rdheader + fields)\n\n rows = [[1, 2], [3, 4]]\n DRHEADER = \"!cih\"\n for row in rows:\n dr_data = struct.pack(\"!ii\", -1, -1)\n dr_header = struct.pack(DRHEADER, 'D', struct.calcsize(DRHEADER) - 1 + len(dr_data), 2)\n self.send_to_socket(dr_header + dr_data)\n\n self.send_CommandComplete()\n self.send_ReadyForQuery()\n\n def send_CommandComplete(self):\n HFMT = \"!ci\"\n msg = \"SELECT 2\\x00\"\n self.send_to_socket(struct.pack(HFMT, \"C\", struct.calcsize(HFMT) - 1 + len(msg)) + msg)\n\n def fieldname_msg(self, name):\n tableid = 0\n columnid = 0\n datatypeid = 23\n datatypesize = 4\n typemodifier = -1\n format_code = 0 # 0=text 1=binary\n return name + \"\\x00\" + struct.pack(\"!ihihih\", tableid, columnid, datatypeid, datatypesize, typemodifier, format_code)\n\n def read_socket(self):\n print \"Trying recv...\"\n data = self.request.recv(1024)\n print \"Received {} bytes: {}\".format(len(data), repr(data))\n print \"Hex: {}\".format(str_to_hex(data))\n return data\n\n def send_to_socket(self, data):\n print \"Sending {} bytes: {}\".format(len(data), repr(data))\n print \"Hex: {}\".format(str_to_hex(data))\n return self.request.sendall(data)\n\n def read_Query(self):\n data = self.read_socket()\n msgident, msglen = struct.unpack(\"!ci\", data[0:5])\n assert msgident == \"Q\"\n print data[5:]\n\n\n def send_ReadyForQuery(self):\n self.send_to_socket(struct.pack(\"!cic\", 'Z', 5, 'I'))\n\n def read_PasswordMessage(self):\n data = self.read_socket()\n b, msglen = struct.unpack(\"!ci\", data[0:5])\n assert b == \"p\"\n print \"Password: {}\".format(data[5:])\n\n\n def read_SSLRequest(self):\n data = self.read_socket()\n msglen, sslcode = struct.unpack(\"!ii\", data)\n assert msglen == 8\n assert sslcode == 80877103\n\n def read_StartupMessage(self):\n data = self.read_socket()\n msglen, protoversion = struct.unpack(\"!ii\", data[0:8])\n print \"msglen: {}, protoversion: {}\".format(msglen, protoversion)\n assert msglen == len(data)\n parameters_string = data[8:]\n print parameters_string.split('\\x00')\n\n def send_AuthenticationOK(self):\n self.send_to_socket(struct.pack(\"!cii\", 'R', 8, 0))\n\n def send_AuthenticationClearText(self):\n self.send_to_socket(struct.pack(\"!cii\", 'R', 8, 3))\n\nif __name__ == \"__main__\":\n server = SocketServer.TCPServer((\"localhost\", 9876), Handler)\n try:\n server.serve_forever()\n except:\n server.shutdown()\n [~]\n$ psql -h localhost -p 9876\nPassword:\npsql (9.1.6, server 0.0.0)\nWARNING: psql version 9.1, server version 0.0.\n Some psql features might not work.\nType \"help\" for help.\n\ncodeape=> Select;\n abc | def\n-----+-----\n |\n |\n(2 rows)\n\ncodeape=>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8945/"
] |
335,019 | <p>I'd like to be able to detect Vista IE7 Protected Mode within a page using javascript, preferably. My thinking is to perform an action that would violate protected mode, thus exposing it. The goal is to give appropriate site help messaging to IE7 Vista users. </p>
| [
{
"answer_id": 338066,
"author": "jdev",
"author_id": 40867,
"author_profile": "https://Stackoverflow.com/users/40867",
"pm_score": 0,
"selected": false,
"text": "var axo = new ActiveXObject(\"ieframe.dll\");\n IEIsProtectedModeProcess()"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40867/"
] |
335,030 | <p>I've seen some variable declare in VB.net in several way like:</p>
<pre><code>print("dim _Foo as string");
</code></pre>
<p>and
print("dim m_Foo as string");
and
print("dim foo as string");</p>
<p>I will like to know what's the standard for VB.net coding.</p>
| [
{
"answer_id": 335053,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 3,
"selected": true,
"text": "Private Dim m_Foo As String\n Private Dim _Foo As String\n Dim Foo As String\n Dim l_Foo As String\n Public Class Bar\n Private m_firstName As String\n\n Public Sub New(ByVal firstName As String)\n m_firstName = firstName\n End Sub\n\n Public Function SayGreeting() As String\n Dim l_Greeting As String\n l_Greeting = String.Format(\"{0}, {1}!\", \"Hello\", m_firstName)\n Return l_Greeting\n End Function\nEnd Class\n"
},
{
"answer_id": 525802,
"author": "Simon Hartcher",
"author_id": 459159,
"author_profile": "https://Stackoverflow.com/users/459159",
"pm_score": 0,
"selected": false,
"text": "_member //Class member - Camel Case\nintLocalVariable //note use of Hungarian notation - Camel Case\npMethodParameter //Camel Case\nMyProperty //Pascal Case\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
335,061 | <p>I wanted to add dynamic charts in the webpage. It goes like this...</p>
<p>I get the start and end date from user and draw separate charts for each date bewteen the start and end date.</p>
<p>I get the data from sql database and bind it with the chart like this:</p>
<pre><code> SqlConnection UsageLogConn = new
SqlConnection(ConfigurationManager.ConnectionStrings["UsageConn"].ConnectionString);
UsageLogConn.Open();//open connection
string sql = "SELECT v.interval,dateadd(mi,(v.interval-1)*2,'" + startdate + " 00:00:00') as 'intervaltime',COUNT(Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2) AS Total FROM usage_internet_intervals v left outer join (select * from Usage_Internet where " + name + " LIKE ('%" + value + "%') and DateTime BETWEEN '" + startdate + " 00:00:00' AND '" + enddate + " 23:59:59') d on v.interval = Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 GROUP BY v.interval,Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 ORDER BY Interval";
SqlCommand cmd = new SqlCommand(sql, UsageLogConn);
SqlDataAdapter mySQLadapter = new SqlDataAdapter(cmd);
Chart1.DataSource = cmd;
// set series members names for the X and Y values
Chart1.Series["Series 1"].XValueMember = "intervaltime";
Chart1.Series["Series 1"].YValueMembers = "Total";
UsageLogConn.Close();
// data bind to the selected data source
Chart1.DataBind();
cmd.Dispose();
</code></pre>
<p>The above code adds only one chart for one date and I have added 'chart1' to design view and its not created dynamic. But I wanted to add more charts dynamic at runtime to the webpage.</p>
<p>Can anyone help me with this?</p>
<p>I am using VS 2008, ASP.NET 3.5
and the charting lib is: using System.Web.UI.DataVisualization.Charting;</p>
| [
{
"answer_id": 335362,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 2,
"selected": false,
"text": " protected void Page_Load(object sender, EventArgs e)\n {\n Bench[] benchList;\n FoodIntake[] foodIntakeList;\n Panel panelChartHolder;\n\n panelChartHolder = new Panel();\n Controls.Add(panelChartHolder);\n\n benchList = Bench.GetAll();\n AddNewCharts(benchList, panelChartHolder, \n GetBenchXValue, GetBenchYValue);\n\n foodIntakeList = FoodIntake.GetAll();\n AddNewCharts(foodIntakeList, panelChartHolder, \n GetFoodIntakeXValue, GetFoodIntakeYValue);\n }\n private void AddNewCharts<T>(T[] listToAdd, Panel panelToAddTo, \n Func<T, DateTime> xMethod, Func<T, Int32> yMethod)\n {\n\n ChartArea mainArea;\n Chart mainChart;\n Series mainSeries;\n\n mainChart = new Chart();\n mainSeries = new Series(\"MainSeries\");\n\n for (Int32 loopCounter = 0; loopCounter < listToAdd.Length; loopCounter++)\n {\n mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]), \n yMethod(listToAdd[loopCounter]));\n }\n\n mainChart.Series.Add(mainSeries);\n mainArea = new ChartArea(\"MainArea\");\n mainChart.ChartAreas.Add(mainArea);\n\n panelToAddTo.Controls.Add(mainChart);\n }\n private DateTime GetBenchXValue(Bench currentBench)\n {\n return currentBench.DateLifted;\n }\n\n private Int32 GetBenchYValue(Bench currentBench)\n {\n return currentBench.BenchAmount;\n }\n\n private DateTime GetFoodIntakeXValue(FoodIntake currentIntake)\n {\n return currentIntake.DateEaten;\n }\n\n private Int32 GetFoodIntakeYValue(FoodIntake currentIntake)\n {\n return currentIntake.Calories;\n }\n using System;\n using System.Web.UI.DataVisualization.Charting;\n using System.Web.UI.WebControls;\n"
},
{
"answer_id": 7119598,
"author": "shridhar",
"author_id": 902151,
"author_profile": "https://Stackoverflow.com/users/902151",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n {\n MySqlConnection UsageLogConn = new MySqlConnection(\"Server=localhost;UID=root;Password=;database=productactivation\");\n UsageLogConn.Open();//open connection\n\n string sql = \"select * from sales\";\n DataSet ds = new DataSet();\n MySqlCommand cmd = new MySqlCommand(sql, UsageLogConn);\n MySqlDataAdapter mySQLadapter = new MySqlDataAdapter(cmd);\n mySQLadapter.Fill(ds);\n Chart1.DataSource = ds;\n\n // set series members names for the X and Y values \n Chart1.Series[\"Series1\"].XValueMember = \"title_id\";\n Chart1.Series[\"Series1\"].YValueMembers = \"qty\";\n Chart1.Series[\"Series2\"].XValueMember = \"title_id\";\n Chart1.Series[\"Series2\"].YValueMembers = \"qty\";\n UsageLogConn.Close();\n // data bind to the selected data source\n Chart1.DataBind();\n\n\n cmd.Dispose();\n\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,073 | <p>I have an Array Collection with any number of Objects. I know each Object has a given property. Is there an easy (aka "built-in") way to get an Array of all the values of that property in the Collection?</p>
<p>For instance, let's say I have the following Collection:</p>
<pre><code>var myArrayCollection:ArrayCollection = new ArrayCollection(
{id: 1, name: "a"}
{id: 2, name: "b"}
{id: 3, name: "c"}
{id: 4, name: "d"}
....
);
</code></pre>
<p>I want to get the Array "1,2,3,4....". Right now, I have to loop through the Collection and push each value to an Array. Since my Collection can get large, I want to avoid looping.</p>
<pre><code>var myArray:Array /* of int */ = [];
for each (var item:Object in myArrayCollection)
{
myArray.push(item.id);
}
</code></pre>
<p>Does anyone have any suggestions?</p>
<p>Thanks. </p>
| [
{
"answer_id": 335362,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 2,
"selected": false,
"text": " protected void Page_Load(object sender, EventArgs e)\n {\n Bench[] benchList;\n FoodIntake[] foodIntakeList;\n Panel panelChartHolder;\n\n panelChartHolder = new Panel();\n Controls.Add(panelChartHolder);\n\n benchList = Bench.GetAll();\n AddNewCharts(benchList, panelChartHolder, \n GetBenchXValue, GetBenchYValue);\n\n foodIntakeList = FoodIntake.GetAll();\n AddNewCharts(foodIntakeList, panelChartHolder, \n GetFoodIntakeXValue, GetFoodIntakeYValue);\n }\n private void AddNewCharts<T>(T[] listToAdd, Panel panelToAddTo, \n Func<T, DateTime> xMethod, Func<T, Int32> yMethod)\n {\n\n ChartArea mainArea;\n Chart mainChart;\n Series mainSeries;\n\n mainChart = new Chart();\n mainSeries = new Series(\"MainSeries\");\n\n for (Int32 loopCounter = 0; loopCounter < listToAdd.Length; loopCounter++)\n {\n mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]), \n yMethod(listToAdd[loopCounter]));\n }\n\n mainChart.Series.Add(mainSeries);\n mainArea = new ChartArea(\"MainArea\");\n mainChart.ChartAreas.Add(mainArea);\n\n panelToAddTo.Controls.Add(mainChart);\n }\n private DateTime GetBenchXValue(Bench currentBench)\n {\n return currentBench.DateLifted;\n }\n\n private Int32 GetBenchYValue(Bench currentBench)\n {\n return currentBench.BenchAmount;\n }\n\n private DateTime GetFoodIntakeXValue(FoodIntake currentIntake)\n {\n return currentIntake.DateEaten;\n }\n\n private Int32 GetFoodIntakeYValue(FoodIntake currentIntake)\n {\n return currentIntake.Calories;\n }\n using System;\n using System.Web.UI.DataVisualization.Charting;\n using System.Web.UI.WebControls;\n"
},
{
"answer_id": 7119598,
"author": "shridhar",
"author_id": 902151,
"author_profile": "https://Stackoverflow.com/users/902151",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n {\n MySqlConnection UsageLogConn = new MySqlConnection(\"Server=localhost;UID=root;Password=;database=productactivation\");\n UsageLogConn.Open();//open connection\n\n string sql = \"select * from sales\";\n DataSet ds = new DataSet();\n MySqlCommand cmd = new MySqlCommand(sql, UsageLogConn);\n MySqlDataAdapter mySQLadapter = new MySqlDataAdapter(cmd);\n mySQLadapter.Fill(ds);\n Chart1.DataSource = ds;\n\n // set series members names for the X and Y values \n Chart1.Series[\"Series1\"].XValueMember = \"title_id\";\n Chart1.Series[\"Series1\"].YValueMembers = \"qty\";\n Chart1.Series[\"Series2\"].XValueMember = \"title_id\";\n Chart1.Series[\"Series2\"].YValueMembers = \"qty\";\n UsageLogConn.Close();\n // data bind to the selected data source\n Chart1.DataBind();\n\n\n cmd.Dispose();\n\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31298/"
] |
335,078 | <p>If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.</p>
| [
{
"answer_id": 335105,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": true,
"text": "import os\nfor path, dirs, files in os.walk( root ):\n for f in files:\n print path, f, os.path.getsize( os.path.join( path, f ) )\n"
},
{
"answer_id": 9439237,
"author": "Perkins",
"author_id": 845159,
"author_profile": "https://Stackoverflow.com/users/845159",
"pm_score": 0,
"selected": false,
"text": "pexpect.run subprocess du <path to folder>"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] |
335,095 | <p>Is it possible to access JSTL's forEach variable via code from within the loop?</p>
<pre><code><c:forEach items="${elements}" var="element">
<% element.someMethod(); %>
</c:forEach>
</code></pre>
| [
{
"answer_id": 335140,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": -1,
"selected": false,
"text": "var c:forEach <c:forEach items=\"${elements}\" var=\"element\">\n ${((Element)element).someMethod()}\n</c:forEach>\n"
},
{
"answer_id": 335145,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "<c:forEach items=\"${elements}\" var=\"element\">\n <% ((Element) pageContext.getAttribute(\"elements\")).someMethod(); %>\n</c:forEach>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
335,096 | <p>As a newbie I'm trying to implement a sorting function in C++, using the list-class.
However, running the code I get the error that the list iterator is not incrementable... However it seems very unlikely as it should be incrementable!</p>
<p>code: </p>
<pre><code>void shuffle (list<int> &list1)
{
list<int> smaller;
list<int> larger;
if (list1.size() > 1)
{
list<int>::iterator it;
//int it;
int x = list1.front();
for (it = list1.begin(); it != list1.end(); it++)
{
if(*it <= x)
{
smaller.push_front(*it);
list1.pop_front();
}
else
{
larger.push_back(*it);
list1.pop_front();
}
shuffle (smaller);
shuffle (larger);
}
}
else
{
print(smaller);
print(larger);
//cout << "No sorting needed! The list still looks like: ";
//print(list1);
}
print(smaller);
print(larger);
}
</code></pre>
<p>I implemented this function just in de CPP file, under the main.</p>
<p>Does anyone has any suggestions?</p>
| [
{
"answer_id": 335136,
"author": "Dusty Campbell",
"author_id": 2174,
"author_profile": "https://Stackoverflow.com/users/2174",
"pm_score": 0,
"selected": false,
"text": "#include <list>\nusing namespace std;\n"
},
{
"answer_id": 335148,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "> int _tmain(int argc, _TCHAR* argv[])\n{\n//DEFINE LIST\nlist <int> list1;\n//FILL LIST\nlist1.push_front(5);\nlist1.push_front(2);\nlist1.push_front(1);\nlist1.push_front(9);\nlist1.push_front(12);\nlist1.push_front(3);\nlist1.push_front(4);\n//PRINT LIST BEFORE SORTING\nprint(list1);\n//SORT LIST\n\nshuffle(list1);\n\n\n\n//PRINT AFTER SORTING\n\nsystem(\"pause\");\n\n\n\n\nreturn 0;\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,100 | <p>I have a table with 7M records I want to trim down to 10k for dev. I tried a delete, but the whole world was nearly overpowered by the transaction log size, so I truncated the table.</p>
<p>Now I wish to insert 10k records from the original table, into my dev table, but it has a identity column, and many, many other columns, so I'd thought I'd try SSIS (through the wizard), which handles the identity nicely, but gives me no place to edit a query. So I quickly made a view with a top clause, and changed the RowSet property of the source to the view. Now everything fails because nothing sees the view, although I copied and pasted the view name from my create view statement, which fails a second time because, lo, the view actually does exist. </p>
<p>Does SSIS define which DB objects are used when a package is created, which would exclude the new view, and if so, how can I refresh that?</p>
| [
{
"answer_id": 404888,
"author": "Coolcoder",
"author_id": 42434,
"author_profile": "https://Stackoverflow.com/users/42434",
"pm_score": 1,
"selected": false,
"text": "SET IDENTITY_INSERT dbo.dev_table ON\nINSERT INTO dev_table (Id, Col1,Col2,Col3,Col4)\nSELECT TOP 10000 Id, Col1, Col2, Col3, Col4 FROM prod_table\nSET IDENTITY_INSERT dbo.dev_table OFF\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
335,108 | <p>I have two third-party libraries occasionally having the same symbol name exported. When the executable is loaded, <em>ld</em> usually picks the wrong one and I getting crash as a result. I cannot do too much about the content of these libraries, so may be there is a way to instruct <em>ld</em> how to find the proper imlementation ?</p>
<p>OS - Solaris 10, my program is built by autoconf/autotools/gcc, conflicting libraries are <em>libclntsh</em> (part of Oracle driver) and OpenLDAP. Unfortuinately, I cannot use Oracle's implementation of LDAP client - it lacks many features OpenLDAP has.</p>
<p>Edited: The linkage is as following: libclntsh.so->A.so->MAIN<-B.so<-libldap_r.so</p>
| [
{
"answer_id": 335171,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 4,
"selected": true,
"text": "-Bdirect"
},
{
"answer_id": 335253,
"author": "Josh Kelley",
"author_id": 25507,
"author_profile": "https://Stackoverflow.com/users/25507",
"pm_score": 2,
"selected": false,
"text": "LD_PRELOAD LD_PRELOAD"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18174/"
] |
335,129 | <p>I'm in the process of learning WPF coming from WinForms development.</p>
<p>I have a TextChanged event assigned to one of my TextBox's in my WPF application. If the user enters invalid data, I want to be able to revert to the previous text value.</p>
<p>In the old forms day, I would replace NewValue with OldValue, but it seems WPF doesn't work the same way.</p>
<p>Any ideas on what I could do it achieve this? Am I just not thinking with WPF yet?</p>
<p>Thanks.</p>
| [
{
"answer_id": 335740,
"author": "Dennis",
"author_id": 73025,
"author_profile": "https://Stackoverflow.com/users/73025",
"pm_score": 6,
"selected": true,
"text": "PreviewTextInput e.Handled = true"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226/"
] |
335,133 | <p>Here's a short test program:</p>
<pre><code>sub foo($;@) {
my $sql = shift;
my @params = @_;
print "sql: $sql\n";
print "params: " . join(",", @params);
}
sub bar($;@) {
foo(@_);
}
bar("select * from blah where x = ? and y = ?",2,3);
print "\n";
</code></pre>
<p>Why is the output this:</p>
<pre><code>sql: 3
params:
</code></pre>
<p>Rather than this?</p>
<pre><code>sql: select * from blah where x = ? and y = ?
params: 2,3
</code></pre>
| [
{
"answer_id": 335152,
"author": "Tarski",
"author_id": 27653,
"author_profile": "https://Stackoverflow.com/users/27653",
"pm_score": 3,
"selected": false,
"text": "($;@)"
},
{
"answer_id": 335154,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": true,
"text": "foo(@_) foo() @_ bar sub bar($;@) {\n foo(shift, @_);\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91385/"
] |
335,135 | <p>A longwinded question - please bear with me!</p>
<p>I want to programatically create an XML document with namespaces and schemas. Something like</p>
<pre><code><myroot
xmlns="http://www.someurl.com/ns/myroot"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd">
<sometag>somecontent</sometag>
</myroot>
</code></pre>
<p>I'm using the rather splendid new LINQ stuff (which is new to me), and was hoping to do the above using an XElement.</p>
<p>I've got a ToXElement() method on my object:</p>
<pre><code> public XElement ToXElement()
{
XNamespace xnsp = "http://www.someurl.com/ns/myroot";
XElement xe = new XElement(
xnsp + "myroot",
new XElement(xnsp + "sometag", "somecontent")
);
return xe;
}
</code></pre>
<p>which gives me the namespace correctly, thus:</p>
<pre><code><myroot xmlns="http://www.someurl.com/ns/myroot">
<sometag>somecontent</sometag>
</myroot>
</code></pre>
<p>My question: how can I add the schema xmlns:xsi and xsi:schemaLocation attributes?</p>
<p>(BTW I can't use simple XAtttributes as I get an error for using the colon ":" in an attribute name...)</p>
<p>Or do I need to use an XDocument or some other LINQ class?</p>
<p>Thanks...</p>
| [
{
"answer_id": 335152,
"author": "Tarski",
"author_id": 27653,
"author_profile": "https://Stackoverflow.com/users/27653",
"pm_score": 3,
"selected": false,
"text": "($;@)"
},
{
"answer_id": 335154,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": true,
"text": "foo(@_) foo() @_ bar sub bar($;@) {\n foo(shift, @_);\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3099/"
] |
335,158 | <p>Is there a sort of php script which will run a series of URLs and then direct the user to the final destination? the use of this is:
creating a checkout cart on a site that doesn't have a robust "wishlist" feature. </p>
<p>The script runs a series of "add item to cart" urls, and then the final destination takes the user to their cart of products i've picked out for them. </p>
| [
{
"answer_id": 335180,
"author": "Jay",
"author_id": 41690,
"author_profile": "https://Stackoverflow.com/users/41690",
"pm_score": 3,
"selected": false,
"text": "$.get(\"http://mywebsite.com/json/cart_add.php?pid=25\");\n$.get(\"http://mywebsite.com/json/cart_add.php?pid=27\");\n"
},
{
"answer_id": 335308,
"author": "mrtunes",
"author_id": 42589,
"author_profile": "https://Stackoverflow.com/users/42589",
"pm_score": 0,
"selected": false,
"text": " <html> \n <head> \n <script type=\"text/javascript\" src=\"jquery-1.2.6.min.js\"></script> \n <script type=\"text/javascript\"> \n $(document).ready(function() { \n $(\"a\").click(function(){ \n $.get(\"http://www.store.com/item4\"); \n $.get(\"http://www.store.com/item5\");\n alert(\"Items Added, Now Redirecting\"); \n }); \n }); \n </script> \n </head> \n <body>\n <a href=\"\">Link</a> \n </body> \n </html>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42589/"
] |
335,192 | <p>I have this code</p>
<pre><code> protected void btnUpdateAddress_Click(object sender, EventArgs e)
{
sdsAddressComparison.Update();
}
</code></pre>
<p>that I'm using to update an oracle database. When I run the update sql code in SQL Navigator I have to type "Commit" or hit the commit button.</p>
<p>Do I have to code in a "Commit" somewhere in ASP.NET? and if so how and where do i do it?</p>
| [
{
"answer_id": 335202,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 2,
"selected": false,
"text": "try {\n // Open connection\n dbConn.Open();\n //DB Update Code Here\n }\n catch (Exception ex) {\n throw;\n }\n finally {\n // Close database connection\n dbConn.Close();\n }\n try {\n // Open connection & begin transaction\n dbConn.Open();\n dbTran = dbConn.BeginTransaction();\n \n //DB Update Code Here\n // Commit transaction\n dbTran.Commit();\n }\n catch (Exception ex) {\n // Rollback transaction\n dbTran.Rollback();\n throw;\n }\n finally {\n // Close database connection\n dbConn.Close();\n }\n"
},
{
"answer_id": 337094,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 0,
"selected": false,
"text": "SET AUTOCOMMIT ON\nSET AUTOCOMMIT OFF\n SET AUTOCOMMIT 100\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,205 | <p>In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:</p>
<pre><code>$string = 'hello';
echo $string{0}; // h
echo $string[0]; // h
</code></pre>
<p>My question is, is there a benefit of one over the other? What's the difference between {} and []?</p>
<p>Thanks.</p>
| [
{
"answer_id": 335213,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 7,
"selected": true,
"text": "$string[0]"
},
{
"answer_id": 26808011,
"author": "Pacerier",
"author_id": 632951,
"author_profile": "https://Stackoverflow.com/users/632951",
"pm_score": 4,
"selected": false,
"text": "$str[42] $str{42} [] {} [] {} []"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,229 | <p>I have a search program that will be looking at a database from a database. If the date range is more than 3 weeks I want to alert them that it might take a while with all the data in the database. I have a confirm message box in a JavaScript function. I want to check the date range in the aspx.cs page. how do I totrigger the message box based on that criteria? here is a copy of some of my code on html. I am not sure how to approach the checkpoint.</p>
<pre><code>function warning() {
var answer = confirm("The date range you have selected will return a substantial amount of data and will take some time to process.\n\nAre you sure you want to continue?");
if (answer)
return true;
else
return false;
}
</code></pre>
| [
{
"answer_id": 335296,
"author": "dragonjujo",
"author_id": 37344,
"author_profile": "https://Stackoverflow.com/users/37344",
"pm_score": 2,
"selected": false,
"text": "SearchButton.Attributes.Add(\"onclick\", \"javascript:return \" + \"confirm('\" + \n\"The date range you have selected will return a substantial amount of data and will take some time to process.\\n\\nAre you sure you want to continue?')\");\n"
},
{
"answer_id": 335333,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": true,
"text": "function warning() { \n\n var ele;\n var startDate;\n var endDate;\n var threeWeeksInMilliseconds = 1814400000; //1000 ms * 60 sec * 60 min * 24 hr * 21 days\n\n //get starting value\n ele = document.getElementById('txtStartDate');\n if (ele == 'undefined'){\n return false; //no start element\n }\n else {\n try{\n startDate = new Date(ele.value);\n }\n catch (e) {\n return false;\n }\n }\n\n //get the ending value\n ele = document.getElementById('txtEndDate');\n if (ele == 'undefined'){\n return false; //no start element\n }\n else {\n try{\n endDate = new Date(ele.value);\n }\n catch (e) {\n return false;\n }\n }\n\n //getTime() returns milliseconds\n if ((endDate.getTime() - startDate.getTime()) < threeWeeksInMilliseconds) {\n return true;\n }\n //else present the message for confirmation.\n\n var msg = \"The date range you have selected will return a substantial \" + \"\" +\n \"amount of data and will take some time to process.\\n\\n\" + \n \"Are you sure you want to continue?\";\n var answer;\n\n answer = confirm(msg);\n\n if (answer) {\n return true;\n }\n else {\n return false;\n }\n\n //default return condition - nothing should get here so this indicates an error.\n //Use true if you want to allow this to process. \n return false;\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,231 | <p>I am writing a custom tag in Django that should output a value stored in a user session, but I cannot find a way to access the session object from within a custom tag function. Is there any way to do this, without manually assigning the session object to a context variable?</p>
| [
{
"answer_id": 335334,
"author": "Matthew Christensen",
"author_id": 2123,
"author_profile": "https://Stackoverflow.com/users/2123",
"pm_score": 2,
"selected": false,
"text": "def add_session(request):\n return {'session': request.session}\n TEMPLATE_CONTEXT_PROCESSORS = (\"django.core.context_processors.auth\",\n\"django.core.context_processors.debug\",\n\"django.core.context_processors.i18n\",\n\"django.core.context_processors.media\",\n'context_processors.add_session',)\n def test(request):\n return render_to_response('test.html',{}, context_instance=RequestContext(request))\n"
},
{
"answer_id": 335825,
"author": "Michael Warkentin",
"author_id": 422277,
"author_profile": "https://Stackoverflow.com/users/422277",
"pm_score": 6,
"selected": true,
"text": "TEMPLATE_CONTEXT_PROCESSORS = (\"django.core.context_processors.auth\",\n\"django.core.context_processors.debug\",\n\"django.core.context_processors.i18n\",\n\"django.core.context_processors.media\",\n'django.core.context_processors.request',)\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34171/"
] |
335,232 | <p>I essentially want to spider my local site and create a list of all the titles and URLs as in:</p>
<pre>
http://localhost/mySite/Default.aspx My Home Page
http://localhost/mySite/Preferences.aspx My Preferences
http://localhost/mySite/Messages.aspx Messages
</pre>
<p>I'm running Windows. I'm open to anything that works--a C# console app, PowerShell, some existing tool, etc. We can assume that the tag does exist in the document.</p>
<p>Note: I need to actually spider the files since the title may be set in code rather than markup.</p>
| [
{
"answer_id": 335324,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": true,
"text": "#!/bin/bash\nfor file in $(find $WWWROOT -iname \\*.aspx); do\n echo -en $file '\\t'\n cat $file | tr '\\n' ' ' | sed -i 's/.*<title>\\([^<]*\\)<\\/title>.*/\\1/'\ndone\n <title> </title>"
},
{
"answer_id": 335353,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 2,
"selected": false,
"text": "wget --spider wget"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
335,244 | <p>I am using the jQuery Cookie plugin (<a href="http://plugins.jquery.com/project/cookie" rel="noreferrer">download</a> and <a href="http://stilbuero.de/jquery/cookie/" rel="noreferrer">demo</a> and <a href="http://plugins.jquery.com/files/jquery.cookie.js.txt" rel="noreferrer">source code with comments</a>) to set and read a cookie. I'm developing the page on my <strong>local machine</strong>.</p>
<p>The following code will successfully set a cookie in FireFox 3, IE 7, and Safari (PC). But <strong>if the browser is Google Chrome AND the page is a local file</strong>, it does not work.</p>
<pre><code>$.cookie("nameofcookie", cookievalue, {path: "/", expires: 30});
</code></pre>
<p><strong>What I know</strong>:</p>
<ul>
<li>The plugin's <a href="http://stilbuero.de/jquery/cookie/" rel="noreferrer">demo</a> works with Chrome.</li>
<li>If I put my code on a web server (address starting with http://), it works with Chrome.</li>
</ul>
<p>So the cookie fails only <strong>for Google Chrome on local files</strong>.</p>
<p><strong>Possible causes</strong>:</p>
<ul>
<li>Google Chrome doesn't accept cookies from web pages on the hard drive (paths like file:///C:/websites/foo.html)</li>
<li>Something in the plugin implentation causes Chrome to reject such cookies</li>
</ul>
<p>Can anyone confirm this and identify the root cause?</p>
| [
{
"answer_id": 335254,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "path: \"/\" /"
},
{
"answer_id": 7494483,
"author": "chaoxfu",
"author_id": 956088,
"author_profile": "https://Stackoverflow.com/users/956088",
"pm_score": 2,
"selected": false,
"text": "$.cookie(\"nameofcookie\", cookievalue, {path: \"/\", expires: 30});\n $.cookie(\"nameofcookie\", cookievalue, {*Path:* \"/\", expires: 30});\n"
},
{
"answer_id": 7685493,
"author": "Serdar Güner",
"author_id": 983725,
"author_profile": "https://Stackoverflow.com/users/983725",
"pm_score": 3,
"selected": false,
"text": "<script src=\"js/jquery.cookies.2.2.0.js\" type=\"text/javascript\"></script>\n<script src=\"js/jquery.Storage.js\" type=\"text/javascript\"></script>\n\nvar is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;\n\n//get cookies\nvar helpFlag=(is_chrome)?$.Storage.get(\"helpFlag\"):$.cookies.get(\"helpFlag\");\n\n//set cookies\nif(is_chrome)$.Storage.set(\"helpFlag\", \"1\");else $.cookies.set(\"helpFlag\", \"1\");\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4376/"
] |
335,250 | <p>Given the below XML snippet I need to get a list of name/value pairs for each child under DataElements. XPath or an XML parser cannot be used for reasons beyond my control so I am using regex.</p>
<pre><code><?xml version="1.0"?>
<StandardDataObject xmlns="myns">
<DataElements>
<EmpStatus>2.0</EmpStatus>
<Expenditure>95465.00</Expenditure>
<StaffType>11.A</StaffType>
<Industry>13</Industry>
</DataElements>
<InteractionElements>
<TargetCenter>92f4-MPA</TargetCenter>
<Trace>7.19879</Trace>
</InteractionElements>
</StandardDataObject>
</code></pre>
<p>The output I need is:
[{EmpStatus:2.0}, {Expenditure:95465.00}, {StaffType:11.A}, {Industry:13}] </p>
<p>The tag names under DataElements are dynamic and so cannot be expressed literally in the regex. The tag names TargetCenter and Trace are static and could be in the regex but if there is a way to avoid hardcoding that would be preferable. </p>
<pre><code>"<([A-Za-z0-9]+?)>([A-Za-z0-9.]*?)</"
</code></pre>
<p>This is the regex I have constructed and it has the problem that it erroneously includes {Trace:719879} in the results. Relying on new-lines within the XML or any other apparent formatting is not an option.</p>
<p>Below is an approximation of the Java code I am using:</p>
<pre><code>private static final Pattern PATTERN_1 = Pattern.compile(..REGEX..);
private List<DataElement> listDataElements(CharSequence cs) {
List<DataElement> list = new ArrayList<DataElement>();
Matcher matcher = PATTERN_1.matcher(cs);
while (matcher.find()) {
list.add(new DataElement(matcher.group(1), matcher.group(2)));
}
return list;
}
</code></pre>
<p>How can I change my regex to only include data elements and ignore the rest?</p>
| [
{
"answer_id": 335262,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "DataElements>.*?</DataElements"
},
{
"answer_id": 335589,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 1,
"selected": false,
"text": "private static final Pattern PATTERN_1 = Pattern.compile(..REGEX..);\nprivate static final String START_TAG = \"<DataElements>\";\nprivate static final String END_TAG = \"</DataElements>\";\nprivate List<DataElement> listDataElements(String input) {\n String cs = input.substring(input.indexOf(START_TAG) + START_TAG.length(), input.indexOf(END_TAG);\n List<DataElement> list = new ArrayList<DataElement>();\n Matcher matcher = PATTERN_1.matcher(cs);\n while (matcher.find()) {\n list.add(new DataElement(matcher.group(1), matcher.group(2)));\n }\n return list;\n}\n"
},
{
"answer_id": 336462,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 5,
"selected": true,
"text": "Pattern regex = Pattern.compile(\"<DataElements>(.*?)</DataElements>\", Pattern.DOTALL);\nMatcher matcher = regex.matcher(subjectString);\nPattern regex2 = Pattern.compile(\"<([^<>]+)>([^<>]+)</\\\\1>\");\nif (matcher.find()) {\n String DataElements = matcher.group(1);\n Matcher matcher2 = regex2.matcher(DataElements);\n while (matcher2.find()) {\n list.add(new DataElement(matcher2.group(1), matcher2.group(2)));\n } \n}\n"
},
{
"answer_id": 44383695,
"author": "Amith Perera",
"author_id": 8118112,
"author_profile": "https://Stackoverflow.com/users/8118112",
"pm_score": 0,
"selected": false,
"text": "Next I tried to load that Reg Ex via property file while injecting it. It worked fine.\n\n p:remoteDirectory=\"${rawDailyReport.remote.download.dir}\"\n p:localDirectory=\"${rawDailyReport.local.valid.dir}\"\n p:redEx=\"${rawDailyReport.download.regex}\"\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3211/"
] |
335,256 | <p>What is, or should I ask, is there, an equivalent to DllMain when creating a DLL using C++/CLI?</p>
<p>Are there any restrictions on what cannot be called from this initialization code?</p>
| [
{
"answer_id": 362016,
"author": "shash",
"author_id": 11684,
"author_profile": "https://Stackoverflow.com/users/11684",
"pm_score": 1,
"selected": false,
"text": "ref"
},
{
"answer_id": 884677,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 3,
"selected": true,
"text": "DllMain()"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697/"
] |
335,267 | <p>I have a custom DataGridView column that uses an embedded control that pops up a search window for the value of that column. The important thing is that the databound column is a numeric ID, but the custom column cells display a text description. </p>
<p>How do I get the column to sort on the text description rather than the numeric ID? </p>
<p>I don't see a way to override the column to sort by FormattedValue instead of Value. I could ensure that the description shows up as a separate column in my data table, but I don't see any way to say "use column VALUE_ID as DataMember but column VALUE_DESCRIPITON as 'SortMember'"</p>
| [
{
"answer_id": 335366,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "DataTable BindingList<T> ApplySortCore RemoveSortCore SupportsSortingCore IsSortedCore SortPropertyCore SortDirectionCore ApplySortCore PropertyDescriptor IComparable IComparable<T> ToString() System.ComponentModel"
},
{
"answer_id": 335453,
"author": "Agies",
"author_id": 333860,
"author_profile": "https://Stackoverflow.com/users/333860",
"pm_score": 3,
"selected": true,
"text": "private bool ascending;\nprivate int sortColumn;\nprivate void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)\n{\n List<SomeObject> list = (List<SomeObject>)someBindingSource.DataSource;\n if (e.ColumnIndex != sortColumn) ascending = false;\n\n int 1 = e.ColumnIndex;\n if (i == DescriptionColumn.Index)\n list.Sort(new Comparison<SomeObject>((x,y) => x.ID.CompareTo(y.ID)));\n\n sortColumn = e.ColumnIndex;\n ascending = !ascending;\n if (!ascending) list.Reverse():\n\n someBindingSource.ResetBindings(false);\n // you may also have to call dgv.Invalidate();\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945/"
] |
335,273 | <p>When I create a new Gdiplus::Bitmap using the Bitmap::FromHBITMAP function,
the resulting Bitmap is opaque - none of the partial transparency from the original HBITMAP is preserved.</p>
<p>Is there a way to create a Gdiplus::Bitmap from an HBITMAP which brings across the alpha channel data?</p>
| [
{
"answer_id": 5860094,
"author": "Geoffrey Elliott",
"author_id": 732523,
"author_profile": "https://Stackoverflow.com/users/732523",
"pm_score": 4,
"selected": false,
"text": "#include <GdiPlus.h>\n#include <memory>\n\nGdiplus::Status HBitmapToBitmap( HBITMAP source, Gdiplus::PixelFormat pixel_format, Gdiplus::Bitmap** result_out )\n{\n BITMAP source_info = { 0 };\n if( !::GetObject( source, sizeof( source_info ), &source_info ) )\n return Gdiplus::GenericError;\n\n Gdiplus::Status s;\n\n std::auto_ptr< Gdiplus::Bitmap > target( new Gdiplus::Bitmap( source_info.bmWidth, source_info.bmHeight, pixel_format ) );\n if( !target.get() )\n return Gdiplus::OutOfMemory;\n if( ( s = target->GetLastStatus() ) != Gdiplus::Ok )\n return s;\n\n Gdiplus::BitmapData target_info;\n Gdiplus::Rect rect( 0, 0, source_info.bmWidth, source_info.bmHeight );\n\n s = target->LockBits( &rect, Gdiplus::ImageLockModeWrite, pixel_format, &target_info );\n if( s != Gdiplus::Ok )\n return s;\n\n if( target_info.Stride != source_info.bmWidthBytes )\n return Gdiplus::InvalidParameter; // pixel_format is wrong!\n\n CopyMemory( target_info.Scan0, source_info.bmBits, source_info.bmWidthBytes * source_info.bmHeight );\n\n s = target->UnlockBits( &target_info );\n if( s != Gdiplus::Ok )\n return s;\n\n *result_out = target.release();\n\n return Gdiplus::Ok;\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25457/"
] |
335,276 | <p><br />I have an application where I need the user to upload a photo. After the photo is uploaded to the server, which shouldn't take very long, the user should get back a response that's a regular HTML page saying "thanks...bla bla bla..."<br />
Now, after the the response is sent back to the client and he goes on his merry way, I want the server to continue to work on this photo. It needs to do something that's heavy and would take a long time. But this is okay because the user isn't waiting for anything. He's probably in a different page.<br />
So my question is, how do I do this with ASP.NET.
The application I'm writing is in ASP.NET MVC so I'm imagining something like</p>
<pre><code>//save the photo on the server
//and send viewdata saying "thanks..."
return View();
//keep doing heavy processing on the photo
</code></pre>
<p>But I guess this isn't really how it's done. Also, since sometimes I work with ASP.NET WebForms, how is this done with WebForms as well.<br />
Thank you!</p>
| [
{
"answer_id": 335431,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 4,
"selected": true,
"text": "Action<object> d = delegate(object val)\n{\n // in this anonymous delegate, write code that you want to run\n ProcessDataAndLog();\n};\n\nd.BeginInvoke(null, null, null); // this spins off the method asynchronously.\n System.Threading.ThreadPool.QueueUserWorkItem(\n delegate(object state)\n {\n // in this anonymous delegate, write code that you want to run\n ProcessDataAndLog();\n });\n"
},
{
"answer_id": 337100,
"author": "pythonandchips",
"author_id": 1213936,
"author_profile": "https://Stackoverflow.com/users/1213936",
"pm_score": 0,
"selected": false,
"text": "//save the photo on the server\n//Add referance in queue (possibly in database to http post that the windows service monitors with details of path to the file, output path, transformation etc.)\n//and send viewdata saying \"thanks...\"\nreturn View();\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30725/"
] |
335,286 | <p>I have two classes, Foo and Bar, that have constructors like this:</p>
<pre><code>class Foo
{
Foo()
{
// do some stuff
}
Foo(int arg)
{
// do some other stuff
}
}
class Bar : Foo
{
Bar() : base()
{
// some third thing
}
}
</code></pre>
<p>Now I want to introduce a constructor for Bar that takes an int, but I want the stuff that happens in Bar() to run <em>as well</em> as the stuff from Foo(int). Something like this:</p>
<pre><code>Bar(int arg) : Bar(), base(arg)
{
// some fourth thing
}
</code></pre>
<p>Is there any way to do this in C#? The best I have so far is putting the work done by Bar() into a function, that also gets called by Bar(int), but this is pretty inelegant.</p>
| [
{
"answer_id": 335321,
"author": "g .",
"author_id": 6944,
"author_profile": "https://Stackoverflow.com/users/6944",
"pm_score": 1,
"selected": false,
"text": "class Bar : Foo\n{\n Bar() : this(0)\n {\n }\n\n Bar(int arg) : base(arg)\n {\n }\n}\n"
},
{
"answer_id": 335325,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 5,
"selected": false,
"text": "Bar() : this(0) \nBar(int) : Foo(int) initializes Bar\nFoo(int) initializes Foo\nFoo() : this(0) \n"
},
{
"answer_id": 335332,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": " public class Foo\n{\n public Foo()\n {\n }\n public Foo(int? arg): this()\n {\n }\n\n}\npublic class Bar : Foo\n{\n private int x;\n public Bar(): this(new int?()) // edited to fix type ambiguity\n {\n // stuff that only runs for paramerless ctor\n }\n public Bar(int? arg)\n : base(arg)\n {\n if (arg.HasValue)\n {\n // Do stuff for both parameterless and parameterized ctor\n }\n // Do other stuff for only parameterized ctor\n }\n}\n"
},
{
"answer_id": 335338,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": 4,
"selected": false,
"text": "class Foo\n{\n Foo()\n {\n // do some stuff\n }\n\n Foo(int arg): this()\n {\n // do some other stuff\n }\n}\n\nclass Bar : Foo\n{\n Bar() : Bar(0)\n {\n // some third thing\n }\n\n Bar(int arg): base(arg)\n {\n // something\n }\n}\n"
},
{
"answer_id": 16291402,
"author": "Moch Yusup",
"author_id": 1074582,
"author_profile": "https://Stackoverflow.com/users/1074582",
"pm_score": 0,
"selected": false,
"text": "public Foo\n{\n public Foo()\n {\n this.InitializeObject();\n }\n\n public Foo(int arg) : this()\n {\n // do something with Foo's arg\n }\n\n protected virtual void InitializeObject()\n {\n // initialize object Foo\n }\n}\n\npublic Bar : Foo\n{\n public Bar : base() { }\n\n public Bar(int arg) : base(arg)\n {\n // do something with Bar's arg\n }\n\n protected override void InitializeObject()\n {\n // initialize object Bar\n\n base.InitializeObject();\n }\n}\n InitializeObject() base.InitializeObject()"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28771/"
] |
335,291 | <p>I just tried (for the first time, I might add) a </p>
<blockquote>
<p>port upgrade installed</p>
</blockquote>
<p>in Macports, and I'm afraid I might come to regret it: A lot of errors -- specially regarding X11 and Python.</p>
<p>Here's a typical error message regarding python:</p>
<blockquote>
<p>---> Activating python24 2.4.5_4+darwin_9
Error: Activating python24 2.4.5_4 failed:
Image error: /opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4 already exists and does not belong to a registered port. Unable to activate port python24.</p>
</blockquote>
<p>My question: Should I expect a bit of trouble? And: Any hints on fixing these errors?</p>
<p>I did do "sync" and "selfupdate" before upgrading.</p>
| [
{
"answer_id": 2360320,
"author": "dman",
"author_id": 213577,
"author_profile": "https://Stackoverflow.com/users/213577",
"pm_score": 3,
"selected": false,
"text": "[...] already exists and does not belong to a registered port\n Putty FireFTP apt-get apt-get apt-get sudo port -d -f install expat"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282296/"
] |
335,311 | <p>My question is about one particular usage of static keyword. It is possible to use <code>static</code> keyword to cover a code block within a class which does not belong to any function. For example following code compiles:</p>
<pre><code>public class Test {
private static final int a;
static {
a = 5;
doSomething(a);
}
private static int doSomething(int x) {
return (x+5);
}
}
</code></pre>
<p>If you remove the <code>static</code> keyword it complains because the variable <code>a</code> is <code>final</code>. However it is possible to remove both <code>final</code> and <code>static</code> keywords and make it compile. </p>
<p>It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?</p>
| [
{
"answer_id": 335339,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 6,
"selected": false,
"text": "static class JNIGlue {\n static {\n System.loadLibrary(\"foo\");\n }\n}\n"
},
{
"answer_id": 335349,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 10,
"selected": true,
"text": "static int a static int a"
},
{
"answer_id": 23020469,
"author": "cardman",
"author_id": 3280038,
"author_profile": "https://Stackoverflow.com/users/3280038",
"pm_score": 3,
"selected": false,
"text": "class MyClass {\n\n private int myField = 3;\n {\n myField = myField + 2;\n //myField is worth 5 for all instance\n }\n\n public MyClass() {\n myField = myField * 4;\n //myField is worth 20 for all instance initialized with this construtor\n }\n\n public MyClass(int _myParam) {\n if (_myParam > 0) {\n myField = myField * 4;\n //myField is worth 20 for all instance initialized with this construtor\n //if _myParam is greater than 0\n } else {\n myField = myField + 5;\n //myField is worth 10 for all instance initialized with this construtor\n //if _myParam is lower than 0 or if _myParam is worth 0\n }\n }\n\n public void setMyField(int _myField) {\n myField = _myField;\n }\n\n\n public int getMyField() {\n return myField;\n }\n}\n\npublic class MainClass{\n\n public static void main(String[] args) {\n MyClass myFirstInstance_ = new MyClass();\n System.out.println(myFirstInstance_.getMyField());//20\n MyClass mySecondInstance_ = new MyClass(1);\n System.out.println(mySecondInstance_.getMyField());//20\n MyClass myThirdInstance_ = new MyClass(-1);\n System.out.println(myThirdInstance_.getMyField());//10\n }\n}\n class MyClass {\n\n private int myField = 3;\n\n public MyClass() {\n myField = myField + 2;\n myField = myField * 4;\n //myField is worth 20 for all instance initialized with this construtor\n }\n\n public MyClass(int _myParam) {\n myField = myField + 2;\n if (_myParam > 0) {\n myField = myField * 4;\n //myField is worth 20 for all instance initialized with this construtor\n //if _myParam is greater than 0\n } else {\n myField = myField + 5;\n //myField is worth 10 for all instance initialized with this construtor\n //if _myParam is lower than 0 or if _myParam is worth 0\n }\n }\n\n public void setMyField(int _myField) {\n myField = _myField;\n }\n\n\n public int getMyField() {\n return myField;\n }\n}\n\npublic class MainClass{\n\n public static void main(String[] args) {\n MyClass myFirstInstance_ = new MyClass();\n System.out.println(myFirstInstance_.getMyField());//20\n MyClass mySecondInstance_ = new MyClass(1);\n System.out.println(mySecondInstance_.getMyField());//20\n MyClass myThirdInstance_ = new MyClass(-1);\n System.out.println(myThirdInstance_.getMyField());//10\n }\n}\n"
},
{
"answer_id": 29225409,
"author": "Madan Sapkota",
"author_id": 782535,
"author_profile": "https://Stackoverflow.com/users/782535",
"pm_score": 8,
"selected": false,
"text": "static {} static { ... } return this super package com.example.learnjava;\n\nimport java.util.ArrayList;\n\npublic class Fruit {\n\n static {\n System.out.println(\"Inside Static Initializer.\");\n\n // fruits array\n ArrayList<String> fruits = new ArrayList<>();\n fruits.add(\"Apple\");\n fruits.add(\"Orange\");\n fruits.add(\"Pear\");\n\n // print fruits\n for (String fruit : fruits) {\n System.out.println(fruit);\n }\n System.out.println(\"End Static Initializer.\\n\");\n }\n\n public static void main(String[] args) {\n System.out.println(\"Inside Main Method.\");\n }\n}\n"
},
{
"answer_id": 30388953,
"author": "Alexei Fando",
"author_id": 1130418,
"author_profile": "https://Stackoverflow.com/users/1130418",
"pm_score": 6,
"selected": false,
"text": "public class Foo {\n \n //instance variable initializer\n String s = \"abc\";\n \n //constructor\n public Foo() {\n System.out.println(\"constructor called\");\n }\n \n //static initializer\n static {\n System.out.println(\"static initializer called\");\n }\n \n //instance initializer\n {\n System.out.println(\"instance initializer called\");\n }\n \n public static void main(String[] args) {\n new Foo();\n new Foo();\n }\n}\n b = 0 int b = 0 int b;\nb = 0;\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33885/"
] |
335,330 | <p>We have a C++ library that we provide to several different clients. Recently we made the switch from using raw pointers in the public interface to using boost::sharedptr instead. This has provided an enormous benefit, as you might guess, in that now the clients no longer have to worry about who needs to delete what and when. When we made the switch I believed it was the right thing to do, but it bothered me that we had to include something from a third-party library in our public interface - generally you avoid that kind of thing if you can. I rationalized it that boost was practically part of the C++ language now, and our use case requires that both the client code and the library hold pointers to the objects. However recently one of our clients has asked us if we could switch to using a neutral smart pointer class in the interface, because our library is essentially forcing them to a particular version of boost- a point which I certainly understand and appreciate. So now I am wondering what the best course of action might be. I have thought about it a little bit, and wondered about creating a simple smart pointer class that simply held a real boost smart pointer. But then the clients would probably immediately stuff one of those into their flavor of boost::sharedptr, and then we'd be three shared pointers deep - which might be a problem, or it might not. Anyway, I'd love to hear some opinions from the community about the best way to solve this problem.</p>
<p>Edit: I originally said transfer of ownership, but I should have specified that code on both sides of the API boundary need to hold a pointer to the object.</p>
| [
{
"answer_id": 335449,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "boost::shared_ptr"
},
{
"answer_id": 3305394,
"author": "Matt Joiner",
"author_id": 149482,
"author_profile": "https://Stackoverflow.com/users/149482",
"pm_score": 1,
"selected": false,
"text": "auto_ptr std::shared_ptr"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] |
335,337 | <p>This could be a little off the ballpark, but a friend asked me about it and it's kind of bothering me. How do you figure out the current path in your address bar if the server redirects all requests to a default file, say, index.html.</p>
<p>Let's say you entered:</p>
<pre><code>www.example.com/
</code></pre>
<p>And your server configuration automatically redirects this request to </p>
<pre><code>www.example.com/index.html
</code></pre>
<p>But the address in your url bar does not change! So how do you figure out using Javascript that the path on this url is index.html? </p>
<p>I looked into location.pathname but that's only giving me /.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 335373,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 1,
"selected": false,
"text": "index.html /"
},
{
"answer_id": 335376,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": true,
"text": "'www.example.com' GET / HTTP/1.1\nUser-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/\n0.9.8h zlib/1.2.3 libssh2/0.15-CVS\nHost: www.example.com\nAccept: */*\n / HTTP/1.1 200 OK\n(more headers)\n\nContent...\n HTTP/1.1 301 Moved Permanently\nLocation: (location of redirect)\n(more headers)\n\n(Optional content)\n / index.html index.php default.aspx /"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32816/"
] |
335,342 | <p>Is SQL Server 2008 a good option to use as an image store for an e-commerce website? It would be used to store product images of various sizes and angles. A web server would output those images, reading the table by a clustered ID. The total image size would be around 10 GB, but will need to scale. I see a lot of benefits over using the file system, but I am worried that SQL server, not having an O(1) lookup, is not the best solution, given that the site has a lot of traffic. Would that even be a bottle-neck? What are some thoughts, or perhaps other options?</p>
| [
{
"answer_id": 335394,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "O(log n)"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13855/"
] |
335,369 | <p>We've run into some problems with the <a href="http://www.parashift.com/c++-faq-lite/static-init-order.html" rel="noreferrer">static initialization order fiasco</a>, and I'm looking for ways to comb through a whole lot of code to find possible occurrences. Any suggestions on how to do this efficiently?</p>
<p>Edit: I'm getting some good answers on how to SOLVE the static initialization order problem, but that's not really my question. I'd like to know how to FIND objects that are subject to this problem. Evan's answer seems to be the best so far in this regard; I don't think we can use valgrind, but we may have memory analysis tools that could perform a similar function. That would catch problems only where the initialization order is wrong for a given build, and the order can change with each build. Perhaps there's a static analysis tool that would catch this. Our platform is IBM XLC/C++ compiler running on AIX.</p>
| [
{
"answer_id": 335414,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 3,
"selected": false,
"text": "class A {\npublic:\n static X &getStatic() { static X my_static; return my_static; }\n};\n"
},
{
"answer_id": 335422,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 1,
"selected": false,
"text": "MyObject myObject\n MyObject &myObject()\n{\n static MyObject myActualObject;\n return myActualObject;\n}\n"
},
{
"answer_id": 335608,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "_initterm _initterm _initterm"
},
{
"answer_id": 335746,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 6,
"selected": false,
"text": "class A\n{\n public:\n // Get the global instance abc\n static A& getInstance_abc() // return a reference\n {\n static A instance_abc;\n return instance_abc;\n }\n};\n getInstance_XXX() class B\n{\n public:\n static B& getInstance_Bglob;\n {\n static B instance_Bglob;\n return instance_Bglob;;\n }\n\n ~B()\n {\n A::getInstance_abc().doSomthing();\n // The object abc is accessed from the destructor.\n // Potential problem.\n // You must guarantee that abc is destroyed after this object.\n // To guarantee this you must make sure it is constructed first.\n // To do this just access the object from the constructor.\n }\n\n B()\n {\n A::getInstance_abc();\n // abc is now fully constructed.\n // This means it was constructed before this object.\n // This means it will be destroyed after this object.\n // This means it is safe to use from the destructor.\n }\n};\n"
},
{
"answer_id": 3402232,
"author": "Warren Stevens",
"author_id": 398327,
"author_profile": "https://Stackoverflow.com/users/398327",
"pm_score": 5,
"selected": false,
"text": "#ifndef FIASCO_H\n#define FIASCO_H\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n// [WS 2010-07-30] Detect the infamous \"Static initialization order fiasco\"\n// email warrenstevens --> [initials]@[firstnamelastname].com \n// read --> http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12 if you haven't suffered\n// To enable this feature --> define E-N-A-B-L-E-_-F-I-A-S-C-O-_-F-I-N-D-E-R, rebuild, and run\n#define ENABLE_FIASCO_FINDER\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifdef ENABLE_FIASCO_FINDER\n\n#include <iostream>\n#include <fstream>\n\ninline bool WriteFiasco(const std::string& fileName)\n{\n static int counter = 0;\n ++counter;\n\n std::ofstream file;\n file.open(\"FiascoFinder.txt\", std::ios::out | std::ios::app);\n file << \"Starting to initialize file - number: [\" << counter << \"] filename: [\" << fileName.c_str() << \"]\" << std::endl;\n file.flush();\n file.close();\n return true;\n}\n\n// [WS 2010-07-30] If you get a name collision on the following line, your usage is likely incorrect\n#define FIASCO_FINDER static const bool g_psuedoUniqueName = WriteFiasco(__FILE__);\n\n#else // ENABLE_FIASCO_FINDER\n// do nothing\n#define FIASCO_FINDER\n\n#endif // ENABLE_FIASCO_FINDER\n\n#endif //FIASCO_H\n #include \"PreCompiledHeader.h\" // (which #include's the above file)\nFIASCO_FINDER\n#include \"RegularIncludeOne.h\"\n#include \"RegularIncludeTwo.h\"\n Starting to initialize file - number: [1] filename: [p:\\\\OneFile.cpp]\nStarting to initialize file - number: [2] filename: [p:\\\\SecondFile.cpp]\nStarting to initialize file - number: [3] filename: [p:\\\\ThirdFile.cpp]\n"
},
{
"answer_id": 58541615,
"author": "Jack Yates",
"author_id": 3160855,
"author_profile": "https://Stackoverflow.com/users/3160855",
"pm_score": 1,
"selected": false,
"text": "$ g++ -fsanitize=address -g staticA.C staticB.C staticC.C -o static \n$ ASAN_OPTIONS=check_initialization_order=true:strict_init_order=true ./static \n=================================================================\n==32208==ERROR: AddressSanitizer: initialization-order-fiasco on address ... at ...\n #0 0x400f96 in firstClass::getValue() staticC.C:13\n #1 0x400de1 in secondClass::secondClass() staticB.C:7\n ...\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10077/"
] |
335,374 | <p>I need to be able to serialize a string and then have it save in a .txt or .xml file. I've never used the implementation to read/write files, just remember I am a relative beginner. Also, I need to know how to deserialize the string to be printed out in terminal as a normal string. </p>
| [
{
"answer_id": 335416,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 0,
"selected": false,
"text": "Element rootEl = new Element(\"root\");\nrootEl.setText(\"my string\");\ndoc.appendChild(rootEl);\nXMLOutputter outputter = new XMLOutputter();\noutputter.output(doc);\n"
},
{
"answer_id": 335551,
"author": "Alex Beardsley",
"author_id": 14007,
"author_profile": "https://Stackoverflow.com/users/14007",
"pm_score": 0,
"selected": false,
"text": "import com.thoughtworks.xstream.XStream;\n\nclass Date {\n int year;\n int month;\n int day;\n}\n\npublic class Serialize {\n public static void main(String[] args) {\n\n XStream xstream = new XStream();\n\n Date date = new Date();\n date.year = 2004;\n date.month = 8;\n date.day = 15;\n\n xstream.alias(\"date\", Date.class);\n\n String decl = \"\\n\";\n\n String xml = xstream.toXML(date);\n\n System.out.print(decl + xml);\n }\n}\n\npublic class Deserialize {\n\n public static void main(String[] args) {\n\n XStream xstream = new XStream();\n\n Date date = new Date();\n\n xstream.alias(\"date\", Date.class);\n\n String xml = xstream.toXML(date);\n\n System.out.print(xml);\n\n Date newdate = (Date)xstream.fromXML(xml);\n newdate.month = 12;\n newdate.day = 2;\n\n String newxml = xstream.toXML(newdate);\n\n System.out.print(\"\\n\\n\" + newxml);\n }\n}\n"
},
{
"answer_id": 335646,
"author": "James",
"author_id": 41039,
"author_profile": "https://Stackoverflow.com/users/41039",
"pm_score": 2,
"selected": false,
"text": "String str = \"serialize me\";\n String file = \"file.txt\";\n try{\n ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));\n out.writeObject(str);\n out.close();\n\n ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));\n String newString = (String) in.readObject();\n assert str.equals(newString);\n System.out.println(\"Strings are equal\");\n }catch(IOException ex){\n ex.printStackTrace();\n }catch(ClassNotFoundException ex){\n ex.printStackTrace();\n }\n"
},
{
"answer_id": 345548,
"author": "Piko",
"author_id": 17304,
"author_profile": "https://Stackoverflow.com/users/17304",
"pm_score": 1,
"selected": false,
"text": "class MyBean{ \n private String name = \"json\"; \n private int pojoId = 1; \n private char[] options = new char[]{'a','f'}; \n private String func1 = \"function(i){ return this.options[i]; }\"; \n private JSONFunction func2 = new JSONFunction(new String[]{\"i\"},\"return this.options[i];\"); \n\n // getters & setters \n ... \n} \n\nJSONObject jsonObject = JSONObject.fromObject( new MyBean() );\nString xmlText = XMLSerializer.write( jsonObject );\n"
},
{
"answer_id": 482403,
"author": "prule",
"author_id": 20242,
"author_profile": "https://Stackoverflow.com/users/20242",
"pm_score": 2,
"selected": false,
"text": "FileUtils.writeStringToFile(File file,String data) FileUtils.readFileToString(File file)"
},
{
"answer_id": 3821236,
"author": "yeforriak",
"author_id": 233026,
"author_profile": "https://Stackoverflow.com/users/233026",
"pm_score": 0,
"selected": false,
"text": " FileOutputStream fos = null;\n try {\n new File(FILE_LOCATION_DIRECTORY).mkdirs();\n File fileLocation = new File(FILE_LOCATION_DIRECTORY + \"/\" + fileName);\n fos = new FileOutputStream(fileLocation);\n stream.toXML(userAlertSubscription, fos); \n } catch (IOException e) {\n Log.error(this, \"Error %s in file %s\", e.getMessage(), fileName);\n } finally {\n IOUtils.closeQuietly(fos);\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36268/"
] |
335,378 | <p>In C# I use the <code>#warning</code> and <code>#error</code> directives,</p>
<pre><code>#warning This is dirty code...
#error Fix this before everything explodes!
</code></pre>
<p>This way, the compiler will let me know that I still have work to do. What technique do you use to mark code so you won't forget about it?</p>
| [
{
"answer_id": 335385,
"author": "Guge",
"author_id": 37771,
"author_profile": "https://Stackoverflow.com/users/37771",
"pm_score": 8,
"selected": true,
"text": "// TODO // HACK"
},
{
"answer_id": 335402,
"author": "John MacIntyre",
"author_id": 29043,
"author_profile": "https://Stackoverflow.com/users/29043",
"pm_score": 3,
"selected": false,
"text": "#error finish this\n"
},
{
"answer_id": 335403,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 3,
"selected": false,
"text": "PutTheUpdateCodeHere();\n"
},
{
"answer_id": 335405,
"author": "Chris Lees",
"author_id": 1398981,
"author_profile": "https://Stackoverflow.com/users/1398981",
"pm_score": 4,
"selected": false,
"text": "//TODO: //HACK: throw new NotImplementedException();"
},
{
"answer_id": 335423,
"author": "idan315",
"author_id": 261724,
"author_profile": "https://Stackoverflow.com/users/261724",
"pm_score": 3,
"selected": false,
"text": "try\n{\n //do stuff\n return true;\n}\ncatch // no idea how to prevent an exception here at the moment, this make it work for now...\n{\n if (DateTime.Today > new DateTime(2007, 2, 7))\n throw new InvalidOperationException(\"fix me already!! no catching exceptions like this!\");\n return false;\n}\n"
},
{
"answer_id": 335557,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 1,
"selected": false,
"text": "// TODO: <explanation>\n // FIXME: <explanation>\n"
},
{
"answer_id": 335777,
"author": "Brian Rudolph",
"author_id": 33114,
"author_profile": "https://Stackoverflow.com/users/33114",
"pm_score": 2,
"selected": false,
"text": "//TODO: Finish this\n"
},
{
"answer_id": 3090336,
"author": "Chubas",
"author_id": 204142,
"author_profile": "https://Stackoverflow.com/users/204142",
"pm_score": 1,
"selected": false,
"text": "// TODO: This code loan causes an annual interest rate of 7.5% developer/hour. Upfront fee as stated by the current implementation. This contract is subject of prior authorization from the DCB (Developer's Code Bank), and tariff may change without warning."
},
{
"answer_id": 3090386,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 2,
"selected": false,
"text": "ToDo(msg) class ToDo_helper\n{\n public:\n ToDo_helper(const std::string& msg, const char* file, int line)\n {\n std::string header(79, '*');\n Log(LOG_WARNING) << header << '\\n'\n << \" TO DO:\\n\"\n << \" Task: \" << msg << '\\n'\n << \" File: \" << file << '\\n'\n << \" Line: \" << line << '\\n'\n << header;\n }\n};\n\n#define TODO_HELPER_2(X, file, line) \\\n static Error::ToDo_helper tdh##line(X, file, line)\n\n#define TODO_HELPER_1(X, file, line) TODO_HELPER_2(X, file, line)\n#define ToDo(X) TODO_HELPER_1(X, __FILE__, __LINE__)\n void some_unfinished_business() {\n ToDo(\"Take care of unfinished business\");\n }\n"
},
{
"answer_id": 3090424,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "//REVIEW // REVIEW - RP - Is this the best way to achieve x? Could we use algorithm y?\n //REFACTOR // REFACTOR - should pull this method up and remove near-dupe code in XYZ.cs\n"
},
{
"answer_id": 59394648,
"author": "Pietro",
"author_id": 235472,
"author_profile": "https://Stackoverflow.com/users/235472",
"pm_score": 1,
"selected": false,
"text": "//+TODO Usual meaning.\n//+H Where I was working last time.\n//+T Temporary/test code.\n//+B Bug.\n//+P Performance issue.\n //+B vs //+B+++ //+ //+B //+B+++ //+ + t"
},
{
"answer_id": 63065457,
"author": "marko.ristin",
"author_id": 1600678,
"author_profile": "https://Stackoverflow.com/users/1600678",
"pm_score": 0,
"selected": false,
"text": "git blame"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343/"
] |
335,387 | <p>What's a nice way to merge two sorted arrays in ActionScript (specifically ActionScript 3.0)? The resulting array should be sorted and without duplicates.</p>
| [
{
"answer_id": 335942,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 5,
"selected": false,
"text": ".concat() ArrayUtil.createUniqueCopy() // from as3corelib:\nimport com.adobe.utils.ArrayUtil;\n\nvar a1:Array = [\"a\", \"b\", \"c\"];\nvar a2:Array = [\"c\", \"b\", \"x\", \"y\"];\n\nvar c:Array = ArrayUtil.createUniqueCopy(a1.concat(a2)); // result: [\"a\", \"b\", \"c\", \"x\", \"y\"]\n Array.indexOf() var a1:Array = [\"a\", \"b\", \"c\"];\nvar a2:Array = [\"c\", \"b\", \"x\", \"y\"];\nvar a3:Array = [\"a\", \"x\", \"x\", \"y\", \"z\"];\n\nvar c:Array = arrConcatUnique(a1, a2, a3); // result: [\"a\", \"b\", \"c\", \"x\", \"y\", \"z\"]\n\nprivate function arrConcatUnique(...args):Array\n{\n var retArr:Array = new Array();\n for each (var arg:* in args)\n {\n if (arg is Array)\n {\n for each (var value:* in arg)\n {\n if (retArr.indexOf(value) == -1)\n retArr.push(value);\n }\n }\n }\n return retArr;\n}\n"
},
{
"answer_id": 357272,
"author": "Tmdean",
"author_id": 45084,
"author_profile": "https://Stackoverflow.com/users/45084",
"pm_score": 2,
"selected": false,
"text": "function merge(a1:Array, a2:Array):Array {\n var result:Array = [];\n var i1:int = 0, i2:int = 0;\n\n while (i1 < a1.length && i2 < a2.length) {\n if (a1[i1] < a2[i2]) {\n result.push(a1[i1]);\n i1++;\n } else if (a2[i2] < a1[i1]) {\n result.push(a2[i2]);\n i2++;\n } else {\n result.push(a1[i1]);\n i1++;\n i2++;\n }\n }\n\n while (i1 < a1.length) result.push(a1[i1++]);\n while (i2 < a2.length) result.push(a2[i2++]);\n\n return result;\n}\n"
},
{
"answer_id": 4499760,
"author": "raph",
"author_id": 549969,
"author_profile": "https://Stackoverflow.com/users/549969",
"pm_score": 2,
"selected": false,
"text": "function remDuplicates(_array:Array):void{\n for (var i:int = 0; i < _array.length;++i) {\n var index:int = _array.indexOf(_array[i]);\n if (index != -1 && index != i) {\n _array.splice(i--, 1);\n }\n }\n}\n var testArray:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];\nvar testArray2:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];\n\ntestArray.concat(testArray2);\ntrace(testArray);\nremDuplicates(testArray);\ntrace(testArray);\n"
},
{
"answer_id": 6080880,
"author": "JonnyReeves",
"author_id": 227349,
"author_profile": "https://Stackoverflow.com/users/227349",
"pm_score": 2,
"selected": false,
"text": "// Combine the two Arrays.\nconst combined : Array = a.concat(b);\n\n// Convert them to a Set; this will knock out all duplicates.\nconst set : Object = {}; // use a Dictionary if combined contains complex types.\n\nconst len : uint = combined.length;\nfor (var i : uint = 0; i < len; i++) {\n set[combined[i]] = true;\n}\n\n// Extract all values from the Set to produce the final result.\nconst result : Array = [];\nfor (var prop : * in set) {\n result.push[prop];\n}\n"
},
{
"answer_id": 8291876,
"author": "Mrugesh",
"author_id": 1050220,
"author_profile": "https://Stackoverflow.com/users/1050220",
"pm_score": 0,
"selected": false,
"text": " var ansArr:Array = new Array();\n var len:uint = p_arr.length;\n var i:uint = 0;\n var j:uint = 0;\n ansArr[j] = p_arr[i];\n i++;\n j++;\n while(i<len)\n {\n if(ansArr[j] != p_arr[i])\n { \n ansArr[j] = p_arr[i];\n j++;\n }\n i++;\n }\n return ansArr;\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4127/"
] |
335,399 | <p>What I want to do is patch an existing Python module that uses urllib2 to run on App Engine, but I don't want to break it so it can be used elsewhere. So I'm looking for a quick solution to test if the module is imported in the App Engine environment or not. Catching ImportError on urllib2 might not be the best solution.</p>
| [
{
"answer_id": 335464,
"author": "chryss",
"author_id": 5169,
"author_profile": "https://Stackoverflow.com/users/5169",
"pm_score": 4,
"selected": false,
"text": ">>> import sys\n>>> 'unicodedata' in sys.modules\nFalse\n>>> import unicodedata\n>>> 'unicodedata' in sys.modules\nTrue\n"
},
{
"answer_id": 17221027,
"author": "Dave",
"author_id": 295163,
"author_profile": "https://Stackoverflow.com/users/295163",
"pm_score": 0,
"selected": false,
"text": "import os, logging\ntry:\n os.environ['APPENGINE_RUNTIME']\nexcept KeyError:\n logging.warn('We are not in App Engine environment')\nelse:\n logging.info('We are in the App Engine environment')\n os.environ env_variables:\n MY_APP_ENGINE_ENVIRONMENT: '982844ed9cbd6ce42318d2804386be29cbc7c35a'\n {'USER_EMAIL': '',\n 'DATACENTER': 'us1',\n 'wsgi.version': (1, 0),\n 'REQUEST_ID_HASH': 'E2C19D51',\n 'SERVER_NAME': 'mydesktop',\n 'QUERY_STRING': '',\n 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'APPENGINE_RUNTIME': 'python27',\n 'wsgi.input': <cStringIO.StringI object at 0x2f145d0>,\n 'SERVER_PROTOCOL': 'HTTP/1.1',\n 'HTTPS': 'off',\n 'USER_IS_ADMIN': '0',\n 'TZ': 'UTC',\n 'REMOTE_ADDR': '192.168.0.2',\n 'HTTP_X_APPENGINE_COUNTRY': 'ZZ',\n 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',\n 'SERVER_SOFTWARE': 'Development/2.0',\n 'HTTP_CACHE_CONTROL': 'max-age=0',\n 'DEFAULT_VERSION_HOSTNAME': 'mydesktop:8080',\n 'SERVER_PORT': '8080',\n 'wsgi.run_once': False,\n 'REQUEST_METHOD': 'GET',\n 'USER_ID': '',\n 'AUTH_DOMAIN': 'gmail.com',\n 'USER_NICKNAME': '',\n 'USER_ORGANIZATION': '',\n 'wsgi.multiprocess': True,\n 'INSTANCE_ID': '8a8e02e6efa8d195346ae0c90cfeafce8aa2',\n 'PATH_INFO': '/',\n 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',\n 'HTTP_HOST': 'mydesktop:8080',\n 'wsgi.errors': <google.appengine.api.logservice.logservice.LogsBuffer object at 0x2f09c30>,\n 'APPLICATION_ID': 'dev~myapp',\n 'wsgi.multithread': True,\n 'CURRENT_VERSION_ID': 'version-1',\n 'SCRIPT_NAME': '',\n 'REQUEST_LOG_ID': '4eafbc91ca4ebd5fee53f19eeab2eb26d243d9ddc92b6b9bc0a063eabdc84cfff',\n 'wsgi.url_scheme': 'http'}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
335,407 | <p>I have a web app with a web-based configuration UI. If the user accesses via HTTP, I want to alert the user that they should really use HTTPS and give them a link to click on to get to the HTTPS-prefixed URL.</p>
<p>Now, this is pretty straightforward if we're on the default ports, but often, we're not - for example, HTTP might be on 8080, with HTTPS on 8181. I can have some heuristics for figuring out which port to use, e.g. 80->443, 8080->8181, but is there any way to get a list of ports and protocols back from the web container? Ideally Java EE standard, but even container-specific would be a start...</p>
<p>EDIT - one clarification - this is for an 'off-the-shelf' application (<a href="http://opensso.org/" rel="nofollow noreferrer">OpenSSO</a>), so I'd really like to be able to (a) give the user the choice to go ahead and use an insecure port if they <em>really</em> want to (e.g. they're deploying on their laptop on some container without a secure port) and (b) not make the user edit server.xml.</p>
| [
{
"answer_id": 336016,
"author": "Loki",
"author_id": 39057,
"author_profile": "https://Stackoverflow.com/users/39057",
"pm_score": 1,
"selected": false,
"text": "<user-data-constraint>\n <transport-guarantee>\n CONFIDENTIAL\n </transport-guarantee>\n</user-data-constraint>\n redirectPort=\"YOUR_SSL_PORT\"\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33905/"
] |
335,408 | <p>I checked out a copy of a C++ application from SourceForge (HoboCopy, if you're curious) and tried to compile it.</p>
<p>Visual Studio tells me that it can't find a particular header file. I found the file in the source tree, but where do I need to put it, so that it will be found when compiling? </p>
<p>Are there special directories?</p>
| [
{
"answer_id": 52629808,
"author": "linrongbin",
"author_id": 4438921,
"author_profile": "https://Stackoverflow.com/users/4438921",
"pm_score": 5,
"selected": false,
"text": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.15.26726\\include C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.17134.0\\ucrt <iostream> <algorithm> <stdio.h> <string.h>"
},
{
"answer_id": 68992293,
"author": "Arpan Saini",
"author_id": 7353562,
"author_profile": "https://Stackoverflow.com/users/7353562",
"pm_score": 0,
"selected": false,
"text": "-header_files\n - util.h\n-source_files\n - util.c\n - main.c\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] |
335,409 | <p>I'm getting a syntax error (undefined line 1 test.js) in Firefox 3 when I run this code. The alert works properly (it displays 'work') but I have no idea why I am receiving the syntax error.</p>
<p>jQuery code:</p>
<pre><code>$.getJSON("json/test.js", function(data) {
alert(data[0].test);
});
</code></pre>
<p>test.js:</p>
<pre><code>[{"test": "work"}]
</code></pre>
<p>Any ideas? I'm working on this for a larger .js file but I've narrowed it down to this code. What's crazy is if I replace the local file with a remote path there is no syntax error (here's an example):</p>
<p><a href="http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?" rel="noreferrer">http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?</a></p>
| [
{
"answer_id": 624700,
"author": "vava",
"author_id": 6258,
"author_profile": "https://Stackoverflow.com/users/6258",
"pm_score": 0,
"selected": false,
"text": "; test.js eval(\"(\" + data + \")\") jsoncallback=? <script> \"json/test.js?callback=?\""
},
{
"answer_id": 633031,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "$.ajaxSetup({'beforeSend': function(xhr){\n if (xhr.overrideMimeType)\n xhr.overrideMimeType(\"text/plain\");\n }\n});\n $.ajaxSetup({ mimeType: \"text/plain\" });\n $.ajax({\n url: \"json/test.js\",\n dataType: \"json\",\n mimeType: \"textPlain\",\n success: function(data){\n alert(data[0].test);\n } });\n"
},
{
"answer_id": 2389616,
"author": "Pete Zicari",
"author_id": 839164,
"author_profile": "https://Stackoverflow.com/users/839164",
"pm_score": 2,
"selected": false,
"text": "[\"item0\",\"item1\",\"Item2\"] {\"result\":[[\"43001\",\"ALEXANDRIA\"],[\"43002\",\"AMLIN\"],[\"43003\",\"ASHLEY\"],[\"43004\",\"BLACKLICK\"],[\"43005\",\"BLADENSBURG\"],[\"43006\",\"BRINKHAVEN\"]]}\n <script>\n $.getJSON(\"temp_test_json.php\",\"\",\n function(data) {\n $.each(data.result, function(i, item) {\n alert(item[0]+ \" \" + i);\n if (i > 4 ) return false;\n });\n });\n</script>\n"
},
{
"answer_id": 32035391,
"author": "oliverpool",
"author_id": 3207406,
"author_profile": "https://Stackoverflow.com/users/3207406",
"pm_score": 0,
"selected": false,
"text": "overrideMimeType var r = new XMLHttpRequest();\nr.open(\"GET\", filepath, true);\nr.overrideMimeType(\"text/plain\");\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8320/"
] |
335,427 | <p>I've found what seems to be the C# equivalent of a <a href="http://thedailywtf.com/Articles/The_FOR-CASE_paradigm.aspx" rel="nofollow noreferrer">FOR-CASE</a> structure in a project I'm working on:</p>
<pre><code>foreach (string param in params.Split(';'))
{
string[] parts = param.Split('=');
string key = parts[0].Trim().ToLower();
string value = parts[1].Trim();
switch (key)
{
case "param1": this.param1 = value; break;
case "param2": this.param2 = value; break;
case "param3": this.param3 = value; break;
case "param4": this.param4 = value; break;
default: break;
}
}
</code></pre>
<p>(Variable names changed to protect the guilty.)</p>
<p>How would you implement this code?</p>
| [
{
"answer_id": 335463,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": 2,
"selected": false,
"text": "foreach (string param in params.Split(';'))\n{\n string[] parts = param.Split('=');\n string key = parts[0].Trim().ToLower();\n string value = parts[1].Trim();\n MyHashTable[key] = value;\n}\n"
},
{
"answer_id": 335617,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": false,
"text": "Type t = this.GetType();\nforeach (string param in params.Split(';'))\n{ \n string[] parts = param.Split('='); \n string key = parts[0].Trim().ToLower(); \n string value = parts[1].Trim(); \n\n t.GetProperty(key).SetValue(this, value, null);\n}\n"
},
{
"answer_id": 335633,
"author": "Andrew Cowenhoven",
"author_id": 12281,
"author_profile": "https://Stackoverflow.com/users/12281",
"pm_score": -1,
"selected": false,
"text": "string parms = \"param1=1;param2=2;param3=3\";\nstring[] parmArr = parms.Split(';'); \n\nstring parm1 = Regex.Replace(parmArr[0], \"param1=\", \"\");\nstring parm2 = Regex.Replace(parmArr[1], \"param2=\", \"\");\nstring parm3 = Regex.Replace(parmArr[2], \"param3=\", \"\");\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,448 | <p>I have written a console application that sets the size of the console and output buffer. My problem is that after the program ends I cannot resize my cmd.exe window the way I did before. After the program sets the size of the window it retains that size no matter what I do afterwards. </p>
| [
{
"answer_id": 335580,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 1,
"selected": false,
"text": "namespace CSharpTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n System.Console.WindowHeight = 50;\n System.Console.WindowWidth = 100;\n System.Console.BufferHeight = 6000;\n System.Console.BufferWidth = 100;\n }\n }\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
335,451 | <p>I want to run a standalone ruby script in which I need my RoR environment to be used. Specifically, I need my models extending ActionMailer and ActiveRecord. I also need to read the database configuration from my database.yml.
How do I go about it?</p>
| [
{
"answer_id": 335489,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 4,
"selected": true,
"text": "#!/usr/bin/ruby\n #!/path/to/your/rails/script/runner\n ./my_script -e production"
},
{
"answer_id": 336377,
"author": "salt.racer",
"author_id": 757,
"author_profile": "https://Stackoverflow.com/users/757",
"pm_score": 0,
"selected": false,
"text": "require \"#{ENV['RAILS_ROOT']}/config/environment.rb\"\n"
},
{
"answer_id": 337591,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 0,
"selected": false,
"text": " # lib/tasks/mystuff.rake\n desc 'do my stuff'\n task :my_stuff => [:environment] do\n # do my stuff\n end\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17494/"
] |
335,466 | <p>The HTTP/1.1 specification (<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noreferrer">RFC2616</a>) defines a number of status codes that can be returned by HTTP server to signal certain conditions. Some of those codes can be utilized by web applications (and frameworks). Which of those codes are the most useful in practice in both classic and asynchronous (XHR) responses, in what situations you use each of them? </p>
<p>Which codes should be avoided, eg. should applications mess with the 5xx code range at all? What are your conventions when returning HTTP codes in REST web services? Do you ever use redirects other than 302?</p>
| [
{
"answer_id": 335596,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "grep 'Status:'"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36656/"
] |
335,481 | <p>I have a form that has a public property</p>
<pre><code>public bool cancelSearch = false;
</code></pre>
<p>I also have a class which is sitting in my bll (business logic layer), in this class I have a method, and in this method I have a loop. I would like to know how can I get the method to recognise the form (this custom class and form1 are in the same namespace). </p>
<p>I have tried just Form1. but the intellisense doesn't recognise the property.
Also I tried to instantialize the form using Form f1 = winSearch.Form1.ActiveForm; but this too did not help</p>
<p>Any ideas?</p>
| [
{
"answer_id": 335501,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "public class YourClass\n{\n private Form1 youFormRef;\n\n public YourClass(Form1 youFormRef)\n {\n this.youFormRef = youFormRef;\n }\n public void ExecuteWithCancel()\n {\n //You while loop here\n //this.youFormRef.cancelSearch...\n }\n}\n public class YourClass\n{\n private Form1 youFormRef;\n\n public int FormRef\n {\n set\n {\n this.youFormRef = value;\n }\n\n get\n {\n return this.youFormRef;\n }\n }\n\n public void ExecuteWithCancel()\n {\n //You while loop here\n //this.youFormRef.cancelSearch\n }\n}\n"
},
{
"answer_id": 335502,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 3,
"selected": true,
"text": "public class MyBLClass\n{\n public void DoSomething(Form1 theForm)\n {\n //You can use theForm.cancelSearch to get the value\n }\n}\n MyBlClass myClassInstance = new MyBlClass;\nmyClassInstance.DoSomething(this);\n"
},
{
"answer_id": 335528,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 1,
"selected": false,
"text": "Application.Run(new Form1());\n Form1 myForm = new Form1();\nApplication.Run(myForm);\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
335,487 | <p>My emacs (on Windows) always launches with a set size, which is rather small, and if I resize it, it's not "remembered" at next start-up. </p>
<p>I've been playing with the following:</p>
<pre><code>(set-frame-position (selected-frame) 200 2) ; pixels x y from upper left
(set-frame-size (selected-frame) 110 58) ; rows and columns w h
</code></pre>
<p>which totally works when I execute it in the scratch buffer. I put it in my .emacs, and although now when I start the program, I can see the frame temporarily set to that size, by the time <code>*scratch*</code> loads, it resets back to the small default again. </p>
<p>Can anyone help me fix up the above code so that it "sticks" on start-up?</p>
| [
{
"answer_id": 335529,
"author": "Bill White",
"author_id": 202280,
"author_profile": "https://Stackoverflow.com/users/202280",
"pm_score": 6,
"selected": true,
"text": "~/.emacs (add-to-list 'default-frame-alist '(left . 0))\n(add-to-list 'default-frame-alist '(top . 0))\n(add-to-list 'default-frame-alist '(height . 50))\n(add-to-list 'default-frame-alist '(width . 155))\n"
},
{
"answer_id": 335561,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 1,
"selected": false,
"text": "HKCU\\Software\\GNU\\Emacs\\\n Emacs.Geometry REG_SZ \"245x74\"\n"
},
{
"answer_id": 589987,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "(setq initial-frame-alist '(\n (top . 40) (left . 10)\n (width . 128) (height . 68)\n )\n )\n"
},
{
"answer_id": 3515749,
"author": "Android Eve",
"author_id": 418055,
"author_profile": "https://Stackoverflow.com/users/418055",
"pm_score": 2,
"selected": false,
"text": " (setq default-frame-alist '((foreground-color . \"LightGray\")\n (background-color . \"Black\")\n (cursor-color . \"Medium Sea Green\")\n (width . 80)\n (height . 36)\n (menu-bar-lines . 1)\n (vertical-scroll-bars . right)))\n (setq initial-frame-alist\n (cons '(width . 96)\n (cons '(height . 72)\n (cons '(menu-bar-lines . 1)\n initial-frame-alist))))\n C:\\emacs-23.2\\bin\\runemacs.exe -geometry 96x72\n"
},
{
"answer_id": 4225868,
"author": "Eric O Lebigot",
"author_id": 42973,
"author_profile": "https://Stackoverflow.com/users/42973",
"pm_score": 2,
"selected": false,
"text": "Emacs.font: -*-fixed-*-*-*-*-8-*-*-*-*-*-*-*\nEmacs.pane.menubar.*.fontList: 8x16\nEmacs.menu*.fontList: -*-fixed-*-*-*-*-8-*-*-*-*-*-*-*\nEmacs.dialog*.fontList: -*-fixed-*-*-*-*-8-*-*-*-*-*-*-*\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38803/"
] |
335,516 | <p>I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm doing wrong here... Any input would be much appreciated.</p>
<p>EDIT: Actually, the way the code is now, the page doesn't even make the function call... so, no dialog comes up at all. I did have the onClick code as:</p>
<pre><code>onClick="confirm('Delete entry?')"
</code></pre>
<p>which did bring up a dialog, but was still going to the link on Cancel.</p>
<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script type="text/javascript">
function delete() {
return confirm('Delete entry?')
}
</script>
...
<tr>
<c:if test="${userIDRO}">
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}"/>" />
<img src="images/edit.GIF" ALT="Edit this skill." border="1"/></a>
</td>
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}&remove=1"/>" onClick="return delete()"/>
<img src="images/remove.GIF" ALT="Remove this skill." border="1"/></a>
</td>
</c:if>
</tr>
</code></pre>
<p></p>
| [
{
"answer_id": 335549,
"author": "Stepan Mazurov",
"author_id": 40786,
"author_profile": "https://Stackoverflow.com/users/40786",
"pm_score": 4,
"selected": false,
"text": "onclick=\"javascript:return confirm('Are you sure you want to delete this comment?')\"\n"
},
{
"answer_id": 335554,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 3,
"selected": false,
"text": "/> >"
},
{
"answer_id": 335565,
"author": "Luca Tettamanti",
"author_id": 42448,
"author_profile": "https://Stackoverflow.com/users/42448",
"pm_score": 8,
"selected": true,
"text": "<a href=\"whatever\" onclick=\"return confirm('are you sure?')\"><img ...></a>\n <script type=\"text/javascript\">\nfunction confirm_delete() {\n return confirm('are you sure?');\n}\n</script>\n...\n<a href=\"whatever\" onclick=\"return confirm_delete()\"><img ...></a>\n"
},
{
"answer_id": 607175,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "onclick=\"return confirm('Delete entry?')\"\n"
},
{
"answer_id": 14773889,
"author": "Gytis",
"author_id": 1360933,
"author_profile": "https://Stackoverflow.com/users/1360933",
"pm_score": 3,
"selected": false,
"text": " $('.deleteObject').click(function () {\n var url = this.href;\n var confirmText = \"Are you sure you want to delete this object?\";\n if(confirm(confirmText)) {\n $.ajax({\n type:\"POST\",\n url:url,\n success:function () {\n // Here goes something...\n },\n });\n }\n return false;\n});\n"
},
{
"answer_id": 21832909,
"author": "user3319721",
"author_id": 3319721,
"author_profile": "https://Stackoverflow.com/users/3319721",
"pm_score": 0,
"selected": false,
"text": "OnClientClick='return (confirm(\"Are you sure you want to delete this comment?\"));'\n"
},
{
"answer_id": 26429510,
"author": "esdebon",
"author_id": 832424,
"author_profile": "https://Stackoverflow.com/users/832424",
"pm_score": 2,
"selected": false,
"text": "<img src=\"images/delete.png\" onclick=\"return confirm_delete('Are you sure?')\"> \n\n\n\n<script type=\"text/javascript\">\nfunction confirm_delete(question) {\n\n if(confirm(question)){\n\n alert(\"Action to delete\");\n\n }else{\n return false; \n }\n\n}\n</script>\n"
},
{
"answer_id": 26675624,
"author": "aki",
"author_id": 925058,
"author_profile": "https://Stackoverflow.com/users/925058",
"pm_score": 2,
"selected": false,
"text": "<button id=\"\" class=\"delete\" onclick=\"javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}\" type=\"button\">\n Delete\n</button>"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22371/"
] |
335,517 | <p>Does anyone know a good .NET dictionary API? I'm not interested in meanings, rather I need to be able to query words in a number of different ways - return words of x length, return partial matches and so on...</p>
| [
{
"answer_id": 335563,
"author": "James Orr",
"author_id": 41457,
"author_profile": "https://Stackoverflow.com/users/41457",
"pm_score": 5,
"selected": true,
"text": "List<string> words = System.IO.File.ReadAllText(\"MyWords.txt\").Split(new string[]{Environment.NewLine}).ToList();\n\n// C# 3.0 (LINQ) example:\n\n // get all words of length 5:\n from word in words where word.length==5 select word\n\n // get partial matches on \"foo\"\n from word in words where word.Contains(\"foo\") select word\n\n// C# 2.0 example:\n\n // get all words of length 5:\n words.FindAll(delegate(string s) { return s.Length == 5; });\n\n // get partial matches on \"foo\"\n words.FindAll(delegate(string s) { return s.Contains(\"foo\"); });\n"
},
{
"answer_id": 337251,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 2,
"selected": false,
"text": "List(T).FindAll(Predicate(T)) : List(T)\n List(String) words = LoadFromDictionary();\nList(String) fiveLetterWords = words.FindAll(delegate(String word)\n {\n return word.Length == 5;\n });\n List(String) words = LoadFromDictionary();\nList(String) abcWords = words.FindAll(delegate(String word)\n {\n return word.StartsWith('abc');\n });\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27805/"
] |
335,524 | <p>I have an SQL Server 2005 server, and I'd like to run a .Net CLR stored procedure on it. However, I'd like to use .NET Framework 3.5.</p>
<p>If I try this right now, I get this error:</p>
<pre><code>Error: Assembly 'system.core, version=3.5.0.0, culture=neutral, publickeytoken=b77a5c561934e089.' was not found in the SQL catalog.
</code></pre>
<p>I'm told this is possible in SQL Server 2008, because SQL Server 2008 ships with .NET Framework 3.5. However, I'm wondering if there's a way to add .NET Framework 3.5 to my SQL Server 2005 installation, so that I can run .NET 3.5 stored procedures on it.</p>
| [
{
"answer_id": 1324006,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 2,
"selected": false,
"text": "EXEC dbo.sp_changedbowner @loginame = N'sa', @map = true\nGO\nsp_configure 'clr enabled', 1\nGO\nRECONFIGURE\nGO\nALTER DATABASE [MyDB] SET TRUSTWORTHY ON\nGO\nCREATE ASSEMBLY [System.Core]\nAUTHORIZATION [dbo]\nFROM \n'C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\v3.5\\System.Core.dll'\nWITH PERMISSION_SET = UNSAFE\nGO\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2273/"
] |
335,526 | <p>I have a DBGrid on a form. The DBGrid has many columns, so an horizontal scroller is displayed. I scroll the DBGrid view to the right to see more columns. If I select a row, the DBGrid view is automatically reset to view the first column (As if I scroll back to the left most position). </p>
<p>Is there a way to prevent that?</p>
| [
{
"answer_id": 335997,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 2,
"selected": false,
"text": "GetScrollInfo(Self.Handle, SB_VERT, SIOld);\n SetScrollInfo( ) SelectedField"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6636/"
] |
335,530 | <p>How do you check that monkey patching has been done to a specific class in Ruby? If that is possible, is it also possible to get the previous implementation(s) of the attribute that's been patched?</p>
| [
{
"answer_id": 335787,
"author": "user37011",
"author_id": 37011,
"author_profile": "https://Stackoverflow.com/users/37011",
"pm_score": 3,
"selected": false,
"text": "method_added method_undefined"
},
{
"answer_id": 336308,
"author": "readonly",
"author_id": 4883,
"author_profile": "https://Stackoverflow.com/users/4883",
"pm_score": 3,
"selected": true,
"text": "#!/usr/bin/env ruby \n\nclass Class\n @@method_history = {}\n\n def self.method_history\n return @@method_history\n end\n\n def method_added(method_name)\n puts \"#{method_name} added to #{self}\"\n @@method_history[self] ||= {}\n @@method_history[self][method_name] = caller\n end\n\n def method_defined_in(method_name)\n return @@method_history[self][method_name]\n end\nend\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
335,531 | <p>I am building a conditional navigation menu that has 3 levels (the 3rd level added today by business, no worries its not like I launch next week. Oh wait I do:)). I have a javascript var that contains the html for my first conditional level. I am now trying to insert another level inside of the first. </p>
<pre><code>var myVar = '<ul class="linksUnit">';
var myVar += '<li>Link 1</li>';
var myVar += if (myVar2 != false) {document.write("Link 2")};
var myVar += '</ul>';
</code></pre>
<p>Any help would be greatly appreciated.</p>
<p>Thanks</p>
| [
{
"answer_id": 335542,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "var myVar = '<ul class=\"linksUnit\">';\nmyVar += '<li>Link 1';\nif (myVar2) { // note != false means true\n // insert a nested unordered list\n myVar += '<ul>';\n myVar += '<li>Link 2</li>';\n myVar += '</ul>';\n}\nmyVar += '</li>'; \nmyVar += '</ul>';\n var W3C DOM document.createElement"
},
{
"answer_id": 335547,
"author": "Thom",
"author_id": 24618,
"author_profile": "https://Stackoverflow.com/users/24618",
"pm_score": 3,
"selected": false,
"text": "var myVar += (myVar2 != false ? \"Link 2\" : \"\");"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27516/"
] |
335,540 | <p>I need to optimize code to get room for some new code. I do not have the space for all the changes. I can not use code bank switching (80c31 with 64k). </p>
| [
{
"answer_id": 335593,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "CALL otherfunc\nRET\n JMP otherfunc\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34531/"
] |
335,546 | <p>Is there a way to have two columns, that match each other in height, without using table cells, fixed heights or Javascript?</p>
<p><strong>Using a TABLE</strong></p>
<pre><code><table>
<tr>
<td style="background:#F00;">
This is a column
</td>
<td style="background:#FF0;">
This is a column<br />
That isn't the same<br />
height at the other<br />
yet the background<br />
still works
</td>
</tr>
</table>
</code></pre>
<p><strong>Using DIVs</strong></p>
<pre><code><div style="float:left;background:#F00" >
This is a column
</div>
<div style="float:left;background:#FF0" >
This is a column<br />
That isn't the same<br />
height at the other<br />
yet the background<br />
still works
</div>
<div style="clear:both;" ></div>
</code></pre>
<p>The goal is to make both backgrounds extend the full height regardless of which side is taller.</p>
<p>Nesting one in the other wouldn't work because it doesn't guarantee both side are the correct height.</p>
<p><strong>Unfortunately, the preview showed the working HTML, but the actual post stripped it out. You should be able to paste this into an HTML file and see what I mean.</strong></p>
| [
{
"answer_id": 335603,
"author": "asleep",
"author_id": 29445,
"author_profile": "https://Stackoverflow.com/users/29445",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n <style>\n html, body\n {\n margin: 0;\n padding: 0;\n height: 100%; /* needed for container min-height */\n }\n #container\n {\n background-color: #333333;\n width: 500px;\n height: auto !important; /* real browsers */\n height: 100%; /* IE6: treaded as min-height*/\n min-height: 100%; /* real browsers */\n }\n #colOne, #colTwo\n {\n width: 250px;\n float: left;\n height: auto !important; /* real browsers */\n height: 100%; /* IE6: treaded as min-height*/\n min-height: 100%; /* real browsers */\n }\n #colOne\n {\n background-color: #cccccc;\n }\n #colTwo\n {\n background-color: #f4f5f3;\n }\n </style>\n</head>\n<body>\n <div id=\"container\">\n <div id=\"colOne\">\n this is something</div>\n <div id=\"colTwo\">\n this is also something</div>\n <div style=\"clear: both;\">\n </div>\n </div>\n</body>\n</html>\n"
},
{
"answer_id": 335822,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": -1,
"selected": false,
"text": "<div id=\"container\">\n <div id=\"col1\">\n this is column 1\n </div>\n <div id=\"col2\">\n this is column 2<br />\n it is obviously longer than the first column <br />\n YEP!\n </div>\n</div>\n #container { background:#f0f; overflow:hidden; width:400px; }\n#col1, #col2 { float:left; width:50%; }\n#col2 { background:#ff0; }\n"
},
{
"answer_id": 335867,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "display:inline-block\n <div><span>\n col1\n</span></div>\n<div><span>\n col2\n</span></div>\n\ndiv {display:inline;}\nspan {display:inline-block;}\n"
},
{
"answer_id": 1046984,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 2,
"selected": false,
"text": "<div class=\"contentSidebarPair\">\n <div class=\"sidebar\"></div>\n <div class=\"content\"></div>\n</div>\n /* sidebar.gif is simply a 200x1px image with the bgcolor of your sidebar.\n #FFF is the bgcolor of your content */\ndiv.contentSidebarPair {\n background: #FFF url('sidebar.gif') repeat-y top left;\n width: 800px;\n margin: 0 auto; /* center */\n zoom: 1; /* For IE */\n}\n\n/* IE6 will not parse this but it doesn't need to */\ndiv.contentSidebarPair:after {\n content: \".\";\n display: block;\n height: 0;\n clear: both;\n visibility: hidden;\n}\n\ndiv.sidebar {\n float: left;\n width: 200px;\n}\n\ndiv.content {\n float: left;\n width: 600px;\n}\n"
},
{
"answer_id": 6651673,
"author": "robertc",
"author_id": 8655,
"author_profile": "https://Stackoverflow.com/users/8655",
"pm_score": 0,
"selected": false,
"text": "<div>\n This is a column\n</div>\n<div>\n This is a column<br />\n That isn't the same<br />\n height at the other<br />\n yet the background<br />\n still works\n</div>\n div { display: table-cell; }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17091/"
] |
335,558 | <p>I need a way to determine from Wise Install Script if SQL Server Management Studio Express 2005 is installed on computer. Does someone know a Registry entry or something that will be present when SSMSE is installed?</p>
| [
{
"answer_id": 336393,
"author": "Sachin Gaur",
"author_id": 2572740,
"author_profile": "https://Stackoverflow.com/users/2572740",
"pm_score": -1,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\Software\\MSSQLServer\\MSSQLServer\\CurrentVersion\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5904/"
] |
335,585 | <p>How can I access a site configured in IIS 7 on the host machine from a guest OS in VMWare (Fedora 10). I have configured the VM to use "NAT"</p>
| [
{
"answer_id": 335623,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "# /sbin/route\nDestination Gateway Genmask Flags Metric Ref Use Iface\n\ndefault 10.x.y.z 0.0.0.0 UG 0 0 0 eth0\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1443363/"
] |
335,597 | <p>I have a many-to-one relationship where the child table can have hundreds of thousands of records. In this case, calling Parent.ChildCollection.Count forces a lazy initialization of the child collection which is extremely expensive.</p>
<p>In Hibernate 3.0 there is a feature lazy="extra" which allows you to check a subset of collection properties without lazy loading the whole thing.</p>
<p>Unfortunately this will not be available until NHibernate 2.1, which is still in Alpha.
<a href="http://jira.nhibernate.org/browse/NH-855" rel="noreferrer">http://jira.nhibernate.org/browse/NH-855</a></p>
<p>How can I accomplish this with NHibernate 2.0.1?</p>
<p>I used to have special properties such as this</p>
<pre><code><property name="ChildCollectionCount" type="int" formula="(select count(*) from ChildTable child where child.parentID = parentID "/>
</code></pre>
<p>but I can't use these anymore because I am now sharing this library and its a performance problem for other users.</p>
| [
{
"answer_id": 335623,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "# /sbin/route\nDestination Gateway Genmask Flags Metric Ref Use Iface\n\ndefault 10.x.y.z 0.0.0.0 UG 0 0 0 eth0\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30957/"
] |
335,598 | <p>I'm experiencing this weird problem which my scrollbar jumps by itself to somewhere that I don't want it to. </p>
<p>I have a table with scrollbar inside this page, if the user have a smaller screen, the page automatically adds a scrollbar. If I scroll down to the bottom of the table and click on it, the scrollbar of the page jumps up so I can no longer see the thing I clicked. Any ideas?</p>
<p>Thanks.</p>
| [
{
"answer_id": 335615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": ":focus :active"
},
{
"answer_id": 681178,
"author": "mike nvck",
"author_id": 36531,
"author_profile": "https://Stackoverflow.com/users/36531",
"pm_score": 0,
"selected": false,
"text": "<a href='#'><div onclick='yourJavaScriptFunction()'>...</div></a>"
},
{
"answer_id": 681184,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 0,
"selected": false,
"text": "<meta http-equiv=\"refresh\" content=\"600\">\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34797/"
] |
335,600 | <p>I have two characters displayed in a game I am writing, the player and the enemy. defined as such:</p>
<pre><code>public void player(Graphics g) {
g.drawImage(plimg, x, y, this);
}
public void enemy(Graphics g) {
g.drawImage(enemy, 200, 200, this);
}
</code></pre>
<p>Then called with:</p>
<pre><code>player(g);
enemy(g);
</code></pre>
<p>I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?</p>
| [
{
"answer_id": 335632,
"author": "asleep",
"author_id": 29445,
"author_profile": "https://Stackoverflow.com/users/29445",
"pm_score": 1,
"selected": false,
"text": "Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height);\n\nRectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height);\n\n//detects when the two rectangles hit\nif(rect1.intersects(rect2))\n{\n\nSystem.out.println(\"game over, g\");\n}\n"
},
{
"answer_id": 335758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " if( Player.BoundingBox.X = Enemy.BoundingBox.X && If( Player.BoundingBox.Y = Enemy.BoundingBox.Y )\n {\n //Oh noes! The enemy and player are on top of eachother.\n }\n"
},
{
"answer_id": 335830,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "public class Player\n{\n int X;\n int Y;\n int Width;\n int Height;\n\n // Getters and Setters\n}\n\npublic class Enemy\n{\n int X;\n int Y;\n int Width;\n int Height;\n\n // Getters and Setters\n}\n foreach (Enemy e in EnemyCollection)\n{\n Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);\n Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);\n\n // Assuming there is an intersect method, otherwise just handcompare the values\n if (r.Intersects(p))\n {\n // A Collision!\n // we know which enemy (e), so we can call e.DoCollision();\n e.DoCollision();\n }\n}\n"
},
{
"answer_id": 336615,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 3,
"selected": false,
"text": "Image.getRGB() playerArray enemyArray height width <= 32 (width+31)/32*height width <= 32 // Find the first line where the two sprites might overlap\nint linePlayer, lineEnemy;\nif (player.y <= enemy.y) {\n linePlayer = enemy.y - player.y;\n lineEnemy = 0;\n} else {\n linePlayer = 0;\n lineEnemy = player.y - enemy.y;\n}\nint line = Math.max(linePlayer, lineEnemy);\n\n// Get the shift between the two\nx = player.x - enemy.x;\nint maxLines = Math.max(player.height, enemy.height);\nfor ( line < maxLines; line ++) {\n // if width > 32, then you need a second loop here\n long playerMask = playerArray[linePlayer];\n long enemyMask = enemyArray[lineEnemy];\n // Reproduce the shift between the two sprites\n if (x < 0) playerMask << (-x);\n else enemyMask << x;\n // If the two masks have common bits, binary AND will return != 0\n if ((playerMask & enemyMask) != 0) {\n // Contact!\n }\n\n}\n"
},
{
"answer_id": 6209407,
"author": "tyler",
"author_id": 780376,
"author_profile": "https://Stackoverflow.com/users/780376",
"pm_score": 2,
"selected": false,
"text": "/**\n *\n * @author Tyler Griffin\n */\nimport java.awt.*;\nimport javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.GraphicsDevice.*;\nimport java.util.ArrayList;\nimport java.awt.Graphics;\nimport java.awt.geom.Line2D;\n\n\npublic class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener\n{\n ArrayList everything=new ArrayList<tile>();\n\n int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;\n int mouseX, mouseY;\n\n GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();\n GraphicsDevice screen = environment.getDefaultScreenDevice();\n DisplayMode displayMode = screen.getDisplayMode();\n\n //private BufferStrategy strategy;\n\n JLayeredPane pane = new JLayeredPane();\n\n tile Tile;\n circle Circle;\n rectangle Rectangle;\n\n textPane text;\n\n public collision()\n {\n setUndecorated(screen.isFullScreenSupported());\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setVisible(true);\n setLayout(null);\n setResizable(false);\n screen.setFullScreenWindow(this);\n\n\n width=displayMode.getWidth();\n height=displayMode.getHeight();\n\n\n Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);\n Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);\n Tile=Circle;\n Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);\n text=new textPane(0,0,width,height,this);\n\n everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));\n everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));\n //everything.add(new line(750,250,750,750,this));\n /*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));\n everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));\n everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));\n everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));\n everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));\n everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));\n everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));\n everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));\n everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));\n everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));\n\n everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));\n everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));\n everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));\n everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));\n everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/\n\n everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));\n everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));\n everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));\n everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));\n everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));\n\n\n addKeyListener(this);\n addMouseMotionListener(this);\n addMouseListener(this);\n }\n\n public void keyReleased(KeyEvent e)\n {\n Object source=e.getSource();\n\n int released=e.getKeyCode();\n\n if (released==KeyEvent.VK_A){left=0;}\n if (released==KeyEvent.VK_W){up=0;}\n if (released==KeyEvent.VK_D){right=0;}\n if (released==KeyEvent.VK_S){down=0;}\n }//end keyReleased\n\n\n public void keyPressed(KeyEvent e)\n {\n Object source=e.getSource();\n\n int pressed=e.getKeyCode();\n\n if (pressed==KeyEvent.VK_A){left=1;}\n if (pressed==KeyEvent.VK_W){up=1;}\n if (pressed==KeyEvent.VK_D){right=1;}\n if (pressed==KeyEvent.VK_S){down=1;}\n\n if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)\n {\n //if (paused==0){paused=1;}\n //else paused=0;\n }\n }//end keyPressed\n\n public void keyTyped(KeyEvent e){}\n\n//***********************************************************************************************\n\n public void mouseDragged(MouseEvent e)\n {\n mouseX=(e.getX());\n mouseY=(e.getY());\n\n //run();\n }\n\n public void mouseMoved(MouseEvent e)\n {\n mouseX=(e.getX());\n mouseY=(e.getY());\n\n //run();\n }\n\n//***********************************************************************************************\n\n public void mousePressed(MouseEvent e)\n {\n if(e.getX()==0 && e.getY()==0){System.exit(0);}\n\n mouseX=(e.getX()+x);\n mouseY=(e.getY()+y);\n\n if(Tile instanceof circle)\n {\n Circle.move(0-Circle.width, 0-Circle.height);\n Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);\n Tile=Rectangle;\n }\n else\n {\n Rectangle.move(0-Rectangle.width, 0-Rectangle.height);\n Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);\n Tile=Circle;\n }\n\n Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);\n }\n\n public void mouseReleased(MouseEvent e)\n {\n //run();\n }\n\n public void mouseEntered(MouseEvent e){}\n public void mouseExited(MouseEvent e){}\n\n public void mouseClicked(MouseEvent e){}\n\n//***********************************************************************************************\n\n public void run()//run collision detection\n {\n while (this == this)\n {\n Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));\n //Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));\n\n for (int i = 0; i < everything.size(); i++)\n {\n tile Temp = (tile) everything.get(i);\n\n if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided\n {\n if (Temp instanceof rectangle)\n {\n if (Tile instanceof rectangle){rectangleRectangle(Temp);}\n else {circleRectangle(Temp);}//Tile instanceof circle\n }\n else\n {\n if (Temp instanceof circle)\n {\n if (Tile instanceof rectangle) {rectangleCircle(Temp);}\n else {circleCircle(Temp);}\n }\n else//line\n {\n if (Tile instanceof rectangle){rectangleLine(Temp);}\n else{circleLine(Temp);}\n }\n }\n }//end if\n }//end for\n\n try {Thread.sleep(16L);}\n catch (Exception e) {}\n\n Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);\n //Rectangle.setBounds(x, y, width, height);\n //Circle.setBounds(x, y, width, height);\n repaint();\n\n text.out=\" \";\n }//end while loop\n }//end run\n\n//***************************************special collision detection/handling functions************************************************\n\n void rectangleRectangle(tile Temp)\n {\n int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;\n\n lapTop=(Temp.y+Temp.height)-Tile.y;\n lapBot=(Tile.y+Tile.height)-Temp.y;\n lapLeft=(Temp.x+Temp.width)-Tile.x;\n lapRight=(Tile.x+Tile.width)-Temp.x;\n\n small=999999999;\n\n if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}\n if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}\n if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}\n if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}\n\n Tile.move(Tile.x+scootX, Tile.y+scootY);text.out=\"collision detected!\";\n }\n\n\n\n void circleRectangle(tile Temp)\n {\n if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))\n {\n rectangleRectangle(Temp);\n }\n else//push from nearest corner\n {\n int x,y;\n if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}\n else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}\n else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}\n else {x=Temp.x; y=Temp.y+Temp.height;}\n\n double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));\n\n if((int)Math.round(distance)<Tile.height/2)\n {\n double normY = ((Tile.y+(Tile.height/2) - y) / distance);\n double normX = ((Tile.x+(Tile.width/2) - x) / distance);\n\n Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out=\"collision detected!\";\n }\n }\n }\n\n\n\n void rectangleCircle(tile Temp)\n {\n if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))\n {\n rectangleRectangle(Temp);\n }\n else//push from nearest corner\n {\n int x,y;\n if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}\n else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}\n else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}\n else {x=Tile.x; y=Tile.y+Tile.height;}\n\n double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));\n\n if((int)Math.round(distance)<Temp.height/2)\n {\n double normY = ((Temp.y+(Temp.height/2) - y) / distance);\n double normX = ((Temp.x+(Temp.width/2) - x) / distance);\n\n if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out=\"collision detected!\";}\n else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out=\"collision detected!\";}\n else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out=\"collision detected!\";}\n else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out=\"collision detected!\";}\n }\n }\n }\n\n\n\n\n void circleCircle(tile Temp)\n {\n double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));\n\n if((int)distance<(Tile.width/2+Temp.width/2))\n {\n double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;\n double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;\n\n Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out=\"collision detected!\";\n }\n }\n\n\n\n void circleLine(tile Temp)\n {\n line Line=(line)Temp;\n\n if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points\n {\n rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);\n circleRectangle(rec);\n remove(rec);\n }\n\n if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points\n {\n rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);\n circleRectangle(rec);\n remove(rec);\n }\n\n\n int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);\n\n x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);\n x2=Tile.x+(Tile.width/2)+Line.height;\n if(Line.posSlope)\n {\n y1=Tile.y+(Tile.height/2)-Line.width;\n y2=Tile.y+(Tile.height/2)+Line.width;\n }\n else\n {\n y1=Tile.y+(Tile.height/2)+Line.width;\n y2=Tile.y+(Tile.height/2)-Line.width;\n }\n\n Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection\n\n if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment\n {\n //if(point!=null){System.out.println(point.x+\",\"+point.y);}\n double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));\n\n if((int)distance<Tile.width/2)\n {\n //System.out.println(\"hit\");\n double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;\n double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;\n\n Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out=\"collision detected!\";\n //System.out.println(point.x+\",\"+point.y);\n }\n }\n\n //new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));\n }\n\n void rectangleLine(tile Temp)\n {\n line Line=(line)Temp;\n if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))\n {\n if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points\n {\n rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);\n rectangleRectangle(rec);\n remove(rec);\n }\n\n if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points\n {\n rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);\n rectangleRectangle(rec);\n remove(rec);\n }\n\n if(Line.posSlope)//positive sloped line\n {\n //first we'll do the top left corner\n int x1=Tile.x-Line.height;\n int x2=Tile.x+Line.height;\n int y1=Tile.y-Line.width;\n int y2=Tile.y+Line.width;\n Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);\n double topDistance=0, botDistance=0;\n\n topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection\n\n topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));\n\n //new let's do the bottom right corner\n x1=Tile.x+Tile.width-Line.height;\n x2=Tile.x+Tile.width+Line.height;\n y1=Tile.y+Tile.height-Line.width;\n y2=Tile.y+Tile.height+Line.width;\n\n botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection\n\n botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));\n\n\n if(topDistance<botDistance)\n {\n if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))\n {\n Tile.move(topPoint.x,topPoint.y);text.out=\"collision detected!\";\n }\n }\n else\n {\n if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))\n {\n Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out=\"collision detected!\";\n }\n }\n }\n else//negative sloped lne\n {\n //first we'll do the top right corner\n int x1=Tile.x+Tile.width-Line.height;\n int x2=Tile.x+Tile.width+Line.height;\n int y1=Tile.y+Line.width;\n int y2=Tile.y-Line.width;\n Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);\n double topDistance=0, botDistance=0;\n\n topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection\n\n topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));\n\n //new let's do the bottom left corner\n x1=Tile.x-Line.height;\n x2=Tile.x+Line.height;\n y1=Tile.y+Tile.height+Line.width;\n y2=Tile.y+Tile.height-Line.width;\n\n botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection\n\n botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));\n\n\n if(topDistance<botDistance)\n {\n if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))\n {\n Tile.move(topPoint.x-Tile.width,topPoint.y);text.out=\"collision detected!\";\n }\n }\n else\n {\n if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))\n {\n Tile.move(botPoint.x,botPoint.y-Tile.height);text.out=\"collision detected!\";\n }\n }\n }\n }\n }\n\n public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)\n {\n double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);\n\n double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;\n double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;\n\n int x=(int)Math.round(xi);\n int y=(int)Math.round(yi);\n\n return new Point(x, y);\n }\n\n//***************************************************************************************\n\n public static void main(String[] args)\n {\n final collision Collision=new collision();\n Collision.run();\n }//end main\n}//end class\n"
},
{
"answer_id": 26587175,
"author": "johnny",
"author_id": 2715575,
"author_profile": "https://Stackoverflow.com/users/2715575",
"pm_score": 2,
"selected": false,
"text": "Rectangle box1 = new Rectangle(100,100,100,100);\nRectangle box2 = new Rectangle(200,200,100,100);\n\n// what this means is if any pixel in box2 enters (hits) box1\nif (box1.contains(box2)) \n{\n // collision occurred\n}\n\n// your code for moving the boxes \n Ellipse2D.Double ball1 = new Ellipse2D.Double(100,100,200,200);\nEllipse2D.Double ball2 = new Ellipse2D.Double(400,100,200,200);\n\n// what this means is if any pixel on the circumference in ball2 touches (hits)\n// ball1\n if (ball1.contains(ball2)) \n {\n // collision occurred\n }\n\n // your code for moving the balls\n Rectangle screenBounds = jpanel.getBounds();\nEllipse2D.Double ball = new Ellipse2D.Double(100,100,200,200); // diameter 200\nRectangle ballBounds = ball.getBounds();\n\nif (!screenBounds.contains(ballBounds))\n{\n// the ball touched the edge of the screen\n}\n"
},
{
"answer_id": 47510806,
"author": "Yashwanth Dornala",
"author_id": 8832800,
"author_profile": "https://Stackoverflow.com/users/8832800",
"pm_score": 1,
"selected": false,
"text": "if(x1===x&&y1==y) if (x1>x&&x2>x+30)"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3609/"
] |
335,601 | <p>I have added uc in contentplace holder of master page but how do you instantiate the user control in master page .cs file to make it visible when the master page loads</p>
| [
{
"answer_id": 336030,
"author": "Pat Hermens",
"author_id": 1677,
"author_profile": "https://Stackoverflow.com/users/1677",
"pm_score": 0,
"selected": false,
"text": "<%@ Reference Control=\"~/path/to/my/customControl.ascx\" %>\n Dim customControl As ASP.customcontrol_ascx = Master.FindControl(\"customControl\")\nIf customControl IsNot Nothing Then\n ...\nEnd If\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21918/"
] |
335,607 | <p>I have a server with two different network interfaces, each with a different IP address. How can I create a socket so it'll go out a specific IP address?</p>
<p>I'd prefer a python example, but the question is language agnostic, so shoot away.</p>
<p>EDIT: Please don't give me "You can't" as an answer. I mean, it is a computer. I can do anything I like to it, for example - I can programatically disable the one interface I don't want on the fly. I'm looking for something prettier.</p>
| [
{
"answer_id": 335662,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 5,
"selected": true,
"text": "setsockopt() SO_BINDTODEVICE struct ifreq ioctl() SIOCGIFINDEX setsockopt()"
},
{
"answer_id": 665588,
"author": "Mikle",
"author_id": 23942,
"author_profile": "https://Stackoverflow.com/users/23942",
"pm_score": 4,
"selected": false,
"text": "import socket\ns = socket.socket()\ns.bind((\"127.0.0.1\", 0))\ns.connect((\"321.12.131.432\", 80))\n"
},
{
"answer_id": 31946437,
"author": "mikad0",
"author_id": 5215880,
"author_profile": "https://Stackoverflow.com/users/5215880",
"pm_score": 1,
"selected": false,
"text": "import socket\ns = socket.socket()\ns.bind((get_ip_address('eth0'), 0))\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23942/"
] |
335,621 | <p>I have a class that after it does some stuff, sends a JMS message.
I'd like to unit test the "stuff", but not necessarily the sending of the message.
<br><br>When I run my test, the "stuff" green bars, but then fails when sending the message (it should, the app server is not running).
What is the best way to do this, is it to mock the message queue, if so, how is that done. <br><br>
I am using Spring, and "jmsTemplate" is injected, along with "queue".</p>
| [
{
"answer_id": 335644,
"author": "tunaranch",
"author_id": 27708,
"author_profile": "https://Stackoverflow.com/users/27708",
"pm_score": 3,
"selected": false,
"text": "JmsTemplate mockTemplate = createMock(JmsTemplate.class)\n"
},
{
"answer_id": 335647,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 4,
"selected": true,
"text": "public class SomeClass {\n public void doit() {\n //do some stuff\n sendMessage( /*some parameters*/);\n }\n\n public void sendMessage( /*some parameters*/ ) { \n //jms stuff\n }\n}\n @Test\npublic void testRealWorkWithoutSendingMessage() {\n SomeClass thing = new SomeClass() {\n @Override\n public void sendMessage( /*some parameters*/ ) { /*do nothing*/ }\n }\n\n thing.doit();\n assertThat( \"Good stuff happened\", x, is( y ) );\n}\n"
},
{
"answer_id": 4315431,
"author": "Ichthyo",
"author_id": 444796,
"author_profile": "https://Stackoverflow.com/users/444796",
"pm_score": 1,
"selected": false,
"text": "<bean id=\"TheMegaContext\"\n class=\"org.springframework.context.support.ClassPathXmlApplicationContext\">\n <constructor-arg>\n <list>\n <value>BasicServices.xml</value>\n <value>DataAccessBeans.xml</value>\n <value>LoginBeans.xml</value>\n <value>BussinessServices.xml</value>\n ....\n </list>\n </constructor-arg>\n</bean>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143/"
] |
335,624 | <p>Any idea how to <strong>return multiple variables</strong> from a function in ActionScript 3? </p>
<p>Anything like VB.NET where you can have the <strong>input argument's variable</strong> modified (ByRef arguments)?</p>
<pre><code>Sub do (ByRef inout As Integer)
inout *= 5;
End Sub
Dim num As Integer = 10
Debug.WriteLine (num) '10
do (num)
Debug.WriteLine (num) '50
</code></pre>
<hr>
<p>Anything <strong>apart from</strong> returning an <strong>associative array</strong>?</p>
<pre><code>return {a:"string 1", b:"string 2"}
</code></pre>
| [
{
"answer_id": 335693,
"author": "LiraNuna",
"author_id": 41983,
"author_profile": "https://Stackoverflow.com/users/41983",
"pm_score": 3,
"selected": true,
"text": "Object Array String"
},
{
"answer_id": 336690,
"author": "Robin Rodricks",
"author_id": 41021,
"author_profile": "https://Stackoverflow.com/users/41021",
"pm_score": 3,
"selected": false,
"text": "function func(a:String){\n a=\"newVal\";\n}\n\nvar b:String = \"old\";\n\ntrace(b) // old\nfunc(b);\ntrace(b) // old\n"
},
{
"answer_id": 684981,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "function Test(a:Object, b:Object):void {\n a = b;\n}\n\nfunction Test2():void {\n var s1:Sprite = null;\n var s2:Sprite = new Sprite;\n\n Test(s1,s2);\n Trace(s1);\n Trace(s2);\n}\n null\n[object Sprite]\n"
},
{
"answer_id": 1529852,
"author": "timoxley",
"author_id": 62851,
"author_profile": "https://Stackoverflow.com/users/62851",
"pm_score": 0,
"selected": false,
"text": "function passByRef(objParam:Object):void \n{ \n objParam.x++; \n objParam.y++; \n trace(objParam.x, objParam.y); \n} \nvar objVar:Object = {x:10, y:15}; \ntrace(objVar.x, objVar.y); // 10 15 \npassByRef(objVar); // 11 16 \ntrace(objVar.x, objVar.y); // 11 16\n"
},
{
"answer_id": 3232754,
"author": "Tim Speed",
"author_id": 389922,
"author_profile": "https://Stackoverflow.com/users/389922",
"pm_score": 2,
"selected": false,
"text": "function Test(a:Object, b:Object):void {\n a = b;\n}\n var s1:Sprite = null;\nvar s2:Sprite = new Sprite;\nTest(s1,s2);\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
] |
335,659 | <p>For example, how can I run me.test below?</p>
<pre><code>myvar = 'test'
me.myvar
</code></pre>
<p>ASP looks for the method "myvar" and doesn't find it. In PHP I could simply say $me->$myvar but ASP's syntax doesn't distinguish between variables and methods. Suggestions?</p>
<p>Closely related to this, is there a method_exists function in ASP Classic?</p>
<p>Thanks in advance!</p>
<p><strong>EDIT:</strong> I'm writing a validation class and would like to call a list of methods via a pipe delimited string. </p>
<p>So for example, to validate a name field, I'd call:</p>
<pre><code>validate("required|min_length(3)|max_length(100)|alphanumeric")
</code></pre>
<p>I like the idea of having a single line that shows all the ways a given field is being validated. And each pipe delimited section of the string is the name of a method.</p>
<p>If you have suggestions for a better setup, I'm all ears!</p>
| [
{
"answer_id": 335675,
"author": "John MacIntyre",
"author_id": 29043,
"author_profile": "https://Stackoverflow.com/users/29043",
"pm_score": 2,
"selected": false,
"text": "Select myvar\n case \"test\":\n test\n\n case \"anotherSub\":\n anotherSub\n\n else\n defaultSub\n\nend select\n <script language=\"vbscript\" runat=\"server\">\n MyJavascriptEval myvar\n</script>\n<script language=\"javascript\" runat=\"server\">\n function MyJavascriptEval( myExpression)\n {\n eval(myExpression);\n }\n\n /* OR\n function MyJavascriptEval( myExpression)\n {\n var f = new Function(myExpression);\n f();\n }\n */\n</script>\n"
},
{
"answer_id": 344654,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": true,
"text": "GetRef Function Test(val)\n Test = val & \" has been tested\"\nEnd Function\n\nDim myvar : myvar = \"Test\"\nDim x : Set x = GetRef(myvar)\nResponse.Write x(\"Thing\")\n validate(\"Hello World\", \"min_length(3)|max_length(10)|alphanumeric\")\n\n\nFunction required(val)\n required = val <> Empty\nEnd Function\n\n\nFunction min_length(val, params)\n min_length = Len(val) >= CInt(params(0))\nEnd Function\n\n\nFunction max_length(val, params)\n max_length = Len(val) <= CInt(params(0))\nEnd Function\n\n\nFunction alphanumeric(val)\n Dim rgx : Set rgx = New RegExp\n rgx.Pattern = \"^[A-Za-z0-9]+$\"\n alphanumeric = rgx.Test(val)\nEnd Function\n\n\nFunction validate(val, criterion)\n\n Dim arrCriterion : arrCriterion = Split(criterion, \"|\")\n Dim criteria\n\n validate = True\n\n For Each criteria in arrCriterion\n\n Dim paramListPos : paramListPos = InStr(criteria, \"(\")\n\n If paramListPos = 0 Then\n validate = GetRef(criteria)(val)\n Else\n Dim paramList\n paramList = Split(Mid(criteria, paramListPos + 1, Len(criteria) - paramListPos - 1), \",\")\n criteria = Left(criteria, paramListPos - 1)\n validate = GetRef(criteria)(val, paramList)\n End If\n If Not validate Then Exit For\n Next\n\nEnd Function\n function test(val) { return val + \" has been tested\"; )\nvar myvar = \"test\"\nResponse.Write(this[myvar](\"Thing\"))\n"
},
{
"answer_id": 344709,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 0,
"selected": false,
"text": "<%\nClass User\n' declare private class variable\nPrivate m_userName\n\n' declare the property\nPublic Property Get UserName\n UserName = m_userName\nEnd Property\nPublic Property Let UserName (strUserName)\n m_userName = strUserName\nEnd Property\n\n' declare and define the method\nSub DisplayUserName\n Response.Write UserName\nEnd Sub\n\nEnd Class\n%> \n"
},
{
"answer_id": 346266,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Execute \"Response.Write \"\"hello world\"\"\"\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
335,660 | <p>Finding a good way to do this has stumped me for a while now: assume I have a selection box with a set of points in it. By dragging the corners you can scale the (distance between) points in the box. Now for an axis aligned box this is easy. Take a corner as an anchor point (subtract this corner from each point, scale it, then add it to the point again) and multiply each points x and y by the factor with which the box has gotten bigger.</p>
<p>But now take a box that is not aligned with the x and y axis. How do you scale the points inside this box when you drag its corners?</p>
| [
{
"answer_id": 335692,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": true,
"text": "u v u v u v Points: p1 = (3,5) and p2 = (6,4)\n\nSelection corners: (0,2),(8,0),(9,4),(1,6)\nselected origin = (8,0)\n\nu = ((0,2)-(8,0))/|(0,2)-(8,0)| = <-0.970, 0.242>\nv = <-0.242, -0.970>\n v u p1´ = p1 - origin = (-5, 5)\np2´ = p2 - origin = (-2, 4)\n\np1_u = p1´ . u = -0.970 * (-5) + 0.242 * 5 = 6.063\np1_v = p1´ . v = -0.242 * (-5) - 0.970 * 5 = -3.638\n\nScale p1_u by 0.5: 3.038\n\np1_u * u + p1_v * v + origin = <5.941, 4.265>\n\nSame for p2: <7.412, 3.647>\n (8,0) (9,4) (0,8) def scale(points, origin, u, scale):\n # normalize\n len_u = (u[0]**2 + u[1]**2) ** 0.5\n u = (u[0]/len_u, u[1]/len_u)\n # create v\n v = (-u[1],u[0])\n ret = []\n for x,y in points:\n # subtract origin\n x, y = x - origin[0], y - origin[1]\n # calculate dot product\n pu = x * u[0] + y * u[1]\n pv = x * v[0] + y * v[1]\n # scale\n pu = pu * scale\n # transform back to normal space\n x = pu * u[0] + pv * v[0] + origin[0]\n y = pu * u[1] + pv * v[1] + origin[1]\n ret.append((x,y))\n return ret\n\n>>> scale([(3,5),(6,4)],(8,0),(-8,2),0.5)\n[(5.9411764705882355, 4.2647058823529411), (7.4117647058823533, 3.6470588235294117)]\n"
},
{
"answer_id": 335866,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 0,
"selected": false,
"text": "scale = ((M - P3) dot (P1 - P3)) / ((P1 - P3) dot (P1 - P3)) N1 = scale*P1 + (1 - scale)*P3\nN2 = scale*P2 + (1 - scale)*P3\nN4 = scale*P4 + (1 - scale)*P3 N2 = ((M - P3) dot (P2 - P3)) / ((P2 - P3) dot (P2 - P3)) * (P2 - P3) + P3\nN4 = ((M - P3) dot (P4 - P3)) / ((P4 - P3) dot (P4 - P3)) * (P4 - P3) + P3 #include <vector>\n\nclass Point\n{\n public:\n float x;\n float y;\n Point() { x = y = 0; }\n Point(float nx, float ny) { x = nx; y = ny; }\n};\n\nPoint& operator-(Point& A, Point& B) { return Point(A.x-B.x, A.y-B.y); }\nPoint& operator+(Point& A, Point& B) { return Point(A.x+B.x, A.y+B.y); }\nPoint& operator*(float sc, Point& P) { return Point(sc*P.x, sc*P.y); }\n\nfloat dot_product(Point A, Point B) { return A.x*B.x + A.y*B.y; }\n\nstruct Rect { Point point[4]; };\n\nvoid scale_points(Rect box, int anchor, Point mouse, vector<Point> points)\n{\n Point& P3 = box.point[anchor];\n Point& P2 = box.point[(anchor + 1)%4];\n Point& P1 = box.point[(anchor + 2)%4];\n Point& P4 = box.point[(anchor + 3)%4];\n\n Point A = P4 - P3;\n Point aFactor = dot_product(mouse - P3, A) / dot_product(A, A) * A;\n\n Point B = P2 - P3;\n Point bFactor = dot_product(mouse - P3, B) / dot_product(B, B) * B;\n\n for (int i = 0; i < points.size(); i++)\n {\n Point P = points[i] - P3;\n points[i] = P3 + dot_product(P, aFactor) + dot_product(P, bFactor);\n }\n}"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42635/"
] |
335,695 | <p>The typical ConfigParser generated file looks like:</p>
<pre><code>[Section]
bar=foo
[Section 2]
bar2= baz
</code></pre>
<p>Now, is there a way to index lists like, for instance:</p>
<pre><code>[Section 3]
barList={
item1,
item2
}
</code></pre>
<p>Related question: <a href="https://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p>
| [
{
"answer_id": 335754,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 8,
"selected": true,
"text": "[Section 3]\nbarList=item1,item2\n"
},
{
"answer_id": 336545,
"author": "Mapad",
"author_id": 28165,
"author_profile": "https://Stackoverflow.com/users/28165",
"pm_score": 1,
"selected": false,
"text": " def get(self, section, option):\n \"\"\" Get a parameter\n if the returning value is a list, convert string value to a python list\"\"\"\n value = SafeConfigParser.get(self, section, option)\n if (value[0] == \"[\") and (value[-1] == \"]\"):\n return eval(value)\n else:\n return value\n class Section\n bar = foo\nclass Section2\n bar2 = baz\nclass Section3\n barList=[ item1, item2 ]\n"
},
{
"answer_id": 8048529,
"author": "Henry Cooke",
"author_id": 284475,
"author_profile": "https://Stackoverflow.com/users/284475",
"pm_score": 7,
"selected": false,
"text": "[paths]\npath1 = /some/path/\npath2 = /another/path/\n...\n config.items( \"paths\" ) path_items = config.items( \"paths\" )\nfor key, path in path_items:\n #do something with path\n"
},
{
"answer_id": 9735884,
"author": "quasimodo",
"author_id": 1273815,
"author_profile": "https://Stackoverflow.com/users/1273815",
"pm_score": 8,
"selected": false,
"text": "[Foo]\nfibs: [1,1,2,3,5,8,13]\n >>> json.loads(config.get(\"Foo\",\"fibs\"))\n[1, 1, 2, 3, 5, 8, 13]\n [Bar]\nfiles_to_check = [\n \"/path/to/file1\",\n \"/path/to/file2\",\n \"/path/to/another file with space in the name\"\n ]\n"
},
{
"answer_id": 11866695,
"author": "Peter Smit",
"author_id": 85514,
"author_profile": "https://Stackoverflow.com/users/85514",
"pm_score": 6,
"selected": false,
"text": ";test.ini\n[hello]\nbarlist = \n item1\n item2\n config.get('hello','barlist') \"\\nitem1\\nitem2\"\n def aslist_cronly(value):\n if isinstance(value, string_types):\n value = filter(None, [x.strip() for x in value.splitlines()])\n return list(value)\n\ndef aslist(value, flatten=True):\n \"\"\" Return a list of strings, separating the input based on newlines\n and, if flatten=True (the default), also split on spaces within\n each line.\"\"\"\n values = aslist_cronly(value)\n if not flatten:\n return values\n result = []\n for value in values:\n subvalues = value.split()\n result.extend(subvalues)\n return result\n class MyConfigParser(ConfigParser):\n def getlist(self,section,option):\n value = self.get(section,option)\n return list(filter(None, (x.strip() for x in value.splitlines())))\n\n def getlistint(self,section,option):\n return [int(x) for x in self.getlist(section,option)]\n"
},
{
"answer_id": 13163390,
"author": "yurisich",
"author_id": 881224,
"author_profile": "https://Stackoverflow.com/users/881224",
"pm_score": 1,
"selected": false,
"text": "import ConfigParser\nimport os\n\nclass Parser(object):\n \"\"\"attributes may need additional manipulation\"\"\"\n def __init__(self, section):\n \"\"\"section to retun all options on, formatted as an object\n transforms all comma-delimited options to lists\n comma-delimited lists with colons are transformed to dicts\n dicts will have values expressed as lists, no matter the length\n \"\"\"\n c = ConfigParser.RawConfigParser()\n c.read(os.path.join(os.path.dirname(__file__), 'config.cfg'))\n\n self.section_name = section\n\n self.__dict__.update({k:v for k, v in c.items(section)})\n\n #transform all ',' into lists, all ':' into dicts\n for key, value in self.__dict__.items():\n if value.find(':') > 0:\n #dict\n vals = value.split(',')\n dicts = [{k:v} for k, v in [d.split(':') for d in vals]]\n merged = {}\n for d in dicts:\n for k, v in d.items():\n merged.setdefault(k, []).append(v)\n self.__dict__[key] = merged\n elif value.find(',') > 0:\n #list\n self.__dict__[key] = value.split(',')\n config.cfg [server]\ncredentials=username:admin,password:$3<r3t\nloggingdirs=/tmp/logs,~/logs,/var/lib/www/logs\ntimeoutwait=15\n >>> import config\n>>> my_server = config.Parser('server')\n>>> my_server.credentials\n{'username': ['admin'], 'password', ['$3<r3t']}\n>>> my_server.loggingdirs:\n['/tmp/logs', '~/logs', '/var/lib/www/logs']\n>>> my_server.timeoutwait\n'15'\n Parser"
},
{
"answer_id": 22478998,
"author": "PythonTester",
"author_id": 2294097,
"author_profile": "https://Stackoverflow.com/users/2294097",
"pm_score": 6,
"selected": false,
"text": "ast.literal_eval()\n [section]\noption=[\"item1\",\"item2\",\"item3\"]\n import ConfigParser\nimport ast\n\nmy_list = ast.literal_eval(config.get(\"section\", \"option\"))\nprint(type(my_list))\nprint(my_list)\n <type'list'>\n[\"item1\",\"item2\",\"item3\"]\n"
},
{
"answer_id": 22675825,
"author": "John Mee",
"author_id": 75033,
"author_profile": "https://Stackoverflow.com/users/75033",
"pm_score": 4,
"selected": false,
"text": "[global]\nspys = richard.sorge@cccp.gov, mata.hari@deutschland.gov\n SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]\n ['richard.sorge@cccp.gov', 'mata.hari@deutschland.gov']\n"
},
{
"answer_id": 30223001,
"author": "LittleEaster",
"author_id": 4685993,
"author_profile": "https://Stackoverflow.com/users/4685993",
"pm_score": 4,
"selected": false,
"text": "[sect]\nalist = a\n b\n c\n l = config.get('sect', 'alist').split('\\n')\n nlist = 1\n 2\n 3\n nl = config.get('sect', 'alist').split('\\n')\nl = [int(nl) for x in nl]\n"
},
{
"answer_id": 50624111,
"author": "Abhishek Jain",
"author_id": 9819333,
"author_profile": "https://Stackoverflow.com/users/9819333",
"pm_score": 0,
"selected": false,
"text": "json.loads ast.literal_eval fieldvalue = [1,2,3,4,5] config.read(*.cfg) config['fieldValue'][0] [ 1"
},
{
"answer_id": 53274707,
"author": "Grr",
"author_id": 5061557,
"author_profile": "https://Stackoverflow.com/users/5061557",
"pm_score": 6,
"selected": false,
"text": "converters ConfigParser() ConfigParser get [Germ]\ngerms: a,list,of,names, and,1,2, 3,numbers\n cp = ConfigParser(converters={'list': lambda x: [i.strip() for i in x.split(',')]})\ncp.read('example.ini')\ncp.getlist('Germ', 'germs')\n['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']\ncp['Germ'].getlist('germs')\n['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']\n ast.literal_eval"
},
{
"answer_id": 57669478,
"author": "feeeper",
"author_id": 1821692,
"author_profile": "https://Stackoverflow.com/users/1821692",
"pm_score": 3,
"selected": false,
"text": "import configparser\n\n# allow_no_value param says that no value keys are ok\nconfig = configparser.ConfigParser(allow_no_value=True)\n\n# overwrite optionxform method for overriding default behaviour (I didn't want lowercased keys)\nconfig.optionxform = lambda optionstr: optionstr\n\nconfig.read('./app.config')\n\nfeatures = list(config['FEATURES'].keys())\n\nprint(features)\n ['BIOtag', 'TextPosition', 'IsNoun', 'IsNomn']\n [FEATURES]\nBIOtag\nTextPosition\nIsNoun\nIsNomn\n"
},
{
"answer_id": 58519919,
"author": "Dominik Maszczyk",
"author_id": 7424596,
"author_profile": "https://Stackoverflow.com/users/7424596",
"pm_score": 0,
"selected": false,
"text": "[DEFAULT]\nkeys = [\n Overall cost structure, Capacity, RAW MATERIALS,\n BY-PRODUCT CREDITS, UTILITIES, PLANT GATE COST,\n PROCESS DESCRIPTION, AT 50% CAPACITY, PRODUCTION COSTS,\n INVESTMENT, US$ MILLION, PRODUCTION COSTS, US ¢/LB,\n VARIABLE COSTS, PRODUCTION COSTS, MAINTENANCE MATERIALS\n ]\n <class 'list'>: ['Overall cost structure', 'Capacity', 'RAW MATERIALS', 'BY-PRODUCT CREDITS', 'UTILITIES', 'PLANT GATE COST', 'PROCESS DESCRIPTION', 'AT 50% CAPACITY', 'PRODUCTION COSTS', 'INVESTMENT', 'US$ MILLION', 'PRODUCTION COSTS', 'US ¢/LB', 'VARIABLE COSTS', 'PRODUCTION COSTS', 'MAINTENANCE MATERIALS']\n class AdvancedInterpolator(Interpolation):\n def before_get(self, parser, section, option, value, defaults):\n is_list = re.search(parser.LIST_MATCHER, value)\n if is_list:\n return parser.getlist(section, option, raw=True)\n return value\n\n\nclass AdvancedConfigParser(ConfigParser):\n\n _DEFAULT_INTERPOLATION = AdvancedInterpolator()\n\n LIST_SPLITTER = '\\s*,\\s*'\n LIST_MATCHER = '^\\[([\\s\\S]*)\\]$'\n\n def _to_list(self, str):\n is_list = re.search(self.LIST_MATCHER, str)\n if is_list:\n return re.split(self.LIST_SPLITTER, is_list.group(1))\n else:\n return re.split(self.LIST_SPLITTER, str)\n\n\n def getlist(self, section, option, conv=lambda x:x.strip(), *, raw=False, vars=None,\n fallback=_UNSET, **kwargs):\n return self._get_conv(\n section, option,\n lambda value: [conv(x) for x in self._to_list(value)],\n raw=raw,\n vars=vars,\n fallback=fallback,\n **kwargs\n )\n\n def getlistint(self, section, option, *, raw=False, vars=None,\n fallback=_UNSET, **kwargs):\n return self.getlist(section, option, int, raw=raw, vars=vars,\n fallback=fallback, **kwargs)\n\n def getlistfloat(self, section, option, *, raw=False, vars=None,\n fallback=_UNSET, **kwargs):\n return self.getlist(section, option, float, raw=raw, vars=vars,\n fallback=fallback, **kwargs)\n\n def getlistboolean(self, section, option, *, raw=False, vars=None,\n fallback=_UNSET, **kwargs):\n return self.getlist(section, option, self._convert_to_boolean,\n raw=raw, vars=vars, fallback=fallback, **kwargs)\n"
},
{
"answer_id": 58736848,
"author": "Mitch Gates",
"author_id": 4024567,
"author_profile": "https://Stackoverflow.com/users/4024567",
"pm_score": 3,
"selected": false,
"text": "#/path/to/config.cfg\n[Numbers]\nfirst_row = 1,2,4,8,12,24,36,48\n import configparser\n\nconfig = configparser.ConfigParser()\nconfig.read('/path/to/config.cfg')\n\n# Load into a list of strings\nfirst_row_strings = config.get('Numbers', 'first_row').split(',')\n\n# Load into a list of integers\nfirst_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]\n"
},
{
"answer_id": 66406714,
"author": "Amir Hossein Zarei",
"author_id": 13646165,
"author_profile": "https://Stackoverflow.com/users/13646165",
"pm_score": 0,
"selected": false,
"text": "from ast import literal_eval\n\nliteral_eval(\"[1,2,3,4]\")\n\nimport json\n\njson.loads(\"[1,2,3,4]\")\n your config file :\n[A]\njson_dis = .example.jason\n--------------------\nyour code :\nimport configparser\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n# getting items of section A\nconfig.items('A')\n# result is a list of key-values\n"
},
{
"answer_id": 67011582,
"author": "Sean Richards",
"author_id": 9257989,
"author_profile": "https://Stackoverflow.com/users/9257989",
"pm_score": 2,
"selected": false,
"text": "[section]\nlistKey1: 1001, 1002, 1003\nlistKey2: AAAA, BBBB, CCCC\n cfgFile = 'config.ini'\nparser = ConfigParser(converters={'list': lambda x: [i.strip() for i in x.split(',')]})\nparser.read(cfgFile)\n\nlist1 = list(map(int, parser.getlist('section', 'listKey1')))\nlist2 = list(map(str, parser.getlist('section', 'listKey2')))\n\nprint(list1)\nprint(list2)\n [1001, 1002, 1003]\n['AAAA', 'BBBB', 'CCCC']\n"
},
{
"answer_id": 72025834,
"author": "rainergo",
"author_id": 14108788,
"author_profile": "https://Stackoverflow.com/users/14108788",
"pm_score": 2,
"selected": false,
"text": "[Section 3]\nbarList=item1,item2\n from configparser import ConfigParser\nconfig = ConfigParser()\nconfig.read('config.ini')\nmy_list = config['Section 3']['barList'].split(',')\n my_list = ['item1', 'item2']\n [Section 3]\nbarList= item1, item2\n my_list = [x.strip() for x in config['Section 3']['barList'].split(',')]\n my_list_of_ints = list(map(int, my_list))\n my_list_of_ints = [item1, item2]\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42636/"
] |
335,719 | <p>I need to use an x509 certificate to get secure message level authentication from a rich client via the internet to a secure WCF Web Service.</p>
<p>Specifically, I am looking for a working step-by-step guide to setup, configuration, coding, and deployment, including creating a 'dev' certificate, installing it, and obtaining a 'real' certificate for production.</p>
| [
{
"answer_id": 342916,
"author": "Nigel Spencer",
"author_id": 28904,
"author_profile": "https://Stackoverflow.com/users/28904",
"pm_score": 7,
"selected": true,
"text": "makecert -n \"CN=MyRootCA\" -r -sv RootCA.pvk RootCA.cer\n http://mycertserver/certsrv makecert -pe -n \"CN=MyCert\" -ss my -sky exchange -sk MyCert \n -iv MyRootCA.pvk -ic MyRootCA.cer -sr localmachine MyCert.cer\n <services>\n <service\n name=\"TestService\"\n behaviorConfiguration=\"wsHttpCertificateBehavior\">\n <endpoint name=\"TestEndPoint\"\n address=\"\"\n binding=\"wsHttpBinding\"\n bindingConfiguration=\"wsHttpEndpointBinding\"\n contract=\"TestService.IMyContract\">\n <identity>\n <dns value=\"\"/>\n </identity>\n </endpoint>\n <endpoint address=\"mex\" binding=\"mexHttpsBinding\" contract=\"IMetadataExchange\"/>\n </service>\n</services>\n\n<bindings>\n <wsHttpBinding>\n <binding name=\"wsHttpEndpointBinding\">\n <security mode=\"Message\">\n <message clientCredentialType=\"Certificate\"/>\n </security>\n </binding>\n </wsHttpBinding>\n</bindings>\n\n<behaviors>\n <behavior name=\"wsHttpCertificateBehavior\">\n <serviceMetadata httpGetEnabled=\"false\" httpsGetEnabled=\"true\"/>\n <serviceCredentials>\n <clientCertificate>\n <authentication \n certificateValidationMode=\"PeerOrChainTrust\" \n revocationMode=\"NoCheck\"/>\n </clientCertificate>\n <serverCertificate findValue=\"CN=MyCert\"/>\n </serviceCredentials>\n </behavior>\n</behaviors>\n <client>\n <endpoint name=\"wsHttpBinding\"\n address=\"https://localhost/TestService/TestService.svc\"\n binding=\"wsHttpBinding\"\n bindingConfiguration=\"wsHttpBinding\"\n behaviorConfiguration=\"wsHttpCertificateBehavior\"\n contract=\"TestService.IMyContract\">\n <identity>\n <dns value=\"MyCert\"/>\n </identity>\n </endpoint>\n</client>\n\n<bindings>\n <wsHttpBinding>\n <binding name=\"wsHttpBinding\">\n <security mode=\"Message\">\n <message clientCredentialType=\"Certificate\"/>\n </security>\n </binding>\n </wsHttpBinding>\n</bindings>\n\n<behaviors>\n <endpointBehaviors>\n <behavior name=\"wsHttpCertificateBehavior\">\n <clientCredentials>\n <clientCertificate findValue=\"MyCert\" storeLocation=\"LocalMachine\"/>\n <serviceCertificate>\n <authentication \n certificateValidationMode=\"PeerOrChainTrust\" \n revocationMode=\"NoCheck\" \n trustedStoreLocation=\"LocalMachine\"/>\n </serviceCertificate>\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n</behaviors>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2918/"
] |
335,732 | <p>I want to allow users to embed badges on their personal site or blogs with a snippet of javascript. The badge is customized on our site based on information in their profiles that at some point is "approved". </p>
<p>Is there a best practice to check what website the javascript is embedded on and if it does not match the website in their "approved" profile display nothing. If it matches inject the html etc.</p>
<p>Thanks</p>
| [
{
"answer_id": 335763,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 0,
"selected": false,
"text": "var topUrl = top.location.href;\n"
},
{
"answer_id": 342495,
"author": "Már Örlygsson",
"author_id": 16271,
"author_profile": "https://Stackoverflow.com/users/16271",
"pm_score": 2,
"selected": true,
"text": "403 Forbidden var etCallHome = new Image();\netCallHome = \"http://yoursite.com/logger?url=\"+document.location.href;\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42648/"
] |
335,736 | <p>I was writing some try-catch blocks for various methods today, and thought to myself it would be good to have utility method which would automatically call the method again for a number of times specified in a parameter, at a certain time.</p>
<p>However, I thought to myself, the method/property etc which will cause an exception will be at the top of the stacktrace (do property calls get put on the stacktrace?) in a single threaded application (so an application with no code relating to threading). So I can simply get the method name at the top and dynamically call it again.</p>
<p>So I would have code like:</p>
<p>string s = StackTrace.GetFrame(0).GetMethodName; (I can't remember the exact syntax).</p>
<p>With this method, I can execute it using an activator or one of several other ways.</p>
<p>But in a multi-threaded application, I could have several methods firing at once and I wouldn't know which one finishes first/last. So I can't expect a method for which I write a try-catch block to be at the top of the stack.</p>
<p>How would I go about achieving this?</p>
| [
{
"answer_id": 335795,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "public static class Extensions {\n public static void Try(this Action a, int maxTries) {\n new (Func<bool>(() => { a(); return true; })).Try(maxTries);\n }\n\n public static TResult Try<TResult>(this Func<TResult> f, int maxTries) {\n Exception lastException = null;\n\n for (int i = 0; i < maxTries; i++) {\n try {\n return f();\n } catch (Exception ex) {\n lastException = ex;\n }\n }\n\n throw lastException;\n }\n}\n // Set a property\nnew Action(() => myObject.Property = 5).Try(5);\n\n// With a return value\nvar count = new Func<int>(() => myList.Count).Try(3);\n Utilities.Try(\n () => MyObject.Property = 5\n).Repeat(5);\n Utilities.Try(() => {\n MyObject.Property1 = 5;\n MyObject.Property2 = 6;\n MyObject.Property3 = 7;\n}).Repeat(5);\n"
},
{
"answer_id": 335801,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "public class TryAgain\n{\n public delegate void CodeToTryAgain ();\n\n public static void Repeat<E>(int count, CodeToTryAgain code) where E : Exception\n {\n while (count-- > 0)\n {\n try\n {\n code();\n return;\n }\n catch (E ex)\n {\n Console.WriteLine(\"Caught an {0} : {1}\", typeof(E).Name, ex.Message);\n // ignoring it!\n }\n }\n }\n}\n ThrowTwice TryAgain.Repeat<MyException>(5, delegate()\n{\n ThrowTwice();\n});\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
335,742 | <p>I have this quiz rails app linked to an IRC bot who asks questions (yes, on IRC), where I have this <code>Question</code> model which contains, well, questions, answers, hints, and a few more things.</p>
<p>I started with <code>Quiz</code> model (like, say, the special Halloween or Christmas quiz) with a <code>quiz_id</code> in the <code>questions</code> table, then, I told myself, that it would be nice to be able to categorize the questions, so I added a <code>Category</code> model (like, say, Movies or Books), with a <code>category_id</code> in the <code>questions</code>.</p>
<p>Now, my users would like to be able to add a question to one or more quiz, and to assign one or more categories to questions…</p>
<p>So, I've been thinking about removing the <code>Quiz</code> and <code>Category</code> models and replace them with tags, so that, there will be a halloween tag, a movie tag, and a question can have "halloween movie christmas" for tags.</p>
<p>In my searchs, I've seen quite a few ways to include tags like <code>acts_as_taggable</code>, <code>acts_as_taggable_on_steroids</code> or whatever else someone has imagined :-)</p>
<p>Now, I'm wondering what I should do, and so, I'm asking, what you have done, how you've done it, why you did it this way.</p>
| [
{
"answer_id": 335795,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "public static class Extensions {\n public static void Try(this Action a, int maxTries) {\n new (Func<bool>(() => { a(); return true; })).Try(maxTries);\n }\n\n public static TResult Try<TResult>(this Func<TResult> f, int maxTries) {\n Exception lastException = null;\n\n for (int i = 0; i < maxTries; i++) {\n try {\n return f();\n } catch (Exception ex) {\n lastException = ex;\n }\n }\n\n throw lastException;\n }\n}\n // Set a property\nnew Action(() => myObject.Property = 5).Try(5);\n\n// With a return value\nvar count = new Func<int>(() => myList.Count).Try(3);\n Utilities.Try(\n () => MyObject.Property = 5\n).Repeat(5);\n Utilities.Try(() => {\n MyObject.Property1 = 5;\n MyObject.Property2 = 6;\n MyObject.Property3 = 7;\n}).Repeat(5);\n"
},
{
"answer_id": 335801,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "public class TryAgain\n{\n public delegate void CodeToTryAgain ();\n\n public static void Repeat<E>(int count, CodeToTryAgain code) where E : Exception\n {\n while (count-- > 0)\n {\n try\n {\n code();\n return;\n }\n catch (E ex)\n {\n Console.WriteLine(\"Caught an {0} : {1}\", typeof(E).Name, ex.Message);\n // ignoring it!\n }\n }\n }\n}\n ThrowTwice TryAgain.Repeat<MyException>(5, delegate()\n{\n ThrowTwice();\n});\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42083/"
] |
335,753 | <p>I need to know how to iterate through records in CR2008 and when it reaches a record that is NOT NULL, record that in a variable.</p>
<p>I have a formula called "frmAccum" that I drop in the details section and suppress it. I use this to gather information for each record that's processed. I also have a formula called frmReset where I rest the stringvar "person_name" to "" and I can drop that in a Group header to reset after a grouping.</p>
<p>When it comes across a person_name field that is NOT NULL and is not empty, I want it to retain the name in a variable to be used in the report header.</p>
<p>So something like this:</p>
<pre><code>stringvar person_name;
whileprintingrecords;
If ({Command.personname} <> "") Then
person_name := {Command.personname}
</code></pre>
<p>I can't get this combination to work. Any help is appreciated.</p>
| [
{
"answer_id": 335795,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "public static class Extensions {\n public static void Try(this Action a, int maxTries) {\n new (Func<bool>(() => { a(); return true; })).Try(maxTries);\n }\n\n public static TResult Try<TResult>(this Func<TResult> f, int maxTries) {\n Exception lastException = null;\n\n for (int i = 0; i < maxTries; i++) {\n try {\n return f();\n } catch (Exception ex) {\n lastException = ex;\n }\n }\n\n throw lastException;\n }\n}\n // Set a property\nnew Action(() => myObject.Property = 5).Try(5);\n\n// With a return value\nvar count = new Func<int>(() => myList.Count).Try(3);\n Utilities.Try(\n () => MyObject.Property = 5\n).Repeat(5);\n Utilities.Try(() => {\n MyObject.Property1 = 5;\n MyObject.Property2 = 6;\n MyObject.Property3 = 7;\n}).Repeat(5);\n"
},
{
"answer_id": 335801,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "public class TryAgain\n{\n public delegate void CodeToTryAgain ();\n\n public static void Repeat<E>(int count, CodeToTryAgain code) where E : Exception\n {\n while (count-- > 0)\n {\n try\n {\n code();\n return;\n }\n catch (E ex)\n {\n Console.WriteLine(\"Caught an {0} : {1}\", typeof(E).Name, ex.Message);\n // ignoring it!\n }\n }\n }\n}\n ThrowTwice TryAgain.Repeat<MyException>(5, delegate()\n{\n ThrowTwice();\n});\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38317/"
] |
335,770 | <p>Example: </p>
<pre><code>$ svn copy foo.txt bar.txt
A bar.txt
</code></pre>
<ul>
<li>When would you use this technique, and why? </li>
<li>Will this command (taken from svn's "red book") creates a copy of <code><foo.txt></code> while preserving the history of it to be shared with <code><bar.txt></code>? </li>
<li>If I'm changing <code><bar.txt></code>, what will happen to <code><foo.txt></code>? </li>
</ul>
<p>What are the equivalents to this in other modern systems (Clearcase, Accurev, Perforce)? </p>
<p>Let me emphasize the point I'm searching for:<br>
Is this kind of branching out on a file level?<br>
What happens if you use it in the same branch, i.e. create a copy of a file and than start changing that new file. all in the same branch?<br>
I understand that it is also used for tagging but what is interesting me is what to expect when performing <code><svn copy></code> on the file level.</p>
| [
{
"answer_id": 335785,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 5,
"selected": false,
"text": "foo.txt bar.txt foo.txt bar.txt bar.txt foo.txt bar.txt foo.txt"
},
{
"answer_id": 335862,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 6,
"selected": true,
"text": "-C"
},
{
"answer_id": 336865,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "svn copy element * .../myBranchForCopy/LATEST\nelement /myPath/myFile /main/myBranch/LATEST -mkbranch myBranchForCopy\n foo.txt myBranch myBranchForCopy foo.txt@@/main/myBranch/myBranchForCopy/LATEST foo.txt@@/main/myBranch/LATEST"
},
{
"answer_id": 2877298,
"author": "René Nyffenegger",
"author_id": 180275,
"author_profile": "https://Stackoverflow.com/users/180275",
"pm_score": 1,
"selected": false,
"text": "svn copy"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10312/"
] |
335,774 | <p>I had some site templates designed for me recently. I got the final HTML code, which validates, but the structure of the document is laid out using DL-DD pairs:</p>
<pre><code><dl>
<dd class="some-class">
Some text.
</dd>
</dl>
</code></pre>
<p>I'm not especially familiar with those tags as I've never used them much, but they don't seem intended for document structure. Am I right? Why would a designer do this?</p>
| [
{
"answer_id": 335789,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<dd>"
},
{
"answer_id": 335794,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 2,
"selected": false,
"text": "DL UL DL DD DT DD <DL>\n <DT>CSS</DT>\n <DD>Cascading Style Sheet</DD>\n</DL>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39539/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.