qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
312,517 | <p>I'm having some trouble with the Google Maps API; I want to determine a LatLong for a certain place (for example, from the name of a city), then focus my map on it. The LatLong part is working, and so is centering the map on that point. However, I cannot figure out how to determine what a good zoomlevel might be when I only have that single point. I cannot just go to some standard zoomlevel that might look good most of the time, 'cause what happens when the user enters "Russia" instead of "Amsterdam", for example? Some help would be appreciated :)</p>
| [
{
"answer_id": 774596,
"author": "Simon Gibbs",
"author_id": 13935,
"author_profile": "https://Stackoverflow.com/users/13935",
"pm_score": 1,
"selected": false,
"text": "GMap2.getBoundsZoomLevel(bounds)\n PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX dbpedia2: <http://dbpedia.org/property/>\nSELECT ?url, ?label, ?lat, ?long, ?area WHERE {\n ?url geo:lat ?lat .\n ?url geo:lat ?long .\n ?url rdfs:label ?label . FILTER ( lang(?label) = 'en' ) .\n ?url dbpedia2:area ?area . FILTER ( datatype(?area) = xsd:double ) \n} LIMIT 10\n"
},
{
"answer_id": 1258068,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 2,
"selected": true,
"text": "{\n \"id\":\"p1\",\n \"address\":\"Beverly Hills, CA 90210, USA\",\n \"AddressDetails\":{\n \"Accuracy\":5,\n \"Country\":{\n \"AdministrativeArea\":{\n \"AdministrativeAreaName\":\"CA\",\n \"SubAdministrativeArea\":{\n \"Locality\":{\n \"LocalityName\":\"Beverly Hills\",\n \"PostalCode\":{\"PostalCodeNumber\":\"90210\"}\n },\n \"SubAdministrativeAreaName\":\"Los Angeles\"\n }\n },\n \"CountryName\":\"USA\",\n \"CountryNameCode\":\"US\"\n }\n },\n // This is what you're looking for\n \"ExtendedData\":{\n \"LatLonBox\":{\n \"north\":34.13919,\n \"south\":34.067018, \n \"east\":-118.38971, \n \"west\":-118.442796\n }\n },\n \"Point\":{\n \"coordinates\":[-118.4104684,34.1030032,0]\n }\n}\n"
},
{
"answer_id": 44553432,
"author": "James L.",
"author_id": 4180797,
"author_profile": "https://Stackoverflow.com/users/4180797",
"pm_score": 0,
"selected": false,
"text": "map.fitBounds(autocomplete.getPlace().geometry.viewport);"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37472/"
] |
312,549 | <p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p>
<pre><code>Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module>
from django.core import management
ImportError: No module named django.core
</code></pre>
| [
{
"answer_id": 325295,
"author": "Fil",
"author_id": 12218,
"author_profile": "https://Stackoverflow.com/users/12218",
"pm_score": 6,
"selected": true,
"text": "import django ActivePython 2.5.1.1 (ActiveState Software Inc.) based on\nPython 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import django\n>>>\n setuptools easy_install setup.py site-packages .pth easy-install.pth django.pth"
},
{
"answer_id": 2081421,
"author": "cmsjr",
"author_id": 23114,
"author_profile": "https://Stackoverflow.com/users/23114",
"pm_score": 3,
"selected": false,
"text": "python c:\\Python26\\scripts\\django-admin.py startproject mysite\n"
},
{
"answer_id": 2154450,
"author": "greg",
"author_id": 260961,
"author_profile": "https://Stackoverflow.com/users/260961",
"pm_score": 0,
"selected": false,
"text": "sudo find /usr/lib/python2.5/site-packages/django -type d -exec chmod go+rx {} \\;\nsudo find /usr/lib/python2.5/site-packages/django -type f -exec chmod go+r {} \\;\n"
},
{
"answer_id": 2172329,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 5,
"selected": false,
"text": "python c:\\python25\\scripts\\django-admin.py startproject mysite\n"
},
{
"answer_id": 2398649,
"author": "Tod",
"author_id": 16679,
"author_profile": "https://Stackoverflow.com/users/16679",
"pm_score": 3,
"selected": false,
"text": "python apps\\django\\django\\bin\\django-admin.py startproject mysite\n"
},
{
"answer_id": 4573897,
"author": "sultan",
"author_id": 256465,
"author_profile": "https://Stackoverflow.com/users/256465",
"pm_score": 0,
"selected": false,
"text": "ln -s $SOMEWHERE/lib/python2.6/site-packages/django/ ./django"
},
{
"answer_id": 4721682,
"author": "wassimans",
"author_id": 313127,
"author_profile": "https://Stackoverflow.com/users/313127",
"pm_score": 0,
"selected": false,
"text": "PYTHONPATH django.pth PYTHONHOME\\Lib\\site-packages PYTHONHOME django.pth PYTHONHOME\\Lib\\site-packages\\django\n PYTHONHOME django.pth PYTHONPATH path.pth"
},
{
"answer_id": 8186132,
"author": "Banjer",
"author_id": 193210,
"author_profile": "https://Stackoverflow.com/users/193210",
"pm_score": 4,
"selected": false,
"text": "vim ~/.bashrc\nexport PYTHONPATH=/usr/local/python-2.7.2/lib/python2.7/site-packages:$PYTHONPATH\nsource ~/.bashrc\n /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages /etc/profile sudo echo \"PYTHONPATH=/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages:$PYTHONPATH\" >> /etc/profile\nsource /etc/profile\n"
},
{
"answer_id": 8528185,
"author": "David Morales",
"author_id": 267705,
"author_profile": "https://Stackoverflow.com/users/267705",
"pm_score": 1,
"selected": false,
"text": "vim /usr/local/share/python/django-admin.py\n #!/usr/bin/python\n #!/usr/local/bin/python\n"
},
{
"answer_id": 10311785,
"author": "kry",
"author_id": 449936,
"author_profile": "https://Stackoverflow.com/users/449936",
"pm_score": 0,
"selected": false,
"text": "Variables/PATH this: ;C:\\Python26\\Scripts;C:\\Python26."
},
{
"answer_id": 14547802,
"author": "Gemmu",
"author_id": 1980027,
"author_profile": "https://Stackoverflow.com/users/1980027",
"pm_score": 1,
"selected": false,
"text": "cmd.exe ftype python (env_p27) C:\\Users\\Gemmu\\env_p27>python .\\Scripts\\django-admin.py startproject mysite"
},
{
"answer_id": 17991527,
"author": "Emil Davtyan",
"author_id": 220710,
"author_profile": "https://Stackoverflow.com/users/220710",
"pm_score": 1,
"selected": false,
"text": "pip sudo"
},
{
"answer_id": 20797090,
"author": "LynxLee",
"author_id": 489794,
"author_profile": "https://Stackoverflow.com/users/489794",
"pm_score": 0,
"selected": false,
"text": "python setup.py install"
},
{
"answer_id": 32341585,
"author": "Tim Reilly",
"author_id": 4175241,
"author_profile": "https://Stackoverflow.com/users/4175241",
"pm_score": 1,
"selected": false,
"text": "(DjangoEnv) C:\\users\\timreilly\\Envs\\django\\Scripts\\django-admin.exe startproject myproject\n"
},
{
"answer_id": 35263660,
"author": "hemant c",
"author_id": 4116509,
"author_profile": "https://Stackoverflow.com/users/4116509",
"pm_score": 0,
"selected": false,
"text": " django version 1.9.2\n django-admin.py startproject MySite\n\n***and not this***\n\npython django-admin.py startproject MySite \n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7965/"
] |
312,551 | <p>I have some XSD-s that define my objects hierarchy. for example math.xsd, base.xsd
while math.xsd is depends on base.xsd. I need to generate classes from those xsd-s.</p>
<p>I've already read about those two tools:
<a href="http://www.bware.biz/CodeXS/CodeXS.asmx" rel="nofollow noreferrer">CodeXS</a> tool and <a href="http://www.bware.biz/CodeXS/CodeXS.asmx" rel="nofollow noreferrer">XSD.exe</a>.
the problem with the xsd.exe is that I didn't succeed generating classes from two xsd-s that depends on each other. is there anyone who knows the right parameters for using the xsd.exe for such case?</p>
<p>moreover, I am looking for:
- more tools
- comparison between those tools
- xsd to object using .net 3.5
Thanks.</p>
| [
{
"answer_id": 1314886,
"author": "Leon Breedt",
"author_id": 90079,
"author_profile": "https://Stackoverflow.com/users/90079",
"pm_score": 2,
"selected": false,
"text": "xsd.exe XmlSchema XmlCodeExporter XmlSchemaImporter XmlSchema schema = null; // Load XSD file here\n var schemas = new XmlSchemas();\n schemas.Add(schema);\n\n var ns = new CodeNamespace { Name = \"MyNamespace\" };\n\n ns.Imports.Add(new CodeNamespaceImport(\"System\"));\n ns.Imports.Add(new CodeNamespaceImport(\"System.Collections.Generic\"));\n\n var exporter = new XmlCodeExporter(ns); \n var importer = new XmlSchemaImporter(schemas); \n\n foreach (XmlSchemaElement element in schema.Elements.Values) \n { \n var mapping = importer.ImportTypeMapping(element.QualifiedName);\n exporter.ExportTypeMapping(mapping); \n }\n\n // Transform CodeDOM as required, adding new attributes, methods, modifying\n // inheritance hierarchy, whatever.\n\n var provider = new CSharpCodeProvider(); \n using (var writer = new StreamWriter(outputFile, false))\n provider.GenerateCodeFromNamespace(ns, writer, new CodeGeneratorOptions())\n XmlSchemaSet XmlResolver XmlSchemaSet Compile() XmlSerializer"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10977/"
] |
312,552 | <p>I am looking for a Java open source beautifier or reformatter for SQL that I can use to clean up DDL statements that I am generating with <a href="http://www.openarchitectureware.org" rel="nofollow noreferrer">openArchitectureWare</a>.</p>
<p>Nothing in the answer to "<a href="https://stackoverflow.com/questions/206441/online-code-beautifier-and-formatter">Online Code Beautifier And Formatter</a>" is of use to me and I have not been able to get <a href="http://www.ohloh.net/projects/simplesqlformatter" rel="nofollow noreferrer">Simple SQL Formatter</a> to work for me.</p>
| [
{
"answer_id": 559120,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 7,
"selected": true,
"text": "org.hibernate.jdbc.util.BasicFormatterImpl org.hibernate.engine.jdbc.internal.BasicFormatterImpl org.hibernate.pretty.Formatter org.hibernate.jdbc.util.BasicFormatterImpl String formattedSQL = new BasicFormatterImpl().format(sql);\n org.hibernate.pretty.Formatter String formattedSQL = new Formatter(sql).format();\n"
},
{
"answer_id": 4873441,
"author": "Stephan",
"author_id": 363573,
"author_profile": "https://Stackoverflow.com/users/363573",
"pm_score": 3,
"selected": false,
"text": "Formatter f = new BasicFormatterImpl();\nString formatted_sql_code = f.format(ugly_sql_code);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1969/"
] |
312,570 | <p>I know that <a href="http://en.wikipedia.org/wiki/Buffer_overflow" rel="nofollow noreferrer">buffer overruns</a> are one potential hazard to using C-style strings (char arrays). If I know my data will fit in my buffer, is it okay to use them anyway? Are there other drawbacks inherent to C-style strings that I need to be aware of?</p>
<p><strong>EDIT:</strong> Here's an example close to what I'm working on:</p>
<pre><code>char buffer[1024];
char * line = NULL;
while ((line = fgets(fp)) != NULL) { // this won't compile, but that's not the issue
// parse one line of command output here.
}
</code></pre>
<p>This code is taking data from a FILE pointer that was created using a <code>popen("df")</code> command. I'm trying to run Linux commands and parse their output to get information about the operating system. Is there anything wrong (or dangerous) with setting the buffer to some arbitrary size this way?</p>
| [
{
"answer_id": 312736,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 3,
"selected": false,
"text": "char *fgets(char *s, int size, FILE *stream);"
},
{
"answer_id": 312841,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "char buffer[1024];\nchar * line = NULL;\nwhile ((line = fgets(buffer, sizeof(buffer), fp)) != NULL) {\n // parse one line of command output here.\n}\n line"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
312,599 | <p>I am trying to get pylons to debug in Eclipse under Ubuntu.
Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.</p>
<p>(<a href="https://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse">this</a> is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)</p>
<p>Can anyone help?</p>
| [
{
"answer_id": 314913,
"author": "SystemicPlural",
"author_id": 40080,
"author_profile": "https://Stackoverflow.com/users/40080",
"pm_score": 3,
"selected": true,
"text": "Window>Preferences>Pydev>Interpreter-Python New sudo python setup.py develop Run>Open Debug Dialog Main Module /usr/bin/paster Arguments Program arguments serve /locationOfYourProject/development.ini --reload"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40080/"
] |
312,605 | <p>I'm making a simple form to create polls, therefore I want the possibility to add additional input fields in case the user wants more options in the poll.</p>
<p>I've made Javascript code that adds a new input field to the form, but the dynamically added input fields are not posted when the form is submitted (I use a standard submit button). </p>
<p><strong>Is there some way to get the dynamically added fields posted/recognized as a part of the form?</strong></p>
<pre><code><form id="myForm" method="post">
<input type="submit">
<input type="text" name="poll[question]">
<input type="text" name="poll[option1]">
<input type="text" name="poll[option2]">
</form>
<a href="javascript:addOption();">Add option</a>
<script>
var optionNumber = 3; //The first option to be added is number 3
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "poll[option"+optionNumber+"]"; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
</code></pre>
| [
{
"answer_id": 312620,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n foreach (string p in this.Request.Params.Keys) {\n if (p.StartsWith(\"poll\")) {\n Response.Write(p + \" \" + this.Request.Params[p] + \"<br />\");\n }\n }\n}\n poll[question] test1\npoll[option1] test2\npoll[option2] test3\npoll[option3] test4\npoll[option4] test5\npoll[option5] test6\npoll[option6] test7\n"
},
{
"answer_id": 312651,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 3,
"selected": true,
"text": "<?php\n print_r($_REQUEST)\n?>\n<html>\n<body>\n\n<form id=\"myForm\" method=\"post\"> \n <input type=\"submit\">\n <input type=\"text\" name=\"poll[question]\"> \n <input type=\"text\" name=\"poll[option1]\"> \n <input type=\"text\" name=\"poll[option2]\"> \n</form> \n<a href=\"javascript:addOption();\">Add option</a> \n\n<script> \n var optionNumber = 3; //The first option to be added is number 3 \n function addOption() { \n var theForm = document.getElementById(\"myForm\"); \n var newOption = document.createElement(\"input\"); \n newOption.name = \"poll[option\"+optionNumber+\"]\"; // poll[optionX]\n newOption.type = \"text\";\n theForm.appendChild(newOption); \n optionNumber++;\n } \n</script>\n</body>\n</html>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37066/"
] |
312,625 | <p>I am creating a Firefox Extension...what would be the javascript to open a URL in the current tab from a menuitem?</p>
<p>e.g. in my overlay.xul file i have the following line:</p>
<pre><code><menuitem label="Visit homepage" oncommand="window.location='http://www.somepage.com'"/>
</code></pre>
<p>but in firefox, when i click on the menu item, it opens the URL but it screws up the entire layout of the browser.</p>
<p>What's the correct way to do this?</p>
| [
{
"answer_id": 312683,
"author": "aryo",
"author_id": 17998,
"author_profile": "https://Stackoverflow.com/users/17998",
"pm_score": 4,
"selected": true,
"text": "<menuitem label=\"Visit homepage\" oncommand=\"content.wrappedJSObject.location='http://www.somepage.com'\"/>\n"
},
{
"answer_id": 724823,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "//open a url current window:\nfunction openUrl(url) {\ncontent.wrappedJSObject.location = url;\nnewTabBrowser = gBrowser.selectedBrowser;\nnewTabBrowser.addEventListener(\"load\", highlight, true);\n}\n\n//new tab\nfunction openUrlNewTab(url) {\nvar win = Components.classes['@mozilla.org/appshell/window-mediator;1']\n .getService(Components.interfaces.nsIWindowMediator)\n .getMostRecentWindow('navigator:browser');\nwin.gBrowser.selectedTab = win.gBrowser.addTab(url);\n}\n"
},
{
"answer_id": 930820,
"author": "anotherjesse",
"author_id": 114941,
"author_profile": "https://Stackoverflow.com/users/114941",
"pm_score": 3,
"selected": false,
"text": "openUILinkIn(url, where);\n openUILinkIn(url, whereToOpenLink(event));\n <menuitem label=\"Visit homepage\" \n oncommand=\"openUILinkIn('http://example.com/', whereToOpenLink(event))\"/>\n <label value=\"google\" class=\"text-link\" href=\"http://google.com/\" />\n"
},
{
"answer_id": 4551238,
"author": "NhanLee",
"author_id": 556685,
"author_profile": "https://Stackoverflow.com/users/556685",
"pm_score": 2,
"selected": false,
"text": "<menuitem label=\"Visit Report Site\" oncommand=\"var win = Components.classes['@mozilla.org/appshell/window-mediator;1']\n.getService(Components.interfaces.nsIWindowMediator)\n.getMostRecentWindow('navigator:browser'); win.openUILinkIn('http://www.google.com', 'tab');\"/>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17998/"
] |
312,626 | <p>I'm coming from Eclipse, working in Visual Studio 2008 Express and just want to highlight code, right-click and comment it out.</p>
<ul>
<li>nothing in right-click</li>
<li>looking in Tools | Options, Toolbars, Commands, can't find a button for it...</li>
</ul>
<p>How do I activate this the comment/uncomment feature, I know Visual Studio 2003 had it.</p>
<p>HERE ARE THE ANSWERS, TURNS OUT IT DEPENDS WHAT YOU ARE USING:</p>
<p><strong>Visual Studio 2008 Full Version:</strong></p>
<p>Comment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>C</kbd><br />
Uncomment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>U</kbd></p>
<p><strong>Visual Web Developer 2008 Express:</strong></p>
<p>Comment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>C</kbd><br />
Uncomment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>U</kbd></p>
<p><strong>Visual C# 2008 Express:</strong></p>
<p>Comment <kbd>Ctrl</kbd>-<kbd>E</kbd> , <kbd>Ctrl</kbd>-<kbd>C</kbd><br />
Uncomment <kbd>Ctrl</kbd>-<kbd>E</kbd> , <kbd>Ctrl</kbd>-<kbd>U</kbd></p>
| [
{
"answer_id": 312885,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 2,
"selected": false,
"text": "/ // * /* */"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
312,642 | <p>I have to give a general note to some huge Java project for which I have but little visibility and I was wondering if there were any guidelines for determining:</p>
<ul>
<li>what number of classes per package can be considered right, to low, or to high (this project has 3.89 classes per package, which seems a bit too small for me), </li>
<li>number of methods per class? (this project has 6.54 methods per class...</li>
<li>number of lines per method? (this project has about 7 lines per method (seems pretty good to me, maybe a bit low))</li>
</ul>
<p>I should note that this question is only dealing with volumetry. I have a bunch of reports from quality tools (checkstyle, jdepend, cpd, pmd, ncss) that give me more vision about code redundancy, classes usage, bugs, etc.</p>
| [
{
"answer_id": 312870,
"author": "P Arrayah",
"author_id": 33459,
"author_profile": "https://Stackoverflow.com/users/33459",
"pm_score": 1,
"selected": false,
"text": "StringUtil.escapeXMLspecialCharacters(someString) StringUtil.XML.escapeSpecialCharacters(someString) XMLUtil.escapeSpecialCharacters(someString) MenuButtons AdjustmentButtons foo foo.bar bar foo.baz baz"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25152/"
] |
312,648 | <p>I thought that if a c pointer pointing to a char array was incremented then it would point to the next element in that array. But when I tried this I found that I had to increment it twice. Trying the increment using sizeof(char) I found that adding the size of a char was too much so it had to be divided by two. </p>
<pre><code>#include <stdio.h>
int main(int argc, char * argv[]){
char *pi;
int i;
pi = argv[1];
printf("%d args.\n",argc-1);
printf("input: ");
for(i=0;i<argc-1;i++){
printf("%c, ",*pi);
/*The line below increments pi by 1 char worth of bytes */
//pi+=sizeof(pi)/2;
/* An alternative to the above line is putting pi++ twice - why? */
pi++;
pi++;
}
printf("\n");
return 0;
}
</code></pre>
<p>Am I doing something wrong? or am I misunderstanding the method of incrementing pointers?</p>
| [
{
"answer_id": 312656,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "ptr T* N N * sizeof (*ptr) N * sizeof (T) pi sizeof (pi) char* char pi+=sizeof(char*)/2; pi+=2; pi+=2 char sizeof (char)"
},
{
"answer_id": 312661,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 4,
"selected": false,
"text": "abc defg\n 2 args.\ninput: a, c,\n #include <stdio.h>\n\nint main(int argc, char * argv[]){\n char **pi;\n int i;\n\n pi = argv + 1;\n printf(\"%d args.\\n\",argc-1);\n printf(\"input: \");\n for(i=0;i<argc-1;i++){\n printf(\"%c, \",**pi);\n pi++;\n }\n printf(\"\\n\");\n return 0;\n}\n 2 args.\ninput: a, d,\n"
},
{
"answer_id": 312662,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 2,
"selected": false,
"text": "int *ipointer = &int_array[0];\nipointer += 2;\n for (i = 1; i < argc; i++) {\n pi = argv[i];\n // ... do something with pi\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,652 | <p>I'm currently in the process of replacing my homebrewn build script by an Ant build script.</p>
<p>Now I need to replace various tokens by the size of a specific file. I know how to get the size in bytes via the <code><length></code> task and store in in a property, but I need the size in kilobytes and megabytes too.</p>
<p>How can I access the file size in other representations (KB, MB) or compute these values from within the Ant target and store them in a property?</p>
<p><strong>Edit:</strong> After I discovered the <code><script></code> task, it was fairly easy to calculate the other values using some JavaScript and add a new property to the project using <code>project.setNewProperty("foo", "bar");</code>.</p>
| [
{
"answer_id": 326536,
"author": "fhe",
"author_id": 4445,
"author_profile": "https://Stackoverflow.com/users/4445",
"pm_score": 4,
"selected": true,
"text": "<script> <target name=\"insert-filesize\">\n <length file=\"${afile}\" property=\"fs.length.bytes\" />\n\n <script language=\"javascript\">\n <![CDATA[\n var length_bytes = project.getProperty(\"fs.length.bytes\");\n var length_kbytes = Math.round((length_bytes / 1024) * Math.pow(10,2))\n / Math.pow(10,2);\n var length_mbytes = Math.round((length_kbytes / 1024) * Math.pow(10,2))\n / Math.pow(10,2);\n project.setNewProperty(\"fs.length.kb\", length_kbytes);\n project.setNewProperty(\"fs.length.mb\", length_mbytes);\n ]]>\n </script>\n\n <copy todir=\"${target.dir}\">\n <fileset dir=\"${source.dir}\">\n <include name=\"**/*\" />\n <exclude name=\"**/*.zip\" />\n </fileset>\n <filterset begintoken=\"$$$$\" endtoken=\"$$$$\">\n <filter token=\"SIZEBYTES\" value=\"${fs.length.bytes}\"/>\n <filter token=\"SIZEKILOBYTES\" value=\"${fs.length.kb}\"/>\n <filter token=\"SIZEMEGABYTES\" value=\"${fs.length.mb}\"/>\n </filterset>\n </copy>\n</target>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4445/"
] |
312,672 | <p>While an applet is loading, it displays a white rectangle for a split second. How can we get rid of it?</p>
| [
{
"answer_id": 326536,
"author": "fhe",
"author_id": 4445,
"author_profile": "https://Stackoverflow.com/users/4445",
"pm_score": 4,
"selected": true,
"text": "<script> <target name=\"insert-filesize\">\n <length file=\"${afile}\" property=\"fs.length.bytes\" />\n\n <script language=\"javascript\">\n <![CDATA[\n var length_bytes = project.getProperty(\"fs.length.bytes\");\n var length_kbytes = Math.round((length_bytes / 1024) * Math.pow(10,2))\n / Math.pow(10,2);\n var length_mbytes = Math.round((length_kbytes / 1024) * Math.pow(10,2))\n / Math.pow(10,2);\n project.setNewProperty(\"fs.length.kb\", length_kbytes);\n project.setNewProperty(\"fs.length.mb\", length_mbytes);\n ]]>\n </script>\n\n <copy todir=\"${target.dir}\">\n <fileset dir=\"${source.dir}\">\n <include name=\"**/*\" />\n <exclude name=\"**/*.zip\" />\n </fileset>\n <filterset begintoken=\"$$$$\" endtoken=\"$$$$\">\n <filter token=\"SIZEBYTES\" value=\"${fs.length.bytes}\"/>\n <filter token=\"SIZEKILOBYTES\" value=\"${fs.length.kb}\"/>\n <filter token=\"SIZEMEGABYTES\" value=\"${fs.length.mb}\"/>\n </filterset>\n </copy>\n</target>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5541/"
] |
312,673 | <pre><code>if __name__=='__main__':
parser = OptionParser()
parser.add_option("-i", "--input_file",
dest="input_filename",
help="Read input from FILE", metavar="FILE")
(options, args) = parser.parse_args()
print options
</code></pre>
<p>result is</p>
<pre><code>$ python convert.py -i video_*
{'input_filename': 'video_1.wmv'}
</code></pre>
<p>there are video_[1-6].wmv in the current folder.
Question is why video_* become video_1.wmv. What i'm doing wrong?</p>
| [
{
"answer_id": 312677,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 4,
"selected": true,
"text": "$ python convert.py -i 'video_*'\n -i python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6 -i args options.input"
},
{
"answer_id": 312816,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "- cp mv rm"
},
{
"answer_id": 312903,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 1,
"selected": false,
"text": "aprogram -e *.wmv\n aprogram sys.argv == ['aprogram', '-e', '1.wmv', '2.wmv', '3.wmv']\n aprogram -e \"*.wmv\"\n sys.argv == ['aprogram', '-e', '*.wmv']\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29364/"
] |
312,674 | <p>First off, how do I know if my html file is running on localhost in Xampp?
Is there a tutorial on how to manage files/directories and get that all working under htdocs?
Is there a good tutorial on how to setup includes?</p>
<p>I want to use "includes" in Xampp with my html.
Can I use both html includes AND php includes?
Do I have to put shtml?
Can I use shtml, html, htm, and php includes?
Do they have to be in an includes directory that is a subdirectory right under htdocs?
Can I reference includes in some other subdirectory?
My site will have over 100 pages, and I am trying to do "experiments" with different versions until I am happy. So, I have subdirectories for the various drop down menus. Unfortunately, I don't seem to be able to get this working in xampp.
Having trouble getting my javascript menus from Vista Buttons to show up, now that I moved my main directory for my site to the htdocs directory.</p>
| [
{
"answer_id": 11563006,
"author": "jibiel",
"author_id": 535406,
"author_profile": "https://Stackoverflow.com/users/535406",
"pm_score": 2,
"selected": false,
"text": "Options +Includes\n AddType text/html .shtml\nAddOutputFilter INCLUDES .shtml\n XBitHack on\n chmod +x pagename.html\n"
},
{
"answer_id": 31273681,
"author": "user1378423",
"author_id": 1378423,
"author_profile": "https://Stackoverflow.com/users/1378423",
"pm_score": 2,
"selected": false,
"text": "c:/xampp/apache/conf/httpd.conf\n AddType text/html .shtml\n AddType text/html .html\nAddOutputFilter INCLUDES .html\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40091/"
] |
312,695 | <p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p>
<p>I have written the following code, however I get the following exception: </p>
<blockquote>
<p>Message File
Name Line Position Traceback Node
31
exceptions.TypeError: this constructor takes no arguments</p>
</blockquote>
<pre><code>class Computer:
name = "Computer1"
ip = "0.0.0.0"
screenSize = 17
def Computer(compName, compIp, compScreenSize):
name = compName
ip = compIp
screenSize = compScreenSize
printStats()
return
def Computer():
printStats()
return
def printStats():
print "Computer Statistics: --------------------------------"
print "Name:" + name
print "IP:" + ip
print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects
print "-----------------------------------------------------"
return
comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
</code></pre>
<p>Any thoughts?</p>
| [
{
"answer_id": 312698,
"author": "mthurlin",
"author_id": 39991,
"author_profile": "https://Stackoverflow.com/users/39991",
"pm_score": 3,
"selected": false,
"text": "__init__ class Computer:\n\n def __init__(self, compName = \"Computer1\", compIp = \"0.0.0.0\", compScreenSize = 22):\n self.name = compName\n self.ip = compIp\n self.screenSize = compScreenSize\n\n self.printStats()\n\n def printStats(self):\n print \"Computer Statistics: --------------------------------\"\n print \"Name:\", self.name\n print \"IP:\", self.ip\n print \"ScreenSize:\", self.screenSize\n print \"-----------------------------------------------------\"\n\n\ncomp1 = Computer()\ncomp2 = Computer(\"The best computer in the world\", \"27.1.0.128\",22)\n"
},
{
"answer_id": 312699,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 1,
"selected": false,
"text": "def __init__(self, ...): class Computer:\n def __init__(self, compName=\"Computer1\", compIp=\"0.0.0.0\", compScreenSize=17):\n self.name = compName\n self.ip = compIp\n self.screenSize = compScreenSize\n\n self.printStats()\n\n return\n\n def printStats(self):\n print \"Computer Statistics: --------------------------------\"\n print \"Name : %s\" % self.name\n print \"IP : %s\" % self.ip\n print \"ScreenSize: %s\" % self.screenSize\n print \"-----------------------------------------------------\"\n return\n\ncomp1 = Computer()\ncomp2 = Computer(\"The best computer in the world\", \"27.1.0.128\",22)\n"
},
{
"answer_id": 312703,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 2,
"selected": false,
"text": "__init__ class comp {\n std::string m_name;\n foo(std::string name);\n};\n\nfoo::foo(std::string name) : m_name(name) {}\n class comp:\n def __init__(self, name=None):\n if name: self.name = name\n else: self.name = 'defaultName'\n"
},
{
"answer_id": 312704,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 1,
"selected": false,
"text": "__init__()\n"
},
{
"answer_id": 312727,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 6,
"selected": true,
"text": "class Computer(object):\n \"\"\"Docstrings are used kind of like Javadoc to document classes and\n members. They are the first thing inside a class or method.\n\n You probably want to extend object, to make it a \"new-style\" class.\n There are reasons for this that are a bit complex to explain.\"\"\"\n\n # everything down here is a static variable, unlike in Java or C# where\n # declarations here are for what members a class has. All instance\n # variables in Python are dynamic, unless you specifically tell Python\n # otherwise.\n defaultName = \"belinda\"\n defaultRes = (1024, 768)\n defaultIP = \"192.168.5.307\"\n\n def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP):\n \"\"\"Constructors in Python are called __init__. Methods with names\n like __something__ often have special significance to the Python\n interpreter.\n\n The first argument to any class method is a reference to the current\n object, called \"self\" by convention.\n\n You can use default function arguments instead of function\n overloading.\"\"\"\n self.name = name\n self.resolution = resolution\n self.ip = ip\n # and so on\n\n def printStats(self):\n \"\"\"You could instead use a __str__(self, ...) function to return this\n string. Then you could simply do \"print(str(computer))\" if you wanted\n to.\"\"\"\n print \"Computer Statistics: --------------------------------\"\n print \"Name:\" + self.name\n print \"IP:\" + self.ip\n print \"ScreenSize:\" , self.resolution //cannot concatenate 'str' and 'tuple' objects\n print \"-----------------------------------------------------\"\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
] |
312,718 | <p>I have quite a few partials in my application, and some of them need to do some jQuery goodness at $(document).ready time.</p>
<p>The problem is, if I put the $(document).ready directly into a script block for the partial, then this gets overridden if another partial does the same thing.</p>
<p>It seems a solution where the various $(document).ready tidbits are gathered up and then included in a single $(document).ready instance is needed.</p>
<p>Is there a defined way to do this already?</p>
| [
{
"answer_id": 4260592,
"author": "RayLoveless",
"author_id": 462971,
"author_profile": "https://Stackoverflow.com/users/462971",
"pm_score": 0,
"selected": false,
"text": "<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl<Myapp...SearchResultsViewModel>\" %>\n\n<script type=\"text/javascript\">\n $(document).ready(function () {\n alert('partial is ready.');\n });\n</script>\n\n<h1>This is my <%: Model.name %> partial view</h1>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40097/"
] |
312,732 | <p>I'm trying to create an algorithm in C# which produces the following output strings:</p>
<pre><code>AAAA
AAAB
AAAC
...and so on...
ZZZX
ZZZY
ZZZZ
</code></pre>
<p>What is the best way to accomplish this?</p>
<pre><code>public static IEnumerable<string> GetWords()
{
//Perform algorithm
yield return word;
}
</code></pre>
| [
{
"answer_id": 312739,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": true,
"text": "public static IEnumerable<String> GetWords()\n{\n for (Char c1 = 'A'; c1 <= 'Z'; c1++)\n {\n for (Char c2 = 'A'; c2 <= 'Z'; c2++)\n {\n for (Char c3 = 'A'; c3 <= 'Z'; c3++)\n {\n for (Char c4 = 'A'; c4 <= 'Z'; c4++)\n {\n yield return \"\" + c1 + c2 + c3 + c4;\n }\n }\n }\n }\n}\n public static IEnumerable<String> GetWords(Int32 length)\n{\n if (length <= 0)\n yield break;\n\n for (Char c = 'A'; c <= 'Z'; c++)\n {\n if (length > 1)\n {\n foreach (String restWord in GetWords(length - 1))\n yield return c + restWord;\n }\n else\n yield return \"\" + c;\n }\n}\n"
},
{
"answer_id": 312761,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 4,
"selected": false,
"text": "var letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".ToCharArray();\n\nvar sequence = from one in letters\n from two in letters\n from three in letters\n from four in letters\n orderby one, two, three, four\n select new string(new[] { one, two, three, four });\n public void Nonsense()\n{\n var letters = new[]{\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\n \"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\n \"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\n \"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"};\n\n foreach (var val in Sequence(letters, 4))\n Console.WriteLine(val);\n}\n\nprivate IQueryable<string> Sequence(string[] alphabet, int size)\n{\n // create the first level\n var sequence = alphabet.AsQueryable();\n\n // add each subsequent level\n for (var i = 1; i < size; i++)\n sequence = AddLevel(sequence, alphabet);\n\n return from value in sequence\n orderby value\n select value;\n}\n\nprivate IQueryable<string> AddLevel(IQueryable<string> current, string[] characters)\n{\n return from one in current\n from character in characters\n select one + character;\n}\n"
},
{
"answer_id": 312817,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 1,
"selected": false,
"text": "DECLARE @Letters TABLE (\n MyChar CHAR(1) PRIMARY KEY\n)\nDECLARE @N INT\nSET @N=0\nWHILE @N<26 BEGIN\n INSERT @Letters (MyChar) VALUES ( CHAR( @N + 65) )\n SET @N = @N + 1\nEND\n-- SELECT * FROM @Letters ORDER BY 1\n\nSELECT A.MyChar, B.MyChar, C.MyChar, D.MyChar\nFROM @Letters A, Letters B, Letters C, Letters D\nORDER BY 1,2,3,4\n"
},
{
"answer_id": 312868,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 0,
"selected": false,
"text": "var chars = 4, abc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", top = 1, fact = [];\nfor (i = 0; i < chars; i++) { fact.unshift(top); top *= abc.length; }\nfor (i = 0; i < top; i++)\n{\n for (j = 0; j < chars; j++) \n document.write(abc[Math.floor(i/fact[j]) % abc.length]);\n document.write(\"<br \\>\\n\");\n}\n"
},
{
"answer_id": 313262,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 1,
"selected": false,
"text": "# Convert a number to the base 26 using [A-Z] as the cyphers\ndef itoa26(n): \n array = [] \n while n: \n lowestDigit = n % 26\n array.append(chr(lowestDigit + ord('A'))) \n n /= 26 \n array.reverse() \n return ''.join(array)\n\ndef generateSequences(nChars):\n for n in xrange(26**nChars):\n string = itoa26(n)\n yield 'A'*(nChars - len(string)) + string\n\nfor string in generateSequences(3):\n print string\n"
},
{
"answer_id": 313302,
"author": "Josh Lee",
"author_id": 19750,
"author_profile": "https://Stackoverflow.com/users/19750",
"pm_score": 1,
"selected": false,
"text": "replicateM 4 ['A'..'Z']\n ('A'*4..'Z'*4).to_a\n"
},
{
"answer_id": 313330,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "{a..z}{a..z}{a..z}{a..z}\n"
},
{
"answer_id": 316121,
"author": "Olmo",
"author_id": 38670,
"author_profile": "https://Stackoverflow.com/users/38670",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<string> letters = new[]{\n \"A\",\"B\",\"C\",\"D\",\"E\",\"F\", \n \"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\n \"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\", \n \"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"};\n\nvar result = Enumerable.Range(0, 4)\n .Aggregate(letters, (curr, i) => curr.SelectMany(s => letters, (s, c) => s + c));\n\nforeach (var val in result)\n Console.WriteLine(val);\n"
},
{
"answer_id": 317543,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\n\nnamespace ConsoleApplication1Test\n{\n class Program\n {\n static char[] my_func( char[] my_chars, int level)\n {\n if (level > 1)\n my_func(my_chars, level - 1);\n my_chars[(my_chars.Length - level)]++;\n if (my_chars[(my_chars.Length - level)] == ('Z' + 1))\n {\n my_chars[(my_chars.Length - level)] = 'A';\n return my_chars;\n }\n else\n {\n Console.Out.WriteLine(my_chars);\n return my_func(my_chars, level);\n }\n }\n static void Main(string[] args)\n {\n char[] text = { 'A', 'A', 'A', 'A' };\n my_func(text,text.Length);\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 411983,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "def getWords(length=3):\n if length == 0: raise StopIteration\n for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':\n if length == 1: yield letter\n else:\n for partialWord in getWords(length-1):\n yield letter+partialWord\n"
},
{
"answer_id": 45414357,
"author": "Mohammed Kaif",
"author_id": 8393558,
"author_profile": "https://Stackoverflow.com/users/8393558",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\nusing namespace std;\nchar alpha[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}\nint main() {\nint num;\ncin >> num;\nif (num == 3) { //all 3 letter words\n for (int i = 0; i <= 25; i++) {\n for (int o = 0; o <= 25; o++) {\n for (int p = 0; p <= 25; p++) {\n cout << alpha[i] << alpha[o] << alpha[p] << \" \";\n }\n }\n }\n}\nelse if (num == 4) { //all 4 letter words\n for (int i = 0; i <= 25; i++) {\n for (int o = 0; o <= 25; o++) {\n for (int p = 0; p <= 25; p++) {\n for (int q = 0; q <= 25; q++) {\n cout << alpha[i] << alpha[o] << alpha[p] << alpha[q] << \" \";\n }\n }\n }\n }\n}\nelse {\n cout << \"Not more than 4\"; //it will take more than 2 hours for generating all 5 letter words\n }\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33431/"
] |
312,735 | <p><strong>(Scroll down to bottom of post to find solution.)</strong></p>
<p>Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called. The
itemCreatedCommand is responsible for
databinding the dropdownlist. </p>
<p>I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...</p>
<pre><code>protected void DataListProducts_ItemCreatedCommand(object
source, DataListItemEventArgs e)
var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
var item = itemBLL.GetFullItem(itemId);
var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");
//Also tried with :
//if(!isPostBack) {
DropDownListColor.DataSource = item.ColorList;
DropDownList.Color.Databind();
// } End !isPostBack)
Label1.test = DropDownListColor.SelectedIndex.toString();
// <- THIS IS ALWAYS 0! *grr*
</code></pre>
<p>I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :) The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file. </p>
<p>EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :) </p>
<p><strong>SOLUTION:</strong> </p>
<p>Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there. </p>
<pre><code> protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
var item = items[dataListItem.ItemIndex];
var color = item.ItemColor[dropDownListColor.SelectedIndex];
var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
LabelPrice.Text = color.Price;
}
</code></pre>
| [
{
"answer_id": 26313942,
"author": "user4132142",
"author_id": 4132142,
"author_profile": "https://Stackoverflow.com/users/4132142",
"pm_score": 0,
"selected": false,
"text": " protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) {\n try {\n ModalPopupExtender1.Show();\n if (ViewState[\"Colors\"] != null) {\n FillColors(ViewState[\"Colors\"].ToString());\n }\n\n DropDownList dropDownListColor = (DropDownList)sender;\n DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;\n\n Image image = (Image)dataListItem.FindControl(\"mdlImage\");\n Label ProductCode = (Label)dataListItem.FindControl(\"lblprdCode\");\n Label ProductName = (Label)dataListItem.FindControl(\"lblProdName\");\n DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl(\"ddlQuantity\");\n Label ProductPrice = (Label)dataListItem.FindControl(\"lblProdPrice\");\n Label TotalPrice = (Label)dataListItem.FindControl(\"lblTotPrice\");\n //Label ProductPrice = (Label)dataListItem.FindControl(\"lblProdPrice\");\n } catch (Exception ex) {\n\n }\n }\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37280/"
] |
312,749 | <p>I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner_product, but consider it as a generic problem).
The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but on the first element of each pair? </p>
<p>I know i can do it manually, providing a hand-made function object that will be a wrapper around the standard container iterator, deferencing it to the first member of the pair intend of the pair itself,but I think there is also a clever one-liner to do it for me. What would it be?</p>
| [
{
"answer_id": 312764,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "reverse_iterator"
},
{
"answer_id": 312766,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "boost::transform_iterator #include <map>\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <iterator>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n\nint main() {\n typedef std::map<std::string, int>::value_type value_type;\n std::map<std::string, int> a;\n a[\"one\"] = 1;\n a[\"two\"] = 2;\n\n // returns the second element \n boost::function<int(value_type&)> f = boost::bind(&value_type::second, _1);\n std::copy(boost::make_transform_iterator(a.begin(), f), \n boost::make_transform_iterator(a.end(), f),\n std::ostream_iterator<int>(std::cout, \" \"));\n\n}\n \"1 2 \""
},
{
"answer_id": 312770,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 1,
"selected": false,
"text": "transform_iterator"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78828/"
] |
312,762 | <p>I have a winforms application that is doing the following:</p>
<p>on each query:</p>
<ol>
<li>Db connect</li>
<li>Db query</li>
<li>Db disconnect</li>
</ol>
<p>as we are trying to avoid having to keep the db connection open. This suffers from performance as we have to connect / disconnect everytime.</p>
<p>What is the idealized model here to have the fastest performance but without having open connection for too long. Is there a best practice here?</p>
| [
{
"answer_id": 312771,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": true,
"text": "SqlConnection using"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
312,767 | <p>I am trying to locate an evil plugin that includes a stoneage version of a certain jar file. How do I do that ?</p>
| [
{
"answer_id": 314860,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": -1,
"selected": false,
"text": "mvn dependency:tree"
},
{
"answer_id": 7261442,
"author": "Hugo Duncan",
"author_id": 84439,
"author_profile": "https://Stackoverflow.com/users/84439",
"pm_score": 4,
"selected": false,
"text": "mvn dependency:resolve-plugins"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
312,789 | <p>...if there is such a thing. Here's an image of two approachs for structuring DLLs/references in a .NET application: <a href="http://www.experts-exchange.com/images/t80668/compArch.png" rel="nofollow noreferrer">http://www.experts-exchange.com/images/t80668/compArch.png</a>. The app can be a website (it is in this case) or a winform. Each box represents a DLL. For the winform app, just replace "webcontrols" with "winformcomponents".</p>
<p>The first (top) image is what I like. You might want to extend "some" of the base web controls and directly use others. The 2nd image makes you extend any web controls via interface. To me that seems overkill since you may want to simply use what is already there without modification. Which is better and what are the advantages/disadvantages?</p>
<p>The first image puts the lowest common constructs(exceptions, fileIO, constants, etc) into a common.dll. The 2nd image puts app business logic and common into one DLL. Which is better and what are the advantages/disadvantages of each apporach? </p>
| [
{
"answer_id": 312827,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "CompName.Web.UI CompName.Data CompName.Common CompName.Web.UI"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40106/"
] |
312,794 | <p>What is the Python equivalent of the following code in Ruby?</p>
<pre><code>def loop
cont=nil
for i in 1..4
puts i
callcc {|continuation| cont=continuation} if i==2
end
return cont
end
> c=loop
1
2
3
4
> c.call
3
4
</code></pre>
<p>Reference: <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/" rel="nofollow noreferrer">Secrets of lightweight development success, Part 9: Continuations-based frameworks</a></p>
| [
{
"answer_id": 312801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "def loop():\n for i in xrange(1,5):\n print i\n if i == 2:\n yield\n\n\nfor i in loop():\n print \"pass\"\n yield .next() loop()"
},
{
"answer_id": 312941,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "def loop(): \n def f(i, cont=[None]): \n for i in range(i, 5):\n print i\n if i == 2:\n cont[0] = lambda i=i+1: f(i)\n return cont[0]\n return f(1)\n\nif __name__ == '__main__':\n c = loop()\n c()\n"
},
{
"answer_id": 313073,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "generator_tools $ easy_install generator_tools from generator_tools import copy_generator\n\ndef _callg(generator, generator_copy=None):\n for _ in generator: # run to the end\n pass\n if generator_copy is not None:\n return lambda: _callg(copy_generator(generator_copy))\n\ndef loop(c):\n c.next() # advance to yield's expression\n return _callg(c, copy_generator(c))\n\nif __name__ == '__main__':\n def loop_gen():\n i = 1\n while i <= 4:\n print i\n if i == 2:\n yield\n i += 1\n\n c = loop(loop_gen())\n print(\"c:\", c)\n for _ in range(2):\n print(\"c():\", c())\n 1\n2\n3\n4\n('c:', <function <lambda> at 0x00A9AC70>)\n3\n4\n('c():', None)\n3\n4\n('c():', None)\n"
},
{
"answer_id": 4328519,
"author": "pts",
"author_id": 97248,
"author_profile": "https://Stackoverflow.com/users/97248",
"pm_score": 2,
"selected": false,
"text": "callcc callcc callcc"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30289/"
] |
312,796 | <p>I'm trying to integrate a NSURLConnection object with UIProgressView, so I can update the user while a file download is happening in the background.</p>
<p>I created a separate object to download the file in the background, and I'm having problems figuring out how to update the progress property in the UIProgressView object with the correct value. It's probably something very simple, but I cannot figure it out with Googling around.</p>
<p>Here's the code that I have:</p>
<pre><code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.resourceData setLength:0];
self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
NSLog(@"content-length: %d bytes", self.filesize);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.resourceData appendData:data];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]];
NSLog(@"resourceData length: %d", [resourceLength intValue]);
NSLog(@"filesize: %d", self.filesize);
NSLog(@"float filesize: %f", [self.filesize floatValue]);
progressView.progress = [resourceLength floatValue] / [self.filesize floatValue];
NSLog(@"progress: %f", [resourceLength floatValue] / [self.filesize floatValue]);
}
</code></pre>
<p>As you can see, the <b>resourceData</b> member variable holds the file data as it is being downloaded. The <b>filesize</b> member variable holds the full size of the file, as returned by my web service in its Content-Length header.</p>
<p>It all works sort of OK, I keep getting the downloaded data with multiple executions of <b>didReceiveData</b> as I should, but when I try to calculate the progress value, no proper value is returned. See below for a small sample of what I get in my console log:</p>
<pre><code>content-length: 4687472 bytes
resourceData length: 2904616
filesize: 4687472
float filesize: -1.000000
progress: -2904616.000000
</code></pre>
<p>For reference, <b>progressView.progress</b> is a float. <b>filesize</b> is a NSNumber that holds a long long. Finally, <b>resourceLength</b> is a NSNumber that holds a NSUInteger.</p>
<p>What am I missing here?</p>
| [
{
"answer_id": 312879,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 6,
"selected": true,
"text": "filesize expectedContentLength NSURLResponseUnknownLength NSURLResponseUnknownLength #define NSURLResponseUnknownLength ((long long)-1)\n"
},
{
"answer_id": 313208,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 3,
"selected": false,
"text": "self.filesize NSNumber %@ NSLog(@\"filesize: %@\", self.filesize);\n %d %lli %d NSLog(@\"filesize: %lli\", [self.filesize longLongValue]);\n"
},
{
"answer_id": 3329254,
"author": "Christian Fries",
"author_id": 231397,
"author_profile": "https://Stackoverflow.com/users/231397",
"pm_score": 0,
"selected": false,
"text": "\n NSLog(@\"filesize: %d\", self.filesize);\n \nNSLog(@\"content-length: %d bytes\", self.filesize);\n \n filesize: 4687472\n \nNSURLResponseUnknownLength\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35478/"
] |
312,810 | <p>I am building an Entity Framework model for a subset of the Pubs database from microsoft. I am only interested and publishers and books, not publishers and employees, but there is a foreign key constraint between the publishers and emoloyees tables. When I remove the employees entity from my model, the model won't validate because of the foreign key constraint.</p>
<p>How do I create a model for a subset of a database when that subset links to other tabes with foreign key constraints?</p>
<p>Because this is for a demo, I deleted the offending tables and constraints from the database, but this won't work in production.</p>
| [
{
"answer_id": 312879,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 6,
"selected": true,
"text": "filesize expectedContentLength NSURLResponseUnknownLength NSURLResponseUnknownLength #define NSURLResponseUnknownLength ((long long)-1)\n"
},
{
"answer_id": 313208,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 3,
"selected": false,
"text": "self.filesize NSNumber %@ NSLog(@\"filesize: %@\", self.filesize);\n %d %lli %d NSLog(@\"filesize: %lli\", [self.filesize longLongValue]);\n"
},
{
"answer_id": 3329254,
"author": "Christian Fries",
"author_id": 231397,
"author_profile": "https://Stackoverflow.com/users/231397",
"pm_score": 0,
"selected": false,
"text": "\n NSLog(@\"filesize: %d\", self.filesize);\n \nNSLog(@\"content-length: %d bytes\", self.filesize);\n \n filesize: 4687472\n \nNSURLResponseUnknownLength\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17715/"
] |
312,846 | <p>I have a very simple model. I want to add a send email routine to on of the methods for the model:</p>
<pre><code>$this->Email->delivery = 'smtp';
$this->Email->template = 'default';
$this->Email->sendAs = 'text';
$this->Email->from = 'email';
$this->Email->to = 'email';
$this->Email->subject = 'Error';
</code></pre>
<p>I've tried putting </p>
<pre><code>App::import('Component', 'Email');
</code></pre>
<p>at the top, to no avail. The error I get is:</p>
<blockquote>
<p>Fatal error: Call to undefined method stdClass::send() in E:\xampp\htdocs8080\app\models\debug.php on line 23</p>
</blockquote>
<p>Any ideas?</p>
<p>I'm running CakePHP 1.2</p>
| [
{
"answer_id": 313184,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 2,
"selected": false,
"text": "var $components = array('Email');\n $this->Email->delivery = ...\n"
},
{
"answer_id": 374092,
"author": "nanoman",
"author_id": 46993,
"author_profile": "https://Stackoverflow.com/users/46993",
"pm_score": 4,
"selected": false,
"text": "function sendEmail(&$controller) {\n App::import('Component', 'Email');\n $email = new EmailComponent();\n $email->startup($controller);\n}\n"
},
{
"answer_id": 617683,
"author": "Sergei",
"author_id": 27309,
"author_profile": "https://Stackoverflow.com/users/27309",
"pm_score": 4,
"selected": true,
"text": "function _sendMail($to,$subject,$template) {\n $this->Email->to = $to;\n // $this->Email->bcc = array('secret@example.com'); // copies\n $this->Email->subject = $subject;\n $this->Email->replyTo = 'noreply@domain.com';\n $this->Email->from = 'MyName <noreply@domain.com>';\n $this->Email->template = $template;\n $this->Email->sendAs = 'text'; //Send as 'html', 'text' or 'both' (default is 'text')\n $this->Email->send();\n}\n $this->_sendMail($this->data['User']['email'],'Thanks for registering!','register');\n var $components = array('Email');\n"
},
{
"answer_id": 719415,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if(empty($this->MailsController)) {\n App::import('Controller','Mails');\n $this->MailsController = new MailsController();\n $this->MailsController->constructClasses();\n $this->MailsController->Email->startup($this->MailsController);\n}\n $this->MailsController->orderMail($user_id,$this->id,$mode);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] |
312,858 | <p>My scenario should be simple... the type I want to convert <em>FROM</em> is <em>ALWAYS</em> 'string'. What I want to convert to... could be many things - ints, DateTimes, ... strings, etc.</p>
<p>This would be easy:</p>
<pre><code>string valueToConvertFrom = "123";
int blah = Convert.ToInt32(valueToConvertFrom);
</code></pre>
<p>However... I don't know (until runtime) that the value I need to convert to is an 'Int' (or whatever). I have tried this:</p>
<pre><code>string valueToConvertFrom = "123";
Type convertToType = typeof(int);
object blah = Convert.ChangeType(valueToConvertFrom, convertToType);
</code></pre>
<p>But that gives me the following error: "Object must implement IConvertible."</p>
<p>I don't want to have to do a switch statement and call "Convert.ToBlah" based on the type name... any suggestions?</p>
| [
{
"answer_id": 312884,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 3,
"selected": false,
"text": "object o = Convert.ChangeType( str, convertToType );\n Type convertToType = ...;\nMethodInfo mi = convertToType.GetMethod(\"Parse\", BindingFlags.Static);\nobject blah;\nif(mi != null)\n{\n blah = mi.Invoke(null, new object[]{valueToConvertFrom});\n}\nelse\n{\n // the type doesn't implement the Parse method, handle it another way :/\n}\n"
},
{
"answer_id": 312898,
"author": "Asher",
"author_id": 38265,
"author_profile": "https://Stackoverflow.com/users/38265",
"pm_score": 6,
"selected": true,
"text": "string valueToConvertFrom = \"123\";\n\nType convertToType = typeof(int);\n\nTypeConverter tc = TypeDescriptor.GetConverter(convertToType); \n\nobject blah =tc.ConvertFromString(valueToConvertFrom);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11917/"
] |
312,861 | <p>I put together a sample scenario of my issue and I hope its enough for someone to point me in the right direction.</p>
<p>I have two tables</p>
<p>Products</p>
<p><img src="https://i.stack.imgur.com/ktnI0.gif" alt="alt text"></p>
<p>Product Meta</p>
<p><img src="https://i.stack.imgur.com/dBrc0.gif" alt="alt text"></p>
<p>I need a result set of the following</p>
<p><img src="https://i.stack.imgur.com/Ken2R.gif" alt="alt text"></p>
| [
{
"answer_id": 312883,
"author": "GregD",
"author_id": 38317,
"author_profile": "https://Stackoverflow.com/users/38317",
"pm_score": 2,
"selected": false,
"text": "Select a.ProductId\n ,a.Name\n ,(Select c.MetaValue\n From [Product Meta] c\n Where c.ProductId = a.ProductId\n And c.MetaKey = 'A') As 'A'\n ,(Select d.MetaValue\n From [Product Meta] d\n Where d.ProductId = a.ProductId\n And d.MetaKey = 'B') As 'B'\n ,(Select e.MetaValue\n From [Product Meta] e\n Where e.ProductId = a.ProductId\n And e.MetaKey = 'C') As 'C'\nFrom Products a\nOrder By a.ProductId Asc\n"
},
{
"answer_id": 326208,
"author": "Rich Andrews",
"author_id": 37381,
"author_profile": "https://Stackoverflow.com/users/37381",
"pm_score": 5,
"selected": true,
"text": "SELECT [p].ProductID,\n [p].Name,\n MAX(CASE [m].MetaKey\n WHEN 'A'\n THEN [m].MetaValue\n END) AS A,\n MAX(CASE [m].MetaKey\n WHEN 'B'\n THEN [m].MetaValue\n END) AS B,\n MAX(CASE [m].MetaKey\n WHEN 'C'\n THEN [m].MetaValue\n END) AS C\nFROM Products [p]\n INNER JOIN ProductMeta [m]\n ON [p].ProductId = [m].ProductId\nGROUP BY [p].ProductID,\n [p].Name \n SUM(CASE x WHEN 'y' THEN yVal ELSE 0 END) AS SUMYVal\n"
},
{
"answer_id": 2556507,
"author": "AaronLS",
"author_id": 84206,
"author_profile": "https://Stackoverflow.com/users/84206",
"pm_score": 3,
"selected": false,
"text": "DatabaseNameHere.dbo.TableNameHere"
},
{
"answer_id": 5799709,
"author": "Thomas",
"author_id": 198643,
"author_profile": "https://Stackoverflow.com/users/198643",
"pm_score": 5,
"selected": false,
"text": "Select P.ProductId, P.Name\n , Min( Case When PM.MetaKey = 'A' Then PM.MetaValue End ) As A\n , Min( Case When PM.MetaKey = 'B' Then PM.MetaValue End ) As B\n , Min( Case When PM.MetaKey = 'C' Then PM.MetaValue End ) As C\nFrom Products As P\n Join ProductMeta As PM\n On PM.ProductId = P.ProductId\nGroup By P.ProductId, P.Name\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34444/"
] |
312,865 | <p>I'm attempting to learn basic Win32 programming and running into a frustrating problem. I wish to convert a variable (Call it NumClicks) and display it as the application name (as part of a string).
From what I've seen, going from int + some block of text to a char* is problematic, because converting it to the requisite end data type(LPCWSTR) is more difficult than a straight casting.</p>
<p>Any ideas or links? </p>
| [
{
"answer_id": 3080957,
"author": "Yevhen",
"author_id": 264292,
"author_profile": "https://Stackoverflow.com/users/264292",
"pm_score": 0,
"selected": false,
"text": "\nint f =55; \nwchar_t buffer[10];\n_itow_s (f, buffer, 10);\nfunc_using_lpcwstr_as_parameter(buffer);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40115/"
] |
312,877 | <p>Situation: you've got a .swf embedded in an html page, and when you click on something in the .swf, it needs to popup a chromeless window. Normally this would be fairly easy - but consider Safari, which completely disables all 'window.open' functionality while its popup-blocker is enabled (it makes an exception if the function is triggered onclick, but it doesn't count clicks in flash). How can you create something which gracefully degrades (provides an alternate and roughly equivalent experience) for browsers that won't execute window.open?</p>
<p>(note: this is AS3, and Safari 3 for PC or Mac we're talking about - but more broadly, any browser that doesn't support or refuses to allow the javascript window.open function.)</p>
| [
{
"answer_id": 313315,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 3,
"selected": true,
"text": "wmode='opaque' wmode='transparent' <div> <div> onclick"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14026/"
] |
312,880 | <p>On a more abstract level then <a href="https://stackoverflow.com/questions/299729/javascript-to-flash-communication">a previous question</a>, in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.</p>
<p>Let's compare and contrast these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface <em>seems</em> like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?</p>
| [
{
"answer_id": 318555,
"author": "Brian Hodge",
"author_id": 20628,
"author_profile": "https://Stackoverflow.com/users/20628",
"pm_score": 3,
"selected": false,
"text": "ExternaInterface navigatoToURL fscommand flash.external.ExternalInterface flash.system.fscommand flash.net.navigateToURL"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14026/"
] |
312,881 | <p>How do I actually run a file on localhost?
I know it is working, but how do I run a file on it, and how do I verify that the file is in fact running on localhost?</p>
<p><strong>Server newbie here, additional questions (I have xampp running Apache 2.2):</strong>
From your responses it sounds like I have to type in the path in the browser in order to open the file on the localhost. So, if I want to have the file in a subdirectory, I would have to type the full path including the directory? </p>
<p>Is there a way to have the browser point to the localhost while I am working on my html, instead of having to type in the path all the time?</p>
<p>I am working in Dreamweaver CS3, and want to use <strong>include</strong> commands (either SSI or PHP), but not have to keep putting my files up on HostGator in order to see if they are working.</p>
<p>What is the best way to do this (please be specific, I know nothing). If there is a detailed tutorial anywhere, really appreciate a link.</p>
<p>Thank you</p>
| [
{
"answer_id": 312886,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 5,
"selected": false,
"text": "http://localhost index.html index.php http://localhost/mytutorial http://localhost/mytutorial\n c:/webservices/apache/www\n c:/xampp/htdocs\n"
},
{
"answer_id": 312889,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 2,
"selected": false,
"text": "system exec"
},
{
"answer_id": 42056001,
"author": "shubhshrma",
"author_id": 7171297,
"author_profile": "https://Stackoverflow.com/users/7171297",
"pm_score": 0,
"selected": false,
"text": "localhost/ localhost/"
},
{
"answer_id": 57916407,
"author": "Yagnik Patel",
"author_id": 11970166,
"author_profile": "https://Stackoverflow.com/users/11970166",
"pm_score": 3,
"selected": false,
"text": "php -S localhost:8888\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40091/"
] |
312,895 | <p>Can someone explain in simple terms the "signals and slots" pattern?</p>
| [
{
"answer_id": 312914,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "signal buttonPressed(IdType) sendMail(IdType) IdType connect(signal, slot) buttonPressed(IdType) sendMail(IdType)"
},
{
"answer_id": 312917,
"author": "Julien Oster",
"author_id": 40111,
"author_profile": "https://Stackoverflow.com/users/40111",
"pm_score": 3,
"selected": false,
"text": "checkboxToggled -> beep\ncheckboxSet -> messageAppear\ncheckboxUnset -> messageDisappear\n"
},
{
"answer_id": 43832205,
"author": "AturSams",
"author_id": 984975,
"author_profile": "https://Stackoverflow.com/users/984975",
"pm_score": 1,
"selected": false,
"text": "slots signal slots"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
312,912 | <p>Given a list of sets:</p>
<ul>
<li>S_1 : [ 1, 2, 3, 4 ]</li>
<li>S_2 : [ 3, 4, 5, 6, 7 ]</li>
<li>S_3 : [ 8, 9, 10, 11 ]</li>
<li>S_4 : [ 1, 8, 12, 13 ]</li>
<li>S_5 : [ 6, 7, 14, 15, 16, 17 ]</li>
</ul>
<p>What the most efficient way to merge all sets that share at least 2 elements? I suppose this is similar to a connected components problem. So the result would be:</p>
<ul>
<li>[ 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17] (S_1 UNION S_2 UNION S_5)</li>
<li>[ 8, 9, 10, 11 ]</li>
<li>[ 1, 8, 12, 13 ] (S_4 shares 1 with S_1, and 8 with S_3, but not merged because they only share one element in each)</li>
</ul>
<p>The naive implementation is O(N^2), where N is the number of sets, which is unworkable for us. This would need to be efficient for millions of sets.</p>
| [
{
"answer_id": 313012,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 3,
"selected": true,
"text": "Let there be a list of many Sets named (S)\n\nPerform a pass through all elements of S, to determine the range (LOW .. HIGH).\n\nCreate an array of pointer to Set, of dimensions (LOW, HIGH), named (M).\n\ndo\n Init all elements of M to NULL. \n\n Iterate though S, processing them one Set at a time, named (Si).\n\n Permutate all ordered pairs in Si. (P1, P2) where P1 <= P2.\n For each pair examine M(P1, P2)\n if M(P1, P2) is NULL\n Continue with the next pair.\n otherwise\n Merge Si, into the Set pointed to by, M(P1, P2).\n Remove Si from S, as it has been merged.\n Move on to processing Set S(i + 1)\n\n If Si was not merged, \n Permutate again through Si\n For each pair, make M(P1, P2) point to Si.\n\nwhile At least one set was merged during the pass.\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21339/"
] |
312,915 | <p>I've been trying to solve this for weeks...</p>
<p>My Goal is to search my inbox for the following messages:</p>
<pre><code>Hello
Hi
Hey
</code></pre>
<p>Im using three files to do this for me. The first, a .forward file in my $HOME</p>
<pre><code>"|IFS=' '&&exec usr/bin/procmail||exit 75 #username"
</code></pre>
<p>And these two are in my ~/.procmail directory</p>
<pre><code>.procmailrc
VERBOSE=off
MAILDIR=$HOME/Mail
PMDIR=$HOME/.procmail
DEFAULT=/var/spool/mail/username
LOGFILE=$PMDIR/log
INCLUDERC=$PMDIR/general.rc
#end of .procmailrc
</code></pre>
<p>And lastly the rule file: general.rc</p>
<pre><code>:0
* ^From:.*sumone@sumaddy.com
* ^Subject:.*hello
$HOME/Mail/Hello
</code></pre>
<p>What's supposed to happen is that all three of these files work together to copy and move mail that contain the hello pattern in its subject. And to be safe it will also look for a certain persons address. Then when those patterns are matched it will stick what it found and create the specified path; if it doesn't already exist.</p>
<p>But its not doing that.
After I'm done editing these files in emacs, vi, .. and then save it, will it work automatically? Or do I need to compile it?</p>
<p>If I do, the .procmailrc might require ( if not all ) the 'Shell=/bin/sh'</p>
<p>Not that I didn't try that...</p>
<hr>
<p>No, my poorly developed design is to process incoming mail..</p>
<p>I've tested it, by sending emails to myself. </p>
<p>What i think, is that my General.RC file isnt coded write. Because, directly after i send myself an email, it SHOULD copy and move it to the specified directory.</p>
<hr>
<p>Its no wonder that i've made those mistakes, i've edited all three of these files a milllllion times.</p>
<p>Nothing is displayed in my LOG file...</p>
<p>I've fixed everything else and i know my /usr/bin/procmail exists because i used whereis to see its path.</p>
<p>But my testing still fails. I keep sending myself emails and checking my Mail Folder to see if the bytes in my "Hello" file have increased.. </p>
<p>How can i get the log to work?
Is the general.rc wrong?</p>
| [
{
"answer_id": 312949,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "|procmail"
},
{
"answer_id": 332740,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 1,
"selected": false,
"text": "VERBOSE=on\nLOGFILE=/tmp/procmail.log\n\n:0 fhbw\n| sed \"s/^Subject:/& --procmail working--/\"\n"
},
{
"answer_id": 7358616,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 1,
"selected": false,
"text": "fgrep"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40120/"
] |
312,922 | <p>I am working on a silverlight app that you need to enter information into a textbox and then just hit enter. Well there is no onclick event, that I could find, so what I did was use the onkeypressup event and check if it was the enter key that was pressed if so do "blah".</p>
<p>It just feels like there is a better way to do this. So the question is, is there?</p>
| [
{
"answer_id": 6662485,
"author": "Dublx",
"author_id": 840465,
"author_profile": "https://Stackoverflow.com/users/840465",
"pm_score": 3,
"selected": false,
"text": " private void MyTextBox_KeyUp(object sender, KeyEventArgs e)\n {\n if (e.Key == Key.Enter) SomeButton_Click(this, null);\n\n }\n\n private void SomeButton_Click(object sender, RoutedEventArgs e)\n {\n ICommand cmd = SomeButton.Command;\n if (cmd.CanExecute(null))\n {\n cmd.Execute(null);\n }\n }\n"
},
{
"answer_id": 10898076,
"author": "slfan",
"author_id": 599668,
"author_profile": "https://Stackoverflow.com/users/599668",
"pm_score": 1,
"selected": false,
"text": "private void MyTextBox_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Key == Key.Enter)\n {\n BindingExpression b = MyTextBox.GetBindingExpression(TextBox.TextProperty); \n if (b != null)\n b.UpdateSource();\n\n ICommand cmd = SomeButton.Command;\n if (cmd.CanExecute(null))\n cmd.Execute(null);\n }\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23571/"
] |
312,925 | <p>I want to add some <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a>-niceness to my Django-coded website. </p>
<p>In my Django code, I use the <code>@login_required</code> decorator from <code>django.contrib.auth.decorators</code> to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page. </p>
<p>What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering.</p>
<p>So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their <code>onclick</code> event and display a "please log in" popup? </p>
| [
{
"answer_id": 313015,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "LINK_VIA onClick=\"return popup(this, 'arg')\" None <A HREF=\"link\" {{LINK_VIA}}>some text</a> LINK_VIA LINK_VIA {% if %} <A HREF=...> {% link_via %}"
},
{
"answer_id": 313074,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 3,
"selected": false,
"text": "<a href=\"{{link}}\" onclick=\"return login_popup()\"> \n django.core.urlresolvers"
},
{
"answer_id": 523196,
"author": "Eric Walker",
"author_id": 61048,
"author_profile": "https://Stackoverflow.com/users/61048",
"pm_score": 7,
"selected": true,
"text": "from functools import wraps\n\ndef ajax_login_required(view_func):\n @wraps(view_func)\n def wrapper(request, *args, **kwargs):\n if request.user.is_authenticated():\n return view_func(request, *args, **kwargs)\n json = simplejson.dumps({ 'not_authenticated': True })\n return HttpResponse(json, mimetype='application/json')\n return wrapper\n @ajax_login_required\ndef ajax_update_module(request, module_slug, action):\n # Etc ...\n return HttpResponse(json, mimetype='application/json')\n $.post('/restricted-url/', data, function(json) {\n if (json.not_authenticated) {\n alert('Not authorized.'); // Or something in a message DIV\n return;\n }\n // Etc ...\n});\n functools.wraps"
},
{
"answer_id": 39063319,
"author": "Mohamed Ould El Kory",
"author_id": 6740177,
"author_profile": "https://Stackoverflow.com/users/6740177",
"pm_score": 1,
"selected": false,
"text": "from functools import wraps\n\ndef ajax_login_required(function):\n def wrap(request, *args, **kwargs):\n if request.user.is_authenticated():\n return function(request, *args, **kwargs)\n json = simplejson.dumps({ 'not_authenticated': True })\n return HttpResponse(json, mimetype='application/json') \n wrap.__doc__ = function.__doc__\n wrap.__name__ = function.__name__\n return wrap\n"
},
{
"answer_id": 49051524,
"author": "Warren Spencer",
"author_id": 5044937,
"author_profile": "https://Stackoverflow.com/users/5044937",
"pm_score": 2,
"selected": false,
"text": "# Standard Imports\nimport functools\nimport django.http\n\ndef ajax_login_required(view_func):\n @functools.wraps(view_func)\n def wrapper(request, *args, **kwargs):\n if request.user.is_authenticated:\n return view_func(request, *args, **kwargs)\n\n return django.http.JsonResponse('Unauthorized', status=401, safe=False)\n\n return wrapper\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
312,936 | <p>I am using C# and Windows Forms. I have a normal progress bar working fine in the program, but now I have another operation where the duration cannot be easily calculated. I would like to display a progress bar but don't know the best way to start/stop the scrolling marquee. I was hoping for something as simple as setting the marquee speed and then having a start() and stop() but it doesn't appear to be that simple. Do I have to run an empty loop in the background? How do I best do this? Thanks</p>
| [
{
"answer_id": 312999,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 8,
"selected": true,
"text": "Marquee myProgressBar.Style = ProgressBarStyle.Marquee;\n MarqueeAnimationSpeed"
},
{
"answer_id": 607481,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "progressBar1.Style = ProgressBarStyle.Marquee;\nprogressBar1.MarqueeAnimationSpeed = 30;\n progressBar1.Style = ProgressBarStyle.Continuous;\nprogressBar1.MarqueeAnimationSpeed = 0;\n"
},
{
"answer_id": 6701081,
"author": "Arda Basoglu",
"author_id": 404577,
"author_profile": "https://Stackoverflow.com/users/404577",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace LoginWithProgressBar\n{\n public partial class TheForm : Form\n {\n // BackgroundWorker object deals with the long running task\n private readonly BackgroundWorker _bw = new BackgroundWorker();\n\n public TheForm()\n {\n InitializeComponent();\n\n // set MarqueeAnimationSpeed\n progressBar.MarqueeAnimationSpeed = 30;\n\n // set Visible false before you start long running task\n progressBar.Visible = false;\n\n _bw.DoWork += Login;\n _bw.RunWorkerCompleted += BwRunWorkerCompleted;\n }\n\n private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n // hide the progress bar when the long running process finishes\n progressBar.Hide();\n }\n\n private static void Login(object sender, DoWorkEventArgs doWorkEventArgs)\n {\n // emulate long (3 seconds) running task\n Thread.Sleep(3000);\n }\n\n private void ButtonLoginClick(object sender, EventArgs e)\n {\n // show the progress bar when the associated event fires (here, a button click)\n progressBar.Show();\n\n // start the long running task async\n _bw.RunWorkerAsync();\n }\n }\n} \n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25946/"
] |
312,957 | <p>Is there a way to use these operators to input and output binary data? The reason I want to do this is that it makes the code readable.
Ex: infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;</p>
| [
{
"answer_id": 312959,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "operator<< operator>> class transformer {\n public:\n virtual std::iostream& transform(std::iostream&) = 0;\n};\n\nclass noise : public transformer {\n public:\n virtual std::iostream& transform(std::iostream&) {\n /* extract, change and put into again */\n }\n};\n\n\nclass echo : public transformer {\n public:\n virtual std::iostream& transform(std::iostream&) {\n /* extract, change and put into again */\n }\n};\n\nstd::iostream& operator>>(std::iostream& io, transformer& ts) {\n return ts.transform(io);\n}\n\nint main() {\n std::stringstream data;\n std::ifstream file(\"sound.wav\");\n\n noise n; echo e;\n\n data << file.rdbuf();\n data >> n >> e;\n /* pipelined data now ready to be played back */\n}\n std::istream std::iostream expression template operator>> typedef transform< echo< noise< istream > > > pipeline;\nstd::ifstream file(\"file.wav\");\npipeline pipe(file);\nint byte = pipe.get();\n #include <iostream>\n\ntemplate<typename T>\nstruct transformer {\n int get() {\n return static_cast<T*>(this)->read();\n }\n};\n\nstruct echot {\n template<typename Chain>\n struct chain : transformer< chain<Chain> > {\n Chain c;\n\n int read() {\n return c.get() + 1;\n }\n\n chain(Chain const& c):c(c) { }\n };\n} echo;\n\nstruct noiset {\n template<typename Chain>\n struct chain : transformer< chain<Chain> > {\n Chain c;\n\n int read() {\n return c.get() * 2;\n }\n\n chain(Chain c):c(c) { }\n };\n} noise;\n\n\ntemplate<typename T>\ntypename T::template chain<std::istream&> operator>>(std::istream& is, T) {\n return typename T::template chain<std::istream&>(is);\n}\n\ntemplate<typename T, typename U>\ntypename U::template chain<T> operator>>(T t, U u) {\n return typename U::template chain<T>(t);\n}\n\nint main() {\n std::cout << (std::cin >> echo >> noise).get() << std::endl;\n}\n"
},
{
"answer_id": 312972,
"author": "njsf",
"author_id": 4995,
"author_profile": "https://Stackoverflow.com/users/4995",
"pm_score": 2,
"selected": false,
"text": "istream& operator>> (istream& is, T& t)\n{\n t.fromStream(is);\n return t;\n}\n\nostream& operator<< (ostream& os, const T& t)\n{\n t.toStream(os);\n return t;\n}\n"
},
{
"answer_id": 313035,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 2,
"selected": false,
"text": "#include <iostream> \n#include <istream> \nusing namespace std; \n\nclass Data2 \n{ \n}; \n\nclass Data3 \n{ \n}; \n\nclass Decrypt \n{ \n}; \n\nclass MetaDataParser \n{ \n}; \n\nData2& operator>>(istream& in, Decrypt& decrypt) \n{ \n return *new Data2; \n} \n\nData3& operator>>(Data2& d2, MetaDataParser& mdp) \n{ \n return *new Data3; \n} \n\nint main() \n{ \n Decrypt decrypt; \n MetaDataParser mdp; \n\n cin >> decrypt >> mdp; \n} \n"
},
{
"answer_id": 313037,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 2,
"selected": false,
"text": "infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760/"
] |
312,967 | <p>I am trying to fade in a <p> on mouseover and fade out on mouseout:</p>
<pre><code> $("p.follow").mouseover(function(){
$(this).fadeTo("slow", 1.00);
})
$("p.follow").mouseout(function(){
$(this).fadeTo("fast", 0.50);
})
</code></pre>
<p>If you go to ryancoughlin.com and on the right side, if you go over it you will see what I mean, it is almost as if it is stuck and keeps fading in.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 312975,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": true,
"text": "$(\"p.follow\").hover(function()\n {\n $(this).stop().fadeTo(\"slow\", 1.00);\n },\n function()\n {\n $(this).stop().fadeTo(\"fast\", 0.50);\n });\n hover stop()"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,983 | <p>I have configured a simple LAMP stack on Debian and I am experiencing some problems with the Apache web server. </p>
<p>Each 3-4 hours the web server is entering a deadlock and all the requests that hit the database block. The server is creating a new child for each request. The number of processes increases very quickly. After a few seconds Monit notices something is wrong and restarts the Apache server.</p>
<p>I suspect this problem is generated by the way PHP handles database connection pooling because the server is still able to answer static content requests. Have you experienced this kind of behavior? What should I try to do?</p>
<p><strong>Update:</strong> Problem solved. It seems it's a bad idea to use APC for opcode caching and user data. I am now using Memcache for storing user data and APC only for code. I still get some segmentation faults from time to time but the server is most of the time stable.</p>
| [
{
"answer_id": 313000,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 1,
"selected": false,
"text": "/var/log/apache2/*"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3885/"
] |
312,989 | <p>I have a HTML with the following content:</p>
<pre><code>... some text ...
<a href="file.aspx?userId=123&section=2">link</a> ... some text ...
... some text ...
<a href="file.aspx?section=5&user=678">link</a> ... some text ...
... some text ...
</code></pre>
<p>I would like to parse that and get a match with named groups:</p>
<p><strong>match 1</strong></p>
<p>group["user"]=123</p>
<p>group["section"]=2</p>
<p><strong>match 2</strong></p>
<p>group["user"]=678</p>
<p>group["section"]=5</p>
<p>I can do it if parameters always go in order, first User and then Section, but I don't know how to do it if the order is different.</p>
<p>Thank you!</p>
| [
{
"answer_id": 313099,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\\<a\\s+href\\s*=\\s*[\"'](?<baseUri>.+?)\\?(?:(?<key>.+?)=(?<value>.+?)[&\"'])*\\s*\\>\n"
},
{
"answer_id": 313106,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 0,
"selected": false,
"text": "/href=\"[^?]*([?&](userId=(?<user>\\d+))|section=(?<section>\\d+))*\"/\n"
},
{
"answer_id": 313138,
"author": "Mike Moore",
"author_id": 2645,
"author_profile": "https://Stackoverflow.com/users/2645",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace RegexTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n string subjectString = @\"... some text ...\n <a href=\"\"file.aspx?userId=123§ion=2\"\">link</a> ... some text ...\n... some text ...\n<a href=\"\"file.aspx?section=5&user=678\"\">link</a> ... some text ...\n... some text ...\";\n Regex regexObj = \n new Regex(@\"<a href=\"\"file.aspx\\?(?:(?:userId=(?<user>.+?)§ion=(?<section>.+?)\"\")|(?:section=(?<section>.+?)&user=(?<user>.+?)\"\"))\");\n Match matchResults = regexObj.Match(subjectString);\n while (matchResults.Success)\n {\n string user = matchResults.Groups[\"user\"].Value;\n string section = matchResults.Groups[\"section\"].Value;\n Console.WriteLine(string.Format(\"User = {0}, Section = {1}\", user, section));\n matchResults = matchResults.NextMatch();\n }\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 313497,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "Regex r = new Regex(@\"<a href=\"\"file\\.aspx\\?\" +\n @\"(?=[^\"\"<>]*?user=(?<user>\\w+))\" +\n @\"(?=[^\"\"<>]*?section=(?<section>\\w+))\";\n"
},
{
"answer_id": 313751,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 0,
"selected": false,
"text": "userID=(?<user>\\d+)§ion=(?<section>\\d+)|section=(?<section>\\d+)&userID=(?<user>\\d+)\n"
},
{
"answer_id": 314240,
"author": "altunyurt",
"author_id": 37491,
"author_profile": "https://Stackoverflow.com/users/37491",
"pm_score": 0,
"selected": false,
"text": "In [2]: x = re.compile('(?:(userId|section)=(\\d+))+')\n\nIn [3]: t = 'href=\"file.aspx?section=2&userId=123\"'\n\nIn [4]: x.findall(t)\nOut[4]: [('section', '2'), ('userId', '123')]\n\nIn [5]: t = 'href=\"file.aspx?userId=123§ion=2\"'\n\nIn [6]: x.findall(t)\nOut[6]: [('userId', '123'), ('section', '2')]\n"
},
{
"answer_id": 8854209,
"author": "hmadrigal",
"author_id": 500134,
"author_profile": "https://Stackoverflow.com/users/500134",
"pm_score": 3,
"selected": false,
"text": "public static class UriExtensions\n{\n private static readonly Regex queryStringRegex;\n static UriExtensions()\n {\n queryStringRegex = new Regex(@\"[\\?&](?<name>[^&=]+)=(?<value>[^&=]+)\");\n }\n\n public static IEnumerable<KeyValuePair<string, string>> ParseQueryString(this Uri uri)\n {\n if (uri == null)\n throw new ArgumentException(\"uri\");\n\n var matches = queryStringRegex.Matches(uri.OriginalString);\n for (int i = 0; i < matches.Count; i++)\n {\n var match = matches[i];\n yield return new KeyValuePair<string, string>(match.Groups[\"name\"].Value, match.Groups[\"value\"].Value);\n }\n }\n}\n var uri = new Uri(HttpUtility.UrlDecode(@\"file.aspx?userId=123§ion=2\"),UriKind.RelativeOrAbsolute);\n var parameters = uri.ParseQueryString().ToDictionary( kvp => kvp.Key, kvp => kvp.Value);\n var userId = parameters[\"userId\"];\n var section = parameters[\"section\"];\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,004 | <p>When working in a big project that requires debugging (like every project) you realize how much people love "printf" before the IDE's built-in debugger. By this I mean</p>
<ul>
<li>Sometimes you need to render variable values to screen (specially for interactive debugging).</li>
<li>Sometimes to log them in a file</li>
<li>Sometimes you have to change the visibility (make them public) just to another class to access it (a logger or a renderer for example).</li>
<li>Some other times you need to save the previous value in a member just to contrast it with the new during debugging</li>
<li>...</li>
</ul>
<p>When a project gets huge with a lot of people working on it, all this debugging-specific code can get messy and hard to differentiate from normal code. This can be crazy for those who have to update/change someone else's code or to prepare it for a release.</p>
<p>How do you solve this?</p>
<p>It is always good to have naming standards and I guess that <em>debug-coding standards</em> should be quite useful (like marking every debug-variable with a _DBG sufix). But I also guess naming is just not enough. Maybe centralizing it into a friendly tracker class, or creating a robust base of macros in order to erase it all for the release. I don't know.</p>
<p><em>What design techniques, patterns and standards would you embrace if you are asked to write a debug-coding document for all others in the project to follow?</em></p>
<p>I am not talking about tools, libraries or IDE-specific commands, but for OO design decisions.</p>
<p>Thanks.</p>
| [
{
"answer_id": 313133,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "Debug.Print\n #If <some var set in the project properties>\n'debugging code\n#End If\n Dim Trc as Std.Traces\n Trc.Tracing = True\nTrc.Tracefile = \"c:\\temp\\app.log\"\nTrc.Trace 'with no argument stores date stamp\nTrc.Trace \"Var=\" & var\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22609/"
] |
313,006 | <p>Is there something similar to <code>sprintf()</code> in C#?</p>
<p>I would for instance like to convert an integer to a 2-byte byte-array.</p>
<p>Something like:</p>
<pre><code>int number = 17;
byte[] s = sprintf("%2c", number);
</code></pre>
| [
{
"answer_id": 313009,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "string s = string.Format(\"{0:00}\", number)\n string byte[] Encoding byte[] raw = Encoding.UTF8.GetBytes(s);\n string s = number.ToString(\"00\");\n string.Format"
},
{
"answer_id": 313032,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 2,
"selected": false,
"text": "byte[] array = BitConverter.GetBytes(17);\n byte[] array = BitConverter.GetBytes((short)17);\n string result = string.Format(\"{0:00}\", 17);\n"
},
{
"answer_id": 313034,
"author": "Markus Johansson",
"author_id": 23423,
"author_profile": "https://Stackoverflow.com/users/23423",
"pm_score": 3,
"selected": true,
"text": "short number = 17;\nSystem.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);\nwriter.Write(number);\nwriter.Flush();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23423/"
] |
313,018 | <p>I see APIs in Quartz for drawing lines and circles. But all I want to do is to specify the (x,y) cartesian coordinate to color a pixel a particular value. How do I do that?</p>
| [
{
"answer_id": 313713,
"author": "Jens Ayton",
"author_id": 6443,
"author_profile": "https://Stackoverflow.com/users/6443",
"pm_score": 4,
"selected": false,
"text": "CGBitmapContextCreate() CGImage CGImageCreate()"
},
{
"answer_id": 322463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "CGContextFillRect(context, CGRectMake(x,y,1,1));\n"
},
{
"answer_id": 8290374,
"author": "Paulo",
"author_id": 1068520,
"author_profile": "https://Stackoverflow.com/users/1068520",
"pm_score": 3,
"selected": false,
"text": "CGContextAddEllipseInRect(Context,(CGRectMake (x_dot, y_dot, 3.0, 3.0));\nCGContextDrawPath(Context, kCGPathFill);\nCGContextStrokePath(Context);\n"
},
{
"answer_id": 43693882,
"author": "Antoine Weber",
"author_id": 7206799,
"author_profile": "https://Stackoverflow.com/users/7206799",
"pm_score": 0,
"selected": false,
"text": " UIRectFill(CGRect(x: x, y: y, width: 1, height: 1))\n UIRectFill()"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,030 | <p>I would like to do something like the following but can't seem to get the syntax for the Do method quite right.</p>
<pre><code>var sqr = new _mocks.CreateRenderer<ShapeRenderer>();
Expect.Call(sqr.CanRender(null)).IgnoreArguments().Do(x =>x.GetType() == typeof(Square)).Repeat.Any();
</code></pre>
<p>So basically, I would like to set up the sqr.CanRender() method to return true if the input is of type Square and false otherwise.</p>
| [
{
"answer_id": 313080,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 3,
"selected": true,
"text": "Expect.Call(sqr.CanRender(null)).IgnoreArguments()\n .Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})\n .Repeat.Any();\n"
},
{
"answer_id": 610040,
"author": "Iain",
"author_id": 5993,
"author_profile": "https://Stackoverflow.com/users/5993",
"pm_score": 2,
"selected": false,
"text": "private delegate bool CanRenderDelegate(Shape shape)\n Expect.Call(sqr.CanRender(null))\n .IgnoreArguments()\n .Do((CanRenderDelegate) delegate(Agent x){return x.GetType() == typeof(Square);})\n .Repeat.Any();\n"
},
{
"answer_id": 1431229,
"author": "Timothy Walters",
"author_id": 14454,
"author_profile": "https://Stackoverflow.com/users/14454",
"pm_score": 1,
"selected": false,
"text": "Expect.Call( sqr.CanRender( Arg<Shape>.Is.TypeOf<Square>() ).Repeat.Any();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
313,036 | <p>Am I doing something wrong or is it not possible to specify a generic class as a constraint to a generic method?</p>
<p>I have been playing around with generics and <a href="http://developer.db4o.com/" rel="nofollow noreferrer">db4o</a> (open source object database) and am writing a test program (see code below) to store and retrieve some user defined generic collections.</p>
<p>I am attempting to write a generic method (see <strong>GetCollectionFromDb</strong> below) to retrieve a specifically typed collection from the database. Unfortunately, the code below returns a compiler generated error for the line:</p>
<pre><code> MyCollection1 collection3 =
GetCollectionFromDb<MyCollection1>(Collection1Name);
</code></pre>
<p>The error message is:</p>
<pre><code>The type 'GenericsTest.MyCollection1'cannot be used as type parameter 'T'
in the generic type or method 'GenericsTest.Program.GetCollectionFromDb<T>(string)'.
There is no implicit reference conversion from'GenericsTest.MyCollection1' to
'GenericsTest.MyCollectionBase<GenericsTest.MyCollection1>'.
</code></pre>
<p>I would appreciate any suggestions as to what I may be doing wrong or how I could approach this differently to reach the deisred outcome.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Db4objects.Db4o;
namespace GenericsTest
{
public class Entity1
{
public string SomeProperty { get; set; }
}
public class Entity2
{
public string SomeProperty { get; set; }
}
public abstract class MyCollectionBase<T> : Collection<T>
{
protected MyCollectionBase() : this("") { }
protected MyCollectionBase(string pCollectionName)
{
CollectionName = pCollectionName;
}
public string CollectionName { get; set; }
}
public class MyCollection1 : MyCollectionBase<Entity1>
{
public MyCollection1(string pCollectionName) :
base(pCollectionName) { }
public void DoSomeWorkOnCollection1() {}
}
public class MyCollection2 : MyCollectionBase<Entity2>
{
public MyCollection2(string pCollectionName) :
base(pCollectionName) { }
public void DoSomeWorkOnCollection2() { }
}
public class Program
{
public static IObjectContainer db = null;
public static void Main(string[] args)
{
const string Collection1Name = "Entity1Collection";
const string Collection2Name = "Entity2Collection";
db = Db4oFactory.OpenFile("Test.db");
Entity1 entity1 = new Entity1();
MyCollection1 collection1 = new MyCollection1(Collection1Name);
collection1.Add(entity1);
db.Store(collection1);
Entity2 entity2 = new Entity2();
MyCollection2 collection2 = new MyCollection2(Collection2Name);
collection1.Add(entity1);
db.Store(collection2);
db.Commit();
db.Close();
db = Db4oFactory.OpenFile("Test.db");
MyCollection1 collection3 =
GetCollectionFromDb<MyCollection1>(Collection1Name);
}
private static T GetCollectionFromDb<T>(string pCollectionName)
where T : MyCollectionBase<T>
{
IList<T> queryResult = db.Query((T c) =>
c.CollectionName == pCollectionName);
if (queryResult.Count != 0) return queryResult[0];
return null;
}
}
}
</code></pre>
| [
{
"answer_id": 313044,
"author": "Brian B.",
"author_id": 21817,
"author_profile": "https://Stackoverflow.com/users/21817",
"pm_score": 3,
"selected": true,
"text": " // ...\n {\n //...\n MyCollection1 collection3 = GetCollectionFromDb<MyCollection1>(Collection1Name);\n\n }\n\n private static T GetCollectionFromDb<T>(string pCollectionName) where T : MyCollectionBase<T>\n {\n IList<T> queryResult = db.Query((T c) => c.CollectionName == pCollectionName);\n if (queryResult.Count != 0) return queryResult[0];\n return null;\n }\n private static MyCollection1 GetCollectionFromDb<MyCollection1>(string pCollectionName) where T : MyCollectionBase< MyCollection1 >\n {\n IList< MyCollection1 > queryResult = db.Query((MyCollection1 c) => c.CollectionName == pCollectionName);\n if (queryResult.Count != 0) return queryResult[0];\n return null;\n }\n"
},
{
"answer_id": 313060,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "MyCollection1 MyCollection<Entity1> MyCollection<MyCollection1> private static T GetCollectionFromDb<T, U>(string pCollectionName) \n where T : MyCollectionBase<U>\n GetCollectionFromDb<MyCollection1, Entity1>(Collection1Name);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2645/"
] |
313,047 | <p>I've been frustrated by this for the entire weekend, plus a day or two, so any help would be significantly appreciated.</p>
<p>I'm trying to write a program that can programmatically go into a SharePoint 2007 doc library, open a file, change the contents of the file, then put the file back. I've gotten all but the last part of this down. The reason Office Open XML is involved is that that's how I'm opening the document and modifying it - through the Office Open XML SDK. My question is: How do I get it from the document back into the library?</p>
<p>The problem as I see it is that there's no save function on the WordprocessingDocument object itself. This prevents me from saving it into the SPFile's SaveBinary function.</p>
| [
{
"answer_id": 314236,
"author": "user4531",
"author_id": 4531,
"author_profile": "https://Stackoverflow.com/users/4531",
"pm_score": 3,
"selected": true,
"text": "Stream fs = mySPFile.OpenBinaryStream();\n\nusing (WordprocessingDocument ooxmlDoc = WordprocessingDocument.Open(fs, true))\n{\n\n MainDocumentPart mainPart = wordDoc.MainDocumentPart;\n XmlDocument xmlMainDocument = new XmlDocument();\n xmlMainDocument.Load(mainPart.GetStream());\n\n // change the contents of the ooxmlDoc / xmlMainDocument\n\n Stream stream = mainPart.GetStream(FileMode.Open, FileAccess.ReadWrite);\n xmlMainDocument.Save(stream);\n // the stream should not be longer than the DocumentPart\n stream.SetLength(stream.Position); \n}\nmySPFile.SaveBinary(fs);\nfs.Dispose();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29227/"
] |
313,049 | <p>This fails with 'X.m is not a function'...</p>
<pre><code>var Y = function () {
this.m = function () {
alert('this is m');
};
};
var X = new function () { };
X.prototype = new Y();
X.m();
</code></pre>
<p>It would certainly work if I skipped the new keyword in the X definition and then instantiated X before calling m() on it. Why can't I do it this way?</p>
| [
{
"answer_id": 313056,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 2,
"selected": false,
"text": "var X = new function () { };\nalert(X.prototype); // displays \"undefined\" because X is an \n // object not a class\n var Y = function () {\n this.m = function () {\n alert('this is m');\n };\n};\n\nvar X = new function () { };\nX.prototype = new Y();\nX.prototype.m(); // displays \"this is m\"\n X.constructor.prototype.m = new Y().m;\nX.m(); // displays \"this is m\"\n X.constructor.prototype = new Y();\nX.m(); // fails\n"
},
{
"answer_id": 313064,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "object function alert(typeof Y); alert(typeof X); X.prototype.m()"
},
{
"answer_id": 313101,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 1,
"selected": false,
"text": "var Y = function () {\n this.m = function () {\n alert('this is m');\n };\n};\n\nvar X = function () { };\nX.prototype = new Y();\n\nnew X().m();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,054 | <p>(Django 1.x, Python 2.6.x)</p>
<p>I have models to the tune of:</p>
<pre><code>class Animal(models.Model):
pass
class Cat(Animal):
def __unicode__(self):
return "This is a cat"
class Dog(Animal):
def __unicode__(self):
return "This is a dog"
class AnimalHome(models.Model):
animal = models.ForeignKey(Animal)
</code></pre>
<p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p>
<hr>
<p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p>
<hr>
<p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p>
<pre><code>Class Animal(models.Model)
def __unicode__(self):
if Dog.objects.filter(pk=self.pk).count() > 0:
return unicode(Dog.objects.get(pk=self.pk))
elif Cat.objects.filter(pk=self.pk).count() > 0:
return unicode(Cat.objects.get(pk=self.pk))
else:
return "An Animal!"
</code></pre>
<hr>
<p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
| [
{
"answer_id": 313105,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "class CommonInfo(models.Model):\n name = models.CharField(max_length=100)\n age = models.PositiveIntegerField()\n\n class Meta:\n abstract = True\n AnimalHome animals Animal.objects.get(pk=42) Dog.objects.get(pk=42) Cat.objects.get(pk=42) KIND_CHOICES = (\n ( \"DOG\", \"Dog\" ),\n ( \"CAT\", \"Cat\" ),\n)\n\nclass Animal( models.Model ):\n kind = models.CharField( max_length= 1, choices=KIND_CHOICES )\n fk = models.IntegerField()\n def get_kind( self ):\n if kind == \"DOG\":\n return Dog.objects.get( pk = fk )\n elif kind == \"CAT\":\n return Cat.objects.get( pk = fk )\n"
},
{
"answer_id": 314030,
"author": "taleinat",
"author_id": 40076,
"author_profile": "https://Stackoverflow.com/users/40076",
"pm_score": 2,
"selected": false,
"text": "class Cat(models.Model):\n def __unicode__(self):\n return u'A Cat!'\n\nclass Dog(models.Model):\n def __unicode__(self):\n return u'A Dog!' \n\nclass Eel(models.Model):\n def __unicode__(self):\n return u'An Eel!' \n\nANIMALS = {\n 'CAT': {'model': Cat, 'name': 'Cat'},\n 'DOG': {'model': Dog, 'name': 'Dog'},\n 'EEL': {'model': Eel, 'name': 'Eel'},\n}\nKIND_CHOICES = tuple((key, ANIMALS[key]['name']) for key in ANIMALS)\n\nclass Animal(models.Model):\n kind = models.CharField(max_length=3, choices=KIND_CHOICES)\n fk = models.IntegerField()\n def get_kind(self):\n return ANIMALS[self.kind]['model'].objects.get(pk=self.fk)\n def __unicode__(self):\n return unicode(self.get_kind())\n ANIMALS = {\n 'CAT': {'model_name': 'Cat', 'name': 'Cat'},\n 'DOG': {'model_name': 'Dog', 'name': 'Dog'},\n 'EEL': {'model_name': 'Eel', 'name': 'Eel'},\n}\nKIND_CHOICES = tuple((key, ANIMALS[key]['name']) for key in ANIMALS)\n\nclass Animal(models.Model):\n kind = models.CharField(max_length=3, choices=KIND_CHOICES)\n def get_kind(self):\n return getattr(self, ANIMALS[self.kind]['model_name'].lower())\n def __unicode__(self):\n return unicode(self.get_kind())\n\nclass Cat(Animal):\n def __unicode__(self):\n return u'A Cat!'\n\nclass Dog(Animal):\n def __unicode__(self):\n return u'A Dog!' \n\nclass Eel(Animal):\n def __unicode__(self):\n return u'An Eel!' \n"
},
{
"answer_id": 314719,
"author": "lawrence",
"author_id": 56817,
"author_profile": "https://Stackoverflow.com/users/56817",
"pm_score": 4,
"selected": true,
"text": "class Animal(models.Model):\n def __unicode__(self):\n if hasattr(self, 'dog'):\n return self.dog.__unicode__()\n elif hasattr(self, 'cat'):\n return self.cat.__unicode__()\n else:\n return 'Animal'\n"
},
{
"answer_id": 316717,
"author": "taleinat",
"author_id": 40076,
"author_profile": "https://Stackoverflow.com/users/40076",
"pm_score": 1,
"selected": false,
"text": "# This will fail\n>>> TaggedItem.objects.filter(content_object=guido)\n# This will also fail\n>>> TaggedItem.objects.get(content_object=guido)\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39396/"
] |
313,070 | <p>Hey having some trouble trying to maintain transparency on a png when i create a thumbnail from it, anyone any experience with this? any help would be great, here's what i am currently doing:</p>
<pre><code>$fileName= "../js/ajaxupload/tees/".$fileName;
list($width, $height) = getimagesize($fileName);
$newwidth = 257;
$newheight = 197;
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagesavealpha($thumb, true);
imagepng($thumb,$newFilename);
</code></pre>
| [
{
"answer_id": 313103,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 7,
"selected": true,
"text": "$thumb = imagecreatetruecolor($newwidth, $newheight);\nimagealphablending($thumb, false);\nimagesavealpha($thumb, true); \n\n$source = imagecreatefrompng($fileName);\nimagealphablending($source, true);\n\nimagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);\n\nimagepng($thumb,$newFilename);\n imagecopyresampled() imagecopyresized()"
},
{
"answer_id": 5083894,
"author": "user629089",
"author_id": 629089,
"author_profile": "https://Stackoverflow.com/users/629089",
"pm_score": 4,
"selected": false,
"text": "$image = imagecreatetruecolor($size, $size);\n\nimagealphablending($image, false);\nimagesavealpha($image, true);\n\n$trans_layer_overlay = imagecolorallocatealpha($image, 220, 220, 220, 127);\nimagefill($image, 0, 0, $trans_layer_overlay);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40141/"
] |
313,111 | <p>What is the equivalent of <code>/dev/null</code> on Windows?</p>
| [
{
"answer_id": 313115,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 10,
"selected": true,
"text": "NUL type c:\\autoexec.bat > NUL\n $null echo 1 > $null\n"
},
{
"answer_id": 313118,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 6,
"selected": false,
"text": "#include <stdio.h>\n\nint main ()\n{\n FILE* outfile = fopen (\"/dev/null\", \"w\");\n if (outfile == NULL)\n {\n fputs (\"could not open '/dev/null'\", stderr);\n }\n outfile = fopen (\"nul\", \"w\");\n if (outfile == NULL)\n {\n fputs (\"could not open 'nul'\", stderr);\n }\n\n return 0;\n}\n"
},
{
"answer_id": 27773642,
"author": "Jerry",
"author_id": 2837824,
"author_profile": "https://Stackoverflow.com/users/2837824",
"pm_score": 6,
"selected": false,
"text": "NUL .. . echo 1 > nul\necho 1 > c:\\nul\necho 1 > c:\\users\\nul\necho 1 > c:\\windows\\nul\n /dev/null"
},
{
"answer_id": 44163934,
"author": "avadin",
"author_id": 4452515,
"author_profile": "https://Stackoverflow.com/users/4452515",
"pm_score": 4,
"selected": false,
"text": "NUL freopen(\"NUL\", \"w\", stderr);\n"
},
{
"answer_id": 47603308,
"author": "Haseeb Mir",
"author_id": 6219626,
"author_profile": "https://Stackoverflow.com/users/6219626",
"pm_score": 0,
"selected": false,
"text": "mySum 5 10 start .\\mySum 5 10 > $NUL 2>&1\n start & /B NUL /dev/null 2>&1 NUL"
},
{
"answer_id": 50652314,
"author": "Marco",
"author_id": 3320401,
"author_profile": "https://Stackoverflow.com/users/3320401",
"pm_score": 4,
"selected": false,
"text": "/dev/null cmd mklink c:\\path\\to\\file.ext NUL:\n mklink /D c:\\path\\to\\dir NUL:\n"
},
{
"answer_id": 72211645,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 1,
"selected": false,
"text": "robocopy .\\test NUL /move /minage:30 \n# delete all files older than 30 days using robocopy\n ERROR 123 (0x0000007B) Accessing Destination Directory \\\\.\\NUL\\\nThe filename, directory name, or volume label syntax is incorrect.\n cmd.exe echo 1 > NUL\n NUL /dev/null robocopy robocopy .\\test NUL\\null /move /minage:30 \n $null echo 1 > $null\n $null $null\\null cmd.exe mkdir test1\ncd test1\necho \"\" > test1.txt\necho \"\" > test2.txt\necho \"\" > test3.txt\n\n$path = '.\\test1'\ncmd.exe /c \"robocopy $path NUL\\null /move\"\n\n# also this works:\ncmd.exe /c \"robocopy $path .\\NUL\\null /move\"\n NUL /dev/null > cmd.exe NUL"
},
{
"answer_id": 74638743,
"author": "jetnet",
"author_id": 10390714,
"author_profile": "https://Stackoverflow.com/users/10390714",
"pm_score": 0,
"selected": false,
"text": "NUL copy /b for /f \"delims=\" %f in ('dir /s /b /a-d D:\\Solr\\data') do @copy /b \"%f\" nul > nul\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40145/"
] |
313,124 | <p>How do I expose the <code>ActualWidth</code> property of one of the components of my user control to users?</p>
<p>I have found plenty of examples of how to expose a normal property by creating a new dependency property and binding, but none on how to expose a read-only property like <code>ActualWidth</code>.</p>
| [
{
"answer_id": 313619,
"author": "ligaz",
"author_id": 6409,
"author_profile": "https://Stackoverflow.com/users/6409",
"pm_score": 0,
"selected": false,
"text": "ActualWidth FrameworkElement"
},
{
"answer_id": 317699,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 4,
"selected": true,
"text": "ActualWidthProperty DependencyPropertyDescriptor // Need to tap into change notification of the FrameworkElement.ActualWidthProperty\nPublic MyUserControl()\n{\n DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty\n (FrameworkElement.ActualWidthProperty, typeof(FrameworkElement));\n descriptor.AddValueChanged(this.MyElement, new EventHandler\n OnActualWidthChanged);\n}\n\n// Dependency Property Declaration\nprivate static DependencyPropertyKey ElementActualWidthPropertyKey = \n DependencyProperty.RegisterReadOnly(\"ElementActualWidth\", typeof(double), \n new PropertyMetadata());\npublic static DependencyProperty ElementActualWidthProperty = \n ElementActualWidthPropertyKey.DependencyProperty;\npublic double ElementActualWidth\n{\n get{return (double)GetValue(ElementActualWidthProperty); }\n}\nprivate void SetActualWidth(double value)\n{\n SetValue(ElementActualWidthPropertyKey, value);\n}\n\n// Dependency Property Callback\n// Called when this.MyElement.ActualWidth is changed\nprivate void OnActualWidthChanged(object sender, Eventargs e)\n{\n this.SetActualWidth(this.MyElement.ActualWidth);\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36074/"
] |
313,127 | <p>From the .net 4.0 previews I have read until now there has been lots of talk on how the next .net version will handle and use cpus with multiple cores. We will have additions like plinq that will help us make use of multiple cores. My question is why should I have to bother my mind with handling multiple cores when all I want is to make my application run faster. Why can't there be a kind of virtual cpu layer that exposes all cores as 1 core to my application? </p>
<p>Edit:
I would like to rephrase my question to avoid misunderstanding,
Could there be made a software that would expose a virtual thread to my application that would be 10 times faster because underlaying it was using 10 cores. I do not want to have different threads doing things in paralell, I just want my one thread running faster. I guess this is not a big problem today but soon we'll have 80 core processors to play with and then I would feel a bit shorthanded only using 1 of them.</p>
| [
{
"answer_id": 834058,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": "int main(int argc, char **argv) {\n const int N = 100000;\n int i, a[N];\n\n #pragma omp parallel for\n for (i = 0; i < N; i++)\n a[i] = 2 * i;\n\n return 0;\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29519/"
] |
313,137 | <p>In my specific case, I have two kinds of "messages" that I need to retrive and paginate.</p>
<p>Let's omit the details, and just say that the first kind is in a model called Msg1 and the other is called Msg2</p>
<p>The fields of these two models are completely different, the only fields that are common to the two models are "date" and "title" (and of course, id).</p>
<p>I can get <code>Msg1.objects.all()</code> and <code>Msg2.objects.all()</code> but can I combine these two queries into one query, sort it by date, and paginate it?</p>
<p>I need to preserve the lazy nature of the query.</p>
<p>The trivial solution is to <code>list(query)</code> both queries and combine them in a python list. but this is inefficient for obvious reasons.</p>
<p>I looked through the django references on models and dp-api, but it doesn't seem that there is a way to combine queries of different models/tables into one.</p>
| [
{
"answer_id": 313149,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "def merge( qs1, qs2 ):\n iqs1= iter(qs1)\n iqs2= iter(qs2)\n k1= iqs1.next()\n k2= iqs2.next()\n k1_data, k2_data = True, True\n while k1_data or k2_data:\n if not k2_data:\n yield k1\n try:\n k1= iqs1.next()\n except StopIteration:\n k1_data= False\n elif not k1_data:\n yield k2\n try:\n k2= iqs2.next()\n except StopIteration:\n k2_data= False\n elif k1.key <= k2.key:\n yield k1\n try:\n k1= iqs1.next()\n except StopIteration:\n k1_data= False\n elif k2.key < k1.key: # or define __cmp__.\n yield k2\n try:\n k2= iqs2.next()\n except StopIteration:\n k2_data= False\n else:\n raise Exception( \"Wow...\" )\n def paginate( qs1, qs2, start=0, size=20 ):\n count= 0\n for row in merge( qs1, qs2 ):\n if start <= count < start+size:\n yield row\n count += 1\n if count == start+size:\n break\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/313137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35364/"
] |
313,139 | <p>Pretty new to css and trying to make the tags on my page smaller on all sides. What are the best settings to modify? Margin doesn't seem to do what I want.</p>
<pre><code>.story .content .tags .tag
{
margin: 10px 5px 10px 5px;
background-color: #99FF33;
font-weight: 500;
color: #330099;
font-style: inherit;
font-family: 'Times New Roman';
padding-right: 6px;
}
</code></pre>
<p>Here is the relevant snippet, I want to make the links smaller vertically. Do I need to specify the height explicitly then?:</p>
<pre><code><span class="tags"><span class="text">:</span>
<% for (int i = 0; i < story.Tags.Length; i++) %>
<% { %>
<% string tag = story.Tags[i]; %>
<% if (i > 0) %>
<% { %>
<%= " "%>
<% } %>
<%= Html.ActionLink<StoryController>(c => c.Tag(tag.UrlEncode(), 1), Server.HtmlEncode(tag), new { @class = "tag" })%>
<% } %>
</span>
</code></pre>
| [
{
"answer_id": 313175,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": " width:200px;\n height:20px;\n"
},
{
"answer_id": 313234,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": 0,
"selected": false,
"text": "padding:3px;\n"
},
{
"answer_id": 313336,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 1,
"selected": false,
"text": " line-height: 12px;\n font-size"
},
{
"answer_id": 313758,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 0,
"selected": false,
"text": ".tag\n{\n display: -moz-inline-block; /* For FF2 */\n display: inline-block; /* For everyone else */\n height: 12px;\n overflow: hidden;\n}\n"
},
{
"answer_id": 313977,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 0,
"selected": false,
"text": "<style>\n.tags {\nfloat: left;\nborder: 1px solid blue;\nlist-style-type: none;\n}\n .tags li {\n float: left;\n margin-right: 6px;\n font-family: 'Times New Roman';\n }\n .tags li a {\n display: block;\n padding: 0 5px;\n text-decoration: none;\n color: #330099;\n background-color: #99FF33;\n }\n .tags li a:hover {\n background-color: #330099;\n color: #99FF33;\n text-decoration: none;\n }\n</style>\n\n\n<ul class=\"tags\">\n <% for (int i = 0; i < story.Tags.Length; i++) { %>\n <% string tag = story.Tags[i]; %>\n <li><%= Html.ActionLink<StoryController>(c => c.Tag(tag.UrlEncode(), 1), Server.HtmlEncode(tag), new { @class = \"tag\" })%></li>\n <% } %>\n</ul>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,141 | <p>Why whenever I compile and run the following code in Visual Studio 2008:</p>
<pre><code>double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2;
Console::WriteLine(whole_number);
</code></pre>
<p>I get an incorrect value of 26 while the answer is 25.</p>
<p>However when I use static casts on the doubles, I get the right answer which is 25.</p>
<p>How can the wrong output be explained?</p>
| [
{
"answer_id": 313144,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "double value1 = 10.5;\ndouble value2 = 15.5;\nint whole_number = value1 + value2; // int whole_number = 26.0;\nConsole::WriteLine(whole_number);\n 26.0 26 10 15 25"
},
{
"answer_id": 313244,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "round math.h"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75350/"
] |
313,146 | <p>I'm running into a recurrent problem with git on windows (I'm running MSysGit from package Git-1.6.0.2-preview20080923.exe, i tried as well with Git-1.5.6.1-preview20080701.exe and the results are the same).</p>
<p>It happens very offen that some files are shown as changed when I didn't change them, and in git-gui it shows that the content removed is the same as the content added (usually it's the whole file), i.e.<br>
<code>- This line was here before</code><br>
<code>- This line was here before as well</code><br>
<code>- and this line too...</code><br>
<code>+ This line was here before</code><br>
<code>+ This line was here before as well</code><br>
<code>+ and this line too...</code> </p>
<p>I tried with <strong><code>git checkout -f</code></strong> and <strong><code>git reset --hard</code></strong>, but the files remain the same. I tried deleting the files prior to the hard reset as well.
I tried googling for it but couldn't find anything related.<br>
Can you tell me how to sort this out, or what steps would you take to confirm that it's a problem with Git and not my system, so I can report it as a bug.</p>
| [
{
"answer_id": 313272,
"author": "Paul",
"author_id": 23356,
"author_profile": "https://Stackoverflow.com/users/23356",
"pm_score": 3,
"selected": false,
"text": "$ git config --global core.autocrlf true\n $ git reset --hard HEAD\n$ git commit -a\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38995/"
] |
313,157 | <p>All the examples I see are for Java SE applications by passing your JAR file at the command line. Can JConsole attach to a WAR or EAR and monitor application performance?</p>
| [
{
"answer_id": 313207,
"author": "Vineet Reynolds",
"author_id": 3916,
"author_profile": "https://Stackoverflow.com/users/3916",
"pm_score": 3,
"selected": true,
"text": ">startup.bat -Dcom.sun.management.jmxremote\n >jconsole\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875/"
] |
313,176 | <p>I am working on a project using rails 2.1.1. With the new release of 2.2.2 I want to migrate to the new version. Is there anything I need to change to migrate my 2.1.1 controllers, views, and models?</p>
| [
{
"answer_id": 314202,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 4,
"selected": true,
"text": "rake rails:update\n rake -T\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
313,178 | <p>Question says it all, I've got a 500,000 line file that gets generated as part of an automated build process on a Windows box and it's riddled with <strong>^M</strong>'s. When it goes out the door it needs to <strong>*nix</strong> friendly, what's the best approach here, is there a handy snippet of code that could do this for me? Or do I need to write a little C# or Java app?</p>
| [
{
"answer_id": 313196,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 2,
"selected": false,
"text": "tr -d '^M' < infile > outfile\n tr -d '\\r' < infile > outfile\n"
},
{
"answer_id": 313202,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 5,
"selected": true,
"text": "#!/usr/bin/perl -pi\ns/\\r\\n/\\n/; perl dos2unix.pl < file.dos > file.unix\n perl -pi dos2unix.pl file.dos\n #include <stdio.h>\n\nint main(void)\n{\n int c;\n while( (c = fgetc(stdin)) != EOF )\n if(c != '\\r')\n fputc(c, stdout);\n return 0;\n}\n dos2unix.exe < file.dos > file.unix\n"
},
{
"answer_id": 313211,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 3,
"selected": false,
"text": "#include <stdio.h>\n\nint main() {\n while(1) {\n int c = fgetc(stdin);\n\n if(c == EOF)\n break;\n\n if(c == '\\r')\n continue;\n\n fputc(c, stdout);\n }\n\n return 0;\n}\n myprogram.exe < input > output\n /* XXX Contains a bug -- see comments XXX */\n\n#include <stdio.h>\n\nint main() {\n int lastc = EOF;\n int c;\n while ((c = fgetc(stdin)) != EOF) {\n if ((lastc != '\\r') || (c != '\\n')) {\n fputc (lastc, stdout);\n }\n lastc = c;\n }\n fputc (lastc, stdout);\n return 0;\n}\n #include <stdio.h>\n\nint main(int argc, char **argv) {\n FILE *file;\n\n if(argc < 2) {\n fprintf(stderr, \"Usage: myd2u <files>\\n\");\n return 1;\n }\n\n file = fopen(argv[1], \"rb+\");\n\n if(!file) {\n perror(\"\");\n return 2;\n }\n\n long readPos = 0, writePos = 0;\n int lastC = EOF;\n\n while(1) {\n fseek(file, readPos, SEEK_SET);\n int c = fgetc(file);\n readPos = ftell(file); /* For good measure. */\n\n if(c == EOF)\n break;\n\n if(c == '\\n' && lastC == '\\r') {\n /* Move back so we override the \\r with the \\n. */\n --writePos;\n }\n\n fseek(file, writePos, SEEK_SET);\n fputc(c, file);\n writePos = ftell(file);\n\n lastC = c;\n }\n\n ftruncate(fileno(file), writePos); /* Not in C89/C99/ANSI! */\n\n fclose(file);\n\n /* 'cus I'm too lazy to make a loop. */\n if(argc > 2)\n main(argc - 1, argv - 1);\n\n return 0;\n}\n"
},
{
"answer_id": 313229,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "File > Conversions > DOS to UNIX"
},
{
"answer_id": 313286,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "dos2unix unix2dos"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
313,186 | <p>I know FireBug with YSlow has to be by far my personal favourite. I also use IE developer toolbar when forced to test pages in IE. Is there any other jewels out there hiding??</p>
| [
{
"answer_id": 313225,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "defaults write com.apple.Safari IncludeDebugMenu \"YES\"\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6088/"
] |
313,199 | <p>I have an application that has many different types of objects that each persist themselves back to the db. This has worked fine so far without transactions and I'm not looking to go hog wild adding them. But there is an occasional need to start a transaction before a whole collection of the objects start updating to ensure that the database is only actually updated if all objects in the collection succeed.</p>
<p>For example, say I have a collection of apples. The command is issued to the collection to update all the apples. [transaction starting should be here] The each apples executes the code to update itself. [transaction commit/rollback should happen here].</p>
<p>The hitch I have is that each update is atomic right now (not explicitly wrapped in a transaction). I could pass an id to each "apple" to identify a transaction that has been stashed in some kind of cache, but then there's the risk that the cache would be invalidated mid-update and cause an unnecessary problem.</p>
<p>So what's the best approach to this?</p>
| [
{
"answer_id": 313278,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": true,
"text": "using(TransactionScope scope = new TransactionScope())\n{\n SaveObjectOne(); //these are just psuedo-code statements\n SaveObjectTwo(); //replace these with your code that saves various objs\n SaveObjectThree();\n scope.Complete(); //this commits the transaction, unless exception throws\n}\n"
},
{
"answer_id": 313826,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 1,
"selected": false,
"text": "public void Save()\n{\n using (SqlConnection connection = new SqlConnection(\"Connection String\"))\n {\n using (SqlTransaction trans = connection.BeginTransaction())\n {\n foreach (BusinessObject obj in this) \n { \n obj.Save(connection); \n } \n trans.Commit();\n } \n }\n}\n"
},
{
"answer_id": 1561485,
"author": "MarkDav.is",
"author_id": 79623,
"author_profile": "https://Stackoverflow.com/users/79623",
"pm_score": 1,
"selected": false,
"text": "using(TransactionScope scope1 = new TransactionScope())\n{\n using(TransactionScope scope2 = new TransactionScope())\n {\n scope2.Complete();\n }\n scope1.Complete();\n}\n TransactionScope RootMethod() void RootMethod()\n{\n using(TransactionScope scope = new TransactionScope())\n {\n /* Perform transactional work here */\n SomeMethod();\n scope.Complete();\n }\n}\n\nvoid SomeMethod()\n{\n using(TransactionScope scope = new TransactionScope())\n {\n /* Perform transactional work here */\n scope.Complete();\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3442/"
] |
313,243 | <p>How to solve "Must be MarshalByRefObject" in a good but multiple-inheritance amputated language like C#?</p>
<p>The problem is very simple, in several cases you just have to inherit from this class (infrastructure requirements).
It does not matter here really, which cases.
So, what do you do if you've already inherited from some other class (your domain model requirements)?</p>
<p>Btw good application frameworks, like spring.net always make sure you DON'T have to inherit from this class no matter what kind of infrastructure you need to apply to your class.</p>
<p><strong>I would like to know what am I getting -3 votes here for?? :)</strong></p>
| [
{
"answer_id": 313275,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 5,
"selected": true,
"text": "public interface IMyType\n{\n string SayHello();\n string BaseTypeMethodIWantToUse();\n}\n\npublic class MyType : MyBaseType, IMyType\n{\n public string SayHello()\n {\n return \"Hello!\";\n }\n}\n\npublic class MyRemoteableType : MarshalByRefObject, IMyType\n{\n private MyType _instance = new MyType();\n\n public string SayHello()\n {\n return _instance.SayHello();\n }\n\n public string BaseTypeMethodIWantToUse()\n {\n return _instance.BaseTypeMethodIWantToUse();\n }\n}\n"
},
{
"answer_id": 313276,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 1,
"selected": false,
"text": "MarshalByRefObject"
},
{
"answer_id": 25626747,
"author": "Joe",
"author_id": 1741414,
"author_profile": "https://Stackoverflow.com/users/1741414",
"pm_score": 0,
"selected": false,
"text": "public class RemotingHost<T> : MarshalByRefObject where T: class\n{\n RemoteProcess host;\n T remoteObject;\n public T RemoteObject { get { return remoteObject; } }\n\n public RemotingAdmin()\n {\n host = new RemoteProcess();\n remoteObject = (T)host.CreateObject(typeof(T));\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38325/"
] |
313,253 | <p>I have code like this to move the player in my game left, right, up, and down:</p>
<pre><code>keysSetRepeat(20, 5);
while (lives) {
scanKeys();
if (keysDownRepeat() & (KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN)) {
u8 new_x = x;
u8 new_y = y;
if (keysDownRepeat() & KEY_LEFT) {
new_x--;
} else if (keysDownRepeat() & KEY_RIGHT) {
new_x++;
} else if (keysDownRepeat() & KEY_DOWN) {
new_y++;
} else if (keysDownRepeat() & KEY_UP) {
new_y--;
}
// ...
}
// ...
swiWaitForVBlank();
}
</code></pre>
<p>Why are the keys not being detected? If I replace <code>keysDownRepeat()</code> with <code>keysDown()</code> it works (without the repeat rate, of course). The <a href="http://libnds.devkitpro.org/a00020.html" rel="nofollow noreferrer">documentation</a> is no help here.</p>
| [
{
"answer_id": 313255,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": true,
"text": "uint32 keysDownRepeat(void) {\n uint32 tmp = keysrepeat;\n\n keysrepeat = 0;\n\n return tmp;\n}\n keysDownRepeat() keysSetRepeat(20, 5);\n\nwhile (lives) {\n scanKeys();\n u32 keys_down_repeat = keysDownRepeat();\n\n if (keys_down_repeat & (KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN)) {\n u8 new_x = x;\n u8 new_y = y;\n\n if (keys_down_repeat & KEY_LEFT) {\n new_x--;\n } else if (keys_down_repeat & KEY_RIGHT) {\n new_x++;\n } else if (keys_down_repeat & KEY_DOWN) {\n new_y++;\n } else if (keys_down_repeat & KEY_UP) {\n new_y--;\n }\n\n // ...\n }\n\n // ...\n\n swiWaitForVBlank();\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
313,269 | <p>I'm looking for your best solutions for creating a new message instance based on a pre-defined XSD schema to be used within a Biztalk orchestration.</p>
<p>Extra votes go to answers with clear & efficient examples or answers with quality referenced links.</p>
| [
{
"answer_id": 313280,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 1,
"selected": false,
"text": "System.Xml.XmlDocument Load LoadXml"
},
{
"answer_id": 313284,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 4,
"selected": false,
"text": "XLANG XMLDocument message assignment LoadXML XMLDocument varXMLDoc.LoadXml(@\"<ns0:SomeXML><AnElementToPopulate></AnElementToPopulate></SomeXML>\"); \nmsgYourMessage = varXMLDom;\n AnElementToPopulate"
},
{
"answer_id": 17289937,
"author": "Ross Oliver",
"author_id": 1288319,
"author_profile": "https://Stackoverflow.com/users/1288319",
"pm_score": 0,
"selected": false,
"text": "xsd.exe /classes /namespace:MyNamespace myschemafile.xsd\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3810/"
] |
313,270 | <p>I know I can configure command line arguments in the Run configuration but I want to run a java file multiple times with different command line arguments. It's a pain to change the Run Configuration every time.</p>
<p>Is there a way I can make Eclipse prompt me for command line arguments every time I run the program?</p>
| [
{
"answer_id": 313292,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 8,
"selected": true,
"text": "string_prompt Program Argument Run ${string_prompt}\n file_prompt folder_prompt Variables (x)= Arguments"
},
{
"answer_id": 6652601,
"author": "Caleb",
"author_id": 839185,
"author_profile": "https://Stackoverflow.com/users/839185",
"pm_score": 6,
"selected": false,
"text": "${string_prompt:My Prompt Text:Default Value}"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24424/"
] |
313,281 | <p>I am using the FlexiGrid jQuery plug in and I need to get a JSON object back form my MVC App, simple enough if the FlexiGrid took just the object but I need to add a few items to the response string for it to work properly with FlexiGrid.</p>
<p>So here is a portion of my controller code:</p>
<pre><code>If Request.QueryString("json") IsNot Nothing Then
Dim data As New StringBuilder()
data.Append("page: " & pageIndex & "," & vbCrLf)
data.Append("total: " & ViewData.TotalCount & "," & vbCrLf)
data.Append("rows: ")
data.Append(Json(objCustomerList))
Return Content(data.ToString())
End If
</code></pre>
<p>Unfortunately in the above code <code>Json(objCustomerList)</code> returns 'System.Web.MVV.JsonResult' instead of the desired JSON string data. I also tried <code>Json(objCustomerList).ToString()</code> just to see what would happen and the same thing again.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 313285,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": false,
"text": "Json() JavaScriptSerializer JsonResult Json() StringBuilder JavaScriptSerializer.Serialize() StringBuilder"
},
{
"answer_id": 318591,
"author": "Slee",
"author_id": 34548,
"author_profile": "https://Stackoverflow.com/users/34548",
"pm_score": 3,
"selected": true,
"text": "Imports System.Web.Script.Serialization\nImports System.Reflection\n\nPublic Class FlexiGrid\n\n Public Class FlexigridRow\n Public id As String\n Public cell As New List(Of String)()\n End Class\n\n Public Class FlexigridObject\n Public page As Integer\n Public total As Integer\n Public rows As New List(Of FlexigridRow)()\n End Class\n\n Public Shared Function GetFlexiGridJSON(ByVal page As Integer, ByVal total As Integer, ByVal o As Object) As String\n\n Dim js As New JavaScriptSerializer\n Dim flexiGrid As New FlexigridObject\n Dim i As Integer = 0\n flexiGrid.page = page\n flexiGrid.total = total\n\n For Each c In o\n Dim r As New FlexigridRow()\n r.id = i\n r.cell = GetPropertyList(c)\n flexiGrid.rows.Add(r)\n i += i\n Next\n\n Return js.Serialize(flexiGrid)\n End Function\n\n Private Shared Function GetPropertyList(ByVal obj As Object) As List(Of String)\n\n Dim propertyList As New List(Of String)()\n\n Dim type As Type = obj.[GetType]()\n Dim properties As PropertyInfo() = type.GetProperties(BindingFlags.Instance Or BindingFlags.[Public])\n For Each [property] As PropertyInfo In properties\n Dim o As Object = [property].GetValue(obj, Nothing)\n propertyList.Add(If(o Is Nothing, \"\", o.ToString()))\n Next\n\n Return propertyList\n\n End Function\n\nEnd Class\n Return Content(GetFlexiGridJSON(pageIndex, TotalCount, objCustomerList))\n"
},
{
"answer_id": 2424792,
"author": "aslakjo",
"author_id": 291451,
"author_profile": "https://Stackoverflow.com/users/291451",
"pm_score": 3,
"selected": false,
"text": "JsonResult json = ... ;\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nstring yourJsonResult = serializer.Serialize(json.Data);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34548/"
] |
313,297 | <p>I'm trying to come up with a simple and efficient way to create a smooth surface which intersects a number of given "sample" points.</p>
<p>For any X,Y point on the surface, I identify up to 4 sample points in each of the 4 directions (the next higher and lower points on the X, and then the Y axes). Given this point, I want a way to compute a Z value that interpolates between the 4 sample points.</p>
<p>Of course the algorithm, given the X, Y position of any of the 4 sample points, should output the Z value for that point. Note also that there may be less than 4 sample points.</p>
<p>I guess some function of the Z values for the 4 sample points, somehow inversely biased by the distance to the sample point, but I can't figure out how to do this.</p>
<p>Anyone got any ideas about a simple way to do this?</p>
| [
{
"answer_id": 344756,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 5,
"selected": true,
"text": "p00 p01 q0 p02 p03\np10 p11 q1 p12 p13\np20 p21 q2 p22 p23\np30 p31 q3 p32 p33\n | 0 1 0 0 | | p[i−2] |\n |−τ 0 τ 0 | | p[i−1] |\np(u) = 1 u u2 u3 | 2τ τ−3 3−2τ −τ | | p[i] |\n |−τ 2−τ τ−2 τ | | p[i+1] |\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050/"
] |
313,306 | <p>In T-SQL, SPACE() function is used to add spaces to a string. For e.g. </p>
<pre><code>@s = 'He' + space(5) + 'llo'
</code></pre>
<p>Output</p>
<pre><code>He llo
</code></pre>
<p>So is there any function in PL/SQL that is equivalent to SPACE()?</p>
<p>Thank you.</p>
| [
{
"answer_id": 313368,
"author": "IK.",
"author_id": 21283,
"author_profile": "https://Stackoverflow.com/users/21283",
"pm_score": 5,
"selected": true,
"text": "select 'He' || rpad(' ',5,' ') || 'llo'\nfrom dual;\n/\n declare\n x varchar2(20);\nbegin\n x:= 'He' || rpad(' ',5,' ') || 'llo';\nend;\n/\n"
},
{
"answer_id": 8899903,
"author": "Ray Martin",
"author_id": 1154645,
"author_profile": "https://Stackoverflow.com/users/1154645",
"pm_score": 0,
"selected": false,
"text": "space() rpad(' ',n,' ')\n n select rpad(' ',39,' ') as \"40 spaces\" from dual\n dual"
},
{
"answer_id": 13700492,
"author": "Karuna",
"author_id": 1875284,
"author_profile": "https://Stackoverflow.com/users/1875284",
"pm_score": 2,
"selected": false,
"text": "rpad(' ',n,' ') n+1 select RPAD('A',3,'-')||RPAD(' ',4,' ')||RPAD('B',5,'-') from dual\n A-- B----\n A-- B"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1602746/"
] |
313,324 | <p>How to declare a static dictionary object inside a static class? I tried</p>
<pre><code>public static class ErrorCode
{
public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>()
{
{ "1", "User name or password problem" }
};
}
</code></pre>
<p>But the compiler complains that "<em>A const field of a reference type other than string can only be initialized with null</em>". </p>
| [
{
"answer_id": 313328,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": -1,
"selected": false,
"text": "public static class ErrorCode\n{\n public const IDictionary<string , string > m_ErrorCodeDic;\n\n public static ErrorCode()\n {\n m_ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\",\"User name or password problem\"} }; \n }\n}\n"
},
{
"answer_id": 313329,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "public static class ErrorCode\n{\n public const IDictionary<string, string> ErrorCodeDic;\n public static ErrorCode()\n {\n ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n }\n}\n"
},
{
"answer_id": 313343,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 3,
"selected": false,
"text": "public static class ErrorCode\n{\n public static IDictionary<string, string> ErrorCodeDic;\n static ErrorCode()\n {\n ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n }\n}\n"
},
{
"answer_id": 313352,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 9,
"selected": true,
"text": "private static readonly Dictionary<string, string> ErrorCodes\n = new Dictionary<string, string>\n{\n { \"1\", \"Error One\" },\n { \"2\", \"Error Two\" }\n};\n"
},
{
"answer_id": 313358,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 1,
"selected": false,
"text": "const static public static class ErrorCode\n{\n public static IDictionary<string, string> ErrorCodeDic\n = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n}\n readonly"
},
{
"answer_id": 5474751,
"author": "areyling",
"author_id": 202870,
"author_profile": "https://Stackoverflow.com/users/202870",
"pm_score": 3,
"selected": false,
"text": "private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary\n{\n { \"1\", \"Unrecognized segment ID\" },\n { \"2\", \"Unexpected segment\" }\n};\n Dictionary<string, string> StringDictionary StringDictionary myDict[\"foo\"]\n myDict StringDictionary Dictionary<string, string>"
},
{
"answer_id": 16078057,
"author": "Sujith Radhakrishnan",
"author_id": 1788322,
"author_profile": "https://Stackoverflow.com/users/1788322",
"pm_score": 2,
"selected": false,
"text": "enum Commands\n{\n StudentDetail\n}\npublic static class Quires\n{\n public static Dictionary<Commands, String> quire\n = new Dictionary<Commands, String>();\n static Quires()\n {\n quire.add(Commands.StudentDetail,@\"SELECT * FROM student_b\");\n }\n}\n"
},
{
"answer_id": 69419168,
"author": "Dororo",
"author_id": 10548894,
"author_profile": "https://Stackoverflow.com/users/10548894",
"pm_score": 0,
"selected": false,
"text": "public Dictionary<string, Boolean> Access\n{\n get\n {\n // Same here, iterate if needed..\n return new Dictionary<string, Boolean>(prv_Access);\n }\n set\n {\n MainWindow.NewSession.Renew();\n if (MainWindow.NewSession.Actual)\n {\n prv_HistoryAccess.Add(DateTime.Now, new Dictionary<string, Boolean>(prv_Access));\n\n // Here you would need to iterate when you deal with mutables..\n prv_Access = value;\n }\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
313,332 | <p>How do I use <a href="http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Xml.XPath/types/XPathNavigator.html#Evaluate(System.String)" rel="nofollow noreferrer">XPathNavigator.Evaluate</a> ( or other methods in XPathNavigator) to obtain the ISBN value for the following xml input?</p>
<pre><code><?xml version="1.0"?>
<!-- a fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
<book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
<title>Pride And Prejudice</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>24.95</price>
</book>
<book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>29.95</price>
</book>
<book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
<title>Emma</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
<book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
<title>Sense and Sensibility</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
</bookstore>
</code></pre>
| [
{
"answer_id": 313328,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": -1,
"selected": false,
"text": "public static class ErrorCode\n{\n public const IDictionary<string , string > m_ErrorCodeDic;\n\n public static ErrorCode()\n {\n m_ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\",\"User name or password problem\"} }; \n }\n}\n"
},
{
"answer_id": 313329,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "public static class ErrorCode\n{\n public const IDictionary<string, string> ErrorCodeDic;\n public static ErrorCode()\n {\n ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n }\n}\n"
},
{
"answer_id": 313343,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 3,
"selected": false,
"text": "public static class ErrorCode\n{\n public static IDictionary<string, string> ErrorCodeDic;\n static ErrorCode()\n {\n ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n }\n}\n"
},
{
"answer_id": 313352,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 9,
"selected": true,
"text": "private static readonly Dictionary<string, string> ErrorCodes\n = new Dictionary<string, string>\n{\n { \"1\", \"Error One\" },\n { \"2\", \"Error Two\" }\n};\n"
},
{
"answer_id": 313358,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 1,
"selected": false,
"text": "const static public static class ErrorCode\n{\n public static IDictionary<string, string> ErrorCodeDic\n = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n}\n readonly"
},
{
"answer_id": 5474751,
"author": "areyling",
"author_id": 202870,
"author_profile": "https://Stackoverflow.com/users/202870",
"pm_score": 3,
"selected": false,
"text": "private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary\n{\n { \"1\", \"Unrecognized segment ID\" },\n { \"2\", \"Unexpected segment\" }\n};\n Dictionary<string, string> StringDictionary StringDictionary myDict[\"foo\"]\n myDict StringDictionary Dictionary<string, string>"
},
{
"answer_id": 16078057,
"author": "Sujith Radhakrishnan",
"author_id": 1788322,
"author_profile": "https://Stackoverflow.com/users/1788322",
"pm_score": 2,
"selected": false,
"text": "enum Commands\n{\n StudentDetail\n}\npublic static class Quires\n{\n public static Dictionary<Commands, String> quire\n = new Dictionary<Commands, String>();\n static Quires()\n {\n quire.add(Commands.StudentDetail,@\"SELECT * FROM student_b\");\n }\n}\n"
},
{
"answer_id": 69419168,
"author": "Dororo",
"author_id": 10548894,
"author_profile": "https://Stackoverflow.com/users/10548894",
"pm_score": 0,
"selected": false,
"text": "public Dictionary<string, Boolean> Access\n{\n get\n {\n // Same here, iterate if needed..\n return new Dictionary<string, Boolean>(prv_Access);\n }\n set\n {\n MainWindow.NewSession.Renew();\n if (MainWindow.NewSession.Actual)\n {\n prv_HistoryAccess.Add(DateTime.Now, new Dictionary<string, Boolean>(prv_Access));\n\n // Here you would need to iterate when you deal with mutables..\n prv_Access = value;\n }\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
313,334 | <p>Reporting Services 2000 SP2</p>
<p>I've got a matrix displaying the number of employees </p>
<pre><code> Business1 Business2 Business3
StartBefore99 9 14 4
StartAfter99 30 20 34
</code></pre>
<p>I'd like to display percentages eg</p>
<pre><code> Business1 Business2 Business3
StartBefore99 9 (23%) 14 (41%) 4 (10%)
StartAfter99 30 (77%) 20 (59%) 34 (90%)
</code></pre>
<p>Any suggestions? I could do it in SQL, but would prefer to do an expression in RS.</p>
<p>Cheers</p>
| [
{
"answer_id": 313328,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": -1,
"selected": false,
"text": "public static class ErrorCode\n{\n public const IDictionary<string , string > m_ErrorCodeDic;\n\n public static ErrorCode()\n {\n m_ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\",\"User name or password problem\"} }; \n }\n}\n"
},
{
"answer_id": 313329,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "public static class ErrorCode\n{\n public const IDictionary<string, string> ErrorCodeDic;\n public static ErrorCode()\n {\n ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n }\n}\n"
},
{
"answer_id": 313343,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 3,
"selected": false,
"text": "public static class ErrorCode\n{\n public static IDictionary<string, string> ErrorCodeDic;\n static ErrorCode()\n {\n ErrorCodeDic = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n }\n}\n"
},
{
"answer_id": 313352,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 9,
"selected": true,
"text": "private static readonly Dictionary<string, string> ErrorCodes\n = new Dictionary<string, string>\n{\n { \"1\", \"Error One\" },\n { \"2\", \"Error Two\" }\n};\n"
},
{
"answer_id": 313358,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 1,
"selected": false,
"text": "const static public static class ErrorCode\n{\n public static IDictionary<string, string> ErrorCodeDic\n = new Dictionary<string, string>()\n { {\"1\", \"User name or password problem\"} };\n}\n readonly"
},
{
"answer_id": 5474751,
"author": "areyling",
"author_id": 202870,
"author_profile": "https://Stackoverflow.com/users/202870",
"pm_score": 3,
"selected": false,
"text": "private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary\n{\n { \"1\", \"Unrecognized segment ID\" },\n { \"2\", \"Unexpected segment\" }\n};\n Dictionary<string, string> StringDictionary StringDictionary myDict[\"foo\"]\n myDict StringDictionary Dictionary<string, string>"
},
{
"answer_id": 16078057,
"author": "Sujith Radhakrishnan",
"author_id": 1788322,
"author_profile": "https://Stackoverflow.com/users/1788322",
"pm_score": 2,
"selected": false,
"text": "enum Commands\n{\n StudentDetail\n}\npublic static class Quires\n{\n public static Dictionary<Commands, String> quire\n = new Dictionary<Commands, String>();\n static Quires()\n {\n quire.add(Commands.StudentDetail,@\"SELECT * FROM student_b\");\n }\n}\n"
},
{
"answer_id": 69419168,
"author": "Dororo",
"author_id": 10548894,
"author_profile": "https://Stackoverflow.com/users/10548894",
"pm_score": 0,
"selected": false,
"text": "public Dictionary<string, Boolean> Access\n{\n get\n {\n // Same here, iterate if needed..\n return new Dictionary<string, Boolean>(prv_Access);\n }\n set\n {\n MainWindow.NewSession.Renew();\n if (MainWindow.NewSession.Actual)\n {\n prv_HistoryAccess.Add(DateTime.Now, new Dictionary<string, Boolean>(prv_Access));\n\n // Here you would need to iterate when you deal with mutables..\n prv_Access = value;\n }\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26086/"
] |
313,359 | <p>When editing PHP code (I'm not sure if it's specific to that language) and I create a new line in the middle of comma-separated lists that span multiple lines, the indent rules always unindent the line I'm leaving. <a href="http://toogeneric.com/files/indent2.mov" rel="noreferrer">Here's a video of it.</a> This happens in arrays, function argument lists, etc.</p>
<p>Is there anything I can do to stop this from happening, or any quicker methods of fixing the error than moving up, re-indenting it, moving down, re-indenting (since it gets cleared when you leave the line), and continuing?</p>
<p><a href="https://gist.github.com/2806bf9f0fb1424fd375" rel="noreferrer">.vimrc</a></p>
| [
{
"answer_id": 313363,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": ":set indentexpr=\"\" :help filetype-indent-off"
},
{
"answer_id": 313384,
"author": "Alex Suraci",
"author_id": 9743,
"author_profile": "https://Stackoverflow.com/users/9743",
"pm_score": 0,
"selected": false,
"text": "<esc>o"
},
{
"answer_id": 315071,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 0,
"selected": false,
"text": ":let g:PHP_default_indenting=1\n :h php-indent"
},
{
"answer_id": 319674,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 2,
"selected": false,
"text": "~/.vim/after/ftplugin setlocal autoindent\nsetlocal cindent\nsetlocal cinwords=if,else,elseif,do,while,foreach,for,case,default,function,class,interface,abstract,private,public,protected,final\nsetlocal cinkeys=0{,0},0),!^F,o,O,e\n\nsetlocal nosmartindent \" don't use smart indent option\n"
},
{
"answer_id": 1943162,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "set cindkeys=-0#\n width: 100%\n set cindkeys-=:\n"
},
{
"answer_id": 3641047,
"author": "a paid nerd",
"author_id": 102704,
"author_profile": "https://Stackoverflow.com/users/102704",
"pm_score": 0,
"selected": false,
"text": "cindent smartindent ~/.vim/filetype.vim au BufNewFile,BufRead *.html,*.css setlocal nocindent smartindent\n"
},
{
"answer_id": 21896816,
"author": "Max",
"author_id": 2962756,
"author_profile": "https://Stackoverflow.com/users/2962756",
"pm_score": 0,
"selected": false,
"text": "elseif lastline =~ '^\\s*?>.*<?\\%(php\\)\\=\\s*$'\n let lnum = lnum - 1\n \"elseif lastline =~ '^\\s*?>.*<?\\%(php\\)\\=\\s*$'\n\" let lnum = lnum - 1\n <?"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9743/"
] |
313,374 | <p>hi i forgot the code which in a sample class you have to add so that it runs automatically?</p>
<p>is it wakeup or something?</p>
<p>like so:</p>
<pre><code>class something {
function automaticxxx_something_which_runs when class is created()
{
}
}
$s = new something();
</code></pre>
<p>-what do i create in the class file so that something runs already after the class is initialized? </p>
<p>i forgot how to name the function name so that it would call it automatically the first function. </p>
| [
{
"answer_id": 313396,
"author": "Matthewd",
"author_id": 40159,
"author_profile": "https://Stackoverflow.com/users/40159",
"pm_score": 3,
"selected": true,
"text": "class Foobar\n{\n function Foobar()\n {\n echo \"Hello World!\\n\";\n }\n}\n\nnew Foobar()\n class Foobar\n{\n function __construct()\n {\n echo \"Hello World!\\n\";\n }\n}\n\nnew Foobar();\n"
},
{
"answer_id": 313441,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "class Foobar\n{\n function __construct()\n {\n echo \"Hello World!\\n\";\n }\n function Foobar() \n {\n return $this->__construct(); \n }\n}\n class Foobar \n{\n public function __construct() \n { \n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1345527/"
] |
313,400 | <p>How exactly does <code>NSInvocation</code> work? Is there a good introduction?</p>
<p>I’m specifically having issues understanding how the following code (from <em>Cocoa Programming for Mac OS X, 3rd Edition</em>) works, but then also be able to apply the concepts independently of the tutorial sample. The code:</p>
<pre><code>- (void)insertObject:(Person *)p inEmployeesAtIndex:(int)index
{
NSLog(@"adding %@ to %@", p, employees);
// Add inverse of this operation to undo stack
NSUndoManager *undo = [self undoManager];
[[undo prepareWithInvocationTarget:self] removeObjectFromEmployeesAtIndex:index];
if (![undo isUndoing])
[undo setActionName:@"Insert Person"];
// Finally, add person to the array
[employees insertObject:p atIndex:index];
}
- (void)removeObjectFromEmployeesAtIndex:(int)index
{
Person *p = [employees objectAtIndex:index];
NSLog(@"removing %@ from %@", p, employees);
// Add inverse of this operation to undo stack
NSUndoManager *undo = [self undoManager];
[[undo prepareWithInvocationTarget:self] insertObject:p
inEmployeesAtIndex:index];
if (![undo isUndoing])
[undo setActionName:@"Delete Person"];
// Finally, remove person from array
[employees removeObjectAtIndex:index];
}
</code></pre>
<p>I get what it’s trying to do. (BTW, <code>employees</code> is an <code>NSArray</code> of a custom <code>Person</code> class.)</p>
<p>Being a .NET guy, I try to associate unfamiliar Obj-C and Cocoa concepts to roughly analogous .NET concepts. Is this similar to .NET’s delegate concept, but untyped? </p>
<p>This isn’t 100% clear from the book, so I’m looking for something supplemental from real Cocoa/Obj-C experts, again with the goal that I understand the fundamental concept beneath the simple(-ish) example. I'm really looking to be able to independently apply the knowledge -- up until chapter 9, I was having no difficulty doing that. But now ... </p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 313455,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 9,
"selected": true,
"text": "NSInvocation NSInvocation NSInvocation addObject: [myArray addObject:myString];\n NSInvocation NSInvocation NSMutableArray addObject: NSMethodSignature * mySignature = [NSMutableArray\n instanceMethodSignatureForSelector:@selector(addObject:)];\nNSInvocation * myInvocation = [NSInvocation\n invocationWithMethodSignature:mySignature];\n [myInvocation setTarget:myArray];\n [myInvocation setSelector:@selector(addObject:)];\n [myInvocation setArgument:&myString atIndex:2];\n myInvocation [myInvocation invoke];\n [myArray addObject:myString]; NSInvocation selector invoke NSUndoManager NSInvocation NSInvocation NSInvocation NSUndoManager NSUndoManager NSInvocation"
},
{
"answer_id": 3224774,
"author": "Dave",
"author_id": 153040,
"author_profile": "https://Stackoverflow.com/users/153040",
"pm_score": 6,
"selected": false,
"text": "- (void)hello:(NSString *)hello world:(NSString *)world\n{\n NSLog(@\"%@ %@!\", hello, world);\n\n NSMethodSignature *signature = [self methodSignatureForSelector:_cmd];\n NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];\n\n [invocation setTarget:self]; // index 0 (hidden)\n [invocation setSelector:_cmd]; // index 1 (hidden)\n [invocation setArgument:&hello atIndex:2]; // index 2\n [invocation setArgument:&world atIndex:3]; // index 3\n\n // NSTimer's always retain invocation arguments due to their firing delay. Release will occur when the timer invalidates itself.\n [NSTimer scheduledTimerWithTimeInterval:1 invocation:invocation repeats:NO];\n}\n [self hello:@\"Hello\" world:@\"world\"]; 2010-07-11 17:48:45.262 Your App[2523:a0f] Hello world!\n2010-07-11 17:48:46.266 Your App[2523:a0f] Hello world!\n2010-07-11 17:48:47.266 Your App[2523:a0f] Hello world!\n2010-07-11 17:48:48.267 Your App[2523:a0f] Hello world!\n2010-07-11 17:48:49.268 Your App[2523:a0f] Hello world!\n2010-07-11 17:48:50.268 Your App[2523:a0f] Hello world!\n2010-07-11 17:48:51.269 Your App[2523:a0f] Hello world!\n...\n self -retainArguments NSMethodSignature *signature = ...;\nNSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];\nid arg1 = ...;\nid arg2 = ...;\n\n[invocation setTarget:...];\n[invocation setSelector:...];\n[invocation setArgument:&arg1 atIndex:2];\n[invocation setArgument:&arg2 atIndex:3];\n\n[invocation retainArguments]; // If you do not call this, arg1 and arg2 might be deallocated.\n\n[self someMethodThatInvokesYourInvocationEventually:invocation];\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] |
313,410 | <p>Try clicking on the "Print" button on the following page:
(link removed - consensus is that everything was working fine and the problem was my setup)
For debugging purposes, I've replaced a chunk of javascript with a simple alert("test"), and even that isn't showing up in IE7 for me. It works totally fine in Safari, FF (Mac and PC) and IE6, but for some reason it's not working in IE7. For your reference, the code in the button is this:</p>
<pre><code><a onclick="makeNewWindow()" href="#"><img src="/print.gif"/></a>
</code></pre>
<p>And the JS inside /newsletter/print.js is this:</p>
<pre><code>function makeNewWindow() {
alert("test");
}
</code></pre>
<p>Can anyone help me understand if there's a way around this, or if this has something to do with the fact that I'm running "IE7 Standalone" via Parallels on my Mac? Any help is greatly appreciated.</p>
<p>Thanks,
Mike</p>
| [
{
"answer_id": 6374103,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "file:// javascript:alert(\"Foo\");"
},
{
"answer_id": 9977448,
"author": "LesFromWalden",
"author_id": 1308154,
"author_profile": "https://Stackoverflow.com/users/1308154",
"pm_score": 0,
"selected": false,
"text": "href='javascript:void(0);' href='# href='javascript:yourFunction();'"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,417 | <p>We're writing a records management product for schools and one of the requirements is the ability to manage course schedules. I haven't looked at the code for how we deal with this (I'm on a different project at the moment), but nonetheless I started wondering how best to handle one particular part of this requirement, namely how to handle the fact that each course can be held one or more days of the week, and how best to store this information in the database. To provide some context, a bare-bones <code>Course</code> table might contain the following columns:</p>
<pre><code>Course Example Data
------ ------------
DeptPrefix ;MATH, ENG, CS, ...
Number ;101, 300, 450, ...
Title ;Algebra, Shakespeare, Advanced Data Structures, ...
Description ;...
DaysOfWeek ;Monday, Tuesday-Thursday, ...
StartTime
EndTime
</code></pre>
<p>What I'm wondering is, what is the best way to handle the <code>DaysOfWeek</code> column in this (contrived) example? The problem I'm having with it is that is a multi-valued field: that is, you can have a course on any day of the week, and the same course can take be held on more than one day. I know certain databases natively support multi-value columns, but is there a "best practice" to handle this assuming the database doesn't natively support it?</p>
<p>I've come up with the following possible solutions so far, but I'm wondering if anyone has anything better:</p>
<h3>Possible Solution #1: Treat DaysOfWeek as a bit field</h3>
<p>This was the first thing that popped into my head (I'm not sure if that's a good thing or not...). In this solution, <code>DaysOfWeek</code> would be defined as a byte, and the first 7 bits would be used to represent the days of week (one bit for each day). A 1 bit would indicate that a class was held on corresponding day of the week.</p>
<p><strong>Pros</strong>: Easy to implement (the application can deal with the bit manipulations), works with any database.</p>
<p><strong>Cons</strong>: Harder to write queries that use the <code>DaysOfWeek</code> column (although you could deal with this at the application level, or create views and stored procedues in the database to simplify this), breaks relational database model.</p>
<h3>Possible Solution #2: Store DaysOfWeek as a string of characters</h3>
<p>This is essentially the same approach as using a bit field, but instead of dealing with raw bits, you assign a unique letter to each day of the week, and the <code>DaysOfWeek</code> column just stores a sequence of letters indicating what days a course is held on. For example, you might associate each weekday with a single-character code as follows:</p>
<pre><code>Weekday Letter
------- ------
Sunday S
Monday M
Tuesday T
Wednesday W
Thursday R
Friday F
Saturday U
</code></pre>
<p>In this case, a course held on Monday, Tuesday, and Friday would have have the value <code>'MTF'</code> for <code>DaysOfWeek</code>, while a class held only on Wednesdays would have a <code>DaysOfWeek</code> value of <code>'W'</code>.</p>
<p><strong>Pros</strong>: Easier to deal with in queries (i.e. You could use <code>INSTR</code>, or its equivalent, to determine if a class is held on a given day). Works with any database that supports INSTR or an equivalent function (most, I would guess...). Also friendlier to look at, and easy to see at a glance what is happening in queries that use the <code>DaysOfWeek</code> column.</p>
<p><strong>Cons</strong>: The only real "con" is that, like the bitfield approach, this breaks the relational model by storing a variable number of values in a single field.</p>
<h3>Possible Solution #3: Use a Lookup Table (ugly)</h3>
<p>Another possibility would be to create a new table that stores all the unique combinations of days of the week, and have the <code>Course.DaysOfWeek</code> column simply be a foreign key into this lookup table. However, this solution seems like the most inelegant one, and I only considered it because it seemed like the The Relational Way<sup>TM</sup> to do things.</p>
<p><strong>Pros</strong>: It's the only solution that is "pure" from a relational database point of view.</p>
<p><strong>Cons</strong>: It's inelegant and cumbersome. For example, how would you design the user interface for assigning corresponding weekdays to a given course around the lookup table? I doubt a user wants to deal with choices alongs the lines of "Sunday", "Sunday, Monday", "Sunday, Monday, Tuesday", "Sunday, Monday, Tuesday, Wednesday", and so on...</p>
<h3>Other Ideas?</h3>
<p>So, is there a more elegant way to handle multiple values in a single column? Or would one the proposed solutions suffice? For what it's worth, I think my second solution is probably the best of the three possible solutions that I outlined here, but I'd be curious to see if someone has a different opinion (or indeed a different approach altogether).</p>
| [
{
"answer_id": 24174625,
"author": "Nelson Teixeira",
"author_id": 2752520,
"author_profile": "https://Stackoverflow.com/users/2752520",
"pm_score": 6,
"selected": false,
"text": " sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64. \n select * from courses where (days & 8) > 0\n select * from courses where (days & 48) > 0\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17862/"
] |
313,432 | <p>I'm a C/Python programmer in C++ land working with the STL for the first time.</p>
<p>In Python, extending a list with another list uses the <code>.extend</code> method:</p>
<pre><code>>>> v = [1, 2, 3]
>>> v_prime = [4, 5, 6]
>>> v.extend(v_prime)
>>> print(v)
[1, 2, 3, 4, 5, 6]
</code></pre>
<p>I currently use this algorithmic approach to extend vectors in C++:</p>
<pre><code>v.resize(v.size() + v_prime.size());
copy(v_prime.begin(), v_prime.end(), v.rbegin());
</code></pre>
<p>Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?</p>
| [
{
"answer_id": 313444,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 7,
"selected": true,
"text": "// reserve() is optional - just to improve performance\nv.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));\nv.insert(v.end(),v_prime.begin(),v_prime.end());\n"
},
{
"answer_id": 313514,
"author": "CTT",
"author_id": 40191,
"author_profile": "https://Stackoverflow.com/users/40191",
"pm_score": 5,
"selected": false,
"text": "copy(v_prime.begin(), v_prime.end(), back_inserter(v));\n"
},
{
"answer_id": 41079085,
"author": "TheJJ",
"author_id": 1348535,
"author_profile": "https://Stackoverflow.com/users/1348535",
"pm_score": 2,
"selected": false,
"text": "extend vec v ext v_prime /**\n * Extend a vector with elements, without destroying source one.\n */\ntemplate<typename T>\nvoid vector_extend(std::vector<T> &vec, const std::vector<T> &ext) {\n vec.reserve(vec.size() + ext.size());\n vec.insert(std::end(vec), std::begin(ext), std::end(ext));\n}\n\n/**\n * Extend a vector with elements with move semantics.\n */\ntemplate<typename T>\nvoid vector_extend(std::vector<T> &vec, std::vector<T> &&ext) {\n if (vec.empty()) {\n vec = std::move(ext);\n }\n else {\n vec.reserve(vec.size() + ext.size());\n std::move(std::begin(ext), std::end(ext), std::back_inserter(vec));\n ext.clear();\n }\n}\n"
},
{
"answer_id": 41104663,
"author": "Tharindu Kumara",
"author_id": 3312620,
"author_profile": "https://Stackoverflow.com/users/3312620",
"pm_score": 4,
"selected": false,
"text": "a.insert(a.end(), b.begin(), b.end());\na.insert(std::end(a), std::begin(b), std::end(b));\n a.reserve(a.size() + distance(b.begin(), b.end()));\n std::copy (b.begin(), b.end(), std::back_inserter(a));\n boost::push_back(a, b);\n"
},
{
"answer_id": 42176894,
"author": "noɥʇʎԀʎzɐɹƆ",
"author_id": 1459669,
"author_profile": "https://Stackoverflow.com/users/1459669",
"pm_score": 2,
"selected": false,
"text": "std::vector::insert A.reserve(A.size() + B.size());\nA.insert(A.end(), B.begin(), B.end());\n reserve() <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script><link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css\"><script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js\"></script><script src=\"https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js\"></script><script>function generateCode(){codeTemplate=\"{0}.reserve({0}.size() + {1}.size()); \\n{0}.insert({0}.end(), {1}.begin(), {1}.end());\",first=document.getElementById(\"1\").value,second=document.getElementById(\"2\").value,\"\"==first&&(first=\"A\"),\"\"==second&&(second=\"B\"),document.getElementById(\"c\").innerHTML=String.format(codeTemplate,first,second)}String.format||(String.format=function(a){var b=Array.prototype.slice.call(arguments,1);return a.replace(/{(\\d+)}/g,function(a,c){return\"undefined\"!=typeof b[c]?b[c]:a})});</script><div class=\"A\" style=\"margin:3% 10% 1% 10%;\"><label for=\"1\">First vector name:</label><input id=\"1\"/><br/><label for=\"1\">Second vector name:</label><input id=\"2\"/><div class=\"D\"><a class=\"waves-effect waves-light btn red col\" onclick=\"generateCode();\" style=\"margin:0 0 4% 0;\">Generate Code</a></div><textarea id=\"c\" onclick=\"this.select()\" style=\"border:none;height:auto;overflow: hidden;font-family:Consolas,Monaco;\">A.reserve(A.size() + B.size()); A.insert(A.end(), B.begin(), B.end());</textarea></div>"
},
{
"answer_id": 64102335,
"author": "Ido Kessler",
"author_id": 7110367,
"author_profile": "https://Stackoverflow.com/users/7110367",
"pm_score": 3,
"selected": false,
"text": "a.insert(a.end(), b.begin(), b.end());\n #include <vector>\n#include <iostream>\n#include <chrono>\n\nint main() {\n std::vector<int> a, b(50);\n auto t1 = std::chrono::high_resolution_clock::now();\n for (int i = 0; i < 5e4; i++) {\n a.reserve(a.size() + b.size()); // line in question.\n a.insert(a.end(), b.begin(), b.end());\n }\n auto t2 = std::chrono::high_resolution_clock::now();\n auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>( t2 - t1 ).count();\n\n std::cout << 1.0 * duration / 1e9;\n return 0;\n}\n\n//run time complexity speed up\n//with reserve 114.558 s O(N) x1\n//without reserve 0.012 s O(N^2) x10000 (~O(N/50))\n"
},
{
"answer_id": 73104252,
"author": "Anthony Ngene",
"author_id": 6656762,
"author_profile": "https://Stackoverflow.com/users/6656762",
"pm_score": 0,
"selected": false,
"text": "for (auto &val: v_prime)\n v.push_back(val);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
313,434 | <p>I am having trouble setting the path to jquery in an mvc app. In my master page I have the script declared and jquery works at the root of my app. When I navigate to a content view page in my app jquery does not get loaded properly. Do I need to set the path in the content page as well or declare the path differently?</p>
<pre><code><script src="Views/Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
</code></pre>
| [
{
"answer_id": 313856,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 4,
"selected": false,
"text": "<script src=\"<%= Url.Content(\"~/Content/jquery-1.2.6.min.js\") %>\" type=\"text/javascript\"></script>\n"
},
{
"answer_id": 315211,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 1,
"selected": false,
"text": "public static class Helper\n{\n private static string ScriptsRoot = \"~/views/scripts/\";\n\n public static string ScriptUrl (string scriptFile)\n {\n return VirtualPathUtility.ToAbsolute (ScriptsRoot + scriptFile);\n }\n}\n <script type=\"text/javascript\" src=\"<%= Helper.ScriptUrl(\"jquery-1.2.6.min.js\") %>\"></script>\n"
},
{
"answer_id": 315781,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 1,
"selected": false,
"text": "<script src=\"<%=ResolveUrl(~/Views/Scripts/jquery-1.2.6.min.js) %>\" type=\"text/javascript\"></script>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
] |
313,442 | <p>I have a website that can be accessed from www.blahblah.com and special.blahblah.com. The www site always works but occasionly I get a 'Content controls have to be top-level controls in a content page or a nested master page that references a master page' error on the special site.</p>
<p>It's exactly the same code running in both situations and the offending page doesn't even have a master page. Why would it work all the time on one and fail sometimes on the other?</p>
| [
{
"answer_id": 4300828,
"author": "Daniel Ryan",
"author_id": 515455,
"author_profile": "https://Stackoverflow.com/users/515455",
"pm_score": 2,
"selected": false,
"text": "<//asp:HyperLink>\n"
},
{
"answer_id": 11197442,
"author": "MunsterMan",
"author_id": 1198613,
"author_profile": "https://Stackoverflow.com/users/1198613",
"pm_score": 1,
"selected": false,
"text": "<ASP:CONTENT <ASP:ContentPlaceholder <ASP:CONTENT"
},
{
"answer_id": 13321239,
"author": "MGOwen",
"author_id": 87861,
"author_profile": "https://Stackoverflow.com/users/87861",
"pm_score": 3,
"selected": false,
"text": "MasterPageFile = \"TheMasterPage.master\"\n this.master.MasterPageFile = \"TheMasterPage.master\"\n"
},
{
"answer_id": 15253645,
"author": "Shawn Englerth",
"author_id": 2140982,
"author_profile": "https://Stackoverflow.com/users/2140982",
"pm_score": 1,
"selected": false,
"text": "</asp:RequiredFieldValidator>. <asp:RequiredFieldValidator ID=\"rfvx\" runat=\"server\"ErrorMessage=\" </b>\"ControlToValidate=\"xxx\" /> <asp:RequiredFieldValidator ID=\"rfvx\" runat=\"server\" ErrorMessage=\" </b>\"ControlToValidate=\"xxx\" ></asp:RequiredFieldValidator>"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10102/"
] |
313,446 | <p>Java was initially slow before the JIT but today performance is pretty close to C++. I want to know if someone has done measurable performance comparisons between the two languages? <b>Where does Java fall short when compared to C++?</b> Java provides many productivity gains to developers so they can write applications much quicker because of garbage college, lack of pointers, etc. Applications such as Firefox, Webkit and Open Office, for example, could be developed much more quickly and reliably if written in 100% Java, perhaps by a factor of 2, but developers still choose C/C++ for performance reasons. Can someone demonstrate where Java cannot be made to perform as well as C++ for applications like the ones that I mentioned.</p>
<p>Let me just add that much application work is still being done in C++ for a reason. This is meant to be more than a subjective questions. Languages with higher levels of abstraction frequently pay a performance penalty. We would all be programming in higher level languages if this penalty did not exist. Where does still Java pay in comparison to C++? Be specific.</p>
| [
{
"answer_id": 3162415,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 2,
"selected": false,
"text": "Dictionary"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,462 | <p>I'm moving from Eclipse to Visual Studio .NET and have found all my beloved hotkeys except two:</p>
<ul>
<li>in Eclipse you can press <kbd>ALT</kbd>-<kbd>←</kbd> and <kbd>ALT</kbd>-<kbd>→</kbd> to visit recent changes you have made, something I use frequently to go back to where I was in some other file and then return. Apparently in VS.NET the <kbd>CTRL</kbd>-<kbd>-</kbd> and <kbd>CTRL</kbd>-<kbd>SHIFT</kbd>-<kbd>-</kbd> do this but they don't seem to always work (e.g. on laptop, may be a numkey issue with the minus) and don't seem to follow the same algorithm of "where I was" as I am used to in Eclipse. Has anyone gotten this to work and rely on it daily, etc.?</li>
<li>in Eclipse, to move a line up or down you press <kbd>ALT</kbd>-<kbd>uparrow</kbd> or <kbd>ALT</kbd>-<kbd>downarrow</kbd> and you just move it through the code until you get it to where you want it, very nice. Also to make a copy of a line, you can press <kbd>SHIFT</kbd>-<kbd>ALT</kbd>-<kbd>uparrow</kbd> or <kbd>SHIFT</kbd>-<kbd>ALT</kbd>-<kbd>downarrow</kbd>. Both of these hotkeys even work for block of lines that you have selected. </li>
</ul>
<p>Has anyone discovered these hotkey features in Visual Studio .NET?</p>
<p><strong>A D D E N D U M :</strong></p>
<p>An example of when you would use the second feature described above is to move the bottom line here up into the for loop. In Eclipse, you would put the cursor on the Console.WriteLine and then press ALT-(uparrow), I use that all the time: one key stroke to move lines up and down.</p>
<pre><code>for (int i = 0; i < 10; i++) {
}
Console.WriteLine(i);
</code></pre>
<p>Ok, extrapolating Charlie's idea with no-selection-ctrl-c to select a line, in Visual Studio you could put your cursor on Console.WriteLine, (no selection) press <kbd>CTRL</kbd>-<kbd>X</kbd> and then move up and press <kbd>CTRL</kbd>-<kbd>V</kbd>.</p>
| [
{
"answer_id": 313475,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": false,
"text": "\n Sub CopyLineBelow()\n DTE.ActiveDocument.Selection.Collapse()\n DTE.ActiveDocument.Selection.Copy()\n DTE.ActiveDocument.Selection.Paste()\n End Sub\n\n Sub CopyLineAbove()\n DTE.ActiveDocument.Selection.Collapse()\n DTE.ActiveDocument.Selection.Copy()\n DTE.ActiveDocument.Selection.LineUp()\n DTE.ActiveDocument.Selection.Paste()\n End Sub\n \n Sub MoveLineUp()\n DTE.ActiveDocument.Selection.Collapse()\n DTE.ActiveDocument.Selection.Cut()\n DTE.ActiveDocument.Selection.LineUp()\n DTE.ActiveDocument.Selection.Paste()\n DTE.ActiveDocument.Selection.LineUp()\n End Sub\n"
},
{
"answer_id": 313495,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "ctrl-alt-r -- record mode\nctrl-c -- copy a line\nup arrow -- go up a line\nhome -- beginning of line (maybe there is a way to paste before the current line without this)\nctrl-v -- paste\nctrl-alt-r -- end record mode\n"
},
{
"answer_id": 740135,
"author": "Nicolas Dorier",
"author_id": 19803,
"author_profile": "https://Stackoverflow.com/users/19803",
"pm_score": 2,
"selected": false,
"text": "Sub LineTransposeUp()\n Dim offset As Integer\n Dim sel As TextSelection\n\n DTE.UndoContext.Open(\"LineTransposeUp\")\n\n Try\n sel = DTE.ActiveDocument.Selection\n offset = sel.ActivePoint.LineCharOffset\n sel.LineUp()\n DTE.ExecuteCommand(\"Edit.LineTranspose\")\n sel.LineUp()\n sel.MoveToLineAndOffset(sel.ActivePoint.Line, offset)\n Catch ex As System.Exception\n End Try\n\n DTE.UndoContext.Close()\nEnd Sub\n"
},
{
"answer_id": 973111,
"author": "Paul Ostrowski",
"author_id": 120212,
"author_profile": "https://Stackoverflow.com/users/120212",
"pm_score": 7,
"selected": true,
"text": "'' Duplicates the current line (or selection of lines) and places the copy\n'' one line below or above the current cursor position (based upon the parameter)\nSub CopyLine(ByVal movingDown As Boolean)\n DTE.UndoContext.Open(\"CopyLine\")\n Dim objSel As TextSelection = DTE.ActiveDocument.Selection\n\n ' store the original selection and cursor position\n Dim topPoint As TextPoint = objSel.TopPoint\n Dim bottomPoint As TextPoint = objSel.BottomPoint\n Dim lTopLine As Long = topPoint.Line\n Dim lTopColumn As Long = topPoint.LineCharOffset\n Dim lBottomLine As Long = bottomPoint.Line\n Dim lBottomColumn As Long = bottomPoint.LineCharOffset()\n\n ' copy each line from the top line to the bottom line\n Dim readLine As Long = lTopLine\n Dim endLine As Long = lBottomLine + 1\n Dim selectionPresent As Boolean = ((lTopLine <> lBottomLine) Or (lTopColumn <> lBottomColumn))\n If (selectionPresent And (lBottomColumn = 1)) Then\n ' A selection is present, but the cursor is in front of the first character\n ' on the bottom line. exclude that bottom line from the copy selection.\n endLine = lBottomLine\n End If\n\n ' figure out how many lines we are copying, so we can re-position\n ' our selection after the copy is done\n Dim verticalOffset As Integer = 0\n If (movingDown) Then\n verticalOffset = endLine - lTopLine\n End If\n\n ' copy each line, one at a time.\n ' The Insert command doesn't handle multiple lines well, and we need\n ' to use Insert to avoid autocompletions\n Dim insertLine As Long = endLine\n While (readLine < endLine)\n ' move to read postion, and read the current line\n objSel.MoveToLineAndOffset(readLine, 1)\n objSel.EndOfLine(True) 'extend to EOL\n Dim lineTxt As String = objSel.Text.Clone\n ' move to the destination position, and insert the copy\n objSel.MoveToLineAndOffset(insertLine, 1)\n objSel.Insert(lineTxt)\n objSel.NewLine()\n ' adjust the read & insertion points\n readLine = readLine + 1\n insertLine = insertLine + 1\n End While\n\n ' restore the cursor to original position and selection\n objSel.MoveToLineAndOffset(lBottomLine + verticalOffset, lBottomColumn)\n objSel.MoveToLineAndOffset(lTopLine + verticalOffset, lTopColumn, True)\n DTE.UndoContext.Close()\nEnd Sub\n\n'' Duplicates the current line (or selection of lines) and places the copy\n'' one line below the current cursor position\nSub CopyLineDown()\n CopyLine(True)\nEnd Sub\n\n'' Duplicates the current line (or selection of lines) and places the copy\n'' one line above the current cursor position\nSub CopyLineUp()\n CopyLine(False)\nEnd Sub\n\n\n'' Moves the selected lines up one line. If no line is\n'' selected, the current line is moved.\n''\nSub MoveLineUp()\n DTE.UndoContext.Open(\"MoveLineUp\")\n Dim objSel As TextSelection = DTE.ActiveDocument.Selection\n ' store the original selection and cursor position\n Dim topPoint As TextPoint = objSel.TopPoint\n Dim bottomPoint As TextPoint = objSel.BottomPoint\n Dim lTopLine As Long = topPoint.Line\n Dim lTopColumn As Long = topPoint.LineCharOffset\n Dim lBottomLine As Long = bottomPoint.Line\n Dim lBottomColumn As Long = bottomPoint.LineCharOffset()\n\n Dim textLineAbove As TextSelection = DTE.ActiveDocument.Selection\n textLineAbove.MoveToLineAndOffset(lTopLine - 1, 1, False)\n textLineAbove.MoveToLineAndOffset(lTopLine, 1, True)\n Dim indentChange As Integer = CountIndentations(textLineAbove.Text) * -1\n\n ' If multiple lines are selected, but the bottom line doesn't\n ' have any characters selected, don't count it as selected\n Dim lEffectiveBottomLine = lBottomLine\n If ((lBottomColumn = 1) And (lBottomLine <> lTopLine)) Then\n lEffectiveBottomLine = lBottomLine - 1\n End If\n\n ' move to the line above the top line\n objSel.MoveToLineAndOffset(lTopLine - 1, 1)\n ' and move it down, until its below the bottom line:\n Do\n DTE.ExecuteCommand(\"Edit.LineTranspose\")\n Loop Until (objSel.BottomPoint.Line >= lEffectiveBottomLine)\n ' Since the line we are on has moved up, our location in the file has changed:\n lTopLine = lTopLine - 1\n lBottomLine = lBottomLine - 1\n\n IndentBlockAndRestoreSelection(objSel, lBottomLine, lBottomColumn, lTopLine, lTopColumn, indentChange)\n\n DTE.UndoContext.Close()\nEnd Sub\n\n'' Moves the selected lines down one line. If no line is\n'' selected, the current line is moved.\n''\nSub MoveLineDown()\n DTE.UndoContext.Open(\"MoveLineDown\")\n Dim objSel As TextSelection = DTE.ActiveDocument.Selection\n ' store the original selection and cursor position\n Dim topPoint As TextPoint = objSel.TopPoint\n Dim bottomPoint As TextPoint = objSel.BottomPoint\n Dim lTopLine As Long = topPoint.Line\n Dim lTopColumn As Long = topPoint.LineCharOffset\n Dim lBottomLine As Long = bottomPoint.Line\n Dim lBottomColumn As Long = bottomPoint.LineCharOffset()\n\n ' If multiple lines are selected, but the bottom line doesn't\n ' have any characters selected, don't count it as selected\n Dim lEffectiveBottomLine = lBottomLine\n If ((lBottomColumn = 1) And (lBottomLine <> lTopLine)) Then\n lEffectiveBottomLine = lBottomLine - 1\n End If\n\n Dim textLineBelow As TextSelection = DTE.ActiveDocument.Selection\n textLineBelow.MoveToLineAndOffset(lEffectiveBottomLine + 1, 1, False)\n textLineBelow.MoveToLineAndOffset(lEffectiveBottomLine + 2, 1, True)\n Dim indentChange As Integer = CountIndentations(textLineBelow.Text)\n\n\n ' move to the bottom line\n objSel.MoveToLineAndOffset(lEffectiveBottomLine, 1)\n ' and move it down, which effectively moves the line below it up\n ' then move the cursor up, always staying one line above the line\n ' that is moving up, and keep moving it up until its above the top line:\n Dim lineCount As Long = lEffectiveBottomLine - lTopLine\n Do\n DTE.ExecuteCommand(\"Edit.LineTranspose\")\n objSel.LineUp(False, 2)\n lineCount = lineCount - 1\n Loop Until (lineCount < 0)\n ' Since the line we are on has moved down, our location in the file has changed:\n lTopLine = lTopLine + 1\n lBottomLine = lBottomLine + 1\n\n IndentBlockAndRestoreSelection(objSel, lBottomLine, lBottomColumn, lTopLine, lTopColumn, indentChange)\n\n DTE.UndoContext.Close()\nEnd Sub\n\n'' This method takes care of indenting the selected text by the indentChange parameter\n'' It then restores the selection to the lTopLine:lTopColumn - lBottomLine:lBottomColumn parameter.\n'' It will adjust these values according to the indentChange performed\nSub IndentBlockAndRestoreSelection(ByVal objSel As TextSelection, ByVal lBottomLine As Long, ByVal lBottomColumn As Long, ByVal lTopLine As Long, ByVal lTopColumn As Long, ByVal indentChange As Integer)\n ' restore the cursor to original position and selection\n objSel.MoveToLineAndOffset(lBottomLine, lBottomColumn)\n objSel.MoveToLineAndOffset(lTopLine, lTopColumn, True)\n If (indentChange = 0) Then\n ' If we don't change the indent, we are done\n Return\n End If\n\n If (lBottomLine = lTopLine) Then\n If (indentChange > 0) Then\n objSel.StartOfLine()\n Else\n objSel.StartOfLine()\n objSel.WordRight()\n End If\n End If\n objSel.Indent(indentChange)\n\n ' Since the selected text has changed column, adjust the columns accordingly:\n ' restore the cursor to original position and selection\n Dim lNewBottomColumn As Long = (lBottomColumn + indentChange)\n Dim lNewTopColumn As Long = (lTopColumn + indentChange)\n ' ensure that we we still on the page.\n ' The \"or\" clause makes it so if we were at the left edge of the line, we remain on the left edge.\n If ((lNewBottomColumn < 2) Or (lBottomColumn = 1)) Then\n ' Single line selections, or a bottomColumn that is already at 1 may still have a new BottomColumn of 1\n If ((lTopLine = lBottomLine) Or (lBottomColumn = 1)) Then\n lNewBottomColumn = 1\n Else\n ' If we have multiple lines selected, don't allow the bottom edge to touch the left column,\n ' or the next move will ignore that bottom line.\n lNewBottomColumn = 2\n End If\n End If\n If ((lNewTopColumn < 2) Or (lTopColumn = 1)) Then\n lNewTopColumn = 1\n End If\n\n ' restore the selection to the modified selection\n objSel.MoveToLineAndOffset(lBottomLine, lNewBottomColumn)\n objSel.MoveToLineAndOffset(lTopLine, lNewTopColumn, True)\nEnd Sub\n\n\n'' This method counts the indentation changes within the text provided as the paramter\nFunction CountIndentations(ByVal text As String) As Integer\n Dim indent As Integer = 0\n While (Text.Length > 0)\n If (Text.StartsWith(\"//\")) Then\n Dim endOfLine As Integer = Text.IndexOf(\"\\n\", 2)\n If (Equals(endOfLine, -1)) Then\n ' The remaining text is all on one line, so the '//' terminates our search\n ' Ignore the rest of the text\n Exit While\n End If\n ' continue looking after the end of line\n Text = Text.Substring(endOfLine + 1)\n End If\n\n If (Text.StartsWith(\"/*\")) Then\n Dim endComment As Integer = Text.IndexOf(\"*/\", 2)\n If (Equals(endComment, -1)) Then\n ' This comment continues beyond the length of this line.\n ' Ignore the rest of the text\n Exit While\n End If\n ' continue looking after the end of this comment block\n Text = Text.Substring(endComment + 1)\n End If\n\n If (Text.StartsWith(\"{\")) Then\n indent = indent + 1\n Else\n If (Text.StartsWith(\"}\")) Then\n indent = indent - 1\n End If\n End If\n Text = Text.Substring(1)\n End While\n Return indent\nEnd Function\n"
},
{
"answer_id": 5919492,
"author": "jdeuce",
"author_id": 742780,
"author_profile": "https://Stackoverflow.com/users/742780",
"pm_score": 0,
"selected": false,
"text": "function test()\n{\n // do stuff\n}\nConsole.WriteLine(\"test\"); \n function test()\n{\n // do stuff\n Console.WriteLine(\"test\"); \n}\n function test()\n{\n // do stuff\nConsole.WriteLine(\"test\"); \n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
313,463 | <p>Is there any way to save the state of vim settings with a document?</p>
<p>To clarify: I'm editing a document and I change a bunch of settings. I don't necessarily recall which; and I don't want to use these settings again, except for the current document. I don't want to manually try to remember what I've changed; or what the magic abbreviations are for the settings I've changed. I just want to have, say, for "mydoc.txt", a "mydoc.vim" file that puts me back where I left off, and the settings file would be saved automatically based on a vim setting, say, or maybe a ctrl-key does it before I exit. It would be handy if vim could automatically look for such a file.</p>
<p>And it would be preferable not to have to edit the settings into and out of the document itself.</p>
| [
{
"answer_id": 313466,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 7,
"selected": false,
"text": "/* ex: set tabstop=8 expandtab: */\n modeline set modeline\n"
},
{
"answer_id": 313544,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 3,
"selected": false,
"text": ":redir > textfile.txt \n:set all \n:redir END\n ~/.vimrc"
},
{
"answer_id": 313711,
"author": "Hasturkun",
"author_id": 20270,
"author_profile": "https://Stackoverflow.com/users/20270",
"pm_score": 6,
"selected": true,
"text": ":mksession\n vim -S Session.vim source Session.vim"
},
{
"answer_id": 313779,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "if has(\"autocmd\")\n autocmd BufRead,BufNewFile Makefile* :set noexpandtab\n autocmd BufRead,BufNewFile mirror.conf :set noexpandtab\n autocmd BufRead,BufNewFile *.html* :set shiftwidth=2\n autocmd BufRead,BufNewFile diff_files :set autowrite\n autocmd BufRead,BufNewFile lbnamed* :set ft=perl\n autocmd BufRead,BufNewFile *.t :set ft=perl\nendif\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31641/"
] |
313,467 | <p>I am using the rounded corners plugin for jquery and have it working rounding elements in my page. The only issue I have is that the elements appear on the page un-rounded and then round. What do I need to do so that the elements only appear rounded?</p>
<p>I originally put my script tags in the head element but should they go somewhere else in a master page to improve perf?</p>
| [
{
"answer_id": 313466,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 7,
"selected": false,
"text": "/* ex: set tabstop=8 expandtab: */\n modeline set modeline\n"
},
{
"answer_id": 313544,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 3,
"selected": false,
"text": ":redir > textfile.txt \n:set all \n:redir END\n ~/.vimrc"
},
{
"answer_id": 313711,
"author": "Hasturkun",
"author_id": 20270,
"author_profile": "https://Stackoverflow.com/users/20270",
"pm_score": 6,
"selected": true,
"text": ":mksession\n vim -S Session.vim source Session.vim"
},
{
"answer_id": 313779,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "if has(\"autocmd\")\n autocmd BufRead,BufNewFile Makefile* :set noexpandtab\n autocmd BufRead,BufNewFile mirror.conf :set noexpandtab\n autocmd BufRead,BufNewFile *.html* :set shiftwidth=2\n autocmd BufRead,BufNewFile diff_files :set autowrite\n autocmd BufRead,BufNewFile lbnamed* :set ft=perl\n autocmd BufRead,BufNewFile *.t :set ft=perl\nendif\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
] |
313,478 | <p>What's the best way to get a regular anchor (<code><a href="..."></code>) to submit the form it is embedded in when clicked?</p>
<pre><code><form>
<ul>
<li>
<p>
The link could be <span>embedded <a href="" onclick="?">at any level</a></span>
in the form, so "this.parentNode.parentNode..." is no good. :(
</p>
</li>
</ul>
</form>
</code></pre>
<p>I know that the easiest way using jQuery would be</p>
<pre><code>$('#myLink').click(function() {
$(this).parents('form:first').submit();
});
</code></pre>
<p>...but I'm trying to find a way to do this without using a library.</p>
<hr>
<p><strong>Edit</strong>: I'm really trying to find a method which doesn't require knowledge of the form (eg: its name, id, etc). This would be similar to how you could put this on an input element: <code><input onclick="this.form.submit()" /></code></p>
| [
{
"answer_id": 313480,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 5,
"selected": false,
"text": "<input> <button>"
},
{
"answer_id": 313486,
"author": "Vinny Carpenter",
"author_id": 10511,
"author_profile": "https://Stackoverflow.com/users/10511",
"pm_score": 4,
"selected": false,
"text": "\n<a href=\"#\" onclick=\"document.formName.submit();\">\n"
},
{
"answer_id": 313613,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 2,
"selected": false,
"text": "<a href=\"#\" onclick=\"document.forms[0].submit();return false;\">Submit Form</a>\n"
},
{
"answer_id": 313624,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 4,
"selected": true,
"text": "<form>\n <ul>\n <li>\n <p>\n The link could be <span>embedded <a href=\"\" onclick=\"get_form(this).submit(); return false\">at any level</a></span>\n in the form, so \"this.parentNode.parentNode...\" is no good. :(\n </p>\n </li>\n </ul>\n</form>\n\n\n\n<script type=\"text/javascript\">\n //<![CDATA[\n function get_form( element )\n {\n while( element )\n {\n element = element.parentNode\n if( element.tagName.toLowerCase() == \"form\" )\n {\n //alert( element ) //debug/test\n return element\n }\n }\n return 0; //error: no form found in ancestors\n }\n //]]>\n</script>\n"
},
{
"answer_id": 313731,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 1,
"selected": false,
"text": "function findParentForm(element) {\n if (element.parentNode.tagName.toLowerCase() == 'html') {\n throw('No Parent Form Found');\n } else if (element.parentNode.tagName.toLowerCase() == 'form') {\n return element.parentNode;\n } else {\n return findParentForm(element.parentNode);\n }\n}\n <form>\n <ul>\n <li>\n <p>\n The link could be <span>embedded <a href=\"\" onclick=\"findParentForm(this).submit(); return false;\">at any level</a></span>\n in the form, so \"this.parentNode.parentNode...\" is no good. :(\n </p>\n </li>\n </ul>\n</form>\n"
},
{
"answer_id": 313874,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "javascript: <li><p><a href=\"javascript:document.forms[0].submit();\">Click here to submit</a></p></li>\n"
},
{
"answer_id": 315959,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 1,
"selected": false,
"text": "<input type=\"submit\" value=\"send\" class=\"linkstyles\"\n onmouseenter=\"this.className+=' hovered';\"\n onmouseleave=\"this.className=this.className.replace(/(^|\\s)hovered(\\s|$)/g, '');\" />\n function submitByLink ( elm ) {\n // Move up domtree until we hit no parentNode or find a form\n while (elm) {\n elm = elm.parentNode;\n if (elm && elm.tagName == 'FORM') {\n // First chance we get, we submit the form and exit.\n // The return on the node it kills the event bubble by forwarding false to browser\n elm.submit(); \n return false;\n }\n }\n // If we got here then there is no form parent and user will be sent to link href\n}\n <a href=\"aPageExplainingWhyYouNeedJavascript.html\" onclick=\"return submitByLink(this);\">Send</a>\n"
},
{
"answer_id": 1104500,
"author": "Gav",
"author_id": 135722,
"author_profile": "https://Stackoverflow.com/users/135722",
"pm_score": 1,
"selected": false,
"text": "$(document).ready(function(){$('#submit').click(function(){$('#signup').submit();});});\n"
},
{
"answer_id": 1879215,
"author": "Jef",
"author_id": 192214,
"author_profile": "https://Stackoverflow.com/users/192214",
"pm_score": 4,
"selected": false,
"text": "<a href=\"#\" onclick=\"$(this).closest('form').submit(); return false;\">Submit</a>\n"
},
{
"answer_id": 2962329,
"author": "Graham King",
"author_id": 146620,
"author_profile": "https://Stackoverflow.com/users/146620",
"pm_score": 4,
"selected": false,
"text": "<form action=\"\">\n <a href=\"\" onclick=\"parentNode.submit();return false;\">Submit</a>\n</form>\n"
},
{
"answer_id": 6358839,
"author": "Tom",
"author_id": 168012,
"author_profile": "https://Stackoverflow.com/users/168012",
"pm_score": 1,
"selected": false,
"text": "<button class=\"submit\" type=\"submit\"><a href=\"#\" onclick=\"return false;\">Link Text</a></button>\n .submit {\n background: transparent;\n border:0;\n display: inline;\n margin: 0;\n padding: 0;\n cursor:pointer;\n}\n.submit a \n{\n color: #CEA249;\n}\n.submit:hover a\n{\n color: white;\n}\n"
},
{
"answer_id": 11022232,
"author": "Mario",
"author_id": 1454637,
"author_profile": "https://Stackoverflow.com/users/1454637",
"pm_score": 3,
"selected": false,
"text": "<input id=\"submitlink\" type=\"submit\" value=\"Text\" />\n input#submitlink {\n background: transparent;\n border: 0;\n cursor:pointer;\n margin: 0;\n padding: 0;\n color: #034af3;\n text-decoration: underline;\n}\n\ninput#submitlink:visited {\n color: #505abc;\n}\n\ninput#submitlink:hover {\n color: #1d60ff;\n text-decoration: none;\n}\n\ninput#submitlink:active {\n color: #12eb87;\n}\n"
},
{
"answer_id": 15962441,
"author": "Ionut Bajescu",
"author_id": 2196608,
"author_profile": "https://Stackoverflow.com/users/2196608",
"pm_score": 1,
"selected": false,
"text": "<form>\n<input type=\"submit\" id=\"submit\" style=\"display:none;\"/>\n<a href=\"#\" onclick=\"$('#submit').click();\">Sample Submit Trick</a> \n</form>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
313,483 | <p>I got my Xampp server running and can run my html in subdirectories now, as well (can't have spaces in the subdirectory names).</p>
<p><strong>SSI Includes or PHP Includes:</strong></p>
<p>Xampp says SSI is deactivated. Tried uncommenting the lines for includes, but it doesn't change the deactivation.</p>
<p>How do I activate SSI?</p>
<p>Then, how do I implement either SSI include statements or PHP include statements into my html to call up html files that include html, images, javascript and commands that call other javascript menu files?</p>
| [
{
"answer_id": 313500,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "<!--#include virtual=\"/something/file.html\" --> \n"
},
{
"answer_id": 384685,
"author": "Matt Kantor",
"author_id": 3625,
"author_profile": "https://Stackoverflow.com/users/3625",
"pm_score": 0,
"selected": false,
"text": "<?php include('path/to/file.php'); ?>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40091/"
] |
313,518 | <p>I have run into a bit of a desgin issue with some code that I have been working on:</p>
<p>My code basic looks like this:</p>
<p><strong>Main COM wrapper:</strong></p>
<pre><code>public class MapinfoWrapper
{
public MapinfoWrapper()
{
Publics.InternalMapinfo = new MapinfoWrapper();
}
public void Do(string cmd)
{
//Call COM do command
}
public string Eval(string cmd)
{
//Return value from COM eval command
}
}
</code></pre>
<p><strong>Public static class to hold internal referance to wrapper</strong>:</p>
<pre><code>internal static class Publics
{
private static MapinfoWrapper _internalwrapper;
internal static MapinfoWrapper InternalMapinfo
{
get
{
return _internalwrapper;
}
set
{
_internalwrapper = value;
}
}
}
</code></pre>
<p><strong>Code that uses internal wrapper instance:</strong></p>
<pre><code> public class TableInfo
{
public string Name {
get { return Publics.InternalMapinfo.Eval("String comman to get the name"); }
set { Publics.InternalMapinfo.Do("String command to set the name"); }
}
}
</code></pre>
<p>Does this smell bad to anyone? Should I be using a internal property to hold a reference to the main wrapper object or should I be using a different design here? </p>
<p>Note: The MapinfoWrapper object will be used by the outside world, so I don't really want to make that a singleton.</p>
| [
{
"answer_id": 313617,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "public class TableInfo\n{\n private IMapinfoWrapper wrapper;\n\n public TableInfo() : this(null) {}\n\n public TableInfo( IMapinfoWrapper wrapper )\n {\n // use from cache if not supplied, could create new here\n this.wrapper = wrapper ?? Publics.InternalMapInfo;\n }\n\n public string Name {\n get { return wrapper.Eval(\"String comman to get the name\"); }\n set { wrapper.Do(\"String command to set the name\"); }\n }\n}\n\npublic interface IMapinfoWrapper\n{\n void Do( string cmd );\n void Eval( string cmd );\n}\n\npublic class MapinfoWrapper \n{\n public MapinfoWrapper()\n {\n }\n\n public void Do(string cmd) \n {\n //Call COM do command\n }\n\n public string Eval(string cmd)\n {\n //Return value from COM eval command\n }\n}\n\ninternal static class Publics\n{\n private static MapinfoWrapper _internalwrapper;\n internal static MapinfoWrapper InternalMapinfo \n { \n get\n {\n if (_internalwrapper == null)\n {\n _internalwrapper = new MapinfoWrapper();\n }\n return _internalwrapper; \n }\n }\n}\n [TestMethod]\n[ExpectedException(typeof(ApplicationException))]\npublic void TestTableInfoName()\n{\n IMapinfoWrapper mockWrapper = new MockMapinfoWrapper();\n mockWrapper.ThrowDoException(typeof(ApplicationException));\n\n TableInfo info = new TableInfo( mockWrapper );\n info.Do( \"invalid command\" );\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
313,538 | <p>We are using shared hosting and the follow features are disabled.</p>
<pre><code>file_uploads = Off
allow_url_fopen = Off
allow_url_include = Off
</code></pre>
<p>We are unable to change hosting and need to figure out some workarounds. The hosting co is also not able/willing to enable these features. </p>
<p>For example:
We are calling 1 server from another in order to get content. So we do an include but since URL file include is disabled we are not sure what options we have to get the content on that second server and store it there using some kind of cache.</p>
<p>We control the content server fully (dedicated) so we can do whatever necessary just not sure if there is some easy solution to the problem. </p>
| [
{
"answer_id": 19554092,
"author": "anoopjohn",
"author_id": 722087,
"author_profile": "https://Stackoverflow.com/users/722087",
"pm_score": 0,
"selected": false,
"text": "function fetch_file($path) {\n $ch = curl_init(\"http://www.example.com/get_file?path=$path&key=security_key\");\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);\n $output = curl_exec($ch);\n curl_close($ch);\n return $output;\n}\n eval fetch_file($path);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,555 | <p>I'm looking for a small C library to handle utf8 strings.</p>
<p>Specifically, splitting based on unicode delimiters for use with stemming algorithms.</p>
<p>Related posts have suggested:</p>
<p>ICU <a href="http://www.icu-project.org/" rel="noreferrer">http://www.icu-project.org/</a> (I found it too bulky for my purposes on embedded devices)</p>
<p>UTF8-CPP: <a href="http://utfcpp.sourceforge.net/" rel="noreferrer">http://utfcpp.sourceforge.net/</a> (Excellent, but C++ not C)</p>
<p>Has anyone found any platform independent, small codebase libraries for handling unicode strings (doesn't need to do naturalisation).</p>
| [
{
"answer_id": 313596,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 4,
"selected": false,
"text": "strstr strcpy strstr"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40175/"
] |
313,567 | <p>I'm writing an application in PHP 5. I want to delete some rows in a SQLite v2 database file. I'm doing something like this:</p>
<pre><code>$sqliteConnection = new SQLiteDatabase('path/to/db');
$queryString = "DELETE FROM myTable WHERE status='not good'";
$result = $sqliteConnection->query($queryString);
</code></pre>
<p>how can I know how many rows were affected by this query? how many rows have I deleted?</p>
| [
{
"answer_id": 313574,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "sqlite_changes() dbhandle echo 'Number of rows modified: ', sqlite_changes($sqliteConnection);\n echo 'Number of rows modified: ', $sqliteConnection->changes();\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9394/"
] |
313,575 | <p>We are using OpenLDAP client library to conect to an LDAP server. The problem is that if there is no activity for some time, server (or firewall in the middle) drops TCP connection.</p>
<p>Our current implementation of "keep-alive" just does search for baseDN from time to time - any better ideas ? </p>
| [
{
"answer_id": 335368,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 1,
"selected": true,
"text": "ldap_set_option( ld, LDAP_OPT_RECONNECT, LDAP_OPT_ON );\n"
},
{
"answer_id": 2591876,
"author": "Alin",
"author_id": 275374,
"author_profile": "https://Stackoverflow.com/users/275374",
"pm_score": 2,
"selected": false,
"text": "LDAP_OPT_RECONNECT"
},
{
"answer_id": 7651493,
"author": "David M. Syzdek",
"author_id": 903194,
"author_profile": "https://Stackoverflow.com/users/903194",
"pm_score": 2,
"selected": false,
"text": "if (ldap_abandon(ld, 0, sctrls, cctrls) != LDAP_SUCCESS)\n {\n /* handle ldap error */\n };"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18174/"
] |
313,581 | <p>I have a N-Ary non sorted in any way tree and each node can have 0-N children. Given the data structure below, how can I fill the tree view assuming you have an array of TermNodes and that array is the first level of the TreeView? I have not been able to come up with a recursive way to do this.</p>
<pre><code>class TermNode
{
public string Name;
public string Definition;
public List<TermNode> Children
}
</code></pre>
| [
{
"answer_id": 313602,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList)\n{\n foreach (TermNode n in TermNodeList)\n {\n TreeNode CurrentNode = Parent.Add(n.Name);\n // no need to recurse on empty list\n if (n.List.Count > 0) BuildTreeView(CurrentNode.Nodes, n.List);\n }\n}\n\n// initial call\nList<TermNode> AllTermNodes = /* all your nodes at root level */;\n\nBuildTreeView(treeView1.Nodes, AllTermNodes);\n"
},
{
"answer_id": 313674,
"author": "Rahul",
"author_id": 11100,
"author_profile": "https://Stackoverflow.com/users/11100",
"pm_score": 1,
"selected": true,
"text": "private void /*TreeNode*/ RecursiveAdd(OntologyNode on, TreeNode tn)\n{\n if (on.Children.Count == 0)\n {\n return; \n }\n foreach (OntologyNode child in on.Children)\n {\n TreeNode tCur = tn.Nodes.Add(child.Name);\n tCur.Tag = child;//optional for some selected node events\n RecursiveAdd(child, tCur); \n }\n }\n foreach( OntologyNode on in Nodes )\n {\n if (on.IsTopLevelNode == true)// internal not pertinent to this code snippet\n {\n TreeNode tn = tvOntoBrowser.Nodes.Add(on.Name);\n tn.Tag = on;\n if (on.Children.Count > 0)\n {\n RecursiveAdd(on, tn);\n }\n }\n\n }\n"
},
{
"answer_id": 313895,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "public interface INode<T>\n{\n List<T> Children { get; }\n}\nclass TermNode:INode<TermNode>\n{\n public string Name;\n public string Definition;\n public List<TermNode> Children { get; set; }\n public TermNode()\n {\n this.Children = new List<TermNode>();\n }\n}\n\npublic class TreeBuilder<T> where T : INode<T>\n{\n public Func<T, TreeNode> obCreateNodeFunc;\n\n public void AddNode(TreeView obTreeView, T obNodeToAdd, TreeNode obParentNodeIfAny) \n {\n TreeNodeCollection obNodes;\n if (obParentNodeIfAny == null)\n {\n obNodes = obTreeView.Nodes;\n }\n else\n {\n obNodes = obParentNodeIfAny.Nodes;\n }\n int iNewNodeIndex = obNodes.Add(obCreateNodeFunc(obNodeToAdd));\n TreeNode obNewNode = obNodes[iNewNodeIndex];\n\n foreach (T child in obNodeToAdd.Children)\n {\n AddNode(obTreeView, child, obNewNode);\n }\n }\n}\n\n// calling code - Some class\n static TreeNode GetTreeNodeFor(TermNode t)\n {\n return new TreeNode(t.Name); // or any logic that returns corr TreeNode for T\n }\n\n void Main()...\n {\n TermNode[] arrNodesList; \n // populate list with nodes\n\n TreeBuilder<TermNode> tb = new TreeBuilder<TermNode>();\n tb.obCreateNodeFunc = GetTreeNodeFor;\n foreach (TermNode obNode in arrNodesList)\n {\n tb.AddNode(treeView, obNode, null);\n }\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11100/"
] |
313,584 | <p>What is the concept of erasure in generics in Java?</p>
| [
{
"answer_id": 313590,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "java.lang.Object T T java.lang.Object List<String> List<Date> typeof(T) T.class"
},
{
"answer_id": 313605,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "new ArrayList<String>() => new ArrayList()\n checkCollection ClassCastException ClassCastException java.util.Iterator Class java.util.Iterator as it is defined in Java SE version 1.4:\n\npublic interface Iterator {\n boolean hasNext();\n Object next();\n void remove();\n}\n\nClass java.util.Iterator as it is defined in Java SE version 5.0:\n\npublic interface Iterator<E> {\n boolean hasNext();\n E next();\n void remove();\n}\n"
},
{
"answer_id": 313661,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "new T[42]"
},
{
"answer_id": 957536,
"author": "jigawot",
"author_id": 117724,
"author_profile": "https://Stackoverflow.com/users/117724",
"pm_score": 5,
"selected": false,
"text": "javac -XD-printflat -d output_dir SomeFile.java\n -printflat -XD javac javac -d output_dir for for"
},
{
"answer_id": 8486923,
"author": "Parag",
"author_id": 34956,
"author_profile": "https://Stackoverflow.com/users/34956",
"pm_score": 5,
"selected": false,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class GenericsErasure {\n public static void main(String args[]) {\n List<String> list = new ArrayList<String>();\n list.add(\"Hello\");\n Iterator<String> iter = list.iterator();\n while(iter.hasNext()) {\n String s = iter.next();\n System.out.println(s);\n }\n }\n}\n import java.io.PrintStream;\nimport java.util.*;\n\npublic class GenericsErasure\n{\n\n public GenericsErasure()\n {\n }\n\n public static void main(String args[])\n {\n List list = new ArrayList();\n list.add(\"Hello\");\n String s;\n for(Iterator iter = list.iterator(); iter.hasNext(); System.out.println(s))\n s = (String)iter.next();\n\n }\n} \n"
},
{
"answer_id": 49182693,
"author": "Soner from The Ottoman Empire",
"author_id": 4990642,
"author_profile": "https://Stackoverflow.com/users/4990642",
"pm_score": 2,
"selected": false,
"text": "import java.util.ArrayList;\nimport java.util.List;\n\n\npublic class S<T> {\n\n T obj; \n\n S(T o) {\n obj = o;\n }\n\n T getob() {\n return obj;\n }\n\n public static void main(String args[]) {\n List<String> list = new ArrayList<>();\n list.add(\"Hello\");\n\n // for-each\n for(String s : list) {\n String temp = s;\n System.out.println(temp);\n }\n\n // stream\n list.forEach(System.out::println);\n }\n}\n import java.io.PrintStream;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\npublic class S {\n\n Object obj;\n\n\n S(Object var1) {\n this.obj = var1;\n }\n\n Object getob() {\n return this.obj;\n }\n\n public static void main(String[] var0) {\n\n ArrayList var1 = new ArrayList();\n var1.add(\"Hello\");\n\n\n // for-each\n Iterator iterator = var1.iterator();\n\n while (iterator.hasNext()) {\n String string;\n String string2 = string = (String)iterator.next();\n System.out.println(string2);\n }\n\n\n // stream\n PrintStream printStream = System.out;\n Objects.requireNonNull(printStream);\n var1.forEach(printStream::println);\n\n\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37626/"
] |
313,611 | <p>Ok, I am new to JQuery, I have a modal that has a asp:Literal control in it. The literal is controled by whatever link is clicked to activate the modal. So, I had hoped it would be as easy as giving the literal value onClick of the link but that's not it. </p>
<p>I'm hoping: the value of the literal is set on the page load so I have to put it in an update panel so it will change when the link is clicked. </p>
<p>Or it could be: Like javascript you have to dynamically set the value of the literal with JQuery onClick. </p>
<p>Thank you for your help. </p>
<p><strong>UPDATE</strong></p>
<p>Here is the HTML for the modal:</p>
<pre><code><div class="modal-holder" id="landing-page-modal" style="display:none">
<div class="modal">
<div class="modal-t">
<a href="#" class="modal-close">
<img src="images/modal-close.gif" border="0" alt="" />
</a>
<div class="modal-scroll">
<a href="#" class="modal-top-arrow">
<img src="images/modal-arr-t.gif" alt="" />
</a>
<a href="#" class="modal-bottom-arrow">
<img src="images/modal-arr-b.gif" alt="" />
</a>
</div>
<div class="modal-b">
<div class="modal-content">
<h2><asp:Label ID="lblModal" Text="Title" runat="server" /></h2>
<p>
<asp:Literal ID="litModal" Text="Test Data Lives Here For Now" runat="server" />
</p>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>Here is the JQuery that activates the modal when a link is clicked:</p>
<pre><code>$('.article a, #menu a, #features a').click(function(){
$('.modal-holder').css({'display': 'block'});
return false;
});
$('.modal-close').click(function(){
$('.modal-holder').css({'display': 'none'});
});
</code></pre>
<p>I want to know how to change the value of the "litModal" control within the modal before it is active. </p>
| [
{
"answer_id": 313646,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "litModal $('.article a, #menu a, #features a').click(function(anchor){\n var val = jQuery(anchor).text();\n // modify val as needed\n $('span#litModal').text( val );\n $('.modal-holder').css({'display': 'block'});\n return false;\n });\n $('.modal-close').click(function(){ $('.modal-holder').css({'display': 'none'}); });\n"
},
{
"answer_id": 313669,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "<p> <p> <div class=\"modal-content\"> landing-page-modal \"#landing-page-modal div.modal-content p\"\n $('.article a, #menu a, #features a').click( function(clickTarget){\n // set the text of the <p> to whatever you like. I took \n // the text of the element that was clicked by the user.\n $('#landing-page-modal div.modal-content p').text( $(clickTarget).text() ); \n\n // now make the whole thing visible\n $('#landing-page-modal').css({'display': 'block'});\n return false;\n});\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] |
313,615 | <p>I have a controller that returns either JSON or partial html depending on if the user is logged in. </p>
<p>Is there anyway to tell the difference once the result has been returned??
What is the best way.</p>
<p>Obviously i have different actions to complete if the response is json or if it is the partial html. With the json one i do a redirect to the login page, and with the html one i just display it. If only i could render the html server side and send it back in json format?? From what i have heard this cannot be done as yet. Thoughts?</p>
<p>Cheers.</p>
<p><strong>DUPLICATE: <a href="https://stackoverflow.com/questions/291466/can-i-evaluate-the-response-type-of-an-ajax-call-in-success-callback">Can I evaluate the response type of an $.ajax() call in success callback?</a></strong></p>
| [
{
"answer_id": 313628,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 0,
"selected": false,
"text": "application/x-format-json"
},
{
"answer_id": 313631,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "decode() undefined"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29376/"
] |
313,622 | <p>Does anyone have a Powershell script to change the credentials used by a Windows service?</p>
| [
{
"answer_id": 313637,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "$class=[WMICLASS]'\\\\.\\root\\Microsoft\\SqlServer\\ComputerManagement:SqlService'\n setserviceaccount() # Copyright Buck Woody, 2007\n# All scripts provided AS-IS. No functionality is guaranteed in any way.\n# Change Service Account name and password using PowerShell and WMI\n$class = Get-WmiObject -computername \"SQLVM03-QF59YPW\" -namespace\nroot\\Microsoft\\SqlServer\\ComputerManagement -class SqlService\n\n#This remmed out part shows the services - I'll just go after number 6 (SQL\n#Server Agent in my case):\n# foreach ($classname in $class) {write-host $classname.DisplayName}\n# $class[6].DisplayName\nstop-service -displayName $class[6].DisplayName\n\n# Note: I recommend you make these parameters, so that you don't store\n# passwords. At your own risk here!\n$class[6].SetServiceAccount(\"account\", \"password\")\nstart-service -displayName $class[6].DisplayName\n"
},
{
"answer_id": 315616,
"author": "Don Jones",
"author_id": 40405,
"author_profile": "https://Stackoverflow.com/users/40405",
"pm_score": 7,
"selected": true,
"text": "$service = gwmi win32_service -computer [computername] -filter \"name='whatever'\"\n$service.change($null,$null,$null,$null,$null,$null,$null,\"P@ssw0rd\")\n"
},
{
"answer_id": 3156649,
"author": "AndyM",
"author_id": 11538,
"author_profile": "https://Stackoverflow.com/users/11538",
"pm_score": 4,
"selected": false,
"text": "$account=\"domain\\user\"\n$password=\"passsword\"\n$service=\"name='servicename'\"\n\n$svc=gwmi win32_service -filter $service\n$svc.StopService()\n$svc.change($null,$null,$null,$null,$null,$null,$account,$password,$null,$null,$null)\n$svc.StartService()\n \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\installutil.exe\" myservice.exe /u\n \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\installutil.exe\" myservice.exe\npowershell -command - < c:\\psscripts\\changeserviceaccount.ps1\n"
},
{
"answer_id": 4370900,
"author": "Chris N",
"author_id": 532858,
"author_profile": "https://Stackoverflow.com/users/532858",
"pm_score": 5,
"selected": false,
"text": "Function Set-ServiceAcctCreds([string]$strCompName,[string]$strServiceName,[string]$newAcct,[string]$newPass){\n $filter = 'Name=' + \"'\" + $strServiceName + \"'\" + ''\n $service = Get-WMIObject -ComputerName $strCompName -namespace \"root\\cimv2\" -class Win32_Service -Filter $filter\n $service.Change($null,$null,$null,$null,$null,$null,$newAcct,$newPass)\n $service.StopService()\n while ($service.Started){\n sleep 2\n $service = Get-WMIObject -ComputerName $strCompName -namespace \"root\\cimv2\" -class Win32_Service -Filter $filter\n }\n $service.StartService()\n}\n"
},
{
"answer_id": 25604732,
"author": "grenade",
"author_id": 68115,
"author_profile": "https://Stackoverflow.com/users/68115",
"pm_score": 3,
"selected": false,
"text": "ReturnValue = 2 .\\set-servicecredentials.ps1 -password p@ssw0rd somedomain\\someuser somehost.somedomain .\\set-servicecredentials.ps1 somehost.somedomain somedomain\\someuser p@ssw0rd param (\n [alias('computer', 'c')]\n [string] $computerName = $env:COMPUTERNAME,\n\n [alias('username', 'u')]\n [string] $serviceUsername = \"$env:USERDOMAIN\\$env:USERNAME\",\n\n [alias('password', 'p')]\n [parameter(mandatory=$true)]\n [string] $servicePassword\n)\nInvoke-Command -ComputerName $computerName -Script {\n param(\n [string] $computerName,\n [string] $serviceUsername,\n [string] $servicePassword\n )\n Get-WmiObject -ComputerName $computerName -Namespace root\\cimv2 -Class Win32_Service | Where-Object { $_.StartName -eq $serviceUsername } | ForEach-Object {\n Write-Host (\"Setting credentials for service: {0} (username: {1}), on host: {2}.\" -f $_.Name, $serviceUsername, $computerName)\n $change = $_.Change($null, $null, $null, $null, $null, $null, $serviceUsername, $servicePassword).ReturnValue\n if ($change -eq 0) {\n Write-Host (\"Service Change() request accepted.\")\n if ($_.Started) {\n $serviceName = $_.Name\n Write-Host (\"Restarting service: {0}, on host: {1}, to implement credential change.\" -f $serviceName, $computerName)\n $stop = ($_.StopService()).ReturnValue\n if ($stop -eq 0) {\n Write-Host -NoNewline (\"StopService() request accepted. Awaiting 'stopped' status.\")\n while ((Get-WmiObject -ComputerName $computerName -Namespace root\\cimv2 -Class Win32_Service -Filter \"Name='$serviceName'\").Started) {\n Start-Sleep -s 2\n Write-Host -NoNewline \".\"\n }\n Write-Host \".\"\n $start = $_.StartService().ReturnValue\n if ($start -eq 0) {\n Write-Host (\"StartService() request accepted.\")\n } else {\n Write-Host (\"Failed to start service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx\" -f $start) -ForegroundColor \"red\"\n }\n } else {\n Write-Host (\"Failed to stop service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx\" -f $stop) -ForegroundColor \"red\"\n }\n }\n } else {\n Write-Host (\"Failed to change service credentials. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx\" -f $change) -ForegroundColor \"red\"\n }\n }\n} -Credential \"$env:USERDOMAIN\\$env:USERNAME\" -ArgumentList $computerName, $serviceUsername, $servicePassword\n"
},
{
"answer_id": 29754927,
"author": "MoonStom",
"author_id": 954407,
"author_profile": "https://Stackoverflow.com/users/954407",
"pm_score": 0,
"selected": false,
"text": "Carbon"
},
{
"answer_id": 49639715,
"author": "Lockszmith",
"author_id": 799379,
"author_profile": "https://Stackoverflow.com/users/799379",
"pm_score": 4,
"selected": false,
"text": "Set-Service -Credential $creds = Get-Credential\nSet-Service -DisplayName \"Remote Registry\" -Credential $creds\n"
},
{
"answer_id": 49812237,
"author": "Syed Waqas",
"author_id": 1211153,
"author_profile": "https://Stackoverflow.com/users/1211153",
"pm_score": 0,
"selected": false,
"text": "$svc=gwmi win32_service -filter 'Service Name'\n\n$svc.change($null,$null,$null,$null,$null,$null,'.\\username','password',$null,$null,$null)\n"
},
{
"answer_id": 61514179,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "icacls c:\\users\\myuser\\appdata\\roaming\\fahclient /grant \"local service:(OI)(CI)(M)\"\nsc config \"FAHClient\" obj=\"NT AUTHORITY\\LocalService\"\n"
},
{
"answer_id": 62532659,
"author": "Blue Clouds",
"author_id": 1501191,
"author_profile": "https://Stackoverflow.com/users/1501191",
"pm_score": 1,
"selected": false,
"text": "$svc = Get-WmiObject win32_service -filter \"name='serviceName'\"\n $svc.GetMethodParameters(\"change\") $svc.change($null,$null,$null,$null,$null,$null,$null,$null,$null,\"admin-username\",\"admin-password\")\n"
},
{
"answer_id": 66650248,
"author": "Silex",
"author_id": 1951468,
"author_profile": "https://Stackoverflow.com/users/1951468",
"pm_score": 2,
"selected": false,
"text": "$false $null $service = Get-WMIObject -class Win32_Service -filter \"name='serviceName'\"\n$service.change($null, $null, $null, $null, $null, $false, \"DOMAIN\\account\", \"mypassword\")\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618/"
] |
313,629 | <p>I am writing a simple memory game using ruby + qt (trying to get away from c++ for while...)<br>
In order to allow a X second timeout to view two open pieces, I need either timers or do the work in a background thread.</p>
<p>What is the simplest way of implementing this without reinventing the wheel?<br>
Ruby threads? Qt threads? Qt timers?</p>
| [
{
"answer_id": 558119,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "block=Proc.new{ Thread.pass }\ntimer=Qt::Timer.new(window)\ninvoke=Qt::BlockInvocation.new(timer, block, \"invoke()\")\nQt::Object.connect(timer, SIGNAL(\"timeout()\"), invoke, SLOT(\"invoke()\"))\ntimer.start(1)\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,639 | <p>I have two UIActionSheets and I am thinking that I will control them with one delegate (the UIViewController that instantiates them). The delegate will capture an actionSheet call and try to figure out which of the two threw the event.</p>
<p>I tried to get the modalView's title to differentiate, but it seems to be invalid...</p>
<p>Should this work? </p>
<p>If not, is there some other way to distinguish which UIActionSheet did the event?</p>
<p>Or do I need to create two different classes that will be separate delegates for each UIActionSheet?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 313667,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 5,
"selected": false,
"text": "UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle ... ];\nactionSheet.tag = 10;\n[actionSheet showInView:self.view];\n - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {\n switch (actionSheet.tag) {\n case 10:\n ...\n }\n}\n"
},
{
"answer_id": 971267,
"author": "David Kanarek",
"author_id": 98848,
"author_profile": "https://Stackoverflow.com/users/98848",
"pm_score": 3,
"selected": false,
"text": "- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {\n if(actionSheet == myDoSomethingActionSheet) {\n if(buttonIndex == 0) {\n [self doThingA];\n return;\n }\n if(buttonIndex == 1) {\n [self doThingB];\n return;\n }\n }\n if(actionSheet == myOtherActionSheet) {\n if(buttonIndex == 3) {\n [self doImportantThing];\n return;\n }\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.