qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
291,162 | <p>I have a form that contains a bunch of checkboxes. Before submitting the form, I'd like to grab the values of the checkboxes and stick them into a text field, then submit that.</p>
<p>So I might have:
Red
Orange
X Yellow
Blue
X Green</p>
<p>And I'd like my textfield to end up with the content "Yellow, Green" . </p>
<p>This doesn't seem too complicated, but I am totally out of my league. I already use jQuery for a few other things so I have the framework ready, if that makes it easer.</p>
<p>Thanks for any advice --</p>
| [
{
"answer_id": 291181,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "var serializedCheckboxes = '';\n$(\"input type='checkbox'\").each(function() {\n if($(this).attr(\"checked\")) {\n serializedCheckboxes += $(this).attr(\"value\") + ',';\n }\n});\n\n$(\"input name='allchecks').attr(\"value\", serializedCheckboxes);\n"
},
{
"answer_id": 291196,
"author": "Falco Foxburr",
"author_id": 37266,
"author_profile": "https://Stackoverflow.com/users/37266",
"pm_score": 0,
"selected": false,
"text": "var serializedCheckboxes = '';\n$(\"input[type=checkbox]\").each(function() {\n if($(this).attr(\"checked\")) {\n serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr(\"value\");\n }\n});\n\n$(\"input[name=allchecks]\").attr(\"value\", serializedCheckboxes);\n"
},
{
"answer_id": 291251,
"author": "Falco Foxburr",
"author_id": 37266,
"author_profile": "https://Stackoverflow.com/users/37266",
"pm_score": 3,
"selected": true,
"text": "$(function(){\n $('#YourFormID').bind('submit',function(){\n var serializedCheckboxes = '';\n $(\"input[type=checkbox]\").each(function() {\n if($(this).attr(\"checked\")) {\n serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr(\"value\");\n }\n });\n $(\"input[name=allchecks]\").attr(\"value\", serializedCheckboxes);\n });\n});\n"
},
{
"answer_id": 291381,
"author": "Falco Foxburr",
"author_id": 37266,
"author_profile": "https://Stackoverflow.com/users/37266",
"pm_score": 0,
"selected": false,
"text": "$(function(){\n $('#YourFormID').bind('submit',function(){\n var serializedCheckboxes = '';\n $(this).find(\"input[type=checkbox]\").filter('.colorCheckBoxes').each(function() {\n if($(this).attr(\"checked\")) {\n serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr(\"value\");\n }\n });\n if (serializedCheckboxes != '')\n $(this).find(\"input[name=allchecks]\").attr(\"value\", serializedCheckboxes);\n });\n});\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,163 | <p>I'm having a hard time determining what characters <strong>must</strong> be escaped when using Perl's qr{} construct</p>
<p>I'm attempting to create a multi-line precompiled regex for text that contains a myriad of normally escaped characters (#*.>:[]) and also contains another precompiled regex. Additionally I need to match as strictly as possible for testing purposes.</p>
<pre><code>my $output = q{# using defaults found in .config
*
*
Options:
1. opt1
> 2. opt2
choice[1-2?]: };
my $sc = qr{(>|\s)}smx;
my $re = qr{# using defaults found in .config
*
*
Options:
$sc 1. opt1
$sc 2. opt2
choice[1-2?]: }mx;
if ( $output =~ $re ) {
print "OK!\n";
}
else {
print "D'oh!\n";
}
</code></pre>
<p>Error:</p>
<pre><code>Quantifier follows nothing in regex; marked by <-- HERE in m/# using defaults found in .config
* <-- HERE
*
Options:
(?msx-i:(>|\s)) 1. opt1
(?msx-i:(>|\s)) 2. opt2
choice[1-2?]: / at ./so.pl line 14.
</code></pre>
<p>Attempting to escape the asterisks results in a failed match (D'oh output). Attempting to escape other pesky chars also results in a failed match. I could continue trying different combos of what to escape, but there's a lot of variations here and am hoping someone could provide some insight.</p>
| [
{
"answer_id": 291194,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 5,
"selected": true,
"text": "my $sc = qr{(>|\\s)};\n\nmy $re = qr{# using defaults found in \\.config\n\\*\n\\*\nOptions:\n$sc 1\\. opt1\n$sc 2\\. opt2\nchoice\\[1-2\\?]: };\n"
},
{
"answer_id": 291215,
"author": "geocar",
"author_id": 37507,
"author_profile": "https://Stackoverflow.com/users/37507",
"pm_score": 3,
"selected": false,
"text": "} .[$()|*+?{\\"
},
{
"answer_id": 291229,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 2,
"selected": false,
"text": "qr//x /x"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214705/"
] |
291,166 | <p>Which one do you prefer to store text in your database? The original casing of the data, or some kind of normalization. Also, should I enforce this with triggers? or should I preprocess input data with client code?</p>
<p>I ask you, because I'm not sure about if there is any difference, besides additional processing time to display data (capitalization of names, for example).</p>
| [
{
"answer_id": 291217,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 3,
"selected": false,
"text": "create table case_test (\n id integer,\n name varchar2(30));\n\ncreate index ucasename on case_test(upper(name));\n select * from case_test where upper(name) like 'TUCK%'; \n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
] |
291,169 | <p>I am trying to use the Event Log to write some debug information and I can't make it works. It complains about not being able to find the Event Source. Do I have to install something on the OS?</p>
| [
{
"answer_id": 291174,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": true,
"text": "System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog();\nstring eventLogName = \"StackOverFlowEventName\";\nstring eventLogSource = \"StackOverFlowWebsite\";\n\n//This code HERE will create the Event for you\nif (!System.Diagnostics.EventLog.SourceExists(eventLogSource))\n{\n System.Diagnostics.EventLog.CreateEventSource(eventLogSource, eventLogName);\n}\n\neventLog1.Source = eventLogSource;\neventLog1.Log = eventLogName;\neventLog1.WriteEntry(\"This is a test\");\n"
},
{
"answer_id": 291187,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 0,
"selected": false,
"text": "System.Diagnostics.EventLog.WriteEntry(assemblyName, \"Error stuff\", System.Diagnostics.EventLogEntryType.Error);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
291,172 | <p>I'm trying to get the following SQL statement to work:</p>
<pre><code>UPDATE myschema.tableA update_tableA
SET field_id =
( SELECT src.field_id
FROM myschema.srcTable src
INNER JOIN myschema.tableB tableB ON
update_tableA.id = tableB.id
AND SDO_ANYINTERACT( tableB.shape, src.shape ) = 'TRUE' );
</code></pre>
<p>When I run this statement, I get the following error:</p>
<pre><code>ORA-00904: "UPDATE_TABLEA"."ID": invalid identifier
</code></pre>
<p>Can I not use a variable scoped outside of the nested select within the nested select? Any thoughts?</p>
<p>P.S. The identifier is indeed valid in the database table. The problem appears to be scope, but I want to make sure that is indeed an issue.</p>
| [
{
"answer_id": 291258,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "\nSELECT src.field_id \n FROM myschema.srcTable src\n INNER JOIN myschema.tableB tableB ON \n"
},
{
"answer_id": 291399,
"author": "Leigh Riffel",
"author_id": 27010,
"author_profile": "https://Stackoverflow.com/users/27010",
"pm_score": 0,
"selected": false,
"text": "drop table test;\ncreate table test as (select 1 key, 'a' value from dual);\ninsert into test values (2,'b');\nselect * from test;\nupdate test t1 \n set value = (select 'c' from dual where t1.key=2);\nselect * from test;\n"
},
{
"answer_id": 291409,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 3,
"selected": true,
"text": "UPDATE myschema.tableA update_tableA\n SET field_id = \n ( SELECT src.field_id \n FROM myschema.srcTable src\n INNER JOIN myschema.tableB tableB ON \n SDO_ANYINTERACT( tableB.shape, src.shape ) = 'TRUE'\n WHERE update_tableA.id = tableB.id \n );\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
] |
291,189 | <p>It has to be simple, here's my CSS: </p>
<pre><code>.progressImage
{
position:relative;
top:50%;
}
.progressPanel
{
height:100%;
width:100%;
text-align:center;
display:none;
}
<asp:Panel ID="pnlProgress" runat="server" CssClass="progressPanel">
<asp:Image ID="Image1" runat="server" CssClass="progressImage" ImageUrl="~/Images/Icons/loading.gif" />
</asp:Panel>
</code></pre>
<p>I toggle panel display depending on user action.</p>
<p>Works great in FireFox, but shows up at the top of the page in Safari.</p>
<p>p.s. "vertical-align:middle;" doesn't work either. </p>
<p>p.p.s. setting "position:relative;" on the panel doesn't work, setting "position:relative;" on the panel and "position:absolute;" on the image breaks it in FF and does nothing in Safari</p>
<p>THIS WORKED:</p>
<pre><code>.progressPanel
{
height:100%;
width:100%;
position:relative;
}
.progressImage
{
position:absolute;
top:50%;
left:50%;
}
</code></pre>
| [
{
"answer_id": 291245,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 2,
"selected": false,
"text": ".progressPanel\n{\n height:100%;\n width:100%;\n text-align:center;\n display:none;\n position: relative;\n}\n background: url('path/to/image.gif') no-repeat center middle;\n"
},
{
"answer_id": 291288,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": true,
"text": ".progressPanel .progressImage <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n <head>\n <title>Test</title>\n <style type=\"text/css\">\n body {\n height:700px;\n }\n .progressImage {\n position:absolute;\n top:50%;\n left:50%;\n margin-left:-16px;\n margin-top:-16px;\n }\n\n .progressPanel {\n position:relative;\n height:100%;\n width:100%;\n text-align:center;\n background:red;\n }\n </style>\n </head>\n <body>\n <div class=\"progressPanel\"><img class=\"progressImage\" src=\"pic.jpg\"/></div>\n </body>\n</html>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
291,249 | <p>I need to store a tree data structure in my database, for which I plan on using <a href="http://code.google.com/p/django-treebeard/" rel="noreferrer">django-treebeard</a> or possibly <a href="http://code.google.com/p/django-mptt/" rel="noreferrer">django-mptt</a>. My source of confusion is that each node could be one of three different possible types: root nodes will always be a type A entity, leaf nodes a type C entity, and anything in between will be a type B entity. I would like to know the best way to model this situation.</p>
<p><strong>update:</strong> I first tried model inheritance, and I think that this could be the best way to go. Unfortunately django-treebeard's public API isn't really designed to handle this. I ended up getting it to work with GenericForeignKey. Thank you very much for the answers.</p>
| [
{
"answer_id": 291981,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "MyNode treebeard.Node class MyA( treebeard.Node ):\n pass\n\nclass MyB( treebeard.Node ):\n pass\n\nclass MyC( treebeard.Node ):\n pass\n MyC MyC MyB"
},
{
"answer_id": 292486,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 3,
"selected": true,
"text": "from django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Node(models.Model):\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n object = generic.GenericForeignKey('content_type', 'object_id')\n # Assuming mptt, as I'm not familiar with treebeard's API\n\n# 1 query to retrieve the tree\ntree = list(Node.tree.all())\n\n# 4 queries to retrieve and cache all ContentType, A, B and C instances, respectively\npopulate_content_object_caches(tree)\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595/"
] |
291,252 | <p>Several times in my career, I have worked in a software group that determined that <br><br>
a) We needed a build/test system<br>
b) We should write our own<br>
c) We can have a developer spend a week, get it done and they shouldn't have to touch it again</p>
<p>Every time, this has resulted in a system that only seems to work for the person that wrote it and requires their constant attention. I've spent time on several occasions looking for a tool that I could grab that would serve our needs, but come up empty-handed. Generally, tools like this server a very narrow market. I'm at the point again of needing something like this. Is there something out there, or do we write it again?<br><br>Here are my requirements in priority order (the last few are just nice to have):<br></p>
<ol>
<li><p>Ability to handle a multi-project build. We have several components that both provide things other components use and use things from other components. A developer should be able to check out 1 component and make changes without having to build the world. Dependencies outside the project should be pulled in automatically. So some way to be able to push and pull the built objects to a server is critical for this. Another aspect of this is the ability to be able to pull down all dependencies to a local directory for development on the road.</p></li>
<li><p>Don't worry about exactly how things get built. This may sound weird, but I don't want the build system to worry about compiling my code. There are already great tools that do this for every language - Ant, CMake, etc. I just want to tell it what to call to make things build, and what output it should care about. This way, Project A can be in Java, Project B can be in C++, you get the idea.</p></li>
<li><p>Have some way to run tests on the output</p></li>
<li><p>Show the current build/test results on a web page</p></li>
<li><p>Email the results</p></li>
<li><p>Integration with RCS (we use svn)</p></li>
</ol>
| [
{
"answer_id": 292873,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "1..N\nok 1 Description # Directive\n# Diagnostic\n....\nok 47 Description\nok 48 Description\nmore tests....\n 1..4\nok 1 - Input file opened\nnot ok 2 - First line of the input valid\nok 3 - Read the rest of the file\nnot ok 4 - Summarized correctly # TODO Not written yet\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16476/"
] |
291,274 | <p>I am using the Html.TextBox helper to create textboxes. I want to set attributes on the textbox, which I understand is done using the following overload: </p>
<p><code>Html.TextBox (string name, object value, object htmlAttributes)</code></p>
<p>However, I want to maintain the functionality where the HTML helper automatically uses the value from either ViewData or ViewData.Model and I do not see a way to just specify the name and the htmlAttributes. Is this possible?</p>
| [
{
"answer_id": 291295,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 7,
"selected": true,
"text": "Html.TextBox( \"name\", null, new { @class = \"css-class\" } );\n"
},
{
"answer_id": 291317,
"author": "Andrew Van Slaars",
"author_id": 8087,
"author_profile": "https://Stackoverflow.com/users/8087",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\" name=\"fieldName\" id=\"fieldName\"/>\n"
},
{
"answer_id": 8621370,
"author": "Jon Crowell",
"author_id": 138938,
"author_profile": "https://Stackoverflow.com/users/138938",
"pm_score": 2,
"selected": false,
"text": " <% foreach (var poPart in Model.myPartsList)\n { %>\n <tr>\n <td>\n <% var part = Model.PartID; %>\n <%: Html.TextBox(part.ToString(), null, new { @class = \"narrowText\", @id = part.ToString() })%>\n </td>\n </tr>\n <% } %>\n"
},
{
"answer_id": 21981396,
"author": "VnDevil",
"author_id": 1326699,
"author_profile": "https://Stackoverflow.com/users/1326699",
"pm_score": 3,
"selected": false,
"text": "@Html.TextBox(\"name\", \"\", new {@class = \"css-class\", @onclick = \"alert('demo');\"});\n"
},
{
"answer_id": 36680570,
"author": "Newred",
"author_id": 1628651,
"author_profile": "https://Stackoverflow.com/users/1628651",
"pm_score": 0,
"selected": false,
"text": " @Html.TextBox(\"Name\", \"Value\", new {@class = \"class1 class2\", @customAttributeName = \"attributeValue\"})\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37786/"
] |
291,304 | <p>I'm having an issue with JQuery and Safari (Windows Version). The code works on FF/IE7/Chrome but not Safari.</p>
<p>I have a simple <code><li></code> that has a <code><div></code> embedded in to - clicking the <code><li></code> should expose the hidden <code>div</code>, but not in Safari.</p>
<p>The HTML:</p>
<pre><code><ul>
<li>something</li>
<li>something2</li>
<li class="more">
<a href="" class="moreFacetsLink">Click to see more options</a>
<div class="moreFacets">bunch of text</div>
</li>
</ul>
</code></pre>
<p>Here is the JQuery code:</p>
<p><pre><code>
$('.moreFacetsLink').click(function () {<br>
$(this).siblings('div').toggle();
});
</pre></code></p>
<p>Any thoughts as to what may be going on here? Again - this seems to work on all other browsers!</p>
<p>I'm a newbie when it comes to JQuery.</p>
<p>Thanks! </p>
| [
{
"answer_id": 291417,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 1,
"selected": false,
"text": "$(\".moreFacetsLink\").click(function () {\n $(this).siblings(\"a\").children(\"div\").toggle();\n});\n"
},
{
"answer_id": 3894141,
"author": "Scott Rippey",
"author_id": 272072,
"author_profile": "https://Stackoverflow.com/users/272072",
"pm_score": 0,
"selected": false,
"text": "return false;"
},
{
"answer_id": 5887384,
"author": "Edgar",
"author_id": 714431,
"author_profile": "https://Stackoverflow.com/users/714431",
"pm_score": 0,
"selected": false,
"text": "$('.moreFacetsLink').click(function (e) {\n e.preventDefault(); // this prevent postback\n\n $(e.target).siblings('div').toggle();\n});\n $(e.target) $(this)"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,326 | <p>I'm using the command line compiler for builds. One problem I see is that the paths mentioned there seem to need to be the short versions of the filenames such that they don't contain any spaces. I don't know so much about this even though I have used it for some time.</p>
<p>I recently upgraded to d2009 and the problem started then.</p>
<p>Is there a way around shortening the path? </p>
<p>I should say I'm not eager to change to use the MS Build tool at this time. I just want to build an old copy of my app & get back to other work.</p>
<p>Here's the path used in the <code>dcc32.cfg</code> file for the <code>-I</code>, <code>-U</code>, <code>-O</code>, and <code>-R</code> parameters:</p>
<pre><code>$(BDS)\LIB;$(BDS)\Imports;$(BDS)\Lib\Indy10;C:\PROGRA~1\Borland\BDS\4.0\RAVERE~1\Lib;c:\prj\lib\lib2002;C:\DOCUME~1\ALLUSE~1\DOCUME~1\RADSTU~1\5.0\Bpl;c:\DOCUME~1\mike\MYDOCU~1\BORLAN~1\bpl;C:\Prj\Lib\LOCKBO~1\source;C:\Prj\Lib\MyComp;C:\Prj\Lib\ABBREV~1\source;C:\Prj\Lib\ZLib;C:\Prj\Lib\MinMod;C:\Prj\Lib\HELPMA~1;C:\Prj\Lib\DXGETT~1;c:\windows\system32;c:\prj\lib\xpburn;C:\Prj\Lib\WININE~1;C:\Prj\Lib\regexpr\Source;C:\Prj\Lib\VCARDR~1;C:\PROGRA~1\Raize\RC4\Lib\BDS2006;C:\Prj\Lib\jcl\lib\d10;C:\Prj\Lib\jcl\source;C:\Prj\Lib\jvcl\lib\D10;C:\Prj\Lib\jvcl\common;C:\Prj\Lib\jvcl\RESOUR~1;C:\Prj\Lib\ProE6\Delphi;C:\Prj\Lib\FastMM4;C:\Prj\Lib\OPENOF~1;C:\Prj\Lib\DEVELO~1\Library\Delphi11;C:\Prj\Lib\DEVELO~1\EX38D9~1\Sources;C:\Prj\Lib\DEVELO~1\EXBD88~1\Sources;C:\Prj\Lib\DEVELO~1\XPTHEM~1\Sources;C:\Prj\Lib\DEVELO~1\EX2EBC~1\Sources;C:\Prj\Lib\DEVELO~1\EXC5FB~1\Sources;C:\Prj\Lib\DEVELO~1\EX7C7C~1\Sources;C:\Prj\Lib\DEVELO~1\EXPRES~3\Sources;C:\Prj\Lib\DEVELO~1\EXPRES~4\Sources;C:\Prj\Lib\DEVELO~1\EXC73B~1\Sources;C:\Prj\Lib\DEVELO~1\EX7165~1\Sources;C:\Prj\Lib\DEVELO~1\EXPRES~2\Sources;C:\Prj\Lib\DEVELO~1\EXPRES~1\Sources;C:\Prj\Lib\DEVELO~1\EX749C~1\Sources;C:\Prj\Lib\DEVELO~1\EX0A1A~1\Sources;C:\Prj\Lib\Mad\madBasic\BDS4;C:\Prj\Lib\Mad\MADDIS~1\BDS4;C:\Prj\Lib\Mad\MADEXC~1\BDS4;C:\Prj\Lib\Mad\MADKER~1\BDS4;C:\Prj\Lib\Mad\MADSEC~1\BDS4;C:\Prj\Lib\Mad\madShell\BDS4;C:\Prj\Lib\Mad\madShell\DeXter;C:\Prj\Lib\Mad\madExcept\..\Plugins;
</code></pre>
<p>I've copied it from the IDE's path like I have done in the path and used a program to shorten the path names.</p>
<p>Although there are no spaces in that path, it still can't find indy's <code>IdCoder.dcu</code> at <code>C:\Program Files\CodeGear\RAD Studio\5.0\lib\Indy10</code></p>
<p>According to the d2007 environment variables, <code>$(BDS)</code> would apparently expand to <code>c:\program files\codegear\rad studio\5.0</code></p>
<p>The IDE is considering this library path to be valid.</p>
<p>Why is this happening? I bet it's a simple mistake I haven't thought of!</p>
<p>Thank you for your help!</p>
| [
{
"answer_id": 291441,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 3,
"selected": true,
"text": "$(BDS)\\Lib\\Indy10\n \"$(BDS)\\Lib\\Indy10\"\n \"C:\\Program Files\\CodeGear\\RAD Studio\\5.0\\lib\\Indy10\"\n"
},
{
"answer_id": 5277812,
"author": "William Egge",
"author_id": 655931,
"author_profile": "https://Stackoverflow.com/users/655931",
"pm_score": 2,
"selected": false,
"text": "G: cd \\Apps\\MyProject"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14031/"
] |
291,328 | <p>I am trying to create a delegate protocol for a custom UIView. Here is my first attempt:</p>
<pre><code>@protocol FunViewDelegate
@optional
- (void) funViewDidInitialize:(FunView *)funView;
@end
@interface FunView : UIView {
@private
}
@property(nonatomic, assign) id<FunViewDelegate> delegate;
@end
</code></pre>
<p>This doesn't work because the FunView interface has not been declared at the time of the FunViewDelegate declaration. I have tried adding a prototype ala C++ before the @protocol:</p>
<pre><code>@interface FunView;
</code></pre>
<p>But this just drives the compiler nuts. How am I supposed to do this?</p>
| [
{
"answer_id": 291408,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": false,
"text": "@protocol FunViewDelegate;\n\n@interface FunView : UIView { \n@private\n id<FunViewDelegate> delegate;\n}\n@property(nonatomic, assign) id<FunViewDelegate> delegate;\n@end\n\n@protocol FunViewDelegate\n@optional\n- (void) funViewDidInitialize:(FunView *)funView;\n@end\n"
},
{
"answer_id": 291416,
"author": "Jens Ayton",
"author_id": 6443,
"author_profile": "https://Stackoverflow.com/users/6443",
"pm_score": 4,
"selected": true,
"text": "@class Foo; @interface Foo;"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
291,336 | <p>I have a folder in NTFS that contains tens of thousands of files. I've deleted all files in that folder, save 1. I ran contig.exe to defragment that folder so now it's in 1 fragment only. However, the size of that folder is still 8MB in size. This implies that there's a lot of gap in the index. Why is that? If I delete that one file, the size of the index automatically goes to zero. My guess is because it gets collapsed into the MFT. Is there any way to get NTFS to truly defragment the index file by defragmenting it based on the content of the file? Any API that you're aware of? Contig.exe only defragment the physical file.</p>
| [
{
"answer_id": 292402,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 4,
"selected": true,
"text": "REM Invoke as \"collapse dirname\"\nren dirname dirname.old\nmkdir dirname\ncd dirname.old\nmove * ../dirname/\ncd ..\nrmdir dirname.old\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13484/"
] |
291,340 | <p>Is there a simple attribute or data contract that I can assign to a function parameter that prevents <code>null</code> from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal <code>null</code> isn't being used anywhere for it and at run-time throw <code>ArgumentNullException</code>.</p>
<p>Currently I write something like ...</p>
<pre><code>if (null == arg)
throw new ArgumentNullException("arg");
</code></pre>
<p>... for every argument that I expect to not be <code>null</code>.</p>
<p>On the same note, is there an opposite to <code>Nullable<></code> whereby the following would fail:</p>
<pre><code>NonNullable<string> s = null; // throw some kind of exception
</code></pre>
| [
{
"answer_id": 291357,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "if (null == arg) if (arg == null)"
},
{
"answer_id": 291490,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 3,
"selected": false,
"text": "private MyType _someVariable = TenantType.None;\n[NotNullValidator(MessageTemplate = \"Some Variable can not be empty\")]\npublic MyType SomeVariable {\n get {\n return _someVariable;\n }\n set {\n _someVariable = value;\n }\n}\n Microsoft.Practices.EnterpriseLibrary.Validation.Validator myValidator = ValidationFactory.CreateValidator<MyClass>();\n\nValidationResults vrInfo = InternalValidator.Validate(myObject);\n"
},
{
"answer_id": 5552096,
"author": "Jeff Grizzle",
"author_id": 692906,
"author_profile": "https://Stackoverflow.com/users/692906",
"pm_score": 0,
"selected": false,
"text": "public static bool ContainsNullParameters(object[] methodParams)\n{\n return (from o in methodParams where o == null).Count() > 0;\n}\n public static bool ContainsNullParameters(Dictionary<string, object> methodParams, out ArgumentNullException containsNullParameters)\n {\n var nullParams = from o in methodParams\n where o.Value == null\n select o;\n\n bool paramsNull = nullParams.Count() > 0;\n\n\n if (paramsNull)\n {\n StringBuilder sb = new StringBuilder();\n foreach (var param in nullParams)\n sb.Append(param.Key + \" is null. \");\n\n containsNullParameters = new ArgumentNullException(sb.ToString());\n }\n else\n containsNullParameters = null;\n\n return paramsNull;\n }\n"
},
{
"answer_id": 7654624,
"author": "Martin Capodici",
"author_id": 417377,
"author_profile": "https://Stackoverflow.com/users/417377",
"pm_score": -1,
"selected": false,
"text": "public static string Default(this string x)\n{\n return x ?? \"\";\n}\n if (model.Day.Default() == \"\")\n{\n //.. Do something to handle no Day ..\n}\n"
},
{
"answer_id": 48690719,
"author": "Greg",
"author_id": 1288589,
"author_profile": "https://Stackoverflow.com/users/1288589",
"pm_score": 5,
"selected": false,
"text": "public class Person\n{\n public string Name { get; set; } // Not Null\n public string? Address { get; set; } // May be Null\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
291,343 | <p><strong>SpousesTable</strong>
<em>SpouseID</em></p>
<p><strong>SpousePreviousAddressesTable</strong>
<em>PreviousAddressID</em>, <em>SpouseID</em>, FromDate, AddressTypeID</p>
<p>What I have now is updating the most recent for the whole table and assigning the most recent regardless of SpouseID the AddressTypeID = 1</p>
<p>I want to assign the most recent SpousePreviousAddress.AddressTypeID = 1
for each unique SpouseID in the SpousePreviousAddresses table.</p>
<pre><code>UPDATE spa
SET spa.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa INNER JOIN Spouses ON spa.SpouseID = Spouses.SpouseID,
(SELECT TOP 1 SpousePreviousAddresses.* FROM SpousePreviousAddresses
INNER JOIN Spouses AS s ON SpousePreviousAddresses.SpouseID = s.SpouseID
WHERE SpousePreviousAddresses.CountryID = 181 ORDER BY SpousePreviousAddresses.FromDate DESC) as us
WHERE spa.PreviousAddressID = us.PreviousAddressID
</code></pre>
<p>I think I need a group by but my sql isn't all that hot. Thanks.</p>
<p><strong>Update that is Working</strong></p>
<p>I was wrong about having found a solution to this earlier. Below is the solution I am going with</p>
<pre><code>WITH result AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) AS rowNumber, *
FROM SpousePreviousAddresses
WHERE CountryID = 181
)
UPDATE result
SET AddressTypeID = 1
FROM result WHERE rowNumber = 1
</code></pre>
| [
{
"answer_id": 291358,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "UPDATE spa SET spa.AddressTypeID = 1 \n WHERE spa.SpouseID IN (\n SELECT DISTINCT s1.SpouseID FROM Spa S1, SpousePreviousAddresses S2\n WHERE s1.SpouseID = s2.SpouseID \n AND s2.CountryID = 181 \n AND s1.PreviousAddressId = s2.PreviousAddressId\n ORDER BY S2.FromDate DESC)\n"
},
{
"answer_id": 291565,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "UPDATE spa1\nSET spa1.AddressTypeID = 1\nFROM SpousePreviousAddresses AS spa1 \n LEFT OUTER JOIN SpousePreviousAddresses AS spa2\n ON (spa1.SpouseID = spa2.SpouseID AND spa1.FromDate < spa2.FromDate)\nWHERE spa1.CountryID = 181 AND spa2.SpouseID IS NULL;\n spa1 spa2 SpouseID SpouseID GROUP BY OUTER JOIN spa2 spa2.* spa1 spa2 spa2.SpouseID IS NULL"
},
{
"answer_id": 291612,
"author": "jheppinstall",
"author_id": 21197,
"author_profile": "https://Stackoverflow.com/users/21197",
"pm_score": 4,
"selected": true,
"text": "WITH result AS\n(\nSELECT \n ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) as rowNumber,\n * \nFROM \n SpousePreviousAddresses\n)\n UPDATE SpousePreviousAddresses\n SET\n AddressTypeID = 2\n FROM \n SpousePreviousAddresses spa\n INNER JOIN result r ON spa.SpouseId = r.SpouseId\n WHERE r.rowNumber = 1\n AND spa.PreviousAddressID = r.PreviousAddressID\n AND spa.CountryID = 181\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30930/"
] |
291,344 | <p>Are they the same thing? Just finished to watch <a href="https://www.asp.net/mvc/videos/mvc-1/aspnet-mvc-storefront/aspnet-mvc-storefront-part-1-architectural-discussion-and-overview" rel="noreferrer">Rob Connery's Storefront tutorial</a> and they seem to be similar techinques. I mean, when I implement a DAL object I have the GetStuff, Add/Delete etc methods and I always write the interface first so that I can switch db later. </p>
<p>Am I confusing things?</p>
| [
{
"answer_id": 293013,
"author": "Kim Major",
"author_id": 32498,
"author_profile": "https://Stackoverflow.com/users/32498",
"pm_score": 7,
"selected": false,
"text": "public interface IRepository : IDisposable\n{\n T[] GetAll<T>();\n T[] GetAll<T>(Expression<Func<T, bool>> filter);\n T GetSingle<T>(Expression<Func<T, bool>> filter);\n T GetSingle<T>(Expression<Func<T, bool>> filter, List<Expression<Func<T, object>>> subSelectors);\n void Delete<T>(T entity);\n void Add<T>(T entity);\n int SaveChanges();\n DbTransaction BeginTransaction();\n}\n"
},
{
"answer_id": 1029544,
"author": "Thomas Jung",
"author_id": 119259,
"author_profile": "https://Stackoverflow.com/users/119259",
"pm_score": 4,
"selected": false,
"text": "specification100 = new AccountHasMoreOrdersThan(100)\nspecification200 = new AccountHasMoreOrdersThan(200)\n\nassert that specification200.isSpecialCaseOf(specification100)\n\nspecificationAge = new AccountIsOlderThan('2000-01-01')\n\ncombinedSpec = new CompositeSpecification(\n SpecificationOperator.And, specification200, specificationAge)\n\nfor each account in Repository<Account>.GetAllSatisfying(combinedSpec)\n assert that account.Created < '2000-01-01'\n assert that account.Orders.Count > 200\n IoCManager.InstanceFor<IAccountDAO>()\n .GetAccountsWithAtLeastOrdersAndCreatedBefore(200, '2000-01-01')\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37795/"
] |
291,359 | <p>I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection? For example:</p>
<pre><code>public string[] Items
{
get;
set;
}
</code></pre>
<p>My method so far:</p>
<pre><code>public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
{
T to = new T();
Type myType = from.GetType();
PropertyInfo[] myProperties = myType.GetProperties();
for (int i = 0; i < myProperties.Length; i++)
{
if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
{
myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
}
}
return to;
}
</code></pre>
| [
{
"answer_id": 291380,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 7,
"selected": true,
"text": "if (propertyInfo.GetIndexParameters().Length > 0)\n{\n // Property is an indexer\n}\n"
},
{
"answer_id": 291386,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 3,
"selected": false,
"text": "GetIndexParameters()"
},
{
"answer_id": 440509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "public string[] Items { get; set; }\n public string this[int index]\n{\n get { ... }\n set { ... }\n}\n"
},
{
"answer_id": 6272040,
"author": "ILIA BROUDNO",
"author_id": 788301,
"author_profile": "https://Stackoverflow.com/users/788301",
"pm_score": 1,
"selected": false,
"text": ".GetIndexParameters().Length > 0)"
},
{
"answer_id": 6384922,
"author": "John Holliday",
"author_id": 803117,
"author_profile": "https://Stackoverflow.com/users/803117",
"pm_score": 2,
"selected": false,
"text": "property.GetValue(obj,null) GetIndexParameters()"
},
{
"answer_id": 17421632,
"author": "Krzysztof Radzimski",
"author_id": 2269514,
"author_profile": "https://Stackoverflow.com/users/2269514",
"pm_score": 1,
"selected": false,
"text": " public static IEnumerable<T> AsEnumerable<T>(this object o) where T : class {\n var list = new List<T>();\n System.Reflection.PropertyInfo indexerProperty = null;\n foreach (System.Reflection.PropertyInfo pi in o.GetType().GetProperties()) {\n if (pi.GetIndexParameters().Length > 0) {\n indexerProperty = pi;\n break;\n }\n }\n\n if (indexerProperty.IsNotNull()) {\n var len = o.GetPropertyValue<int>(\"Length\");\n for (int i = 0; i < len; i++) {\n var item = indexerProperty.GetValue(o, new object[]{i});\n if (item.IsNotNull()) {\n var itemObject = item as T;\n if (itemObject.IsNotNull()) {\n list.Add(itemObject);\n }\n }\n }\n }\n\n return list;\n }\n\n\n public static bool IsNotNull(this object o) {\n return o != null;\n }\n\n public static T GetPropertyValue<T>(this object source, string property) {\n if (source == null)\n throw new ArgumentNullException(\"source\");\n\n var sourceType = source.GetType();\n var sourceProperties = sourceType.GetProperties();\n var properties = sourceProperties\n .Where(s => s.Name.Equals(property));\n if (properties.Count() == 0) {\n sourceProperties = sourceType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);\n properties = sourceProperties.Where(s => s.Name.Equals(property));\n }\n\n if (properties.Count() > 0) {\n var propertyValue = properties\n .Select(s => s.GetValue(source, null))\n .FirstOrDefault();\n\n return propertyValue != null ? (T)propertyValue : default(T);\n }\n\n return default(T);\n }\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37797/"
] |
291,369 | <p>Unfortunately, the problem is not more specific than that. I've found a few examples of people reporting similar problems by doing <a href="http://www.google.com/search?source=ig&hl=en&rlz=&=&q=%22Unknown+object+in+backup+file%22&btnG=Google+Search&aq=f" rel="nofollow noreferrer">a Google search</a>, but I can't find the part of the restore that is actually causing the problem, which might help me track it down on my own.</p>
<p>Suggestions for either resolving this problem or being able to track down the root cause would be appreciated.</p>
| [
{
"answer_id": 293319,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "max_allowed_packet"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
291,387 | <p>I'm new to .net and c#, so I want to make sure i'm using the right tool for the job.</p>
<p>The XML i'm receiving is a description of a directory tree on another machine, so it go many levels deep. What I need to do now is to take the XML and create a structure of objects (custom classes) and populate them with info from the XML input, like File, Folder, Tags, Property...</p>
<p>The Tree stucture of this XML input makes it, in my mind, a prime candidate for using recursion to walk the tree.</p>
<p>Is there a different way of doing this in .net 3.5?</p>
<p>I've looked at XmlReaders, but they seem to be walking the tree in a linear fashion, not really what i'm looking for...</p>
<p>The XML i'm receiving is part of a 3rd party api, so is outside my control, and may change in the futures.</p>
<p>I've looked into Deserialization, but it's shortcomings (black box implementation, need to declare members a public, slow, only works for simple objects...) takes it out of the list as well.</p>
<p>Thanks for your input on this.</p>
| [
{
"answer_id": 291457,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 5,
"selected": false,
"text": "XDocument doc = XDocument.Parse(someString);\n //if Directory is tag name of Directory XML\n//Note: Root is just the root XElement of the document\nvar directoryElements = doc.Root.Elements(\"Directory\"); \n\n//you get the idea\nvar fileElements = doc.Root.Elements(\"File\"); \n List<MyFileType> files = new List<MyFileType>();\n\nforeach(XElelement fileElement in fileElements)\n{\n files.Add(new MyFileType()\n { \n Prop1 = fileElement.Element(\"Prop1\"), //assumes properties are elements\n Prop2 = fileElement.Element(\"Prop2\"),\n });\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37794/"
] |
291,391 | <p>Thanks for reading this.</p>
<p>I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and putting the ONE on the ID I got it to work. However, in changing the code to reference a class (since there will be multiple data groups that include a select with a text box next to it) and <code>$(this)</code>, I could not get it to work. Any ideas would be helpful. Thanks</p>
<p>The relevance of the text box next to the select is the second part of the code...to update the text box when an option is selected in the select</p>
<p><code>.one</code> is so the select is updated only once, then the <code>.bind</code> allows any options selected to be placed in the adjacent text box.</p>
<pre><code>$('.classSelect').one("click",
function() {
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(this).html(request); // populate select box
} // End success
}); // End ajax method
$(this).bind("click",
function() {
$(this).next().val($(this).val());
}); // End BIND
}); // End One
<select id="mySelect" class="classSelect"></select>
<input type="text">
</code></pre>
| [
{
"answer_id": 291412,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "$(\"select[class='classSelect']\") ...\n"
},
{
"answer_id": 291433,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "$(this) $('.classSelect').one(\"click\", function() {\n $(this); // refers to $('.classSelect')\n\n $.ajax({\n // content\n $(this); // does not refer to $('.classSelect')\n });\n});\n $('.classSelect').one(\"click\", function() {\n var e = $(this);\n\n $.ajax({\n ...\n success : function(request) {\n e.html(request);\n }\n }); // end ajax\n\n $(this).bind('click', function() {\n // bind stuff\n\n }); // end bind\n\n}); // end one\n load() $.ajax() load() $('.classSelect').one('click', function() {\n var options = {\n type : 'post',\n dataType : 'text',\n data : {\n '_service' : myService,\n '_program' : myProgram ,\n 'param' : myParams\n } \n } // end options\n\n // load() will automatically load your .classSelect with the results\n $(this).load(myUrl, options);\n\n\n $(this).click(function() {\n // etc...\n\n }); // end click\n\n}); // end one\n"
},
{
"answer_id": 291434,
"author": "philnash",
"author_id": 28376,
"author_profile": "https://Stackoverflow.com/users/28376",
"pm_score": 1,
"selected": false,
"text": "var _this = this;\n success:\n function(request) {\n _this.html(request); // populate select box\n }\n"
},
{
"answer_id": 291485,
"author": "Claudio",
"author_id": 27958,
"author_profile": "https://Stackoverflow.com/users/27958",
"pm_score": 0,
"selected": false,
"text": "var that = $(this);\n... some code ...\nsuccess: function(request) {\n that.html(request)\n}\n"
},
{
"answer_id": 291496,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 0,
"selected": false,
"text": "$('.classSelect').one(\"click\",\n function() {\n var e = $(this) ;\n\n $.ajax({\n type: \"post\",\n url: myURL ,\n dataType: \"text\",\n data: {\n '_service' : myService,\n '_program' : myProgram ,\n 'param' : myParams\n },\n success:\n function(request) {\n $(e).html(request); // populate select box\n } // End success\n }); // End ajax method\n\n $(e).one(\"click\",\n function() {\n $(e).next().val($(e).val());\n }); // End BIND\n }); // End One\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
291,395 | <p>I'm working with an XML file that subscribes to an industry standard. The standards document for the schema defines one of the fields as a rational number and its data is represented as two integers, typically with the second value being a 1 (e.g. <code><foo>20 1</foo></code>). I've been hunting around without a great deal of success to see if there's an XML-defined standard for rational numbers. I did find this (8 year old) exchange on the mailing list for XML-SCHEMA:</p>
<p><a href="http://markmail.org/message/znvfw2r3a2pfeykl" rel="nofollow noreferrer">http://markmail.org/message/znvfw2r3a2pfeykl</a></p>
<p>I'm not clear that there is a standard "XML way" for representing rational numbers and whether the standard applying to this document is subscribing to it, or whether they've cooked up their own way of doing it for their documents and are relying on people to read the standard. The document is not specific beyond saying the field is a rational number.</p>
<p>Assuming there is a standard way of representing rational numbers and this document is correctly implementing it, does the functionality in System.Xml recognize it? Again, my searches have not been particularly fruitful.</p>
<p>Thanks for any feedback anyone has.</p>
| [
{
"answer_id": 1933672,
"author": "mckamey",
"author_id": 43217,
"author_profile": "https://Stackoverflow.com/users/43217",
"pm_score": 2,
"selected": false,
"text": "Rational<T> IConvertable ' ' 314159265358979323846 / 100000000000000000000\n 2/3 0.66666666666666666667\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31167/"
] |
291,405 | <p>When building a multi-lingual website (with ASP.NET web forms), I'll use an HTTP module to rewrite the URLs to end up with something friendly (for humans & search engines) like:</p>
<pre><code>uk/products/product_category_one/sub_category_one/index.aspx
uk/products/product_category_one/sub_category_one/widget_mk5.aspx
es/productos/categoría_de_producto_una/widget_mk5.aspx
</code></pre>
<p>My (newbie) understanding of MVC is that the URL should take the format of</p>
<blockquote>
<p>Controller / Action / Identifier</p>
</blockquote>
<p>so replicating the functionality above with MVC will end up with URLs similar to:</p>
<pre><code>products/category/123/product_category_one/sub_category_one
products/items/456/widget_mk5
</code></pre>
<p>Questions..</p>
<ul>
<li>Can I insert a country code into the URL before the 'controller' segment?</li>
<li>Is it possible to map 'products' and 'productos' to the same controller?</li>
</ul>
<p>Thanks for your help</p>
<p><strong>Edit:</strong>
In addition to Panos' answer below I found more information on the <a href="http://www.asp.net/learn/mvc/tutorial-05-vb.aspx" rel="noreferrer">ASP.NET Website</a>.</p>
| [
{
"answer_id": 291692,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 5,
"selected": true,
"text": " routes.MapRoute(\n \"ukRoute\",\n \"{lang}/Products/{action}/{id}/{subcategory}\",\n new { lang = \"uk\", controller = \"Products\", action = \"Index\", id = \"\", subcategory = \"\" }\n );\n routes.MapRoute(\n \"esRoute\",\n \"{lang}/Productos/{action}/{id}/{subcategory}\",\n new { lang = \"es\", controller = \"Products\", action = \"Index\", id = \"\", subcategory = \"\" }\n );\n ActionResult Category(string id, string subcategory) ProductsController uk/Products/Category/1/A\nes/Productos/Category/1/A\n <%= Html.RouteLink(\"English 1.A\", \"ukRoute\", new { lang = \"uk\", action = \"Category\", id = \"1\", subcategory = \"A\" })%>\n<%= Html.RouteLink(\"Spanish 1.A\", \"esRoute\", new { lang = \"es\", action = \"Category\", id = \"1\", subcategory = \"A\" })%>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
291,406 | <p>When extracting files from a ZIP file I was using the following.</p>
<pre><code>Sub Unzip(strFile)
' This routine unzips a file. NOTE: The files are extracted to a folder '
' in the same location using the name of the file minus the extension. '
' EX. C:\Test.zip will be extracted to C:\Test '
'strFile (String) = Full path and filename of the file to be unzipped. '
Dim arrFile
arrFile = Split(strFile, ".")
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateFolder(arrFile(0) & "\ ")
pathToZipFile= arrFile(0) & ".zip"
extractTo= arrFile(0) & "\ "
set objShell = CreateObject("Shell.Application")
set filesInzip=objShell.NameSpace(pathToZipFile).items
objShell.NameSpace(extractTo).CopyHere(filesInzip)
fso.DeleteFile pathToZipFile, True
Set fso = Nothing
Set objShell = Nothing
End Sub 'Unzip
</code></pre>
<p>This was working, but now I get a "The File Exists" Error. </p>
<p>What is the reason for this? Are there any alternatives?</p>
| [
{
"answer_id": 338324,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "For i = 1 To 99\n If aqFileSystem.Exists(GetAppPath(\"Local Settings\", \"\") & \"\\Temp\\Temporary Directory \" & i & \" for DialogState.zip\") = True Then\n result = aqFileSystem.ChangeAttributes(GetAppPath(\"Local Settings\", \"\") & \"\\Temp\\Temporary Directory \" & i & \" for DialogState.zip\", 1 OR 2, aqFileSystem.fattrFree) \n Call DelFolder(GetAppPath(\"Local Settings\", \"\") & \"\\Temp\\Temporary Directory \" & i & \" for DialogState.zip\") \n Else\n Exit For\n End If\nNext\n"
},
{
"answer_id": 692498,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "WScript.echo(\"Instantiating a ZipFile object...\")\nDim zip \nSet zip = CreateObject(\"Ionic.Zip.ZipFile\")\n\nWScript.echo(\"Initialize (Read)...\")\nzip.Initialize(\"C:\\Temp\\ZipFile-created-from-VBScript.zip\")\n\nWScript.echo(\"setting the password for extraction...\")\nzip.Password = \"This is the Password.\"\n\n' set the default action for extracting an existing file\n' 0 = throw exception\n' 1 = overwrite silently\n' 2 = don't overwrite (silently)\n' 3 = invoke the ExtractProgress event\nzip.ExtractExistingFile = 1\n\nWScript.echo(\"extracting all files...\")\nCall zip.ExtractAll(\"extract\")\n\nWScript.echo(\"Disposing...\")\nzip.Dispose()\n\nWScript.echo(\"Done.\")\n dim filename \nfilename = \"C:\\temp\\ZipFile-created-from-VBScript.zip\"\n\nWScript.echo(\"Instantiating a ZipFile object...\")\ndim zip2 \nset zip2 = CreateObject(\"Ionic.Zip.ZipFile\")\n\nWScript.echo(\"using AES256 encryption...\")\nzip2.Encryption = 3\n\nWScript.echo(\"setting the password...\")\nzip2.Password = \"This is the Password.\"\n\nWScript.echo(\"adding a selection of files...\")\nzip2.AddSelectedFiles(\"*.js\")\nzip2.AddSelectedFiles(\"*.vbs\")\n\nWScript.echo(\"setting the save name...\")\nzip2.Name = filename\n\nWScript.echo(\"Saving...\")\nzip2.Save()\n\nWScript.echo(\"Disposing...\")\nzip2.Dispose()\n\nWScript.echo(\"Done.\")\n"
},
{
"answer_id": 6710371,
"author": "bobpaul",
"author_id": 308709,
"author_profile": "https://Stackoverflow.com/users/308709",
"pm_score": 2,
"selected": false,
"text": "strZipFile = \"test.zip\" 'name of zip file\noutFolder = \".\" 'destination folder of unzipped files (must exist)\n'If using full paths rather than relative to the script, comment the next line\npwd = Replace(WScript.ScriptFullName, WScript.ScriptName, \"\")\n\nSet objShell = CreateObject( \"Shell.Application\" )\nSet objSource = objShell.NameSpace(pwd+strZipFile).Items()\nSet objTarget = objShell.NameSpace(pwd+outFolder)\nintOptions = 256\nobjTarget.CopyHere objSource, intOptions\n\n'Clean up\nSet WshShell = CreateObject(\"Wscript.Shell\")\ntempfolder = WshShell.ExpandEnvironmentStrings(\"%temp%\")\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nCall fso.DeleteFolder(tempfolder + \"\\Temporary Directory 1 for \" + strZipFile, True ) \n"
},
{
"answer_id": 9934879,
"author": "Rich",
"author_id": 1031929,
"author_profile": "https://Stackoverflow.com/users/1031929",
"pm_score": 3,
"selected": false,
"text": "C:\\Documents Settings\\USERNAME\\Local Settings\\Temp '========================\n 'Sub: UnzipFiles\n 'Language: vbscript\n 'Usage: UnzipFiles(\"C:\\dir\", \"extract.zip\")\n 'Definition: UnzipFiles([Directory where zip is located & where files will be extracted], [zip file name])\n '========================\n Sub UnzipFiles(folder, file)\n Dim sa, filesInzip, zfile, fso, i : i = 1\n Set sa = CreateObject(\"Shell.Application\")\n Set filesInzip=sa.NameSpace(folder&file).items\n For Each zfile In filesInzip\n If Not fso.FileExists(folder & zfile) Then\n sa.NameSpace(folder).CopyHere(zfile), &H100 \n i = i + 1\n End If\n If i = 99 Then\n zCleanup(file, i)\n i = 1\n End If\n Next\n If i > 1 Then \n zCleanup(file, i)\n End If\n fso.DeleteFile(folder&file)\n End Sub\n\n '========================\n 'Sub: zCleanup\n 'Language: vbscript\n 'Usage: zCleanup(\"filename.zip\", 4)\n 'Definition: zCleanup([Filename of Zip previously extracted], [Number of files within zip container])\n '========================\n Sub zCleanUp(file, count) \n 'Clean up\n Dim i, fso\n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n For i = 1 To count\n If fso.FolderExists(fso.GetSpecialFolder(2) & \"\\Temporary Directory \" & i & \" for \" & file) = True Then\n text = fso.DeleteFolder(fso.GetSpecialFolder(2) & \"\\Temporary Directory \" & i & \" for \" & file, True)\n Else\n Exit For\n End If\n Next\n End Sub\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,413 | <p>I am looking for the VB.NET equivalent of</p>
<pre><code>var strings = new string[] {"abc", "def", "ghi"};
</code></pre>
| [
{
"answer_id": 291423,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 3,
"selected": false,
"text": "Dim strings As String() = New String() {\"abc\", \"def\", \"ghi\"}\n"
},
{
"answer_id": 291426,
"author": "Jesper Palm",
"author_id": 36455,
"author_profile": "https://Stackoverflow.com/users/36455",
"pm_score": 3,
"selected": false,
"text": "Dim strings = New String() {\"abc\", \"def\", \"ghi\"}\n"
},
{
"answer_id": 291429,
"author": "Steve Wright",
"author_id": 3256,
"author_profile": "https://Stackoverflow.com/users/3256",
"pm_score": 2,
"selected": false,
"text": "Dim strings As String() = {\"abc\", \"def\", \"ghi\"}"
},
{
"answer_id": 291430,
"author": "gfrizzle",
"author_id": 23935,
"author_profile": "https://Stackoverflow.com/users/23935",
"pm_score": 7,
"selected": true,
"text": "Dim strings() As String = {\"abc\", \"def\", \"ghi\"}\n"
},
{
"answer_id": 291471,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "class Test\n{\n static void Main()\n {\n var strings = new string[] {\"abc\", \"def\", \"ghi\"};\n }\n}\n csc /debug+ Test.cs\n Private Shared Sub Main()\n Dim strings As String() = New String() { \"abc\", \"def\", \"ghi\" }\nEnd Sub\n"
},
{
"answer_id": 10233382,
"author": "Netricity",
"author_id": 161632,
"author_profile": "https://Stackoverflow.com/users/161632",
"pm_score": 3,
"selected": false,
"text": "Dim strings = {\"abc\", \"def\", \"ghi\"}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191/"
] |
291,424 | <p>In a Windows program, what is the canonical way to parse the command line obtained from GetCommandLine into multiple arguments, similar to the argv array in Unix? It seems that CommandLineToArgvW does this for a Unicode command line, but I can't find a non-Unicode equivalent. Should I be using Unicode or not? If not, how do I parse the command line?</p>
| [
{
"answer_id": 291505,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "CommandLineToArgvW()"
},
{
"answer_id": 1399224,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "__argv main()"
},
{
"answer_id": 4023686,
"author": "Sylvain Defresne",
"author_id": 5353,
"author_profile": "https://Stackoverflow.com/users/5353",
"pm_score": 4,
"selected": false,
"text": "LPSTR* CommandLineToArgvA(LPSTR lpCmdLine, INT *pNumArgs)\n{\n int retval;\n retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, NULL, 0);\n if (!SUCCEEDED(retval))\n return NULL;\n\n LPWSTR lpWideCharStr = (LPWSTR)malloc(retval * sizeof(WCHAR));\n if (lpWideCharStr == NULL)\n return NULL;\n\n retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, lpWideCharStr, retval);\n if (!SUCCEEDED(retval))\n {\n free(lpWideCharStr);\n return NULL;\n }\n\n int numArgs;\n LPWSTR* args;\n args = CommandLineToArgvW(lpWideCharStr, &numArgs);\n free(lpWideCharStr);\n if (args == NULL)\n return NULL;\n\n int storage = numArgs * sizeof(LPSTR);\n for (int i = 0; i < numArgs; ++ i)\n {\n BOOL lpUsedDefaultChar = FALSE;\n retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, NULL, 0, NULL, &lpUsedDefaultChar);\n if (!SUCCEEDED(retval))\n {\n LocalFree(args);\n return NULL;\n }\n\n storage += retval;\n }\n\n LPSTR* result = (LPSTR*)LocalAlloc(LMEM_FIXED, storage);\n if (result == NULL)\n {\n LocalFree(args);\n return NULL;\n }\n\n int bufLen = storage - numArgs * sizeof(LPSTR);\n LPSTR buffer = ((LPSTR)result) + numArgs * sizeof(LPSTR);\n for (int i = 0; i < numArgs; ++ i)\n {\n assert(bufLen > 0);\n BOOL lpUsedDefaultChar = FALSE;\n retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, buffer, bufLen, NULL, &lpUsedDefaultChar);\n if (!SUCCEEDED(retval))\n {\n LocalFree(result);\n LocalFree(args);\n return NULL;\n }\n\n result[i] = buffer;\n buffer += retval;\n bufLen -= retval;\n }\n\n LocalFree(args);\n\n *pNumArgs = numArgs;\n return result;\n}\n"
},
{
"answer_id": 42048224,
"author": "James Yang",
"author_id": 4612829,
"author_profile": "https://Stackoverflow.com/users/4612829",
"pm_score": 2,
"selected": false,
"text": "CommandLineToArgvW shell32.dll /*************************************************************************\n * CommandLineToArgvA [SHELL32.@]\n * \n * MODIFIED FROM https://www.winehq.org/ project\n * We must interpret the quotes in the command line to rebuild the argv\n * array correctly:\n * - arguments are separated by spaces or tabs\n * - quotes serve as optional argument delimiters\n * '\"a b\"' -> 'a b'\n * - escaped quotes must be converted back to '\"'\n * '\\\"' -> '\"'\n * - consecutive backslashes preceding a quote see their number halved with\n * the remainder escaping the quote:\n * 2n backslashes + quote -> n backslashes + quote as an argument delimiter\n * 2n+1 backslashes + quote -> n backslashes + literal quote\n * - backslashes that are not followed by a quote are copied literally:\n * 'a\\b' -> 'a\\b'\n * 'a\\\\b' -> 'a\\\\b'\n * - in quoted strings, consecutive quotes see their number divided by three\n * with the remainder modulo 3 deciding whether to close the string or not.\n * Note that the opening quote must be counted in the consecutive quotes,\n * that's the (1+) below:\n * (1+) 3n quotes -> n quotes\n * (1+) 3n+1 quotes -> n quotes plus closes the quoted string\n * (1+) 3n+2 quotes -> n+1 quotes plus closes the quoted string\n * - in unquoted strings, the first quote opens the quoted string and the\n * remaining consecutive quotes follow the above rule.\n */\n\nLPSTR* WINAPI CommandLineToArgvA(LPSTR lpCmdline, int* numargs)\n{\n DWORD argc;\n LPSTR *argv;\n LPSTR s;\n LPSTR d;\n LPSTR cmdline;\n int qcount,bcount;\n\n if(!numargs || *lpCmdline==0)\n {\n SetLastError(ERROR_INVALID_PARAMETER);\n return NULL;\n }\n\n /* --- First count the arguments */\n argc=1;\n s=lpCmdline;\n /* The first argument, the executable path, follows special rules */\n if (*s=='\"')\n {\n /* The executable path ends at the next quote, no matter what */\n s++;\n while (*s)\n if (*s++=='\"')\n break;\n }\n else\n {\n /* The executable path ends at the next space, no matter what */\n while (*s && *s!=' ' && *s!='\\t')\n s++;\n }\n /* skip to the first argument, if any */\n while (*s==' ' || *s=='\\t')\n s++;\n if (*s)\n argc++;\n\n /* Analyze the remaining arguments */\n qcount=bcount=0;\n while (*s)\n {\n if ((*s==' ' || *s=='\\t') && qcount==0)\n {\n /* skip to the next argument and count it if any */\n while (*s==' ' || *s=='\\t')\n s++;\n if (*s)\n argc++;\n bcount=0;\n }\n else if (*s=='\\\\')\n {\n /* '\\', count them */\n bcount++;\n s++;\n }\n else if (*s=='\"')\n {\n /* '\"' */\n if ((bcount & 1)==0)\n qcount++; /* unescaped '\"' */\n s++;\n bcount=0;\n /* consecutive quotes, see comment in copying code below */\n while (*s=='\"')\n {\n qcount++;\n s++;\n }\n qcount=qcount % 3;\n if (qcount==2)\n qcount=0;\n }\n else\n {\n /* a regular character */\n bcount=0;\n s++;\n }\n }\n\n /* Allocate in a single lump, the string array, and the strings that go\n * with it. This way the caller can make a single LocalFree() call to free\n * both, as per MSDN.\n */\n argv=LocalAlloc(LMEM_FIXED, (argc+1)*sizeof(LPSTR)+(strlen(lpCmdline)+1)*sizeof(char));\n if (!argv)\n return NULL;\n cmdline=(LPSTR)(argv+argc+1);\n strcpy(cmdline, lpCmdline);\n\n /* --- Then split and copy the arguments */\n argv[0]=d=cmdline;\n argc=1;\n /* The first argument, the executable path, follows special rules */\n if (*d=='\"')\n {\n /* The executable path ends at the next quote, no matter what */\n s=d+1;\n while (*s)\n {\n if (*s=='\"')\n {\n s++;\n break;\n }\n *d++=*s++;\n }\n }\n else\n {\n /* The executable path ends at the next space, no matter what */\n while (*d && *d!=' ' && *d!='\\t')\n d++;\n s=d;\n if (*s)\n s++;\n }\n /* close the executable path */\n *d++=0;\n /* skip to the first argument and initialize it if any */\n while (*s==' ' || *s=='\\t')\n s++;\n if (!*s)\n {\n /* There are no parameters so we are all done */\n argv[argc]=NULL;\n *numargs=argc;\n return argv;\n }\n\n /* Split and copy the remaining arguments */\n argv[argc++]=d;\n qcount=bcount=0;\n while (*s)\n {\n if ((*s==' ' || *s=='\\t') && qcount==0)\n {\n /* close the argument */\n *d++=0;\n bcount=0;\n\n /* skip to the next one and initialize it if any */\n do {\n s++;\n } while (*s==' ' || *s=='\\t');\n if (*s)\n argv[argc++]=d;\n }\n else if (*s=='\\\\')\n {\n *d++=*s++;\n bcount++;\n }\n else if (*s=='\"')\n {\n if ((bcount & 1)==0)\n {\n /* Preceded by an even number of '\\', this is half that\n * number of '\\', plus a quote which we erase.\n */\n d-=bcount/2;\n qcount++;\n }\n else\n {\n /* Preceded by an odd number of '\\', this is half that\n * number of '\\' followed by a '\"'\n */\n d=d-bcount/2-1;\n *d++='\"';\n }\n s++;\n bcount=0;\n /* Now count the number of consecutive quotes. Note that qcount\n * already takes into account the opening quote if any, as well as\n * the quote that lead us here.\n */\n while (*s=='\"')\n {\n if (++qcount==3)\n {\n *d++='\"';\n qcount=0;\n }\n s++;\n }\n if (qcount==2)\n qcount=0;\n }\n else\n {\n /* a regular character */\n *d++=*s++;\n bcount=0;\n }\n }\n *d='\\0';\n argv[argc]=NULL;\n *numargs=argc;\n\n return argv;\n}\n \"\" NULL CommandLineToArgvW int argc;\nLPSTR * argv = CommandLineToArgvA(GetCommandLineA(), &argc);\n\n// AFTER consumed argv\nLocalFree(argv);\n"
},
{
"answer_id": 47702108,
"author": "Erudite Programmer",
"author_id": 9069105,
"author_profile": "https://Stackoverflow.com/users/9069105",
"pm_score": 3,
"selected": false,
"text": "_In_opt_ NULL int argc = 0;\n LPSTR *argv = CommandLineToArgvA(GetCommandLineA(), &argc);\n HeapFree(GetProcessHeap(), NULL, argv); LPSTR* CommandLineToArgvA(_In_opt_ LPCSTR lpCmdLine, _Out_ int *pNumArgs)\n{\n if (!pNumArgs)\n {\n SetLastError(ERROR_INVALID_PARAMETER);\n return NULL;\n }\n *pNumArgs = 0;\n /*follow CommandLinetoArgvW and if lpCmdLine is NULL return the path to the executable.\n Use 'programname' so that we don't have to allocate MAX_PATH * sizeof(CHAR) for argv\n every time. Since this is ANSI the return can't be greater than MAX_PATH (260\n characters)*/\n CHAR programname[MAX_PATH] = {};\n /*pnlength = the length of the string that is copied to the buffer, in characters, not\n including the terminating null character*/\n DWORD pnlength = GetModuleFileNameA(NULL, programname, MAX_PATH);\n if (pnlength == 0) //error getting program name\n {\n //GetModuleFileNameA will SetLastError\n return NULL;\n }\n if (*lpCmdLine == NULL)\n {\n\n /*In keeping with CommandLineToArgvW the caller should make a single call to HeapFree\n to release the memory of argv. Allocate a single block of memory with space for two\n pointers (representing argv[0] and argv[1]). argv[0] will contain a pointer to argv+2\n where the actual program name will be stored. argv[1] will be nullptr per the C++\n specifications for argv. Hence space required is the size of a LPSTR (char*) multiplied\n by 2 [pointers] + the length of the program name (+1 for null terminating character)\n multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS flag,\n so if there is a failure on allocating memory an exception will be generated.*/\n LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),\n HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,\n (sizeof(LPSTR) * 2) + ((pnlength + 1) * sizeof(CHAR))));\n memcpy(argv + 2, programname, pnlength+1); //add 1 for the terminating null character\n argv[0] = reinterpret_cast<LPSTR>(argv + 2);\n argv[1] = nullptr;\n *pNumArgs = 1;\n return argv;\n }\n /*We need to determine the number of arguments and the number of characters so that the\n proper amount of memory can be allocated for argv. Our argument count starts at 1 as the\n first \"argument\" is the program name even if there are no other arguments per specs.*/\n int argc = 1;\n int numchars = 0;\n LPCSTR templpcl = lpCmdLine;\n bool in_quotes = false; //'in quotes' mode is off (false) or on (true)\n /*first scan the program name and copy it. The handling is much simpler than for other\n arguments. Basically, whatever lies between the leading double-quote and next one, or a\n terminal null character is simply accepted. Fancier handling is not required because the\n program name must be a legal NTFS/HPFS file name. Note that the double-quote characters are\n not copied.*/\n do {\n if (*templpcl == '\"')\n {\n //don't add \" to character count\n in_quotes = !in_quotes;\n templpcl++; //move to next character\n continue;\n }\n ++numchars; //count character\n templpcl++; //move to next character\n if (_ismbblead(*templpcl) != 0) //handle MBCS\n {\n ++numchars;\n templpcl++; //skip over trail byte\n }\n } while (*templpcl != '\\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\\t')));\n //parsed first argument\n if (*templpcl == '\\0')\n {\n /*no more arguments, rewind and the next for statement will handle*/\n templpcl--;\n }\n //loop through the remaining arguments\n int slashcount = 0; //count of backslashes\n bool countorcopychar = true; //count the character or not\n for (;;)\n {\n if (*templpcl)\n {\n //next argument begins with next non-whitespace character\n while (*templpcl == ' ' || *templpcl == '\\t')\n ++templpcl;\n }\n if (*templpcl == '\\0')\n break; //end of arguments\n\n ++argc; //next argument - increment argument count\n //loop through this argument\n for (;;)\n {\n /*Rules:\n 2N backslashes + \" ==> N backslashes and begin/end quote\n 2N + 1 backslashes + \" ==> N backslashes + literal \"\n N backslashes ==> N backslashes*/\n slashcount = 0;\n countorcopychar = true;\n while (*templpcl == '\\\\')\n {\n //count the number of backslashes for use below\n ++templpcl;\n ++slashcount;\n }\n if (*templpcl == '\"')\n {\n //if 2N backslashes before, start/end quote, otherwise count.\n if (slashcount % 2 == 0) //even number of backslashes\n {\n if (in_quotes && *(templpcl +1) == '\"')\n {\n in_quotes = !in_quotes; //NB: parse_cmdline omits this line\n templpcl++; //double quote inside quoted string\n }\n else\n {\n //skip first quote character and count second\n countorcopychar = false;\n in_quotes = !in_quotes;\n }\n }\n slashcount /= 2;\n }\n //count slashes\n while (slashcount--)\n {\n ++numchars;\n }\n if (*templpcl == '\\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\\t')))\n {\n //at the end of the argument - break\n break;\n }\n if (countorcopychar)\n {\n if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS\n {\n ++templpcl; //skip over trail byte\n ++numchars;\n }\n ++numchars;\n }\n ++templpcl;\n }\n //add a count for the null-terminating character\n ++numchars;\n }\n /*allocate memory for argv. Allocate a single block of memory with space for argc number of\n pointers. argv[0] will contain a pointer to argv+argc where the actual program name will be\n stored. argv[argc] will be nullptr per the C++ specifications. Hence space required is the\n size of a LPSTR (char*) multiplied by argc + 1 pointers + the number of characters counted\n above multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS\n flag, so if there is a failure on allocating memory an exception will be generated.*/\n LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),\n HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,\n (sizeof(LPSTR) * (argc+1)) + (numchars * sizeof(CHAR))));\n //now loop through the commandline again and split out arguments\n in_quotes = false;\n templpcl = lpCmdLine;\n argv[0] = reinterpret_cast<LPSTR>(argv + argc+1);\n LPSTR tempargv = reinterpret_cast<LPSTR>(argv + argc+1);\n do {\n if (*templpcl == '\"')\n {\n in_quotes = !in_quotes;\n templpcl++; //move to next character\n continue;\n }\n *tempargv++ = *templpcl;\n templpcl++; //move to next character\n if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS\n {\n *tempargv++ = *templpcl; //copy second byte\n templpcl++; //skip over trail byte\n }\n } while (*templpcl != '\\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\\t')));\n //parsed first argument\n if (*templpcl == '\\0')\n {\n //no more arguments, rewind and the next for statement will handle\n templpcl--;\n }\n else\n {\n //end of program name - add null terminator\n *tempargv = '\\0';\n }\n int currentarg = 1;\n argv[currentarg] = ++tempargv;\n //loop through the remaining arguments\n slashcount = 0; //count of backslashes\n countorcopychar = true; //count the character or not\n for (;;)\n {\n if (*templpcl)\n {\n //next argument begins with next non-whitespace character\n while (*templpcl == ' ' || *templpcl == '\\t')\n ++templpcl;\n }\n if (*templpcl == '\\0')\n break; //end of arguments\n argv[currentarg] = ++tempargv; //copy address of this argument string\n //next argument - loop through it's characters\n for (;;)\n {\n /*Rules:\n 2N backslashes + \" ==> N backslashes and begin/end quote\n 2N + 1 backslashes + \" ==> N backslashes + literal \"\n N backslashes ==> N backslashes*/\n slashcount = 0;\n countorcopychar = true;\n while (*templpcl == '\\\\')\n {\n //count the number of backslashes for use below\n ++templpcl;\n ++slashcount;\n }\n if (*templpcl == '\"')\n {\n //if 2N backslashes before, start/end quote, otherwise copy literally.\n if (slashcount % 2 == 0) //even number of backslashes\n {\n if (in_quotes && *(templpcl+1) == '\"')\n {\n in_quotes = !in_quotes; //NB: parse_cmdline omits this line\n templpcl++; //double quote inside quoted string\n }\n else\n {\n //skip first quote character and count second\n countorcopychar = false;\n in_quotes = !in_quotes;\n }\n }\n slashcount /= 2;\n }\n //copy slashes\n while (slashcount--)\n {\n *tempargv++ = '\\\\';\n }\n if (*templpcl == '\\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\\t')))\n {\n //at the end of the argument - break\n break;\n }\n if (countorcopychar)\n {\n *tempargv++ = *templpcl;\n if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS\n {\n ++templpcl; //skip over trail byte\n *tempargv++ = *templpcl;\n }\n }\n ++templpcl;\n }\n //null-terminate the argument\n *tempargv = '\\0';\n ++currentarg;\n }\n argv[argc] = nullptr;\n *pNumArgs = argc;\n return argv;\n}\n"
},
{
"answer_id": 57941046,
"author": "CP Taylor",
"author_id": 562007,
"author_profile": "https://Stackoverflow.com/users/562007",
"pm_score": 1,
"selected": false,
"text": "int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {\n int argc;\n LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &argc);\n char **argv = new char*[argc];\n for (int i=0; i<argc; i++) {\n int lgth = wcslen(szArglist[i]);\n argv[i] = new char[lgth+1];\n for (int j=0; j<=lgth; j++)\n argv[i][j] = char(szArglist[i][j]);\n }\n LocalFree(szArglist);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,444 | <p>I'm trying to inject a dynamic where clause in my Linq to SQL query and I get an overload exception. The same expression work when added in the query proper?</p>
<pre><code> qry.Where(Function(c) c.CallDate < Date.Now.AddDays(-1))
</code></pre>
<p>Any thoughts on how to this to work?</p>
<p>The exception reads:</p>
<pre><code>Overload resolution failed because no accessible 'Where' can be called with these arguments:
Extension method 'Public Function Where(predicate As System.Func(Of Calls, Integer, Boolean)) As System.Collections.Generic.IEnumerable(Of Calls)' defined in 'System.Linq.Enumerable': Nested function does not have the same signature as delegate 'System.Func(Of Calls, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Func(Of Calls, Boolean)) As System.Collections.Generic.IEnumerable(Of Calls)' defined in 'System.Linq.Enumerable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of Calls, Integer, Boolean))) As System.Linq.IQueryable(Of Calls)' defined in 'System.Linq.Queryable': Nested function does not have the same signature as delegate 'System.Func(Of Calls, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of Calls, Boolean))) As System.Linq.IQueryable(Of Calls)' defined in 'System.Linq.Queryable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'. C:\Projects\Test Projects\Encore\EncoreData.vb 59 9 Encore
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 291505,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "CommandLineToArgvW()"
},
{
"answer_id": 1399224,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "__argv main()"
},
{
"answer_id": 4023686,
"author": "Sylvain Defresne",
"author_id": 5353,
"author_profile": "https://Stackoverflow.com/users/5353",
"pm_score": 4,
"selected": false,
"text": "LPSTR* CommandLineToArgvA(LPSTR lpCmdLine, INT *pNumArgs)\n{\n int retval;\n retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, NULL, 0);\n if (!SUCCEEDED(retval))\n return NULL;\n\n LPWSTR lpWideCharStr = (LPWSTR)malloc(retval * sizeof(WCHAR));\n if (lpWideCharStr == NULL)\n return NULL;\n\n retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, lpWideCharStr, retval);\n if (!SUCCEEDED(retval))\n {\n free(lpWideCharStr);\n return NULL;\n }\n\n int numArgs;\n LPWSTR* args;\n args = CommandLineToArgvW(lpWideCharStr, &numArgs);\n free(lpWideCharStr);\n if (args == NULL)\n return NULL;\n\n int storage = numArgs * sizeof(LPSTR);\n for (int i = 0; i < numArgs; ++ i)\n {\n BOOL lpUsedDefaultChar = FALSE;\n retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, NULL, 0, NULL, &lpUsedDefaultChar);\n if (!SUCCEEDED(retval))\n {\n LocalFree(args);\n return NULL;\n }\n\n storage += retval;\n }\n\n LPSTR* result = (LPSTR*)LocalAlloc(LMEM_FIXED, storage);\n if (result == NULL)\n {\n LocalFree(args);\n return NULL;\n }\n\n int bufLen = storage - numArgs * sizeof(LPSTR);\n LPSTR buffer = ((LPSTR)result) + numArgs * sizeof(LPSTR);\n for (int i = 0; i < numArgs; ++ i)\n {\n assert(bufLen > 0);\n BOOL lpUsedDefaultChar = FALSE;\n retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, buffer, bufLen, NULL, &lpUsedDefaultChar);\n if (!SUCCEEDED(retval))\n {\n LocalFree(result);\n LocalFree(args);\n return NULL;\n }\n\n result[i] = buffer;\n buffer += retval;\n bufLen -= retval;\n }\n\n LocalFree(args);\n\n *pNumArgs = numArgs;\n return result;\n}\n"
},
{
"answer_id": 42048224,
"author": "James Yang",
"author_id": 4612829,
"author_profile": "https://Stackoverflow.com/users/4612829",
"pm_score": 2,
"selected": false,
"text": "CommandLineToArgvW shell32.dll /*************************************************************************\n * CommandLineToArgvA [SHELL32.@]\n * \n * MODIFIED FROM https://www.winehq.org/ project\n * We must interpret the quotes in the command line to rebuild the argv\n * array correctly:\n * - arguments are separated by spaces or tabs\n * - quotes serve as optional argument delimiters\n * '\"a b\"' -> 'a b'\n * - escaped quotes must be converted back to '\"'\n * '\\\"' -> '\"'\n * - consecutive backslashes preceding a quote see their number halved with\n * the remainder escaping the quote:\n * 2n backslashes + quote -> n backslashes + quote as an argument delimiter\n * 2n+1 backslashes + quote -> n backslashes + literal quote\n * - backslashes that are not followed by a quote are copied literally:\n * 'a\\b' -> 'a\\b'\n * 'a\\\\b' -> 'a\\\\b'\n * - in quoted strings, consecutive quotes see their number divided by three\n * with the remainder modulo 3 deciding whether to close the string or not.\n * Note that the opening quote must be counted in the consecutive quotes,\n * that's the (1+) below:\n * (1+) 3n quotes -> n quotes\n * (1+) 3n+1 quotes -> n quotes plus closes the quoted string\n * (1+) 3n+2 quotes -> n+1 quotes plus closes the quoted string\n * - in unquoted strings, the first quote opens the quoted string and the\n * remaining consecutive quotes follow the above rule.\n */\n\nLPSTR* WINAPI CommandLineToArgvA(LPSTR lpCmdline, int* numargs)\n{\n DWORD argc;\n LPSTR *argv;\n LPSTR s;\n LPSTR d;\n LPSTR cmdline;\n int qcount,bcount;\n\n if(!numargs || *lpCmdline==0)\n {\n SetLastError(ERROR_INVALID_PARAMETER);\n return NULL;\n }\n\n /* --- First count the arguments */\n argc=1;\n s=lpCmdline;\n /* The first argument, the executable path, follows special rules */\n if (*s=='\"')\n {\n /* The executable path ends at the next quote, no matter what */\n s++;\n while (*s)\n if (*s++=='\"')\n break;\n }\n else\n {\n /* The executable path ends at the next space, no matter what */\n while (*s && *s!=' ' && *s!='\\t')\n s++;\n }\n /* skip to the first argument, if any */\n while (*s==' ' || *s=='\\t')\n s++;\n if (*s)\n argc++;\n\n /* Analyze the remaining arguments */\n qcount=bcount=0;\n while (*s)\n {\n if ((*s==' ' || *s=='\\t') && qcount==0)\n {\n /* skip to the next argument and count it if any */\n while (*s==' ' || *s=='\\t')\n s++;\n if (*s)\n argc++;\n bcount=0;\n }\n else if (*s=='\\\\')\n {\n /* '\\', count them */\n bcount++;\n s++;\n }\n else if (*s=='\"')\n {\n /* '\"' */\n if ((bcount & 1)==0)\n qcount++; /* unescaped '\"' */\n s++;\n bcount=0;\n /* consecutive quotes, see comment in copying code below */\n while (*s=='\"')\n {\n qcount++;\n s++;\n }\n qcount=qcount % 3;\n if (qcount==2)\n qcount=0;\n }\n else\n {\n /* a regular character */\n bcount=0;\n s++;\n }\n }\n\n /* Allocate in a single lump, the string array, and the strings that go\n * with it. This way the caller can make a single LocalFree() call to free\n * both, as per MSDN.\n */\n argv=LocalAlloc(LMEM_FIXED, (argc+1)*sizeof(LPSTR)+(strlen(lpCmdline)+1)*sizeof(char));\n if (!argv)\n return NULL;\n cmdline=(LPSTR)(argv+argc+1);\n strcpy(cmdline, lpCmdline);\n\n /* --- Then split and copy the arguments */\n argv[0]=d=cmdline;\n argc=1;\n /* The first argument, the executable path, follows special rules */\n if (*d=='\"')\n {\n /* The executable path ends at the next quote, no matter what */\n s=d+1;\n while (*s)\n {\n if (*s=='\"')\n {\n s++;\n break;\n }\n *d++=*s++;\n }\n }\n else\n {\n /* The executable path ends at the next space, no matter what */\n while (*d && *d!=' ' && *d!='\\t')\n d++;\n s=d;\n if (*s)\n s++;\n }\n /* close the executable path */\n *d++=0;\n /* skip to the first argument and initialize it if any */\n while (*s==' ' || *s=='\\t')\n s++;\n if (!*s)\n {\n /* There are no parameters so we are all done */\n argv[argc]=NULL;\n *numargs=argc;\n return argv;\n }\n\n /* Split and copy the remaining arguments */\n argv[argc++]=d;\n qcount=bcount=0;\n while (*s)\n {\n if ((*s==' ' || *s=='\\t') && qcount==0)\n {\n /* close the argument */\n *d++=0;\n bcount=0;\n\n /* skip to the next one and initialize it if any */\n do {\n s++;\n } while (*s==' ' || *s=='\\t');\n if (*s)\n argv[argc++]=d;\n }\n else if (*s=='\\\\')\n {\n *d++=*s++;\n bcount++;\n }\n else if (*s=='\"')\n {\n if ((bcount & 1)==0)\n {\n /* Preceded by an even number of '\\', this is half that\n * number of '\\', plus a quote which we erase.\n */\n d-=bcount/2;\n qcount++;\n }\n else\n {\n /* Preceded by an odd number of '\\', this is half that\n * number of '\\' followed by a '\"'\n */\n d=d-bcount/2-1;\n *d++='\"';\n }\n s++;\n bcount=0;\n /* Now count the number of consecutive quotes. Note that qcount\n * already takes into account the opening quote if any, as well as\n * the quote that lead us here.\n */\n while (*s=='\"')\n {\n if (++qcount==3)\n {\n *d++='\"';\n qcount=0;\n }\n s++;\n }\n if (qcount==2)\n qcount=0;\n }\n else\n {\n /* a regular character */\n *d++=*s++;\n bcount=0;\n }\n }\n *d='\\0';\n argv[argc]=NULL;\n *numargs=argc;\n\n return argv;\n}\n \"\" NULL CommandLineToArgvW int argc;\nLPSTR * argv = CommandLineToArgvA(GetCommandLineA(), &argc);\n\n// AFTER consumed argv\nLocalFree(argv);\n"
},
{
"answer_id": 47702108,
"author": "Erudite Programmer",
"author_id": 9069105,
"author_profile": "https://Stackoverflow.com/users/9069105",
"pm_score": 3,
"selected": false,
"text": "_In_opt_ NULL int argc = 0;\n LPSTR *argv = CommandLineToArgvA(GetCommandLineA(), &argc);\n HeapFree(GetProcessHeap(), NULL, argv); LPSTR* CommandLineToArgvA(_In_opt_ LPCSTR lpCmdLine, _Out_ int *pNumArgs)\n{\n if (!pNumArgs)\n {\n SetLastError(ERROR_INVALID_PARAMETER);\n return NULL;\n }\n *pNumArgs = 0;\n /*follow CommandLinetoArgvW and if lpCmdLine is NULL return the path to the executable.\n Use 'programname' so that we don't have to allocate MAX_PATH * sizeof(CHAR) for argv\n every time. Since this is ANSI the return can't be greater than MAX_PATH (260\n characters)*/\n CHAR programname[MAX_PATH] = {};\n /*pnlength = the length of the string that is copied to the buffer, in characters, not\n including the terminating null character*/\n DWORD pnlength = GetModuleFileNameA(NULL, programname, MAX_PATH);\n if (pnlength == 0) //error getting program name\n {\n //GetModuleFileNameA will SetLastError\n return NULL;\n }\n if (*lpCmdLine == NULL)\n {\n\n /*In keeping with CommandLineToArgvW the caller should make a single call to HeapFree\n to release the memory of argv. Allocate a single block of memory with space for two\n pointers (representing argv[0] and argv[1]). argv[0] will contain a pointer to argv+2\n where the actual program name will be stored. argv[1] will be nullptr per the C++\n specifications for argv. Hence space required is the size of a LPSTR (char*) multiplied\n by 2 [pointers] + the length of the program name (+1 for null terminating character)\n multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS flag,\n so if there is a failure on allocating memory an exception will be generated.*/\n LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),\n HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,\n (sizeof(LPSTR) * 2) + ((pnlength + 1) * sizeof(CHAR))));\n memcpy(argv + 2, programname, pnlength+1); //add 1 for the terminating null character\n argv[0] = reinterpret_cast<LPSTR>(argv + 2);\n argv[1] = nullptr;\n *pNumArgs = 1;\n return argv;\n }\n /*We need to determine the number of arguments and the number of characters so that the\n proper amount of memory can be allocated for argv. Our argument count starts at 1 as the\n first \"argument\" is the program name even if there are no other arguments per specs.*/\n int argc = 1;\n int numchars = 0;\n LPCSTR templpcl = lpCmdLine;\n bool in_quotes = false; //'in quotes' mode is off (false) or on (true)\n /*first scan the program name and copy it. The handling is much simpler than for other\n arguments. Basically, whatever lies between the leading double-quote and next one, or a\n terminal null character is simply accepted. Fancier handling is not required because the\n program name must be a legal NTFS/HPFS file name. Note that the double-quote characters are\n not copied.*/\n do {\n if (*templpcl == '\"')\n {\n //don't add \" to character count\n in_quotes = !in_quotes;\n templpcl++; //move to next character\n continue;\n }\n ++numchars; //count character\n templpcl++; //move to next character\n if (_ismbblead(*templpcl) != 0) //handle MBCS\n {\n ++numchars;\n templpcl++; //skip over trail byte\n }\n } while (*templpcl != '\\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\\t')));\n //parsed first argument\n if (*templpcl == '\\0')\n {\n /*no more arguments, rewind and the next for statement will handle*/\n templpcl--;\n }\n //loop through the remaining arguments\n int slashcount = 0; //count of backslashes\n bool countorcopychar = true; //count the character or not\n for (;;)\n {\n if (*templpcl)\n {\n //next argument begins with next non-whitespace character\n while (*templpcl == ' ' || *templpcl == '\\t')\n ++templpcl;\n }\n if (*templpcl == '\\0')\n break; //end of arguments\n\n ++argc; //next argument - increment argument count\n //loop through this argument\n for (;;)\n {\n /*Rules:\n 2N backslashes + \" ==> N backslashes and begin/end quote\n 2N + 1 backslashes + \" ==> N backslashes + literal \"\n N backslashes ==> N backslashes*/\n slashcount = 0;\n countorcopychar = true;\n while (*templpcl == '\\\\')\n {\n //count the number of backslashes for use below\n ++templpcl;\n ++slashcount;\n }\n if (*templpcl == '\"')\n {\n //if 2N backslashes before, start/end quote, otherwise count.\n if (slashcount % 2 == 0) //even number of backslashes\n {\n if (in_quotes && *(templpcl +1) == '\"')\n {\n in_quotes = !in_quotes; //NB: parse_cmdline omits this line\n templpcl++; //double quote inside quoted string\n }\n else\n {\n //skip first quote character and count second\n countorcopychar = false;\n in_quotes = !in_quotes;\n }\n }\n slashcount /= 2;\n }\n //count slashes\n while (slashcount--)\n {\n ++numchars;\n }\n if (*templpcl == '\\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\\t')))\n {\n //at the end of the argument - break\n break;\n }\n if (countorcopychar)\n {\n if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS\n {\n ++templpcl; //skip over trail byte\n ++numchars;\n }\n ++numchars;\n }\n ++templpcl;\n }\n //add a count for the null-terminating character\n ++numchars;\n }\n /*allocate memory for argv. Allocate a single block of memory with space for argc number of\n pointers. argv[0] will contain a pointer to argv+argc where the actual program name will be\n stored. argv[argc] will be nullptr per the C++ specifications. Hence space required is the\n size of a LPSTR (char*) multiplied by argc + 1 pointers + the number of characters counted\n above multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS\n flag, so if there is a failure on allocating memory an exception will be generated.*/\n LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),\n HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,\n (sizeof(LPSTR) * (argc+1)) + (numchars * sizeof(CHAR))));\n //now loop through the commandline again and split out arguments\n in_quotes = false;\n templpcl = lpCmdLine;\n argv[0] = reinterpret_cast<LPSTR>(argv + argc+1);\n LPSTR tempargv = reinterpret_cast<LPSTR>(argv + argc+1);\n do {\n if (*templpcl == '\"')\n {\n in_quotes = !in_quotes;\n templpcl++; //move to next character\n continue;\n }\n *tempargv++ = *templpcl;\n templpcl++; //move to next character\n if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS\n {\n *tempargv++ = *templpcl; //copy second byte\n templpcl++; //skip over trail byte\n }\n } while (*templpcl != '\\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\\t')));\n //parsed first argument\n if (*templpcl == '\\0')\n {\n //no more arguments, rewind and the next for statement will handle\n templpcl--;\n }\n else\n {\n //end of program name - add null terminator\n *tempargv = '\\0';\n }\n int currentarg = 1;\n argv[currentarg] = ++tempargv;\n //loop through the remaining arguments\n slashcount = 0; //count of backslashes\n countorcopychar = true; //count the character or not\n for (;;)\n {\n if (*templpcl)\n {\n //next argument begins with next non-whitespace character\n while (*templpcl == ' ' || *templpcl == '\\t')\n ++templpcl;\n }\n if (*templpcl == '\\0')\n break; //end of arguments\n argv[currentarg] = ++tempargv; //copy address of this argument string\n //next argument - loop through it's characters\n for (;;)\n {\n /*Rules:\n 2N backslashes + \" ==> N backslashes and begin/end quote\n 2N + 1 backslashes + \" ==> N backslashes + literal \"\n N backslashes ==> N backslashes*/\n slashcount = 0;\n countorcopychar = true;\n while (*templpcl == '\\\\')\n {\n //count the number of backslashes for use below\n ++templpcl;\n ++slashcount;\n }\n if (*templpcl == '\"')\n {\n //if 2N backslashes before, start/end quote, otherwise copy literally.\n if (slashcount % 2 == 0) //even number of backslashes\n {\n if (in_quotes && *(templpcl+1) == '\"')\n {\n in_quotes = !in_quotes; //NB: parse_cmdline omits this line\n templpcl++; //double quote inside quoted string\n }\n else\n {\n //skip first quote character and count second\n countorcopychar = false;\n in_quotes = !in_quotes;\n }\n }\n slashcount /= 2;\n }\n //copy slashes\n while (slashcount--)\n {\n *tempargv++ = '\\\\';\n }\n if (*templpcl == '\\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\\t')))\n {\n //at the end of the argument - break\n break;\n }\n if (countorcopychar)\n {\n *tempargv++ = *templpcl;\n if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS\n {\n ++templpcl; //skip over trail byte\n *tempargv++ = *templpcl;\n }\n }\n ++templpcl;\n }\n //null-terminate the argument\n *tempargv = '\\0';\n ++currentarg;\n }\n argv[argc] = nullptr;\n *pNumArgs = argc;\n return argv;\n}\n"
},
{
"answer_id": 57941046,
"author": "CP Taylor",
"author_id": 562007,
"author_profile": "https://Stackoverflow.com/users/562007",
"pm_score": 1,
"selected": false,
"text": "int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {\n int argc;\n LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &argc);\n char **argv = new char*[argc];\n for (int i=0; i<argc; i++) {\n int lgth = wcslen(szArglist[i]);\n argv[i] = new char[lgth+1];\n for (int j=0; j<=lgth; j++)\n argv[i][j] = char(szArglist[i][j]);\n }\n LocalFree(szArglist);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25121/"
] |
291,445 | <p>I'm trying to grab data from a MySQL database.</p>
<p>Approach 2 - apply/map style</p>
<p>I'm using the <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-net-examples-mysqlcommand.html" rel="nofollow noreferrer" title="MySQL Reference Site">MySQL ADO Reference</a> to try to build this system. In particular, the example found at 21.2.3.1.7.</p>
<p>(using a pseudo code)</p>
<pre><code>let table = build_sequence(query.read)
</code></pre>
<p>Where query.read returns a row in the table(Or rather, a list of elements that happen to be a row in the table). And the table variable is a list of lists that will represent a table returned from the query.</p>
<p>I've stared at the code given below, and it's syntax is over my head, I'm afraid. </p>
<p>Approach 1 - looping.</p>
<p>Problem 1: It's inelegant, requiring a mutable.</p>
<p>Problem 2: This just <em>feels</em> wrong, based on my prior experience with Prolog & Lisp. There's gotta be a more...<em>functional</em> way to do this.</p>
<p>I'm not sure where to begin though. Comments & thoughts?</p>
<pre><code>let reader : MySql.Data.MySqlClient.MySqlDataReader = command.ExecuteReader()
let arr = []
let mutable rowIter = 0
let readingLoop() =
while(reader.Read()) do
rowIter = rowIter + 1
for i = 0 to reader.FieldCount do
//set arr[someiterator, i] = reader.GetValue[i].ToString())
</code></pre>
| [
{
"answer_id": 291588,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 2,
"selected": false,
"text": "#light\n\ntype ThingLikeSqlReader() =\n let mutable rowNum = 0\n member this.Read() =\n if rowNum > 3 then\n false\n else\n rowNum <- rowNum + 1\n true\n member this.FieldCount = 5\n member this.GetValue(i) = i + 1\n\nlet reader = new ThingLikeSqlReader() \nlet data = reader |> Seq.unfold (fun (reader : ThingLikeSqlReader) ->\n if reader.Read() then\n Some (List.init reader.FieldCount (fun i -> reader.GetValue(i)), reader)\n else\n None) |> Seq.to_list \nprintfn \"%A\" data\n"
},
{
"answer_id": 295788,
"author": "simonuk",
"author_id": 28136,
"author_profile": "https://Stackoverflow.com/users/28136",
"pm_score": 4,
"selected": true,
"text": "let openConnection (connectionName : string) =\n let connectionSetting = ConfigurationManager.ConnectionStrings.Item(connectionName)\n let connectionString = connectionSetting.ConnectionString\n let connection = new OracleConnection(connectionString)\n connection.Open()\n connection\n\nlet generator<'a> (reader : IDataReader) =\n if reader.Read() then\n let t = typeof<'a>\n let props = t.GetProperties()\n let types = props\n |> Seq.map (fun x -> x.PropertyType)\n |> Seq.to_array\n let cstr = t.GetConstructor(types)\n let values = Array.create reader.FieldCount (new obj())\n reader.GetValues(values) |> ignore\n let values = values\n |> Array.map (fun x -> match x with | :? DBNull -> null | _ -> x)\n Some (cstr.Invoke(values) :?> 'a)\n else\n None\n\nlet executeSqlReader<'a> (connectionName : string) (sql : string) : 'a list = \n let connection = openConnection connectionName\n\n let opener() = \n let command = connection.CreateCommand(CommandText = sql, CommandType = CommandType.Text)\n command.ExecuteReader()\n\n let result = Seq.to_list(Seq.generate_using opener generator) \n\n connection.Close()\n connection.Dispose()\n result\n type ColumnDefinition = {\n TableName : string;\n ColumnName : string;\n DataType : string;\n DataLength : decimal; \n}\n\nlet tableList = executeSqlReader<ColumnDefinition>\n \"MyDatabase\"\n \"SELECT t.table_name, column_name, data_type, data_length FROM USER_TABLES t, USER_TAB_COLUMNS c where t.TABLE_NAME = c.table_name order by t.table_name, c.COLUMN_NAME\"\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26227/"
] |
291,448 | <p>Is it possible for a python script to open its own source file and overwrite it?</p>
<p>The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.</p>
| [
{
"answer_id": 291733,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 4,
"selected": false,
"text": "# Check version of module\nimport module\n\n# Check update address\nif update_version > module.version:\n download(update_module)\n import module\n reload(module)\n\nmodule.main()\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] |
291,455 | <p>I have an XSD file that is encoded in UTF-8, and any text editor I run it through doesn't show any character at the beginning of the file, but when I pull it up in Visual Studio's debugger, I clearly see an empty box in front of the file. </p>
<p><img src="https://i294.photobucket.com/albums/mm93/geostock/bom3.jpg" alt="Box in file"></p>
<p>I also get the error: </p>
<p><strong>Data at the root level is invalid. Line 1, position 1.</strong></p>
<p><img src="https://i294.photobucket.com/albums/mm93/geostock/bom4.jpg" alt="alt text"></p>
<p>Anyone know what this is?</p>
<p>Update: Edited post to qualify type of file. It's an XSD file created by Microsoft's XSD creator.</p>
| [
{
"answer_id": 291462,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 7,
"selected": true,
"text": "EF BB BF EF BB BF"
},
{
"answer_id": 300470,
"author": "Benedikt Waldvogel",
"author_id": 4308,
"author_profile": "https://Stackoverflow.com/users/4308",
"pm_score": 5,
"selected": false,
"text": "# vim file.xml\n:set nobomb\n:wq\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16587/"
] |
291,459 | <p>I have an application where I'm dynamically loading routes by a model, and calling <code>ActionController::Routing::Routes.reload!</code> after creating/updating that model. The problem is that after doing this, I'm receiving the following error when I try to hit that new route:</p>
<pre><code>ActionController::MethodNotAllowed
Only get, head, post, put, and delete requests are allowed.
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/routing/recognition_optimisation.rb:65:in `recognize_path'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/routing/route_set.rb:384:in `recognize'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:148:in `handle_request'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:107:in `dispatch'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:104:in `synchronize'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:104:in `dispatch'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:120:in `dispatch_cgi'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:35:in `dispatch'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:502:in `load'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:502:in `load'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:502:in `load'
/usr/lib/ruby/gems/1.8/gems/rails-2.1.0/lib/commands/servers/mongrel.rb:64
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'
/usr/lib/ruby/gems/1.8/gems/rails-2.1.0/lib/commands/server.rb:39
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
script/server:3
</code></pre>
<p>What's really odd is that the request has no parameters, and the response headers are <code>{"cookie"=>[],
"Allow"=>"GET,
HEAD,
POST,
PUT,
DELETE",
"Cache-Control"=>"no-cache"}</code></p>
<p>All this even though the request is definitely GET (according to Firebug) and according to the response GET is certainly allowed.</p>
<p>I'm using Rails 2.1.0 and Mongrel 1.1.5 (after googling, I noticed some have problems with older versions).</p>
<p>Anyone have thoughts?</p>
| [
{
"answer_id": 291462,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 7,
"selected": true,
"text": "EF BB BF EF BB BF"
},
{
"answer_id": 300470,
"author": "Benedikt Waldvogel",
"author_id": 4308,
"author_profile": "https://Stackoverflow.com/users/4308",
"pm_score": 5,
"selected": false,
"text": "# vim file.xml\n:set nobomb\n:wq\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6705/"
] |
291,466 | <p>I am using jQuery to make an AJAX request to a remote endpoint. That endpoint will return a JSON object if there is a failure and that object will describe the failure. If the request is successful it will return HTML or XML.</p>
<p>I see how to define the expected request type in jQuery as part of the <code>$.ajax()</code> call. Is there a way to detect the request type in the <code>success</code> handler?</p>
<pre><code>$.ajax(
{
type: "DELETE",
url: "/SomeEndpoint",
//dataType: "html",
data:
{
"Param2": param0val,
"Param1": param1val
},
success: function(data) {
//data could be JSON or XML/HTML
},
error: function(res, textStatus, errorThrown) {
alert('failed... :(');
}
}
);
</code></pre>
| [
{
"answer_id": 291566,
"author": "dowski",
"author_id": 21712,
"author_profile": "https://Stackoverflow.com/users/21712",
"pm_score": 3,
"selected": true,
"text": "xhr = $.ajax(\n {\n //SNIP\n success: function(data) {\n var ct = xhr.getResponseHeader('Content-Type');\n if (ct == 'application/json') {\n //deserialize as JSON and continue\n } else if (ct == 'text/xml') {\n //deserialize as XML and continue\n }\n },\n //SNIP\n);\n"
},
{
"answer_id": 291569,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "complete $.ajax({\n ...\n\n complete : function(xhr, status) {\n // status is either \"success\" or \"error\"\n // complete is fired after success or error functions\n // xhr is the xhr object itself\n\n var header = xhr.getResponseHeader('Content-Type');\n },\n\n ...\n});\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
291,475 | <p>I have a win form (c#) with a datagridview. I set the grid's datasource to a datatable.</p>
<p>The user wants to check if some data in the datatable exists in another source, so we loop through the table comparing rows to the other source and set the rowerror on the datatable to a short message. The datagridview is not showing these errors. The errortext on the datagridviewrows are set, but no error displayed.</p>
<p>Am I just expecting too much for the errors to show and they only show in the context of editing the data in the grid? </p>
<p>I have been tinkering with this for a day and searched for someone that has posted a simalar issue to no avail - help!</p>
| [
{
"answer_id": 828947,
"author": "Andrew",
"author_id": 74448,
"author_profile": "https://Stackoverflow.com/users/74448",
"pm_score": 4,
"selected": false,
"text": "AutoSizeRowsMode DataGridViewAutoSizeRowsMode.None Errortext AutoSizeRowsMode DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None\n"
},
{
"answer_id": 4053331,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "grid.RowTemplate.Height = 22\n"
},
{
"answer_id": 7806008,
"author": "Julien P",
"author_id": 735753,
"author_profile": "https://Stackoverflow.com/users/735753",
"pm_score": 0,
"selected": false,
"text": "myDataGridView.DataSource = myDataSet.Tables(0) \nmyDataGridView.Refresh()\n"
},
{
"answer_id": 13482100,
"author": "Tim Fortune",
"author_id": 1840158,
"author_profile": "https://Stackoverflow.com/users/1840158",
"pm_score": 3,
"selected": false,
"text": "DataGridView ErrorText"
},
{
"answer_id": 16504365,
"author": "strongline",
"author_id": 2349587,
"author_profile": "https://Stackoverflow.com/users/2349587",
"pm_score": -1,
"selected": false,
"text": "SendKeys.Send(\"{ESC}\");\n"
},
{
"answer_id": 31877383,
"author": "esc",
"author_id": 2594731,
"author_profile": "https://Stackoverflow.com/users/2594731",
"pm_score": 2,
"selected": false,
"text": "dgv.ShowRowErrors"
},
{
"answer_id": 40841855,
"author": "Bolek",
"author_id": 1524524,
"author_profile": "https://Stackoverflow.com/users/1524524",
"pm_score": 1,
"selected": false,
"text": "private void gridGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n e.Cancel=true"
},
{
"answer_id": 43539143,
"author": "Karin",
"author_id": 2573649,
"author_profile": "https://Stackoverflow.com/users/2573649",
"pm_score": 2,
"selected": false,
"text": "gvwWebsites.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = \"You have already used that address.\";\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,493 | <p>I've been struggling with this check constraint for a few hours and was hoping someone would be kind enough to explain why this check constraint isn't doing what I think it should be doing.</p>
<pre><code>ALTER TABLE CLIENTS
add CONSTRAINT CHK_DISABILITY_INCOME_TYPE_ID CHECK ((IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL) OR (IS_DISABLED = 0 AND DISABILITY_INCOME_TYPE_ID IS NULL) OR (IS_DISABLED = 1));
</code></pre>
<p>Essentially, you must be disabled to collect disability income. It appears as though the first part of this check constraint <code>(IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL)</code> is not enforced (see below).</p>
<p>The available values for <code>DISABILITY_INCOME_TYPE_ID</code> are 1 and 2, which is enforced via foreign key. Both <code>IS_DISABLED</code> and <code>DISABILITY_INCOME_TYPE_ID</code> can be null.</p>
<pre><code>-- incorrectly succeeds (Why?)
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (null, 1);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (null, 2);
-- correctly fails
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (0, 1);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (0, 2);
-- correctly succeeds
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (0, null);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (1, 1);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (1, 2);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (1, null);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (null, null);
</code></pre>
<p>Thanks for your help,
Michael</p>
| [
{
"answer_id": 291581,
"author": "Khb",
"author_id": 37817,
"author_profile": "https://Stackoverflow.com/users/37817",
"pm_score": 1,
"selected": false,
"text": "ALTER TABLE CLIENTS ADD CONSTRAINT CHK_1 CHECK (IS_DISABLED = 0 AND DISABILITY_INCOME_TYPE_ID IS NULL)\n\nALTER TABLE CLIENTS ADD CONSTRAINT CHK_2 CHECK (IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL)\n\nALTER TABLE CLIENTS ADD CONSTRAINT CHK_3 CHECK (IS_DISABLED = 1)\n"
},
{
"answer_id": 291903,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": true,
"text": "IS_DISABLED NULL DISABILITY_INCOME_TYPE_ID postgres=> select (null is null and 1 is null);\n ?column?\n----------\n f\n(1 registro)\n\npostgres=> select (null is null and 1 is null) or (null = 0 and 1 is null);\n ?column?\n----------\n f\n(1 registro)\n\npostgres=> select (null is null and 1 is null) or (null = 0 and 1 is null) or (null = 1);\n ?column?\n----------\n\n(1 registro)\n CHECK ((IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL)\n OR (IS_DISABLED IS NOT NULL AND IS_DISABLED = 0 AND DISABILITY_INCOME_TYPE_ID IS NULL)\n OR (IS_DISABLED IS NOT NULL AND IS_DISABLED = 1));\n"
},
{
"answer_id": 292288,
"author": "BacMan",
"author_id": 455213,
"author_profile": "https://Stackoverflow.com/users/455213",
"pm_score": 0,
"selected": false,
"text": "CHECK\n((IS_DISABLED IS NULL AND NVL(DISABILITY_INCOME_TYPE_ID, 0) = 0)\nOR (IS_DISABLED = 0 AND NVL(DISABILITY_INCOME_TYPE_ID, 0) = 0) \nOR (IS_DISABLED IS NOT NULL AND IS_DISABLED = 1));\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455213/"
] |
291,508 | <p>When A Python exception is thrown by code that spans multiple lines, e.g.:</p>
<pre><code> myfoos = [foo("bar",
"baz",
"quux",
i) for i in range(10)]
</code></pre>
<p>Python will report the line number of the last line, and will show the code fragment from that line:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 4, in <module>
i) for i in range(10)]
NameError: name 'foo' is not defined
</code></pre>
<p>Is there any way to determine what the first line is? Is there any way to catch the exception and manipulate the <a href="http://docs.python.org/library/traceback.html" rel="nofollow noreferrer">traceback</a> object to be able to report something like this instead:</p>
<pre><code>Traceback (most recent call last):
File "test.py", lines 1-4 in <module>
myfoos = [foo("bar",
"baz",
"quux",
i) for i in range(10)]
NameError: name 'foo' is not defined
</code></pre>
| [
{
"answer_id": 291579,
"author": "dragonjujo",
"author_id": 37344,
"author_profile": "https://Stackoverflow.com/users/37344",
"pm_score": 0,
"selected": false,
"text": "try:\n somecode\nexcept NameError\n NameError.lineno = [1,4]\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] |
291,518 | <p>When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use <code>DependencyProperty</code> for properties the View is going to bind against and I have seen the ViewModel implementing <code>INotifyPropertyChanged</code> instead. </p>
<p>My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?</p>
| [
{
"answer_id": 293234,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 4,
"selected": false,
"text": "INotifyPropertyChanged string INotifyPropertyChanged"
},
{
"answer_id": 547295,
"author": "Adam",
"author_id": 1341,
"author_profile": "https://Stackoverflow.com/users/1341",
"pm_score": 4,
"selected": false,
"text": "INotifyPropertyChanged DependencyProperty public static DependencyProperty NameProperty = DependencyProperty.Register( \"Name\", typeof( String), typeof( Customer ) );\n\npublic String Name\n{\n set { SetValue( NameProperty, value ); }\n get { return ( String ) GetValue( NameProperty ); }\n}\n INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged;\n // ...\n// Something cool...\n// ...\n\nif( this.PropertyChanged != null )\n{\n PropertyChanged( this, new PropertyChangedEventArgs( \"Name\" ) );\n}\n\n// More cool stuff that will reliably happen...\n"
},
{
"answer_id": 5452109,
"author": "ramos",
"author_id": 679313,
"author_profile": "https://Stackoverflow.com/users/679313",
"pm_score": 2,
"selected": false,
"text": "DependencyObject ListBox TextBox INotifyPropertyChanged DependencyProperty TextBox"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227/"
] |
291,519 | <p>In the Windows registry, how does <code>CurrentControlSet</code> differ from
<code>ControlSet001</code> and <code>ControlSet002</code>? Which should be set when installing for all
users?</p>
<p>We are trying to add an environment variable for all users. Is this correct?</p>
<pre><code>HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Envinronment
</code></pre>
| [
{
"answer_id": 291528,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 7,
"selected": true,
"text": "CurrentControlSet ControlSet001 ControlSet002 CurrentControlSet CurrentControlSet ControlSet001 ControlSet002"
},
{
"answer_id": 291779,
"author": "Khb",
"author_id": 37817,
"author_profile": "https://Stackoverflow.com/users/37817",
"pm_score": 4,
"selected": false,
"text": "CurrentControlSet ControlSet ControlSet"
},
{
"answer_id": 1129773,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "CurrentControlSet ControlSetXXX CurrentControlSet CurrentControlSet"
},
{
"answer_id": 21812775,
"author": "mike",
"author_id": 3316202,
"author_profile": "https://Stackoverflow.com/users/3316202",
"pm_score": 3,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SYSTEM\\Select\\"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17975/"
] |
291,522 | <p>I have a simple WPF application with a menu. I need to add menu items dynamically at runtime. When I simply create a new menu item, and add it onto its parent MenuItem, it does not display in the menu, regardless of if UpdateLayout is called.</p>
<p>What must happen to allow a menu to have additional items dynamically added at runtime?</p>
<p>Note: the following code doesn't work.</p>
<pre><code> MenuItem mi = new MenuItem();
mi.Header = "Item to add";
mi.Visibility = Visibility.Visible;
//addTest is a menuitem that exists in the forms defined menu
addTest.Items.Add(mi);
addTest.UpdateLayout();
</code></pre>
<p>At the moment, the default menu items are defined in the xaml file. I want to add additional menu items onto this menu and its existing menu items. However, as stated, the above code does nothing.</p>
| [
{
"answer_id": 291550,
"author": "Whytespot",
"author_id": 33185,
"author_profile": "https://Stackoverflow.com/users/33185",
"pm_score": 6,
"selected": true,
"text": "//Add to main menu\nMenuItem newMenuItem1 = new MenuItem();\nnewMenuItem1.Header = \"Test 123\";\nthis.MainMenu.Items.Add(newMenuItem1);\n\n//Add to a sub item\nMenuItem newMenuItem2 = new MenuItem();\nMenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];\nnewMenuItem2.Header = \"Test 456\";\nnewExistMenuItem.Items.Add(newMenuItem2);\n"
},
{
"answer_id": 1108515,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 3,
"selected": false,
"text": "<MenuItem Name=\"LanguageMenu\" Header=\"_Language\">\n <MenuItem Header=\"English\" IsCheckable=\"True\" Click=\"File_Language_Click\"/>\n</MenuItem>\n // Clear the existing item(s) (this will actually remove the \"English\" element defined in XAML)\nLanguageMenu.Items.Clear(); \n\n// Dynamically get flag images from a specified folder to use for definingthe menu items \nstring[] files = Directory.GetFiles(Settings.LanguagePath, \"*.png\");\nforeach (string imagePath in files)\n{\n // Create the new menu item\n MenuItem item = new MenuItem();\n\n // Set the text of the menu item to the name of the file (removing the path and extention)\n item.Header = imagePath.Replace(Settings.LanguagePath, \"\").Replace(\".png\", \"\").Trim(\"\\\\\".ToCharArray());\n if (File.Exists(imagePath))\n {\n // Create image element to set as icon on the menu element\n Image icon = new Image();\n BitmapImage bmImage = new BitmapImage();\n bmImage.BeginInit();\n bmImage.UriSource = new Uri(imagePath, UriKind.Absolute);\n bmImage.EndInit();\n icon.Source = bmImage;\n icon.MaxWidth = 25;\n item.Icon = icon;\n }\n\n // Hook up the event handler (in this case the method File_Language_Click handles all these menu items)\n item.Click += new RoutedEventHandler(File_Language_Click); \n\n // Add menu item as child to pre-defined menu item\n LanguageMenu.Items.Add(item); // Add menu item as child to pre-defined menu item\n}\n"
},
{
"answer_id": 4354412,
"author": "Patrick Hendry",
"author_id": 530540,
"author_profile": "https://Stackoverflow.com/users/530540",
"pm_score": 3,
"selected": false,
"text": "<menuitem> <toolbar> <menuitem> <menu> <toolbar>\n <menuitem>\n </menuitem>\n</toolbar> \n <toolbar>\n <menu>\n <menuitem>\n </menuitem>\n </menu>\n</toolbar> \n"
},
{
"answer_id": 27546380,
"author": "Коныч Казах",
"author_id": 4374147,
"author_profile": "https://Stackoverflow.com/users/4374147",
"pm_score": -1,
"selected": false,
"text": "CREATE TABLE `webmenu` (\n `idmenu` smallint(5) NOT NULL,\n `submenu` smallint(5) DEFAULT NULL,\n `menu_title` varchar(45) DEFAULT NULL,\n `menu_url` varchar(45) DEFAULT NULL,\n `status` enum('1','0') DEFAULT '1',\n PRIMARY KEY (`idmenu`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nSELECT \nidmenu,\n(select menu_title from webmenu where idmenu=wm.submenu and status='1') as childmenu,\nmenu_title,\nmenu_url \nFROM tartyp.webmenu as wm\nwhere\nstatus='1'\norder by idmenu, submenu;\n cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);\n\n reader = cmd.ExecuteReader();\n MainMenu.Items.Clear();\n while (reader.Read())\n {\n\n if (reader[\"childmenu\"] == DBNull.Value)\n {\n MenuItem homeMenuItem = new MenuItem(reader[\"menu_title\"].ToString(), reader[\"menu_url\"].ToString());\n MainMenu.Items.Add(homeMenuItem);\n }\n else\n {\n String childmenu = reader[\"childmenu\"].ToString(); \n\n for (int i = 0; i < MainMenu.Items.Count; i++)\n {\n if (MainMenu.Items[i].Text == childmenu)\n { \n MenuItem childMenuItem = new MenuItem(reader[\"menu_title\"].ToString(), reader[\"menu_url\"].ToString());\n MenuItem findMenuItem = MainMenu.Items[i];\n findMenuItem.ChildItems.Add(childMenuItem);\n break; \n }\n }\n }\n\n }\n reader.Close();\n conn.Close();\n"
},
{
"answer_id": 27971207,
"author": "Brandon Hawbaker",
"author_id": 967811,
"author_profile": "https://Stackoverflow.com/users/967811",
"pm_score": 0,
"selected": false,
"text": "row.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));\n <DataGrid AutoGenerateColumns=\"False\" HorizontalAlignment=\"Stretch\" Margin=\"12,29,12,12\" Name=\"grid\" VerticalAlignment=\"Stretch\" Background=\"#FF3A81A0\" AlternatingRowBackground=\"#FFD9EEF2\" FontSize=\"15\" RowHeaderWidth=\"0\" KeyDown=\"grid_KeyDown\">\n <DataGrid.ContextMenu>\n <ContextMenu>\n <MenuItem Header=\"_Encrypt Row Values\" Click=\"MenuItem_ContextMenu_Click_EncryptRowValues\" Name=\"MenuItem_EncryptRowValues\" />\n <MenuItem Header=\"De_crypt Row Values\" Click=\"MenuItem_ContextMenu_Click_DecryptRowValues\" Name=\"MenuItem_DecryptRowValues\" />\n <MenuItem Header=\"Copy Row_s\" Click=\"MenuItem_ContextMenu_Click_CopyRows\" />\n </ContextMenu>\n </DataGrid.ContextMenu>\n <DataGrid.Resources>\n\n\n //Add Encryption Menu Items\n for (int i=0; i< encryptionKeys.Count; i++)\n {\n MenuItem keyOption = new MenuItem();\n keyOption.Header = \"_\" + i.ToString() + \" \" + encryptionKeys[i];\n MenuItem_EncryptRowValues.Items.Add(keyOption);\n }\n\n //Add Decryption Menu Items\n for (int i = 0; i < encryptionKeys.Count; i++)\n {\n MenuItem keyOption = new MenuItem();\n keyOption.Header = \"_\" + i.ToString() + \" \" + encryptionKeys[i];\n MenuItem_DecryptRowValues.Items.Add(keyOption);\n }\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18313/"
] |
291,527 | <p>I'm working on a website that uses not just frames, but frames within frames (ew, I know, but I don't get to choose). It actually works OK most of the time, but I'm running into a problem with some of the frames within frames in Safari (only).</p>
<p>Some of the two-deep frames render in Safari with a small space on the right-hand side of the frame - I think it's just the ones with scroll set to "no", but fiddling with the scroll settings hasn't fixed it yet. It basically looks like there should be a scroll bar there, but there isn't.</p>
<p>I've been working on this awhile and tried a lot of things: changing the heights of the rows, changing the scroll settings, adding a <code>colls='100%'</code> tag, changing the heights of the contents of the frames, as well as checking to make sure widths are set to 100% throughout. Nothing's fixed it so far. </p>
<p>Does any one know what's happening here?</p>
<p>Here's the basic gist of the code and some screenshots - please forgive the lack of proper quotes; it still renders and fixing them all in this codebase would be a losing battle:</p>
<pre><code><html>
<frameset id=fset frameborder=0 border=0 framespacing=0 onbeforeunload="onAppClosing()" onload="onAppInit()" rows="125px,*,0">
<frame src="navFrame.html" name=ControlPanel marginwidth=0 marginheight=0 frameborder=0 scrolling=no noresize>
<frame src="contentFrame.html" name=C marginwidth=0 marginheight=0 frameborder=0 scrolling=no>
<frame src="invisiFrame.html" name=PING marginwidth=0 marginheight=0 frameborder=0 noresize>
<noframes><body>Tough luck.</center></body></noframes>
</frameset></html>
</code></pre>
<p>Inside that second frame (named "C" and with src of "contentFrame") is this:</p>
<pre><code> <HTML>
<HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8"></head>
<frameset rows="48px,*,28px" border=0 frameborder=0 framespacing=0>
<frame src="pageTitle.html" name=Title marginwidth=0 marginheight=0 noresize scrolling=no frameborder=0>
<frame src="content.html" name=ScreenBody marginwidth=0 marginheight=0 frameborder=0>
<frame src="submitBar.html" name=ContextPanel marginwidth=0 marginheight=0 frameborder=0 scrolling=no noresize>
</FRAMESET>
</HTML>
</code></pre>
<p>The frames that are troublesome are the first frame (named "Title" with src of "pageTitle.html") and the last frame (named "ContextPanel" with src of "submitBar.html") both have their widths set to 100% and heights are either 100%, not set, or a value less than or equal to their row height.</p>
<p>Here is an image of the problem:</p>
<p><img src="https://farm4.static.flickr.com/3290/3029873741_f42727c4e5_o.gif" alt="image showing site in Firefox and Safari, with sections labeled"></p>
| [
{
"answer_id": 291550,
"author": "Whytespot",
"author_id": 33185,
"author_profile": "https://Stackoverflow.com/users/33185",
"pm_score": 6,
"selected": true,
"text": "//Add to main menu\nMenuItem newMenuItem1 = new MenuItem();\nnewMenuItem1.Header = \"Test 123\";\nthis.MainMenu.Items.Add(newMenuItem1);\n\n//Add to a sub item\nMenuItem newMenuItem2 = new MenuItem();\nMenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];\nnewMenuItem2.Header = \"Test 456\";\nnewExistMenuItem.Items.Add(newMenuItem2);\n"
},
{
"answer_id": 1108515,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 3,
"selected": false,
"text": "<MenuItem Name=\"LanguageMenu\" Header=\"_Language\">\n <MenuItem Header=\"English\" IsCheckable=\"True\" Click=\"File_Language_Click\"/>\n</MenuItem>\n // Clear the existing item(s) (this will actually remove the \"English\" element defined in XAML)\nLanguageMenu.Items.Clear(); \n\n// Dynamically get flag images from a specified folder to use for definingthe menu items \nstring[] files = Directory.GetFiles(Settings.LanguagePath, \"*.png\");\nforeach (string imagePath in files)\n{\n // Create the new menu item\n MenuItem item = new MenuItem();\n\n // Set the text of the menu item to the name of the file (removing the path and extention)\n item.Header = imagePath.Replace(Settings.LanguagePath, \"\").Replace(\".png\", \"\").Trim(\"\\\\\".ToCharArray());\n if (File.Exists(imagePath))\n {\n // Create image element to set as icon on the menu element\n Image icon = new Image();\n BitmapImage bmImage = new BitmapImage();\n bmImage.BeginInit();\n bmImage.UriSource = new Uri(imagePath, UriKind.Absolute);\n bmImage.EndInit();\n icon.Source = bmImage;\n icon.MaxWidth = 25;\n item.Icon = icon;\n }\n\n // Hook up the event handler (in this case the method File_Language_Click handles all these menu items)\n item.Click += new RoutedEventHandler(File_Language_Click); \n\n // Add menu item as child to pre-defined menu item\n LanguageMenu.Items.Add(item); // Add menu item as child to pre-defined menu item\n}\n"
},
{
"answer_id": 4354412,
"author": "Patrick Hendry",
"author_id": 530540,
"author_profile": "https://Stackoverflow.com/users/530540",
"pm_score": 3,
"selected": false,
"text": "<menuitem> <toolbar> <menuitem> <menu> <toolbar>\n <menuitem>\n </menuitem>\n</toolbar> \n <toolbar>\n <menu>\n <menuitem>\n </menuitem>\n </menu>\n</toolbar> \n"
},
{
"answer_id": 27546380,
"author": "Коныч Казах",
"author_id": 4374147,
"author_profile": "https://Stackoverflow.com/users/4374147",
"pm_score": -1,
"selected": false,
"text": "CREATE TABLE `webmenu` (\n `idmenu` smallint(5) NOT NULL,\n `submenu` smallint(5) DEFAULT NULL,\n `menu_title` varchar(45) DEFAULT NULL,\n `menu_url` varchar(45) DEFAULT NULL,\n `status` enum('1','0') DEFAULT '1',\n PRIMARY KEY (`idmenu`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nSELECT \nidmenu,\n(select menu_title from webmenu where idmenu=wm.submenu and status='1') as childmenu,\nmenu_title,\nmenu_url \nFROM tartyp.webmenu as wm\nwhere\nstatus='1'\norder by idmenu, submenu;\n cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);\n\n reader = cmd.ExecuteReader();\n MainMenu.Items.Clear();\n while (reader.Read())\n {\n\n if (reader[\"childmenu\"] == DBNull.Value)\n {\n MenuItem homeMenuItem = new MenuItem(reader[\"menu_title\"].ToString(), reader[\"menu_url\"].ToString());\n MainMenu.Items.Add(homeMenuItem);\n }\n else\n {\n String childmenu = reader[\"childmenu\"].ToString(); \n\n for (int i = 0; i < MainMenu.Items.Count; i++)\n {\n if (MainMenu.Items[i].Text == childmenu)\n { \n MenuItem childMenuItem = new MenuItem(reader[\"menu_title\"].ToString(), reader[\"menu_url\"].ToString());\n MenuItem findMenuItem = MainMenu.Items[i];\n findMenuItem.ChildItems.Add(childMenuItem);\n break; \n }\n }\n }\n\n }\n reader.Close();\n conn.Close();\n"
},
{
"answer_id": 27971207,
"author": "Brandon Hawbaker",
"author_id": 967811,
"author_profile": "https://Stackoverflow.com/users/967811",
"pm_score": 0,
"selected": false,
"text": "row.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));\n <DataGrid AutoGenerateColumns=\"False\" HorizontalAlignment=\"Stretch\" Margin=\"12,29,12,12\" Name=\"grid\" VerticalAlignment=\"Stretch\" Background=\"#FF3A81A0\" AlternatingRowBackground=\"#FFD9EEF2\" FontSize=\"15\" RowHeaderWidth=\"0\" KeyDown=\"grid_KeyDown\">\n <DataGrid.ContextMenu>\n <ContextMenu>\n <MenuItem Header=\"_Encrypt Row Values\" Click=\"MenuItem_ContextMenu_Click_EncryptRowValues\" Name=\"MenuItem_EncryptRowValues\" />\n <MenuItem Header=\"De_crypt Row Values\" Click=\"MenuItem_ContextMenu_Click_DecryptRowValues\" Name=\"MenuItem_DecryptRowValues\" />\n <MenuItem Header=\"Copy Row_s\" Click=\"MenuItem_ContextMenu_Click_CopyRows\" />\n </ContextMenu>\n </DataGrid.ContextMenu>\n <DataGrid.Resources>\n\n\n //Add Encryption Menu Items\n for (int i=0; i< encryptionKeys.Count; i++)\n {\n MenuItem keyOption = new MenuItem();\n keyOption.Header = \"_\" + i.ToString() + \" \" + encryptionKeys[i];\n MenuItem_EncryptRowValues.Items.Add(keyOption);\n }\n\n //Add Decryption Menu Items\n for (int i = 0; i < encryptionKeys.Count; i++)\n {\n MenuItem keyOption = new MenuItem();\n keyOption.Header = \"_\" + i.ToString() + \" \" + encryptionKeys[i];\n MenuItem_DecryptRowValues.Items.Add(keyOption);\n }\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18860/"
] |
291,537 | <p>As a followup to <a href="https://stackoverflow.com/questions/290335/how-can-i-position-an-element-at-the-bottom-of-its-container-in-firefox">this question</a> on absolute positioning within a table cell, I'm trying to get something working in Firefox. Once again, I'm about 95% there, and there's just 1 little thing that's keeping me from declaring victory. Using the follow sample markup:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test</title>
<style type="text/css">
table { width:500px; border-collapse:collapse}
th, td { border:1px solid black; vertical-align: top; }
th { width:100px; }
td { background:#ccc; }
.wrap { position:relative; height:100%; padding-bottom:1em; background:#aaa; }
.manage { text-align:right; position:absolute; bottom:0; right:0; }
p{ margin: 0 0 5px 0; }
</style>
</head>
<body >
<table>
<tr>
<th>Mauris tortor nulla, sagittis ut, faucibus eu, imperdiet ut, libero.</th>
<td><div class="wrap"><p>Cras diam.</p><div class="manage">Edit | Delete</div></div></td>
</tr>
<tr>
<th>Cras diam.</th>
<td><div class="wrap"><p>Cras diam.</p><div class="manage">Edit | Delete</div></div></td>
</tr>
<tr>
<th>Cras diam.</th>
<td><div class="wrap"><p>Mauris tortor nulla, sagittis ut, faucibus eu, imperdiet ut, libero. Sed elementum. Praesent porta, tellus ut dictum ullamcorper, est ante condimentum metus, non molestie lorem turpis in sapien. Aenean id enim. Nullam placerat blandit ante. Aenean ac ligula.</p><div class="manage">Edit | Delete</div></div></td>
</tr>
</table>
</body>
</html>
</code></pre>
<p>How can I get the wrap div to always fill the cell, so that the management area sits at the bottom of the cell? And yes, the data that I am putting in the table is (in my mind) tabular, so I would like to use a table here. As a last resort, I may turn to an ugly nested div solution, but since a table is semantically correct here I'd like to use one if possible. Note that the background colors are simply to show the relative sizes of the elements - I don't care about background for my layout. Also note that I'd like the cells to have a flexible height, so that they only expand enough to fit their content.</p>
| [
{
"answer_id": 291651,
"author": "da5id",
"author_id": 14979,
"author_profile": "https://Stackoverflow.com/users/14979",
"pm_score": 2,
"selected": false,
"text": "<style type=\"text/css\">\ntable { width:500px; border-collapse:collapse}\nth, td { height:200px; border:1px solid black; vertical-align: top; }\nth { width:100px; }\ntd { background:#ccc; }\n.wrap { position:relative; height:200px; padding-bottom:1em; background:#aaa; }\n.manage { text-align:right; position:absolute; bottom:0; right:0; }\np{ margin: 0 0 5px 0; }\n</style>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] |
291,574 | <p>I want a query that returns a list of all the (user) stored procedures in a database by name, with the number of lines of code for each one.</p>
<p>i.e.</p>
<pre><code>sp_name lines_of_code
-------- -------------
DoStuff1 120
DoStuff2 50
DoStuff3 30
</code></pre>
<p>Any ideas how to do this?</p>
| [
{
"answer_id": 291633,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 7,
"selected": true,
"text": "select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc\nfrom\n(\n select o.name as sp_name, \n (len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code,\n case when o.xtype = 'P' then 'Stored Procedure'\n when o.xtype in ('FN', 'IF', 'TF') then 'Function'\n end as type_desc\n from sysobjects o\n inner join syscomments c\n on c.id = o.id\n where o.xtype in ('P', 'FN', 'IF', 'TF')\n and o.category = 0\n and o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams')\n) t\ngroup by t.sp_name, t.type_desc\norder by 1\n"
},
{
"answer_id": 291720,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 2,
"selected": false,
"text": "SET NOCOUNT ON\n\nDECLARE @ProcName varchar(100)\nDECLARE @LineCount int\n\nDECLARE C CURSOR LOCAL FOR\n SELECT o.name as ProcName FROM sysobjects o WHERE (o.xtype = 'P') ORDER BY o.name\n\nOPEN C\n\nCREATE TABLE #ProcLines ([Text] varchar(1000))\n\nFETCH NEXT FROM C INTO @ProcName\n\nWHILE @@FETCH_STATUS = 0 \nBEGIN\n\n DELETE FROM #ProcLines\n INSERT INTO #ProcLines EXEC('sp_helptext ' + @ProcName + '')\n\n SELECT @LineCount = COUNT(*) FROM #ProcLines\n\n PRINT @ProcName + ' Lines: ' + LTRIM(STR(@LineCount))\n\n FETCH NEXT FROM C INTO @ProcName\n\nEND\n\nCLOSE C\n\nDEALLOCATE C\n\nDROP TABLE #ProcLines\n"
},
{
"answer_id": 2073617,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": false,
"text": "SELECT o.type_desc AS ROUTINE_TYPE\n ,QUOTENAME(s.[name]) + '.' + QUOTENAME(o.[name]) AS [OBJECT_NAME]\n ,(LEN(m.definition) - LEN(REPLACE(m.definition, CHAR(10), ''))) AS LINES_OF_CODE\nFROM sys.sql_modules AS m\nINNER JOIN sys.objects AS o\n ON m.[object_id] = o.[OBJECT_ID]\nINNER JOIN sys.schemas AS s\n ON s.[schema_id] = o.[schema_id]\n"
},
{
"answer_id": 2620902,
"author": "Hari Prasad Savaravilli",
"author_id": 314359,
"author_profile": "https://Stackoverflow.com/users/314359",
"pm_score": -1,
"selected": false,
"text": "select * from sysobjects where type = 'p'\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161040/"
] |
291,582 | <p>Using strictly SQL (no PHP or anything else), is it possible to create a table <strong>and insert default data into that table</strong> only if that table doesn't exist?</p>
| [
{
"answer_id": 291635,
"author": "Jonas Kongslund",
"author_id": 37548,
"author_profile": "https://Stackoverflow.com/users/37548",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE IF NOT EXISTS T (\n ID int(10) unsigned NOT NULL primary key,\n NAME varchar(255) NOT NULL\n);\n\nREPLACE INTO T SELECT 1, 'John Doe';\nREPLACE INTO T SELECT 2, 'Jane Doe';\n"
},
{
"answer_id": 291642,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "if(not exists select * from whatever_meta where table_name = \"whatever)\nbegin\n ...\nend\n"
},
{
"answer_id": 291668,
"author": "Matt",
"author_id": 32881,
"author_profile": "https://Stackoverflow.com/users/32881",
"pm_score": 0,
"selected": false,
"text": "@status = SHOW TABLES LIKE 'my_table';\nINSERT INTO my_table VALUES (1,'hello'),(2,'world') WHERE @status <> false;\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32881/"
] |
291,603 | <p>How can I tell the preprocessor not to replace a specific macro?</p>
<p>The specific problem is the following: Windows header files define the GetMessage macro.</p>
<p>My C++ header files with my API have a GetMessage method. I do not want to rename my method. But when using the API on Windows, including windows.h replaces my GetMessage method call with GetMessageA.</p>
| [
{
"answer_id": 291615,
"author": "ShoeLace",
"author_id": 3825,
"author_profile": "https://Stackoverflow.com/users/3825",
"pm_score": 3,
"selected": false,
"text": "#pragma push_macro(\"GetMessage\")\n#undef GetMessage\n\n// Your GetMessage usage/definition here\n\n#pragma pop_macro(\"GetMessage\")\n"
},
{
"answer_id": 291677,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 0,
"selected": false,
"text": "#undef GetMessage\n"
},
{
"answer_id": 291711,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 3,
"selected": false,
"text": "(GetMessage)(...) GetMessage"
},
{
"answer_id": 291735,
"author": "Brian",
"author_id": 17356,
"author_profile": "https://Stackoverflow.com/users/17356",
"pm_score": 2,
"selected": false,
"text": "#pragma push_macro(\"GetMessage\")\n#undef GetMessage\n\n// Your GetMessage usage/definition here\n\n#pragma pop_macro(\"GetMessage\")\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37820/"
] |
291,620 | <p>When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?</p>
<p>Lets say you have a query:</p>
<pre><code>Query q = session.createQuery("from Table where date_field < :now");
q.setDate("now", new java.util.Date());
</code></pre>
<p>"now" will be set to GMT time, while "new Date()" gets your current server time.</p>
<p>Thanks.</p>
| [
{
"answer_id": 291970,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 2,
"selected": false,
"text": "Properties properties = new Properties();\nproperties.setProperty(\"timeZone\", databaseTimeZone);\nquery.setParameter(\"from\", dateEnteredByUser, Hibernate.custom(LocalizedDateType.class, properties));\n"
},
{
"answer_id": 452154,
"author": "serg",
"author_id": 20128,
"author_profile": "https://Stackoverflow.com/users/20128",
"pm_score": 7,
"selected": true,
"text": "query.setDate() query.setTimestamp(\"date\", dateObj)"
},
{
"answer_id": 51374698,
"author": "Kayvan Tehrani",
"author_id": 732328,
"author_profile": "https://Stackoverflow.com/users/732328",
"pm_score": 1,
"selected": false,
"text": " /* @deprecated (since 5.2) use {@link #setParameter(int, Object)} or\n {@link #setParameter(int, Object, Type)} instead\n */\n import org.hibernate.query.Query;\n...\nQuery query = session.createQuery(\"from Table where date_field < :now\");\nquery.setParameter(\"now\", new Date(), TimestampType.INSTANCE );\n query.setParameter(\"firstMomentOfToday\", new Date(), DateType.INSTANCE);\n"
},
{
"answer_id": 72110444,
"author": "Christine",
"author_id": 904624,
"author_profile": "https://Stackoverflow.com/users/904624",
"pm_score": 0,
"selected": false,
"text": "query.setParameter(\"now\", new Date(), TemporalType.DATE );"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
] |
291,623 | <p>I am trying to design a location lookup in which the user can specify a location to any desired level of accuracy. eg. one of Country, State, City, Borough etc,</p>
<p>I have a used a common location table, which will then be used in a lookup with the table name selected dynamically, but was wondering if there is a feasible alternative way to do this.</p>
<p><a href="http://img386.imageshack.us/img386/3842/locationschemadh6.png" rel="nofollow noreferrer">alt text http://img386.imageshack.us/img386/3842/locationschemadh6.png</a></p>
<p><strong>Edit</strong> The hierarchical table looks like the way to go. Thanks for the tip.</p>
| [
{
"answer_id": 291634,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 3,
"selected": true,
"text": "locations\n id int\n parentId int\n name varchar(45)\n"
},
{
"answer_id": 291691,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE location (\n id INT PRIMARY KEY,\n table_name VARCHAR(45) NOT NULL CHECK (table_name in ('city', 'state')),\n table_id INT NOT NULL -- matches an id in either city or state\n);\n location.table location SELECT l.id, COALESCE(s.name, c.name, 'Unknown Location') AS name\nFROM location AS l\n LEFT OUTER JOIN state AS s ON (l.id = s.location_id)\n LEFT OUTER JOIN city AS c ON (l.id = c.location_id);\n location city state CREATE TABLE location (\n id INT PRIMARY KEY,\n loc_type VARCHAR(45) NOT NULL CHECK (table_name in ('city', 'state')),\n loc_name VARCHAR(45) NOT NULL,\n parent_id INT, -- NULL if root of tree\n FOREIGN KEY (parent_id) REFERENCES location(id)\n);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36670/"
] |
291,631 | <p>I recently upgraded from Delphi 4 to Delphi 2009. With Delphi 4 I had been using <a href="http://web.archive.org/web/20001205122400/http://www.eccentrica.org/gabr/gpprofile/gpprofile.htm" rel="noreferrer">GpProfile by Primoz Gabrijelcic</a> as a profiler and <a href="http://web.archive.org/web/20031204135824/http://www.turbopower.com/products/sleuth/" rel="noreferrer">Memory Sleuth by Turbo Power</a> for memory analysis and leak debugging. Both worked well for me. But I now need new tools that will work with Delphi 2009. </p>
<p>The leader in Profiling/Analysis tools for Delphi by a wide margin is obviously <a href="http://www.automatedqa.com/products/aqtime/index.asp" rel="noreferrer">AQTime by AutomatedQA</a>. They recently even gobbled up <a href="http://www.scip.be/index.php?Page=ArticlesDelphi07&Lang=EN" rel="noreferrer">Memproof by Atanas Soyanov</a>, which I understood was an excellent and free memory analysis tool, and incorporated its functionality into AQTime. But AQTime is very expensive for an individual programmer. It actually costs more than the upgrade to Delphi 2009 cost!</p>
<p>So my question is: Are there other less expensive options to do profiling and memory analysis in current versions of Delphi that you are happy with and recommend, or should I bite the bullet and pay the big bucks for AQTime?</p>
<hr>
<p>Addenum: It seems the early answerers are indicating that the FastMM manager already included in Delphi is very good for finding memory leaks.</p>
<p>So then, are there any good alternatives for source code profiling? </p>
<p>One I'm curious about is <a href="http://www.prodelphi.de/indexpd.htm" rel="noreferrer">ProDelphi by Michael Adolph</a> which is less than one sixth the cost of AQTime. Do you use it? Is AQTime worth paying six times as much?</p>
<hr>
<p>Addenum 2: I downloaded trial versions of both AQTime and ProDelphi.</p>
<p>AQTime was a bit overwhelming and a little confusing at first. It took a few hours to find some of the tricks needed to hook it up. </p>
<p>ProDelphi was very much like the GpProfile that I was used to. But its windows are cluttered and confusing and it's not quite as nice as GpProfile.</p>
<p>To me the big differences seem to be:</p>
<ol>
<li><p>ProDelphi changes your code. AQTime does not. Changing code may corrupt your data if something goes wrong, but my experience with GpProfile was that it never happened to me. Plus one for AQTime.</p></li>
<li><p>ProDelphi requires you turn optimization off. But what you want to profile is your program with optimization on, the way it will be run. Plus one for AQTime.</p></li>
<li><p>ProDelphi only can profile down to the function or procedure. AQTime can go down to individual lines. Plus 2 for AQTime.</p></li>
<li><p>ProDelphi has a free version that will profile 20 routines, and its pro version costs less than $100 USD. AQTime is $600 USD. Plus 4 for ProDelphi.</p></li>
</ol>
<p>The score is now 4-4. What do you think?</p>
<hr>
<p>Addenum 3: Primoz Gabrijelcic is planning to get GpProfile working again. See his comments on some of the responses below. He on StackOverflow as <a href="https://stackoverflow.com/users/4997/gabr">Gabr</a>.</p>
<hr>
<p>Addenum 4: It seems like there may be a profiler solution after all. See <a href="https://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi/672554#672554">Andre's open source asmprofiler, described below</a>.</p>
| [
{
"answer_id": 292047,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 6,
"selected": true,
"text": "ReportMemoryLeaksOnShutDown := True;\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30176/"
] |
291,647 | <p>I embedded a swf in my html page, but I would like it to swap to another swf when I clicked on a button in html. I used swfobject.js to embed the swf, and I use prototype to write the javascript. I thought I can just do this</p>
<pre><code>$('movie').value = 'swf/bhts.swf';
alert($('movie').value);
</code></pre>
<p>the value did change to swf/bhts.swf, but it is still playing the original swf file...
this is the code I use to embed swf</p>
<pre><code><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="530" height="298" id="flashcontent">
<param id="movie" name="movie" value="swf/trailer.swf" />
</object>
</code></pre>
<p>thanks.</p>
| [
{
"answer_id": 291656,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<div id='flashContent'>\n</div>\n\n<script type='text/javascript'> \n // Setup your initial flash \n var so = new SwfObject(.....);\n so.write ('flashContent');\n\n // Some event handler\n someElement.onclick = function ()\n {\n // Load up the new SWF\n so = new swfObject(....);\n so.write('flashContent');\n }\n</script>\n"
},
{
"answer_id": 291818,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 0,
"selected": false,
"text": "var swf = getElementById(\"flash_id\");\nswf.LoadMovie(0, \"http://example.com/newSwfUrl.swf\");\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34797/"
] |
291,661 | <p>I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.</p>
<p>I have an application that is pulling email via POP3. I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email. I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc. I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.</p>
<p>Hope this makes some amount of sense and that someone can shed some light on this. In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.</p>
| [
{
"answer_id": 1478524,
"author": "mightytightywty",
"author_id": 134585,
"author_profile": "https://Stackoverflow.com/users/134585",
"pm_score": 3,
"selected": false,
"text": " public string ExtractAlternateView()\n {\n var message = new System.Net.Mail.MailMessage();\n message.Body = \"This is the TEXT version\";\n\n //Add textBody as an AlternateView\n message.AlternateViews.Add(\n System.Net.Mail.AlternateView.CreateAlternateViewFromString(\n \"This is the HTML version\",\n new System.Net.Mime.ContentType(\"text/html\")\n )\n );\n\n var dataStream = message.AlternateViews[0].ContentStream;\n byte[] byteBuffer = new byte[dataStream.Length];\n return System.Text.Encoding.ASCII.GetString(byteBuffer, 0, dataStream.Read(byteBuffer, 0, byteBuffer.Length));\n }\n"
},
{
"answer_id": 6736953,
"author": "John Kaster",
"author_id": 74137,
"author_profile": "https://Stackoverflow.com/users/74137",
"pm_score": 4,
"selected": false,
"text": "var dataStream = view.ContentStream;\ndataStream.Position = 0;\nbyte[] byteBuffer = new byte[dataStream.Length];\nvar encoding = Encoding.GetEncoding(view.ContentType.CharSet);\nstring body = encoding.GetString(byteBuffer, 0, \n dataStream.Read(byteBuffer, 0, byteBuffer.Length));\n"
},
{
"answer_id": 20024414,
"author": "carlos357",
"author_id": 1079231,
"author_profile": "https://Stackoverflow.com/users/1079231",
"pm_score": 2,
"selected": false,
"text": "public string GetPlainTextBodyFromMsg(MailMessage msg)\n{\n StreamReader plain_text_body_reader = new StreamReader(msg.AlternateViews[0].ContentStream);\n return(plain_text_body_reader.ReadToEnd());\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678/"
] |
291,675 | <p>How can I take full advantage of 64-bit architecture in my .NET 2.0 Web Applications and Console/Forms Applications?</p>
| [
{
"answer_id": 291719,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 1,
"selected": false,
"text": "long"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
291,696 | <p>Have you ever had alternating background colors in a Jasper report and then exported it to Excel? The Excel export seems to ignore the alternating color.</p>
<p>I've got a Jasper report where the rows alternating background color using the procedure referenced <a href="http://www.brianburridge.com/2006/06/19/highlighting-odd-even-rows-jasperreports" rel="nofollow noreferrer">HERE</a>. When I preview it using the viewer or export to PDF it works -- but not when I export to Excel. I've tried using <code>JRXlsExporter</code> and <code>JExcelApiExporter</code> both to no avail. </p>
<p>I think it might be a side-effect of how you have to make alternating row colors in Jasper, which I despise to begin with, but have found no other way.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 291907,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "Boolean.valueOf( $V{PAGE_COUNT}.intValue() % 2 == 0 )\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23904/"
] |
291,704 | <p>We have an advanced webpage (ASP.NET, C#), and a application which needs to be installed on the client computer in order to utilize the webpage to its fullest. The application is a tray app, and has primarily two tasks. Detect when certain events happen on the webserver (for instance invited to a meeting, or notify of an upcoming meeting). The other task the trayapp has is to use a custom protocol (trayapp://) to perform some ajax calls back to the server.</p>
<p>One problem we have is how to determine if the application is installed on the local machine or not. Now the user has to tick a checkbox to inform the website that the application is installed, and that it's safe to call the trayapp:// url calls.</p>
<p>Is there any way, for instance through a JavaScript or similar to detect if our application is installed on the local machine?</p>
<p>The check needs to work for IE, FF and Opera browsers.</p>
| [
{
"answer_id": 291747,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 3,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\\n Internet Settings\\Accepted Documents\n"
},
{
"answer_id": 291760,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 4,
"selected": true,
"text": "if (navigator.plugins[\"Adobe Acrobat\"]) {\n// do some stuff if it is installed\n} else {\n// do some other stuff if its not installed\n}\n function getActiveXObject(name){\n try{\n return new ActiveXObject(name);\n }\n catch(err){\n return undefined;\n }\n};\n HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\Curr entVersion\\Internet\nSettings\\User Agent\\Post Platform\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33431/"
] |
291,705 | <p>Someone posted a great little function here the other day that separated the full path of a file into several parts that looked like this:</p>
<pre><code>Function BreakDown(Full As String, FName As String, PName As String, Ext As String) As Integer
If Full = "" Then
BreakDown = False
Exit Function
End If
If InStr(Full, "\") Then
FName = Full
PName = ""
Sloc% = InStr(FName, "\")
Do While Sloc% <> 0
PName = PName + Left$(FName, Sloc%)
FName = Mid$(FName, Sloc% + 1)
Sloc% = InStr(FName, "\")
Loop
Else
PName = ""
FName = Full
End If
Dot% = InStr(Full, ".")
If Dot% <> 0 Then
Ext = Mid$(Full, Dot%)
Else
Ext = ""
End If
BreakDown = True
End Function
</code></pre>
<p>However if the line continues past that point it counts it as part of the extension, is there anyway to make this only count to 3 characters after the last period in a string?</p>
| [
{
"answer_id": 291732,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 0,
"selected": false,
"text": "Full = Trim(Full)\n Ext = Mid$(Full, Dot%)\n Ext = Mid$(Full, Dot%, 3)\n"
},
{
"answer_id": 291741,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 2,
"selected": true,
"text": "Dot% = InStrRev(Full, \".\") ' First . from end of string\nIf Dot% <> 0 Then\n Ext = Mid$(Full, Dot%, 3)\nElse\n Ext = \"\"\nEnd If\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| [
{
"answer_id": 291759,
"author": "Kamil Kisiel",
"author_id": 15061,
"author_profile": "https://Stackoverflow.com/users/15061",
"pm_score": 5,
"selected": true,
"text": "os.stat() file.readlines([sizehint])"
},
{
"answer_id": 291838,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 2,
"selected": false,
"text": "wc split bash split -dl$((`wc -l 'filename'|sed 's/ .*$//'` / 3 + 1)) filename filename-chunk.\n filename-chunk.00 filename-chunk.02"
},
{
"answer_id": 292848,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": -1,
"selected": false,
"text": "lines = 0\nfor l in open(filename): lines += 1\n"
},
{
"answer_id": 294384,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "def Split(inputFile,numParts,outputName):\n fileSize=os.stat(inputFile).st_size\n parts=FileSizeParts(fileSize,numParts)\n openInputFile = open(inputFile, 'r')\n outPart=1\n for part in parts:\n if openInputFile.tell()<fileSize:\n fullOutputName=outputName+os.extsep+str(outPart)\n outPart+=1\n openOutputFile=open(fullOutputName,'w')\n openOutputFile.writelines(openInputFile.readlines(part))\n openOutputFile.close()\n openInputFile.close()\n return outPart-1\n"
},
{
"answer_id": 2203848,
"author": "Joe Koberg",
"author_id": 76310,
"author_profile": "https://Stackoverflow.com/users/76310",
"pm_score": 3,
"selected": false,
"text": "def getSomeChunk(filename, start, len):\n fobj = open(filename, 'r+b')\n m = mmap.mmap(fobj.fileno(), 0)\n return m[start:start+len]\n"
},
{
"answer_id": 2204075,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 3,
"selected": false,
"text": "import itertools\n\ndef slicefile(filename, start, end):\n lines = open(filename)\n return itertools.islice(lines, start, end)\n\nout = open(\"/blah.txt\", \"w\")\nfor line in slicefile(\"/python27/readme.txt\", 10, 15):\n out.write(line)\n"
},
{
"answer_id": 10599406,
"author": "Alex L",
"author_id": 1129194,
"author_profile": "https://Stackoverflow.com/users/1129194",
"pm_score": 3,
"selected": false,
"text": ">>> import logging.handlers\n>>> log = logging.getLogger()\n>>> fh = logging.handlers.RotatingFileHandler(\"D://filename.txt\", \n maxBytes=2**20*100, backupCount=100) \n# 100 MB each, up to a maximum of 100 files\n>>> log.addHandler(fh)\n>>> log.setLevel(logging.INFO)\n>>> f = open(\"D://biglog.txt\")\n>>> while True:\n... log.info(f.readline().strip())\n RotatingFileHandler"
},
{
"answer_id": 20335874,
"author": "Ryan",
"author_id": 3058664,
"author_profile": "https://Stackoverflow.com/users/3058664",
"pm_score": 0,
"selected": false,
"text": "import os\n\nfil = \"inputfile\"\noutfil = \"outputfile\"\n\nf = open(fil,'r')\n\nnumbits = 1000000000\n\nfor i in range(0,os.stat(fil).st_size/numbits+1):\n o = open(outfil+str(i),'w')\n segment = f.readlines(numbits)\n for c in range(0,len(segment)):\n o.write(segment[c]+\"\\n\")\n o.close()\n"
},
{
"answer_id": 23847737,
"author": "Ron Smith",
"author_id": 2271803,
"author_profile": "https://Stackoverflow.com/users/2271803",
"pm_score": 0,
"selected": false,
"text": "# user input FileNames and LinesPerFile\nFileCount = 1\nFileNames = []\nwhile True:\n FileName = raw_input('File Name ' + str(FileCount) + ' (enter \"Done\" after last File):')\n FileCount = FileCount + 1\n if FileName == 'Done':\n break\n else:\n FileNames.append(FileName)\nLinesPerFile = raw_input('Lines Per File:')\nLinesPerFile = int(LinesPerFile)\n\nfor FileName in FileNames:\n File = open(FileName)\n\n # get Header row\n for Line in File:\n Header = Line\n break\n\n FileCount = 0\n Linecount = 1\n for Line in File:\n\n #skip Header in File\n if Line == Header:\n continue\n\n #create NewFile with Header every [LinesPerFile] Lines\n if Linecount % LinesPerFile == 1:\n FileCount = FileCount + 1\n NewFileName = FileName[:FileName.find('.')] + '-Part' + str(FileCount) + FileName[FileName.find('.'):]\n NewFile = open(NewFileName,'w')\n NewFile.write(Header)\n\n NewFile.write(Line)\n Linecount = Linecount + 1\n\n NewFile.close()\n"
},
{
"answer_id": 27641636,
"author": "inspectorG4dget",
"author_id": 198633,
"author_profile": "https://Stackoverflow.com/users/198633",
"pm_score": 3,
"selected": false,
"text": "itertools.islice def splitfile(infilepath, chunksize):\n fname, ext = infilepath.rsplit('.',1)\n i = 0\n written = False\n with open(infilepath) as infile:\n while True:\n outfilepath = \"{}{}.{}\".format(fname, i, ext)\n with open(outfilepath, 'w') as outfile:\n for line in (infile.readline() for _ in range(chunksize)):\n outfile.write(line)\n written = bool(line)\n if not written:\n break\n i += 1\n"
},
{
"answer_id": 33151466,
"author": "Mudit Verma",
"author_id": 4210571,
"author_profile": "https://Stackoverflow.com/users/4210571",
"pm_score": 2,
"selected": false,
"text": "import os\nimport sys\n\ndef getfilesize(filename):\n with open(filename,\"rb\") as fr:\n fr.seek(0,2) # move to end of the file\n size=fr.tell()\n print(\"getfilesize: size: %s\" % size)\n return fr.tell()\n\ndef splitfile(filename, splitsize):\n # Open original file in read only mode\n if not os.path.isfile(filename):\n print(\"No such file as: \\\"%s\\\"\" % filename)\n return\n\n filesize=getfilesize(filename)\n with open(filename,\"rb\") as fr:\n counter=1\n orginalfilename = filename.split(\".\")\n readlimit = 5000 #read 5kb at a time\n n_splits = filesize//splitsize\n print(\"splitfile: No of splits required: %s\" % str(n_splits))\n for i in range(n_splits+1):\n chunks_count = int(splitsize)//int(readlimit)\n data_5kb = fr.read(readlimit) # read\n # Create split files\n print(\"chunks_count: %d\" % chunks_count)\n with open(orginalfilename[0]+\"_{id}.\".format(id=str(counter))+orginalfilename[1],\"ab\") as fw:\n fw.seek(0) \n fw.truncate()# truncate original if present\n while data_5kb: \n fw.write(data_5kb)\n if chunks_count:\n chunks_count-=1\n data_5kb = fr.read(readlimit)\n else: break \n counter+=1 \n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3: print(\"Filename or splitsize not provided: Usage: filesplit.py filename splitsizeinkb \")\n else:\n filesize = int(sys.argv[2]) * 1000 #make into kb\n filename = sys.argv[1]\n splitfile(filename, filesize)\n"
},
{
"answer_id": 46432560,
"author": "radtek",
"author_id": 2023392,
"author_profile": "https://Stackoverflow.com/users/2023392",
"pm_score": 2,
"selected": false,
"text": "subprocess \"\"\"\nSplits the file into the same directory and\ndeletes the original file\n\"\"\"\n\nimport subprocess\nimport sys\nimport os\n\nSPLIT_FILE_CHUNK_SIZE = '5000'\nSPLIT_PREFIX_LENGTH = '2' # subprocess expects a string, i.e. 2 = aa, ab, ac etc..\n\nif __name__ == \"__main__\":\n\n file_path = sys.argv[1]\n # i.e. split -a 2 -l 5000 t/some_file.txt ~/tmp/t/\n subprocess.call([\"split\", \"-a\", SPLIT_PREFIX_LENGTH, \"-l\", SPLIT_FILE_CHUNK_SIZE, file_path,\n os.path.dirname(file_path) + '/'])\n\n # Remove the original file once done splitting\n try:\n os.remove(file_path)\n except OSError:\n pass\n import os\nfs_result = os.system(\"python file_splitter.py {}\".format(local_file_path))\n subprocess subprocess os.system CHUNK_SIZE = 5000\n\ndef yield_csv_rows(reader, chunk_size):\n \"\"\"\n Opens file to ingest, reads each line to return list of rows\n Expects the header is already removed\n Replacement for ingest_csv\n :param reader: dictReader\n :param chunk_size: int, chunk size\n \"\"\"\n chunk = []\n for i, row in enumerate(reader):\n if i % chunk_size == 0 and i > 0:\n yield chunk\n del chunk[:]\n chunk.append(row)\n yield chunk\n\nwith open(local_file_path, 'rb') as f:\n f.readline().strip().replace('\"', '')\n reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='\"')\n chunks = yield_csv_rows(reader, CHUNK_SIZE)\n for chunk in chunks:\n if not chunk:\n break\n # Do something with your chunk here\n readlines() \"\"\"\nSimple example using readlines()\nwhere the 'file' is generated via:\nseq 10000 > file\n\"\"\"\nCHUNK_SIZE = 5\n\n\ndef yield_rows(reader, chunk_size):\n \"\"\"\n Yield row chunks\n \"\"\"\n chunk = []\n for i, row in enumerate(reader):\n if i % chunk_size == 0 and i > 0:\n yield chunk\n del chunk[:]\n chunk.append(row)\n yield chunk\n\n\ndef batch_operation(data):\n for item in data:\n print(item)\n\n\nwith open('file', 'r') as f:\n chunks = yield_rows(f.readlines(), CHUNK_SIZE)\n for _chunk in chunks:\n batch_operation(_chunk)\n"
},
{
"answer_id": 64169380,
"author": "Ajith",
"author_id": 10990603,
"author_profile": "https://Stackoverflow.com/users/10990603",
"pm_score": 1,
"selected": false,
"text": "for idx,val in enumerate(get_chunk(content, CHUNK_SIZE)):\n data=val\n index=idx\n\ndef get_chunk(content,size):\n for i in range(0,len(content),size):\n yield content[i:i+size]\n"
},
{
"answer_id": 72335598,
"author": "Manoj Kumar Singh",
"author_id": 7347911,
"author_profile": "https://Stackoverflow.com/users/7347911",
"pm_score": 0,
"selected": false,
"text": "import subprocess\nsubprocess.run('split -l number_of_lines file_path', shell = True)\n subprocess.run('split -l 50000 /home/data', shell = True)\n ! wc -l file_path\n ! wc -l /home/data\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4834/"
] |
291,757 | <p>I have a linux dev server I watch, and lately its chugging at some points so I'd like to keep a better eye on it. I used to use Gkrellm, but its been a pain to try get Gkrellm to build on my Mac. </p>
<p>Besides servering X remotely (which would not be optimal), I guess i'm looking for alternatives to Gkrellm.</p>
<p>I would like a program that will let me watch the I/O CPU, Memory, processes, etc of a remote server running Linux. I am on a Mac.</p>
| [
{
"answer_id": 1684523,
"author": "Kevin Campion",
"author_id": 83833,
"author_profile": "https://Stackoverflow.com/users/83833",
"pm_score": 1,
"selected": false,
"text": "# sudo port install gkrellm\n # sudo port clean xorg-xproto\n# sudo port install xorg-xproto\n # sudo port install gkrellm\n # sudo port clean gtk-doc\n# sudo port install gtk-doc\n # sudo port install gkrellm\n # gkrellm\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,761 | <p>Here's my problem: I have to call a web service with a secure header from a classic ASP page that returns a complex data type. For various reasons concerning a 3rd party tool it has to be classic ASP. We decided that I should create an external dll to do this - which I did (in c#) so it returns a dataset (Something ASP can understand). However now I need to expose that function to the ASP page. Because this is classic ASP I think the only straightforward way to do this is to expose this class library as a COM object. I need to know the down and dirty easiest way to accomplish this task. What do I have to do to my dll?<br><br>
I have never created a COM object before only used. Somebody said my class has to be static and I can't have a constructor. Is this true? Can someone layout the steps for me?</p>
<p>HELP! (o:</p>
<p>Edit: This specific problem is now solved however as Robert Rossney noted I can't do anything with the DataSet in classic ASP. This has led me to post a second question <a href="https://stackoverflow.com/questions/301045/problem-implementing-xmltextwriter-in-new-xmlrecordsetwriter-for-streams">here</a> regarding implementing XmlTextWriter - Robert if you see this I think you could really help! </p>
| [
{
"answer_id": 292065,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Data;\nusing System.Runtime.InteropServices;\n\nnamespace COMTest\n{\n [Guid(\"AC4C4347-27EA-4735-B9F2-CF672B4CBB4A\")]\n [ComVisible(true)]\n public interface ICOMTest\n {\n [ComVisible(true)]\n DataSet GetDataSet();\n }\n\n [Guid(\"CB733AB1-9DFC-437d-A769-203DD7282A8C\")]\n [ProgId(\"COMTest.COMTest\")]\n [ComVisible(true)]\n public class COMTest : ICOMTest\n {\n public DataSet GetDataSet()\n {\n DataSet ds = new DataSet(\"COMTest\");\n return ds;\n }\n }\n bin\\Debug <%\nDim o\nSet o = Server.CreateObject(\"COMTest.COMTest\")\nResponse.Write(\"Server.CreateObject worked.\")\nResponse.Write(\"<br/>\")\nDim ds\nSet ds = o.GetDataSet()\nIf Not ds is Nothing Then\n Response.Write(\"o.GetDataSet returned an object. Can we use it?\")\n Response.Write(\"<br/>\")\n Response.Write(\"We have a DataSet, and its DataSetName is: \")\n Response.Write(ds.DataSetName)\nEnd If\n%>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29650/"
] |
291,774 | <p>What is the regex for a alpha numeric word, at least 6 characters long (but at most 50).</p>
| [
{
"answer_id": 291783,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "/[a-zA-Z0-9]{6,50}/\n"
},
{
"answer_id": 291785,
"author": "chroder",
"author_id": 18802,
"author_profile": "https://Stackoverflow.com/users/18802",
"pm_score": 4,
"selected": false,
"text": "/[a-zA-Z0-9]{6,50}/\n /\\b[a-zA-Z0-9]{6,50}\\b/\n"
},
{
"answer_id": 291846,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 3,
"selected": false,
"text": "\\b\\w{6,50}\\b\n \\w {6,50} \\b ^\\w{6,50}$\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,780 | <p>Hey, I'm really new to Haskell and have been using more classic programming languages my whole life. I have no idea what is going on here. I'm trying to make a very simple Viterbi algorithm implementation, but for only two states (honest and dishonest casino)</p>
<p>I have a problem where I want to address my array, but I don't think I'm getting types right. That or I'm making a new array each time I try to address it - equally stupid. Look at myArray, te infix, and dynamicProgram especially, PLEASE. Pretty pretty please </p>
<pre> Code
<code>
import Array
import Char
trans :: Int -> Int -> Double -> Double -> Double
trans from x trans11 trans21 =
if (from == 1) && (x == 1)
then trans11
else if (from == 1) && (x == 2)
then (1-trans11)
else if (from == 2) && (x == 1)
then trans21
else (1-trans21)
em :: Char -> [Double] -> Double
em c list = list!! a
where a = digitToInt c
intToChar :: Int -> Char
intToChar n | n == 1 = '1'
| n == 2 = '2'
casino :: Char -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> Double
casino seqchar 1 y em1 em2 t1 t2= 0.5 * (em seqchar em1)
casino seqchar 2 y em1 em2 t1 t2= 0.5 * (em seqchar em2)
casino seqchar x y em1 em2 t1 t2= maximum[ (1 @@ y-1)*(em seqchar em1)*(trans 1 x t1 t2),(2 @@ y-1)*(em seqchar em2)*(trans 2 x t1 t2) ]
dynamicProgram :: [Char] -> (Char -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> Double) -> [Double] -> [Double] -> Double -> Double -> (Array a b)
dynamicProgram string score list1 list2 trans11 trans21 = myArray 1 len
[score (string!!y) x y list1 list2 trans11 trans21 | x Int -> [Double] -> Array a b
myArray startIndex endIndex values = listArray (startIndex,startIndex) (endIndex,endIndex) values
traceback :: [Char] -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> [Char]
traceback s 1 0 em1 em2 t1 t2 = []
traceback s 2 0 em1 em2 t1 t2 = []
traceback s x y em1 em2 t1 t2 | x@@y == (1 @@ y-1)*(em (s!!y) em1)*(trans 1 x t1 t2) = '1' : traceback s 1 (y-1) em1 em2 t1 t2
| x@@y == (2 @@ y-1)*(em (s!!y) em1)*(trans 2 x t1 t2) = '2' : traceback s 2 (y-1) em1 em2 t1 t2
answer :: [Char] -> [Double] -> [Double] -> Double -> Double -> [Char]
answer string list1 list2 t1 t2 = reverse $ maxC : traceback string max end list1 list2 t1 t2 $ dynamicProgram casino string list1 list2 t1 t2
where
end = (length string) + 1
max | maximum (1@@end) (2@@end) == 1@@end = 1
| maximum (1@@end) (2@@end) == 2@@end = 2
maxC = intToChar max
infix 5 @@
(@@) i j = myArray ! (i, j)
main = do
putStrLn "What is the sequence to test?"
seq state 1 transmission probability?"
trp1 state 2 transmission probability is " ++ (1-trp1)
putStrLn "What is the state 2 -> state 1 transmission probability?"
trp2 state 2 transmission probability is " ++ (1-trp2)
putStrLn "I assume that the prob of starting in either state is 1/2. Go!"
answer seq st1 st2 trp1 trp2
</code></pre>
| [
{
"answer_id": 291836,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": false,
"text": "foo.hs:34:71:\n Couldn't match expected type `[e]' against inferred type `(a, b)'\n In the second argument of `listArray', namely\n `(endIndex, endIndex)'\n In the expression:\n listArray (startIndex, startIndex) (endIndex, endIndex) values\n In the definition of `myArray':\n myArray startIndex endIndex values\n = listArray (startIndex, startIndex) (endIndex, endIndex) values\n listArray :: (Ix i) => (i, i) -> [e] -> Array i e\n -- Defined in GHC.Arr\n listArray (startIndex, endIndex) values\n Array a b Array Int Double foo.hs:43:44:\n Couldn't match expected type `a -> b'\n against inferred type `[Char]'\n In the first argument of `($)', namely\n `maxC : (traceback string max end list1 list2 t1 t2)'\n In the second argument of `($)', namely\n `(maxC : (traceback string max end list1 list2 t1 t2))\n $ (dynamicProgram casino string list1 list2 t1 t2)'\n In the expression:\n reverse\n $ ((maxC : (traceback string max end list1 list2 t1 t2))\n $ (dynamicProgram casino string list1 list2 t1 t2))\n $ $ foo.hs:51:11:\n Couldn't match expected type `Array i e'\n against inferred type `Int -> Int -> [Double] -> Array a b'\n In the first argument of `(!)', namely `myArray'\n In the expression: myArray ! (i, j)\n In the definition of `@@': @@ i j = myArray ! (i, j)\n myArray myArray @@ foo.hs:63:4:\n Couldn't match expected type `[a]' against inferred type `IO ()'\n In the first argument of `(++)', namely\n `putStrLn\n \"I assume that the state 1 -> state 2 transmission probability is \"'\n In the expression:\n (putStrLn\n \"I assume that the state 1 -> state 2 transmission probability is \")\n ++\n (1 - trp1)\n In a 'do' expression:\n (putStrLn\n \"I assume that the state 1 -> state 2 transmission probability is \")\n ++\n (1 - trp1)\n $ listArray ((startIndex, startIndex), (endIndex, endIndex)) values\n Array (Int, Int) Double"
},
{
"answer_id": 321226,
"author": "Chris Eidhof",
"author_id": 36929,
"author_profile": "https://Stackoverflow.com/users/36929",
"pm_score": 1,
"selected": false,
"text": "trans :: Int -> Int -> Double -> Double -> Double\ntrans 1 1 trans11 trans21 = trans11\ntrans 1 2 trans11 trans21 = 1-trans11\ntrans 2 1 trans11 trans21 = trans21\ntrans _ _ trans11 trans21 = 1-trans21\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37840/"
] |
291,792 | <p>I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit <strong>Select All</strong> it doesn't select all. I can right click and click <strong>Select All</strong> but <kbd>CTRL</kbd> + <kbd>A</kbd> doesn't do anything. Why?</p>
<pre><code>wnd = CreateWindow("EDIT", 0,
WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
x, y, w, h,
parentWnd,
NULL, NULL, NULL);
</code></pre>
| [
{
"answer_id": 291798,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 2,
"selected": false,
"text": " protected override void OnKeyDown(KeyEventArgs e)\n {\n // Ctrl-A does a Select All in the editor window\n if (e.Control && (e.KeyCode == Keys.A))\n {\n this.SelectAll();\n e.Handled = true;\n }\n }\n"
},
{
"answer_id": 291949,
"author": "Harold Bamford",
"author_id": 10574,
"author_profile": "https://Stackoverflow.com/users/10574",
"pm_score": 3,
"selected": true,
"text": "WM_CHAR WM_KEYDOWN Translate()"
},
{
"answer_id": 294780,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 0,
"selected": false,
"text": "SelectAll"
},
{
"answer_id": 315720,
"author": "Phil Hord",
"author_id": 33342,
"author_profile": "https://Stackoverflow.com/users/33342",
"pm_score": 3,
"selected": false,
"text": "static BOOL IsEdit( CWnd *pWnd ) \n{\n if ( ! pWnd ) return FALSE ;\n HWND hWnd = pWnd->GetSafeHwnd();\n if (hWnd == NULL)\n return FALSE;\n\n TCHAR szClassName[6];\n return ::GetClassName(hWnd, szClassName, 6) &&\n _tcsicmp(szClassName, _T(\"Edit\")) == 0;\n}\n\nBOOL LogWindowDlg::PreTranslateMessage(MSG* pMsg) \n{\n if(pMsg->message==WM_KEYDOWN)\n {\n if ( pMsg->wParam=='A' && GetKeyState(VK_CONTROL)<0 )\n {\n // User pressed Ctrl-A. Let's select-all\n CWnd * wnd = GetFocus() ;\n if ( wnd && IsEdit(wnd) )\n ((CEdit *)wnd)->SetSel(0,-1) ;\n }\n } \n return CDialog::PreTranslateMessage(pMsg);\n}\n"
},
{
"answer_id": 15823410,
"author": "sandun dhammika",
"author_id": 442399,
"author_profile": "https://Stackoverflow.com/users/442399",
"pm_score": 2,
"selected": false,
"text": "SendMessage(hwndEdit,EM_SETSEL,0,-1);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,793 | <p>Is there a way to recursively add all "non added" files to SVN?</p>
<p>I want to do something like</p>
<pre><code>svn add trunk/
</code></pre>
<p>to add all new files, without getting:</p>
<pre><code>svn: warning: 'trunk' is already under version control
</code></pre>
<p>If this is not possible, is there a way to get a list of all files that are not under version control in the directory?</p>
<p>Note that I am only interested in using the command line. </p>
| [
{
"answer_id": 291800,
"author": "Jonas Kongslund",
"author_id": 37548,
"author_profile": "https://Stackoverflow.com/users/37548",
"pm_score": 5,
"selected": true,
"text": "svn add * --force\n"
},
{
"answer_id": 291854,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 3,
"selected": false,
"text": "svn status | awk '/\\?/ {print $2}' | xargs svn add"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
291,813 | <p>What is the recommended way to embed PDF in HTML?</p>
<ul>
<li>iFrame? </li>
<li>Object? </li>
<li>Embed?</li>
</ul>
<p>What does Adobe say itself about it?</p>
<p>In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.</p>
| [
{
"answer_id": 293250,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 2,
"selected": false,
"text": "src"
},
{
"answer_id": 2199443,
"author": "amIT",
"author_id": 266155,
"author_profile": "https://Stackoverflow.com/users/266155",
"pm_score": 5,
"selected": false,
"text": "<!-- Embed PDF File -->\n<object src=\"YourFile.pdf\" type=\"application/pdf\" title=\"SamplePdf\" width=\"500\" height=\"720\">\n <a href=\"YourFile.pdf\">shree</a> \n</object>\n"
},
{
"answer_id": 2417237,
"author": "Lukasz Korzybski",
"author_id": 210356,
"author_profile": "https://Stackoverflow.com/users/210356",
"pm_score": 9,
"selected": false,
"text": "<iframe src=\"https://docs.google.com/gview?url=http://example.com/mypdf.pdf&embedded=true\" style=\"width:718px; height:700px;\" frameborder=\"0\"></iframe>\n"
},
{
"answer_id": 5171817,
"author": "Gayle",
"author_id": 606057,
"author_profile": "https://Stackoverflow.com/users/606057",
"pm_score": 7,
"selected": false,
"text": "<object width=\"400\" height=\"500\" type=\"application/pdf\" data=\"/my_pdf.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0\">\n <p>Insert your error message here, if the PDF cannot be displayed.</p>\n</object>\n"
},
{
"answer_id": 7044015,
"author": "Batfan",
"author_id": 163906,
"author_profile": "https://Stackoverflow.com/users/163906",
"pm_score": 9,
"selected": false,
"text": "<embed src=\"http://example.com/the.pdf\" width=\"500\" height=\"375\" \n type=\"application/pdf\">\n <embed src=\"https://drive.google.com/viewerng/\nviewer?embedded=true&url=http://example.com/the.pdf\" width=\"500\" height=\"375\">\n"
},
{
"answer_id": 8404731,
"author": "Dan Mantyla",
"author_id": 279093,
"author_profile": "https://Stackoverflow.com/users/279093",
"pm_score": 5,
"selected": false,
"text": "<?php\n $dir = '/absolute/path/to/my/directory/';\n $name = 'myPDF.pdf';\n exec(\"/bin/convert $dir$name $dir$name.png\");\n print '<img src=\"$dir$name.png\" />';\n?>\n"
},
{
"answer_id": 23681394,
"author": "Suneel Kumar",
"author_id": 2301402,
"author_profile": "https://Stackoverflow.com/users/2301402",
"pm_score": 6,
"selected": false,
"text": "<object> <embed> <object data=\"http://yoursite.com/the.pdf\" type=\"application/pdf\" width=\"750px\" height=\"750px\">\n <embed src=\"http://yoursite.com/the.pdf\" type=\"application/pdf\">\n <p>This browser does not support PDFs. Please download the PDF to view it: <a href=\"http://yoursite.com/the.pdf\">Download PDF</a>.</p>\n </embed>\n</object>\n"
},
{
"answer_id": 30337875,
"author": "George Pligoropoulos",
"author_id": 720484,
"author_profile": "https://Stackoverflow.com/users/720484",
"pm_score": 2,
"selected": false,
"text": "iframe <iframe width='1000' height='800' src='http://bit.ly/1JxrtjR' frameborder='0' allowfullscreen></iframe>\n"
},
{
"answer_id": 35179913,
"author": "Daryl H",
"author_id": 2088442,
"author_profile": "https://Stackoverflow.com/users/2088442",
"pm_score": 2,
"selected": false,
"text": "<object width=\"400\" height=\"400\" data=\"helloworld.pdf\"></object>\n"
},
{
"answer_id": 39029439,
"author": "Said Bouigherdaine",
"author_id": 5006631,
"author_profile": "https://Stackoverflow.com/users/5006631",
"pm_score": 4,
"selected": false,
"text": "<div id=\"example1\"></div>\n <script src=\"/js/pdfobject.js\"></script>\n<script>PDFObject.embed(\"/pdf/sample-3pp.pdf\", \"#example1\");</script>\n <style>\n.pdfobject-container { height: 500px;}\n.pdfobject { border: 1px solid #666; }\n</style>\n"
},
{
"answer_id": 42425218,
"author": "PLA",
"author_id": 4046,
"author_profile": "https://Stackoverflow.com/users/4046",
"pm_score": 2,
"selected": false,
"text": "convert <img src='/webAppDirectory/PdfToImageServlet?pdfFile=/usr/share/cups/data/default-testpage.pdf'>"
},
{
"answer_id": 46731420,
"author": "Wynn",
"author_id": 7387551,
"author_profile": "https://Stackoverflow.com/users/7387551",
"pm_score": -1,
"selected": false,
"text": "<script>window.location='url'</script>\n"
},
{
"answer_id": 46843047,
"author": "Astrophage",
"author_id": 7302498,
"author_profile": "https://Stackoverflow.com/users/7302498",
"pm_score": 4,
"selected": false,
"text": "var transferData = getFormAsJson()\nif (isMicrosoftBrowser()) {\n // Case IE / Edge (because doesn't recoginzie Pdf-Base64 use Iframe)\n var form = document.getElementById('pdf-helper-form');\n $(\"#pdfHelperTransferData\").val(transferData);\n form.target = \"iframe-pdf-shower\";\n form.action = \"serverSideFunctonWhichWritesPdfinResponse\";\n form.submit();\n } else {\n // Case non IE use Object tag instead of iframe\n $.ajax({\n url: \"serverSideFunctonWhichRetrivesPdfAsBase64\",\n type: \"post\",\n data: { downloadHelperTransferData: transferData },\n success: function (result) {\n $(\"#object-pdf-shower\").attr(\"data\", result);\n }\n })\n }\n\n <div id=\"pdf-helper-hidden-container\" style=\"display:none\">\n <form id=\"pdf-helper-form\" method=\"post\">\n <input type=\"hidden\" name=\"pdfHelperTransferData\" id=\"pdfHelperTransferData\" />\n </form>\n</div>\n\n<div id=\"pdf-wrapper\" class=\"modal-content\">\n <iframe id=\"iframe-pdf-shower\" name=\"iframe-pdf-shower\"></iframe>\n <object id=\"object-pdf-shower\" type=\"application/pdf\"></object>\n</div>\n"
},
{
"answer_id": 50387899,
"author": "Despertaweb",
"author_id": 1997920,
"author_profile": "https://Stackoverflow.com/users/1997920",
"pm_score": 3,
"selected": false,
"text": " axios({\n url: `urltoPDFfile.pdf`,\n method: 'GET',\n headers: headers,\n responseType: 'blob'\n })\n .then((response) => {\n this.urlPdf = URL.createObjectURL(response.data)\n })\n .catch((error) => {\n console.log('ERROR ', error)\n })\n <object width='100%' height='600px' :data='urlPdf' type='application/pdf'></object>\n"
},
{
"answer_id": 51402906,
"author": "fartwhif",
"author_id": 6620171,
"author_profile": "https://Stackoverflow.com/users/6620171",
"pm_score": 2,
"selected": false,
"text": "/viewer.html?file=blob:19B579EA-5217-41C6-96E4-5D8DF5A5C70B\n"
},
{
"answer_id": 56622901,
"author": "Ahmedakhtar11",
"author_id": 9023714,
"author_profile": "https://Stackoverflow.com/users/9023714",
"pm_score": 4,
"selected": false,
"text": "<embed src=\"example.pdf\" width=\"1000\" height=\"800\" frameborder=\"0\" allowfullscreen>\n <iframe src=\"example.pdf\" style=\"width:1000px; height:800px;\" frameborder=\"0\" allowfullscreen></iframe>\n"
},
{
"answer_id": 59400309,
"author": "Pecata",
"author_id": 5833858,
"author_profile": "https://Stackoverflow.com/users/5833858",
"pm_score": 2,
"selected": false,
"text": "const pdfBase64 = //fetched from url or generated with jspdf or other library\n\n <embed\n src={pdfBase64}\n width=\"500\"\n height=\"375\"\n type=\"application/pdf\"\n ></embed>\n"
},
{
"answer_id": 63429551,
"author": "Marc Partensky",
"author_id": 9802810,
"author_profile": "https://Stackoverflow.com/users/9802810",
"pm_score": 0,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\">\n\n<div class=\"embed-responsive embed-responsive-1by1\">\n <iframe class=\"embed-responsive-item\" src=\"http://example.com/the.pdf\" type=\"application/pdf\" allowfullscreen></iframe>\n</div>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>"
},
{
"answer_id": 63461496,
"author": "Tony Bui",
"author_id": 9694174,
"author_profile": "https://Stackoverflow.com/users/9694174",
"pm_score": 0,
"selected": false,
"text": "const blob = dataURItoBlob(this.dataUrl); var temp_url = window.URL.createObjectURL(blob); const target = document.querySelector(targetID); target.innerHTML = `<iframe src='${temp_url}' type=\"application/pdf\"></iframe>"
},
{
"answer_id": 65545243,
"author": "Bob Singor",
"author_id": 275929,
"author_profile": "https://Stackoverflow.com/users/275929",
"pm_score": -1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CloudPDF Viewer</title>\n <style>\n body, html {\n height: 100%;\n margin: 0px;\n }\n </style>\n</head>\n<body style=\"height: 100%\">\n <div id=\"viewer\" style=\"width: 800px; height: 500px; margin: 80px auto;\"></div>\n <script type=\"text/javascript\" src=\"https://cloudpdf.io/viewer.min.js?version=0.1.0-beta.11\"></script>\n <script>\n document.addEventListener('DOMContentLoaded', function(){\n const config = { \n documentId: 'eee2079d-b0b6-4267-9812-b6b9eadb9c60',\n darkMode: true,\n };\n CloudPDF(config, document.getElementById('viewer')).then((instance) => {\n\n });\n });\n </script>\n </body>\n</html>\n"
},
{
"answer_id": 66074005,
"author": "raoof",
"author_id": 765629,
"author_profile": "https://Stackoverflow.com/users/765629",
"pm_score": 0,
"selected": false,
"text": "<embed src=\"data:application/pdf;base64,...\"/>\n"
},
{
"answer_id": 70740636,
"author": "NeNaD",
"author_id": 14389830,
"author_profile": "https://Stackoverflow.com/users/14389830",
"pm_score": 3,
"selected": false,
"text": "api_key file_url file_url { location: { url: \"url_of_the_pdf\" } } <div id=\"adobe-dc-view\"></div>\n\n<script src=\"https://documentcloud.adobe.com/view-sdk/main.js\"></script>\n\n<script type=\"text/javascript\">\n document.addEventListener(\"adobe_dc_view_sdk.ready\", function(){\n var adobeDCView = new AdobeDC.View({clientId: \"api_key\", divId: \"adobe-dc-view\"});\n adobeDCView.previewFile({\n content: { location: { url: \"url_of_the_pdf\" } },\n metaData: { fileName: \"file_name_to_display\" }\n }, {});\n });\n</script>\n { promise: <FILE_PROMISE> } <div id=\"adobe-dc-view\"></div>\n\n<script src=\"https://documentcloud.adobe.com/view-sdk/main.js\"></script>\n\n<script type=\"text/javascript\">\n document.addEventListener(\"adobe_dc_view_sdk.ready\", function(){\n var adobeDCView = new AdobeDC.View({clientId: \"api_key\", divId: \"adobe-dc-view\"});\n adobeDCView.previewFile({\n content: { promise: <FILE_PROMISE> }\n metaData: { fileName: \"file_name_to_display\" }\n }, {});\n });\n</script>\n"
},
{
"answer_id": 74221354,
"author": "Duc Trung Mai",
"author_id": 7569705,
"author_profile": "https://Stackoverflow.com/users/7569705",
"pm_score": 0,
"selected": false,
"text": "embed iframe"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
291,828 | <p>I wrote a function in C that converts a string to an integer and returns the integer. When I call the function I also want it to let me know if the string is not a valid number. In the past I returned -1 when this error occurred, because I didn't need to convert strings to negative numbers. But now I want it to convert strings to negative numbers, so what is the best way to report the error?</p>
<p>In case I wasn't clear about this: I don't want this function to report the error to the user, I want it to report the error to the code that called the function. ("Report" might be the wrong word to use...)</p>
<p>Here's the code:</p>
<pre><code>s32 intval(const char *string) {
bool negative = false;
u32 current_char = 0;
if (string[0] == '-') {
negative = true;
current_char = 1;
}
s32 num = 0;
while (string[current_char]) {
if (string[current_char] < '0' || string[current_char] > '9') {
// Return an error here.. but how?
}
num *= 10;
num += string[current_char] - '0';
current_char++;
}
if (negative) {
num = -num;
}
return num;
}
</code></pre>
| [
{
"answer_id": 291830,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 4,
"selected": false,
"text": "int my_function(int *ok) {\n /* whatever */\n if(ok) {\n *ok = success;\n }\n return ret_val;\n}\n int ok;\nint ret = my_function(&ok);\nif(ok) {\n /* use ret safely here */\n}\n s32 intval(const char *string, int *ok) {\n bool negative = false;\n u32 current_char = 0;\n\n if (string[0] == '-') {\n negative = true;\n current_char = 1;\n }\n\n s32 num = 0;\n while (string[current_char]) {\n if (string[current_char] < '0' || string[current_char] > '9') {\n // Return an error here.. but how?\n if(ok) { *ok = 0; }\n }\n\n num *= 10;\n num += string[current_char] - '0';\n current_char++;\n }\n\n if (negative) {\n num = -num;\n }\n if(ok) { *ok = 1; }\n return num;\n}\n\nint ok;\ns32 val = intval(\"123a\", &ok);\nif(ok) {\n printf(\"conversion successful\\n\");\n}\n"
},
{
"answer_id": 291832,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "int intval(const char *string, s32 *parsed)\n{\n *parsed = 0; // So that if we return an error, the value is well-defined\n\n // Normal code, returning error codes if necessary\n // ...\n\n *parsed = num;\n return SUCCESS; // Or whatever\n}\n"
},
{
"answer_id": 291834,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "errno.h"
},
{
"answer_id": 291861,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "INT_MAX INT_MIN GetLastError() errno On Error Goto Next atoi() intval() atoi()"
},
{
"answer_id": 292113,
"author": "Darian Miller",
"author_id": 35696,
"author_profile": "https://Stackoverflow.com/users/35696",
"pm_score": 1,
"selected": false,
"text": "Pseudo code\n MyErrStatEnum = (myUndefined, myOK, myNegativeVal, myWhatever)\n\nResultClass\n Value:Integer;\n ErrorStatus:MyErrStatEnum\n result := yourMethod(inputString)\n\nif Result.ErrorStatus = myOK then \n use Result.Value\nelse\n do something with Result.ErrorStatus\n\nfree result\n create result\nyourMethod(inputString, result)\n\nif Result.ErrorStatus = myOK then \n use Result.Value\nelse\n do something with Result.ErrorStatus\n\nfree result\n"
},
{
"answer_id": 292449,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 2,
"selected": false,
"text": "\ns32\nmy_strtos32_base10(const char *nptr, char **endptr)\n{\n long ret;\n ret = strtol(nptr, endptr, 10);\n return ret;\n}\n"
},
{
"answer_id": 296277,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "long strtol(const char * restrict str, char **restrict endptr, int base);\n"
},
{
"answer_id": 51333248,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "typedef struct {\n int value;\n int error;\n} int_error;\n\nint_error intval(const char *string);\n\n...\n\nint_error = intval(some_string);\nif (int_error.error) {\n Process_Error();\n}\n\nint only_care_about_value = intval(some_string).value;\nint only_care_about_error = intval(some_string).error;\n NULL #include <math.h>\n#include <stddef.h>\n\ndouble y = foo(x);\nif (isnan(y)) {\n Process_Error();\n}\n\nvoid *ptr = bar(x);\nif (ptr == NULL) {\n Process_Error();\n}\n _Generic error_t foo(&dest, x) dest_t foo(x, &error) _Generic error_t narrow(destination_t *, source_t) long long short long long ll = ...; \nint i;\nchar ch; \nerror = narrow(&i, ll);\n...\nerror = narrow(&ch, i);\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
291,829 | <p>I have a file with several thousand rows and several columns separated with tabs What I'd like to do is loop through each individually, Drop the columns into an array so that I can place them in another application individually, then move onto the next line. Unfortunately I got about as far as this:</p>
<pre><code>Open mytextfile.txt For Input As #FileHandle
Do While Not EOF(FileHandle)
Line Input #FileHandle, IndividualLine
StringToBreakup = IndividualLine
Loop
</code></pre>
<p>So how would I go about breaking individual line up into an array</p>
| [
{
"answer_id": 291837,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 0,
"selected": false,
"text": "Dim StringArray as Variant\n\nOpen mytextfile.txt For Input As #FileHandle\n Do While Not EOF(FileHandle)\n Line Input #FileHandle, IndividualLine\n StringToBreakup = IndividualLine\n\n StringArray = Split(StringToBreakup, CHR(9)) \n\n Process array here...\n\nLoop\n"
},
{
"answer_id": 291857,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Dim str() as String\n\nOpen mytextfile.txt For Input As #FileHandle\n Do While Not EOF(FileHandle)\n Line Input #FileHandle, IndividualLine\n str = Split(IndividualLine, vbTab)\n Debug.Print str(0) 'First array element\nLoop\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,841 | <p>For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?</p>
<pre><code>if ($("#navbar .heading").text() > "") {
$("#navbar .heading").hide();
}
</code></pre>
<p>and </p>
<pre><code>var $heading = $("#navbar .heading");
if ($heading.text() > "") {
$heading.hide();
}
</code></pre>
<p>If the selector is more complex I can imagine it's a non-trivial hit.</p>
| [
{
"answer_id": 291862,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 3,
"selected": false,
"text": "$(\"#navbar .heading:not(:empty)\").hide();\n"
},
{
"answer_id": 291923,
"author": "Neil C. Obremski",
"author_id": 9642,
"author_profile": "https://Stackoverflow.com/users/9642",
"pm_score": 5,
"selected": true,
"text": "if ((cached = $(\"#navbar .heading\")).text() > \"\") {\n cached.hide();\n}\n"
},
{
"answer_id": 293793,
"author": "JoeBloggs",
"author_id": 34097,
"author_profile": "https://Stackoverflow.com/users/34097",
"pm_score": 4,
"selected": false,
"text": "$('#someid .someclass').show();\n$('#someid').append('<div class=\"someclass\">New!</div>');\n$('#someid .someclass').hide();\n"
},
{
"answer_id": 7768279,
"author": "Aleksandr Makov",
"author_id": 898099,
"author_profile": "https://Stackoverflow.com/users/898099",
"pm_score": 4,
"selected": false,
"text": "var cache = {};\n\nfunction $$(s)\n{\n if (cache.hasOwnProperty(s))\n {\n return $(cache[s]);\n }\n\n var e = $(s);\n\n if(e.length > 0)\n {\n return $(cache[s] = e);\n }\n\n}\n $$('div').each(function(){ ... });\n console.log($$('#forms .col.r')[0] === $('#forms .col.r')[0]);\n $$"
},
{
"answer_id": 10159441,
"author": "gnarf",
"author_id": 91914,
"author_profile": "https://Stackoverflow.com/users/91914",
"pm_score": 5,
"selected": false,
"text": "$( selector ) var element = $(\"#someid\");\n\nelement.click( function() {\n\n // no need to re-select #someid since we cached it\n element.hide(); \n});\n"
},
{
"answer_id": 11584004,
"author": "Sefi Grossman",
"author_id": 1541396,
"author_profile": "https://Stackoverflow.com/users/1541396",
"pm_score": 3,
"selected": false,
"text": "function $$(a, b, c){\n var key;\n if(c){\n key = a + \",\" + b;\n if(!this.hasOwnProperty(key) || c){\n this[key] = $(a, b);\n } \n }\n else if(b){\n if(typeof b == \"boolean\"){ \n key = a; \n if(!this.hasOwnProperty(key) || b){\n this[key] = $(a);\n }\n }\n else{\n key = a + \",\" + b;\n this[key] = $(a, b); \n } \n }\n else{\n key = a;\n if(!this.hasOwnProperty(key)){\n this[key] = $(a);\n } \n }\n return this[key]; \n}\n <div class=\"test\">a</div>\n<div id=\"container\">\n <div class=\"test\">b</div>\n</div>\n\n<script>\n $$(\".test\").append(\"1\"); //default behavior\n $$(\".test\", \"#container\").append(\"2\"); //contextual \n $$(\".test\", \"#container\").append(\"3\"); //uses cache\n $$(\".test\", \"#container\", true).append(\"4\"); //forces back to the dome\n\n</script>\n"
},
{
"answer_id": 12093418,
"author": "Joschi",
"author_id": 1619990,
"author_profile": "https://Stackoverflow.com/users/1619990",
"pm_score": 2,
"selected": false,
"text": "function $$(selector) {\n return cache.hasOwnProperty(selector) \n ? cache[selector] \n : cache[selector] = $(selector); \n};\n"
},
{
"answer_id": 37420144,
"author": "jduhls",
"author_id": 603560,
"author_profile": "https://Stackoverflow.com/users/603560",
"pm_score": 1,
"selected": false,
"text": "<script src=\"https://gist.github.com/jduhls/ceb7c5fdf2ae1fd2d613e1bab160e296.js\"></script>"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
291,844 | <p>Which is faster? This:</p>
<pre><code>bool isEqual = (MyObject1 is MyObject2)
</code></pre>
<p>Or this:</p>
<pre><code>bool isEqual = ("blah" == "blah1")
</code></pre>
<p>It would be helpful to figure out which one is faster. Obviously, if you apply .ToUpper() to each side of the string comparison like programmers often do, that would require reallocating memory which affects performance. But how about if .ToUpper() is out of the equation like in the above sample?</p>
| [
{
"answer_id": 291856,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 2,
"selected": false,
"text": "string toto = \"toto\";\nstring tata = \"tata\";\n\nbool isEqual = string.Compare(toto, tata, StringComparison.InvariantCultureIgnoreCase) == 0; \n\nConsole.WriteLine(isEqual); \n"
},
{
"answer_id": 291883,
"author": "Frode Lillerud",
"author_id": 33431,
"author_profile": "https://Stackoverflow.com/users/33431",
"pm_score": 3,
"selected": false,
"text": "bool isEqual = String.Equals(\"test\", \"test\");\n bool isEqual = (\"test\" == \"test\");\n bool isEqual = \"test\".Equals(\"test\");\n"
},
{
"answer_id": 291911,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "::rimshot:: is == s \"I'm a string\" if (((object) s) == ((object) \"I'm a string\")) { ... }\n s"
},
{
"answer_id": 65524780,
"author": "MPavlak",
"author_id": 652688,
"author_profile": "https://Stackoverflow.com/users/652688",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace ConsoleApp1\n{\n public sealed class A\n {\n public const string TypeName = \"A\";\n }\n\n public sealed class B\n {\n public const string TypeName = \"B\";\n }\n\n public sealed class C\n {\n public const string TypeName = \"C\";\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n var testlist = Enumerable.Repeat(0, 100).SelectMany(x => new object[] { new A(), new B(), new C() }).ToList();\n\n int count = 0;\n\n void checkTypeName()\n {\n foreach (var item in testlist)\n {\n switch (item)\n {\n case A.TypeName:\n count++;\n break;\n case B.TypeName:\n count++;\n break;\n case C.TypeName:\n count++;\n break;\n default:\n break;\n }\n }\n }\n\n void checkType()\n {\n foreach (var item in testlist)\n {\n switch (item)\n {\n case A _:\n count++;\n break;\n case B _:\n count++;\n break;\n case C _:\n count++;\n break;\n default:\n break;\n }\n }\n }\n\n Stopwatch sw = Stopwatch.StartNew();\n for (int i = 0; i < 100000; i++)\n {\n checkTypeName();\n }\n sw.Stop();\n Console.WriteLine(sw.Elapsed);\n sw.Restart();\n for (int i = 0; i < 100000; i++)\n {\n checkType();\n }\n sw.Stop();\n Console.WriteLine(sw.Elapsed);\n }\n }\n}\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28661/"
] |
291,847 | <p>I have a very simple SOAP web service that I need to consume from a Java client. What is the easiest way to accomplish this without using any third party libraries? A requirement is that the host and port is read from the web.xml before every call to the ws.</p>
| [
{
"answer_id": 292269,
"author": "FoxyBOA",
"author_id": 19347,
"author_profile": "https://Stackoverflow.com/users/19347",
"pm_score": 5,
"selected": false,
"text": "DynamicClientFactory dcf = DynamicClientFactory.newInstance();\nClient client = dcf.createClient(\"http://admin:password@localhost:8080\"+\n \"/services/MyService?wsdl\");\nObject[] a = client.invoke(\"test\", \"\");\nSystem.out.println(a);\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\nfactory.setAddress(\"http://admin:password@localhost:8080/services/MyService\");\nfactory.setServiceClass(ITest.class);\nITest client = (ITest) factory.create();\nclient.test();\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16684/"
] |
291,848 | <p>Is it possible to programmatically either via the win32API (python) or via a command line option set the processor affinity for a process?</p>
| [
{
"answer_id": 291851,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 0,
"selected": false,
"text": "DWORD processorId = 0;\nSetThreadIdealProcessor(GetCurrentThread(),processorId);\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
291,849 | <p>What is the simplest way in VB6 to loop through all the files in a specified folder directory and get their names?</p>
| [
{
"answer_id": 291882,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 5,
"selected": true,
"text": "sFilename = Dir(sFoldername)\n\nDo While sFilename > \"\"\n\n debug.print sFilename \n sFilename = Dir()\n\nLoop\n"
},
{
"answer_id": 294811,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 3,
"selected": false,
"text": "Dim fso As New FileSystemObject\nDim fil As File\n\nFor Each fil In fso.GetFolder(\"C:\\\").Files\n Debug.Print fil.Name\nNext\n"
},
{
"answer_id": 13982325,
"author": "bigsancho",
"author_id": 1920279,
"author_profile": "https://Stackoverflow.com/users/1920279",
"pm_score": 4,
"selected": false,
"text": "Dim fso As New FileSystemObject\nDim fld As Folder\nDim fil As File\nSet fld = fso.GetFolder(\"C:\\My Folder\")\nFor Each fil In fld.Files\n Debug.Print fil.Name\nNext\nSet fil = Nothing\nSet fld = Nothing\nSet fso = Nothing\n"
},
{
"answer_id": 34104513,
"author": "Janardhan G",
"author_id": 4877840,
"author_profile": "https://Stackoverflow.com/users/4877840",
"pm_score": 0,
"selected": false,
"text": "Private Sub browseButton_Click()\n\nDim path As String\npath = \"C:\\My Folder\"\n\nList1.path() = path\nList1.Pattern = \"*.txt\"\nEnd Sub\n"
},
{
"answer_id": 50770431,
"author": "Codemaker",
"author_id": 7103882,
"author_profile": "https://Stackoverflow.com/users/7103882",
"pm_score": 0,
"selected": false,
"text": "Dim fso As New FileSystemObject\nDim fld As Folder\nDim file As File\nSet fld = fso.GetFolder(\"C:\\vishnu\")\nFor Each file In fld.Files\n msgbox file.Name\nNext\n"
},
{
"answer_id": 50980431,
"author": "Sajid Dewan",
"author_id": 9976282,
"author_profile": "https://Stackoverflow.com/users/9976282",
"pm_score": 2,
"selected": false,
"text": "sFilename = Dir(App.Path & \"\\Forms\\\")\nDo While sFilename > \"\"\n If (Right(sFilename, 4) = \".frm\") Then\n cbo.List(CountVal) = Left(sFilename, (Len(sFilename) - 4))\n CountVal = CountVal + 1\n End If\n\n sFilename = Dir()\nLoop\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
291,853 | <p>Doesn't an ORM usually involve doing something like a select *?</p>
<p>If I have a table, MyThing, with column A, B, C, D, etc, then there typically would be an object, MyThing with properties A, B, C, D. </p>
<p>It would be evil if that object were incompletely instantiated by a select statement that looked like this, only fetching the A, B, not the C, D:</p>
<p>select A, B from MyThing /* don't get C and D, because we don't need them */</p>
<p>but it would also be evil to always do this:</p>
<p>select A, B, C, D /* get all the columns so that we can completely instantiate the MyThing object */</p>
<p>Does ORM make an assumption that database access is so fast now you don't have to worry about it and so you can always fetch all the columns?</p>
<p>Or, do you have different MyThing objects, one for each combo of columns that might happen to be in a select statement?</p>
<p><strong>EDIT: Before you answer the question, please read Nicholas Piasecki's and Bill Karwin's answers. I guess I asked my question poorly because many misunderstood it, but Nicholas understood it 100%. Like him, I'm interested in other answers.</strong></p>
<hr>
<p>EDIT #2: Links that relate to this question:</p>
<p><a href="https://stackoverflow.com/questions/18655/why-do-we-need-entity-objects">Why do we need entity objects?</a></p>
<p><a href="http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx" rel="nofollow noreferrer">http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx</a>, especially the section "The Partial-Object Problem and the Load-Time Paradox"</p>
<p><a href="http://groups.google.com/group/comp.object/browse_thread/thread/853fca22ded31c00/99f41d57f195f48b" rel="nofollow noreferrer">http://groups.google.com/group/comp.object/browse_thread/thread/853fca22ded31c00/99f41d57f195f48b</a>?</p>
<p><a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html" rel="nofollow noreferrer">http://www.martinfowler.com/bliki/AnemicDomainModel.html</a></p>
<p><a href="http://database-programmer.blogspot.com/2008/06/why-i-do-not-use-orm.html" rel="nofollow noreferrer">http://database-programmer.blogspot.com/2008/06/why-i-do-not-use-orm.html</a></p>
| [
{
"answer_id": 291886,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 7,
"selected": true,
"text": "Brand BrandId BrandName Brand Description Brand Brand Description get string desc = brand.Description DataAccessException"
},
{
"answer_id": 291901,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": false,
"text": "SELECT * SELECT * SELECT *"
},
{
"answer_id": 291915,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 3,
"selected": false,
"text": "select * from c in data.Customers\nselect c\n from c in data.Customers\nselect new\n{\n c.FirstName,\n c.LastName,\n c.Email\n}\n from c in data.Customers\njoin o in data.Orders on c.CustomerId equals o.CustomerId\nselect new\n{\n Name = c.FirstName + \" \" + c.LastName,\n Email = c.Email,\n Date = o.DateSubmitted\n}\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
291,866 | <p>I've long toyed with the idea of some kind of auto-cleanup page that performs routine maintenence tasks and is called out of scope of the current page execution by means of calling a 1x1 pixel gif with the asp.net page as the src parameter. One thing I've never really decided on, however, is how to handle the timing of such a page's execution so that it doesn't execute with every request, maybe like.. every 5th request. or every 30 minutes or some other interval.</p>
<p>How would you consider building such a mechanism?</p>
| [
{
"answer_id": 292014,
"author": "Anjisan",
"author_id": 25304,
"author_profile": "https://Stackoverflow.com/users/25304",
"pm_score": 2,
"selected": false,
"text": "void Application_Start(object sender, EventArgs e) \n{\n // Code that runs on application startup\n Application[\"Sessions\"] = 0;\n}\n\nvoid Session_Start(object sender, EventArgs e) \n{\n // Code that runs when a new session is started\n Application.Lock();\n Application[\"Sessions\"] = (int)Application[\"Sessions\"] + 1;\n\n if ((int)Application[\"Sessions\"] % 5 == 0)\n {\n DoSomething();\n Application[\"Sessions\"] = 0;\n }\n Application.UnLock();\n}\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34942/"
] |
291,868 | <p>Is there a built in function equivalent to .NET's</p>
<pre><code>Guid.NewGuid();
</code></pre>
<p>in Cocoa?</p>
<p>My desire is to produce a string along the lines of <code>550e8400-e29b-41d4-a716-446655440000</code> which represents a unique identifier.</p>
| [
{
"answer_id": 292006,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "uuidgen"
},
{
"answer_id": 292105,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 2,
"selected": false,
"text": "[[NSProcessInfo processInfo] globallyUniqueString]"
},
{
"answer_id": 293211,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 5,
"selected": false,
"text": "+(NSString*)UUIDString {\n CFUUIDRef theUUID = CFUUIDCreate(NULL);\n CFStringRef string = CFUUIDCreateString(NULL, theUUID);\n CFRelease(theUUID);\n return [(NSString *)string autorelease];\n}\n +(CFUUIDBytes)UUIDBytes {\n CFUUIDRef theUUID = CFUUIDCreate(NULL);\n CFUUIDBytes bytes = CFUUIDGetUUIDBytes(theUUID);\n CFRelease(theUUID);\n return bytes;\n}\n"
},
{
"answer_id": 22093094,
"author": "David Elliman",
"author_id": 1456073,
"author_profile": "https://Stackoverflow.com/users/1456073",
"pm_score": 3,
"selected": false,
"text": "NSString *uuidString = [[NSUUID UUID] UUIDString];\n"
},
{
"answer_id": 65670536,
"author": "Arefe",
"author_id": 2746110,
"author_profile": "https://Stackoverflow.com/users/2746110",
"pm_score": 2,
"selected": false,
"text": "~/.bash_profile uuid alias uuid=\"uuidgen | tr '[:upper:]' '[:lower:]'\"\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
291,871 | <p>Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?</p>
<p>I.e. I want to set a timeout on blocking socket in boost asio?</p>
<p>socket.read_some(boost::asio::buffer(pData, maxSize), error_);</p>
<p>Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed.</p>
| [
{
"answer_id": 292438,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 4,
"selected": true,
"text": "setsocktopt() boost::asio Specify the receiving or sending timeouts until reporting an\n error. The argument is a struct timeval. If an input or output\n function blocks for this period of time, and data has been sent\n or received, the return value of that function will be the\n amount of data transferred; if no data has been transferred and\n the timeout has been reached then -1 is returned with errno set\n to EAGAIN or EWOULDBLOCK just as if the socket was specified to\n be non-blocking. If the timeout is set to zero (the default)\n then the operation will never timeout. Timeouts only have\n effect for system calls that perform socket I/O (e.g., read(2),\n recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for\n select(2), poll(2), epoll_wait(2), etc.\n"
},
{
"answer_id": 5735084,
"author": "Ty Hoffman",
"author_id": 714213,
"author_profile": "https://Stackoverflow.com/users/714213",
"pm_score": 3,
"selected": false,
"text": " // socket here is: boost::shared_ptr<boost::asio::ip::tcp::socket> a_socket_ptr\n\n // Set up a timed select call, so we can handle timeout cases.\n\n fd_set fileDescriptorSet;\n struct timeval timeStruct;\n\n // set the timeout to 30 seconds\n timeStruct.tv_sec = 30;\n timeStruct.tv_usec = 0;\n FD_ZERO(&fileDescriptorSet);\n\n // We'll need to get the underlying native socket for this select call, in order\n // to add a simple timeout on the read:\n\n int nativeSocket = a_socket_ptr->native();\n\n FD_SET(nativeSocket,&fileDescriptorSet);\n\n select(nativeSocket+1,&fileDescriptorSet,NULL,NULL,&timeStruct);\n\n if(!FD_ISSET(nativeSocket,&fileDescriptorSet)){ // timeout\n\n std::string sMsg(\"TIMEOUT on read client data. Client IP: \");\n\n sMsg.append(a_socket_ptr->remote_endpoint().address().to_string());\n\n throw MyException(sMsg);\n }\n\n // now we know there's something to read, so read\n boost::system::error_code error;\n size_t iBytesRead = a_socket_ptr->read_some(boost::asio::buffer(myVector), error);\n\n ...\n"
},
{
"answer_id": 46151572,
"author": "scinart",
"author_id": 1889040,
"author_profile": "https://Stackoverflow.com/users/1889040",
"pm_score": 2,
"selected": false,
"text": "io_service.run_one() run() {\n Semaphore r_sem;\n boost::system::error_code r_ec;\n boost::asio::async_read(s,buffer,\n [this, &r_ec, &r_sem](const boost::system::error_code& ec_, size_t) {\n r_ec=ec_;\n r_sem.notify();\n });\n if(!r_sem.wait_for(std::chrono::seconds(3))) // wait for 3 seconds\n {\n s.cancel();\n r_sem.wait();\n throw boost::system::system_error(boost::asio::error::try_again);\n }\n else if(r_ec)\n throw boost::system::system_error(r_ec);\n}\n Semaphore wait_for"
},
{
"answer_id": 51850018,
"author": "Pavel Verevkin",
"author_id": 8216712,
"author_profile": "https://Stackoverflow.com/users/8216712",
"pm_score": 5,
"selected": false,
"text": "socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 });\n const int timeout = 200;\n::setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof timeout);//SO_SNDTIMEO for send ops\n typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option; //somewhere in your headers to be used everywhere you need it\n//...\nsocket.set_option(rcv_timeout_option{ 200 });\n #include <future>\n#include <chrono>\n//...\nauto status = std::async(std::launch::async, [&] (){ /*your stream ops*/ })\n .wait_for(std::chrono::milliseconds{ 200 });\nswitch (status)\n {\n case std::future_status::deferred:\n //... should never happen with std::launch::async\n break;\n case std::future_status::ready:\n //...\n break;\n case std::future_status::timeout:\n //...\n break;\n }\n"
},
{
"answer_id": 60357333,
"author": "dtsull",
"author_id": 9990487,
"author_profile": "https://Stackoverflow.com/users/9990487",
"pm_score": 2,
"selected": false,
"text": "SO_RCVTIMEO SO_SNDTIMEO timeval \"sys/time.h\" int timeval int boost::asio::detail::socket_option::integer"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
291,888 | <p>I've got a stock standard ASP.NET website. Anyone can read/view any page (except the admin section) but when someone wants to contribute, they need to be logged in. Just like most contribution sites out there.</p>
<p>So, if i have my OWN login control or username/password/submit input fields, why would i want to have forms auth turned on instead of just none? what does forms auth give me, which having my own code that check my database for a user/pass and my own two input fields + a submit button, does the job perfectly? </p>
<p>(NOTE: i really dislike the asp.net membership stuff that creates all those tables and usp's in the database, so please don't suggest I use that).</p>
<p>Like, with my code, when i authenticate a user (with my own database code), i manually create my own identity, etc.</p>
<p>is all this required? what is the main purpose of this?</p>
<p>cheers!</p>
| [
{
"answer_id": 291913,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "...do your authentication against your DB or Active Directory\n\nif (Request.QueryString[\"ReturnUrl\"] != null)\n{\n FormsAuthentication.RedirectFromLoginPage(userName.Text, false);\n}\nelse\n{\n FormsAuthentication.SetAuthCookie(userName.Text, false);\n}\n <system.web>\n <authentication mode=\"Forms\">\n <forms loginUrl=\"Login.aspx\"\n protection=\"All\"\n timeout=\"30\"\n name=\"my-auth-cookie\" \n path=\"/\"\n requireSSL=\"false\"\n slidingExpiration=\"true\"\n defaultUrl=\"default.aspx\" />\n </authentication>\n</system.web>\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
291,891 | <p>I am using the dojo.io.iframe.send method to send a file to my server. I want to provide a way that the user can cancel the send once it is in progress, in case it is taking too long or the user realizes she sent the wrong file.</p>
<p>I can't figure a way to do this. I could use a timeout to terminate the send if it is taking a long time (that is, the server does not respond quickly), but that is not what I want. I want to terminate any time the user makes a gesture (such as clicking a "Cancel" button.</p>
<p>Thanks!</p>
| [
{
"answer_id": 506798,
"author": "Martijn Laarman",
"author_id": 47020,
"author_profile": "https://Stackoverflow.com/users/47020",
"pm_score": 2,
"selected": false,
"text": "window.stop() execCommand(\"Stop\") about:blank"
},
{
"answer_id": 9842399,
"author": "Bob",
"author_id": 1155246,
"author_profile": "https://Stackoverflow.com/users/1155246",
"pm_score": 2,
"selected": false,
"text": "dojo.io.iframe dojo.io.iframe dojo.io.iframe dojo.io.iframe.send() dojo.io.iframe .cancel() var dfd = dojo.io.iframe.send({...});\n var dfd2 = dojo.io.iframe.send({...}); // this send will not start until the first one completes. it is blocked internally by dojo.io.iframe.\n\n...\n onclick: function() {\n dfd.cancel();\n}\n send() .cancel() dojo.io.iframe send() dojo.io.iframe"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,893 | <p>Currently, I'm using a strategy found on many blog posts. Basically, the URL contains the page number (e.g. /Users/List/5 will give you the users on page 5 of your paged list of users). However, I'm not running into a situation where one page must list two separate paged lists. How do I go about doing this using ASP.NET MVC? Do I simply provide two url parameters (e.g. /Users/List?page1=1&page2=2)? Is there a better way by using partial views?</p>
| [
{
"answer_id": 292297,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<div id=\"list1\"><%= Html.RenderPartial (\"ListA\") %></div>\n<div id=\"list2\"><%= Html.RenderPartial (\"ListB\") %></div>\n"
},
{
"answer_id": 17887347,
"author": "DevDave",
"author_id": 896631,
"author_profile": "https://Stackoverflow.com/users/896631",
"pm_score": 1,
"selected": false,
"text": "Nuget"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
291,908 | <p>I would like to match "approximate" matches in Web.SiteMap</p>
<p>The Web.Sitemap static sitemap provider works well, except for one thing. IT'S STATIC!</p>
<p>So, if I would have to have a sitemapnode for each of the 10,000 articles on my page like so :</p>
<ul>
<li>site.com/articles/1/article-title</li>
<li>site.com/articles/2/another-article-title</li>
<li>site.com/articles/3/another-article-again</li>
<li>...</li>
<li>site.com/articles/9999/the-last-article</li>
</ul>
<p>Is there some kind of Wildcard mapping I can do with the SiteMap to match Anything under Articles?</p>
<p>Or perhaps in my Webforms Page, is there a way to Manually set the current node?</p>
<p>I've found a "bit" of help on <a href="https://web.archive.org/web/20200925074743/http://geekswithblogs.net/Patware/archive/2008/11/12/126987.aspx" rel="nofollow noreferrer">this page</a> when doing this with the ASP.Net MVC Framework, but still looking for a good solution for Webforms.</p>
<p>I think what I'm going to have to do is create a custom SiteMap Provider</p>
| [
{
"answer_id": 301744,
"author": "user39603",
"author_id": 39603,
"author_profile": "https://Stackoverflow.com/users/39603",
"pm_score": 2,
"selected": false,
"text": "<siteMapNode> <siteMapNode url=\"dynamicpage.aspx\" title=\"blah\" params=\"id\" />\n"
},
{
"answer_id": 304722,
"author": "user39603",
"author_id": 39603,
"author_profile": "https://Stackoverflow.com/users/39603",
"pm_score": 4,
"selected": true,
"text": "<siteMapNode url=\"/article.aspx\" title=\"(this will be replaced)\" param=\"id\" />\n public class DynamicSiteMapPath : SiteMapPath\n{\n protected override void InitializeItem(SiteMapNodeItem item)\n {\n if (item.ItemType != SiteMapNodeItemType.PathSeparator)\n {\n string url = item.SiteMapNode.Url;\n string param = item.SiteMapNode[\"param\"];\n\n // get parameter value\n int id = System.Web.HttpContext.Current.Request.QueryString[param];\n\n // retrieve article from database using id\n <write your own code>\n\n // override node link\n HyperLink link = new HyperLink();\n link.NavigateUrl = url + \"?\" + param + \"=\" + id.ToString();\n link.Text = <the article title from the database>;\n link.ToolTip = <the article title from the database>;\n item.Controls.Add(link);\n }\n else\n {\n // if current node is a separator, initialize as usual\n base.InitializeItem(item);\n }\n }\n}\n <mycontrols:DynamicSiteMapPath ID=\"dsmpMain\" runat=\"server\" />\n"
},
{
"answer_id": 4475572,
"author": "Graham",
"author_id": 542441,
"author_profile": "https://Stackoverflow.com/users/542441",
"pm_score": 2,
"selected": false,
"text": " namespace WebFormTools\n{\n class RouteBaseSitemapProvider : XmlSiteMapProvider\n {\n public override SiteMapNode CurrentNode\n {\n get\n {\n var node = base.CurrentNode;\n\n\n if (node == null) \n {\n // we don't have a node, see if this is from a route\n var page = HttpContext.Current.CurrentHandler as System.Web.UI.Page;\n\n if (page != null && page.RouteData != null)\n {\n // try and get the Virtual path associated with this route\n var handler = page.RouteData.RouteHandler as PageRouteHandler;\n\n if (handler != null) {\n // try and find that path instead.\n node = FindSiteMapNode(handler.VirtualPath);\n }\n }\n\n }\n\n return node;\n }\n }\n }\n}\n <siteMap defaultProvider=\"RouteBaseSitemapProvider\">\n <providers>\n <add name=\"RouteBaseSitemapProvider\" type=\"WebFormTools.RouteBaseSitemapProvider\" siteMapFile=\"Web.sitemap\" />\n </providers>\n</siteMap>\n routes.MapPageRoute(\"EvalRoutes\",\n \"Evals/{type}/New.aspx\",\n \"~/Evals/New.aspx\");\n <siteMapNode url=\"~/Evals/New.aspx\" title=\"New Eval - {type}\" description=\"\" />\n public System.Web.SiteMapNode Process(System.Web.SiteMapNode currentNode)\n {\n if (currentNode == null) return currentNode;\n\n var page = HttpContext.Current.CurrentHandler as System.Web.UI.Page;\n\n if (page != null && page.RouteData != null)\n {\n\n Dictionary<Regex, string> replacements = new Dictionary<Regex, string>();\n\n // build a list of RegEx to aid in converstion, using RegEx so I can ignore class. Technically I could also\n foreach (var key in page.RouteData.Values.Keys)\n {\n replacements.Add(new Regex(string.Format(\"\\\\{{{0}\\\\}}\", key), RegexOptions.IgnoreCase), page.RouteData.Values[key].ToString()); \n }\n\n\n // navigate up the nodes\n var activeNode = currentNode;\n while (activeNode != null)\n {\n // to the replacements\n foreach(var replacement in replacements)\n {\n activeNode.Title = replacement.Key.Replace(activeNode.Title, replacement.Value);\n }\n\n activeNode = activeNode.ParentNode;\n }\n\n }\n\n return currentNode;\n }\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
291,920 | <p>I have to include Groovy classes into existing Java apps, and include Groovy into Ant's <code>build.xml</code> file.</p>
<p>What is the best way to configure Ant's <code>build.xml</code> for it? </p>
<p>Update: Are there more specifics in combining Java and Groovy compilations? Sequence of tasks?</p>
| [
{
"answer_id": 291931,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<project name=\"groovy-build\" default=\"listSourceFiles\">\n\n<taskdef name=\"groovy\"\n classname=\"org.codehaus.groovy.ant.Groovy\"/>\n<groovy>\n ant.... // some ant groovy directives\n</groovy>\n</target>\n</project>\n"
},
{
"answer_id": 291940,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": ".groovy .java <groovyc>"
},
{
"answer_id": 18484008,
"author": "Ondrej Kvasnovsky",
"author_id": 931428,
"author_profile": "https://Stackoverflow.com/users/931428",
"pm_score": 0,
"selected": false,
"text": "<groovyc srcdir=\"${testSourceDirectory}\" destdir=\"${testClassesDirectory}\">\n <classpath>\n <pathelement path=\"${mainClassesDirectory}\"/>\n <pathelement path=\"${testClassesDirectory}\"/>\n <path refid=\"testPath\"/>\n </classpath>\n <javac source=\"1.4\" target=\"1.4\" debug=\"on\" />\n</groovyc>\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33917/"
] |
291,922 | <p>I have a nested function to show/hide paragraphs news-ticker-style.</p>
<p>The problem is that when the loop starts over (line 4), the opacity effects stop working correctly so the paragraphs appear abruptly. </p>
<p>Any jquery masters know about this? Am I making this too hard?</p>
<pre><code>$('#special-ticker p').hide();
var a=0;
function outer() {
function inner() {
if(a===$('#special-ticker p').length) { a = 0; }
$('#special-ticker p').
eq(a).
fadeIn(800, function(){
$(this).animate({opacity:100},10000,null,function(){
$(this).hide(800,function(){
a++;
outer();
});
});
});
}
return inner();
}
$(function(){
outer();
});
</code></pre>
| [
{
"answer_id": 292020,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "$(this).animate({opacity:100},10000,null,function(){\n//...\n $(this).animate({ opacity : 1 }, 10000, null, function() {\n"
},
{
"answer_id": 292028,
"author": "Andy",
"author_id": 26693,
"author_profile": "https://Stackoverflow.com/users/26693",
"pm_score": 1,
"selected": false,
"text": "\n newsticker = function (selector) {\n $(selector).hide();\n var i = $(selector).length - 1;\n var toggle = function() {\n $(selector).eq(i).fadeOut(\"slow\", function() {\n i = ++i % $(selector).length;\n $(selector).eq(i).fadeIn(\"slow\", function() {\n setTimeout(toggle, 1000)\n });\n\n });\n }; \n toggle();\n };\n \n new newsticker(\"#special-ticker p\");\n"
},
{
"answer_id": 293295,
"author": "Jason Moore",
"author_id": 18158,
"author_profile": "https://Stackoverflow.com/users/18158",
"pm_score": 1,
"selected": false,
"text": "<style type=\"text/css\" media=\"screen\">\n.hidden { display: none; }\n</style>\n\n<p>Show me</p>\n<p class=\"big hidden\">Use javascript to show me later.</p>\n"
},
{
"answer_id": 294121,
"author": "Jason Moore",
"author_id": 18158,
"author_profile": "https://Stackoverflow.com/users/18158",
"pm_score": 1,
"selected": false,
"text": "var jS = $('#special-ticker p');\n// jS.hide(); // not needed if css hides elements initially\nvar i = 0;\n\nfunction do_ticker() {\n jS.eq(i).fadeIn(800, function() {\n var me = $(this); \n setTimeout(function() { me.hide(800, \n function() { \n i = ++i % jS.length;\n do_ticker();\n });\n },1000); // setTimeout\n });\n};\ndo_ticker();\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33822/"
] |
291,927 | <p>I have a Canvas in a Flex application which has items inside it that cover only about 50% of the area of the main canvas.</p>
<p>i want the canvas to respond to <code>rollOver</code> events for the full area, and not just the area that is covered by the items inside.</p>
<p>I have been setting the following attributes to achieve this :</p>
<pre><code><mx:Canvas backgroundColor="white"
backgroundAlpha=".01"
rollOver="rollOver(event)">...
</code></pre>
<p>This causes the entire canvas to respond to rollOver events. It works great - I'm just not happy with it and figure there must be a better way to achieve it. </p>
<p>Is there a way to force mouse events to act on the entire area of a UIComponent?</p>
| [
{
"answer_id": 291959,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": -1,
"selected": false,
"text": "\n\nimport flash.event.MouseEvent;\n...\ncanvas.addEventListener(MouseEvent.ROLL_OVER,function(event:MouseEvent):void {\n ...\n});\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
291,938 | <p>i did this in msvc 2005.</p>
<pre><code>typedef void (*cleanup_t)();
void func(cleanup_t clean)
{
cleanup_t();
}
</code></pre>
<p>Why does this compile? and not give me a warning? ok, it gave me a unreferenced formal parameter warning but originally i did this when clean was in a class no there was no unreferenced formal parameter when this code gave me problems.</p>
<p>What is cleanup_t(); really doing and what is the point? now for laughs i tried int() and that worked also.</p>
| [
{
"answer_id": 291952,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "1 + 2;\n cleanup_t template <class T>\nclass foo\n{\n T myT;\n\n public:\n\n foo() {\n myT = T();\n };\n};\n\ntypedef void (*cleanup_t)();\n\n\nclass bar\n{\n};\n\n\nint not_quite_a_cleanup_t_func()\n{\n return 1;\n}\n\n\nint main()\n{\n foo<int> intFoo;\n foo<cleanup_t> cleanup_t_foo;\n foo<bar> barFoo;\n\n // here I'm going to harp on one of the things I don't like about C++:\n //\n // That so many things that look like function calls are not or that\n // the parens cause subtle behavior changes.\n //\n // I believe this is the reason this question was posted to \n // stackoverflow, so it's not too far off topic.\n // \n // Many of these things exist because of backwards compatibility with C or\n // because they wanted to fit in new features without adding keywords or\n // new reserved tokens or making the parser even more complex than it already\n // is. So there are probably good rationales for them.\n //\n // But I find it confusing more often than not, and the fact that there\n // might be a rationale for it doesn't mean I have to like it...\n\n cleanup_t cleanup1(); // declares a function named cleanup1 that returns a cleanup_t\n\n cleanup_t cleanup2 = cleanup_t(); // cleanup2 is a variable of type cleanup_t that \n // is default initialized\n\n cleanup_t* cleanup3 = new cleanup_t; // cleanup3 is a pointer to type cleanup_t that \n // is initialized to point to memory that is \n // *not* initialized\n\n cleanup_t* cleanup4 = new cleanup_t(); // cleanup4 is a pointer to type cleanup_t that\n // is initialized to point to memory that *is*\n // initialized (using default intialization)\n\n cleanup2 = cleanup_t( not_quite_a_cleanup_t_func); // explicit type conversion using functional notation\n\n cleanup_t(); // the OP's problem\n cleanup2(); // call the function pointed to by cleanup2\n (*cleanup2)(); // same thing\n\n class cleanup_class\n {\n cleanup_t cleanup5;\n\n public:\n cleanup_class() : \n cleanup5() // class member default initialization\n { };\n };\n}\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,939 | <p>while exploring jQuery I came up with the following weird script. I don't see myself doing this really however concatenating strings to achieve a variable name is not unusual in JavaScript. </p>
<p>Any feedback welcome.</p>
<pre><code>...
<script type="text/javascript">
var a = 'y';
$(document).ready(function() {
$('p[id^=' + $('p[id=x]').html() + a + "]").css('color','blue');
});
</script>
...
<p id="x">2a</p>
<p id="2ay_">mytext</p>
</code></pre>
| [
{
"answer_id": 291948,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": true,
"text": "jQuery.html()"
},
{
"answer_id": 663363,
"author": "rfunduk",
"author_id": 210,
"author_profile": "https://Stackoverflow.com/users/210",
"pm_score": 0,
"selected": false,
"text": "$"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34565/"
] |
291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to" rel="noreferrer"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| [
{
"answer_id": 291968,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 9,
"selected": true,
"text": "queryset form.rate.queryset = Rate.objects.filter(company_id=the_company.id)\n form.fields[\"rate\"].queryset = ..."
},
{
"answer_id": 1244586,
"author": "michael",
"author_id": 59592,
"author_profile": "https://Stackoverflow.com/users/59592",
"pm_score": 7,
"selected": false,
"text": "ModelForm.__init__ class ClientForm(forms.ModelForm):\n def __init__(self,company,*args,**kwargs):\n super (ClientForm,self ).__init__(*args,**kwargs) # populates the post\n self.fields['rate'].queryset = Rate.objects.filter(company=company)\n self.fields['client'].queryset = Client.objects.filter(company=company)\n\n class Meta:\n model = Client\n\ndef addclient(request, company_id):\n the_company = get_object_or_404(Company, id=company_id)\n\n if request.POST:\n form = ClientForm(the_company,request.POST) #<-- Note the extra arg\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(the_company.get_clients_url())\n else:\n form = ClientForm(the_company)\n\n return render_to_response('addclient.html', \n {'form': form, 'the_company':the_company})\n class UberClientForm(ClientForm):\n class Meta:\n model = UberClient\n\ndef view(request):\n ...\n form = UberClientForm(company)\n ...\n\n#or even extend the existing custom init\nclass PITAClient(ClientForm):\n def __init__(company, *args, **args):\n super (PITAClient,self ).__init__(company,*args,**kwargs)\n self.fields['support_staff'].queryset = User.objects.exclude(user='michael')\n"
},
{
"answer_id": 1610856,
"author": "Tim",
"author_id": 194999,
"author_profile": "https://Stackoverflow.com/users/194999",
"pm_score": 2,
"selected": false,
"text": "# models.py\nclass Company(models.Model):\n # ...\nclass Contract(models.Model):\n company = models.ForeignKey(Company)\n locations = models.ManyToManyField('Location')\nclass Location(models.Model):\n company = models.ForeignKey(Company)\n # admin.py\nclass LocationInline(admin.TabularInline):\n model = Location\nclass ContractInline(admin.TabularInline):\n model = Contract\nclass CompanyAdmin(admin.ModelAdmin):\n inlines = (ContractInline, LocationInline)\n inline_filter = dict(Location__company='self')\n"
},
{
"answer_id": 6989226,
"author": "Hassek",
"author_id": 836144,
"author_profile": "https://Stackoverflow.com/users/836144",
"pm_score": 2,
"selected": false,
"text": "formmodel.base_fields['myfield'].queryset = MyModel.objects.filter(...)\n"
},
{
"answer_id": 10159363,
"author": "teewuane",
"author_id": 495679,
"author_profile": "https://Stackoverflow.com/users/495679",
"pm_score": 5,
"selected": false,
"text": "class AddPhotoToProject(CreateView):\n \"\"\"\n a view where a user can associate a photo with a project\n \"\"\"\n model = Connection\n form_class = CreateConnectionForm\n\n\n def get_context_data(self, **kwargs):\n context = super(AddPhotoToProject, self).get_context_data(**kwargs)\n context['photo'] = self.kwargs['pk']\n context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)\n return context\n def form_valid(self, form):\n pobj = Photo.objects.get(pk=self.kwargs['pk'])\n obj = form.save(commit=False)\n obj.photo = pobj\n obj.save()\n\n return_json = {'success': True}\n\n if self.request.is_ajax():\n\n final_response = json.dumps(return_json)\n return HttpResponse(final_response)\n\n else:\n\n messages.success(self.request, 'photo was added to project!')\n return HttpResponseRedirect(reverse('MyPhotos'))\n context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)\n"
},
{
"answer_id": 15667564,
"author": "neil.millikin",
"author_id": 860124,
"author_profile": "https://Stackoverflow.com/users/860124",
"pm_score": 6,
"selected": false,
"text": "class ClientAdminForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(ClientAdminForm, self).__init__(*args, **kwargs)\n # access object through self.instance...\n self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)\n\nclass ClientAdmin(admin.ModelAdmin):\n form = ClientAdminForm\n ....\n ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶\n'''The formfield_for_foreignkey method on a ModelAdmin allows you to \n override the default formfield for a foreign keys field. For example, \n to return a subset of objects for this foreign key field based on the\n user:'''\n\nclass MyModelAdmin(admin.ModelAdmin):\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"car\":\n kwargs[\"queryset\"] = Car.objects.filter(owner=request.user)\n return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n class FrontEndAdmin(models.ModelAdmin):\n def __init__(self, model, admin_site):\n self.model = model\n self.opts = model._meta\n self.admin_site = admin_site\n super(FrontEndAdmin, self).__init__(model, admin_site)\n def get_actions(self, request):\n actions = super(FrontEndAdmin, self).get_actions(request)\n if 'delete_selected' in actions:\n del actions['delete_selected']\n return actions\n def has_delete_permission(self, request, obj=None):\n return False\n def get_queryset(self, request):\n if request.user.is_superuser:\n try:\n qs = self.model.objects.all()\n except AttributeError:\n qs = self.model._default_manager.get_queryset()\n return qs\n\n else:\n try:\n qs = self.model.objects.all()\n except AttributeError:\n qs = self.model._default_manager.get_queryset()\n\n if hasattr(self.model, ‘user’):\n return qs.filter(user=request.user)\n if hasattr(self.model, ‘porcupine’):\n return qs.filter(porcupine=request.user.porcupine)\n else:\n return qs\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if request.employee.is_superuser:\n return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n else:\n if hasattr(db_field.rel.to, 'user'):\n kwargs[\"queryset\"] = db_field.rel.to.objects.filter(user=request.user)\n if hasattr(db_field.rel.to, 'porcupine'):\n kwargs[\"queryset\"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)\n return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)\n"
},
{
"answer_id": 38988875,
"author": "F.Tamy",
"author_id": 6628397,
"author_profile": "https://Stackoverflow.com/users/6628397",
"pm_score": 1,
"selected": false,
"text": "class ChangeKeyValueForm(forms.ModelForm): \n _terminal_list = forms.ModelMultipleChoiceField( \nqueryset=Terminal.objects.all() )\n\n class Meta:\n model = ChangeKeyValue\n fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time', ] \n\nclass ChangeKeyValueAdmin(admin.ModelAdmin):\n form = ChangeKeyValueForm\n list_display = ('terminal','task_list', 'plugin','last_update_time')\n list_per_page =16\n\n def get_form(self, request, obj = None, **kwargs):\n form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)\n qs, filterargs = Terminal.get_list(request)\n form.base_fields['_terminal_list'].queryset = qs\n return form\n"
},
{
"answer_id": 66945791,
"author": "jorge4larcon",
"author_id": 14189976,
"author_profile": "https://Stackoverflow.com/users/14189976",
"pm_score": -1,
"selected": false,
"text": "__init__ class CountryAdminForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['capital'].queryset = self.instance.cities.all()\n\nclass CountryAdmin(admin.ModelAdmin):\n form = CountryAdminForm\n"
},
{
"answer_id": 70403685,
"author": "Martin CR",
"author_id": 5058026,
"author_profile": "https://Stackoverflow.com/users/5058026",
"pm_score": 0,
"selected": false,
"text": "limit_choices_to base_fields['field_name'] get_form_class() class ClientCreateView(LoginRequired, CreateView):\n model = Client\n fields = '__all__'\n \n def get_form_class(self):\n modelform = super().get_form_class()\n modelform.base_fields['rate'].limit_choices_to = {'company': self.kwargs['company']}\n return modelform\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
291,946 | <p>Is it possible to use a TabContainer inside a templated FormView like so:
</p>
<pre><code> <ItemTemplate>
<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel ID="Tab1" runat="server">
<HeaderTemplate>Tab One</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="Tab2" runat="server">
<HeaderTemplate>Tab 2</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</ItemTemplate>
<EditTemplate>
<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel ID="Tab1" runat="server">
<HeaderTemplate>Tab One</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="Tab2" runat="server">
<HeaderTemplate>Tab 2</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</EditTemplate>
</code></pre>
<p>
</p>
<p>Everything works fine for only one template view at a time; for example if ItemTemplate works then EditTemplate won't. ASP.NET will complain about duplicate bound field IDs.</p>
<p>Has anybody tried doing what I'm trying to do?</p>
<p>Thanks.- Gene</p>
<p>EDIT :</p>
<p><em>I don't think the tab containers with the same IDs is the issue here since they are both inside separate Template elements and only one Template gets rendered at a time.</em></p>
<p>UPDATE:</p>
<p><em>I didn't manage to find a solution, and I think it's not possible. So, just moved on and use unique IDs. Being lazy, I wrote some code to automate the dreaded naming process. I hope someone out there has a better answer to share. Anyway, I'm too poor to afford to put a bounty on it.</em> ;-)</p>
| [
{
"answer_id": 291989,
"author": "Bobby Borszich",
"author_id": 35585,
"author_profile": "https://Stackoverflow.com/users/35585",
"pm_score": 1,
"selected": false,
"text": "<cc1:TabContainer ID=\"TabContainer1\" runat=\"server\">\n<cc1:TabContainer ID=\"TabContainer2\" runat=\"server\">\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22556/"
] |
291,976 | <p>Having a relative path, how do I turn it into an absolute one from the location where the elisp file that I'm loading is. That is, I have an elisp file that I'm loading, it has an relative path and I need an absolute one.</p>
| [
{
"answer_id": 292001,
"author": "Emerick Rogul",
"author_id": 33837,
"author_profile": "https://Stackoverflow.com/users/33837",
"pm_score": 3,
"selected": false,
"text": "expand-file-name"
},
{
"answer_id": 292044,
"author": "pupeno",
"author_id": 6068,
"author_profile": "https://Stackoverflow.com/users/6068",
"pm_score": 4,
"selected": false,
"text": "(expand-file-name \"relative/path\" (file-name-directory load-file-name))\n"
},
{
"answer_id": 292179,
"author": "Trey Jackson",
"author_id": 6148,
"author_profile": "https://Stackoverflow.com/users/6148",
"pm_score": 6,
"selected": true,
"text": "'file-truename\n ;; this is in the file being loaded\n(let ((default-directory (file-name-directory load-file-name)))\n (file-truename \"blih\"))\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <code>x</code> found? Some possible choices include the list below:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function <code>spam</code> is passed somewhere else. And maybe <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="noreferrer">lambda functions</a> pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| [
{
"answer_id": 292002,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "globals locals x Foo.spam for if try code2 Foo.code2 self.code2 variable.instance self.variable self"
},
{
"answer_id": 292498,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": false,
"text": "x= 0\ndef fun1():\n x= 1\n def fun2():\n x= 2\n def fun3():\n return x\n return fun3()\n return fun2()\nprint fun1(), x\n\n2 0\n 0 0\n"
},
{
"answer_id": 292502,
"author": "Rizwan Kassim",
"author_id": 35335,
"author_profile": "https://Stackoverflow.com/users/35335",
"pm_score": 10,
"selected": true,
"text": "def lambda def lambda global def open range SyntaxError code1\nclass Foo:\n code2\n def spam():\n code3\n for code4:\n code5\n x()\n for def spam code3 code4 code5 def x code1 x x code2"
},
{
"answer_id": 293097,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 7,
"selected": false,
"text": "def foo():\n x=4\n def bar():\n print x # Accesses x from foo's scope\n bar() # Prints 4\n x=5\n bar() # Prints 5\n global_var1 = []\nglobal_var2 = 1\n\ndef func():\n # This is OK: It's just accessing, not rebinding\n global_var1.append(4) \n\n # This won't affect global_var2. Instead it creates a new variable\n global_var2 = 2 \n\n local1 = 4\n def embedded_func():\n # Again, this doen't affect func's local1 variable. It creates a \n # new local variable also called local1 instead.\n local1 = 5\n print local1\n\n embedded_func() # Prints 5\n print local1 # Prints 4\n global_var = 4\ndef change_global():\n global global_var\n global_var = global_var + 1\n nonlocal"
},
{
"answer_id": 23471004,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 7,
"selected": false,
"text": "def class x = 0\nclass X(object):\n y = x\n x = x + 1 # x is now a variable\n z = x\n\n def method(self):\n print(self.x) # -> 1\n print(x) # -> 0, the global x\n print(y) # -> NameError: global name 'y' is not defined\n\ninst = X()\nprint(inst.x, inst.y, inst.z, x) # -> (1, 0, 1, 0)\n for >>> [ i for i in range(5) ]\n>>> i\n4\n def __main__ sys.modules __main__ sys.modules['__main__'] import __main__ UnboundLocalError NameError x = 5\ndef foobar():\n print(x) # causes UnboundLocalError!\n x += 1 # because assignment here makes x a local variable within the function\n\n# call the function\nfoobar()\n x = 5\ndef foobar():\n global x\n print(x)\n x += 1\n\nfoobar() # -> 5\nprint(x) # -> 6\n x = 5\ny = 13\ndef make_closure():\n x = 42\n y = 911\n def func():\n global x # sees the global value\n print(x, y)\n x += 1\n\n return func\n\nfunc = make_closure()\nfunc() # -> 5 911\nprint(x, y) # -> 6 13\n def make_closure():\n value = [0]\n def get_next_value():\n value[0] += 1\n return value[0]\n\n return get_next_value\n\nget_next = make_closure()\nprint(get_next()) # -> 1\nprint(get_next()) # -> 2\n nonlocal def make_closure():\n value = 0\n def get_next_value():\n nonlocal value\n value += 1\n return value\n return get_next_value\n\nget_next = make_closure() # identical behavior to the previous example.\n nonlocal nonlocal for with __builtin__ builtins print print import __builtin__\n\nprint3 = __builtin__.__dict__['print']\n from __future__ import print_function print print print print"
},
{
"answer_id": 34094235,
"author": "brianray",
"author_id": 226800,
"author_profile": "https://Stackoverflow.com/users/226800",
"pm_score": 5,
"selected": false,
"text": "from __future__ import print_function # for python 2 support\n\nx = 100\nprint(\"1. Global x:\", x)\nclass Test(object):\n y = x\n print(\"2. Enclosed y:\", y)\n x = x + 1\n print(\"3. Enclosed x:\", x)\n\n def method(self):\n print(\"4. Enclosed self.x\", self.x)\n print(\"5. Global x\", x)\n try:\n print(y)\n except NameError as e:\n print(\"6.\", e)\n\n def method_local_ref(self):\n try:\n print(x)\n except UnboundLocalError as e:\n print(\"7.\", e)\n x = 200 # causing 7 because has same name\n print(\"8. Local x\", x)\n\ninst = Test()\ninst.method()\ninst.method_local_ref()\n 1. Global x: 100\n2. Enclosed y: 100\n3. Enclosed x: 101\n4. Enclosed self.x 101\n5. Global x 100\n6. global name 'y' is not defined\n7. local variable 'x' referenced before assignment\n8. Local x 200\n"
},
{
"answer_id": 62379080,
"author": "MisterMiyagi",
"author_id": 5349916,
"author_profile": "https://Stackoverflow.com/users/5349916",
"pm_score": 3,
"selected": false,
"text": "print int zip def lambda def lambda class if for with nonlocal global := print(\"builtins are available without definition\")\n\nsome_global = \"1\" # global variables are at module scope\n\ndef outer_function():\n some_closure = \"3.1\" # locals and closure are defined the same, at function scope\n some_local = \"3.2\" # a variable becomes a closure if a nested scope uses it\n\n class InnerClass:\n some_classvar = \"3.3\" # class variables exist *only* at class scope\n\n def inner_function(self):\n some_local = \"3.2\" # locals can replace outer names\n print(some_closure) # closures are always readable\n return InnerClass\n class class ┎ builtins [print, ...]\n┗━┱ globals [some_global]\n ┗━┱ outer_function [some_local, some_closure]\n ┣━╾ InnerClass [some_classvar]\n ┗━╾ inner_function [some_local]\n some_local outer_function inner_function some_local outer_function inner_function some_closure print inner_function outer_function some_local outer_function inner_function for with del nonlocal global nonlocal global \nsome_global = \"1\"\n\ndef outer_function():\n some_closure = \"3.2\"\n some_global = \"this is ignored by a nested global declaration\"\n \n def inner_function():\n global some_global # declare variable from global scope\n nonlocal some_closure # declare variable from enclosing scope\n message = \" bound by an inner scope\"\n some_global = some_global + message\n some_closure = some_closure + message\n return inner_function\n nonlocal nonlocal global some_global = \"global\"\n\ndef outer_function():\n some_closure = \"closure\"\n return [ # new function-like scope started by comprehension\n comp_local # names resolved using regular name resolution\n for comp_local # iteration targets are local\n in \"iterable\"\n if comp_local in some_global and comp_local in some_global\n ]\n := nonlocal global print(some_global := \"global\")\n\ndef outer_function():\n print(some_closure := \"closure\")\n print(some_global := \"global\")\n\ndef outer_function():\n print(some_closure := \"closure\")\n steps = [\n # v write to variable in containing scope\n (some_closure := some_closure + comp_local)\n # ^ read from variable in containing scope\n for comp_local in some_global\n ]\n return some_closure, steps\n ┎ builtins [print, ...]\n┗━┱ globals [some_global]\n ┗━┱ outer_function [some_closure]\n ┗━╾ <listcomp> [comp_local]\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/291978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320510/"
] |
292,016 | <p>I've been asked to find a way to connect from a Linux system to one of several Windows servers. What we need to do ideally is connect to whatever Windows server is causing the trouble, kill a process, and restart the process. Ideally, it would be something that could be put into a script that could be run from the Linux computer. All the solutions I've found so far involve some kind of remote desktop connection, but like I said, a command line solution is preferable? Is this possible? And I apologize...not quite a programming question, but I'm at my wit's end.</p>
| [
{
"answer_id": 292073,
"author": "Rizwan Kassim",
"author_id": 35335,
"author_profile": "https://Stackoverflow.com/users/35335",
"pm_score": 2,
"selected": true,
"text": "taskkill /f /im notepad.exe\n ps -elW"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29801/"
] |
292,026 | <p>The default seems to be upper case, but is there really any reason to use upper case for keywords?</p>
<p>I started using upper case, because I was just trying to match what <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> gives me whenever I tried to create something, like a new <a href="https://en.wikipedia.org/wiki/Stored_procedure" rel="nofollow noreferrer">stored procedure</a>. But then, I felt terrible for my baby (5th) finger, that always needs to hold down the <kbd>Shift</kbd> button, so I stopped using upper case. Is there a reason why I should go back to upper case?</p>
| [
{
"answer_id": 293676,
"author": "davidtbernal",
"author_id": 19370,
"author_profile": "https://Stackoverflow.com/users/19370",
"pm_score": 5,
"selected": false,
"text": "SELECT name, id, xtype, uid, info, status, \nbase_schema_ver, replinfo, parent_obj, crdate, \nftcatid, schema_ver, stats_schema_ver, type, \nuserstat, sysstat, indexdel, refdate, version, \ndeltrig, instrig, updtrig, seltrig, category, cache\nFROM sysobjects\nWHERE category = 0\nAND xtype IN ('U', 'P', 'FN', 'IF', 'TF')\nORDER BY 1\n SELECT name, id, xtype, uid, info, status, \n base_schema_ver, replinfo, parent_obj, crdate, \n ftcatid, schema_ver, stats_schema_ver, type, \n userstat, sysstat, indexdel, refdate, version, \n deltrig, instrig, updtrig, seltrig, category, cache\nFROM sysobjects\nLEFT JOIN systhingies ON\n sysobjects.col1=systhingies.col2\nWHERE category = 0\n AND xtype IN ('U', 'P', 'FN', 'IF', 'TF')\nORDER BY 1\n"
},
{
"answer_id": 10279383,
"author": "puk",
"author_id": 654789,
"author_profile": "https://Stackoverflow.com/users/654789",
"pm_score": -1,
"selected": false,
"text": "if ( !$bla ) \n{\n echo \"select something from something where something\";\n}\n\nif ( !$beepboop ) \n{\n echo \"create table if not exists loremIpsum;\n}\n\n$query = \"\nCREATE TABLE IF NOT EXISTS HISTORY\n(\n ID INT NOT NULL AUTO_INCREMENT,\n INSERTDATE TIMESTAMP DEFAULT NOW(),\n ALTERDATE TIMESTAMP(8) DEFAULT NOW(),\n DELETEDATE TIMESTAMP(8),\n ALTERCOUNT INT DEFAULT 0,\n SELECTCOUNT INT DEFAULT 0,\n\n PRIMARY KEY(ID),\n)ENGINE=InnoDB\n\";\n\nmysqlQuery( $query, $con );\n if ( !$bla ) \n{\n echo \"select something from something where something\";\n}\n\nif ( !$beepboop ) \n{\n echo \"create table if not exists loremIpsum;\n}\n\n$query = \"\ncreate table if not exists history\n(\n id int not null auto_increment,\n insertdate timestamp default now(),\n alterdate timestamp(8) default now(),\n deletedate timestamp(8),\n altercount int default 0,\n selectcount int default 0,\n\n primary key(id),\n)engine=InnoDB\n\";\n\nmysqlQuery( $query, $con );\n CREATE TABLE IF NOT EXISTS history\n(\n ID INT NOT NULL AUTO_INCREMENT,\n insertDate TIMESTAMP DEFAULT NOW(),\n alterDate TIMESTAMP(8) DEFAULT NOW(),\n deleteDate TIMESTAMP(8),\n alterCount INT DEFAULT 0,\n selectCount INT DEFAULT 0,\n\n PRIMARY KEY(ID),\n)ENGINE=InnoDB\n ID id iD"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1381/"
] |
292,032 | <p>Just noticed that the style of the navigation menu on windows.com is just what i need for my website. I'm wondering how to create that kind of drop down list that has multiple columns. When the mouse hover on each item, the column gives a preview of that item. Thank you. </p>
| [
{
"answer_id": 292118,
"author": "Phil.Wheeler",
"author_id": 15609,
"author_profile": "https://Stackoverflow.com/users/15609",
"pm_score": 0,
"selected": false,
"text": "<ul> <li> <span> <!-- BEGIN: Products Menu -->\n <div id=\"PageWrapper\" class=\"HomePage\">\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37857/"
] |
292,037 | <p>I'm trying to highlight the search results but I want to include the surrounding text that is limited by the enclosing tags.</p>
<p>So if the $term is "cool" the preg_replace should end up with:</p>
<pre><code><div><span style="background: #f00">My hair cut so cool!</span></div>
</code></pre>
<p>Unfortunately my regex doesn't seem to capture the surrounding text, only the $term. The surrounding tags could be any kind of valid tag.</p>
<pre><code> 0:
1: $term = 'cool';
2: ob_start();
3:
10: foreach($items as $item) {
11: // echoing results here
12: echo '<div>' . $item->text . '</div>';
13: }
30: $content = ob_get_contents();
31: ob_clean() ;
32:
33: $pattern = "/(?<!<[^>])($term)/i";
34: $replace = "<span style=\"background: #f00\">$1</span>";
35: echo preg_replace($pattern, $replace, $content);
36:
</code></pre>
<p>EDIT: The foreach loop is one of many and is located in a separate class. Because of this I can't do the replacement in the loop itself. Also it seems more efficient to process the final output instead of each loop over the data.</p>
| [
{
"answer_id": 292291,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 3,
"selected": true,
"text": "$pattern = \"/[^<>]*$term[^<>]*/i\";\n$replace = \"<span style=\\\"background: #f00\\\">$0</span>\";\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
292,041 | <p>I'd like to add a custom title to one of the predefined UITabBarItems. Whenever I select the particular instance I like in Interface Builder -- if I modify the the title it gets preset back to a 'custom' identifier. Ideally I'd like the book icon from the 'Bookmarks' identifier with my own custom title.</p>
<p>Is this level of customization currently supported by the SDK? Am I going to have to ultimately screen scrape the image and apply it as a custom image?</p>
<p>Thanks for any insight or documentation which points me in the right direction.</p>
| [
{
"answer_id": 292055,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 4,
"selected": true,
"text": "-initWithTitle:image:tag"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
292,066 | <p>This code is blunderous, as it adds a class to an array and later tries to pull it and manipulate it as if it were an object.</p>
<pre><code>private function fail(event:Event):void
{
var myObj:MyClass;
var a:ArrayCollection = new ArrayCollection();
var x:MyClass;
var y:MyClass;
myObj = new MyClass;
a.addItem(myObj);
a.addItem(MyClass); // !!BAD!!
x = a[0];
y = a[1];
}
</code></pre>
<p>When I did this accidentally, it took me forever to see what I had done wrong. Partly because the error message didn't tell me anything I could understand:</p>
<pre><code>TypeError: Error #1034: Type Coercion failed: cannot convert com.ibm.ITest::MyClass$ to com.ibm.ITest.MyClass.
at ITest/fail()[C:\work_simple01\ITest\src\ITest.mxml:51]
at ITest/___ITest_Button5_click()[C:\work_simple01\ITest\src\ITest.mxml:61]
</code></pre>
<p>So my question is, why is the line marked !!BAD!! above even allowed? I would expect a compile time error here. Since it compiles, there must be some use for this that I am unaware of. What is it?</p>
| [
{
"answer_id": 332259,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 4,
"selected": true,
"text": "function drawBricks(xs:Array, ys:Array, brickType:Class){\n xs.map(function(o,i,a){\n var brick = new brickType();\n // etc.\n }); \n}\n drawBricks([0,1,2,3], [4,4,4,4], Brick); // draw a long piece\ndrawBricks(times(0, 21), countFrom(0, 21), SceneBrick); // draw a big vertical \"wall\"\n"
},
{
"answer_id": 334594,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 1,
"selected": false,
"text": "var a:ArrayCollection = new ArrayCollection();\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24734/"
] |
292,068 | <p>I have seen a lot of <code>ob_get_clean()</code> the last while. Typically I have done <code>$test .= 'test'</code></p>
<p>I'm wondering if one is faster and/or better than the other.</p>
<p>Here is the code using <code>ob_get_clean()</code>:</p>
<pre><code>ob_start();
foreach($items as $item) {
echo '<div>' . $item . '</div>';
}
$test = ob_get_clean();
</code></pre>
<p>Here is the code using <code>$test .= 'test'</code>:</p>
<pre><code>$test = '';
foreach($items as $item) {
$test .= '<div>' . $item . '</div>';
}
</code></pre>
<p>Which is better?</p>
| [
{
"answer_id": 292087,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 3,
"selected": false,
"text": "ob_get_contents() ob_clean() ob_get_clean()"
},
{
"answer_id": 292219,
"author": "Preston",
"author_id": 25213,
"author_profile": "https://Stackoverflow.com/users/25213",
"pm_score": 4,
"selected": true,
"text": "ob_start() ob_get_clean()"
},
{
"answer_id": 292611,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": false,
"text": "ob_start();\n\nforeach($items as $item) {\n echo '<div>';\n echo $item;\n echo '</div>';\n}\n\n$test = ob_get_clean();\n"
},
{
"answer_id": 292753,
"author": "Alexander Malfait",
"author_id": 27449,
"author_profile": "https://Stackoverflow.com/users/27449",
"pm_score": 2,
"selected": false,
"text": "ob_start();\n?>\n\n<? foreach($items as $item) { ?>\n <div><?= $item ?></div>\n<? } ?>\n\n<?\n$test = ob_get_clean();\n"
},
{
"answer_id": 292954,
"author": "Ciaran McNulty",
"author_id": 34024,
"author_profile": "https://Stackoverflow.com/users/34024",
"pm_score": 2,
"selected": false,
"text": "echo '<div>'.$test.'</div>'; echo '<div>', $test , '</div>';"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
292,071 | <p>I'm working on a game for the iPhone that has a drawing/paint mechanic involved and I'm having problems trying to create a tool that would erase things already painted.</p>
<p>The main problem is that the background being painted on is not a solid color but a static image or animation. I've tried using different blending options and logical operations in drawing but nothing seemed to work. I'm new to OpenGL so I must be missing something.</p>
<p>Any tips?</p>
<p>EDIT: To give a little more information, I'm using textures for my brushes and using glVertexPointer() and glDrawArrays() to render them. For example:</p>
<pre><code>glBindTexture(GL_TEXTURE_2D, circleBrush);
glVertexPointer(3, GL_FLOAT, 0, verts);
glTexCoordPointer(2, GL_FLOAT, 0, coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
</code></pre>
<p>EDIT 2: Unfortunately, stencil buffers are not available on the iPhone. : (</p>
<p>EDIT 3: Framebuffer objects are available on the iPhone and that is the road I took. I haven't fully implemented it yet, but so far it looks like it works the way I wanted it to. Thanks everyone!</p>
| [
{
"answer_id": 292140,
"author": "Whaledawg",
"author_id": 23829,
"author_profile": "https://Stackoverflow.com/users/23829",
"pm_score": 2,
"selected": false,
"text": " glWindowPos2i(X, Y);\n glDrawPixels(drawing->Width, drawing->Height, drawing->Format, \n GL_UNSIGNED_BYTE, drawing->ImageData);\n glEnable(GL_BLEND);\n glDisable(GL_DEPTH_TEST);\n glWindowPos2i(X, Y);\n //background never changes\n glDrawPixels(background->Width, background->Height, background->Format, \n GL_UNSIGNED_BYTE, background->ImageData);\n glWindowPos2i(X, Y);\n glDrawPixels(drawing->Width, drawing->Height, drawing->Format, \n GL_UNSIGNED_BYTE, drawing->ImageData);\n glEnable(GL_DEPTH_TEST);\n glDisable(GL_BLEND);\n"
},
{
"answer_id": 299257,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 4,
"selected": true,
"text": "glTexSubImage2D"
},
{
"answer_id": 6032224,
"author": "oberthelot",
"author_id": 735097,
"author_profile": "https://Stackoverflow.com/users/735097",
"pm_score": 2,
"selected": false,
"text": " //Turn off writing to the Color Buffer and Depth Buffer\n //We want to draw to the Stencil Buffer only\n glColorMask(false, false, false, false);\n glDepthMask(false);\n\n //Enable the Stencil Buffer\n glEnable(GL_STENCIL_TEST);\n\n //Set 1 into the stencil buffer\n glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);\n glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);\n\n //CALL YOUR DRAWING METHOD HERE\n\n\n //Turn on Color Buffer and Depth Buffer\n glColorMask(true, true, true, true);\n glDepthMask(true);\n\n //Only write to the Stencil Buffer where 1 is set\n glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF);\n //Keep the content of the Stencil Buffer\n glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);\n\n //CALL OUR DRAWING METHOD AGAIN\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37863/"
] |
292,085 | <p>I stumbled upon this javascript obfuscator called <a href="http://www.ideareactor.com/idea/HomePage.html" rel="nofollow noreferrer">Squash</a>, I want to use it on my ExtJS project to obfuscate my javascript files. I've tried it and the result are totally obfuscated codes. But it seems that I have to obfuscate the ExtJS library too because I got warnings that it couldn't find functions such as <code>Ext.onReady()</code>, <code>Ext.form.FormPanel()</code>, etc.</p>
<p>I just want to ask if any of you guys have successfully used Squash + ExtJS in a project and how did you manage to make it work. </p>
| [
{
"answer_id": 293751,
"author": "holli",
"author_id": 18606,
"author_profile": "https://Stackoverflow.com/users/18606",
"pm_score": 1,
"selected": false,
"text": "@Public setDocumentTitle"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
292,091 | <p>How can I delete all the tables in a web page? The tables don't have any ids associated with them.</p>
| [
{
"answer_id": 292096,
"author": "Kyle West",
"author_id": 34133,
"author_profile": "https://Stackoverflow.com/users/34133",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(function() {\n $(\"table\").remove();\n});\n"
},
{
"answer_id": 292106,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "var tables = document.getElementsByTagName(\"TABLE\");\nfor (var i=tables.length-1; i>=0;i-=1)\n if (tables[i]) tables[i].parentNode.removeChild(tables[i]);\n"
},
{
"answer_id": 292467,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": false,
"text": "var tables= document.getElementsByTagName('table');\nwhile (tables.length>0)\n tables[0].parentNode.removeChild(tables[0]);\n var tables= document.getElementsByTagName('table');\nfor (var i= tables.length; i-->0;)\n tables[i].parentNode.removeChild(tables[i]);\n function toArray(l) {\n var a= [];\n for (var i= 0; i<l.length; i++)\n a[i]= l[i];\n return a;\n}\n\nvar tables= toArray(document.getElementsByTagName('table'));\nfor (var i= 0; i<tables.length; i++)\n ...\n"
},
{
"answer_id": 293463,
"author": "José Leal",
"author_id": 37190,
"author_profile": "https://Stackoverflow.com/users/37190",
"pm_score": 1,
"selected": false,
"text": "function myF() {\n this.checkChild = function(tagN, node) {\n if (node.tagName.toLower() == tagN.toLower()) {\n node.parentNode.removeChild(node);\n }\n else {\n var i;\n for(i = 0; i < node.childNodes.length; i++)\n this.checkChild(tagN, node.childNodes[i]);\n }\n }\n}\n \nvar m = new myF();\nm.checkChild(\"The name of the tagname. This case: table\", document.body); \n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code>while True:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| [
{
"answer_id": 293249,
"author": "K. Brafford",
"author_id": 33263,
"author_profile": "https://Stackoverflow.com/users/33263",
"pm_score": 3,
"selected": false,
"text": "import msvcrt # built-in module\n\ndef kbfunc():\n return ord(msvcrt.getch()) if msvcrt.kbhit() else 0\n #include <conio.h>\n\nint kb_inkey () {\n int rc;\n int key;\n\n key = _kbhit();\n\n if (key == 0) {\n rc = 0;\n } else {\n rc = _getch();\n }\n\n return rc;\n}\n import ctypes\nimport time\n\n# first, load the DLL\ntry:\n kblib = ctypes.CDLL(\"PyKeyboardAccess.dll\")\nexcept:\n raise (\"Error Loading PyKeyboardAccess.dll\")\n\n# now, find our function\ntry:\n kbfunc = kblib.kb_inkey\nexcept:\n raise (\"Could not find the kb_inkey function in the dll!\")\n\n# Ok, now let's demo the capability \nwhile True:\n x = kbfunc()\n\n if x != 0:\n print \"Got key: %d\" % x\n else:\n time.sleep(.01)\n"
},
{
"answer_id": 303976,
"author": "K. Brafford",
"author_id": 33263,
"author_profile": "https://Stackoverflow.com/users/33263",
"pm_score": 4,
"selected": false,
"text": "import msvcrt \n\ndef kbfunc(): \n x = msvcrt.kbhit()\n if x: \n ret = ord(msvcrt.getch()) \n else: \n ret = 0 \n return ret\n"
},
{
"answer_id": 1450063,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "import sys\nimport select\n\ndef heardEnter():\n i,o,e = select.select([sys.stdin],[],[],0.0001)\n for s in i:\n if s == sys.stdin:\n input = sys.stdin.readline()\n return True\n return False\n"
},
{
"answer_id": 3524350,
"author": "W. Russell",
"author_id": 425527,
"author_profile": "https://Stackoverflow.com/users/425527",
"pm_score": 5,
"selected": false,
"text": "import curses\n\ndef main(stdscr):\n # do not wait for input when calling getch\n stdscr.nodelay(1)\n while True:\n # get keyboard input, returns -1 if none available\n c = stdscr.getch()\n if c != -1:\n # print numeric value\n stdscr.addstr(str(c) + ' ')\n stdscr.refresh()\n # return curser to start position\n stdscr.move(0, 0)\n\nif __name__ == '__main__':\n curses.wrapper(main)\n"
},
{
"answer_id": 31754526,
"author": "Andria",
"author_id": 4709300,
"author_profile": "https://Stackoverflow.com/users/4709300",
"pm_score": -1,
"selected": false,
"text": "t = threading.Thread(target=sys.stdin.read(1) args=(1,))\nt.start()\ntime.sleep(5)\nt.join()\n def timed_getch(self, bytes=1, timeout=1):\n t = threading.Thread(target=sys.stdin.read, args=(bytes,))\n t.start()\n time.sleep(timeout)\n t.join()\n del t\n"
},
{
"answer_id": 41083602,
"author": "wroscoe",
"author_id": 184031,
"author_profile": "https://Stackoverflow.com/users/184031",
"pm_score": 4,
"selected": false,
"text": "from pynput.keyboard import Key, Listener\n\ndef on_press(key):\n print('{0} pressed'.format(\n key))\n\ndef on_release(key):\n print('{0} release'.format(\n key))\n if key == Key.esc:\n # Stop listener\n return False\n\n# Collect events until released\nwith Listener(\n on_press=on_press,\n on_release=on_release) as listener:\n listener.join()\n"
},
{
"answer_id": 49366794,
"author": "ullix",
"author_id": 3815773,
"author_profile": "https://Stackoverflow.com/users/3815773",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nimport curses, time\n\ndef main(stdscr):\n \"\"\"checking for keypress\"\"\"\n stdscr.nodelay(True) # do not wait for input when calling getch\n return stdscr.getch()\n\nwhile True:\n print(\"key:\", curses.wrapper(main)) # prints: 'key: 97' for 'a' pressed\n # '-1' on no presses\n time.sleep(1)\n"
},
{
"answer_id": 55692274,
"author": "ivan_pozdeev",
"author_id": 648265,
"author_profile": "https://Stackoverflow.com/users/648265",
"pm_score": 3,
"selected": false,
"text": "kbhit import os\nif os.name == 'nt':\n import msvcrt\nelse:\n import sys, select\n\ndef kbhit():\n ''' Returns True if a keypress is waiting to be read in stdin, False otherwise.\n '''\n if os.name == 'nt':\n return msvcrt.kbhit()\n else:\n dr,dw,de = select.select([sys.stdin], [], [], 0)\n return dr != []\n read() True"
},
{
"answer_id": 68962153,
"author": "Prashantzz",
"author_id": 12862934,
"author_profile": "https://Stackoverflow.com/users/12862934",
"pm_score": 1,
"selected": false,
"text": "pip install pynput from pynput.keyboard import Key, Listener\n\ndef pressed(key):\n print('Pressed:',key)\n\ndef released(key):\n print('Released:',key)\n if key == Key.enter:\n # Stop detecting when enter key is pressed\n return False\n\n# Below loop for Detcting keys runs until enter key is pressed\nwith Listener(on_press=pressed, on_release=released) as detector:\n detector.join()\n Key.enter"
},
{
"answer_id": 69740412,
"author": "ilon",
"author_id": 7388328,
"author_profile": "https://Stackoverflow.com/users/7388328",
"pm_score": 2,
"selected": false,
"text": "from sshkeyboard import listen_keyboard, stop_listening\n\ndef press(key):\n print(f\"'{key}' pressed\")\n if key == \"z\":\n stop_listening()\n\nlisten_keyboard(on_press=press)\n pip install sshkeyboard"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33263/"
] |
292,097 | <p>I wanted to grep for java process and then find the max heap memory used.
I tried this</p>
<pre><code>def ex =['sh','-c','ps -aef | grep Xmx']
String str = ex.execute().text
</code></pre>
<p>while <code>str</code> has something like <em>java -Xmx1024M /kv/classes/bebo/ -Xms512M</em>
How do I extract the value <em>1024M</em>? I was planning to user java regex but thought someone might know a cool way in groovy.</p>
| [
{
"answer_id": 292286,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 0,
"selected": false,
"text": "String ResultString = null;\nPattern regex = Pattern.compile(\"-Xmx(\\\\d+M)\");\nMatcher regexMatcher = regex.matcher(str);\nif (regexMatcher.find()) {\n ResultString = regexMatcher.group(1);\n} \n"
},
{
"answer_id": 292336,
"author": "user27037",
"author_id": 27037,
"author_profile": "https://Stackoverflow.com/users/27037",
"pm_score": 0,
"selected": false,
"text": "def ex =['sh','-c',\"ps -aef | grep Xmx | sed -e 's/^.*Xmx\\([0-9]*[mM]*\\) *$/\\1/'\"]; \nString str = ex.execute().text;\n"
},
{
"answer_id": 292801,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 4,
"selected": true,
"text": "(\"ps -aef\".execute().text =~ /.*-Xmx([0-9]+M).*/).each { full, match -> println match } \n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37870/"
] |
292,098 | <p>VB 6: How can I execute a .bat file but wait until its done running before moving on?</p>
| [
{
"answer_id": 292108,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 4,
"selected": true,
"text": " Type SHELLEXECUTEINFO\n cbSize As Long\n fMask As Long\n hwnd As Long\n lpVerb As String\n lpFile As String\n lpParameters As String\n lpDirectory As String\n nShow As Long\n hInstApp As Long\n ' Optional fields'\n lpIDList As Long\n lpClass As String\n hkeyClass As Long\n dwHotKey As Long\n hIcon As Long\n hProcess As Long\n End Type\n\n Public Declare Function ShellExecuteEx Lib \"shell32.dll\" \n (lpExecInfo As SHELLEXECUTEINFO) As Long\n\n Public Declare Function apiShellExecute Lib \"shell32.dll\" _\n Alias \"ShellExecuteA\" _\n (ByVal hwnd As Long, _\n ByVal lpOperation As String, _\n ByVal lpFile As String, _\n ByVal lpParameters As String, _\n ByVal lpDirectory As String, _\n ByVal nShowCmd As Long) _\n As Long\n\n Declare Function WaitForSingleObject Lib \"kernel32\" \n (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long\n\n\n Public Const SEE_MASK_NOCLOSEPROCESS As Long = &H40\n Public Const SEE_MASK_FLAG_DDEWAIT As Long = &H100\n\n '***App Window Constants***'\n Public Const WIN_NORMAL = 1 'Open Normal'\n Public Const WIN_MAX = 2 'Open Maximized'\n Public Const WIN_MIN = 3 'Open Minimized'\n\n '***Error Codes***'\n Private Const ERROR_SUCCESS = 32&\n Private Const ERROR_NO_ASSOC = 31&\n Private Const ERROR_OUT_OF_MEM = 0&\n Private Const ERROR_FILE_NOT_FOUND = 2&\n Private Const ERROR_PATH_NOT_FOUND = 3&\n Private Const ERROR_BAD_FORMAT = 11&\n\n' Returns 'True' if file was opened ...'\nPublic Function fHandleFile(ByVal stFile As String, _\n ByVal lShowHow As Long, _\n ByRef stRet As String, _\n Optional ByVal bWaitForClose As Boolean = False) As Boolean\nOn Error GoTo err_Handler\n Dim lRet As Long\n Dim ret As Long\n Dim lngProcessHandle As Long\n Dim varTaskID As Variant\n Dim shInfo As SHELLEXECUTEINFO\n Dim retval As Long\n\n 'First try ShellExecute'\n With shInfo\n .cbSize = LenB(shInfo)\n .lpFile = stFile\n .nShow = lShowHow\n If bWaitForClose Then\n .fMask = SEE_MASK_FLAG_DDEWAIT + SEE_MASK_NOCLOSEPROCESS\n End If\n .lpVerb = \"open\"\n End With\n\n Call ShellExecuteEx(shInfo)\n lRet = shInfo.hInstApp\n\n If lRet > ERROR_SUCCESS And bWaitForClose = True Then\n lngProcessHandle = shInfo.hProcess\n\n Do\n retval = WaitForSingleObject(lngProcessHandle, 0)\n DoEvents\n Loop Until retval <> 258\n ret = CloseHandle(lngProcessHandle)\n End If\n\n fHandleFile = (lRet > 0)\n\nexit_handler:\n Exit Function\n\nerr_Handler:\n RaiseError Err.Number, Err.Source, Err.Description\nEnd Function\n"
},
{
"answer_id": 294135,
"author": "Bob",
"author_id": 24007,
"author_profile": "https://Stackoverflow.com/users/24007",
"pm_score": 0,
"selected": false,
"text": "Private Const INFINITE = &HFFFF\nPrivate Const SYNCHRONIZE = &H100000\nPrivate Const PROCESS_QUERY_INFORMATION = &H400\n\nPrivate Declare Function CloseHandle Lib \"kernel32\" ( _\n ByVal hObject As Long) As Long\n\nPrivate Declare Function GetExitCodeProcess Lib \"kernel32\" ( _\n ByVal hProcess As Long, _\n lpExitCode As Long) As Long\n\nPrivate Declare Function OpenProcess Lib \"kernel32\" ( _\n ByVal dwDesiredAccess As Long, _\n ByVal bInheritHandle As Long, _\n ByVal dwProcessId As Long) As Long\n\nPrivate Declare Function WaitForSingleObject Lib \"kernel32\" ( _\n ByVal hHandle As Long, _\n ByVal dwMilliseconds As Long) As Long\n\nPrivate Function SyncShell( _\n ByVal PathName As String, _\n ByVal WindowStyle As VbAppWinStyle) As Long\n 'Shell and wait. Return exit code result, raise an\n 'exception on any error.\n Dim lngPid As Long\n Dim lngHandle As Long\n Dim lngExitCode As Long\n\n lngPid = Shell(PathName, WindowStyle)\n If lngPid <> 0 Then\n lngHandle = OpenProcess(SYNCHRONIZE _\n Or PROCESS_QUERY_INFORMATION, 0, lngPid)\n If lngHandle <> 0 Then\n WaitForSingleObject lngHandle, INFINITE\n If GetExitCodeProcess(lngHandle, lngExitCode) <> 0 Then\n SyncShell = lngExitCode\n CloseHandle lngHandle\n Else\n CloseHandle lngHandle\n Err.Raise &H8004AA00, \"SyncShell\", _\n \"Failed to retrieve exit code, error \" _\n & CStr(Err.LastDllError)\n End If\n Else\n Err.Raise &H8004AA01, \"SyncShell\", _\n \"Failed to open child process\"\n End If\n Else\n Err.Raise &H8004AA02, \"SyncShell\", _\n \"Failed to Shell child process\"\n End If\nEnd Function\n"
},
{
"answer_id": 346099,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 3,
"selected": false,
"text": "Declare Function OpenProcess Lib \"kernel32\" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long\nDeclare Function WaitForSingleObject Lib \"kernel32\" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long\nDeclare Function CloseHandle Lib \"kernel32\" (ByVal hObject As Long) As Long\n\nPrivate Const SYNCHRONIZE = &H100000\nPrivate Const WAIT_TIMEOUT As Long = &H102&\n\nPrivate Sub RunCommandLine(sCmdLine As String)\n\n Dim nProcessID As Long\n Dim hProcess As Long\n Dim nResult As Long\n\n nProcessID = Shell(sCmdLine, vbNormalNoFocus)\n\n If nProcessID <> 0 Then\n\n hProcess = OpenProcess(SYNCHRONIZE, 0, nProcessID)\n\n If hProcess <> 0 Then\n Do\n\n DoEvents\n nResult = WaitForSingleObject(hProcess, 50)\n\n Loop Until nResult <> WAIT_TIMEOUT Or m_bStop\n CloseHandle hProcess\n\n End If\n End If\n\n\nEnd Sub\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
292,101 | <p>I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html" rel="noreferrer">standard</a>, even as <a href="http://msdn.microsoft.com/en-us/library/aa768859(VS.85).aspx" rel="noreferrer">documented</a> on the MSDN site.</p>
<p>My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?</p>
<ul>
<li>Call the add method differently based on the value of the user agent?</li>
<li>Wrap the select object in a class that provides the proper method signature?</li>
<li>Use a javascript library which does this for you (specify which library)?</li>
</ul>
| [
{
"answer_id": 292122,
"author": "Elle H",
"author_id": 23666,
"author_profile": "https://Stackoverflow.com/users/23666",
"pm_score": 4,
"selected": false,
"text": "function addOption(selectID, display, value)\n{\n var obj = document.getElementById(selectID);\n obj.options[obj.options.length] = new Option(display, value);\n}\n"
},
{
"answer_id": 292216,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 2,
"selected": false,
"text": "$(\"#selectID\").addOption(value, text);\n"
},
{
"answer_id": 292501,
"author": "Sanket",
"author_id": 19708,
"author_profile": "https://Stackoverflow.com/users/19708",
"pm_score": 4,
"selected": true,
"text": " try\n {\n //Standards compliant\n list.add(optionTag, null);\n }\n catch (err)\n {\n //IE\n list.add(optionTag);\n }\n"
},
{
"answer_id": 292523,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 2,
"selected": false,
"text": "document.createElement('option')\nselectEl.appendChild()\n"
},
{
"answer_id": 634961,
"author": "EoghanM",
"author_id": 6691,
"author_profile": "https://Stackoverflow.com/users/6691",
"pm_score": 0,
"selected": false,
"text": " try{\n list.add(optionTag, 0);\n } catch (err) {\n // Firefox is dumb for once: http://www.quirksmode.org/dom/w3c_html.html#selects\n list.add(optionTag, list.options[0]);\n }\n"
},
{
"answer_id": 697573,
"author": "simon",
"author_id": 76777,
"author_profile": "https://Stackoverflow.com/users/76777",
"pm_score": 2,
"selected": false,
"text": "/*\nadds an option to select element, alphabetically sorted according to the lower case value of the display element (option.text)\n*/\n\nfunction insertOptionToList(optionToInsert, targetSelectElement){\n\n for (var i=0;i<targetSelectElement.options.length;i++){\n var tempOptionText = targetSelectElement.options[i].text;\n if(tempOptionText.length>0 && optionToInsert.text.toLowerCase()<tempOptionText.toLowerCase()){\n targetSelectElement.insertBefore(optionToInsert,targetSelectElement[i]);\n return true;\n }\n }\n targetSelectElement.options[targetSelectElement.options.length] = optionToInsert;\n return true; \n}\n"
},
{
"answer_id": 2062127,
"author": "Gabo Esquivel",
"author_id": 250435,
"author_profile": "https://Stackoverflow.com/users/250435",
"pm_score": 1,
"selected": false,
"text": "$(selectID).append($('<option>'+display+'</option>').attr('value', value));"
},
{
"answer_id": 10425563,
"author": "Codemaster Dev",
"author_id": 1371610,
"author_profile": "https://Stackoverflow.com/users/1371610",
"pm_score": 1,
"selected": false,
"text": "function populateSelectField()\n{\n\n document.frmMain.fldSelect.options.length = 0;\n document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option(\"Your Value 1\");\n document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option(\"Your Value 2\");\n document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option(\"Your Value 3\");\n document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option(\"Your Value 4\");\n}\n"
},
{
"answer_id": 12016563,
"author": "Chuck P",
"author_id": 1608460,
"author_profile": "https://Stackoverflow.com/users/1608460",
"pm_score": 0,
"selected": false,
"text": "<select id=\"selectItem\"></select>\n\nvar s=document.getElementById(\"selectItem\");\ns.innerHTML+=\"<option>apples</option>\";\ns.innerHTML+=\"<option>bananas</option>\"; //(...etc)\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25191/"
] |
292,109 | <p>With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allocations. </p>
<p>Any ideas? I'm looking for the simplest possible solution. Recompiling the library is not an option. </p>
| [
{
"answer_id": 292129,
"author": "Emerick Rogul",
"author_id": 33837,
"author_profile": "https://Stackoverflow.com/users/33837",
"pm_score": 3,
"selected": false,
"text": "new delete new[] malloc_hook free_hook"
},
{
"answer_id": 292143,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": false,
"text": "#include <stdlib.h>\n\nint main (void)\n{\n void *ptr = malloc(10);\n free(ptr);\n\n return 0;\n}\n\n\n$ g++ test.cpp -o test\n$ ltrace -e malloc,free ./test\nmalloc(10) = 0x804a008\nfree(0x804a008) = <void>\n+++ exited (status 0) +++\n"
},
{
"answer_id": 1735543,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": true,
"text": "malloc_hook(3) malloc __realloc_hook __free_hook #include <stdio.h>\n#include <malloc.h>\n\nstatic void *(*old_malloc_hook)(size_t, const void *);\n\nstatic void *new_malloc_hook(size_t size, const void *caller) {\n void *mem;\n\n __malloc_hook = old_malloc_hook;\n mem = malloc(size);\n fprintf(stderr, \"%p: malloc(%zu) = %p\\n\", caller, size, mem);\n __malloc_hook = new_malloc_hook;\n\n return mem;\n}\n\nstatic void init_my_hooks(void) {\n old_malloc_hook = __malloc_hook;\n __malloc_hook = new_malloc_hook;\n}\n\nvoid (*__malloc_initialize_hook)(void) = init_my_hooks;\n printf malloc malloc"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23524/"
] |
292,137 | <p>In Google groups and some other web sites, there is a 5-star rating component which is pretty neat, such as in this url:
<a href="http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en" rel="noreferrer">http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en</a></p>
<p>I am wondering whether there is an existing 5-star rating component in the iPhone environment. Or if there is not, if anyone has clue where to start?</p>
<p>Thanks</p>
| [
{
"answer_id": 299948,
"author": "Alex",
"author_id": 35999,
"author_profile": "https://Stackoverflow.com/users/35999",
"pm_score": 3,
"selected": false,
"text": "CGFloat relativeTouchLocation = [event locationInView:self] / self.bounds.size.width;\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32096/"
] |
292,164 | <p>In Visual Studio I can type e.g. </p>
<blockquote>
<p>for <kbd>TAB</kbd> <kbd>TAB</kbd></p>
</blockquote>
<p>and a code snippet pops in. </p>
<p>Are there built-in code snippets for private, public, etc. methods as well?</p>
| [
{
"answer_id": 292168,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 8,
"selected": true,
"text": "static int main static void main"
},
{
"answer_id": 16510215,
"author": "daniel1426",
"author_id": 1985601,
"author_profile": "https://Stackoverflow.com/users/1985601",
"pm_score": 1,
"selected": false,
"text": "<CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>method</Title>\n <Shortcut>method</Shortcut>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>access_modifier</ID>\n <Default>private</Default>\n </Literal>\n <Literal>\n <ID>return_type</ID>\n <Default>void</Default>\n </Literal>\n <Literal>\n <ID>name</ID>\n <Default>New_method</Default>\n </Literal>\n </Declarations>\n <Code Language=\"csharp\">\n <![CDATA[$access_modifier$ $return_type$ $name$ ()\n {\n $end$\n }]]>\n </Code>\n </Snippet>\n</CodeSnippet>\n"
},
{
"answer_id": 19247785,
"author": "Kevin Hogg",
"author_id": 687441,
"author_profile": "https://Stackoverflow.com/users/687441",
"pm_score": 4,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>method</Title>\n <Shortcut>method</Shortcut>\n <Description>Code snippet for method</Description>\n <Author>Kevin Hogg</Author>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>methodname</ID>\n <ToolTip>Method name</ToolTip>\n <Function>MethodName()</Function>\n <Default>MethodNamePlaceholder</Default>\n </Literal>\n </Declarations>\n <Code Language=\"csharp\"><![CDATA[public void $methodname$ ()\n {\n $end$\n }]]>\n </Code>\n </Snippet>\n </CodeSnippet>\n</CodeSnippets>\n method<tab><tab>\n public void MethodNamePlaceholder()\n{\n\n}\n"
},
{
"answer_id": 29824797,
"author": "Scott Nimrod",
"author_id": 492701,
"author_profile": "https://Stackoverflow.com/users/492701",
"pm_score": 5,
"selected": false,
"text": "method (typical method)\n\nvmethod (virtual method)\n\nsmethod (static method)\n\nxmethod (extension method)\n"
}
] | 2008/11/15 | [
"https://Stackoverflow.com/questions/292164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.