qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
179,845
|
<p>I know it's bad to use HTML Tables for everything... and that tables should be used only to present tabular data and not to achieve some style goal. </p>
<p>My question is, how do you make HTML forms with CSS so they look nice and aligned like when using tables?</p>
|
[
{
"answer_id": 10179810,
"author": "random",
"author_id": 9314,
"author_profile": "https://Stackoverflow.com/users/9314",
"pm_score": 2,
"selected": false,
"text": "<label> clear:left; <div> <p> .formlabel{\n clear:left;\n display:block;\n float:left;\n margin:0 0 1em 0;\n padding:0 0.5em 0 0;\n text-align:right;\n width:8em;\n}\n\n.forminput{\n float:left;\n margin:0 0.5em 0.5em 0;\n}\n\n.formwarning{\n clear:left;\n float:left;\n margin:0 0.5em 1em 0;\n}\n <fieldset><legend>Details</legend>\n <label for=\"name\" class=\"formlabel\">Name</label>\n <input id=\"name\" name=\"name\" type=\"text\" class=\"forminput\" />\n <div class=\"formwarning\">Validation error message</div>\n\n <label for=\"dob_year\" class=\"formlabel\">DOB</label>\n <div class=\"forminput\">\n <input id=\"dob_year\" name=\"dob_year\" type=\"text\" size=\"4\" /> /\n <input id=\"dob_month\" name=\"dob_month\" type=\"text\" size=\"2\" /> /\n <input id=\"dob_day\" name=\"dob_day\" type=\"text\" size=\"2\" />\n </div>\n\n <label class=\"formlabel\">Sex</label>\n <label for=\"female\" class=\"forminput\">Female</label>\n <input id=\"female\" name=\"sex\" type=\"radio\" class=\"forminput\" />\n <label for=\"male\" class=\"forminput\">Male</label>\n <input id=\"male\" name=\"sex\" type=\"radio\" class=\"forminput\" />\n\n <label for=\"state\" class=\"formlabel\">State</label>\n <select id=\"state\" name=\"state\" class=\"forminput\">\n <option>ACT</option>\n <option>New South Wales</option>\n <option>Northern Territory</option>\n <option>Queensland</option>\n <option>South Australia</option>\n <option>Tasmania</option>\n <option>Victoria</option>\n <option>Western Australia</option>\n </select>\n\n <label for=\"deadseal\" class=\"formlabel\">Death certificate</label>\n <input id=\"deadseal\" name=\"deadseal\" type=\"file\" class=\"forminput\" />\n</fieldset>\n <div> :after"
},
{
"answer_id": 35824655,
"author": "Walkinraven",
"author_id": 3146734,
"author_profile": "https://Stackoverflow.com/users/3146734",
"pm_score": 0,
"selected": false,
"text": "<form>\n<div id=\"personal_name\">\n<label>Name</label>\n<input name=\"name\" />\n</div>\n</form>\n form\n{display: table}\n#personal_name\n{display: table-row}\n#personal_name input, #personal_name label\n{display: table-cell}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7595/"
] |
179,868
|
<p>It seems that the </p>
<ul>
<li><a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.debug(v=vs.110).aspx" rel="noreferrer"><code>System.Diagnostics.Debug</code></a>, and </li>
<li><a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.trace(v=vs.110).aspx" rel="noreferrer"><code>System.Diagnostics.Trace</code></a> </li>
</ul>
<p>are largely the same, with the notable exception that <strong>Debug</strong> usage is compiled out in a release configuration. </p>
<p>When would you use one and not the other? The only answer to this I've dug up so far is just that you use the <strong>Debug</strong> class to generate output that you only see in debug configuration, and <strong>Trace</strong> will remain in a release configuration, but that doesn't really answer the question in my head.</p>
<p>If you're going to instrument your code, why would you ever use <strong>Debug</strong>, since <strong>Trace</strong> can be turned off without a recompile?</p>
|
[
{
"answer_id": 179886,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 1,
"selected": false,
"text": "Debug.WriteLine(\"Connecting to DB with username: blah and PW: pass\");\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] |
179,904
|
<p>I've been recently asked to learn some MATLAB basics for a class.</p>
<p>What does make it so cool for researchers and people that works in university?
I saw it's cool to work with matrices and plotting things... (things that can be done easily in Python using some libraries).</p>
<p>Writing a function or parsing a file is just painful. I'm still at the start, what am I missing?</p>
<p>In the "real" world, what should I think to use it for? When should it can do better than Python? For better I mean: easy way to write something performing.</p>
<hr>
<p><strong>UPDATE 1:</strong> One of the things I'd like to know the most is "Am I missing something?" :D</p>
<p><strong>UPDATE 2:</strong> Thank you for your answers. My question is not about buy or not to buy MATLAB. The university has the possibility to give me a copy of an old version of MATLAB (MATLAB 5 I guess) for free, without breaking the license. I'm interested in its capabilities and if it deserves a deeper study (I won't need anything more than <em>basic</em> MATLAB in oder to pass the exam :P ) it will really be better than Python for a specific kind of task in the real world.</p>
|
[
{
"answer_id": 8347327,
"author": "Oli",
"author_id": 1052189,
"author_profile": "https://Stackoverflow.com/users/1052189",
"pm_score": 5,
"selected": false,
"text": "ind2sub im2col hist(Im(:)) unique(list) bsxfun(@plus,M,V) convn(A) tic; %%code; toc imcrop(im) imagesc(matrix) bsxfun(@times,A,1./sqrt(sum(A.^2))) A(:,sum(A)<e)=[] gpuX = gpuarray(X); \n%%% code normally and everything is done on GPU\n parfor n=1:100\n%%% code normally and everything is multi-threaded\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21384/"
] |
179,927
|
<p>In visual studio, I have an asp.net 3.5 project that is using MS Enterprise Library 4.0 application blocks. </p>
<p>When I have my web config file open, my Error list fills up with 99 messages with things like </p>
<pre><code>Could not find schema information for the element 'dataConfiguration'.
Could not find schema information for the attribute 'defaultDatabase'.
Could not find schema information for the element 'loggingConfiguration'.
Could not find schema information for the attribute 'tracingEnabled'.
Could not find schema information for the attribute 'defaultCategory'.
</code></pre>
<p>If I close the Web.config file they go away (but they come back as soon as I need to open the file again).</p>
<p>After doing some looking, I found that this is becauase there is an XSD or schema file missing that Visual Studio needs in order to properly 'understand' the schema that is in the web.config file and provide intellisense for it. </p>
<p>Does anyone know how to either supply VS with the appropriate schema information, or to turn off these messages?</p>
<p>@Franci - Thanks for the info, I have tried that tool as well as the MMC snap in (they tend to blow up the formatting in the Web.config) but they still do not resolve the irritating warnings I receive. Thanks for trying. </p>
|
[
{
"answer_id": 179945,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 1,
"selected": false,
"text": "<configSections>\n <section name=\"loggingConfiguration\" type=\"Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n</configSections>\n"
},
{
"answer_id": 464620,
"author": "user57433",
"author_id": 57433,
"author_profile": "https://Stackoverflow.com/users/57433",
"pm_score": 5,
"selected": true,
"text": "app.config LoggingConfiguration DotNetConfig.xsd <xs:element name=\"loggingConfiguration\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"listeners\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"add\">\n <xs:complexType>\n <xs:attribute name=\"fileName\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"footer\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"formatter\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"header\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"rollFileExistsBehavior\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"rollInterval\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"rollSizeKB\" type=\"xs:unsignedByte\" use=\"required\" />\n <xs:attribute name=\"timeStampPattern\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"listenerDataType\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"traceOutputOptions\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"filter\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"formatters\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"add\">\n <xs:complexType>\n <xs:attribute name=\"template\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"logFilters\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"add\">\n <xs:complexType>\n <xs:attribute name=\"enabled\" type=\"xs:boolean\" use=\"required\" />\n <xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"categorySources\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"add\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"listeners\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"add\">\n <xs:complexType>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"specialSources\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"allEvents\">\n <xs:complexType>\n <xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n <xs:element name=\"notProcessed\">\n <xs:complexType>\n <xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n <xs:element name=\"errors\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"listeners\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"add\">\n <xs:complexType>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"switchValue\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"tracingEnabled\" type=\"xs:boolean\" use=\"required\" />\n <xs:attribute name=\"defaultCategory\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"logWarningsWhenNoCategoriesMatch\" type=\"xs:boolean\" use=\"required\" />\n </xs:complexType>\n</xs:element>\n"
},
{
"answer_id": 29321444,
"author": "Wade Price",
"author_id": 4639374,
"author_profile": "https://Stackoverflow.com/users/4639374",
"pm_score": 1,
"selected": false,
"text": "app.config Properties Schemas ... use DotNetConfig30.xsd"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16391/"
] |
179,934
|
<p>This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call:</p>
<pre><code>function callCancelPlan(activePlanId, ntLogin) {
var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}';
$.ajax({
type: "POST",
url: "ArpWorkItem.aspx/CancelPlan",
data: paramList,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert("success");
},
error: function(xml,textStatus,errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
});
}
</code></pre>
<p>And here is the page method I am trying to call:</p>
<pre><code>[WebMethod()]
private static void CancelPlan(int activePlanId, string ntLogin)
{
StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter();
presenter.CancelExistingPlan(offer, ntLogin);
}
</code></pre>
<p>I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?</p>
|
[
{
"answer_id": 17837848,
"author": "Tukaram",
"author_id": 2613382,
"author_profile": "https://Stackoverflow.com/users/2613382",
"pm_score": 2,
"selected": false,
"text": "public static [WebMethod]\npublic static string MethodName() {} \n"
},
{
"answer_id": 66999229,
"author": "JustSomeGuyInWorld",
"author_id": 11872132,
"author_profile": "https://Stackoverflow.com/users/11872132",
"pm_score": 1,
"selected": false,
"text": "settings.AutoRedirectMode = RedirectMode.Permanent;\n settings.AutoRedirectMode = RedirectMode.Off;\n public\n\nstatic\n using System.Web.Services;\n [WebMethod] \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
179,938
|
<p>i'm want to have a repeater generate a bunch of checkboxes, e.g.:</p>
<pre><code><tr><td><input type="checkbox" name="t" value="11cbf4deb87" /> <input type="checkbox" name="a" value="33cbf4deb87" />stackoverflow.com</td></tr>
<tr><td><input type="checkbox" name="t" value="11cbf4deb88" /> <input type="checkbox" name="a" value="33cbf4deb87" />microsoft.com</td></tr>
<tr><td><input type="checkbox" name="t" value="11cd3f33a89" /> <input type="checkbox" name="a" value="33cbf4deb87" />gmail.com</td></tr>
<tr><td><input type="checkbox" name="t" value="1138fecd337" /> <input type="checkbox" name="a" value="33cbf4deb87" />youporn.com</td></tr>
<tr><td><input type="checkbox" name="t" value="11009efdacc" /> <input type="checkbox" name="a" value="33bf4deb87" />fantasti.cc</td></tr>
</code></pre>
<p>Question 1: How do i individually reference each checkbox when the repeater is running so i can set the unique value?</p>
<p>Do i data-bind it with something like:</p>
<pre><code><itemtemplate>
<tr>
<td>
<input type="checkbox" name="t"
value="<%# ((Item)Container.DataItem).TangoUniquifier %>" />
<input type="checkbox" name="a"
value="<%# ((Item)Container.DataItem).AlphaUniquifier %>" />
<%# ((Item)Container.DataItem).SiteName %>
</td>
</tr>
</itemtemplate>
</code></pre>
<p>Or am i supposed to set it somehow in the OnItemDataBound?</p>
<pre><code><asp:repeater id="ItemsRepeater"
OnItemDataBound="ItemsRepeater_OnItemDataBound" runat="server">
...
<itemtemplate>
<tr>
<td>
<input id="chkTango" type="checkbox" name="t" runat="server" />
<input id="chkAlpha" type="checkbox" name="a" runat="server" />
<%# ((Item)Container.DataItem).SiteName %>
</td>
</tr>
</itemtemplate>
...
</asp:repeater>
protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
// if the data bound item is an item or alternating item (not the header etc)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// get the associated item
Item item = (Item)e.Item.DataItem;
//???
this.chkTango.Value = item.TangoUniquifier;
this.chkAlpha.Value = item.AlphaUniquifier;
}
}
</code></pre>
<p>But if i'm supposed to reference it in the code-behind, how do i reference it in the code-behind? Am i supposed to reference it using the (server-side) id property of an <code><INPUT></code> control? i realize that the ID of a control on the server-side is not the same as the ID that will be present on the client.</p>
<p>Or do i have to do something where i have to find an INPUT control with a name of "t" and another with a name of "a"? And what kind of control is a CheckBox that allows me to set it's input value?</p>
<pre><code>protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
// if the data bound item is an item or alternating item (not the header etc)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// get the associated item
Item item = (Item)e.Item.DataItem;
CheckBox chkTango = (CheckBox)e.Item.FindControl("chkTango");
chkTango.Value = item.TangoUniquifier;
CheckBox chkAlpha = (CheckBox)e.Item.FindControl("chkAlpha");
chkAlpha.Value = item.AlphaUniquifier;
}
}
</code></pre>
<hr>
<p>Question 2:
When the user later clicks SUBMIT, how do i find all the checked checkboxes, or more specifically their VALUES?</p>
<p>Do i have to FindControl?</p>
<pre><code>protected void DoStuffWithLinks_Click(object sender, EventArgs e)
{
// loop through the repeater items
foreach (RepeaterItem repeaterItem in actionItemRepeater.Items)
{
Item item = repeaterItem.DataItem as Item;
// grab the checkboxes
CheckBox chkAlpha = (CheckBox)repeaterItem.FindControl("chkAlpha");
CheckBox chkTango = (CheckBox)repeaterItem.FindControl("chkTango");
if (chkAlpha.Checked)
{
item.DoAlphaStuff(chkAlpha.Name);
}
if (chkTango.Checked)
{
item.DoTangoStuff(chkTango.Name);
}
}
}
</code></pre>
<p>Is the repeater items DataItem still there on a click event handler?</p>
|
[
{
"answer_id": 180307,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 5,
"selected": true,
"text": " <asp:CheckBox id=\"whatever\" runat=\"Server\" />\n CheckBox checkBox = (CheckBox)e.Item.FindControl(\"whatever\");\ncheckBox.Checked = true;\n foreach (RepeaterItem item in myRepeater.Items)\n{\n if (item.ItemType == ListItemType.Item \n || item.ItemType == ListItemType.AlternatingItem) \n { \n CheckBox checkBox = (CheckBox)item.FindControl(\"whatever\");\n if (checkBox.Checked)\n { /* do something */ }\n }\n}\n as FindControl() as ctl00_cph0_ParentContainer_MyRepeater_ctl01_MyCheckbox\nctl00_cph0_ParentContainer_MyRepeater_ctl02_MyCheckbox\nctl00_cph0_ParentContainer_MyRepeater_ctl03_MyCheckbox\n"
},
{
"answer_id": 1364892,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<asp:HiddenField ID=\"repeaterhidden\" Value='<%# DataBinder.Eval(Container.DataItem, \"value\")%>' runat=\"server\" >\n HiddenField hiddenField = (HiddenField)item.FindControl(repeaterStringhidden);\n\n{ /* do something with hiddenField.Value */\n"
},
{
"answer_id": 9737116,
"author": "marquito",
"author_id": 461076,
"author_profile": "https://Stackoverflow.com/users/461076",
"pm_score": 1,
"selected": false,
"text": " foreach (RepeaterItem item in rptClientes.Items)\n {\n Panel pnl = (Panel)item.FindControl(\"divCliente\");\n Control c = pnl.FindControl(\"hdnID\");\n if (c is HiddenField)\n {\n if (((HiddenField)c).Value == hdnClienteNome.Value)\n pnl.BackColor = System.Drawing.Color.Beige;\n }\n }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
179,940
|
<p>We are developing a C# application for a web-service client. This will run on Windows XP PC's.</p>
<p>One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end.</p>
<p>However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.</p>
<p>The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.</p>
<pre><code>CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);
</code></pre>
<p>As per <a href="http://www.timeanddate.com/worldclock/city.html?n=22" rel="noreferrer">this date site</a>:</p>
<blockquote>
<p>UTC/GMT Offset </p>
<p>Standard time zone: UTC/GMT +12 hours<br>
Daylight saving time: +1 hour<br>
Current time zone offset: <strong>UTC/GMT +13 hours</strong> </p>
</blockquote>
<p>How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?</p>
|
[
{
"answer_id": 179966,
"author": "coder1",
"author_id": 3018,
"author_profile": "https://Stackoverflow.com/users/3018",
"pm_score": 6,
"selected": false,
"text": "TimeZone.CurrentTimeZone.ToLocalTime(date);\n"
},
{
"answer_id": 180105,
"author": "rbrayb",
"author_id": 9922,
"author_profile": "https://Stackoverflow.com/users/9922",
"pm_score": 2,
"selected": false,
"text": "string date = \"Web service date\"..ToString(\"R\", ci);\nDateTime convertedDate = DateTime.Parse(date); \nDateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);\n"
},
{
"answer_id": 182552,
"author": "Brendan Kowitz",
"author_id": 25767,
"author_profile": "https://Stackoverflow.com/users/25767",
"pm_score": 3,
"selected": false,
"text": "DateTime convertedDate = DateTime.Parse(date);\nDateTime localDate = convertedDate.ToLocalTime();\n DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );\n"
},
{
"answer_id": 455965,
"author": "Daniel Ballinger",
"author_id": 54026,
"author_profile": "https://Stackoverflow.com/users/54026",
"pm_score": 7,
"selected": false,
"text": "// Coordinated Universal Time string from \n// DateTime.Now.ToUniversalTime().ToString(\"u\");\nstring date = \"2009-02-25 16:13:00Z\"; \n// Local .NET timeZone.\nDateTime localDateTime = DateTime.Parse(date); \nDateTime utcDateTime = localDateTime.ToUniversalTime();\n\n// ID from: \n// \"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zone\"\n// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx\nstring nzTimeZoneKey = \"New Zealand Standard Time\";\nTimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);\nDateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);\n"
},
{
"answer_id": 963812,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 9,
"selected": false,
"text": "2012-09-19 01:27:30.000 DateTime.Parse DateTime DateTimeOffset DateTime convertedDate = DateTime.Parse(dateStr);\n\nvar kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified\n DateTime convertedDate = DateTime.SpecifyKind(\n DateTime.Parse(dateStr),\n DateTimeKind.Utc);\n\nvar kind = convertedDate.Kind; // will equal DateTimeKind.Utc\n ToLocalTime DateTime dt = convertedDate.ToLocalTime();\n"
},
{
"answer_id": 7905548,
"author": "David",
"author_id": 654199,
"author_profile": "https://Stackoverflow.com/users/654199",
"pm_score": 4,
"selected": false,
"text": "DateTime.Parse() DateTime DateTime.ParseExact(dateString, \n \"MM/dd/yyyy HH:mm:ss\", \n CultureInfo.InvariantCulture, \n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)\n DateTime.TryParseExact(...)\n AssumeUniversal AssumeUniversal AdjustToUniversal DateTime.Parse(dateString, new CultureInfo(\"en-US\"))\n CultureInfo Parse() ParseExact() ParseExact() Parse()"
},
{
"answer_id": 13410106,
"author": "CJ7",
"author_id": 327528,
"author_profile": "https://Stackoverflow.com/users/327528",
"pm_score": 5,
"selected": false,
"text": "DateTime Kind Unspecified ToLocalTime UTC Unspecified DateTime convertedDate.ToLocalTime();\n Kind DateTime Unspecified UTC Unspecified UTC ToLocalTime"
},
{
"answer_id": 44225724,
"author": "Prince Prasad",
"author_id": 2722284,
"author_profile": "https://Stackoverflow.com/users/2722284",
"pm_score": 3,
"selected": false,
"text": "@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)\n"
},
{
"answer_id": 65817420,
"author": "David Al-Yakobi",
"author_id": 15038341,
"author_profile": "https://Stackoverflow.com/users/15038341",
"pm_score": 0,
"selected": false,
"text": "CreatedDate.ToUniversalTime().ToLocalTime();\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9922/"
] |
179,955
|
<p>Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing)</p>
|
[
{
"answer_id": 179971,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 7,
"selected": true,
"text": " // enable anti-aliased text:\n System.setProperty(\"awt.useSystemAAFontSettings\",\"on\");\n -Dawt.useSystemAAFontSettings=on\n"
},
{
"answer_id": 11990630,
"author": "Luke Usherwood",
"author_id": 932359,
"author_profile": "https://Stackoverflow.com/users/932359",
"pm_score": 3,
"selected": false,
"text": "Graphics.drawText if (desktopHints == null) { \n Toolkit tk = Toolkit.getDefaultToolkit(); \n desktopHints = (Map) (tk.getDesktopProperty(\"awt.font.desktophints\")); \n}\nif (desktopHints != null) { \n g2d.addRenderingHints(desktopHints); \n} \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
179,969
|
<p>We are migrating our test report data (unit, regression, integration, etc..) from an XML format to a database format for better analysis. Right now the majority of our test analysis is done using the CruiseControl.NET dashboard, but this is limited to primarily the most recent test data. Older test data can be accessed but not easily compared to new test data. We want to pin point problem components and better narrow down bugs. With the onset of tons of information brought on by our newly implemented regression and integration testing I would like to see some better metrics generated (possibly performance and the like). Have you worked with any business intelligence systems that will provide a framework for accurately and easily implementing some sort of analysis and reporting? </p>
<p>I have looked into JasperReports and Pentaho but I'm struggling with implemetation of Pentaho at the moment. Should I continue my fight with the system? Is this what I'm looking for? </p>
|
[
{
"answer_id": 1797104,
"author": "O. Jones",
"author_id": 205608,
"author_profile": "https://Stackoverflow.com/users/205608",
"pm_score": 0,
"selected": false,
"text": " select * \n from test \n where failed='yes' \n order by testno, date desc\n select max(date), min(date), testno \n from test\n where failed='yes'\n group by testno \n order by testno \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] |
179,985
|
<p>We have a database library in C# that we can use like this:</p>
<pre><code>DatabaseConnection conn = DatabaseConnection.FromConnectionString("...");
</code></pre>
<p>This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc.</p>
<p>Internally, the <code>DatabaseConnection</code> class is an abstract class implementing some of the basic methods, but the <code>FromConnectionString</code> method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection.</p>
<p>The connection string contains information about what kind of database engine and version this connection is for.</p>
<p>I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this?</p>
<pre><code>conn = DatabaseConnection("...")
</code></pre>
<p>or using a class method?</p>
<pre><code>conn = DatabaseConnection.FromConnectionString("...")
</code></pre>
<p>is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string?</p>
<p>Ok, let me ask a different question... What is the <em>pythonic</em> way of doing this?</p>
<p>I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.</p>
|
[
{
"answer_id": 180009,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 4,
"selected": true,
"text": "class class1:\n def greet(self):\n print \"hi\"\n\nclass class2:\n def greet(self):\n print \"hello\"\n\nmaker = class1\nobj1 = maker()\n\nmaker = class2\nobj2 = maker()\n\nobj1.greet() # prints \"hi\"\nobj2.greet() # prints \"hello\"\n"
},
{
"answer_id": 180028,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "def DatabaseConnectionFromString(connection_string)\n return _DatabaseConnection(connection_string)\n\ndef DatabaseConnectionFromSomethingElse(something_else)\n connection_string = convert_something_else_into_string(something_else)\n return _DatabaseConnection(connection_string)\n\nclass _DatabaseConnection(object):\n def __init__(self, connection_string):\n self.connection_string = connection_string\n DatabaseConnection(object):\n def __init__(self, connection_string):\n self.connection_string = connection_string\n\nDatabaseConnectionFromSomethingElse(object)\n def __init__(self, something_else):\n self.connection_string = convert_something_else_into_string(something_else)\n"
},
{
"answer_id": 180142,
"author": "Sanjaya R",
"author_id": 9353,
"author_profile": "https://Stackoverflow.com/users/9353",
"pm_score": 2,
"selected": false,
"text": "def DatabaseConnection( str ): \n if ( IsOracle( str ) ): \n return OracleConnection( str ) \n else: \n return SomeOtherConnection( str )\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
179,987
|
<p>I am in a situation where I must update an existing database structure from varchar to nvarchar using a script. Since this script is run everytime a configuration application is run, I would rather determine if a column has already been changed to nvarchar and not perform an alter on the table. The databases which I must support are SQL Server 2000, 2005 and 2008. </p>
|
[
{
"answer_id": 180022,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 3,
"selected": true,
"text": "IF EXISTS \n (SELECT *\n FROM sysobjects syo\n JOIN syscolumns syc ON\n syc.id = syo.id\n JOIN systypes syt ON\n syt.xtype = syc.xtype\n WHERE \n syt.name = 'nvarchar' AND\n syo.name = 'MY TABLE NAME' AND\n syc.name = 'MY COLUMN NAME')\nBEGIN\n ALTER ...\nEND\n"
},
{
"answer_id": 180161,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 5,
"selected": false,
"text": "SELECT 'ALTER TABLE ' + isnull(schema_name(syo.id), 'dbo') + '.' + syo.name \n + ' ALTER COLUMN ' + syc.name + ' NVARCHAR(' + case syc.length when -1 then 'MAX' \n ELSE convert(nvarchar(10),syc.length) end + ');'\n FROM sysobjects syo\n JOIN syscolumns syc ON\n syc.id = syo.id\n JOIN systypes syt ON\n syt.xtype = syc.xtype\n WHERE \n syt.name = 'varchar' \n and syo.xtype='U'\n NVARCHAR VARCHAR NVARCHAR(MAX) WHILE"
},
{
"answer_id": 13468461,
"author": "Appyks",
"author_id": 900087,
"author_profile": "https://Stackoverflow.com/users/900087",
"pm_score": 2,
"selected": false,
"text": "SELECT 'ALTER TABLE [' + isnull(schema_name(syo.object_id), sysc.name) + '].[' + syo.name \n + '] ALTER COLUMN ' + syc.name + ' NVARCHAR(' + case syc.max_length when -1 then 'MAX' \n ELSE convert(nvarchar(10),syc.max_length) end + ');'\n FROM sys.objects syo\n JOIN sys.columns syc ON\n syc.object_id= syo.object_id\n JOIN sys.types syt ON\n syt.system_type_id = syc.system_type_id\n JOIN sys.schemas sysc ON\n syo.schema_id=sysc.schema_id\n WHERE \n syt.name = 'varchar' \n and syo.type='U'\n"
},
{
"answer_id": 31827056,
"author": "Nezam",
"author_id": 1221203,
"author_profile": "https://Stackoverflow.com/users/1221203",
"pm_score": 2,
"selected": false,
"text": "NOT NULL NULL SELECT cmd = 'alter table [' + c.table_schema + '].[' + c.table_name \n + '] alter column [' + c.column_name + '] nvarchar('\n +CASE WHEN CHARACTER_MAXIMUM_LENGTH<=4000\n THEN CAST(CHARACTER_MAXIMUM_LENGTH as varchar(10)) ELSE 'max' END+')' \n + CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END,*\nFROM information_schema.columns c\nWHERE c.data_type='varchar' \nORDER BY CHARACTER_MAXIMUM_LENGTH desc\n"
},
{
"answer_id": 54932584,
"author": "hobwell",
"author_id": 1781344,
"author_profile": "https://Stackoverflow.com/users/1781344",
"pm_score": 0,
"selected": false,
"text": "SELECT cmd = 'ALTER TABLE [' + c.table_schema + '].[' + c.table_name \n + '] ALTER COLUMN [' + c.column_name + '] NVARCHAR('\n +CASE WHEN CHARACTER_MAXIMUM_LENGTH<=4000 THEN \n CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN\n 'MAX' ELSE CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10)) END ELSE 'MAX' END+')' \n + CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END,*\nFROM information_schema.columns c\nWHERE c.data_type='VARCHAR' \nORDER BY CHARACTER_MAXIMUM_LENGTH DESC\n SELECT cmd = \nCASE WHEN name IS NOT NULL THEN\n 'ALTER TABLE ' + c.table_name + ' DROP CONSTRAINT ' + d.name + '; ' +\n 'ALTER TABLE [' + c.table_schema + '].[' + c.table_name + '] ALTER COLUMN [' + c.column_name + '] ' + \n 'NVARCHAR(' +\n CASE WHEN CHARACTER_MAXIMUM_LENGTH <= 4000 THEN \n CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN\n 'MAX' \n ELSE \n CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10)) \n END \n ELSE \n 'MAX' \n END \n + ')' +\n CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END + '; ' + \n 'ALTER TABLE '+ c.table_name + ' ADD CONSTRAINT ' + d.name +' DEFAULT '+ c.column_default + ' FOR ' + c.column_name + ';'\nELSE\n 'ALTER TABLE [' + c.table_schema + '].[' + c.table_name + '] ALTER COLUMN [' + c.column_name + '] ' +\n 'NVARCHAR(' +\n CASE WHEN CHARACTER_MAXIMUM_LENGTH<=4000 THEN\n CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN\n 'MAX' \n ELSE \n CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10)) \n END \n ELSE \n 'MAX' \n END\n + ')' +\n CASE WHEN IS_NULLABLE='NO' THEN ' NOT NULL' ELSE '' END \nEND,d.name, c.*\nFROM information_schema.columns c\nLEFT OUTER JOIN sys.default_constraints d ON d.parent_object_id = object_id(c.table_name)\nAND d.parent_column_id = columnproperty(object_id(c.table_name), c.column_name, 'ColumnId')\nWHERE c.data_type='VARCHAR' \nORDER BY CHARACTER_MAXIMUM_LENGTH DESC\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4441/"
] |
179,988
|
<p>Wanted to see peoples thoughts on best way to organize directory and project structure on a project / solution for a winforms C# app. </p>
<p>Most people agree its best to seperate view, business logic, data objects, interfaces but wanted to see how different people tackle this. In addition, isolate third party dependencies into implementation projects and then have interface exported projects that consumers reference </p>
<p><li>View.csproj
<li>BusinessLogic.csproj
<li>Data.csproj
<li>CalculatorService.Exported.csproj (interfaces)
<li>CalculatorService.MyCalcImpl.csproj (one implementation)
<li>CalculatorService.MyCalcImpl2.csproj (another implementation)</p>
<p>Also, in terms of folder structure, what is better nesting:</p>
<p>Interfaces<br>
---IFoo<br>
---IData<br>
Impl<br>
---Foo<br>
---Data </p>
<p>or </p>
<p>Product<br>
---Interfaces/IProduct<br>
---Impl/Product<br>
Foo<br>
---Impl/Foo<br>
---Interfaces/IFoo </p>
<p>All trying to push for decoupled dependencies on abstractions and quick ability to changed implementations.</p>
<p>Thoughts? Best practices?</p>
|
[
{
"answer_id": 180029,
"author": "Bill",
"author_id": 14547,
"author_profile": "https://Stackoverflow.com/users/14547",
"pm_score": 0,
"selected": false,
"text": "\\XCENT\n\\XCENT\\App1\n\\XCENT\\App1\\UI\n\\XCENT\\App1\\UI\\Test //test harness for UI\n\\XCENT\\App1\\Data\n\\XCENT\\App1\\Data\\Test //test harnesses for Data\n"
},
{
"answer_id": 180701,
"author": "Odd",
"author_id": 11908,
"author_profile": "https://Stackoverflow.com/users/11908",
"pm_score": 4,
"selected": true,
"text": "Project\n-Models\n-Controllers\n-Views\n Project\n-Models\n-Presenters\n-Views\n Project\n-Models\n--Inventory\n-Controllers\n--Inventory\n---TransactionsController.cs\n-Views\n--Inventory\n---Transactions\n----EditTransactionsView.dfm\n"
},
{
"answer_id": 6209673,
"author": "Nick Bedford",
"author_id": 151429,
"author_profile": "https://Stackoverflow.com/users/151429",
"pm_score": 3,
"selected": false,
"text": "- Project\n + Forms\n + Classes\n + UserControls\n + Resources\n + Data\n new Forms.AboutForm().ShowDialog();\nControls.Add(new Controls.UberTextBox());\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/179988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
180,003
|
<p>I would like a code sample for a function that takes a tDateTime and an integer as input and sets the system time using setlocaltime after advancing that tDateTime by (int) months. The time should stay the same.</p>
<p>pseudo code example</p>
<pre><code>SetNewTime(NOW,2);
</code></pre>
<p>The issues I'm running into are rather frustrating. I cannot use incmonth or similar with a tDateTime, only a tDate, etc.</p>
|
[
{
"answer_id": 180065,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 4,
"selected": true,
"text": "program OneMonth;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Windows,\n Messages;\n\nprocedure SetLocalSystemTime(settotime: TDateTime);\nvar\n SystemTime : TSystemTime;\nbegin\n DateTimeToSystemTime(settotime,SystemTime);\n SetLocalTime(SystemTime);\n //tell windows that the time changed\n PostMessage(HWND_BROADCAST,WM_TIMECHANGE,0,0);\nend;\n\nbegin\n try\n SetLocalSystemTime(IncMonth(Now,1));\n except on E:Exception do\n Writeln(E.Classname, ': ', E.Message);\n end;\nend.\n"
},
{
"answer_id": 180116,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 1,
"selected": false,
"text": "procedure SetNewTime(aDateTime: TDateTime; aMonths: Integer);\nvar\n lSystemTime: TSystemTime;\nbegin\n DateTimeToSystemTime(aDateTime, lSystemTime);\n Inc(lSystemTime.wMonth, aMonths);\n setSystemTime(lSystemTime);\nend;\n"
},
{
"answer_id": 180331,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 2,
"selected": false,
"text": "function IncMonth ( const StartDate : TDateTime {; NumberOfMonths : Integer = 1} ) : TDateTime;\n"
},
{
"answer_id": 180718,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 1,
"selected": false,
"text": "procedure SetNewTime(aDateTime: TDateTime; aMonths: Integer);\nvar\n lSystemTime: TSystemTime;\n lTimeZone: TTimeZoneInformation;\n begin\n GetTimeZoneInformation(lTimeZone);\n aDateTime := aDateTime + (lTimeZone.Bias / 1440);\n DateTimeToSystemTime(aDateTime, lSystemTime);\n Inc(lSystemTime.wMonth, aMonths);\n setSystemTime(lSystemTime);\nend;\n"
},
{
"answer_id": 185518,
"author": "user26293",
"author_id": 26293,
"author_profile": "https://Stackoverflow.com/users/26293",
"pm_score": 0,
"selected": false,
"text": "procedure SetSystemDateTime(aDateTime: TDateTime);\nvar\n lSystemTime: TSystemTime;\n lTimeZone: TTimeZoneInformation;\n begin\n GetTimeZoneInformation(lTimeZone);\n aDateTime := aDateTime + (lTimeZone.Bias / 1440);\n DateTimeToSystemTime(aDateTime, lSystemTime);\n setSystemTime(lSystemTime);\nend;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172/"
] |
180,005
|
<p>This Linq to SQL query ...</p>
<pre><code> Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country)
</code></pre>
<p>... is generating this SQL:</p>
<pre><code>SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country]
FROM [dbo].[Concessions] AS [t0]
WHERE [t0].[Country] = ga
</code></pre>
<p>... when what I want is</p>
<pre><code>WHERE [t0].[Country] = 'ga'
</code></pre>
<p>Any ideas why?</p>
|
[
{
"answer_id": 180035,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": -1,
"selected": false,
"text": "Select New With {t.ConcessionID, t.Title, t.Country}\n Select t.ConcessionID, t.Title, t.Country\n"
},
{
"answer_id": 180093,
"author": "mspmsp",
"author_id": 21724,
"author_profile": "https://Stackoverflow.com/users/21724",
"pm_score": 1,
"selected": false,
"text": "t.Country = \"ga\" t.Country == \"ga\""
},
{
"answer_id": 180186,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country]\nFROM [dbo].[Concessions] AS [t0]\nWHERE [t0].[Country] = @p0\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
180,007
|
<p>How would you configure/handle extraneous/optional URLs entities (aliases, maybe)?</p>
<p>SO is a good example:</p>
<ul>
<li>stackoverflow.com/questions/99999999/</li>
<li>stackoverflow.com/questions/99999999/<strong>question-goes-here</strong> (bad example, but I couldn't think of better)</li>
</ul>
<p>Amazon URLs are even more confusing (e.g., the <a href="https://rads.stackoverflow.com/amzn/click/com/B000FI73MA" rel="nofollow noreferrer" rel="nofollow noreferrer">Kindle</a>)</p>
<ul>
<li>amazon.com/gp/product/B000FI73MA/</li>
<li>amazon.com/<strong>Kindle-Amazons-Wireless-Reading-Device</strong>/dp/B000FI73MA/</li>
</ul>
<p>[<strong>EDIT</strong>] This probably isn't the best plan-of-action, but I'm really asking this in general vs. for any single server.</p>
|
[
{
"answer_id": 180068,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 1,
"selected": false,
"text": "RewriteRule ^([^\\/]+)\\/([^\\/]+)\\/(.*) index.php?controller=$1&view=$2&args=$3\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15031/"
] |
180,030
|
<p>In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem.</p>
<p>In Vista it instead returns the date that the picture is copied from the camera.</p>
<p>How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".</p>
|
[
{
"answer_id": 180455,
"author": "sepang",
"author_id": 25930,
"author_profile": "https://Stackoverflow.com/users/25930",
"pm_score": 4,
"selected": false,
"text": "Image myImage = Image.FromFile(@\"C:\\temp\\IMG_0325.JPG\");\nPropertyItem propItem = myImage.GetPropertyItem(306);\nDateTime dtaken;\n\n//Convert date taken metadata to a DateTime object\nstring sdate = Encoding.UTF8.GetString(propItem.Value).Trim();\nstring secondhalf = sdate.Substring(sdate.IndexOf(\" \"), (sdate.Length - sdate.IndexOf(\" \")));\nstring firsthalf = sdate.Substring(0, 10);\nfirsthalf = firsthalf.Replace(\":\", \"-\");\nsdate = firsthalf + secondhalf;\ndtaken = DateTime.Parse(sdate);\n"
},
{
"answer_id": 7713780,
"author": "kDar",
"author_id": 987801,
"author_profile": "https://Stackoverflow.com/users/987801",
"pm_score": 8,
"selected": true,
"text": "//we init this once so that if the function is repeatedly called\n//it isn't stressing the garbage man\nprivate static Regex r = new Regex(\":\");\n\n//retrieves the datetime WITHOUT loading the whole image\npublic static DateTime GetDateTakenFromImage(string path)\n{\n using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n using (Image myImage = Image.FromStream(fs, false, false))\n {\n PropertyItem propItem = myImage.GetPropertyItem(36867);\n string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), \"-\", 2);\n return DateTime.Parse(dateTaken);\n }\n}\n"
},
{
"answer_id": 35244415,
"author": "Peter Redei",
"author_id": 5892816,
"author_profile": "https://Stackoverflow.com/users/5892816",
"pm_score": 0,
"selected": false,
"text": " //retrieves the datetime WITHOUT loading the whole image\n public static DateTime GetDateTakenFromImage(string path)\n {\n using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n using (Image myImage = Image.FromStream(fs, false, false))\n {\n PropertyItem propItem = null;\n try\n {\n propItem = myImage.GetPropertyItem(36867);\n }\n catch { }\n if (propItem != null)\n {\n string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), \"-\", 2);\n return DateTime.Parse(dateTaken);\n }\n else\n return new FileInfo(path).LastWriteTime;\n }\n }\n"
},
{
"answer_id": 39839380,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": false,
"text": "// Read all metadata from the image\nvar directories = ImageMetadataReader.ReadMetadata(stream);\n\n// Find the so-called Exif \"SubIFD\" (which may be null)\nvar subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();\n\n// Read the DateTime tag value\nvar dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTimeOriginal);\n Image.GetPropertyItem JpegBitmapDecoder BitmapMetadata ImageMetadataReader var directories = JpegMetadataReader.ReadMetadata(stream, new[] { new ExifReader() });\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25930/"
] |
180,032
|
<p>Right now, I have a SQL Query like this one:</p>
<pre><code>SELECT X, Y FROM POINTS
</code></pre>
<p>It returns results like so:</p>
<pre><code>X Y
----------
12 3
15 2
18 12
20 29
</code></pre>
<p>I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag):</p>
<pre><code>XYLIST
----------
12,3,15,2,18,12,20,29
</code></pre>
<p>Is there a way to do this using just SQL?</p>
|
[
{
"answer_id": 180053,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 1,
"selected": false,
"text": "DECLARE @s VarChar(8000)\nSET @s = ''\n\nSELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar) \nFROM POINTS\n\nSELECT @s \n"
},
{
"answer_id": 180060,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 6,
"selected": true,
"text": "DECLARE @XYList varchar(MAX)\nSET @XYList = ''\n\nSELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','\nFROM POINTS\n\n-- Remove last comma\nSELECT LEFT(@XYList, LEN(@XYList) - 1)\n"
},
{
"answer_id": 180375,
"author": "Joshua Carmody",
"author_id": 8409,
"author_profile": "https://Stackoverflow.com/users/8409",
"pm_score": 7,
"selected": false,
"text": "SELECT STUFF(( SELECT ',' + X + ',' + Y\n FROM Points\n FOR\n XML PATH('')\n ), 1, 1, '') AS XYList\n"
},
{
"answer_id": 181249,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 4,
"selected": false,
"text": "COALESCE DECLARE @XYList AS varchar(MAX) -- Leave as NULL\n\nSELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y)\nFROM POINTS\n"
},
{
"answer_id": 51291223,
"author": "Carter Medlin",
"author_id": 324479,
"author_profile": "https://Stackoverflow.com/users/324479",
"pm_score": 4,
"selected": false,
"text": "STRING_AGG SELECT STRING_AGG (X + ',' + Y, ',') AS XYLIST\nFROM POINTS\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8409/"
] |
180,052
|
<p>Is it possible to check out subdirectories of a repository in Git?</p>
<p>Imagine I am setting up a new WordPress installation. I will create two new directories for my plugin and theme customization:</p>
<ul>
<li><code>wordpress/wp-content/plugins/myplugins/</code> </li>
<li><code>wordpress/wp-content/themes/mytheme/</code></li>
</ul>
<p>I want to maintain these directories via Git. In Subversion, I would accomplish this by having <code>trunk/myplugins/</code> and <code>trunk/mytheme/</code> directories and checking out subdirectories. Does Git have a way to accomplish the same task using a single repository?</p>
<p>I could just be missing the boat on some Git paradigm, as a long time SVN user with little exposure to Git.</p>
<p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/466303/git-branches-with-completely-different-content">Multiple branches</a> storing different content is an interesting way to handle this.</p>
|
[
{
"answer_id": 180150,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 4,
"selected": false,
"text": "mytheme myplugins"
},
{
"answer_id": 184675,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": false,
"text": ".git"
},
{
"answer_id": 52270636,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "git clone --filter d1 git clone \\\n --depth 1 \\\n --filter=blob:none \\\n --no-checkout \\\n https://github.com/cirosantilli/test-git-partial-clone \\\n;\ncd test-git-partial-clone\ngit checkout master -- d1\n"
},
{
"answer_id": 57959405,
"author": "W.Perrin",
"author_id": 7720976,
"author_profile": "https://Stackoverflow.com/users/7720976",
"pm_score": 0,
"selected": false,
"text": "shell regex git regex git checkout commit_id */*.bat # *.bat in 1-depth subdir exclude current dir, shell regex \ngit checkout commit_id '*.bat' # *.bat in all subdir include current dir, git regex\n subdir git checkout master */*/wp-content/*/*\ngit checkout master '*/wp-content/*'\n"
},
{
"answer_id": 59513164,
"author": "Yuliia Ashomok",
"author_id": 3627736,
"author_profile": "https://Stackoverflow.com/users/3627736",
"pm_score": 0,
"selected": false,
"text": "git checkout [some_dir|file.txt]\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7675/"
] |
180,064
|
<p>Error message:</p>
<blockquote>
<p>fatal: git checkout: updating paths is incompatible with switching branches/forcing</p>
</blockquote>
<p>How to get past this Git checkout error?</p>
|
[
{
"answer_id": 180229,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": true,
"text": "git checkout HEAD $blah git checkout $blah"
},
{
"answer_id": 414223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "git checkout -f $blah git checkout --help rm $blah && git checkout $blah"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
180,075
|
<p>If I create a Stored Procedure in SQL and call it (<code>EXEC spStoredProcedure</code>) within the BEGIN/END TRANSACTION, does this other stored procedure also fall into the transaction?</p>
<p>I didn't know if it worked like try/catches in C#.</p>
|
[
{
"answer_id": 180195,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 4,
"selected": false,
"text": " BEGIN TRY\n BEGIN TRANSACTION\n\n DO SOMETHING\n\n COMMIT\n END TRY\n BEGIN CATCH\n IF @@TRANCOUNT > 0\n ROLLBACK\n\n -- Raise an error with the details of the exception\n DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int\n SELECT @ErrMsg = ERROR_MESSAGE(),\n @ErrSeverity = ERROR_SEVERITY()\n\n RAISERROR(@ErrMsg, @ErrSeverity, 1)\n END CATCH\n"
},
{
"answer_id": 180315,
"author": "James",
"author_id": 2719,
"author_profile": "https://Stackoverflow.com/users/2719",
"pm_score": 3,
"selected": false,
"text": "IF @@TRANCOUNT > 0 ROLLBACK\n IF(@@TRANCOUNT = 1) ROLLBACK TRAN\nELSE IF(@@TRANCOUNT > 1) COMMIT TRAN\nRETURN @error\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
180,095
|
<p>I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.</p>
<p>What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.</p>
<p>PS: <a href="https://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly">This</a> question/answer deals with the problem in a generic way; how specifically should I solve it?</p>
|
[
{
"answer_id": 180152,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "try:\n # do something\nexcept socket.error, e:\n # A socket error\nexcept IOError, e:\n if e.errno == errno.EPIPE:\n # EPIPE error\n else:\n # Other error\n"
},
{
"answer_id": 180378,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 2,
"selected": false,
"text": "SIGPIPE EPIPE"
},
{
"answer_id": 180421,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": -1,
"selected": false,
"text": "try:\n # do something\nexcept IOError, e:\n # ooops, check the attributes of e to see precisely what happened.\n if e.errno != 23:\n # I don't know how to handle this\n raise\n"
},
{
"answer_id": 180922,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 6,
"selected": false,
"text": "socket.error: (32, 'Broken pipe') import socket, errno, time\n\n# setup socket to listen for incoming connections\ns = socket.socket()\ns.bind(('localhost', 1234))\ns.listen(1)\nremote, address = s.accept()\n\nprint \"Got connection from: \", address\n\nwhile 1:\n try:\n remote.send(\"message to peer\\n\")\n time.sleep(1)\n except socket.error, e:\n if isinstance(e.args, tuple):\n print \"errno is %d\" % e[0]\n if e[0] == errno.EPIPE:\n # remote peer disconnected\n print \"Detected remote disconnect\"\n else:\n # determine and handle different error\n pass\n else:\n print \"socket error \", e\n remote.close()\n break\n except IOError, e:\n # Hmmm, Can IOError actually be raised by the socket module?\n print \"Got IOError: \", e\n break\n select.select() poll select socket.recv()"
},
{
"answer_id": 46946689,
"author": "yuan",
"author_id": 7832332,
"author_profile": "https://Stackoverflow.com/users/7832332",
"pm_score": -1,
"selected": false,
"text": "$ packet_write_wait: Connection to 10.. port 22: Broken pipe\n [1] Done nohup python -u add_asc_dec.py > add2.log 2>&1\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24208/"
] |
180,097
|
<p>I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.</p>
<p>The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:</p>
<pre><code>doSomething int double
doSomethingElse java.lang.String boolean
</code></pre>
<p>If the input was something like <code>java.lang.String</code>, I know I could use <code>Class.forName("java.lang.String")</code> to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?</p>
<p><strong>Edit:</strong>
Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the <code>ClassUtils</code> class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.</p>
|
[
{
"answer_id": 180139,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 5,
"selected": false,
"text": "Class int.class Integer.TYPE TYPE forName Class clazz = Class.forName(\"java.lang.Integer\");\nClass intClass = clazz.getField(\"TYPE\").get(null);\n\nintClass.equals(int.class); // => true\n"
},
{
"answer_id": 180477,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 4,
"selected": false,
"text": "void someWhere(){\n String methodDescription = \"doSomething int double java.lang.Integer java.lang.String\"\n String [] parts = methodDescription.split();\n String methodName= parts[0]\n Class [] paramsTypes = getParamTypes( parts ); // Well, not all the array, but a, sub array from 1 to arr.length.. \n\n Method m = someObject.class.getMethod( methodName, paramTypes );\n etc. etc etc.\n}\n\npublic Class[] paramTypes( String [] array ){\n List<Class> list = new ArrayList<Class>();\n for( String type : array ) {\n if( builtInMap.contains( type )) {\n list.add( builtInMap.get( type ) );\n }else{\n list.add( Class.forName( type ) );\n }\n }\n return list.toArray();\n} \n\n // That's right.\nMap<String,Class> builtInMap = new HashMap<String,Class>();{\n builtInMap.put(\"int\", Integer.TYPE );\n builtInMap.put(\"long\", Long.TYPE );\n builtInMap.put(\"double\", Double.TYPE );\n builtInMap.put(\"float\", Float.TYPE );\n builtInMap.put(\"bool\", Boolean.TYPE );\n builtInMap.put(\"char\", Character.TYPE );\n builtInMap.put(\"byte\", Byte.TYPE );\n builtInMap.put(\"void\", Void.TYPE );\n builtInMap.put(\"short\", Short.TYPE );\n}\n"
},
{
"answer_id": 646735,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 2,
"selected": false,
"text": "private static final Map<String, Class> BUILT_IN_MAP = \n new ConcurrentHashMap<String, Class>();\n\nstatic {\n for (Class c : new Class[]{void.class, boolean.class, byte.class, char.class, \n short.class, int.class, float.class, double.class, long.class})\n BUILT_IN_MAP.put(c.getName(), c);\n}\n\npublic static Class forName(String name) throws ClassNotFoundException {\n Class c = BUILT_IN_MAP.get(name);\n if (c == null)\n // assumes you have only one class loader!\n BUILT_IN_MAP.put(name, c = Class.forName(name));\n return c;\n}\n"
},
{
"answer_id": 12668403,
"author": "Arham",
"author_id": 1710942,
"author_profile": "https://Stackoverflow.com/users/1710942",
"pm_score": 2,
"selected": false,
"text": "public class CheckPrimitve {\n public static void main(String[] args) {\n Sample s = new Sample();\n try {\n System.out.println(s.getClass().getField(\"sampleInt\").getType() == int.class); // returns true\n System.out.println(s.getClass().getField(\"sampleInt\").getType().isPrimitive()); // returns true\n } catch (NoSuchFieldException e) { \n e.printStackTrace();\n } catch (SecurityException e) {\n e.printStackTrace();\n } \n }\n}\n\nclass Sample {\n public int sampleInt;\n public Sample() {\n sampleInt = 10;\n }\n}\n public class CheckPrimitve {\n public static void main(String[] args) {\n int i = 3;\n Object o = i;\n System.out.println(o.getClass().getSimpleName().equals(\"Integer\")); // returns true\n Field[] fields = o.getClass().getFields();\n for(Field field:fields) {\n System.out.println(field.getType()); // returns {int, int, class java.lang.Class, int}\n }\n }\n }\n"
},
{
"answer_id": 42673473,
"author": "Adrodoc",
"author_id": 4149050,
"author_profile": "https://Stackoverflow.com/users/4149050",
"pm_score": 1,
"selected": false,
"text": "com.google.common.primitives.Primitives"
},
{
"answer_id": 59038893,
"author": "LSafer",
"author_id": 11816777,
"author_profile": "https://Stackoverflow.com/users/11816777",
"pm_score": 0,
"selected": false,
"text": "/**\n * Get an array class of the given class.\n *\n * @param klass to get an array class of\n * @param <C> the targeted class\n * @return an array class of the given class\n */\npublic static <C> Class<C[]> arrayClass(Class<C> klass) {\n return (Class<C[]>) Array.newInstance(klass, 0).getClass();\n}\n\n/**\n * Get the class that extends {@link Object} that represent the given class.\n *\n * @param klass to get the object class of\n * @return the class that extends Object class and represent the given class\n */\npublic static Class<?> objectiveClass(Class<?> klass) {\n Class<?> component = klass.getComponentType();\n if (component != null) {\n if (component.isPrimitive() || component.isArray())\n return Reflect.arrayClass(Reflect.objectiveClass(component));\n } else if (klass.isPrimitive()) {\n if (klass == char.class)\n return Character.class;\n if (klass == int.class)\n return Integer.class;\n if (klass == boolean.class)\n return Boolean.class;\n if (klass == byte.class)\n return Byte.class;\n if (klass == double.class)\n return Double.class;\n if (klass == float.class)\n return Float.class;\n if (klass == long.class)\n return Long.class;\n if (klass == short.class)\n return Short.class;\n }\n\n return klass;\n}\n\n/**\n * Get the class that don't extends {@link Object} from the given class.\n *\n * @param klass to get the non-object class of\n * @return the non-object class of the given class\n * @throws IllegalArgumentException when the given class don't have a primitive type\n */\npublic static Class<?> primitiveClass(Class<?> klass) {\n if (klass == Character.class)\n return char.class;\n if (klass == Integer.class)\n return int.class;\n if (klass == Boolean.class)\n return boolean.class;\n if (klass == Byte.class)\n return byte.class;\n if (klass == Double.class)\n return double.class;\n if (klass == Float.class)\n return float.class;\n if (klass == Long.class)\n return long.class;\n if (klass == Short.class)\n return short.class;\n\n throw new IllegalArgumentException(klass + \" don't have a primitive type\");\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3005/"
] |
180,103
|
<p>I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document?</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
// ???
});
</script>
</code></pre>
|
[
{
"answer_id": 180118,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 5,
"selected": false,
"text": "$(document).ready(function ()\n{\n document.title = \"Hello World!\";\n});\n $(function ()\n{\n // this is a shorthand for the whole document-ready thing\n // In my opinion, it's more readable \n});\n"
},
{
"answer_id": 180122,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\">\n$(document).ready(function() {\n\n $(this).attr(\"title\", \"sometitle\");\n\n});\n</script>\n"
},
{
"answer_id": 180129,
"author": "dpan",
"author_id": 8911,
"author_profile": "https://Stackoverflow.com/users/8911",
"pm_score": 9,
"selected": true,
"text": "<script type=\"text/javascript\">\n\n $(document).ready(function() {\n document.title = 'blah';\n });\n\n</script>\n"
},
{
"answer_id": 188868,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "@page_title <%= @page_title || 'Default Title' %>"
},
{
"answer_id": 4063283,
"author": "vasio",
"author_id": 492771,
"author_profile": "https://Stackoverflow.com/users/492771",
"pm_score": 6,
"selected": false,
"text": "$('title').text('hi') document.title = 'new title';"
},
{
"answer_id": 4989558,
"author": "Albert",
"author_id": 615824,
"author_profile": "https://Stackoverflow.com/users/615824",
"pm_score": 6,
"selected": false,
"text": "$(document).attr(\"title\", \"New Title\");\n"
},
{
"answer_id": 8063034,
"author": "andreas",
"author_id": 1037340,
"author_profile": "https://Stackoverflow.com/users/1037340",
"pm_score": -1,
"selected": false,
"text": "$.get('get_title.php',function(*respons*){\n title=*respons* + 'whatever you want' \n $(document).attr('title',title)\n})\n"
},
{
"answer_id": 11171548,
"author": "John F",
"author_id": 1477123,
"author_profile": "https://Stackoverflow.com/users/1477123",
"pm_score": 3,
"selected": false,
"text": "$('html head').find('title').text(\"My New Page Title\");\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
180,107
|
<p>I have an HTML wrapper that contains a Flex application, is there an Event that I can listen on, that is triggered when a user leaves the HTML wrapper either by navigation arrows or closing the browser?</p>
<p>Thanks. </p>
|
[
{
"answer_id": 180219,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 1,
"selected": false,
"text": "window.onbeforeunload = function(e) {\n // Browser will pop up a confirmation dialog, with some text before\n // and after your return string; try it in different browsers to\n // see how they behave.\n return 'String to confirm';\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
180,119
|
<p>I recently started working on a small game for my own amusement, using Microsoft XNA and C#. My question is in regards to designing a game object and the objects that inherit it. I'm going to define a game object as something that can be rendered on screen. So for this, I decided to make a base class which all other objects that will need to be rendered will inherit, called GameObject. The code below is the class I made:</p>
<pre><code>class GameObject
{
private Model model = null;
private float scale = 1f;
private Vector3 position = Vector3.Zero;
private Vector3 rotation = Vector3.Zero;
private Vector3 velocity = Vector3.Zero;
private bool alive = false;
protected ContentManager content;
#region Constructors
public GameObject(ContentManager content, string modelResource)
{
this.content = content;
model = content.Load<Model>(modelResource);
}
public GameObject(ContentManager content, string modelResource, bool alive)
: this(content, modelResource)
{
this.alive = alive;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale)
: this(content, modelResource, alive)
{
this.scale = scale;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position)
: this(content, modelResource, alive, scale)
{
this.position = position;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation)
: this(content, modelResource, alive, scale, position)
{
this.rotation = rotation;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity)
: this(content, modelResource, alive, scale, position, rotation)
{
this.velocity = velocity;
}
#endregion
}
</code></pre>
<p>I've left out extra methods that do things such as rotate, move, and draw the object. Now if I wanted to create another object, like a ship, I'd create a Ship class, which would inherit GameObject. Sample code below:</p>
<pre><code>class Ship : GameObject
{
private int num_missiles = 20; // the number of missiles this ship can have alive at any given time
private Missile[] missiles;
private float max_missile_distance = 3000f; // max distance a missile can be from the ship before it dies
#region Constructors
public Ship(ContentManager content, string modelResource)
: base(content, modelResource)
{
InitShip();
}
public Ship(ContentManager content, string modelResource , bool alive)
: base(content, modelResource, alive)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale)
: base(content, modelResource, alive, scale)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position)
: base(content, modelResource, alive, scale, position)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation)
: base(content, modelResource, alive, scale, position, rotation)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity)
: base(content, modelResource, alive, scale, position, rotation, velocity)
{
InitShip();
}
#endregion
}
</code></pre>
<p>Again, I've left out any extra Ship-specific methods, like firing a missile. Do you think that this sort of design is good or should it be improved somehow or changed completely? It seems like the constructors for child classes is messy, but maybe that's the only way to do it. I've never done anything like this and am wondering if I'm way off track.</p>
<hr>
<p>Thanks to everyone that left an answer. They were all very helpful. There seems to be a general consensus that changing it around to use an MVC pattern would be best. I'm going to look further into exactly how to do that. I'll also be removing most of the constructors and will have just one constructor, because all of the arguments after modelResource aren't necessary to create the object, and they can all be changed later through method calls.</p>
|
[
{
"answer_id": 180382,
"author": "Parappa",
"author_id": 9974,
"author_profile": "https://Stackoverflow.com/users/9974",
"pm_score": 1,
"selected": false,
"text": "// main loop\nwhile (true) {\n ProcessInput(); // handle input events\n UpdateGameWorld(); // update game objects\n RenderFrame(); // each render object draws itself\n}\n"
},
{
"answer_id": 180591,
"author": "Jeff B",
"author_id": 25879,
"author_profile": "https://Stackoverflow.com/users/25879",
"pm_score": 3,
"selected": false,
"text": "new Ship(content, \"resource\", true, null, null, null, null);\n GameObjectParams params(content, \"resource\");\nparams.IsAlive = true;\nnew Ship(params);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19649/"
] |
180,158
|
<ol>
<li>How do I get a method's execution time? </li>
<li>Is there a <code>Timer</code> utility class for things like timing how long a task takes, etc? </li>
</ol>
<p>Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.</p>
|
[
{
"answer_id": 180179,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 8,
"selected": false,
"text": "long startTime = System.currentTimeMillis();\n\ndoReallyLongThing();\n\nlong endTime = System.currentTimeMillis();\n\nSystem.out.println(\"That took \" + (endTime - startTime) + \" milliseconds\");\n"
},
{
"answer_id": 180180,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 3,
"selected": false,
"text": "long start_time = System.currentTimeMillis();\nobject.method();\nlong end_time = System.currentTimeMillis();\nlong execution_time = end_time - start_time;\n"
},
{
"answer_id": 180191,
"author": "Diastrophism",
"author_id": 18093,
"author_profile": "https://Stackoverflow.com/users/18093",
"pm_score": 11,
"selected": true,
"text": "long startTime = System.nanoTime();\nmethodToTime();\nlong endTime = System.nanoTime();\n\nlong duration = (endTime - startTime); //divide by 1000000 to get milliseconds.\n"
},
{
"answer_id": 180192,
"author": "Ryan Rodemoyer",
"author_id": 1444511,
"author_profile": "https://Stackoverflow.com/users/1444511",
"pm_score": 3,
"selected": false,
"text": "long startTime = System.currentTimeMillis();\n// code goes here\nlong finishTime = System.currentTimeMillis();\nlong elapsedTime = finishTime - startTime; // elapsed time in milliseconds\n"
},
{
"answer_id": 180204,
"author": "Horst Gutmann",
"author_id": 22312,
"author_profile": "https://Stackoverflow.com/users/22312",
"pm_score": 3,
"selected": false,
"text": "long start = System.currentTimeMillis();\n// ... do something ...\nlong end = System.currentTimeMillis();\n"
},
{
"answer_id": 181571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "public @interface Trace {\n boolean showParameters();\n}\n\n@Aspect\npublic class TraceAspect {\n [...]\n @Around(\"tracePointcut() && @annotation(trace) && !within(TraceAspect)\")\n public Object traceAdvice ( ProceedingJintPoint jP, Trace trace ) {\n\n Object result;\n // initilize timer\n\n try { \n result = jp.procced();\n } finally { \n // calculate execution time \n }\n\n return result;\n }\n [...]\n}\n"
},
{
"answer_id": 264547,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 4,
"selected": false,
"text": " int runs = 0, runsPerRound = 10;\n long begin = System.nanoTime(), end;\n do {\n for (int i=0; i<runsPerRound; ++i) timedMethod();\n end = System.nanoTime();\n runs += runsPerRound;\n runsPerRound *= 2;\n } while (runs < Integer.MAX_VALUE / 2 && 1000000000L > end - begin);\n System.out.println(\"Time for timedMethod() is \" + \n 0.000000001 * (end-begin) / runs + \" seconds\");\n"
},
{
"answer_id": 8365561,
"author": "Narayan",
"author_id": 1078611,
"author_profile": "https://Stackoverflow.com/users/1078611",
"pm_score": 4,
"selected": false,
"text": "org.apache.commons.lang.time.StopWatch sw = new org.apache.commons.lang.time.StopWatch();\n\nSystem.out.println(\"getEventFilterTreeData :: Start Time : \" + sw.getTime());\nsw.start();\n\n// Method execution code\n\nsw.stop();\nSystem.out.println(\"getEventFilterTreeData :: End Time : \" + sw.getTime());\n"
},
{
"answer_id": 9454173,
"author": "mergenchik",
"author_id": 1233031,
"author_profile": "https://Stackoverflow.com/users/1233031",
"pm_score": 3,
"selected": false,
"text": "String watchTag = \"target.SomeMethod\";\nStopWatch stopWatch = new LoggingStopWatch(watchTag);\nResult result = null; // Result is a type of a return value of a method\ntry {\n result = target.SomeMethod();\n stopWatch.stop(watchTag + \".success\");\n} catch (Exception e) {\n stopWatch.stop(watchTag + \".fail\", \"Exception was \" + e);\n throw e; \n}\n"
},
{
"answer_id": 11047430,
"author": "iceberg",
"author_id": 1436703,
"author_profile": "https://Stackoverflow.com/users/1436703",
"pm_score": 4,
"selected": false,
"text": "import java.util.concurrent.TimeUnit;\n\nlong startTime = System.currentTimeMillis();\n........\n........\n........\nlong finishTime = System.currentTimeMillis();\n\nString diff = millisToShortDHMS(finishTime - startTime);\n\n\n /**\n * converts time (in milliseconds) to human-readable format\n * \"<dd:>hh:mm:ss\"\n */\n public static String millisToShortDHMS(long duration) {\n String res = \"\";\n long days = TimeUnit.MILLISECONDS.toDays(duration);\n long hours = TimeUnit.MILLISECONDS.toHours(duration)\n - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));\n long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)\n - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));\n long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)\n - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));\n if (days == 0) {\n res = String.format(\"%02d:%02d:%02d\", hours, minutes, seconds);\n }\n else {\n res = String.format(\"%dd%02d:%02d:%02d\", days, hours, minutes, seconds);\n }\n return res;\n }\n"
},
{
"answer_id": 14186259,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 3,
"selected": false,
"text": "@Loggable @Loggable(Loggable.DEBUG)\npublic String getSomeResult() {\n // return some value\n}\n DEBUG"
},
{
"answer_id": 15395499,
"author": "Dmitry Kalashnikov",
"author_id": 857165,
"author_profile": "https://Stackoverflow.com/users/857165",
"pm_score": 8,
"selected": false,
"text": "import com.google.common.base.Stopwatch;\n\nStopwatch timer = Stopwatch.createStarted();\n//method invocation\nLOG.info(\"Method took: \" + timer.stop());\n Stopwatch timer = Stopwatch.createUnstarted();\nfor (...) {\n timer.start();\n methodToTrackTimeFor();\n timer.stop();\n methodNotToTrackTimeFor();\n}\nLOG.info(\"Method took: \" + timer);\n"
},
{
"answer_id": 15789819,
"author": "Maciek Kreft",
"author_id": 203459,
"author_profile": "https://Stackoverflow.com/users/203459",
"pm_score": 3,
"selected": false,
"text": "new Timer(\"\"){{\n // code to time \n}}.timeMe();\n\n\n\npublic class Timer {\n\n private final String timerName;\n private long started;\n\n public Timer(String timerName) {\n this.timerName = timerName;\n this.started = System.currentTimeMillis();\n }\n\n public void timeMe() {\n System.out.println(\n String.format(\"Execution of '%s' takes %dms.\", \n timerName, \n started-System.currentTimeMillis()));\n }\n\n}\n"
},
{
"answer_id": 17442594,
"author": "hmitcs",
"author_id": 2545547,
"author_profile": "https://Stackoverflow.com/users/2545547",
"pm_score": 1,
"selected": false,
"text": "System.nanoTime()"
},
{
"answer_id": 20416934,
"author": "gifpif",
"author_id": 2093934,
"author_profile": "https://Stackoverflow.com/users/2093934",
"pm_score": 2,
"selected": false,
"text": "long startTime = System.currentTimeMillis();\n//@ Method call\nSystem.out.println(\"Total time [ms]: \" + (System.currentTimeMillis() - startTime)); \n"
},
{
"answer_id": 20803059,
"author": "Denis Kutlubaev",
"author_id": 751641,
"author_profile": "https://Stackoverflow.com/users/751641",
"pm_score": 2,
"selected": false,
"text": "long startTime = System.nanoTime();\n\nmethodCode ...\n\nlong endTime = System.nanoTime();\ndouble duration = (double)(endTime - startTime) / (Math.pow(10, 9));\nLog.v(TAG, \"MethodName time (s) = \" + duration);\n"
},
{
"answer_id": 22894871,
"author": "TondaCZE",
"author_id": 2272158,
"author_profile": "https://Stackoverflow.com/users/2272158",
"pm_score": 6,
"selected": false,
"text": "System.currentTimeMillis(); java.lang.management getCpuTime() import java.lang.management.ManagementFactory;\nimport java.lang.management.ThreadMXBean;\n\npublic class CPUUtils {\n\n /** Get CPU time in nanoseconds. */\n public static long getCpuTime( ) {\n ThreadMXBean bean = ManagementFactory.getThreadMXBean( );\n return bean.isCurrentThreadCpuTimeSupported( ) ?\n bean.getCurrentThreadCpuTime( ) : 0L;\n }\n\n /** Get user time in nanoseconds. */\n public static long getUserTime( ) {\n ThreadMXBean bean = ManagementFactory.getThreadMXBean( );\n return bean.isCurrentThreadCpuTimeSupported( ) ?\n bean.getCurrentThreadUserTime( ) : 0L;\n }\n\n /** Get system time in nanoseconds. */\n public static long getSystemTime( ) {\n ThreadMXBean bean = ManagementFactory.getThreadMXBean( );\n return bean.isCurrentThreadCpuTimeSupported( ) ?\n (bean.getCurrentThreadCpuTime( ) - bean.getCurrentThreadUserTime( )) : 0L;\n }\n\n}\n"
},
{
"answer_id": 25884289,
"author": "leo",
"author_id": 510583,
"author_profile": "https://Stackoverflow.com/users/510583",
"pm_score": 2,
"selected": false,
"text": "System.nanoTime() : 750ns System.currentTimeMillis() : 18ns System.nanoTime()"
},
{
"answer_id": 27990107,
"author": "Alexey Pismenskiy",
"author_id": 2495060,
"author_profile": "https://Stackoverflow.com/users/2495060",
"pm_score": 2,
"selected": false,
"text": "measure {\n // your operation here\n}\n public interface Timer {\n void wrap();\n}\n\n\npublic class Logger {\n\n public static void logTime(Timer timer) {\n long start = System.currentTimeMillis();\n timer.wrap();\n System.out.println(\"\" + (System.currentTimeMillis() - start) + \"ms\");\n }\n\n public static void main(String a[]) {\n Logger.logTime(new Timer() {\n public void wrap() {\n // Your method here\n timeConsumingOperation();\n }\n });\n\n }\n\n public static void timeConsumingOperation() {\n for (int i = 0; i<=10000; i++) {\n System.out.println(\"i=\" +i);\n }\n }\n}\n"
},
{
"answer_id": 28177737,
"author": "msysmilu",
"author_id": 2251011,
"author_profile": "https://Stackoverflow.com/users/2251011",
"pm_score": 2,
"selected": false,
"text": "public class Stopwatch {\n static long startTime;\n static long splitTime;\n static long endTime;\n\n public Stopwatch() {\n start();\n }\n\n public void start() {\n startTime = System.currentTimeMillis();\n splitTime = System.currentTimeMillis();\n endTime = System.currentTimeMillis();\n }\n\n public void split() {\n split(\"\");\n }\n\n public void split(String tag) {\n endTime = System.currentTimeMillis();\n System.out.println(\"Split time for [\" + tag + \"]: \" + (endTime - splitTime) + \" ms\");\n splitTime = endTime;\n }\n\n public void end() {\n end(\"\");\n }\n public void end(String tag) {\n endTime = System.currentTimeMillis();\n System.out.println(\"Final time for [\" + tag + \"]: \" + (endTime - startTime) + \" ms\");\n }\n}\n public static Schedule getSchedule(Activity activity_context) {\n String scheduleJson = null;\n Schedule schedule = null;\n/*->*/ Stopwatch stopwatch = new Stopwatch();\n\n InputStream scheduleJsonInputStream = activity_context.getResources().openRawResource(R.raw.skating_times);\n/*->*/ stopwatch.split(\"open raw resource\");\n\n scheduleJson = FileToString.convertStreamToString(scheduleJsonInputStream);\n/*->*/ stopwatch.split(\"file to string\");\n\n schedule = new Gson().fromJson(scheduleJson, Schedule.class);\n/*->*/ stopwatch.split(\"parse Json\");\n/*->*/ stopwatch.end(\"Method getSchedule\"); \n return schedule;\n}\n Split time for [file to string]: 672 ms\nSplit time for [parse Json]: 893 ms\nFinal time for [get Schedule]: 1565 ms\n"
},
{
"answer_id": 28274381,
"author": "Sufiyan Ghori",
"author_id": 1149423,
"author_profile": "https://Stackoverflow.com/users/1149423",
"pm_score": 7,
"selected": false,
"text": "Instant start = Instant.now();\nThread.sleep(5000);\nInstant end = Instant.now();\nSystem.out.println(Duration.between(start, end));\n PT5S\n"
},
{
"answer_id": 30975902,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 2,
"selected": false,
"text": "Instant Instant start = Instant.now();\ntry {\n Thread.sleep(7000);\n} catch (InterruptedException e) {\n e.printStackTrace();\n}\nInstant end = Instant.now();\nSystem.out.println(Duration.between(start, end));\n PT7.001S"
},
{
"answer_id": 31853341,
"author": "Sunil Manheri",
"author_id": 300538,
"author_profile": "https://Stackoverflow.com/users/300538",
"pm_score": 4,
"selected": false,
"text": "StopWatch stopWatch = new StopWatch(\"Performance Test Result\");\n\nstopWatch.start(\"Method 1\");\ndoSomething1();//method to test\nstopWatch.stop();\n\nstopWatch.start(\"Method 2\");\ndoSomething2();//method to test\nstopWatch.stop();\n\nSystem.out.println(stopWatch.prettyPrint());\n StopWatch 'Performance Test Result': running time (millis) = 12829\n-----------------------------------------\nms % Task name\n-----------------------------------------\n11907 036% Method 1\n00922 064% Method 2\n @Around(\"execution(* my.package..*.*(..))\")\npublic Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {\n StopWatch stopWatch = new StopWatch();\n stopWatch.start();\n Object retVal = joinPoint.proceed();\n stopWatch.stop();\n log.info(\" execution time: \" + stopWatch.getTotalTimeMillis() + \" ms\");\n return retVal;\n}\n"
},
{
"answer_id": 33927764,
"author": "Stefan",
"author_id": 3226909,
"author_profile": "https://Stackoverflow.com/users/3226909",
"pm_score": 5,
"selected": false,
"text": "Object returnValue = TimeIt.printTime(() -> methodeWithReturnValue());\n//do stuff with your returnValue\n public class TimeIt {\n\npublic static <T> T printTime(Callable<T> task) {\n T call = null;\n try {\n long startTime = System.currentTimeMillis();\n call = task.call();\n System.out.print((System.currentTimeMillis() - startTime) / 1000d + \"s\");\n } catch (Exception e) {\n //...\n }\n return call;\n}\n}\n Function<Integer, Integer> yourFunction= (n) -> {\n return IntStream.range(0, n).reduce(0, (a, b) -> a + b);\n };\n\nInteger returnValue = TimeIt.printTime2(yourFunction).apply(10000);\n//do stuff with your returnValue\n\npublic static <T, R> Function<T, R> printTime2(Function<T, R> task) {\n return (t) -> {\n long startTime = System.currentTimeMillis();\n R apply = task.apply(t);\n System.out.print((System.currentTimeMillis() - startTime) / 1000d\n + \"s\");\n return apply;\n };\n}\n"
},
{
"answer_id": 34086460,
"author": "Yash",
"author_id": 5081877,
"author_profile": "https://Stackoverflow.com/users/5081877",
"pm_score": 7,
"selected": false,
"text": "Date startDate = Calendar.getInstance().getTime();\nlong d_StartTime = new Date().getTime();\nThread.sleep(1000 * 4);\nDate endDate = Calendar.getInstance().getTime();\nlong d_endTime = new Date().getTime();\nSystem.out.format(\"StartDate : %s, EndDate : %s \\n\", startDate, endDate);\nSystem.out.format(\"Milli = %s, ( D_Start : %s, D_End : %s ) \\n\", (d_endTime - d_StartTime),d_StartTime, d_endTime);\n long startTime = System.currentTimeMillis();\nThread.sleep(1000 * 4);\nlong endTime = System.currentTimeMillis();\nlong duration = (endTime - startTime); \nSystem.out.format(\"Milli = %s, ( S_Start : %s, S_End : %s ) \\n\", duration, startTime, endTime );\nSystem.out.println(\"Human-Readable format : \"+millisToShortDHMS( duration ) );\n public static String millisToShortDHMS(long duration) {\n String res = \"\"; // java.util.concurrent.TimeUnit;\n long days = TimeUnit.MILLISECONDS.toDays(duration);\n long hours = TimeUnit.MILLISECONDS.toHours(duration) -\n TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));\n long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) -\n TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));\n long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) -\n TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));\n long millis = TimeUnit.MILLISECONDS.toMillis(duration) - \n TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(duration));\n\n if (days == 0) res = String.format(\"%02d:%02d:%02d.%04d\", hours, minutes, seconds, millis);\n else res = String.format(\"%dd %02d:%02d:%02d.%04d\", days, hours, minutes, seconds, millis);\n return res;\n}\n com.google.common.base.Stopwatch g_SW = Stopwatch.createUnstarted();\ng_SW.start();\nThread.sleep(1000 * 4);\ng_SW.stop();\nSystem.out.println(\"Google StopWatch : \"+g_SW);\n org.apache.commons.lang3.time.StopWatch sw = new StopWatch();\nsw.start(); \nThread.sleep(1000 * 4); \nsw.stop();\nSystem.out.println(\"Apache StopWatch : \"+ millisToShortDHMS(sw.getTime()) );\n public static void jodaTime() throws InterruptedException, ParseException{\n java.text.SimpleDateFormat ms_SDF = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss.SSS\");\n String start = ms_SDF.format( new Date() ); // java.util.Date\n\n Thread.sleep(10000);\n\n String end = ms_SDF.format( new Date() ); \n System.out.println(\"Start:\"+start+\"\\t Stop:\"+end);\n\n Date date_1 = ms_SDF.parse(start);\n Date date_2 = ms_SDF.parse(end); \n Interval interval = new org.joda.time.Interval( date_1.getTime(), date_2.getTime() );\n Period period = interval.toPeriod(); //org.joda.time.Period\n\n System.out.format(\"%dY/%dM/%dD, %02d:%02d:%02d.%04d \\n\", \n period.getYears(), period.getMonths(), period.getDays(),\n period.getHours(), period.getMinutes(), period.getSeconds(), period.getMillis());\n}\n Instant start = java.time.Instant.now();\n Thread.sleep(1000);\nInstant end = java.time.Instant.now();\nDuration between = java.time.Duration.between(start, end);\nSystem.out.println( between ); // PT1.001S\nSystem.out.format(\"%dD, %02d:%02d:%02d.%04d \\n\", between.toDays(),\n between.toHours(), between.toMinutes(), between.getSeconds(), between.toMillis()); // 0D, 00:00:01.1001 \n StopWatch sw = new org.springframework.util.StopWatch();\nsw.start(\"Method-1\"); // Start a named task\n Thread.sleep(500);\nsw.stop();\n\nsw.start(\"Method-2\");\n Thread.sleep(300);\nsw.stop();\n\nsw.start(\"Method-3\");\n Thread.sleep(200);\nsw.stop();\n\nSystem.out.println(\"Total time in milliseconds for all tasks :\\n\"+sw.getTotalTimeMillis());\nSystem.out.println(\"Table describing all tasks performed :\\n\"+sw.prettyPrint());\n\nSystem.out.format(\"Time taken by the last task : [%s]:[%d]\", \n sw.getLastTaskName(),sw.getLastTaskTimeMillis());\n\nSystem.out.println(\"\\n Array of the data for tasks performed « Task Name: Time Taken\");\nTaskInfo[] listofTasks = sw.getTaskInfo();\nfor (TaskInfo task : listofTasks) {\n System.out.format(\"[%s]:[%d]\\n\", \n task.getTaskName(), task.getTimeMillis());\n}\n Total time in milliseconds for all tasks :\n999\nTable describing all tasks performed :\nStopWatch '': running time (millis) = 999\n-----------------------------------------\nms % Task name\n-----------------------------------------\n00500 050% Method-1\n00299 030% Method-2\n00200 020% Method-3\n\nTime taken by the last task : [Method-3]:[200]\n Array of the data for tasks performed « Task Name: Time Taken\n[Method-1]:[500]\n[Method-2]:[299]\n[Method-3]:[200]\n"
},
{
"answer_id": 41160571,
"author": "timxor",
"author_id": 1482105,
"author_profile": "https://Stackoverflow.com/users/1482105",
"pm_score": 2,
"selected": false,
"text": " long startTime = System.nanoTime();\n // ... methodToTime();\n long endTime = System.nanoTime();\n long duration = (endTime - startTime);\n long seconds = (duration / 1000) % 60;\n // formatedSeconds = (0.xy seconds)\n String formatedSeconds = String.format(\"(0.%d seconds)\", seconds);\n System.out.println(\"formatedSeconds = \"+ formatedSeconds);\n // i.e actual formatedSeconds = (0.52 seconds)\n"
},
{
"answer_id": 41376436,
"author": "StationaryTraveller",
"author_id": 2204803,
"author_profile": "https://Stackoverflow.com/users/2204803",
"pm_score": 2,
"selected": false,
"text": "public class Timer{\n private static long start_time;\n\n public static double tic(){\n return start_time = System.nanoTime();\n }\n\n public static double toc(){\n return (System.nanoTime()-start_time)/1000000000.0;\n }\n\n}\n Timer.tic();\n// Code 1\nSystem.out.println(\"Code 1 runtime: \"+Timer.toc()+\" seconds.\");\n// Code 2\nSystem.out.println(\"(Code 1 + Code 2) runtime: \"+Timer.toc()+\"seconds\");\nTimer.tic();\n// Code 3\nSystem.out.println(\"Code 3 runtime: \"+Timer.toc()+\" seconds.\");\n"
},
{
"answer_id": 44949335,
"author": "Maciel Escudero Bombonato",
"author_id": 1096326,
"author_profile": "https://Stackoverflow.com/users/1096326",
"pm_score": 1,
"selected": false,
"text": "@AroundInvoke @Singleton\npublic class TimedInterceptor implements Serializable {\n\n @AroundInvoke\n public Object logMethod(InvocationContext ic) throws Exception {\n Date start = new Date();\n Object result = ic.proceed();\n Date end = new Date();\n System.out.println(\"time: \" + (end.getTime - start.getTime()));\n return result;\n }\n}\n @Interceptors(TimedInterceptor.class)\npublic void onMessage(final Message message) { ... \n"
},
{
"answer_id": 45413916,
"author": "Justinas Jakavonis",
"author_id": 5962766,
"author_profile": "https://Stackoverflow.com/users/5962766",
"pm_score": 3,
"selected": false,
"text": "<dependencies>\n <dependency>\n <groupId>io.dropwizard.metrics</groupId>\n <artifactId>metrics-core</artifactId>\n <version>${metrics.version}</version>\n </dependency>\n</dependencies>\n @Timed\npublic void exampleMethod(){\n // some code\n}\n final Timer timer = metricsRegistry.timer(\"some_name\");\nfinal Timer.Context context = timer.time();\n// timed code\ncontext.stop();\n @Timed com.example.ExampleService.exampleMethod\n count = 2\n mean rate = 3.11 calls/minute\n 1-minute rate = 0.96 calls/minute\n 5-minute rate = 0.20 calls/minute\n 15-minute rate = 0.07 calls/minute\n min = 17.01 milliseconds\n max = 1006.68 milliseconds\n mean = 511.84 milliseconds\n stddev = 699.80 milliseconds\n median = 511.84 milliseconds\n 75% <= 1006.68 milliseconds\n 95% <= 1006.68 milliseconds\n 98% <= 1006.68 milliseconds\n 99% <= 1006.68 milliseconds\n 99.9% <= 1006.68 milliseconds\n"
},
{
"answer_id": 49168439,
"author": "praveen jain",
"author_id": 1993534,
"author_profile": "https://Stackoverflow.com/users/1993534",
"pm_score": 2,
"selected": false,
"text": "StopWatch stopWatch = new StopWatch()\nstopWatch.start(); //start stopwatch\n// write your function or line of code.\nstopWatch.stop(); //stop stopwatch\nstopWatch.getTotalTimeMillis() ; ///get total time\n"
},
{
"answer_id": 53052361,
"author": "Pratik Patil",
"author_id": 4773290,
"author_profile": "https://Stackoverflow.com/users/4773290",
"pm_score": 3,
"selected": false,
"text": "Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds\n public class series\n{\n public static void main(String[] args)\n {\n long startTime = System.nanoTime();\n\n long n = 10_00_000;\n printFactorial(n);\n\n long endTime = System.nanoTime();\n printExecutionTime(startTime, endTime);\n\n }\n\n public static void printExecutionTime(long startTime, long endTime)\n {\n long time_ns = endTime - startTime;\n long time_ms = TimeUnit.NANOSECONDS.toMillis(time_ns);\n long time_sec = TimeUnit.NANOSECONDS.toSeconds(time_ns);\n long time_min = TimeUnit.NANOSECONDS.toMinutes(time_ns);\n long time_hour = TimeUnit.NANOSECONDS.toHours(time_ns);\n\n System.out.print(\"\\nExecution Time: \");\n if(time_hour > 0)\n System.out.print(time_hour + \" Hours, \");\n if(time_min > 0)\n System.out.print(time_min % 60 + \" Minutes, \");\n if(time_sec > 0)\n System.out.print(time_sec % 60 + \" Seconds, \");\n if(time_ms > 0)\n System.out.print(time_ms % 1E+3 + \" MicroSeconds, \");\n if(time_ns > 0)\n System.out.print(time_ns % 1E+6 + \" NanoSeconds\");\n }\n}\n"
},
{
"answer_id": 58167003,
"author": "Aska Fed",
"author_id": 5922688,
"author_profile": "https://Stackoverflow.com/users/5922688",
"pm_score": 1,
"selected": false,
"text": "public static <T> T timed (String description, Consumer<String> out, Supplier<T> code) {\n final LocalDateTime start = LocalDateTime.now ();\n T res = code.get ();\n final long execTime = Duration.between (start, LocalDateTime.now ()).toMillis ();\n out.accept (String.format (\"%s: %d ms\", description, execTime));\n return res;\n}\n public static void main (String[] args) throws InterruptedException {\n timed (\"Simple example\", System.out::println, Timing::myCode);\n}\n\npublic static Object myCode () {\n try {\n Thread.sleep (1500);\n } catch (InterruptedException e) {\n e.printStackTrace ();\n }\n return null;\n}\n"
},
{
"answer_id": 61475752,
"author": "Ahmad Hoghooghi",
"author_id": 2246238,
"author_profile": "https://Stackoverflow.com/users/2246238",
"pm_score": -1,
"selected": false,
"text": "TimeTracedExecuter public static void main(String[] args) {\n\n Integer square = new TimeTracedExecutor<>(Main::calculateSquare)\n .executeWithInput(\"calculate square of num\",5,logger);\n\n}\npublic static int calculateSquare(int num){\n return num*num;\n}\n INFO: It took 3 milliseconds to calculate square of num import java.text.NumberFormat;\nimport java.time.Duration;\nimport java.time.Instant;\nimport java.util.function.Function;\nimport java.util.logging.Logger;\n\npublic class TimeTracedExecutor<T,R> {\n Function<T,R> methodToExecute;\n\n public TimeTracedExecutor(Function<T, R> methodToExecute) {\n this.methodToExecute = methodToExecute;\n }\n\n public R executeWithInput(String taskDescription, T t, Logger logger){\n Instant start = Instant.now();\n R r= methodToExecute.apply(t);\n Instant finish = Instant.now();\n String format = \"It took %s milliseconds to \"+taskDescription;\n String elapsedTime = NumberFormat.getNumberInstance().format(Duration.between(start, finish).toMillis());\n logger.info(String.format(format, elapsedTime));\n return r;\n }\n}\n"
},
{
"answer_id": 61832131,
"author": "Bhaskara Arani",
"author_id": 4838509,
"author_profile": "https://Stackoverflow.com/users/4838509",
"pm_score": 3,
"selected": false,
"text": "//measuring elapsed time using Spring StopWatch\n StopWatch watch = new StopWatch();\n watch.start();\n for(int i=0; i< 1000; i++){\n Object obj = new Object();\n }\n watch.stop();\n System.out.println(\"Total execution time to create 1000 objects in Java using StopWatch in millis: \"\n + watch.getTotalTimeMillis());\n"
},
{
"answer_id": 69223408,
"author": "jhenya-d",
"author_id": 2054164,
"author_profile": "https://Stackoverflow.com/users/2054164",
"pm_score": 0,
"selected": false,
"text": "Timer import java.util.function.*;\n\npublic interface Timer {\n\n default void timeIt(Runnable r) {\n timeIt(() -> { r.run(); return 0;});\n }\n\n default <S,T> T timeIt(Function<S,T> fun, S arg) {\n long start = System.nanoTime();\n T result = fun.apply(arg);\n long stop = System.nanoTime();\n System.out.println(\"Time: \" + (stop-start)/1000000.0 + \" msec\");\n return result;\n }\n\n default <T> T timeIt(Supplier<T> s) {\n return timeIt(obj -> s.get(), null);\n }\n}\n class MyClass implements Timer ..\n\ntimeIt(this::myFunction); \n"
},
{
"answer_id": 70313074,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 0,
"selected": false,
"text": "Timing public record TimedResult<T>(T result, Duration duration) {}\n\npublic static Duration time(Runnable r) {\n var s = Instant.now();\n r.run();\n var dur = Duration.between(s, Instant.now());\n return dur;\n}\n\npublic static <T> TimedResult<T> time(Callable<T> r) throws Exception {\n var s = Instant.now();\n T res = r.call();\n var dur = Duration.between(s, Instant.now());\n return new TimedResult<>(res, dur);\n}\n Duration result = Timing.time(() -> {\n // do some work.\n});\n\nTimedResult<String> result = Timing.time(() -> {\n // do some work.\n return \"answer\";\n});\n\nDuration timeTaken = result.duration();\nString answer = result.result();\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140/"
] |
180,172
|
<p>Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?</p>
<pre><code>MyObject object; // ok - default ctor
MyObject object(blah); // ok
MyObject object(); // error
</code></pre>
<p>I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?</p>
|
[
{
"answer_id": 180185,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 6,
"selected": false,
"text": "object MyObject"
},
{
"answer_id": 180189,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 7,
"selected": false,
"text": "int MyFunction(); // clearly a function\nMyObject object(); // also a function declaration\n"
},
{
"answer_id": 181463,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 9,
"selected": true,
"text": "std::ifstream ifs(\"file.txt\");\nstd::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>());\n v std::vector<T> v((std::istream_iterator<T>(ifs)), std::istream_iterator<T>());\n std::vector<T> v{std::istream_iterator<T>{ifs}, std::istream_iterator<T>{}};\n"
},
{
"answer_id": 181772,
"author": "dalle",
"author_id": 19100,
"author_profile": "https://Stackoverflow.com/users/19100",
"pm_score": 3,
"selected": false,
"text": "MyObject object1 = MyObject();\nMyObject object2 = MyObject(object1);\n auto auto object1 = MyObject();\nauto object2 = MyObject(object1);\n"
},
{
"answer_id": 31093033,
"author": "Andreas DM",
"author_id": 3677097,
"author_profile": "https://Stackoverflow.com/users/3677097",
"pm_score": 3,
"selected": false,
"text": "() X a();"
},
{
"answer_id": 46824436,
"author": "Hitokage",
"author_id": 3027604,
"author_profile": "https://Stackoverflow.com/users/3027604",
"pm_score": 2,
"selected": false,
"text": "Jedi luke{}; //default constructor\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10897/"
] |
180,211
|
<p>To make click-able divs, I do:</p>
<pre><code><div class="clickable" url="http://google.com">
blah blah
</div>
</code></pre>
<p>and then </p>
<pre><code>$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
});
</code></pre>
<p>I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div contains a click-able element, such as
<a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called</p>
<p>This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function <em>AND</em> follows the link in the 'url' attribute of the div.</p>
<p>Anyway around this?</p>
|
[
{
"answer_id": 180246,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 3,
"selected": false,
"text": "\n$(\"div.clickable\").click(\nfunction(event)\n{\n window.location = $(this).attr(\"url\");\n event.preventDefault();\n});\n"
},
{
"answer_id": 180278,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 6,
"selected": true,
"text": "$(\"div.clickable\").click(\nfunction()\n{\n window.location = $(this).attr(\"url\");\n return false;\n});\n"
},
{
"answer_id": 2195216,
"author": "Sander Aarts",
"author_id": 265623,
"author_profile": "https://Stackoverflow.com/users/265623",
"pm_score": 3,
"selected": false,
"text": "$(\"div.clickable).clickable();"
},
{
"answer_id": 54482019,
"author": "Adem Ozturk",
"author_id": 5389509,
"author_profile": "https://Stackoverflow.com/users/5389509",
"pm_score": 0,
"selected": false,
"text": "<div class=\"info\">\n <h2>Takvim</h2>\n <a href=\"item-list.php\"> Click Me !</a>\n</div>\n\n\n$(document).delegate(\"div.info\", \"click\", function() {\n window.location = $(this).find(\"a\").attr(\"href\");\n});\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2721/"
] |
180,242
|
<p>We are making a Ruby On Rails webapp where every customer gets their own database.<br>
The database needs to be created after they fill out a form on our website.</p>
<p>We have a template database that has all of the tables and columns that we need to copy. How can I do this in programatically from ruby on rails?</p>
|
[
{
"answer_id": 180282,
"author": "Tilendor",
"author_id": 1470,
"author_profile": "https://Stackoverflow.com/users/1470",
"pm_score": 4,
"selected": true,
"text": " def copy_template_database\n template_name = \"customerdb1\" # Database to copy from\n new_name = \"temp\" #database to create & copy to\n\n #connect to template database to copy. Note that this will override any previous\n #connections for all Models that inherit from ActiveRecord::Base\n ActiveRecord::Base.establish_connection({:adapter => \"mysql\", :database => template_name, :host => \"olddev\",\n :username => \"root\", :password => \"password\" })\n\n sql_connection = ActiveRecord::Base.connection \n sql_connection.execute(\"CREATE DATABASE #{new_name} CHARACTER SET latin1 COLLATE latin1_general_ci\")\n tables = sql_connection.select_all(\"Show Tables\")\n #the results are an array of hashes, ie:\n # [{\"table_from_customerdb1\" => \"customers\"},{\"table_from_customerdb1\" => \"employees},...]\n table_names = Array.new\n tables.each { |hash| hash.each_value { |name| table_names << name }}\n\n table_names.each { |name| \n sql_connection.execute(\"CREATE TABLE #{new_name}.#{name} LIKE #{template_name}.#{name}\")\n sql_connection.execute(\"INSERT INTO #{new_name}.#{name} SELECT * FROM #{template_name}.#{name}\")\n }\n #This statement is optional. It connects ActiveRecord to the new database\n ActiveRecord::Base.establish_connection({:adapter => \"mysql\", :database => new_name, :host => \"olddev\",\n :username => \"root\", :password => \"password\" })\n end\n"
},
{
"answer_id": 182589,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 3,
"selected": false,
"text": "> mysqldump -uroot -proot templateDB > dump.sql\n> mysql -uroot -proot --execute=\"CREATE DATABASE newDB\"\n> mysql -uroot -proot newDB < dump.sql\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470/"
] |
180,245
|
<p>I have this CheckBoxList on a page:</p>
<pre><code><asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource"
datatextfield="CountryName" datavaluefield="CountryCode" />
</code></pre>
<p>I'd like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but the values don't appear to be available on the client side. The HTML output looks like this:</p>
<pre><code><table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;">
<tr>
<td><input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /><label for="ctl00_Content_Locations_0">Democratic Republic of the Congo</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /><label for="ctl00_Content_Locations_1">Central African Republic</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /><label for="ctl00_Content_Locations_2">Congo</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /><label for="ctl00_Content_Locations_3">Cameroon</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /><label for="ctl00_Content_Locations_4">Gabon</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /><label for="ctl00_Content_Locations_5">Equatorial Guinea</label></td>
</tr>
</code></pre>
<p></p>
<p>The values ("cd", "cg", "ga", etc.) are nowhere to be found. Where are they? Is it even possible to access them on the client, or do I need to build this checkboxlist myself using a repeater or something?</p>
|
[
{
"answer_id": 222147,
"author": "rjarmstrong",
"author_id": 25809,
"author_profile": "https://Stackoverflow.com/users/25809",
"pm_score": 2,
"selected": false,
"text": "<asp:Repeater ID=\"rptItems\" runat=\"server\" DataSourceID=\"odsDataSource\">\n<ItemTemplate>\n<input id=\"iptCheckBox\" type=\"checkbox\" runat=\"server\" value='<%# Eval(\"Key\") %>'><%# Eval(\"Value\") %></input>\n</ItemTemplate>\n</asp:Repeater>\n"
},
{
"answer_id": 1878966,
"author": "Swapna",
"author_id": 228546,
"author_profile": "https://Stackoverflow.com/users/228546",
"pm_score": 3,
"selected": false,
"text": "<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:CheckBoxList ID=\"CheckBoxList1\" runat=\"server\" DataTextField=\"tx\" DataValueField=\"vl\">\n </asp:CheckBoxList>\n </div>\n <input id=\"Button1\" type=\"button\" value=\"button\" onclick=\"return Button1_onclick()\" /> \n </form>\n</body>\n<script type=\"text/javascript\">\n\nfunction Button1_onclick() \n{\nvar itemarr = document.getElementById(\"CheckBoxList1\").getElementsByTagName(\"span\");\nvar itemlen = itemarr.length;\n for(i = 0; i <itemlen;i++)\n {\n alert(itemarr[i].getAttribute(\"dvalue\"));\n }\nreturn false;\n}\n\n\n</script>\n protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n DataTable dt = new DataTable();\n dt.Columns.Add(\"tx\");\n dt.Columns.Add(\"vl\");\n DataRow dr = dt.NewRow();\n dr[0] = \"asdas\";\n dr[1] = \"1\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"456456\";\n dr[1] = \"2\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"yjryut\";\n dr[1] = \"3\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"yjrfdgdfgyut\";\n dr[1] = \"3\";\n dt.Rows.Add(dr);\n dr = dt.NewRow();\n dr[0] = \"34534\";\n dr[1] = \"3\";\n dt.Rows.Add(dr);\n CheckBoxList1.DataSource = dt;\n CheckBoxList1.DataBind();\n foreach (ListItem li in CheckBoxList1.Items)\n {\n li.Attributes.Add(\"dvalue\", li.Value);\n }\n }\n}\n"
},
{
"answer_id": 3549453,
"author": "user428602",
"author_id": 428602,
"author_profile": "https://Stackoverflow.com/users/428602",
"pm_score": 0,
"selected": false,
"text": "ChkboxList1.DataSource = dsData;\nChkboxList1.DataTextField = \"your-display-column-name\";\nChkboxList1.DataValueField = \"your-identifier-column-name\";\nChkboxList1.DataBind();\n\nforeach (ListItem li in ChkboxList1.Items)\n{\n li.Attributes.Add(\"DataValue\", li.Value); \n}\n var selValues = \"\";\nvar ChkboxList1Ctl = document.getElementById(\"ChkboxList1\");\nvar ChkboxList1Arr = null;\nvar ChkboxList1Attr= null;\n\nif (ChkboxList1Ctl != null)\n{\n ChkboxList1Arr = ChkboxList1Ctl.getElementsByTagName(\"INPUT\");\n ChkboxList1Attr = ChkboxList1Ctl.getElementByTagName(\"span\");\n}\nif (ChkboxList1Arr != null)\n{\n for (var i = 0; i < ChkboxList1Arr.length; i++)\n {\n if (ChkboxList1Arr[i].checked)\n selValues += ChkboxList1Attr[i].getAttribute(\"DataValue\") + \",\";\n }\n if (selValues.length > 0)\n selValues = selValues.substr(0, selValues.length - 1);\n}\n"
},
{
"answer_id": 10301643,
"author": "danyim",
"author_id": 350951,
"author_profile": "https://Stackoverflow.com/users/350951",
"pm_score": 2,
"selected": false,
"text": " <asp:Repeater ID=\"rptItems\" runat=\"server\">\n <ItemTemplate>\n <input ID=\"iptCheckBox\" type=\"checkbox\" runat=\"server\" value='<%# Eval(\"your_data_value\") %>' />\n <label ID=\"iptLabel\" runat=\"server\"><%# Eval(\"your_data_field\") %></label>\n <br />\n </ItemTemplate>\n </asp:Repeater>\n Private Sub rptItems_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptItems.ItemDataBound\n Dim checkBox As HtmlInputCheckBox = DirectCast(e.Item.FindControl(\"iptCheckBox\"), HtmlInputCheckBox)\n Dim label As HtmlControl = DirectCast(e.Item.FindControl(\"iptLabel\"), HtmlControl)\n\n label.Attributes.Add(\"for\", checkBox.ClientID)\nEnd Sub\n"
},
{
"answer_id": 15030781,
"author": "AdamE",
"author_id": 796858,
"author_profile": "https://Stackoverflow.com/users/796858",
"pm_score": 4,
"selected": false,
"text": "<pages controlRenderingCompatibilityVersion=\"3.5\">\n if (this.RenderingCompatibility >= VersionUtil.Framework40)\n{\n this._controlToRepeat.InputAttributes.Add(\"value\", item.Value);\n}\n <input type=\"checkbox\" value=\"myvalue1\" id=\"someid\" />\n"
},
{
"answer_id": 35276896,
"author": "David Sherret",
"author_id": 188246,
"author_profile": "https://Stackoverflow.com/users/188246",
"pm_score": 0,
"selected": false,
"text": "<pages controlRenderingCompatibilityVersion=\"3.5\"> CheckBoxList Render public class CheckBoxListExt : CheckBoxList\n{\n protected override void Render(HtmlTextWriter writer)\n {\n foreach (ListItem item in this.Items)\n {\n item.Attributes.Add(\"data-value\", item.Value);\n }\n\n base.Render(writer);\n }\n}\n data-value span"
},
{
"answer_id": 44547137,
"author": "Jigs17",
"author_id": 8018680,
"author_profile": "https://Stackoverflow.com/users/8018680",
"pm_score": 0,
"selected": false,
"text": "Easy Way I Do It.\n\n//First create query directly From Database that contains hidden field code format (i do it in stored procedure)\n\nSELECT Id,Name + '<input id=\"hf_Id\" name=\"hf_Id\" value=\"'+convert(nvarchar(100),Id)+'\" type=\"hidden\">' as Name FROM User\n\n//Then bind checkbox list as normally(i bind it from dataview).\n\ncbl.DataSource = dv;\ncbl.DataTextField = \"Name\";\ncbl.DataValueField = \"Id\";\ncbl.DataBind();\n\n//Then finally it represent code as follow.\n\n<table id=\"cbl_Position\" border=\"0\">\n<tbody>\n<tr>\n<td>\n<input id=\"cbl_0\" name=\"cbl$0\" type=\"checkbox\">\n<label for=\"cbl_0\">\nABC\n<input id=\"hf_Id\" name=\"hf_Id\" value=\"1\" type=\"hidden\">\n</label>\n</td>\n</tr>\n</table>\n\nThis way you can get DataValueField as inside hiddenfield and also can get it value from client side using javascript.\n"
},
{
"answer_id": 63115878,
"author": "Muhammad Awais",
"author_id": 3901944,
"author_profile": "https://Stackoverflow.com/users/3901944",
"pm_score": 0,
"selected": false,
"text": "<asp:CheckBoxList ID=\"chkAttachments\" runat=\"server\"></asp:CheckBoxList>\n private void LoadCheckBoxData()\n {\n\n var docList = new List<Documents>(); // need to get the list data from database\n chkAttachments.Items.Clear();\n\n ListItem item = new ListItem();\n \n foreach (var doc in docList )\n {\n item = new ListItem();\n item.Value = doc.Id.ToString();\n item.Text = doc.doc_name;\n chkAttachments.Items.Add(item);\n }\n }\n \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
180,266
|
<p>How do you think, is it a good idea to have such an enum:</p>
<pre><code>enum AvailableSpace {
Percent10,
Percent20,
SqF500,
SqF600
}
</code></pre>
<p>The question is about the semantics of the values names, i.e. both percentage and square feet. I really believe that it's not a good idea, but I could not find and guidelines, etc. in support of this.</p>
<p>EDIT: This will be used to determine a state of an entity - i.e. as a read only property to describe a state of an object. If we know the total space (i.e. the object itself knows it), we have the option to convert internally, so we either have only percentage, or square feet, or both. The argument is, that "both" is not a good idea.</p>
<p>The above is an example of course, but the real problem is that some data providers send us totals (sq.f.), and others percentage, and my goal is to unify the UI. I'm free to make some approximations, so the exact values will be adapted based on how accurate we want to present the information.</p>
<p>The question is only about the semantics of the value names, not the content - i.e. if it is a good idea to put percentage in an (potential) int enum.</p>
|
[
{
"answer_id": 180284,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 3,
"selected": false,
"text": "public enum OperatingSystem\n{\n Windows95,\n Windows98,\n Windows2000,\n WindowsXP,\n WindowsVista,\n MacOSClassic,\n MacOSXTiger,\n MacOSXLeopard\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8220/"
] |
180,272
|
<p>Is it even possible?</p>
<p>Basically, there's a remote repository from which I pull using just:</p>
<pre><code>git pull
</code></pre>
<p>Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".</p>
|
[
{
"answer_id": 180329,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 6,
"selected": false,
"text": "git fetch http://host.xz/path/to/repo.git/ \n git log origin \n git merge origin\n git log -p //log with diff\n"
},
{
"answer_id": 180368,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 9,
"selected": true,
"text": "git fetch git log HEAD..origin/master git log -p HEAD..origin/master git diff HEAD...origin/master git cherry-pick git pull"
},
{
"answer_id": 5376713,
"author": "Antonio Bardazzi",
"author_id": 614407,
"author_profile": "https://Stackoverflow.com/users/614407",
"pm_score": 5,
"selected": false,
"text": "origin master origin/master git checkout master \ngit fetch \ngit diff origin/master\ngit pull --rebase origin master\n"
},
{
"answer_id": 7103880,
"author": "Matthias",
"author_id": 127013,
"author_profile": "https://Stackoverflow.com/users/127013",
"pm_score": 4,
"selected": false,
"text": "alias.changes=!git log --name-status HEAD..\n $git fetch\n$git changes origin\n merge"
},
{
"answer_id": 48784435,
"author": "Andy P",
"author_id": 2115610,
"author_profile": "https://Stackoverflow.com/users/2115610",
"pm_score": 2,
"selected": false,
"text": "~/.gitconfig [alias]\n diffpull=!git fetch && git diff HEAD..@{u}\n git pull"
},
{
"answer_id": 48800580,
"author": "cowboycb",
"author_id": 9137976,
"author_profile": "https://Stackoverflow.com/users/9137976",
"pm_score": 2,
"selected": false,
"text": "diff --git a/app/controller/xxxx.php b/app/controller/xxxx.php\ndiff --git a/app/view/yyyy.php b/app/view/yyyy.php\n"
},
{
"answer_id": 59737915,
"author": "AXE Labs",
"author_id": 632827,
"author_profile": "https://Stackoverflow.com/users/632827",
"pm_score": 0,
"selected": false,
"text": "$ alias gtp=\"tar -c . | (cd /tmp && mkdir tp && cd tp && tar -x && git pull; rm -rf /tmp/tp)\"\n $ git status\n# On branch master\nnothing to commit (working directory clean)\n\n$ gtp\nremote: Finding sources: 100% (25/25)\nremote: Total 25 (delta 10), reused 25 (delta 10)\nUnpacking objects: 100% (25/25), done.\nFrom ssh://my.git.domain/reapO\n 32d61dc..05287d6 master -> origin/master\nUpdating 32d61dc..05287d6\nFast-forward\n subdir/some.file | 2 +-\n .../somepath/by.tes | 3 ++-\n .../somepath/data | 11 +++++++++++\n 3 files changed, 14 insertions(+), 2 deletions(-)\n\n$ git status\n# On branch master\nnothing to commit (working directory clean)\n\n$ git fetch\nremote: Finding sources: 100% (25/25)\nremote: Total 25 (delta 10), reused 25 (delta 10)\nUnpacking objects: 100% (25/25), done.\nFrom ssh://my.git.domain/reapO\n 32d61dc..05287d6 master -> origin/master\n\n$ git status\n# On branch master\n# Your branch is behind 'origin/master' by 3 commits, and can be fast-forwarded.\n#\nnothing to commit (working directory clean)\n"
},
{
"answer_id": 67351884,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "prefetch git maintenance git fetch refs/heads refs/remotes refs/prefetch/<remote>/ git fetch --prefetch derrickstolee gitster fetch --prefetch --prefetch refs/prefetch/ filter_prefetch_refspec() refs/tags/ refs/prefetch/ force i-- --prefetch refs/tags/* i-- refs/tags/* refs/heads/* fetch-options --prefetch refs/prefetch/"
},
{
"answer_id": 68115220,
"author": "SuperNova",
"author_id": 3464971,
"author_profile": "https://Stackoverflow.com/users/3464971",
"pm_score": 1,
"selected": false,
"text": "git fetch origin\n\n# show commit logs of changes\ngit log master..origin/master\n\n# show diffs of changes\ngit diff master..origin/master\n\n# apply the changes by merge..\ngit merge origin/master\n\n# .. or just pull the changes\ngit pull\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] |
180,283
|
<p>I've got an ASP.NET page that has a bunch of controls that need to be populated (e.g. dropdown lists).</p>
<p>I'd like to make a single trip to the db and bring back multiple recordsets instead of making a round-trip for each control.</p>
<p>I could bring back multiple tables in a DataSet, or I could bring back a DataReader and use '.NextResult' to put each result set into a custom business class.</p>
<p>Will I likely see a big enough performance advantage using the DataReader approach, or should I just use the DataSet approach?</p>
<p>Any examples of how you usually handle this would be appreciated.</p>
|
[
{
"answer_id": 180650,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 2,
"selected": false,
"text": "DataReader DataReader DataTable DataSet DataSet DataReader"
},
{
"answer_id": 4222922,
"author": "Shiv Kumar",
"author_id": 501146,
"author_profile": "https://Stackoverflow.com/users/501146",
"pm_score": 2,
"selected": false,
"text": "public sealed class BlogItemDrw : BaseDbDataReaderWrapper\n{\n public Int64 ItemId { get { return (Int64)DbDataReader[0]; } }\n public Int64 MemberId { get { return (Int64)DbDataReader[1]; } }\n public String ItemTitle { get { return (String)DbDataReader[2]; } }\n public String ItemDesc { get { if (DbDataReader[3] != DBNull.Value) return (String)DbDataReader[3]; else return default(String); } }\n public DateTime ItemPubdate { get { return (DateTime)DbDataReader[4]; } }\n public Int32 ItemCommentCnt { get { return (Int32)DbDataReader[5]; } }\n public Boolean ItemAllowComment { get { return (Boolean)DbDataReader[6]; } }\n public BlogItemDrw()\n :base()\n {\n }\n\n public BlogItemDrw(DbDataReader dbDataReader)\n :base(dbDataReader)\n {\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624/"
] |
180,297
|
<p>I'm learning Java and I'm wondering what everyone's Java rules are. The rules that you know intrinsically and if you see someone breaking them you try to correct them. Things to keep you out of trouble or help improve things. Things you should never do. Things you should always do. The rules that a beginner would not know.</p>
|
[
{
"answer_id": 180357,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 3,
"selected": false,
"text": "== .equals() (string1 == string2) string1 string2"
},
{
"answer_id": 180376,
"author": "Synoli",
"author_id": 17305,
"author_profile": "https://Stackoverflow.com/users/17305",
"pm_score": 2,
"selected": false,
"text": "ArrayList Vector HashMap Hashtable Collections Hashtable Vector"
},
{
"answer_id": 180437,
"author": "Synoli",
"author_id": 17305,
"author_profile": "https://Stackoverflow.com/users/17305",
"pm_score": 2,
"selected": false,
"text": "public void doXY(LinkedList widgets) Lists Set public void doXY(Collection widgets)"
},
{
"answer_id": 180878,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "String s;\nif(x == 5)\n s=\"5\";\n\nif(y == 5) \n s.append(\"5\"); // Compiler will tell you s might not have been assigned\n // UNLESS your first line was \"String s=null\"\n"
},
{
"answer_id": 182792,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "public class Foo\n{\n boolean b = false;\n int n = 0;\n float x = 0.0;\n SomeClass sc = null;\n}\n"
},
{
"answer_id": 5306177,
"author": "MatBanik",
"author_id": 465179,
"author_profile": "https://Stackoverflow.com/users/465179",
"pm_score": 1,
"selected": false,
"text": "properties methods Comment"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
180,320
|
<p>I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.</p>
<p>Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.</p>
<p>This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.</p>
<p>So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like</p>
<ul>
<li>Inscrutable compiler errors in
places where you don't expect them?</li>
<li>Code bloat? </li>
<li>Difficulty in tracing code?</li>
<li>Setting Debugger Breakpoints?</li>
</ul>
|
[
{
"answer_id": 180539,
"author": "Jeff B",
"author_id": 25879,
"author_profile": "https://Stackoverflow.com/users/25879",
"pm_score": 5,
"selected": false,
"text": "template<int d,int t> class Unit\n{\n double value;\npublic:\n Unit(double n)\n {\n value = n;\n }\n Unit<d,t> operator+(Unit<d,t> n)\n {\n return Unit<d,t>(value + n.value);\n }\n Unit<d,t> operator-(Unit<d,t> n)\n {\n return Unit<d,t>(value - n.value);\n }\n Unit<d,t> operator*(double n)\n {\n return Unit<d,t>(value * n);\n }\n Unit<d,t> operator/(double n)\n {\n return Unit<d,t>(value / n);\n }\n Unit<d+d2,t+t2> operator*(Unit<d2,t2> n)\n {\n return Unit<d+d2,t+t2>(value * n.value);\n }\n Unit<d-d2,t-t2> operator/(Unit<d2,t2> n)\n {\n return Unit<d-d2,t-t2>(value / n.value);\n }\n etc....\n};\n\n#define Distance Unit<1,0>\n#define Time Unit<0,1>\n#define Second Time(1.0)\n#define Meter Distance(1.0)\n\nvoid foo()\n{\n Distance moved1 = 5 * Meter;\n Distance moved2 = 10 * Meter;\n Time time1 = 10 * Second;\n Time time2 = 20 * Second;\n if ((moved1 / time1) == (moved2 / time2))\n printf(\"Same speed!\");\n}\n"
},
{
"answer_id": 619772,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 2,
"selected": false,
"text": "template<class T>\nvoid Garbage(int a, int b)\n{\n fdsa uiofew & (a9 s) fdsahj += *! wtf;\n}\n <template arguments>"
},
{
"answer_id": 1395791,
"author": "Partial",
"author_id": 127716,
"author_profile": "https://Stackoverflow.com/users/127716",
"pm_score": 2,
"selected": false,
"text": "int main()\n{\n SimpleList<short> lstA;\n //...\n SimpleList<int> lstB = lstA; //would normally give an error after trying to compile\n}\n #include <algorithm>\n\ntemplate<class T>\nclass SimpleList\n{\npublic:\n typedef T value_type;\n typedef std::size_t size_type;\n\nprivate:\n struct Knot\n {\n value_type val_;\n Knot * next_;\n Knot(const value_type &val)\n :val_(val), next_(0)\n {}\n };\n Knot * head_;\n size_type nelems_;\n\npublic:\n //Default constructor\n SimpleList() throw()\n :head_(0), nelems_(0)\n {}\n bool empty() const throw()\n { return size() == 0; }\n size_type size() const throw()\n { return nelems_; }\n\nprivate:\n Knot * last() throw() //could be done better\n {\n if(empty()) return 0;\n Knot *p = head_;\n while (p->next_)\n p = p->next_;\n return p;\n }\n\npublic:\n void push_back(const value_type & val)\n {\n Knot *p = last();\n if(!p)\n head_ = new Knot(val);\n else\n p->next_ = new Knot(val);\n ++nelems_;\n }\n void clear() throw()\n {\n while(head_)\n {\n Knot *p = head_->next_;\n delete head_;\n head_ = p;\n }\n nelems_ = 0;\n }\n //Destructor:\n ~SimpleList() throw()\n { clear(); }\n //Iterators:\n class iterator\n {\n Knot * cur_;\n public:\n iterator(Knot *p) throw()\n :cur_(p)\n {}\n bool operator==(const iterator & iter)const throw()\n { return cur_ == iter.cur_; }\n bool operator!=(const iterator & iter)const throw()\n { return !(*this == iter); }\n iterator & operator++()\n {\n cur_ = cur_->next_;\n return *this;\n }\n iterator operator++(int)\n {\n iterator temp(*this);\n operator++();\n return temp;\n }\n value_type & operator*()throw()\n { return cur_->val_; }\n value_type operator*() const\n { return cur_->val_; }\n value_type operator->()\n { return cur_->val_; }\n const value_type operator->() const\n { return cur_->val_; }\n };\n iterator begin() throw()\n { return iterator(head_); }\n iterator begin() const throw()\n { return iterator(head_); }\n iterator end() throw()\n { return iterator(0); }\n iterator end() const throw()\n { return iterator(0); }\n //Copy constructor:\n SimpleList(const SimpleList & lst)\n :head_(0), nelems_(0)\n {\n for(iterator i = lst.begin(); i != lst.end(); ++i)\n push_back(*i);\n }\n void swap(SimpleList & lst) throw()\n {\n std::swap(head_, lst.head_);\n std::swap(nelems_, lst.nelems_);\n }\n SimpleList & operator=(const SimpleList & lst)\n {\n SimpleList(lst).swap(*this);\n return *this;\n }\n //Conversion constructor\n template<class U>\n SimpleList(const SimpleList<U> &lst)\n :head_(0), nelems_(0)\n {\n for(typename SimpleList<U>::iterator iter = lst.begin(); iter != lst.end(); ++iter)\n push_back(*iter);\n }\n template<class U>\n SimpleList & operator=(const SimpleList<U> &lst)\n {\n SimpleList(lst).swap(*this);\n return *this;\n }\n //Sequence constructor:\n template<class Iter>\n SimpleList(Iter first, Iter last)\n :head_(0), nelems_(0)\n {\n for(;first!=last; ++first)\n push_back(*first);\n\n\n }\n};\n"
},
{
"answer_id": 1902564,
"author": "Gregory Pakosz",
"author_id": 216063,
"author_profile": "https://Stackoverflow.com/users/216063",
"pm_score": 5,
"selected": false,
"text": "int float operator + add<float>(5, 3); add<int>(5, 3); #define min(i, j) (((i) < (j)) ? (i) : (j)) i j"
},
{
"answer_id": 1902565,
"author": "catchmeifyoutry",
"author_id": 218682,
"author_profile": "https://Stackoverflow.com/users/218682",
"pm_score": 3,
"selected": false,
"text": "namespace foo {\n template <class NumberType>\n NumberType add(NumberType a, NumberType b)\n {\n return a+b;\n }\n\n #define ADD(x, y) ((x)+(y))\n} // namespace foo\n\nnamespace logspace \n{\n // no problemo\n template <class NumberType>\n NumberType add(NumberType a, NumberType b)\n {\n return log(a)+log(b);\n }\n\n // redefintion: warning/error/bugs!\n #define ADD(x, y) (log(x)+log(y))\n\n} // namespace logspace\n"
},
{
"answer_id": 1902575,
"author": "GManNickG",
"author_id": 87234,
"author_profile": "https://Stackoverflow.com/users/87234",
"pm_score": 4,
"selected": false,
"text": "template <typename T>\nstruct is_void\n{\n static const bool value = false;\n}\n\ntemplate <>\nstruct is_void<void>\n{\n static const bool value = true;\n}\n"
},
{
"answer_id": 1902593,
"author": "Jerry Coffin",
"author_id": 179910,
"author_profile": "https://Stackoverflow.com/users/179910",
"pm_score": 3,
"selected": false,
"text": "typename typename struct X { \n int x;\n};\n\nstruct Y {\n typedef long x;\n};\n\ntemplate <class T>\nclass Z { \n T::x;\n};\n\nZ<X>; // T::x == the int variable named x\nZ<Y>; // T::x == a typedef for the type 'long'\n typename"
},
{
"answer_id": 1902609,
"author": "Michael Krelin - hacker",
"author_id": 95382,
"author_profile": "https://Stackoverflow.com/users/95382",
"pm_score": 2,
"selected": false,
"text": "#define min(a,b) ((a)<(b))?(a):(b)\n c = min(a++,++b);\n min() operrator<"
},
{
"answer_id": 1903729,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 2,
"selected": false,
"text": "#define max(a, b)... max std::swap swap"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
180,330
|
<p>I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later. </p>
<p>Can anybody tell me how to obtain the file path from the save dialog box to use it later?</p>
|
[
{
"answer_id": 180332,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": true,
"text": "SaveFileDialog saveFileDialog1 = new SaveFileDialog(); \nsaveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); \nsaveFileDialog1.Filter = \"Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*\" ; \nsaveFileDialog1.FilterIndex = 1; \n\nif(saveFileDialog1.ShowDialog() == DialogResult.OK) \n{ \n Console.WriteLine(saveFileDialog1.FileName);//Do what you want here\n} \n"
},
{
"answer_id": 180359,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 2,
"selected": false,
"text": "if (saveFileDialog.ShowDialog() == DialogResult.OK)\n{\n this.textBox1.Text = saveFileDialog.FileName;\n}\n"
},
{
"answer_id": 4721043,
"author": "Nidz",
"author_id": 579496,
"author_profile": "https://Stackoverflow.com/users/579496",
"pm_score": 2,
"selected": false,
"text": "private void mnuFileSave_Click(object sender, EventArgs e)\n{\n dlgFileSave.Filter = \"RTF Files|*.rtf|\"+\"Text files (*.txt)|*.txt|All files (*.*)|*.*\";\n dlgFileSave.FilterIndex = 1;\n if (dlgFileSave.ShowDialog() == System.Windows.Forms.DialogResult.OK && dlgFileSave.FileName.Length > 0)\n {\n foreach (string strFile in dlgFileSave.FileNames)\n {\n SingleDocument document = new SingleDocument();\n document.rtbNotice.SaveFile(strFile, RichTextBoxStreamType.RichText);\n document.MdiParent = this;\n document.Show();\n }\n }\n}\n"
},
{
"answer_id": 26754513,
"author": "user4218087",
"author_id": 4218087,
"author_profile": "https://Stackoverflow.com/users/4218087",
"pm_score": -1,
"selected": false,
"text": "saveFileDialog1.ShowDialog();\nrichTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
180,349
|
<p>In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to.</p>
<p>How do I dynamically and programatically connect ActiveRecord to the right db?</p>
|
[
{
"answer_id": 180355,
"author": "Tilendor",
"author_id": 1470,
"author_profile": "https://Stackoverflow.com/users/1470",
"pm_score": 4,
"selected": false,
"text": " ActiveRecord::Base.establish_connection({:adapter => \"mysql\", :database => new_name, :host => \"olddev\",\n :username => \"root\", :password => \"password\" })\n"
},
{
"answer_id": 180391,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 6,
"selected": true,
"text": "customer = CustomerModel.find(id)\nspec = CustomerModel.configurations[RAILS_ENV]\nnew_spec = spec.clone\nnew_spec[\"database\"] = customer.database_name\nActiveRecord::Base.establish_connection(new_spec)\nActiveRecord::Migrator.migrate(\"db/migrate_data/\", nil)\n CustomerModel.establish_connection(spec)\n"
},
{
"answer_id": 30492099,
"author": "Andre Figueiredo",
"author_id": 986862,
"author_profile": "https://Stackoverflow.com/users/986862",
"pm_score": 4,
"selected": false,
"text": "conn_config = ActiveRecord::Base.connection_config\nconn_config[:database] = new_database\nActiveRecord::Base.establish_connection conn_config\n"
},
{
"answer_id": 44147811,
"author": "Dorian",
"author_id": 407213,
"author_profile": "https://Stackoverflow.com/users/407213",
"pm_score": 2,
"selected": false,
"text": "class Database\n def self.development!\n ActiveRecord::Base.establish_connection(:development)\n end\n\n def self.production!\n ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])\n end\n\n def self.staging!\n ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])\n end\nend\n .env dotenv-rails PRODUCTION_DATABASE=postgres://...\nSTAGING_DATABASE=postgres://...\n Database.development!\nUser.count\nDatabase.production!\nUser.count\nDatabase.staging!\nUser.count\n# etc.\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470/"
] |
180,358
|
<p>I'm a pretty experienced Java programmer that's been doing quite a bit of Win32 stuff in the last couple of years. Mainly I've been using VB6, but I really need to move to something better.</p>
<p>I've spent a month or so playing with Delphi 2009. I like the VCL GUI stuff, Delphi seems more suited to Windows API calls than VB6, I really like the fact that it's much better at OO than VB6, and I like the unit-testing framework that comes with the IDE.</p>
<p>But I really struggle with the fact that there's no widely-used garbage collector for Delphi - having to free every object manually or use interfaces for everything seems to have a pretty big impact on the way that you can do things effectively in an object oriented way. Also I'm not particularly keen on the syntax, or the fact that you have to declare variables all at the top of a method.</p>
<p>I can handle Delphi, but I'm wondering if C++ Builder 2009 might be a better choice for me. I know very little about C++ Builder and C++, but then I know very little about Delphi either. I know there's a lot to the C++ language, but I suspect it's only necessary to know a subset of it to get things done productively... I have heard that the C++ of today is a lot more productive to program in than the C++ of 10 years ago. </p>
<p>I'll be doing new development only so I wouldn't need to master every aspect of the C++ language - if I can find an equivalent for each of Java's language features I'll be happy enough, and as I progress I could start looking at the more advanced stuff a bit more. (Sorry if that sounds painfully naive - if so please set me straight!)</p>
<p>So, for a Java programmer that's new to both Delphi and C++ Builder, which would you consider to be a better choice for productive development of Win32 exes and dlls, and why? What do you see to be the pros and cons of each?</p>
|
[
{
"answer_id": 180449,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 3,
"selected": false,
"text": "MyObj = TMyObj.Create;\n\ntry\n MyObj.DoSomething;\nfinally\n MyObj.Free;\nend\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961/"
] |
180,363
|
<p>I have a custom control that I created for my project. In this control there are several child controls like a Label, a PictureBox, and a LinkLabel. Other then the LinkLabel, I want the mouse over event currently on the parent control and have the control respond to the mouse over. The background color changes when you hover over the control, but the background color doesn't change when over a child control; this is because there is no MouseEnter and MouseLeave events on the child control. I solved this issue by added the parent controls delegate methods to the child controls. The problem remains that the click event also is ignored over the child controls when I've subscribed to the click event on my parent control. I can subscribe to each individual child control, but how do I force the click event of the parent control? The term I've found by searching is Event Bubbling, but this seems to only apply to ASP.NET technologies and frameworks. Any suggestions?</p>
|
[
{
"answer_id": 180490,
"author": "Fox Diller",
"author_id": 24017,
"author_profile": "https://Stackoverflow.com/users/24017",
"pm_score": 1,
"selected": false,
"text": "private void Control_Click(object sender, EventArgs e)\n{\n // this is the parent control.\n InvokeOnClick(this, new EventArgs());\n}\n\nprivate void IFLVControl_MouseEnter(object sender, EventArgs e)\n{\n this.BackColor = Color.DarkGray;\n}\n\nprivate void IFLVControl_MouseLeave(object sender, EventArgs e)\n{\n this.BackColor = Color.White;\n}\n"
},
{
"answer_id": 4133481,
"author": "Geoffrey",
"author_id": 501842,
"author_profile": "https://Stackoverflow.com/users/501842",
"pm_score": 1,
"selected": false,
"text": "Public Shared Sub RelayEvents(ByVal usrcon As Windows.Forms.Control, ByVal del As System.EventHandler, Optional ByVal includeChildren As Boolean = True)\n For Each con As Windows.Forms.Control In usrcon.Controls\n AddHandler con.Click, del\n If includeChildren Then\n RelayEvents(con, del)\n End If\n Next\nEnd Sub\n CustomMethods.RelayEvents(Me, New EventHandler(AddressOf Me_Click))\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24017/"
] |
180,366
|
<p>I have a Page that has a single instance of a UserControl that itself has a single UpdatePanel. Inside the UpdatePanel are several Button controls. The Click event for these controls are wired up in the code-behind, in the Init event of the UserControl.</p>
<p>I get the Click event for the first button I push, every time, no problem. After that, I only get Click events for one button (SearchButton) - the rest are ignored. I have included the code for the control below - for sake of brevity, I have excluded the click event handler methods, but they are all of the standard "void Button_Click(object sender, EventArgs e)" variety. Any ideas?</p>
<pre><code><asp:UpdatePanel ID="PickerUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="Container" runat="server">
<div>
<asp:TextBox ID="PickerResults" runat="server" style="margin-right: 3px;" SkinID="Plain" />
<asp:Image
ID="LaunchPopup" runat="server" ImageUrl="~/images/icons/user_manage.png"
ImageAlign="Top" BorderColor="#294254" BorderStyle="Dotted" BorderWidth="1px"
Height="20px" Width="20px" style="cursor: pointer;" />
</div>
<asp:Panel ID="PickerPanel" runat="server" DefaultButton="OKButton" CssClass="popupDialog" style="height: 227px; width: 400px; padding: 5px; display: none;">
<asp:Panel runat="server" id="ContactPickerSearchParams" style="margin-bottom: 3px;" DefaultButton="SearchButton">
Search: <asp:TextBox ID="SearchTerms" runat="server" style="margin-right: 3px;" Width="266px" SkinID="Plain" />
<asp:Button ID="SearchButton" runat="server" Text="Go" Width="60px" SkinID="Plain" />
</asp:Panel>
<asp:ListBox ID="SearchResults" runat="server" Height="150px" Width="100%" SelectionMode="Multiple" style="margin-bottom: 3px;" />
<asp:Button ID="AddButton" runat="server" Text="Add >>" style="margin-right: 3px;" Width="60px" SkinID="Plain" />
<asp:TextBox ID="ChosenPeople" runat="server" Width="325px" SkinID="Plain" />
<div style="float: left;">
<asp:Button ID="AddNewContact" runat="server" SkinID="Plain" Width="150px" Text="New Contact" />
</div>
<div style="text-align: right;">
<asp:Button ID="OKButton" runat="server" Text="Ok" SkinID="Plain" Width="100px" />
</div>
<input id="SelectedContacts" runat="server" visible="false" />
</asp:Panel>
<ajax:PopupControlExtender ID="PickerPopEx" runat="server" PopupControlID="PickerPanel" TargetControlID="LaunchPopup" Position="Bottom" />
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AddButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="SearchButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="AddNewContact" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
public partial class ContactPicker : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
SearchButton.Click += new EventHandler(SearchButton_Click);
AddButton.Click += new EventHandler(AddButton_Click);
OKButton.Click += new EventHandler(OKButton_Click);
}
// Other code left out
}
</code></pre>
|
[
{
"answer_id": 4248741,
"author": "Orson",
"author_id": 207756,
"author_profile": "https://Stackoverflow.com/users/207756",
"pm_score": 0,
"selected": false,
"text": "LinkButton dgPatients_ItemDataBound PostBackUrl LinkButton HyperLink"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35/"
] |
180,370
|
<p>I am aware of the <a href="http://msdn.microsoft.com/en-us/library/system.timezone(VS.80).aspx" rel="noreferrer">System.TimeZone</a> class as well as the many uses of the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tostring(VS.80).aspx" rel="noreferrer">DateTime.ToString()</a> method. What I haven't been able to find is a way to convert a DateTime to a string that, in addition to the time and date info, contains the three-letter Time Zone abbreviation (in fact, much the same way StackOverflow's tooltips for relative time display works).</p>
<p>To make an example easy for everyone to follow as well as consume, let's continue with the StackOverflow example. If you look at the tooltip that displays on relative times, it displays with the full date, the time including seconds in twelve-hour format, an AM/PM designation, and then the three-letter Time Zone abbreviation (in their case, Coordinated Universal Time). I realize I could easily get GMT or UTC by using the built-in methods, but what I really want is the time as it is locally — in this case, on a web server.</p>
<p>If our web server is running Windows Server 2k3 and has it's time zone set to CST (or, until <a href="http://en.wikipedia.org/wiki/Daylight_saving_time#Terminology" rel="noreferrer">daylight saving</a> switches back, CDT is it?), I'd like our ASP.NET web app to display DateTimes relative to that time zone as well as formatted to display a "CST" on the end. I realize I could easily hard-code this, but in the interest of robustness, I'd really prefer a solution based on the server running the code's OS environment settings.</p>
<p>Right now, I have everything but the time zone abbreviation using the following code:</p>
<pre><code>myDateTime.ToString("MM/dd/yyyy hh:mm:ss tt")
</code></pre>
<p>Which displays:</p>
<p>10/07/2008 03:40:31 PM</p>
<p>All I want (and it's not much, promise!) is for it to say:</p>
<p>10/07/2008 03:40:31 PM CDT</p>
<p>I can use System.TimeZone.CurrentTimeZone and use it to correctly display "Central Daylight Time" but... that's a bit too long for brevity's sake. Am I then stuck writing a string manipulation routine to strip out white-space and any non-uppercase letters? While that might work, that seems incredibly hack to me...</p>
<p><a href="http://www.google.com/search?hl=en&safe=off&q=C%23+time+zone+abbreviation&btnG=Search" rel="noreferrer">Googling</a> and looking around on here did not produce anything applicable to my specific question.</p>
|
[
{
"answer_id": 180559,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 0,
"selected": false,
"text": "string[] words = tzname.Split(\" \".ToCharArray());\nstring tzabbr = \"\";\nforeach (string word in words)\n tzabbr += word[0];\n"
},
{
"answer_id": 794958,
"author": "craigmoliver",
"author_id": 12252,
"author_profile": "https://Stackoverflow.com/users/12252",
"pm_score": 4,
"selected": false,
"text": "public static String TimeZoneName(DateTime dt)\n{\n String sName = TimeZone.CurrentTimeZone.IsDaylightSavingTime(dt) \n ? TimeZone.CurrentTimeZone.DaylightName \n : TimeZone.CurrentTimeZone.StandardName;\n\n String sNewName = \"\";\n String[] sSplit = sName.Split(new char[]{' '});\n foreach (String s in sSplit)\n if (s.Length >= 1)\n sNewName += s.Substring(0, 1);\n\n return sNewName;\n}\n"
},
{
"answer_id": 7600922,
"author": "Bob Houghton",
"author_id": 971645,
"author_profile": "https://Stackoverflow.com/users/971645",
"pm_score": 1,
"selected": false,
"text": " public static string ToCurrentTimeZoneString(this DateTime date)\n {\n string name = TimeZone.CurrentTimeZone.IsDaylightSavingTime(date) ?\n TimeZone.CurrentTimeZone.DaylightName :\n TimeZone.CurrentTimeZone.StandardName;\n return name;\n }\n\n public static string ToCurrentTimeZoneShortString(this DateTime date)\n {\n StringBuilder result = new StringBuilder();\n\n foreach (string value in date.ToCurrentTimeZoneString().Split(' '))\n {\n if (value.IsNotNullOrEmptyWithTrim())\n {\n result.Append(char.ToUpper(value[0]));\n }\n }\n\n return result.ToString();\n }\n"
},
{
"answer_id": 12860785,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "public static String TimeZoneName2(DateTime dt)\n{\n var return ToCurrentTimeZoneShortString(dt)\n .Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);\n return sSplit.Aggregate(\"\", (st,w)=> st +=w[0]);\n}\n public static String TimeZoneName3(DateTime dt)\n{\n return ToCurrentTimeZoneShortString(dt).Split(' ')\n .Aggregate(\"\", (st,w)=> st +=w[0]);\n}\n"
},
{
"answer_id": 27451460,
"author": "kaptan",
"author_id": 266659,
"author_profile": "https://Stackoverflow.com/users/266659",
"pm_score": 2,
"selected": false,
"text": "DateTime x public static string ConvertToFormattedLocalTimeWithTimezone(DateTime dateTimeUtc)\n {\n var tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); // Get the system's time zone\n var zdt = new ZonedDateTime(Instant.FromDateTimeUtc(dateTimeUtc), tz);\n return zdt.ToString(\"MM'/'dd'/'yyyy' 'hh':'mm':'ss' 'tt' 'x\", CultureInfo.InvariantCulture);\n }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290/"
] |
180,373
|
<p>Is there any way instead of a JS hack where I can post from an iframe to another page outside the iframe?</p>
<p>the iframe is posting data to a 3rd party and then just responding back with a URL which is the redirection URl thus we cannot set the form target. We are PCI compliant and thus we cannot use <code>window.parent.location = url;</code></p>
|
[
{
"answer_id": 180387,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<form>"
},
{
"answer_id": 180390,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 0,
"selected": false,
"text": "target='_parent'"
},
{
"answer_id": 180504,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 0,
"selected": false,
"text": "window.parent.location = url;"
},
{
"answer_id": 204347,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 2,
"selected": true,
"text": "window.parent.location window.location"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24958/"
] |
180,398
|
<p>I'd like to have it yell hooray whenever an assert statement succeeds, or at the very least have it display the number of successful assert statements that were encountered.</p>
<p>I'm using JUnit4.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 10710348,
"author": "rzrelyea",
"author_id": 1241450,
"author_profile": "https://Stackoverflow.com/users/1241450",
"pm_score": 4,
"selected": false,
"text": "<junit showoutput=\"true\" printsummary=\"on\" enabletestlistenerevents=\"true\" fork=\"@{fork}\" forkmode=\"once\" haltonfailure=\"no\" timeout=\"1800000\">\n Running com.foo.bar.MyTest\njunit.framework.TestListener: tests to run: 2\njunit.framework.TestListener: startTest(myTestOne)\njunit.framework.TestListener: endTest(myTestOne)\njunit.framework.TestListener: startTest(myTestTwo)\njunit.framework.TestListener: endTest(myTestTwo)\nTests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.495 sec\n"
},
{
"answer_id": 63414160,
"author": "ccpizza",
"author_id": 191246,
"author_profile": "https://Stackoverflow.com/users/191246",
"pm_score": 1,
"selected": false,
"text": "Assume.assumeTrue(interestingData, false);\n Assume.assumeTrue(interestingData, true)"
},
{
"answer_id": 66847648,
"author": "Maicon Mauricio",
"author_id": 15016163,
"author_profile": "https://Stackoverflow.com/users/15016163",
"pm_score": 1,
"selected": false,
"text": "build build/reports/tests/test/index.html"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
180,401
|
<p>I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.</p>
<p>How about these examples:</p>
<ol>
<li><code>int* test;</code></li>
<li><code>int *test;</code></li>
<li><code>int * test;</code></li>
<li><code>int* test,test2;</code></li>
<li><code>int *test,test2;</code></li>
<li><code>int * test,test2;</code></li>
</ol>
<p>Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one.</p>
<p>The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?</p>
|
[
{
"answer_id": 180409,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 8,
"selected": true,
"text": "int *test, *test2;\n int* test;\nint* test2;\n"
},
{
"answer_id": 180417,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "test test2"
},
{
"answer_id": 180420,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 6,
"selected": false,
"text": "int* test;\nint *test;\nint * test;\n int *var1, var2 int *var1;\nint var2;\n"
},
{
"answer_id": 180457,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 5,
"selected": false,
"text": "int* test; // test is a pointer to an int\n int* const test; // test is a const pointer to an int\n\nint const * test; // test is a pointer to a const int ... but many people write this as \nconst int * test; // test is a pointer to an int that's const\n"
},
{
"answer_id": 180509,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "[X] [] (type1, type2) *"
},
{
"answer_id": 180602,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": -1,
"selected": false,
"text": "int const bla;\n"
},
{
"answer_id": 8685467,
"author": "huskerchad",
"author_id": 1109067,
"author_profile": "https://Stackoverflow.com/users/1109067",
"pm_score": 4,
"selected": false,
"text": "* int* x; // \"x is a pointer to int\"\n int *x; // \"*x is an int\"\n int* x,y; // \"x is a pointer to int, y is an int\"\n int *x,y; // it's a little clearer what is going on here\n int *x, *y; // two pointers\n"
},
{
"answer_id": 12439110,
"author": "fredoverflow",
"author_id": 252000,
"author_profile": "https://Stackoverflow.com/users/252000",
"pm_score": 4,
"selected": false,
"text": "#include <type_traits>\n\nstd::add_pointer<int>::type test, test2;\n"
},
{
"answer_id": 34559760,
"author": "Michel Billaud",
"author_id": 4744142,
"author_profile": "https://Stackoverflow.com/users/4744142",
"pm_score": 2,
"selected": false,
"text": "char *a[100];\n *a[42] char a[42] a"
},
{
"answer_id": 55958119,
"author": "deLock",
"author_id": 8588773,
"author_profile": "https://Stackoverflow.com/users/8588773",
"pm_score": 2,
"selected": false,
"text": "int *pointer1, *pointer2; // Fully consistent, two pointers\nint* pointer1, pointer2; // Inconsistent -- because only the first one is a pointer, the second one is an int variable\n// The second case is unexpected, and thus prone to errors\n int x,y; int* pointer1, pointer2; pointer1 pointer2 MyClass *volatile MyObjName void test (const char *const p) // const value pointed to by a const pointer void* ClassName::getItemPtr () {return &item;} // Clear at first sight"
},
{
"answer_id": 64339233,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 4,
"selected": false,
"text": "inttest;\n inttest ; int test int test;\n * int*test;\n int * test ; int *test;\nint* test;\nint*test;\nint * test;\n unsigned long int a[10]={0}, *p=NULL, f(void);\n unsigned long int a[10]={0} *p=NULL f(void) a p f a unsigned long int ={0} p unsigned long int NULL f unsigned long int int[10] a;\n [] a int int* p;\n * p int int (*p); int* p, q;\n * p int (*p), q;\n int *test1, test2;\nint* test1, test2;\nint * test1, test2;\n test1 * int test2 int T *a[N];\n T (*a)[N];\n T *f(void);\n T (*f)(void);\n T (*a[N])(void);\n T (*f(void))[N];\n T T *(*(*f(void))[N])(void); // yes, it's eye-stabby. Welcome to C and C++.\n signal void (*signal(int, void (*)(int)))(int);\n signal -- signal\n signal( ) -- is a function taking\n signal( ) -- unnamed parameter\n signal(int ) -- is an int\n signal(int, ) -- unnamed parameter\n signal(int, (*) ) -- is a pointer to\n signal(int, (*)( )) -- a function taking\n signal(int, (*)( )) -- unnamed parameter\n signal(int, (*)(int)) -- is an int\n signal(int, void (*)(int)) -- returning void\n (*signal(int, void (*)(int))) -- returning a pointer to\n (*signal(int, void (*)(int)))( ) -- a function taking\n (*signal(int, void (*)(int)))( ) -- unnamed parameter\n (*signal(int, void (*)(int)))(int) -- is an int\nvoid (*signal(int, void (*)(int)))(int); -- returning void\n \n const const int *p; \nint const *p;\n p const int p const int x = 1;\nconst int y = 2;\n\nconst int *p = &x;\np = &y;\n *p = 3; // constraint violation, the pointed-to object is const\n int * const p;\n p const int p int x = 1;\nint y = 2;\nint * const p = &x;\n\n*p = 3;\n p p = &y; // constraint violation, p is const\n int ap int i printf( \"%d\", *ap[i] );\n *ap[i] int ap int *ap[N]; // ap is an array of pointer to int, fully specified by the combination\n // of the type specifier and declarator\n *ap[N] *ap[i] * [] [] * * ap[N] *(ap[N]) int pa i printf( \"%d\", (*pa)[i] );\n (*pa)[i] int int (*pa)[N];\n i pa i pa * pa * [] () int *p; *p int p int int * sizeof (int *) sizeof (int [10]) void foo( int *, int (*)[10] );\n * [] (int *λ) sizeof (int λ[10]) void foo( int *λ, int (*λ)[10] ); int *[10] int (*)[10] T* p;\n T* p, q; T* a[N] * a[i] T* p T* p, q; T *p, q; for i = 0;\nfor( ; i < N; ) \n{ \n ... \n i++; \n}\n T* p;"
},
{
"answer_id": 71562364,
"author": "TallChuck",
"author_id": 6284025,
"author_profile": "https://Stackoverflow.com/users/6284025",
"pm_score": 0,
"selected": false,
"text": "int* i;\n i ip int *ip;\n *ip int double *dp, atof(char *);\n *dp atof(s) double atof char int* test, test2;\n int* int int int *ip, i;\ni = *ip;\n *ip i *ip i ip"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
180,405
|
<p>I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16. </p>
<pre><code>var users = from u in dc.Users
where ((u.UserRolesBitmask & 1) == 1)
|| ((u.UserRolesBitmask & 4) == 4)
|| ((u.UserRolesBitmask & 16) == 16)
select u;
</code></pre>
<p>I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:</p>
<pre><code>private List<User> GetUsersFromRoles(uint[] UserRoles) {}
</code></pre>
<p>Any pointers on how to dynamically build my query? Thanks</p>
|
[
{
"answer_id": 180447,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 2,
"selected": false,
"text": "private List<User> GetUsersFromRoles(uint[] UserRoles) {\n uint roleMask = 0;\n for (var i = 0; i < UserRoles.Length;i++) roleMask= roleMask| UserRoles[i];\n // roleMasknow contains the OR'ed bitfields of the roles we're looking for\n\n return (from u in dc.Users where (u.UserRolesBitmask & roleMask) > 0) select u);\n}\n"
},
{
"answer_id": 180465,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 1,
"selected": false,
"text": "private List<User> GetUsersFromRoles(uint[] userRoles) \n{\n List<User> users = new List<User>();\n\n foreach(uint userRole in UserRoles)\n {\n List<User> usersInRole = GetUsersFromRole(userRole);\n foreach(User user in usersInRole )\n {\n users.Add(user);\n }\n }\n return users;\n} \n\nprivate List<User> GetUsersFromRole(uint userRole) \n{\n var users = from u in dc.Users\n where ((u.UserRolesBitmask & UserRole) == UserRole)\n select u;\n\n return users; \n}\n"
},
{
"answer_id": 180469,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 0,
"selected": false,
"text": "private List<User> GetUsersFromRoles(uint UserRoles) {\n return from u in dc.Users \n where (u.UserRolesBitmask & UserRoles) != 0\n select u;\n}\n"
},
{
"answer_id": 180488,
"author": "Lucas",
"author_id": 24231,
"author_profile": "https://Stackoverflow.com/users/24231",
"pm_score": 2,
"selected": false,
"text": "// C#\nprivate List<User> GetUsersFromRoles(uint[] UserRoles)\n{\n var users = dc.Users;\n\n foreach (uint role in UserRoles)\n {\n users = users.Where(u => (u.UserRolesBitmask & role) == role);\n }\n\n return users.ToList();\n}\n var result = from user in Users\n from role in UserRoles\n where (user.UserRolesBitmask & role) == role\n select user;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
180,422
|
<p>I'm trying to determine which records to delete from a database when a user submits a form.
The page has two CheckBoxList one representing the records before modification and one after.</p>
<p>I can easily get the selected values that need to be deleted like this...</p>
<pre><code>//get the items not selected that were selected before
var oldSelectedItems = from oItem in oldChklSpecialNeeds.Items.Cast<ListItem>()
where !(from nItem in newChklSpecialNeeds.Items.Cast<ListItem>()
where nItem.Selected
select nItem.Value).Contains(oItem.Value)
&& oItem.Selected
select oItem.Value;
</code></pre>
<p>now I am trying to do something like this but it isn't allowing it...</p>
<pre><code>var itemsToDelete = from specialNeed in db.SpecialNeeds
join oldSelectedItem in oldSelectedItems on specialNeed.SpecialNeedsTypeCd equals oldSelectedItem.Value
where specialNeed.CustomerId == customerId
</code></pre>
<p>I can easily just use a foreach loop and a .DeleteOnSubmit() for each item but I'm thinking there is a way use functionality of LINQ and pass the whole query result of an inner join to .DeleteAllOnSubmit() </p>
<pre><code>//like so
db.SpecialNeeds.DeleteAllOnSubmit(itemsToDelete);
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 180706,
"author": "Lucas",
"author_id": 24231,
"author_profile": "https://Stackoverflow.com/users/24231",
"pm_score": 3,
"selected": true,
"text": "var itemsToDelete = from specialNeed in db.SpecialNeeds\n where oldSelectedItems.Contains(specialNeed.SpecialNeedsTypeCd)\n && specialNeed.CustomerId == customerId\n select ...;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
] |
180,430
|
<p>I'm refactoring some PHP code and discovered that certain nested combinations of </p>
<pre><code>if () :
</code></pre>
<p>and </p>
<pre><code>if () {
</code></pre>
<p>generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this.</p>
<p>Example - generates syntax error:</p>
<pre><code>if ( $test == 1 ) :
if ( $test2 == 'a' ) {
if ( $test3 == 'A' ) {
} else {
}
}
else :
echo 'test2';
endif;
</code></pre>
<p>Example - does NOT generate syntax error:</p>
<pre><code>if ( $test == 1 ) :
if ( $test2 == 'a' ) :
if ( $test3 == 'A' ) :
else :
endif;
endif;
else :
echo 'test2';
endif;
</code></pre>
<p>Could someone please explain to me why the first block of code is generating an error? </p>
|
[
{
"answer_id": 180507,
"author": "I GIVE CRAP ANSWERS",
"author_id": 25083,
"author_profile": "https://Stackoverflow.com/users/25083",
"pm_score": 3,
"selected": true,
"text": "else else endif if"
},
{
"answer_id": 180995,
"author": "dmazzoni",
"author_id": 7193,
"author_profile": "https://Stackoverflow.com/users/7193",
"pm_score": 1,
"selected": false,
"text": "if ( $test == 1 ) :\n if ( $test2 == 'a' ) {\n if ( $test3 == 'A' ) {\n } else {\n }\n };\nelse :\n echo 'test2';\nendif;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24190/"
] |
180,451
|
<p>Using answers to <a href="https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays">this question</a>, I have been able to populate a select box based on the selection of another select box. ( <a href="https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays#58062">I posted my answer here</a>) Pulling the data from an array structure built server-side, stored in a .js file and referenced in the html page.</p>
<p>Now I would like to add a third select box. If I had 3 sets of data (model, make, options) something like this (pseudo code):</p>
<pre><code>cars : [Honda[Accord[Lx, Dx]], [Civic[2dr, Hatchback]],
[Toyota[Camry[Blk, Red]], [Prius[2dr,4dr]]
</code></pre>
<p>Ex: If Honda were selected, the next select box would have [Accord Civic] and if Accord were selected the next select box would have [Lx Dx]</p>
<p>How can I</p>
<p>1) create an array structure to hold the data? such that</p>
<p>2) I can use the value from one select box to reference the needed values for the next select box</p>
<p>Thanks</p>
<p><strong>EDIT</strong></p>
<p>I can create the following, but can't figure out the references in a way that would help populate a select box</p>
<pre><code>var cars = [
{"makes" : "Honda",
"models" : [
{'Accord' : ["2dr","4dr"]} ,
{'CRV' : ["2dr","Hatchback"]} ,
{'Pilot': ["base","superDuper"] } ]
},
{"makes" :"Toyota",
"models" : [
{'Prius' : ["green","reallyGreen"]} ,
{'Camry' : ["sporty","square"]} ,
{'Corolla' : ["cheap","superFly"] } ]
} ] ;
alert(cars[0].models[0].Accord[0]); ---> 2dr
</code></pre>
|
[
{
"answer_id": 180926,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 7,
"selected": true,
"text": "var carMakers = [\n { name: 'Honda', models: [\n { name: 'Accord', features: ['2dr', '4dr'] },\n { name: 'CRV', features: ['2dr', 'Hatchback'] },\n { name: 'Pilot', features: ['base', 'superDuper'] }\n ]},\n\n { name: 'Toyota', models: [\n { name: 'Prius', features: ['green', 'superGreen'] },\n { name: 'Camry', features: ['sporty', 'square'] },\n { name: 'Corolla', features: ['cheap', 'superFly'] }\n ]}\n];\n // returns array of elements whose 'prop' property is 'value'\nfunction filterByProperty(arr, prop, value) {\n return $.grep(arr, function (item) { return item[prop] == value });\n}\n\n// populates select list from array of items given as objects: { name: 'text', value: 'value' }\nfunction populateSelect(el, items) {\n el.options.length = 0;\n if (items.length > 0)\n el.options[0] = new Option('please select', '');\n\n $.each(items, function () {\n el.options[el.options.length] = new Option(this.name, this.value);\n });\n}\n\n// initialization\n$(document).ready(function () {\n // populating 1st select list\n populateSelect($('#maker').get(0), $.map(carMakers, function(maker) { return { name: maker.name, value: maker.name} }));\n\n // populating 2nd select list\n $('#maker').bind('change', function() {\n var makerName = this.value,\n carMaker = filterByProperty(carMakers, 'name', makerName),\n models = [];\n\n if (carMaker.length > 0)\n models = $.map(carMaker[0].models, function(model) { return { name: model.name, value: makerName + '.' + model.name} });\n\n populateSelect($('#model').get(0), models);\n $('#model').trigger('change');\n });\n\n // populating 3rd select list\n $('#model').bind('change', function () {\n var nameAndModel = this.value.split('.'),\n features = [];\n\n if (2 == nameAndModel.length) {\n var makerName = nameAndModel[0], \n carModel = nameAndModel[1],\n carMaker = filterByProperty(carMakers, 'name', makerName);\n\n if (carMaker.length > 0) {\n var model = filterByProperty(carMaker[0].models, 'name', carModel)\n\n if (model.length > 0)\n features = $.map(model[0].features, function(feature) { return { name: feature, value: makerName + '.' + carModel + '.' + feature} })\n }\n }\n\n populateSelect($('#feature').get(0), features);\n })\n\n // alerting value on 3rd select list change\n $('#feature').bind('change', function () { \n if (this.value.length > 0)\n alert(this.value);\n })\n});\n"
},
{
"answer_id": 187865,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 2,
"selected": false,
"text": "<html><head>\n<script language=\"Javascript\" src=\"javascript/jquery-1.2.6.min.js\"></script>\n<script type=\"text/JavaScript\">\nvar cars = [\n{ name: 'Honda', models: [\n{ name: 'Accord', features: ['2dr', '4dr'] },\n{ name: 'CRV', features: ['2dr', 'Hatchback'] },\n{ name: 'Pilot', features: ['base', 'superDuper'] }\n ]},\n{ name: 'Toyota', models: [\n{ name: 'Prius', features: ['green', 'superGreen'] },\n{ name: 'Camry', features: ['sporty', 'square'] },\n{ name: 'Corolla', features: ['cheap', 'superFly'] }\n ]\n }\n];\n$(function() {\nvar options = '' ;\nfor (var i = 0; i < cars.length; i++) {\n var opt = cars[i].name ;\n if (i == 0){ options += '<option selected value=\"' + opt + '\">' + opt + '</option>'; }\n else {options += '<option value=\"' + opt + '\">' + opt + '</option>'; } \n}\n$(\"#maker\").html(options); // populate select box with array\n\nvar options = '' ;\nfor (var i=0; i < cars[0].models.length; i++) { \n var opt = cars[0].models[0].name ;\n if (i==0){options += '<option selected value=\"' + opt + '\">' + opt + '</option>';}\n else {options += '<option value=\"' + opt + '\">' + opt + '</option>';} \n}\n$(\"#model\").html(options); // populate select box with array\n\nvar options = '' ;\nfor (var i=0; i < cars[0].models[0].features.length; i++) { \n var opt = cars[0].models[0].features[i] ;\n if (i==0){options += '<option selected value=\"' + opt + '\">' + opt + '</option>';}\n else {options += '<option value=\"' + opt + '\">' + opt + '</option>';}\n}\n$(\"#feature\").html(options); // populate select box with array\n\n$(\"#maker\").bind(\"click\",\n function() {\n $(\"#model\").children().remove() ; // clear select box\n for(var i=0; i<cars.length; i++) {\n if (cars[i].name == this.value) {\n var options = '' ;\n for (var j=0; j < cars[i].models.length; j++) { \n var opt= cars[i].models[j].name ;\n if (j==0) {options += '<option selected value=\"' + opt + '\">' + opt + '</option>';}\n else {options += '<option value=\"' + opt + '\">' + opt + '</option>';} \n }\n break;\n }\n }\n $(\"#model\").html(options); // populate select box with array\n\n $(\"#feature\").children().remove() ; // clear select box\n for(var i=0; i<cars.length; i++) {\n for(var j=0; j<cars[i].models.length; j++) {\n if(cars[i].models[j].name == $(\"#model\").val()) {\n var options = '' ;\n for (var k=0; k < cars[i].models[j].features.length; k++) { \n var opt = cars[i].models[j].features[k] ;\n if (k==0){options += '<option selected value=\"' + opt + '\">' + opt + '</option>';}\n else {options += '<option value=\"' + opt + '\">' + opt + '</option>';}\n }\n break;\n }\n }\n }\n $(\"#feature\").html(options); // populate select box with array\n });\n\n $(\"#model\").bind(\"click\",\n function() {\n $(\"#feature\").children().remove() ; // clear select box\n for(var i=0; i<cars.length; i++) {\n for(var j=0; j<cars[i].models.length; j++) {\n if(cars[i].models[j].name == this.value) {\n var options = '' ;\n for (var k=0; k < cars[i].models[j].features.length; k++) { \n var opt = cars[i].models[j].features[k] ;\n if (k==0){options += '<option selected value=\"' + opt + '\">' + opt + '</option>';}\n else {options += '<option value=\"' + opt + '\">' + opt + '</option>';}\n }\n break ;\n }\n }\n }\n $(\"#feature\").html(options); // populate select box with array\n });\n});\n</script>\n</head> <body>\n<div id=\"selection\">\n<select id=\"maker\"size=\"10\" style=\"{width=75px}\"></select>\n<select id=\"model\" size=\"10\" style=\"{width=75px}\"></select>\n<select id=\"feature\" size=\"10\"style=\"{width=75px}\"></select>\n</div></body></html>\n"
},
{
"answer_id": 7883989,
"author": "DoctorJava",
"author_id": 1011927,
"author_profile": "https://Stackoverflow.com/users/1011927",
"pm_score": 2,
"selected": false,
"text": "<html lang=\"en\">\n <head>\n <title>Populate a select dropdown list with jQuery - WebDev Ingredients</title>\n <script type=\"text/javascript\" src=\"js/jquery-1.4.2.js\"></script>\n <script type=\"text/javascript\">\n var types = [ \n { typeID: 1, name: 'Domestic'},\n { typeID: 2, name: 'Import'},\n { typeID: 3, name: 'Boat'}\n ]\n var makes = [ \n { typeID: 1, makeID: 1, name: 'Chevy'}, \n { typeID: 1, makeID: 2, name: 'Ford'}, \n { typeID: 1, makeID: 3, name: 'Delorean'}, \n { typeID: 2, makeID: 4, name: 'Honda'}, \n { typeID: 2, makeID: 5, name: 'Toyota'}, \n { typeID: 2, makeID: 6, name: 'Saab'} \n ] \n var model = [ \n { makeID: 1, modelID: 1, name: 'Camaro'}, \n { makeID: 1, modelID: 2, name: 'Chevelle'}, \n { makeID: 1, modelID: 3, name: 'Nova'}, \n { makeID: 2, modelID: 4, name: 'Focus'}, \n { makeID: 2, modelID: 5, name: 'Galaxie'}, \n { makeID: 2, modelID: 6, name: 'Mustang'}, \n { makeID: 4, modelID: 7, name: 'Accord'},\n { makeID: 4, modelID: 8, name: 'Civic'}, \n { makeID: 4, modelID: 9, name: 'Odyssey'}, \n { makeID: 5, modelID: 10, name: 'Camry'}, \n { makeID: 5, modelID: 11, name: 'Corolla'}\n ]\n // \n // Put this in a stand alone .js file\n //\n // returns array of elements whose 'prop' property is 'value' \n function filterByProperty(arr, prop, value) { \n return $.grep(arr, function (item) { return item[prop] == value }); \n } \n // populates select list from array of items given as objects: { name: 'text', value: 'value' } \n function populateSelect(el, items) { \n el.options.length = 0; \n if (items.length > 0) \n el.options[0] = new Option('please select', ''); \n $.each(items, function () { \n el.options[el.options.length] = new Option(this.name, this.value); \n }); \n } \n // initialization \n $(document).ready(function () { \n // populating 1st select list \n populateSelect($('#sType').get(0), $.map(types, function(type) { return { name: type.name, value: type.typeID} })); \n // populating 2nd select list \n $('#sType').bind('change', function() { \n var theModels = filterByProperty(makes, 'typeID', this.value);\n populateSelect($('#sMake').get(0), $.map(theModels, function(make) { return { name: make.name, value: make.makeID} })); \n $('#sMake').trigger('change'); \n }); \n // populating 3nd select list \n $('#sMake').bind('change', function() { \n var theSeries = filterByProperty(model, 'makeID', this.value); \n populateSelect($('#sModel').get(0), $.map(theSeries, function(model) { return { name: model.name, value: model.modelID} })); \n }); \n });\n </script>\n </head>\n <body>\n Enter values, click submit, and look at the post parameters\n <form method=\"get\" action=\"index.php\">\n <div id=\"selection\"> \n <select id=\"sType\" name=\"type_id\" style=\"{width=75px}\"></select> \n <select id=\"sMake\" name=\"make_id\" style=\"{width=75px}\"></select> \n <select id=\"sModel\" name=\"model_id\" style=\"{width=75px}\"></select> \n </div>\n <input type=\"submit\">\n </form>\n </body>\n</html> \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
180,452
|
<p>I have a c# form (let's call it MainForm) with a number of custom controls on it. I'd like to have the MainForm.OnClick() method fire anytime someone clicks on the form regardless of whether the click happened on the form or if the click was on one of the custom controls. I'm looking for behavior similar to the KeyPreview feature of forms except for mouse clicks rather than key presses.</p>
|
[
{
"answer_id": 180558,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded\n\n AddHandler e.Control.MouseClick, AddressOf Example_MouseClick\nEnd Sub\n\nPrivate Sub Example_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick\n MessageBox.Show(\"Click\")\nEnd Sub\n"
},
{
"answer_id": 180621,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 1,
"selected": false,
"text": " public Form1()\n {\n InitializeComponent();\n HookEvents();\n }\n\n private void HookEvents() {\n foreach (Control ctl in this.Controls) {\n ctl.MouseClick += new MouseEventHandler(Form1_MouseClick);\n }\n } \n\n void Form1_MouseClick(object sender, MouseEventArgs e)\n {\n LogEvent(sender, \"MouseClick\");\n }\n\n // and then this just logs to a multiline textbox you have somwhere on the form\n private void LogEvent(object sender, string msg) {\n this.textBox1.Text = string.Format(\"{0} {1} ({2}) \\n {3}\",\n DateTime.Now.TimeOfDay.ToString(),\n msg,\n sender.GetType().Name,\n textBox1.Text\n );\n }\n 14:51:42.3381985 MouseClick (Form1) \n14:51:40.6194485 MouseClick (RichTextBox) \n14:51:40.0100735 MouseClick (TextBox) \n14:51:39.6194485 MouseClick (Form1) \n14:51:39.2131985 MouseClick (RichTextBox) \n14:51:38.8694485 MouseClick (Button) \n"
},
{
"answer_id": 11990432,
"author": "ChéDon",
"author_id": 1329654,
"author_profile": "https://Stackoverflow.com/users/1329654",
"pm_score": 3,
"selected": false,
"text": "namespace Temp\n{\n public delegate void GlobalMouseClickEventHander(object sender, MouseEventArgs e);\n\n public partial class TestForm : Form\n {\n [Category(\"Action\")]\n [Description(\"Fires when any control on the form is clicked.\")]\n public event GlobalMouseClickEventHander GlobalMouseClick;\n\n public TestForm()\n {\n InitializeComponent();\n BindControlMouseClicks(this);\n }\n\n private void BindControlMouseClicks(Control con)\n {\n con.MouseClick += delegate(object sender, MouseEventArgs e)\n {\n TriggerMouseClicked(sender, e);\n };\n // bind to controls already added\n foreach (Control i in con.Controls)\n {\n BindControlMouseClicks(i);\n }\n // bind to controls added in the future\n con.ControlAdded += delegate(object sender, ControlEventArgs e)\n {\n BindControlMouseClicks(e.Control);\n }; \n }\n\n private void TriggerMouseClicked(object sender, MouseEventArgs e)\n {\n if (GlobalMouseClick != null)\n {\n GlobalMouseClick(sender, e);\n }\n }\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] |
180,464
|
<p>I'm running PHP on Windows/IIS.</p>
<p>My session variables don't seem to be preserved from page-to-page.</p>
<p>This code…</p>
<pre><code>//echos out the session variables in a nice format for inspection
echo "<p><pre>";
print_r($_SESSION);
echo "</pre></p>";
</code></pre>
<p>…outputs blank values, like this…</p>
<pre>
Array
(
[s_firstvar] =>
[s_var2] =>
[s_third] =>
[s_numberfour] =>
[s_youget] =>
[s_thepoint] =>
[] =>
)
</pre>
<p>I found suggestions on a forum…</p>
<blockquote>
<p>I had a similar problem recently (Win2000, IIS), and it turned out that PHP
did not have write-access to whatever directory that the session data was
stored in. You may want to look into this.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>have you set session.save_path?</p>
</blockquote>
<p>What's the proper use of php.ini's session.save_path? And, is that my problem?</p>
|
[
{
"answer_id": 180486,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "session_start() save_path session_start()"
},
{
"answer_id": 180495,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 1,
"selected": true,
"text": "$_SESSION['$s_firstvar'] = 3;\n $_SESSION['s_firstvar'] = 3;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
180,470
|
<p>Right now our test and production databases are on the same server, but with different names. Deploying has meant editing Web.config to change all the connection strings for the correct database. A step which I forget all too frequently... </p>
<p>We've finally created a new database server for testing, and I'm moving the databases over... but now the server will be different and we'll still need to deal with connection string issues. </p>
<p>I was thinking of managing it via a hosts file, but the thought of switching that on my desktop machine whenever I need to test against production data seems cumbersome at best.</p>
<p>So I'm just wondering if there's a better way out there. Something that would build with a "production" web config for deployment would be ideal...</p>
|
[
{
"answer_id": 180502,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<Target Name=\"AfterBuild\">\n <Copy Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \" SourceFiles=\"$(SourceWebPhysicalPath)\\web.release.config\" DestinationFiles=\"$(OutputPath)\\web.config\" />\n <Delete Files=\"$(OutputPath)\\web.release.config\" />\n</Target>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17145/"
] |
180,516
|
<p>I have roughly the following code. Could this be made nicer or more efficient? Perhaps using <code>std::remove_if</code>? Can you remove items from the map while traversing it? Can we avoid using the temporary map?</p>
<pre><code>typedef std::map<Action, What> Actions;
static Actions _actions;
bool expired(const Actions::value_type &action)
{
return <something>;
}
void bar(const Actions::value_type &action)
{
// do some stuff
}
void foo()
{
// loop the actions finding expired items
Actions actions;
BOOST_FOREACH(Actions::value_type &action, _actions)
{
if (expired(action))
bar(action);
else
actions[action.first]=action.second;
}
}
actions.swap(_actions);
}
</code></pre>
|
[
{
"answer_id": 180616,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 6,
"selected": true,
"text": "Actions::iterator it = _actions.begin();\nwhile (it != _actions.end())\n{\n if (expired(*it))\n {\n bar(*it);\n Actions::iterator toerase = it;\n ++it;\n _actions.erase(toerase);\n }\n else\n ++it;\n}\n"
},
{
"answer_id": 180679,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 2,
"selected": false,
"text": "Actions::iterator it = _actions.begin();\nwhile (it != _actions.end())\n{\n if (expired(*it))\n {\n bar(*it);\n it = _actions::erase(it);\n }\n else\n ++it;\n}\n"
},
{
"answer_id": 180772,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 6,
"selected": false,
"text": "for(Actions::iterator it = _actions.begin();it != _actions.end();)\n{\n if (expired(*it))\n {\n bar(*it);\n _actions.erase(it++); // Note the post increment here.\n // This increments 'it' and returns a copy of\n // the original 'it' to be used by erase()\n }\n else\n {\n ++it; // Use Pre-Increment here as it is more effecient\n // Because no copy of it is required.\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
180,518
|
<p>I've just discovered that Oracle lets you do the following:</p>
<pre><code>SELECT foo.a, (SELECT c
FROM bar
WHERE foo.a = bar.a)
from foo
</code></pre>
<p>As long as only one row in bar matches any row in foo.</p>
<p>The explain plan I get from PL/SQL developer is this:</p>
<pre><code>SELECT STATEMENT, GOAL = ALL_ROWS
TABLE ACCESS FULL BAR
TABLE ACCESS FULL FOO
</code></pre>
<p>This doesn't actually specify how the tables are joined. A colleague asserted that this is more efficient than doing a regular join. Is that true? What is the join strategy on such a select statement, and why doesn't it show up in the explain plan?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 180588,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 3,
"selected": true,
"text": "--------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n--------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1837 | 23881 | 3 (0)| 00:00:01 |\n|* 1 | TABLE ACCESS FULL| BAR | 18 | 468 | 2 (0)| 00:00:01 |\n| 2 | TABLE ACCESS FULL| FOO | 1837 | 23881 | 3 (0)| 00:00:01 |\n--------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n 1 - filter(\"BAR\".\"A\"=:B1)\n\nNote\n-----\n - dynamic sampling used for this statement\n\n18 rows selected.\n"
},
{
"answer_id": 180913,
"author": "Andrew not the Saint",
"author_id": 23670,
"author_profile": "https://Stackoverflow.com/users/23670",
"pm_score": 2,
"selected": false,
"text": "SELECT foo.a, bar1.c, pub1.d\nFROM foo\nJOIN (SELECT a, MIN(c) as c\n FROM bar\n GROUP BY a) bar1\n ON foo.a = bar1.a\nJOIN (SELECT a, MAX(d) as d\n FROM pub\n GROUP BY a) pub1\n ON foo.a = pub1.a\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15962/"
] |
180,549
|
<p>Being an aspiring Apple developer, I want to get the opinions of the community if it is better to learn C first before moving into Objective-C and ultimately the Cocoa Framework?</p>
<p>My gut says learn C, which will give me a good foundation.</p>
|
[
{
"answer_id": 3681154,
"author": "Sven",
"author_id": 431526,
"author_profile": "https://Stackoverflow.com/users/431526",
"pm_score": 1,
"selected": false,
"text": "NSString *string = [[NSString alloc] init];\nstring = @\"something\";\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8804/"
] |
180,563
|
<p>I'd like to bold the text for a tab page under certain conditions (not, necessarily, GotFocus). Is it true the only 'er easiest way to do this is by overriding the DrawItem event for the tab control?</p>
<p><a href="http://www.vbforums.com/showthread.php?t=355093" rel="noreferrer">http://www.vbforums.com/showthread.php?t=355093</a></p>
<p>It seems like there should be an easier way. </p>
<p>Like ...</p>
<p><code>
tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold)
</code></p>
<p>That doesn't work, obviously.</p>
|
[
{
"answer_id": 180637,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 3,
"selected": false,
"text": "tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold)\n tabControl.Font = New Font(Me.Font, FontStyle.Bold)\n"
},
{
"answer_id": 184122,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Private Sub Form_Current()\n If IsNull(Me.Subform.Form.Field_Name) Then\n Me.Tab_Name.Caption = \"Tab One\"\n Else\n Me.Tab_Name.Caption = \"Tab One +++\"\n End If\nEnd Sub\n"
},
{
"answer_id": 4945845,
"author": "aceregid",
"author_id": 609849,
"author_profile": "https://Stackoverflow.com/users/609849",
"pm_score": 1,
"selected": false,
"text": "private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)\n{\n Font BoldFont = new Font(tabControl1.Font, FontStyle.Bold);\n e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, BoldFont, Brushes.Black, e.Bounds);\n}\n\nprivate void Form1_Paint(object sender, PaintEventArgs e)\n{\n tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81/"
] |
180,572
|
<p>My situation is as follows:</p>
<p>I have a normalized database, in which I hold geographic information about airports. The structure is:</p>
<pre><code>airport --is in--> city --is in--> country --is in--> continent
</code></pre>
<p>Now I want to let users administrate this data, without giving them direct access to the database. We need to offer this administration interface via a web service.</p>
<p>Now, when it comes to designing the service, we ran into the discussion about how to define the operations. We came up with different solutions:</p>
<p><strong>Solution A: specific operations</strong></p>
<p>For each of the four tables (airport, city, country, continent) we define 3 operations:</p>
<ul>
<li>insert</li>
<li>get</li>
<li>update</li>
</ul>
<p>This would lead to 12 operations with 2 request/response objects = 24 objects</p>
<p>To create an all new airport with all dependencies, at least 4 requests would be necessary.</p>
<p><strong>Solution B: generic</strong></p>
<p>There is only one operation, which is controlled via parameters. This operation is capable of creating everything needed to administer the database.</p>
<p>The operation would decide what needs to be done and executes it. If an error occures, it will roll back everything.</p>
<p>==> 1 Operation = 2 highly complex request/response-objects</p>
<p><strong>Solution C: Meet in the middle 1</strong></p>
<p>One generic operation per table, which is capable of executing get, insert, update, just like solution B, but focused on one table each.</p>
<p>==> 4 operations = 8 complex request/response-objects</p>
<p><strong>Solution D: Meet in the middle 2</strong></p>
<p>One generic operation per action (get, insert, delete), which can work on each table and resolve dependencies.</p>
<p>==> 3 operations = 6 slightly more complex request/response-objects</p>
<p><strong>Example</strong></p>
<p>Since this was rather abstract, hier a simplified example for request-objects for creating (JFK/New York/USA/North America):</p>
<p><strong>Solution A:</strong></p>
<p>Request 1/4:</p>
<pre><code><insertContinent>North America</insertContinent>
</code></pre>
<p>Request 2/4:</p>
<pre><code><insertCountry continent="North America">USA</insertCountry>
</code></pre>
<p>Request 3/4:</p>
<pre><code><insertCity country="USA">New York</insertCity>
</code></pre>
<p>Request 4/4:</p>
<pre><code><insertAirport city="New York">JFK</insertAirport>
</code></pre>
<p><strong>Solution B:</strong></p>
<p>Request 1/1:</p>
<pre><code><action type="insertCountry" parent="North America">USA</action>
<action type="insertAirport" parent="New York">JFK</action>
<action type="insertContinent" parent="">North America</action>
<action type="insertCity" parent="USA">New York</action>
</code></pre>
<p><strong>Solution C:</strong></p>
<p>Request 1/4:</p>
<pre><code><countryAction type="insert" parent="North America">USA</countryAction>
</code></pre>
<p>Request 2/4:</p>
<pre><code><airportAction type="insert" parent="New York">JFK</airportAction>
</code></pre>
<p>Request 3/4:</p>
<pre><code><continentAction type="insert" parent="">North America</continentAction >
</code></pre>
<p>Request 4/4:</p>
<pre><code><cityAction type="insert" parent="USA">New York</cityAction >
</code></pre>
<p><strong>Solution D:</strong>
Request 1/1:</p>
<pre><code><insert airport="JFK" city="New York" country="USA" continent="North America" />
</code></pre>
<p>Solution D seems rather elegant for me, therefore I tried to put this in XSD:</p>
<p>Code:</p>
<pre><code><complexType name="NewContinent">
<sequence>
<element name="NAME" type="string"></element>
</sequence>
</complexType>
<complexType name="NewCountry">
<sequence>
<element name="ISOCODE" type="string"></element>
<element name="NAME" type="string"></element>
<choice>
<element name="newCONTINENT" type="tns:NewContinent"></element>
<element name="CONTINENT" type="string"></element>
</choice>
</sequence>
</complexType>
<complexType name="NewCity">
<sequence>
<element name="IATA" type="string"></element>
<element name="NAME" type="string"></element>
<choice>
<element name="COUNTRY" type="string"></element>
<element name="newCOUNTRY" type="tns:NewCountry"></element>
</choice>
</sequence>
</complexType>
<complexType name="NewAirport">
<sequence>
<element name="IATA" type="string"></element>
<element name="NAME" type="string"></element>
<choice>
<element name="CITY" type="string"></element>
<element name="newCITY" type="tns:NewCity"></element>
</choice>
</sequence>
</complexType>
</code></pre>
<p>A corresponding request would then look like follows:</p>
<pre><code><complexType name="Request">
<choice>
<element name="AIRPORT" type="tns:NewAirport"></element>
<element name="CITY" type="tns:NewCity"></element>
<element name="COUNTRY" type="tns:NewCountry"></element>
<element name="CONTINENT" type="tns:NewContinent"></element>
</choice>
</complexType>
</code></pre>
<p>Now my question: <strong>Is this really the best solution available? Is the XSD enough to understand, what is going on?</strong></p>
|
[
{
"answer_id": 184512,
"author": "Ed Greaves",
"author_id": 26262,
"author_profile": "https://Stackoverflow.com/users/26262",
"pm_score": 4,
"selected": true,
"text": "<insert airport=\"JFK\" city=\"New York\" country=\"USA\" continent=\"North America\" />\n <insert URL=\"airport?city=Chicago\">ORD</insert>\n"
},
{
"answer_id": 3272477,
"author": "DougWebb",
"author_id": 73475,
"author_profile": "https://Stackoverflow.com/users/73475",
"pm_score": 1,
"selected": false,
"text": "<airport href=\"/airports/JFK\">\n <name>JFK</name>\n <city>New York</city>\n <country>USA</country>\n <continent>North America</continent>\n</airport>\n <div class=\"object airport\" href=\"/airports/JFK\">\n <ul class=\"attributes\"> \n <li class=\"name\">JFK</li>\n <li class=\"city\">New York</li>\n <li class=\"country\">USA</li>\n <li class=\"continent\">North America</li>\n </ul>\n</div>\n /airports/JFK GET PUT DELETE /airports/ /airports/?city=New+York /airports/?country=USA GET href PUT POST /airports/ PUT POST GET PUT DELETE POST class Airport\n has String name\n has String city\n has String country\n has String continent\n method void update(name, city, country, continent)\n method void delete()\n\nclass AirportList\n method Airport[] get(opt name, opt city, opt country, opt continent)\n method void add(name, city, country, continent)\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25253/"
] |
180,601
|
<p>My style of coding includes the following idiom:</p>
<pre><code>class Derived : public Base
{
public :
typedef Base super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
</code></pre>
<p>This enables me to use "super" as an alias to Base, for example, in constructors:</p>
<pre><code>Derived(int i, int j)
: super(i), J(j)
{
}
</code></pre>
<p>Or even when calling the method from the base class inside its overridden version:</p>
<pre><code>void Derived::foo()
{
super::foo() ;
// ... And then, do something else
}
</code></pre>
<p>It can even be chained (I have still to find the use for that, though):</p>
<pre><code>class DerivedDerived : public Derived
{
public :
typedef Derived super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
void DerivedDerived::bar()
{
super::bar() ; // will call Derived::bar
super::super::bar ; // will call Base::bar
// ... And then, do something else
}
</code></pre>
<p>Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated.</p>
<p>The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword.</p>
<p>So, my questions:</p>
<ul>
<li>is this use of typedef super common/rare/never seen in the code you work with?</li>
<li>is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?</li>
<li>should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?</li>
</ul>
<p><b>Edit:</b> Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?).</p>
<p><b>Edit 2:</b> Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.</p>
|
[
{
"answer_id": 180613,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 2,
"selected": false,
"text": "boost::iterator_adaptor"
},
{
"answer_id": 180627,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 5,
"selected": false,
"text": "class Base\n{\npublic: virtual void foo() { ... }\n};\n\nclass Derived: public Base\n{\npublic:\n typedef Base super;\n virtual void foo()\n {\n super::foo(); // call superclass implementation\n\n // do other stuff\n ...\n }\n};\n\nclass DerivedAgain: public Derived\n{\npublic:\n virtual void foo()\n {\n // Call superclass function\n super::foo(); // oops, calls Base::foo() rather than Derived::foo()\n\n ...\n }\n};\n"
},
{
"answer_id": 180633,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 8,
"selected": true,
"text": "super"
},
{
"answer_id": 180634,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 7,
"selected": false,
"text": "class MyClass : public MyBase\n{\nprivate: // Prevents erroneous use by other classes.\n typedef MyBase inherited;\n...\n"
},
{
"answer_id": 180685,
"author": "jdkoftinoff",
"author_id": 32198,
"author_profile": "https://Stackoverflow.com/users/32198",
"pm_score": 2,
"selected": false,
"text": "template <typename T, size_t C, typename U>\nclass A\n{ ... };\n\ntemplate <typename T>\nclass B : public A<T,99,T>\n{ ... };\n"
},
{
"answer_id": 181917,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "base Base super template <typename TText, typename TSpec>\nclass Finder<Index<TText, PizzaChili<TSpec>>, MyFinderType>\n : public Finder<Index<TText, MyFinderImpl<TSpec>>, Default>\n{\n using TBase = Finder<Index<TText, MyFinderImpl<TSpec>>, Default>;\n // …\n}\n"
},
{
"answer_id": 5622694,
"author": "paperjam",
"author_id": 674683,
"author_profile": "https://Stackoverflow.com/users/674683",
"pm_score": 4,
"selected": false,
"text": "template <class C>\nstruct MakeAlias : C\n{ \n typedef C BaseAlias;\n};\n class Derived : public Base\n{\nprivate:\n typedef Base Super;\n};\n class Derived : public MakeAlias<Base>\n{\n // Can refer to Base as BaseAlias here\n};\n BaseAlias"
},
{
"answer_id": 31618380,
"author": "Kevin",
"author_id": 2972004,
"author_profile": "https://Stackoverflow.com/users/2972004",
"pm_score": 2,
"selected": false,
"text": "PrimaryParent template<typename BaseClass>\nclass PrimaryParent : virtual public BaseClass\n{\nprotected:\n using super = BaseClass;\npublic:\n template<typename ...ArgTypes>\n PrimaryParent<BaseClass>(ArgTypes... args) : BaseClass(args...){}\n}\n class MyObject : public PrimaryParent<SomeBaseClass>\n{\npublic:\n MyObject() : PrimaryParent<SomeBaseClass>(SomeParams) {}\n}\n PrimaryParent BaseClass BaseClass public BaseClass PrimaryParent MyObject BaseClass super PrimaryParent PrimaryParent MyObject PrimaryParent PrimaryParent class SomeOtherBase : public PrimaryParent<Ancestor>{}\n\nclass MixinClass {}\n\n//Good\nclass BaseClass : public PrimaryParent<SomeOtherBase>, public MixinClass\n{}\n\n\n//Not Good (now 'super' is ambiguous)\nclass MyObject : public PrimaryParent<BaseClass>, public SomeOtherBase{}\n\n//Also Not Good ('super' is again ambiguous)\nclass MyObject : public PrimaryParent<BaseClass>, public PrimaryParent<SomeOtherBase>{}\n PrimaryParent super PrimaryParent super PrimaryParent super"
},
{
"answer_id": 35420894,
"author": "Zhro",
"author_id": 1762276,
"author_profile": "https://Stackoverflow.com/users/1762276",
"pm_score": 0,
"selected": false,
"text": "// some header.h\n\n#define CLASS some_iterator\n#define SUPER_CLASS some_const_iterator\n#define SUPER static_cast<SUPER_CLASS&>(*this)\n\ntemplate<typename T>\nclass CLASS : SUPER_CLASS {\n typedef CLASS<T> class_type;\n\n class_type& operator++();\n};\n\ntemplate<typename T>\ntypename CLASS<T>::class_type CLASS<T>::operator++(\n int)\n{\n class_type copy = *this;\n\n // Macro\n ++SUPER;\n\n // vs\n\n // Typedef\n // super::operator++();\n\n return copy;\n}\n\n#undef CLASS\n#undef SUPER_CLASS\n#undef SUPER\n super"
},
{
"answer_id": 61619711,
"author": "metablaster",
"author_id": 12091999,
"author_profile": "https://Stackoverflow.com/users/12091999",
"pm_score": 1,
"selected": false,
"text": "super != base. #include <iostream>\n\n// Library defiens 4 classes in typical library class hierarchy\nclass Abstract\n{\npublic:\n virtual void f() = 0;\n};\n\nclass LibraryBase1 :\n virtual public Abstract\n{\npublic:\n void f() override\n {\n std::cout << \"Base1\" << std::endl;\n }\n};\n\nclass LibraryBase2 :\n virtual public Abstract\n{\npublic:\n void f() override\n {\n std::cout << \"Base2\" << std::endl;\n }\n};\n\nclass LibraryDerivate :\n public LibraryBase1,\n public LibraryBase2\n{\n // base is meaningfull only for this class,\n // this class decides who is my base in multiple inheritance\nprivate:\n using base = LibraryBase1;\n\nprotected:\n // this is super! base is not super but base!\n using super = LibraryDerivate;\n\npublic:\n void f() override\n {\n std::cout << \"I'm super not my Base\" << std::endl;\n std::cout << \"Calling my *default* base: \" << std::endl;\n base::f();\n }\n};\n\n// Library user\nstruct UserBase :\n public LibraryDerivate\n{\nprotected:\n // NOTE: If user overrides f() he must update who is super, in one class before base!\n using super = UserBase; // this typedef is needed only so that most derived version\n // is called, which calls next super in hierarchy.\n // it's not needed here, just saying how to chain \"super\" calls if needed\n\n // NOTE: User can't call base, base is a concept private to each class, super is not.\nprivate:\n using base = LibraryDerivate; // example of typedefing base.\n\n};\n\nstruct UserDerived :\n public UserBase\n{\n // NOTE: to typedef who is super here we would need to specify full name\n // when calling super method, but in this sample is it's not needed.\n\n // Good super is called, example of good super is last implementor of f()\n // example of bad super is calling base (but which base??)\n void f() override\n {\n super::f();\n }\n};\n\nint main()\n{\n UserDerived derived;\n // derived calls super implementation because that's what\n // \"super\" is supposed to mean! super != base\n derived.f();\n\n // Yes it work with polymorphism!\n Abstract* pUser = new LibraryDerivate;\n pUser->f();\n\n Abstract* pUserBase = new UserBase;\n pUserBase->f();\n}\n main()"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
] |
180,606
|
<p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
|
[
{
"answer_id": 180615,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 8,
"selected": true,
"text": ">>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]\n>>> ''.join(chr(i) for i in L)\n'hello, world'\n"
},
{
"answer_id": 180617,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 3,
"selected": false,
"text": "l = [83, 84, 65, 67, 75]\n\ns = \"\".join([chr(c) for c in l])\n\nprint s\n"
},
{
"answer_id": 181057,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "\n>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]\n>>> ''.join(map(chr,L))\n'hello, world'\n"
},
{
"answer_id": 184708,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 4,
"selected": false,
"text": "import array\ndef f7(list):\n return array.array('B', list).tostring()\n"
},
{
"answer_id": 31800289,
"author": "ptsivakumar",
"author_id": 878403,
"author_profile": "https://Stackoverflow.com/users/878403",
"pm_score": 2,
"selected": false,
"text": "def working_ascii():\n \"\"\"\n G r e e t i n g s !\n 71, 114, 101, 101, 116, 105, 110, 103, 115, 33\n \"\"\"\n\n hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]\n pmsg = ''.join(chr(i) for i in hello)\n print(pmsg)\n\n for i in range(33, 256):\n print(\" ascii: {0} char: {1}\".format(i, chr(i)))\n\nworking_ascii()\n"
},
{
"answer_id": 34246694,
"author": "David White",
"author_id": 5396645,
"author_profile": "https://Stackoverflow.com/users/5396645",
"pm_score": 3,
"selected": false,
"text": "charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]\nmystring = \"\"\nfor char in charlist:\n mystring = mystring + chr(char)\nprint mystring\n"
},
{
"answer_id": 53691464,
"author": "Idan Rakovsky",
"author_id": 10766457,
"author_profile": "https://Stackoverflow.com/users/10766457",
"pm_score": 0,
"selected": false,
"text": "Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]\nprint(''.join(chr(number) for number in Question))\n"
},
{
"answer_id": 55509509,
"author": "Timo Herngreen",
"author_id": 8810830,
"author_profile": "https://Stackoverflow.com/users/8810830",
"pm_score": 3,
"selected": false,
"text": "bytes(list).decode() list(string.encode())"
},
{
"answer_id": 61790880,
"author": "user13528444",
"author_id": 13528444,
"author_profile": "https://Stackoverflow.com/users/13528444",
"pm_score": 1,
"selected": false,
"text": "bytes(seq).decode() test_bytes_decode : 12.8046 μs/rep\n test_join_map : 62.1697 μs/rep\ntest_array_library : 63.7088 μs/rep\n test_join_list : 112.021 μs/rep\ntest_join_iterator : 171.331 μs/rep\n test_naive_add : 286.632 μs/rep\n import array, string, timeit, random\nfrom collections import namedtuple\n\n# Thomas Wouters (https://stackoverflow.com/a/180615/13528444)\ndef test_join_iterator(seq):\n return ''.join(chr(c) for c in seq)\n\n# community wiki (https://stackoverflow.com/a/181057/13528444)\ndef test_join_map(seq):\n return ''.join(map(chr, seq))\n\n# Thomas Vander Stichele (https://stackoverflow.com/a/180617/13528444)\ndef test_join_list(seq):\n return ''.join([chr(c) for c in seq])\n\n# Toni Ruža (https://stackoverflow.com/a/184708/13528444)\n# Also from https://www.python.org/doc/essays/list2str/\ndef test_array_library(seq):\n return array.array('b', seq).tobytes().decode() # Updated from tostring() for Python 3\n\n# David White (https://stackoverflow.com/a/34246694/13528444)\ndef test_naive_add(seq):\n output = ''\n for c in seq:\n output += chr(c)\n return output\n\n# Timo Herngreen (https://stackoverflow.com/a/55509509/13528444)\ndef test_bytes_decode(seq):\n return bytes(seq).decode()\n\nRESULT = ''.join(random.choices(string.printable, None, k=1000))\nINT_SEQ = [ord(c) for c in RESULT]\nREPS=10000\n\nif __name__ == '__main__':\n tests = {\n name: test\n for (name, test) in globals().items()\n if name.startswith('test_')\n }\n\n Result = namedtuple('Result', ['name', 'passed', 'time', 'reps'])\n results = [\n Result(\n name=name,\n passed=test(INT_SEQ) == RESULT,\n time=timeit.Timer(\n stmt=f'{name}(INT_SEQ)',\n setup=f'from __main__ import INT_SEQ, {name}'\n ).timeit(REPS) / REPS,\n reps=REPS)\n for name, test in tests.items()\n ]\n results.sort(key=lambda r: r.time if r.passed else float('inf'))\n\n def seconds_per_rep(secs):\n (unit, amount) = (\n ('s', secs) if secs > 1\n else ('ms', secs * 10 ** 3) if secs > (10 ** -3)\n else ('μs', secs * 10 ** 6) if secs > (10 ** -6)\n else ('ns', secs * 10 ** 9))\n return f'{amount:.6} {unit}/rep'\n\n max_name_length = max(len(name) for name in tests)\n for r in results:\n print(\n r.name.rjust(max_name_length),\n ':',\n 'failed' if not r.passed else seconds_per_rep(r.time))\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
180,624
|
<p>I'm developing a solution which uses an ActiveX control (a commercial one which we bought and that I did not develop). I need to develop the proper installation pages to simulate what happens when a user who has never visited the site and does not have the add-on installed comes to the page.</p>
<p>I've found the "Manage Add-Ons" bit in Internet Options and I'm not having any luck.</p>
<p>In IE7, I see an ability to enable or disable any control and a "Delete ActiveX" option, but it's disabled for this particular control.</p>
<p>In IE8 Beta 2, the "Manage Add-Ons" bit has been completely reworked and I no longer see an option to delete the control. Each control has a "Properties" dialog and I can "Remove" it, but the button doesn't appear to do anything (could be related to how "Delete ActiveX" doesn't work for this on in IE7).</p>
<p>It looks like maybe this control is installed in such a way that merely deleting it from IE won't work or isn't allowed, but it's not a control with its own entry on the Add/Remove Programs menu in XP, so I can't uninstall it that way either.</p>
<p>How can I delete/remove (not disable) this ActiveX control in IE so that I can simulate what happens when people come to the site and the ActiveX control hasn't been installed yet? I figure there must be a way to "purge" IE of it.</p>
|
[
{
"answer_id": 180640,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 4,
"selected": true,
"text": "regsvr32 /u badboy.ocx\n"
},
{
"answer_id": 6303168,
"author": "Prasi",
"author_id": 792300,
"author_profile": "https://Stackoverflow.com/users/792300",
"pm_score": -1,
"selected": false,
"text": "IE Tools -> Internet options -> Advanced Tab"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
] |
180,626
|
<p>I am hosting a service within a Windows Service. </p>
<p>The following snippet instantiates the ServiceHost object:</p>
<pre><code>Host = new ServiceHost(typeof(Services.DocumentInfoService));
</code></pre>
<p>The DocumentInfoService class implements a contract interface that has methods that invoke business objects requiring initialization (actually a connection string). Ideally, I'd like the hosting process to get the connection string from the config file and pass it to a constructor for my service object, DocumentInfoService, which would hold onto it and use it to pass to business objects as needed.</p>
<p>However, the ServiceHost constructor takes a System.Type object -- so instances of DocumentInfoService are created via the default constructor. I did note that there is another constructor method for ServiceHost that takes an object instance -- but the docs indicate that is for use with singletons.</p>
<p>Is there a way for me to get to my object after it is constructed so that I can pass it some initialization data?</p>
|
[
{
"answer_id": 180645,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "ServiceHost"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7961/"
] |
180,629
|
<p>I am using VS 2008/C# and binding a local List of helper classes as the DataSource for a DataGridView control. Calling the Remove() method on my List of helper classes fires the CellFormatting event of the DataGridView, which makes sense (a bit). </p>
<p>When removing whatever happens to be the DataBoundItem of the last row in the grid (so long as the grid has more than one row) the DataGridView's Rows collection is not updated before this event fires. So, in the CellFormatting event handler, I get an IndexOutOfRangeException as the Rows collection is one too large.</p>
<p>I've tried removing the row using the DataGridView.Rows.Remove() method, and binding using a BindingSource rather than binding the List directly as the data source.</p>
<p>I found a few references to this occurance via Google, but answers were either not forthcoming or said to use a Delete() method on either the DataGridView or the DataGridView.Rows collection - neither of which currently exist.</p>
<p>Sorting does not appear to be the issue either, as performing/not performing a sort results in the same outcome.</p>
<p>The only exception to the "last row" being a problem for removal is if the DataGridView contains only one row - in which case everything works fine.</p>
|
[
{
"answer_id": 3862495,
"author": "inam101",
"author_id": 407339,
"author_profile": "https://Stackoverflow.com/users/407339",
"pm_score": 0,
"selected": false,
"text": "private void dgViewItems_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)\n{\n dataAdapter.Update((DataTable)bindingSource1.DataSource);\n}\n"
},
{
"answer_id": 5357428,
"author": "DCNYAM",
"author_id": 30419,
"author_profile": "https://Stackoverflow.com/users/30419",
"pm_score": 0,
"selected": false,
"text": "RemoveHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting\nMe.BindingSource1.Remove(item)\nAddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting\n"
},
{
"answer_id": 5917465,
"author": "Caravansary",
"author_id": 725001,
"author_profile": "https://Stackoverflow.com/users/725001",
"pm_score": 1,
"selected": false,
"text": " If Dgv.CurrentCell.RowIndex + 1 = Dgv.Rows.Count Then\n For m = Dgv.Rows.Count - 2 To 0 Step -1\n Dgv.Rows(m + 1).Cells(0).Value = Dgv.Rows(m).Cells(0).Value\n Dgv.Rows(m + 1).Cells(1).Value = Dgv.Rows(m).Cells(1).Value\n Dgv.Rows(m + 1).Cells(2).Value = Dgv.Rows(m).Cells(2).Value\n Dgv.Rows(m + 1).Cells(3).Value = Dgv.Rows(m).Cells(3).Value\n\n Next\n Dgv.Rows.RemoveAt(0)\n Exit Sub\n End If\n Dgv.Rows.Remove(Dgv.CurrentRow)\n"
},
{
"answer_id": 10913319,
"author": "Asad Naeem",
"author_id": 390163,
"author_profile": "https://Stackoverflow.com/users/390163",
"pm_score": 2,
"selected": false,
"text": "myDataGridView1.AllowUserToAddRows = false\n"
},
{
"answer_id": 14608317,
"author": "Airy",
"author_id": 2026065,
"author_profile": "https://Stackoverflow.com/users/2026065",
"pm_score": 3,
"selected": false,
"text": "Datagridview dataGridView1.AllowUserToAddRows = false;\n dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);\ndataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25971/"
] |
180,638
|
<p>My database application is going to be deployed at multiple sites in different time zones.</p>
<p>I need a T-SQL function that will determine the UTC timestamp of midnight on January 1 of the current year for YTD calculations. All of the data is stored in UTC timestamps.</p>
<p>For example, Chicago is UTC-6 with Daylight Savings Time (DST), the function needs to return '2008-01-01 06:00:00' if run any time in 2008 in Chicago. If run in New York (GMT-5 + DST) next year, it needs to return '2009-01-01 05:00:00'.</p>
<p>I can get the current year from <code>YEAR(GETDATE())</code>. I thought I could do a <code>DATEDIFF</code> between <code>GETDATE()</code> and <code>GETUTCDATE()</code> to determine the offset but the result depends on whether the query is run during DST or not. I do not know of any built in T-SQL functions for determining the offset or whether or not the current time is DST or not?</p>
<p>Does anyone have a solution to this problem in T-SQL? I could hard code it or store it in a table but would prefer not to. I suppose that this is a perfect situation for using CLR Integration in SQL Server 2005. I am just wondering if there is a T-SQL solution that I am unaware of?</p>
|
[
{
"answer_id": 180694,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 0,
"selected": false,
"text": "(timestamp + (getutcdate() - getdate())) > cast('01/01/2008' as datetime)\n getdate()"
},
{
"answer_id": 180700,
"author": "neonski",
"author_id": 17112,
"author_profile": "https://Stackoverflow.com/users/17112",
"pm_score": 0,
"selected": false,
"text": "FROM_TZ(YOUR_TIMESTAMP, 'UTC') AT TIME ZONE 'America/Dawson_Creek'\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8785/"
] |
180,647
|
<p>I am hoping to find a resource for lining up input elements in a HTML page. I find it difficult to get a select element and a text box to be the same width even when using the width style attribute, and it is even more difficult across browsers. Finally, file inputs seem impossible to get to the same width cross browser. Are there any good guides or tips for accomplishing this? Perhaps there are some default CSS attributes I should be setting.</p>
|
[
{
"answer_id": 180660,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "input, select {\n width: 100px;\n margin: 0px;\n border: 1px solid;\n}\n"
},
{
"answer_id": 181523,
"author": "cowgod",
"author_id": 6406,
"author_profile": "https://Stackoverflow.com/users/6406",
"pm_score": 5,
"selected": true,
"text": "<select> <input type=\"file\"> <select> <select> <input type=\"file\"> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n <title>Example Form</title>\n <style type=\"text/css\">\n label,\n input,\n select,\n textarea {\n display: block;\n width: 200px;\n float: left;\n margin-bottom: 1em;\n }\n \n select {\n width: 205px;\n }\n \n label {\n text-align: right;\n width: 100px;\n padding-right: 2em;\n }\n \n .clear {\n clear: both;\n }\n </style>\n</head>\n\n<body>\n <form action=\"#\">\n <fieldset>\n <legend>User Profile</legend>\n <label for=\"fname\">First Name</label>\n <input id=\"fname\" name=\"fname\" type=\"text\" />\n <br class=\"clear\" />\n\n <label for=\"lname\">Last Name</label>\n <input id=\"lname\" name=\"lname\" type=\"text\" />\n <br class=\"clear\" />\n\n <label for=\"fav_lang\">Favorite Language</label>\n <select id=\"fav_lang\" name=\"fav_lang\">\n <option value=\"c#\">C#</option>\n <option value=\"java\">Java</option>\n <option value=\"ruby\">Ruby</option>\n <option value=\"python\">Python</option>\n <option value=\"perl\">Perl</option>\n </select>\n <br class=\"clear\" />\n\n <label for=\"bio\">Biography</label>\n <textarea id=\"bio\" name=\"bio\" cols=\"14\" rows=\"4\"></textarea>\n <br class=\"clear\" />\n </fieldset>\n </form>\n</body>\n\n</html>"
},
{
"answer_id": 1750099,
"author": "AlfaTeK",
"author_id": 43671,
"author_profile": "https://Stackoverflow.com/users/43671",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n <title></title>\n <link href=\"styles/reset.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n <style type=\"text/css\">\n input, select{\n width: 100%;\n }\n </style>\n</head>\n<body>\n\n<div style=\"width: 200px;\">\n <input type=\"text\">\n <select>\n <option>asdasd</option>\n <option>asdasd</option>\n </select>\n\n</div>\n\n</body>\n</html>\n"
},
{
"answer_id": 7861529,
"author": "Dalius",
"author_id": 1008798,
"author_profile": "https://Stackoverflow.com/users/1008798",
"pm_score": 2,
"selected": false,
"text": "<form class=\"style\">\n <input name=\"someInput\" />\n <select name=\"options\">\n <option value=\"1\">Value 1</option>\n <option value=\"2\">Value 2</option>\n </select>\n</form>\n\n.style select {\n width: 100px;\n padding: 1px;\n border: 1px solid black;\n}\n.style input {\n width: 96px; /* -2 px for 1px padding(1px from each side) and -2px for border\n (select element seems to put border inside, not outside?) */\n padding: 1px;\n border: 1px solid black;\n}\n"
},
{
"answer_id": 9112877,
"author": "Slawa",
"author_id": 417153,
"author_profile": "https://Stackoverflow.com/users/417153",
"pm_score": 0,
"selected": false,
"text": "$(function () {\n var allSelects = $('input[type=\"text\"], textarea');\n allSelects.css('width', (allSelects.width()-6)+'px');\n}\n"
},
{
"answer_id": 11011842,
"author": "Jim",
"author_id": 470206,
"author_profile": "https://Stackoverflow.com/users/470206",
"pm_score": 0,
"selected": false,
"text": "input { width: 200px; padding: 10px; border-width:5px; }\nselect { width: 230px; padding: 10px; border-width:5px; }\n input, select {\n width: 200px;\n padding: 10px;\n border-width:5px;\n -webkit-box-sizing: content-box; /* Safari/Chrome, other WebKit */\n -moz-box-sizing: content-box; /* Firefox, other Gecko */\n box-sizing: content-box; /* Opera/IE 8+ */\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
] |
180,658
|
<p>When 'val' below is not a <code>bool</code> I get an exception, I believe I can use <code>TryParse</code> but I'm not sure how best to use it with my code below. Can anyone help?</p>
<pre><code>checkBox.Checked = Convert.ToBoolean(val);
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 180663,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "val Checked bool result;\nif (bool.TryParse(val, out result))\n{\n // val does represent a Boolean\n checkBox.Checked = result;\n}\nelse\n{\n // val does not represent a Boolean\n}\n"
},
{
"answer_id": 180665,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "bool result = false;\nbool.TryParse(val, out result);\ncheckBox.Checked = result;\n"
},
{
"answer_id": 180666,
"author": "Yes - that Jake.",
"author_id": 5287,
"author_profile": "https://Stackoverflow.com/users/5287",
"pm_score": 1,
"selected": false,
"text": "bool z = false;\nif(Boolean.TryParse(val, out z))\n{\n checkBox.Checked = z;\n}\n"
},
{
"answer_id": 180672,
"author": "Mesh",
"author_id": 15710,
"author_profile": "https://Stackoverflow.com/users/15710",
"pm_score": 0,
"selected": false,
"text": "if( isBool ) \n{\n ///ok;\n\n}\nelse\n{\n // fail;\n}\n"
},
{
"answer_id": 180677,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 0,
"selected": false,
"text": "bool output;\ncheckBox.Checked = bool.TryParse(val, out output) && output;\n checkBox.Checked = val != 0; \n"
},
{
"answer_id": 4511177,
"author": "mkamoski",
"author_id": 348907,
"author_profile": "https://Stackoverflow.com/users/348907",
"pm_score": 0,
"selected": false,
"text": "bool myBool = val ?? false;\n"
},
{
"answer_id": 15793180,
"author": "Mick Bruno",
"author_id": 730366,
"author_profile": "https://Stackoverflow.com/users/730366",
"pm_score": -1,
"selected": false,
"text": "bool shouldCheck;\nTryParseBool(val, out shouldCheck);\ncheckBox.Checked = shouldCheck;\n\n/// <summary>\n/// Legal values: Case insensitive strings TRUE/FALSE, T/F, YES/NO, Y/N, numbers (0 => false, non-zero => true)\n/// Similar to \"bool.TryParse(string text, out bool)\" except that it handles values other than 'true'/'false'\n/// </summary>\npublic static bool TryParseBool(object inVal, out bool retVal)\n{\n // There are a couple of built-in ways to convert values to boolean, but unfortunately they skip things like YES/NO, 1/0, T/F\n //bool.TryParse(string, out bool retVal) (.NET 4.0 Only); Convert.ToBoolean(object) (requires try/catch)\n inVal = (inVal ?? \"\").ToString().Trim().ToUpper();\n switch ((string)inVal)\n {\n case \"TRUE\":\n case \"T\":\n case \"YES\":\n case \"Y\":\n retVal = true;\n return true;\n case \"FALSE\":\n case \"F\":\n case \"NO\":\n case \"N\":\n retVal = false;\n return true;\n default:\n // If value can be parsed as a number, 0==false, non-zero==true (old C/C++ usage)\n double number;\n if (double.TryParse((string)inVal, out number))\n {\n retVal = (number != 0);\n return true;\n }\n // If not a valid value for conversion, return false (not parsed)\n retVal = false;\n return false;\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
180,741
|
<p>How do you iterate over each file in a directory with a .bat or .cmd file?</p>
<p>For simplicity please provide an answer that just echoes the filename or file path.</p>
|
[
{
"answer_id": 180749,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 10,
"selected": true,
"text": "for /f %f in ('dir /b c:\\') do echo %f\n for /f %%f in ('dir /b c:\\') do echo %%f\n for /f for /f \"delims=|\" %%f in ('dir /b c:\\') do echo %%f\n usebackq for for /f \"usebackq delims=|\" %%f in (`dir /b \"c:\\program files\"`) do echo %%f\n ^ for /f \"usebackq delims=|\" %%f in (`dir /b \"c:\\program files\" ^| findstr /i microsoft`) do echo %%f\n"
},
{
"answer_id": 180758,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 5,
"selected": false,
"text": "for /r path %%var in (*.*) do some_command %%var\n"
},
{
"answer_id": 12965217,
"author": "Paul Houx",
"author_id": 858219,
"author_profile": "https://Stackoverflow.com/users/858219",
"pm_score": 7,
"selected": false,
"text": "forfiles /s /m *.png /c \"cmd /c echo @path\"\n"
},
{
"answer_id": 16553191,
"author": "Anon",
"author_id": 2383535,
"author_profile": "https://Stackoverflow.com/users/2383535",
"pm_score": 0,
"selected": false,
"text": "for /f \"delims=|\" %f in ('forfiles') do attrib -s -h -r %f"
},
{
"answer_id": 19849383,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 6,
"selected": false,
"text": "for %f in (*.*) do echo %f\n for %%f in (*.*) do echo %%f\n for %%f in (%1\\*.*) do echo %%f\n"
},
{
"answer_id": 36683463,
"author": "thistleknot",
"author_id": 1731972,
"author_profile": "https://Stackoverflow.com/users/1731972",
"pm_score": 3,
"selected": false,
"text": "for %f in (*.mp4) do call ffmpeg -i \"%~f\" -vcodec copy -acodec copy \"%~nf.avi\"\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
180,746
|
<p>I have an upcoming project which will have to be able to print simple reports from its data. It'll be WPF-based, and I'm wondering which way to go.</p>
<p>I know that WPF introduces its own printing technology (based on XPS) which looks quite easy to use. However, part of me wonders whether it would just be easier to use the ReportViewer control and embed it in a Windows Forms host control, since that will give users the ability to export to a variety of formats as well as print.</p>
<p>Has anyone had any experience with printing/reporting from WPF? Which direction would you recommend?</p>
|
[
{
"answer_id": 2830252,
"author": "Ray Burns",
"author_id": 199245,
"author_profile": "https://Stackoverflow.com/users/199245",
"pm_score": 5,
"selected": false,
"text": "DocumentPaginator Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => {} ));"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] |
180,750
|
<p>Is there a way to take substrings of a string with .bat/.cmd files?</p>
<p>For example given the string "hello.txt" is there a way to strip the .txt?</p>
<p>EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?</p>
|
[
{
"answer_id": 180766,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 4,
"selected": true,
"text": "test.bat\n----------\necho %~n1 %~n2\n\nc:\\> test.bat myfile.txt my.long.file.bat\n myfile my.long.file\n echo %variable:0,4% => \"test.txt\" => \"test\"\n echo %variable:~0,-4% => \"file...name.txt\" => \"file...name\"\n"
},
{
"answer_id": 180768,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 0,
"selected": false,
"text": "%~n1"
},
{
"answer_id": 180790,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 1,
"selected": false,
"text": "help set set source=hello.txt\nREM print hello\necho %source:~0,-4%\nREM print o.t\necho %source:~4,3%\nREM print help.txt\necho %source:lo=p%\nREM etc\necho %source:llo=%\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
180,760
|
<p>Can someone explain how to use if-then statements and for loops in Makefiles? I can't seem to find any good documentation with examples.</p>
|
[
{
"answer_id": 180775,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 4,
"selected": false,
"text": "ifeq ($(strip $(OS)),Linux)\n PYTHON = /usr/bin/python\n FIND = /usr/bin/find\nendif\n"
},
{
"answer_id": 180818,
"author": "John Mulder",
"author_id": 2242,
"author_profile": "https://Stackoverflow.com/users/2242",
"pm_score": 7,
"selected": true,
"text": "conditional-directive\ntext-if-true\nendif\n conditional-directive\ntext-if-true\nelse\ntext-if-false\nendif\n conditional-directive\ntext-if-one-is-true\nelse\nconditional-directive\ntext-if-true\nelse\ntext-if-false\nendif\nendif\n ifeq (arg1, arg2)\nifeq 'arg1' 'arg2'\nifeq \"arg1\" \"arg2\"\nifeq \"arg1\" 'arg2'\nifeq 'arg1' \"arg2\"\n ifneq (arg1, arg2)\nifneq 'arg1' 'arg2'\nifneq \"arg1\" \"arg2\"\nifneq \"arg1\" 'arg2'\nifneq 'arg1' \"arg2\"\n ifdef variable-name\n ifndef variable-name \n $(foreach var, list, text) \n"
},
{
"answer_id": 5893113,
"author": "Kramer",
"author_id": 125368,
"author_profile": "https://Stackoverflow.com/users/125368",
"pm_score": 3,
"selected": false,
"text": "LIST_OF_THINGS_TO_DO = do_this do_that \n$(LIST_OF_THINGS_TO_DO): \n run $@ > $@.out\n\nSUBDIRS = snafu fubar\n$(SUBDIRS):\n cd $@ && $(MAKE)\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2039/"
] |
180,777
|
<p>I have a ListBox which displays items of variable height. I want to show as many items as will fit in the available space, without showing a vertical scrollbar. Other than surgery on the ListBox item template, is there a way to only show the number of items which will fit without scrolling?</p>
|
[
{
"answer_id": 180824,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 5,
"selected": true,
"text": " <ListBox ScrollViewer.VerticalScrollBarVisibility=\"Auto\" /> \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] |
180,793
|
<p>I need to clip out all the occurances of the pattern '--' that are <em>inside</em> single quotes in long string (leaving intact the ones that are outside single quotes). </p>
<p>Is there a RegEx way of doing this?
(using it with an iterator from the language is OK).</p>
<p>For example, starting with</p>
<pre><code>"xxxx rt / $ 'dfdf--fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '--ggh--' vcbcvb"
</code></pre>
<p>I should end up with:</p>
<pre><code>"xxxx rt / $ 'dfdffggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g 'ggh' vcbcvb"
</code></pre>
<p>So I am looking for a regex that could be run from the following languages as shown:</p>
<pre><code> +-------------+------------------------------------------+
| Language | RegEx |
+-------------+------------------------------------------+
| JavaScript | input.replace(/someregex/g, "") |
| PHP | preg_replace('/someregex/', "", input) |
| Python | re.sub(r'someregex', "", input) |
| Ruby | input.gsub(/someregex/, "") |
+-------------+------------------------------------------+
</code></pre>
|
[
{
"answer_id": 180837,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "(?( ) | ) def remove_double_dashes_in_apostrophes(text):\n return \"'\".join(\n part.replace(\"--\", \"\") if (ix&1) else part\n for ix, part in enumerate(text.split(\"'\")))\n"
},
{
"answer_id": 180856,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "import re\np = re.compile(r\"((?:^[^']*')?[^']*?(?:'[^']*'[^']*?)*?)(-{2,})\")\ntxt = \"xxxx rt / $ 'dfdf--fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '--ggh--' vcbcvb\"\nprint re.sub(p, r'\\1-', txt)\n xxxx rt / $ 'dfdf-fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '-ggh-' vcbcvb\n ( # Group 1\n (?:^[^']*')? # Start of string, up till the first single quote\n [^']*? # Inside the single quotes, as few characters as possible\n (?:\n '[^']*' # No double dashes inside theses single quotes, jump to the next.\n [^']*?\n )*? # as few as possible\n)\n(-{2,}) # The dashes themselves (Group 2)\n -{2,}(?=[^'`]*`)\n (?:^[^']*')?\n (?:^[^']*'|(?!^))\n ((?:^[^']*'|(?!^))[^']*?(?:'[^']*'[^']*?)*?)(-{2,})\n"
},
{
"answer_id": 180950,
"author": "bog",
"author_id": 20909,
"author_profile": "https://Stackoverflow.com/users/20909",
"pm_score": 0,
"selected": false,
"text": ":again\ns/'\\(.*\\)--\\(.*\\)'/'\\1\\2'/g\nt again\n :again s/'\\(.*\\)--\\(.*\\)'/'\\1\\2'/g t again"
},
{
"answer_id": 181181,
"author": "Mike Berrow",
"author_id": 17251,
"author_profile": "https://Stackoverflow.com/users/17251",
"pm_score": 3,
"selected": true,
"text": "--(?=[^\\']*'([^']|'[^']*')*$)\n (?=...) input.replace(/--(?=[^']*'([^']|'[^']*')*$)/g, \"\") preg_replace('/--(?=[^\\']*'([^']|'[^']*')*$)/', \"\", input) re.sub(r'--(?=[^\\']*'([^']|'[^']*')*$)', \"\", input) input.gsub(/--(?=[^\\']*'([^']|'[^']*')*$)/, \"\")"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17251/"
] |
180,796
|
<p>I have a servlet which is in the same web application as the JSF servlet.
How do I replace (rather than redirect) the servlet response with the JSF response? </p>
|
[
{
"answer_id": 180903,
"author": "Martin",
"author_id": 24364,
"author_profile": "https://Stackoverflow.com/users/24364",
"pm_score": 1,
"selected": false,
"text": "public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {\n // Do stuff\n req.getRequestDispatcher(\"/blah.jsf\").forward(req, res);\n // Do other stuff\n}\n"
},
{
"answer_id": 6114847,
"author": "Ondřej Xicht Světlík",
"author_id": 768106,
"author_profile": "https://Stackoverflow.com/users/768106",
"pm_score": 0,
"selected": false,
"text": " <rule>\n <from>^/my/servlet/uri</from>\n <to>/jsfpage.jsf</to>\n </rule>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
180,809
|
<p>Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface?</p>
<p>In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.</p>
|
[
{
"answer_id": 180816,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 8,
"selected": true,
"text": "save_as = True\n"
},
{
"answer_id": 49752122,
"author": "kontextify",
"author_id": 2231950,
"author_profile": "https://Stackoverflow.com/users/2231950",
"pm_score": 3,
"selected": false,
"text": "save_as"
},
{
"answer_id": 56566322,
"author": "Abel",
"author_id": 7995920,
"author_profile": "https://Stackoverflow.com/users/7995920",
"pm_score": 0,
"selected": false,
"text": "def duplicate_jorn(modeladmin, request, queryset):\n post_url = request.META['HTTP_REFERER']\n\n for object in queryset:\n object.id = None\n object.name = object.name+'-b'\n object.save()\n\n return HttpResponseRedirect(post_url)\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23366/"
] |
180,814
|
<p>Here's my situation.</p>
<p>I have a button on my ASP.NET webform. This button creates a new browser window pointing to a page which has a lot of hidden fields (which are dynamically generated). This form submits itself to SQL Reporting Services on the bodies onload event. This works fine and the report is displayed in this new window.</p>
<p>However, now I want to still POST a form to SQL Reporting services but I want to get back an excel spreadsheet. So I add another hidden input with a name of rs:Format and value of Excel. This works and the user gets the option to download the excel file.</p>
<p>However they are now stuck with the extra window that was created. How do I get around this? I've tried creating the dynamic form and POST in the same window, but then they see the (empty) page with the form, and not the page they generated the report from. I've tried closing the window that I've created but I don't know where to put the javascript to do this. If I put it on the onload, then the window closes without the form being submitted.</p>
<p>Any ideas for what to do here?</p>
<p>Edit: What I was doing here wasn't the best way of getting the result I needed. I ended up using a WebRequest to get the excel report from Reporting Services instead posting a form, therefore I didn't need the second window afterall.</p>
|
[
{
"answer_id": 180826,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "function getReport(excelFormat)\n{\n if (excelFormat)\n document.form1.target = '_blank';\n else\n document.form1.target = '_self';\n document.form1.submit();\n}\n"
},
{
"answer_id": 180934,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\n function submitReport( button ) {\n PageMethod.SubmitReport(onSuccess,onFailure,{ control: button });\n }\n\n function onSuccess(values,ctx) {\n var form = document.createElement('form');\n form.action = reporting-services.url;\n form.method = 'post';\n document.body.appendChild(form);\n .... add hidden fields to form from returned values\n form.submit();\n document.body.removeChild(form);\n }\n\n function onFailure(error,ctx) {\n ... pop up some error message....\n }\n\n </script>\n\n ...\n\n <asp:Button runat=\"server\" id=\"reportButton\" ClientClick=\"submitReport(this);return false;\" Text=\"Report\" />\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] |
180,841
|
<p>Here are some gems:</p>
<p>Literals:</p>
<pre><code>var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');
</code></pre>
<p>Defaults:</p>
<pre><code>arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';
</code></pre>
<p>Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:</p>
<pre><code>(function() { ... })(); // Creates an anonymous function and executes it
</code></pre>
<p><strong>Question:</strong> What other great syntactic sugar is available in javascript?</p>
|
[
{
"answer_id": 180866,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 4,
"selected": false,
"text": "==="
},
{
"answer_id": 180867,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 3,
"selected": false,
"text": "check ? value1 : value2\n"
},
{
"answer_id": 180907,
"author": "VirtuosiMedia",
"author_id": 13281,
"author_profile": "https://Stackoverflow.com/users/13281",
"pm_score": 2,
"selected": false,
"text": "var foo = (condition) ? value1 : value2;\n"
},
{
"answer_id": 180916,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 5,
"selected": false,
"text": "String.prototype.isNullOrEmpty = function(input) {\n return input === null || input.length === 0;\n}\n"
},
{
"answer_id": 180933,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 5,
"selected": false,
"text": "var getter, setter;\n\n(function()\n{\n var _privateVar=123;\n getter = function() { return _privateVar; };\n setter = function(v) { _privateVar = v; };\n})()\n"
},
{
"answer_id": 181939,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "function Foo(bar)\n{\n this._bar = bar;\n}\n\nFoo.prototype =\n{\n get bar()\n {\n return this._bar;\n },\n\n set bar(bar)\n {\n this._bar = bar.toUpperCase();\n }\n};\n >>> var myFoo = new Foo(\"bar\");\n>>> myFoo.bar\n\"BAR\"\n>>> myFoo.bar = \"Baz\";\n>>> myFoo.bar\n\"BAZ\"\n"
},
{
"answer_id": 182231,
"author": "Pablo Cabrera",
"author_id": 12540,
"author_profile": "https://Stackoverflow.com/users/12540",
"pm_score": 2,
"selected": false,
"text": "myArray.forEach(function(element) { alert(element); });\n"
},
{
"answer_id": 186150,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "(function() { ... }).someMethod(); // Functions as objects\n"
},
{
"answer_id": 224114,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 7,
"selected": true,
"text": "Date.now()\n var start = Date.now();\n// some code\nalert((Date.now() - start) + \" ms elapsed\");\n"
},
{
"answer_id": 308796,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 4,
"selected": false,
"text": "var s = new Array(repeat+1).join(\"-\");\n"
},
{
"answer_id": 700998,
"author": "Serkan Yersen",
"author_id": 85094,
"author_profile": "https://Stackoverflow.com/users/85094",
"pm_score": 4,
"selected": false,
"text": "var tags = {\n name: \"Jack\",\n location: \"USA\"\n};\n\n\"Name: {name}<br>From {location}\".replace(/\\{(.*?)\\}/gim, function(all, match){\n return tags[match];\n});\n"
},
{
"answer_id": 701061,
"author": "Martijn Laarman",
"author_id": 47020,
"author_profile": "https://Stackoverflow.com/users/47020",
"pm_score": 0,
"selected": false,
"text": "var i = 12;\nvar s = i+\"\";\n"
},
{
"answer_id": 1221417,
"author": "RameshVel",
"author_id": 97572,
"author_profile": "https://Stackoverflow.com/users/97572",
"pm_score": 1,
"selected": false,
"text": " var $$ = document.getElementById;\n\n $$('samText');\n"
},
{
"answer_id": 1345481,
"author": "pramodc84",
"author_id": 40614,
"author_profile": "https://Stackoverflow.com/users/40614",
"pm_score": 4,
"selected": false,
"text": "var myArray = [1,2,3];\nmyArray.length // 3 elements.\nmyArray.length = 2; //Deletes the last element.\nmyArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.\n"
},
{
"answer_id": 1361134,
"author": "pramodc84",
"author_id": 40614,
"author_profile": "https://Stackoverflow.com/users/40614",
"pm_score": 0,
"selected": false,
"text": "element.innerHTML = \"\"; // Replaces body of HTML element with an empty string.\n"
},
{
"answer_id": 3525010,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 1,
"selected": false,
"text": "var today = new Date((new Date()).setHours(0, 0, 0, 0));\n var today = new Date().setHours(0, 0, 0, 0);\n"
},
{
"answer_id": 3526226,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 1,
"selected": false,
"text": "var foo = {}; // empty object literal\n\nalert(foo.bar) // will alert \"undefined\"\n\nalert(foo.bar || \"bar\"); // will alert the fallback (\"bar\")\n // will result in a type error\nif (foo.bar.length === 0)\n\n// with a default fallback you are always sure that the length\n// property will be available.\nif ((foo.bar || \"\").length === 0) \n"
},
{
"answer_id": 3529178,
"author": "Skilldrick",
"author_id": 49376,
"author_profile": "https://Stackoverflow.com/users/49376",
"pm_score": 4,
"selected": false,
"text": "|| && answer = obj && obj.property\n if (obj) {\n answer = obj.property;\n}\nelse {\n answer = null;\n}\n"
},
{
"answer_id": 3918632,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 2,
"selected": false,
"text": "var str = \"John Doe\";\n var [fname, lname] = str.split(\" \");\nalert(lname + \", \" + fname);\n var a = str.split(\" \");\nalert(a[1] + \", \" + a[0]);\n var [str, fname, lname] = str.match(/(.*) (.*)/);\n"
},
{
"answer_id": 5257738,
"author": "manixrock",
"author_id": 93691,
"author_profile": "https://Stackoverflow.com/users/93691",
"pm_score": 1,
"selected": false,
"text": "var numberName = [\"zero\", \"one\", \"two\", \"three\", \"four\"][number];\n var numberValue = {\"zero\":0, \"one\":1, \"two\":2, \"three\":3, \"four\":4}[numberName];\n var errorDesc = {301: \"Moved Permanently\",\n 404: \"Resource not found\",\n 503: \"Server down\"\n }[errorNo] || \"An unknown error has occurred\";\n"
},
{
"answer_id": 5628693,
"author": "ming_codes",
"author_id": 387028,
"author_profile": "https://Stackoverflow.com/users/387028",
"pm_score": 1,
"selected": false,
"text": "a = b && b.length;\n a = b ? b.length : null;\n a = b && b.c && b.c.length;\n"
},
{
"answer_id": 37650287,
"author": "Gerard Simpson",
"author_id": 4476186,
"author_profile": "https://Stackoverflow.com/users/4476186",
"pm_score": 2,
"selected": false,
"text": "var test = \"hello, world!\";\n(() => test)(); //returns \"hello, world!\";\n"
},
{
"answer_id": 44949871,
"author": "Raimonds",
"author_id": 2349048,
"author_profile": "https://Stackoverflow.com/users/2349048",
"pm_score": 0,
"selected": false,
"text": "0 | \"3\" //result = 3\n0 | \"some string\" -> //result = 0\n0 | \"0\" -> 0 //result = 0\n"
},
{
"answer_id": 46314286,
"author": "Mohan Kumar",
"author_id": 4919836,
"author_profile": "https://Stackoverflow.com/users/4919836",
"pm_score": 0,
"selected": false,
"text": "var a = 10;\nvar b = 20;\nvar text = `${a} + ${b} = ${a+b}`;\n"
},
{
"answer_id": 71998266,
"author": "Amin Dannak",
"author_id": 13049584,
"author_profile": "https://Stackoverflow.com/users/13049584",
"pm_score": 0,
"selected": false,
"text": "?. if(error && error.response && error.response.msg){ // do something} if(error?.response?.msg){ // do something }"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17964/"
] |
180,844
|
<p>How would you reference the models (Accord, CRV, Prius, etc) in this structure?
Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options?</p>
<pre><code>var cars = [
{
"makes" : "Honda",
"models" : [
{'Accord' : ["2dr","4dr"]} ,
{'CRV' : ["2dr","Hatchback"]} ,
{'Pilot' : ["base","superDuper"] }
]
},
{
"makes" : "Toyota",
"models" : [
{'Prius' : ["green","reallyGreen"]} ,
{'Camry' : ["sporty","square"]} ,
{'Corolla' : ["cheap","superFly"] }
]
}
];
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 180850,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 3,
"selected": false,
"text": "cars.Honda.Accord\ncars.Toyota.Prius\n var cars = {\n Honda : {\n Accord : [\"2dr\", \"4dr\"],\n CRV : [\"2dr\", \"Hatchback\"],\n Pilot : [\"base\", \"superDuper\"]\n },\n Toyota : {\n Prius : [\"green\", \"reallyGreen\"],\n Camry : [\"sporty\", \"square\"],\n Corolla : [\"cheap\", \"superFly\"]\n }\n};\n"
},
{
"answer_id": 180861,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 2,
"selected": false,
"text": " cars[0].models[0].Accord\n cars[0].models[1].CRV\n var cars = [\n{makes : \"Honda\",\n models : {\n Accord : [\"2dr\",\"4dr\"],\n CRV : [\"2dr\",\"Hatchback\"],\n Pilot: [\"base\",\"superDuper\"] \n }\n}, \n{makes :\"Toyota\",\n models : {\n Prius : [\"green\",\"reallyGreen\"],\n Camry : [\"sporty\",\"square\"],\n Corolla : [\"cheap\",\"superFly\"]\n }\n}];\n models"
},
{
"answer_id": 180968,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 4,
"selected": true,
"text": "var cars = [\n { name: 'Honda', models: [\n { name: 'Accord', features: ['2dr', '4dr'] },\n { name: 'CRV', features: ['2dr', 'Hatchback'] },\n { name: 'Pilot', features: ['base', 'superDuper'] }\n ]},\n\n { name: 'Toyota', models: [\n { name: 'Prius', features: ['green', 'superGreen'] },\n { name: 'Camry', features: ['sporty', 'square'] },\n { name: 'Corolla', features: ['cheap', 'superFly'] }\n ]}\n];\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
180,853
|
<p>What is the maximum length for the text string contained in a CEdit control in MFC? I get a beep when trying to add a character after the character 30001 is this documented anywhere? Can I display longer texts in a CEdit? Should I use another control?</p>
<p>As "Windows programmer" says down below, the text length limit is not the same when the user types as when we programatically set the text using SetWindowText. The limit for setting a text programatically is not mentioned anywhere. The default text lentgth limit for the user typing is wrong. (see my own post below). </p>
<p>I'm guessing that after I call pEdit->SetLimitText(0) the limit for both programatically and user input text length is 7FFFFFFE bytes. Am I right?</p>
<p>In vista, when pasting text longer than 40000 characters into a CEdit, it becomes unresponsive. It does not matter if I called SetLimitText(100000) previously.</p>
|
[
{
"answer_id": 184484,
"author": "rec",
"author_id": 14022,
"author_profile": "https://Stackoverflow.com/users/14022",
"pm_score": 5,
"selected": true,
"text": "CWnd* pWnd = dlg.GetDlgItem(nItemId);\nCEdit *edit = static_cast<CEdit*>(pWnd); //dynamic_cast does not work\nif(edit != 0)\n{\n UINT limit = edit->GetLimitText(); //The current text limit, in bytes, for this CEdit object.\n //value returned: 30000 (0x7530)\n edit->SetLimitText(0);\n limit = edit->GetLimitText();\n //value returned: 2147483646 (0x7FFFFFFE) \n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14022/"
] |
180,887
|
<p>Sorry if this sounds like a really stupid question, but I need to make a link change colour when you are on the page it links to.</p>
<p>For example, when you are on the "Questions" page of StackOverflow, the link at the top changes colour. How do you do this?</p>
|
[
{
"answer_id": 180892,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "class=\"youarehere\""
},
{
"answer_id": 180897,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "body.questions #questionsTab\n{\n color: #f00;\n}\n"
},
{
"answer_id": 180900,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 3,
"selected": false,
"text": "<a id=\"active\" href=\"thisPage.html\">this page</a>\n a#active { color: yellow; }\n"
},
{
"answer_id": 180901,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "<!-- base.html -->\n...\n<body class=\"{% block bodyclass %}{% endblock %}\">\n...\n<div id=\"nav\">\n <ul>\n <li id=\"nav-questions\"><a href=\"{% url questions %}\">Questions</a></li>\n <li id=\"nav-tags\"><a href=\"{% url tags %}\">Tags</a></li>\n <li id=\"nav-users\"><a href=\"{% url users %}\">Users</a></li>\n <li id=\"nav-badges\"><a href=\"{% url badges %}\">Badges</a></li>\n <li id=\"nav-ask-question\"><a href=\"{% url ask_question %}\">Ask Question</a></li>\n </ul>\n</div>\n bodyclass <!-- questions.html -->\n{% extends \"base.html\" %}\n{% block bodyclass %}questions{% endblock %}\n...\n body.questions #nav-questions a,\nbody.tags #nav-tags a,\nbody.users #nav-users a,\nbody.badges #nav-badges a,\nbody.ask-question #nav-ask-question a { background-color: #f90; }\n"
},
{
"answer_id": 180915,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": false,
"text": "// assuming this JS function is called when page loads\nonload()\n{\n if (location.href.indexOf('/questions') > 0)\n {\n document.getElementById('questionsLink').className = 'questionsStyleOn';\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/180887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25695/"
] |
180,910
|
<p>If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?</p>
|
[
{
"answer_id": 187917,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 4,
"selected": false,
"text": "C-x C-q toggle-read-only C-x C-f find-file dired C-h i (emacs)dired RET"
},
{
"answer_id": 208787,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 3,
"selected": false,
"text": "toggle-read-only C-x C-q (defun set-buffer-file-writable ()\n \"Make the file shown in the current buffer writable.\nMake the buffer writable as well.\"\n (interactive)\n (unix-output \"chmod\" \"+w\" (buffer-file-name))\n (toggle-read-only nil)\n (message (trim-right '(?\\n) (unix-output \"ls\" \"-l\" (buffer-file-name)))))\n unix-output trim-right (defun unix-output (command &rest args)\n \"Run a unix command and, if it returns 0, return the output as a string.\nOtherwise, signal an error. The error message is the first line of the output.\"\n (let ((output-buffer (generate-new-buffer \"*stdout*\")))\n (unwind-protect\n (let ((return-value (apply 'call-process command nil\n output-buffer nil args)))\n (set-buffer output-buffer)\n (save-excursion \n (unless (= return-value 0)\n (goto-char (point-min))\n (end-of-line)\n (if (= (point-min) (point))\n (error \"Command failed: %s%s\" command\n (with-output-to-string\n (dolist (arg args)\n (princ \" \")\n (princ arg))))\n (error \"%s\" (buffer-substring-no-properties (point-min) \n (point)))))\n (buffer-substring-no-properties (point-min) (point-max))))\n (kill-buffer output-buffer))))\n\n(defun trim-right (bag string &optional start end)\n (setq bag (if (eq bag t) '(?\\ ?\\n ?\\t ?\\v ?\\r ?\\f) bag)\n start (or start 0)\n end (or end (length string)))\n (while (and (> end 0)\n (member (aref string (1- end)) bag))\n (decf end))\n (substring string start end))\n ~/.emacs.el M-x set-buffer-file-writable"
},
{
"answer_id": 2408222,
"author": "Dmytro Kuznetsov",
"author_id": 287248,
"author_profile": "https://Stackoverflow.com/users/287248",
"pm_score": 4,
"selected": false,
"text": "M-x set-file-modes filename mode M-x set-file-modes <RET> ReadOnlyFile.txt <RET> 0666"
},
{
"answer_id": 8372163,
"author": "Louis Roehrs",
"author_id": 1079565,
"author_profile": "https://Stackoverflow.com/users/1079565",
"pm_score": 2,
"selected": false,
"text": "Shift + M modespec chmod M modespec <RET>"
},
{
"answer_id": 34173102,
"author": "Li Tianyi",
"author_id": 5657892,
"author_profile": "https://Stackoverflow.com/users/5657892",
"pm_score": 0,
"selected": false,
"text": "C-x C-q (defun spacemacs/sudo-edit (&optional arg)\n (interactive \"p\")\n (if (or arg (not buffer-file-name))\n (find-file (concat \"/sudo:root@localhost:\" (ido-read-file-name \"File: \")))\n (find-alternate-file (concat \"/sudo:root@localhost:\" buffer-file-name))))\n spacemacs/sudo-edit spacemacs/sudo-edit"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
180,924
|
<p>Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)?</p>
|
[
{
"answer_id": 181401,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": true,
"text": "-Djava.security.manager -Djava.security.policy=\"XXXX\\conf\\catalina.policy\"\n C:\\Program Files\\Apache Software Foundation\\Tomcat 5.5"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
180,929
|
<p>I want to programmatically create a new column in an MS Access table. I've tried many permutations of <code>ALTER TABLE MyTable Add MyField DECIMAL (9,4) NULL;</code> and got: </p>
<blockquote>
<p>Syntax Error in Field Definition</p>
</blockquote>
<p>I can easily create a number field that goes to a <code>Double</code> type, but I want <code>decimal</code>. I would very strongly prefer to do this in a single <code>ALTER TABLE</code> statement and not have to create a field and then alter it. </p>
<p>I am using Access 2003.</p>
|
[
{
"answer_id": 181169,
"author": "Chris OC",
"author_id": 11041,
"author_profile": "https://Stackoverflow.com/users/11041",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE MyTable\n Add COLUMN MyField DECIMAL (9,4) NULL;\n Dim conn As ADODB.Connection\n\nSet conn = CurrentProject.Connection\nconn.Execute \"ALTER TABLE MyTable \" _\n & \"ADD COLUMN MyField DECIMAL (9,4) NULL;\"\nconn.Close\n"
},
{
"answer_id": 181763,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 3,
"selected": true,
"text": "Dim my_tableDef As DAO.TableDef\nDim my_field As DAO.Field\n\nSet my_tableDef = currentDb.TableDefs(my_table)\nSet my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize)\nmy_Field.decimalPlaces = myDecimalPlaces\nmy_Field.defaultValue = myDefaultValue\n\nmy_tableDef.Fields.Append my_Field\n\nset my_Field = nothing\nset my_tableDef = nothing\n strSql = \"ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);\"\nCurrentProject.Connection.Execute strSql\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12897/"
] |
180,930
|
<p>I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.</p>
<p>Given this data:</p>
<pre><code>var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");
</code></pre>
<p>And this code: ** Which is not correct and is what needs to be fixed!! **</p>
<pre><code>var shaped = data.Select(c =>
new { c = c }
).ToList();
serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();
</code></pre>
<p>I would like <code>desiredResult</code> to be:</p>
<pre><code>{
"One": "One",
"Two": "Two",
"Three": "Three"
}
</code></pre>
<p>but it is currently:</p>
<p><code>{ "c" : "One" },{ "c" : "Two" }</code>, etc. </p>
<p>One problem is that on the left side of the object initializer I want the value of <code>c</code>, not <code>c</code> itself...</p>
|
[
{
"answer_id": 181169,
"author": "Chris OC",
"author_id": 11041,
"author_profile": "https://Stackoverflow.com/users/11041",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE MyTable\n Add COLUMN MyField DECIMAL (9,4) NULL;\n Dim conn As ADODB.Connection\n\nSet conn = CurrentProject.Connection\nconn.Execute \"ALTER TABLE MyTable \" _\n & \"ADD COLUMN MyField DECIMAL (9,4) NULL;\"\nconn.Close\n"
},
{
"answer_id": 181763,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 3,
"selected": true,
"text": "Dim my_tableDef As DAO.TableDef\nDim my_field As DAO.Field\n\nSet my_tableDef = currentDb.TableDefs(my_table)\nSet my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize)\nmy_Field.decimalPlaces = myDecimalPlaces\nmy_Field.defaultValue = myDefaultValue\n\nmy_tableDef.Fields.Append my_Field\n\nset my_Field = nothing\nset my_tableDef = nothing\n strSql = \"ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);\"\nCurrentProject.Connection.Execute strSql\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410357/"
] |
180,935
|
<p>I've got a LOT of tests written for a piece of software (which is a GREAT thing) but it was built essentially as a standalone test in C#. While this works well enough, it suffers from a few shortcomings, not the least of which is that it isn't using a standard testing framework and ends up requiring the person running the test to comment out calls to tests that shouldn't be run (when it isn't desired to run the entire test 'suite'). I'd like to incorporate it into my automated testing process.</p>
<p>I saw that the Test Edition of VS 2008 has the notion of a 'Generic Test' that might do what I want, but we're not in a position to spend the money on that version currently. I recently started using the VS 2008 Pro version.</p>
<p>These test methods follow a familiar pattern:</p>
<ul>
<li>Do some setup for the test. </li>
<li>Execute the test.</li>
<li>Reset for the next test.</li>
</ul>
<p>Each of them returns a bool (pass/fail) and a string ref to a fail reason, filled in if it fails.</p>
<p>On the bright side, at least the test methods are consistent. </p>
<p>I am sitting here tonight contemplating the approach I might take tomorrow morning to migrate all this test code to a testing framework and, frankly, I'm not all that excited about the idea of poring over 8-9K lines of test code by hand to do the conversion. </p>
<p>Have you had any experience undertaking such a conversion? Do you have any tips? I think I might be stuck slogging through it all doing global search/replaces and hand-changing the tests.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 180977,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": true,
"text": "[Test] Assert [Test]\npublic void MyTest()\n{\n string msg;\n bool result = OldTestClass.MyTest(out msg);\n if (!result)\n {\n Console.WriteLine(msg);\n }\n Assert.AreEqual(result, true);\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
] |
180,937
|
<p>It's my understanding that common wisdom says to only use exceptions for truly exceptional conditions (In fact, I've seen that statement here at SO several times). </p>
<p>However, Krzysztof Cwalina says:</p>
<blockquote>
<blockquote>
<p>One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition.</p>
</blockquote>
</blockquote>
<p>He then also goes on to say that exceptions should be used for: </p>
<ul>
<li>Usage errors</li>
<li>Program errors</li>
<li>System failures</li>
</ul>
<p>Considering Krzysztof Cwalina is the PM for the CLR team at MS I ask: What do you think of his statement? </p>
|
[
{
"answer_id": 181014,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 3,
"selected": false,
"text": "getHeader(File f) FileHeader null null TRUE FALSE FILE_NOT_FOUND FileNotFound DeviceNotReady InvalidUserInput"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
180,947
|
<p>Is there a freely available Base64 decoding code snippet in C++?</p>
|
[
{
"answer_id": 180949,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "/*\n base64.cpp and base64.h\n\n Copyright (C) 2004-2008 René Nyffenegger\n\n This source code is provided 'as-is', without any express or implied\n warranty. In no event will the author be held liable for any damages\n arising from the use of this software.\n\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n\n 1. The origin of this source code must not be misrepresented; you must not\n claim that you wrote the original source code. If you use this source code\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original source code.\n\n 3. This notice may not be removed or altered from any source distribution.\n\n René Nyffenegger rene.nyffenegger@adp-gmbh.ch\n\n*/\n\nstatic const std::string base64_chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+/\";\n\n\nstatic inline bool is_base64(unsigned char c) {\n return (isalnum(c) || (c == '+') || (c == '/'));\n}\n\nstd::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {\n std::string ret;\n int i = 0;\n int j = 0;\n unsigned char char_array_3[3];\n unsigned char char_array_4[4];\n\n while (in_len--) {\n char_array_3[i++] = *(bytes_to_encode++);\n if (i == 3) {\n char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;\n char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);\n char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);\n char_array_4[3] = char_array_3[2] & 0x3f;\n\n for(i = 0; (i <4) ; i++)\n ret += base64_chars[char_array_4[i]];\n i = 0;\n }\n }\n\n if (i)\n {\n for(j = i; j < 3; j++)\n char_array_3[j] = '\\0';\n\n char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;\n char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);\n char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);\n char_array_4[3] = char_array_3[2] & 0x3f;\n\n for (j = 0; (j < i + 1); j++)\n ret += base64_chars[char_array_4[j]];\n\n while((i++ < 3))\n ret += '=';\n\n }\n\n return ret;\n\n}\nstd::string base64_decode(std::string const& encoded_string) {\n int in_len = encoded_string.size();\n int i = 0;\n int j = 0;\n int in_ = 0;\n unsigned char char_array_4[4], char_array_3[3];\n std::string ret;\n\n while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {\n char_array_4[i++] = encoded_string[in_]; in_++;\n if (i ==4) {\n for (i = 0; i <4; i++)\n char_array_4[i] = base64_chars.find(char_array_4[i]);\n\n char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);\n char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);\n char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];\n\n for (i = 0; (i < 3); i++)\n ret += char_array_3[i];\n i = 0;\n }\n }\n\n if (i) {\n for (j = i; j <4; j++)\n char_array_4[j] = 0;\n\n for (j = 0; j <4; j++)\n char_array_4[j] = base64_chars.find(char_array_4[j]);\n\n char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);\n char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);\n char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];\n\n for (j = 0; (j < i - 1); j++) ret += char_array_3[j];\n }\n\n return ret;\n}\n"
},
{
"answer_id": 13935718,
"author": "LihO",
"author_id": 1168156,
"author_profile": "https://Stackoverflow.com/users/1168156",
"pm_score": 7,
"selected": false,
"text": "std::string #ifndef _BASE64_H_\n#define _BASE64_H_\n\n#include <vector>\n#include <string>\ntypedef unsigned char BYTE;\n\nstd::string base64_encode(BYTE const* buf, unsigned int bufLen);\nstd::vector<BYTE> base64_decode(std::string const&);\n\n#endif\n #include \"base64.h\"\n#include <iostream>\n\nstatic const std::string base64_chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+/\";\n\n\nstatic inline bool is_base64(BYTE c) {\n return (isalnum(c) || (c == '+') || (c == '/'));\n}\n\nstd::string base64_encode(BYTE const* buf, unsigned int bufLen) {\n std::string ret;\n int i = 0;\n int j = 0;\n BYTE char_array_3[3];\n BYTE char_array_4[4];\n\n while (bufLen--) {\n char_array_3[i++] = *(buf++);\n if (i == 3) {\n char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;\n char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);\n char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);\n char_array_4[3] = char_array_3[2] & 0x3f;\n\n for(i = 0; (i <4) ; i++)\n ret += base64_chars[char_array_4[i]];\n i = 0;\n }\n }\n\n if (i)\n {\n for(j = i; j < 3; j++)\n char_array_3[j] = '\\0';\n\n char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;\n char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);\n char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);\n char_array_4[3] = char_array_3[2] & 0x3f;\n\n for (j = 0; (j < i + 1); j++)\n ret += base64_chars[char_array_4[j]];\n\n while((i++ < 3))\n ret += '=';\n }\n\n return ret;\n}\n\nstd::vector<BYTE> base64_decode(std::string const& encoded_string) {\n int in_len = encoded_string.size();\n int i = 0;\n int j = 0;\n int in_ = 0;\n BYTE char_array_4[4], char_array_3[3];\n std::vector<BYTE> ret;\n\n while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {\n char_array_4[i++] = encoded_string[in_]; in_++;\n if (i ==4) {\n for (i = 0; i <4; i++)\n char_array_4[i] = base64_chars.find(char_array_4[i]);\n\n char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);\n char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);\n char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];\n\n for (i = 0; (i < 3); i++)\n ret.push_back(char_array_3[i]);\n i = 0;\n }\n }\n\n if (i) {\n for (j = i; j <4; j++)\n char_array_4[j] = 0;\n\n for (j = 0; j <4; j++)\n char_array_4[j] = base64_chars.find(char_array_4[j]);\n\n char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);\n char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);\n char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];\n\n for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);\n }\n\n return ret;\n}\n std::vector<BYTE> myData;\n...\nstd::string encodedData = base64_encode(&myData[0], myData.size());\nstd::vector<BYTE> decodedData = base64_decode(encodedData);\n"
},
{
"answer_id": 25123052,
"author": "azawadzki",
"author_id": 3905597,
"author_profile": "https://Stackoverflow.com/users/3905597",
"pm_score": 4,
"selected": false,
"text": "some_data_t in[] { ... };\nconstexpr int len = sizeof(in)/sizeof(in[0]);\n\nstd::string encoded;\nbn::encode_b64(in, in + len, std::back_inserter(encoded));\n\nsome_data_t out[len];\nbn::decode_b64(encoded.begin(), encoded.end(), out);\n"
},
{
"answer_id": 31322410,
"author": "DaedalusAlpha",
"author_id": 498519,
"author_profile": "https://Stackoverflow.com/users/498519",
"pm_score": 4,
"selected": false,
"text": "#ifndef _BASE64_H_\n#define _BASE64_H_\n\n#include <vector>\n#include <string>\ntypedef unsigned char BYTE;\n\nclass Base64\n{\npublic:\n static std::string encode(const std::vector<BYTE>& buf);\n static std::string encode(const BYTE* buf, unsigned int bufLen);\n static std::vector<BYTE> decode(std::string encoded_string);\n};\n\n#endif\n static const BYTE from_base64[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 62, 255, 63,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,\n 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 63,\n 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255};\n\nstatic const char to_base64[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+/\";\n\n\nstd::string Base64::encode(const std::vector<BYTE>& buf)\n{\n if (buf.empty())\n return \"\"; // Avoid dereferencing buf if it's empty\n return encode(&buf[0], (unsigned int)buf.size());\n}\n\nstd::string Base64::encode(const BYTE* buf, unsigned int bufLen)\n{\n // Calculate how many bytes that needs to be added to get a multiple of 3\n size_t missing = 0;\n size_t ret_size = bufLen;\n while ((ret_size % 3) != 0)\n {\n ++ret_size;\n ++missing;\n }\n\n // Expand the return string size to a multiple of 4\n ret_size = 4*ret_size/3;\n\n std::string ret;\n ret.reserve(ret_size);\n\n for (unsigned int i=0; i<ret_size/4; ++i)\n {\n // Read a group of three bytes (avoid buffer overrun by replacing with 0)\n size_t index = i*3;\n BYTE b3[3];\n b3[0] = (index+0 < bufLen) ? buf[index+0] : 0;\n b3[1] = (index+1 < bufLen) ? buf[index+1] : 0;\n b3[2] = (index+2 < bufLen) ? buf[index+2] : 0;\n\n // Transform into four base 64 characters\n BYTE b4[4];\n b4[0] = ((b3[0] & 0xfc) >> 2);\n b4[1] = ((b3[0] & 0x03) << 4) + ((b3[1] & 0xf0) >> 4);\n b4[2] = ((b3[1] & 0x0f) << 2) + ((b3[2] & 0xc0) >> 6);\n b4[3] = ((b3[2] & 0x3f) << 0);\n\n // Add the base 64 characters to the return value\n ret.push_back(to_base64[b4[0]]);\n ret.push_back(to_base64[b4[1]]);\n ret.push_back(to_base64[b4[2]]);\n ret.push_back(to_base64[b4[3]]);\n }\n\n // Replace data that is invalid (always as many as there are missing bytes)\n for (size_t i=0; i<missing; ++i)\n ret[ret_size - i - 1] = '=';\n\n return ret;\n}\n\nstd::vector<BYTE> Base64::decode(std::string encoded_string)\n{\n // Make sure string length is a multiple of 4\n while ((encoded_string.size() % 4) != 0)\n encoded_string.push_back('=');\n\n size_t encoded_size = encoded_string.size();\n std::vector<BYTE> ret;\n ret.reserve(3*encoded_size/4);\n\n for (size_t i=0; i<encoded_size; i += 4)\n {\n // Get values for each group of four base 64 characters\n BYTE b4[4];\n b4[0] = (encoded_string[i+0] <= 'z') ? from_base64[encoded_string[i+0]] : 0xff;\n b4[1] = (encoded_string[i+1] <= 'z') ? from_base64[encoded_string[i+1]] : 0xff;\n b4[2] = (encoded_string[i+2] <= 'z') ? from_base64[encoded_string[i+2]] : 0xff;\n b4[3] = (encoded_string[i+3] <= 'z') ? from_base64[encoded_string[i+3]] : 0xff;\n\n // Transform into a group of three bytes\n BYTE b3[3];\n b3[0] = ((b4[0] & 0x3f) << 2) + ((b4[1] & 0x30) >> 4);\n b3[1] = ((b4[1] & 0x0f) << 4) + ((b4[2] & 0x3c) >> 2);\n b3[2] = ((b4[2] & 0x03) << 6) + ((b4[3] & 0x3f) >> 0);\n\n // Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)\n if (b4[1] != 0xff) ret.push_back(b3[0]);\n if (b4[2] != 0xff) ret.push_back(b3[1]);\n if (b4[3] != 0xff) ret.push_back(b3[2]);\n }\n\n return ret;\n}\n BYTE buf[] = \"ABCD\";\nstd::string encoded = Base64::encode(buf, 4);\n// encoded = \"QUJDRA==\"\nstd::vector<BYTE> decoded = Base64::decode(encoded);\n"
},
{
"answer_id": 34571089,
"author": "Manuel Martinez",
"author_id": 5739045,
"author_profile": "https://Stackoverflow.com/users/5739045",
"pm_score": 6,
"selected": false,
"text": "static std::string base64_encode(const std::string &in) {\n\n std::string out;\n\n int val = 0, valb = -6;\n for (uchar c : in) {\n val = (val << 8) + c;\n valb += 8;\n while (valb >= 0) {\n out.push_back(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"[(val>>valb)&0x3F]);\n valb -= 6;\n }\n }\n if (valb>-6) out.push_back(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"[((val<<8)>>(valb+8))&0x3F]);\n while (out.size()%4) out.push_back('=');\n return out;\n}\n\nstatic std::string base64_decode(const std::string &in) {\n\n std::string out;\n\n std::vector<int> T(256,-1);\n for (int i=0; i<64; i++) T[\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"[i]] = i;\n\n int val=0, valb=-8;\n for (uchar c : in) {\n if (T[c] == -1) break;\n val = (val << 6) + T[c];\n valb += 6;\n if (valb >= 0) {\n out.push_back(char((val>>valb)&0xFF));\n valb -= 8;\n }\n }\n return out;\n}\n"
},
{
"answer_id": 35328409,
"author": "elegant dice",
"author_id": 924505,
"author_profile": "https://Stackoverflow.com/users/924505",
"pm_score": 3,
"selected": false,
"text": "void base64_encode(string & out, const vector<uint8_t>& buf);\nvoid base64_encode(string & out, const uint8_t* buf, size_t bufLen);\nvoid base64_encode(string & out, string const& buf);\n\nvoid base64_decode(vector<uint8_t> & out, string const& encoded_string);\n\n// Use this if you know the output should be a valid string\nvoid base64_decode(string & out, string const& encoded_string);\n static const uint8_t from_base64[128] = {\n // 8 rows of 16 = 128\n // Note: only requires 123 entries, as we only lookup for <= z , which z=122\n\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 62, 255, 63,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 0, 255, 255, 255,\n 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 63,\n 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255\n};\n\nstatic const char to_base64[65] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+/\";\n\n\nvoid base64_encode(string & out, string const& buf)\n{\n if (buf.empty())\n base64_encode(out, NULL, 0);\n else\n base64_encode(out, reinterpret_cast<uint8_t const*>(&buf[0]), buf.size());\n}\n\n\nvoid base64_encode(string & out, std::vector<uint8_t> const& buf)\n{\n if (buf.empty())\n base64_encode(out, NULL, 0);\n else\n base64_encode(out, &buf[0], buf.size());\n}\n\nvoid base64_encode(string & ret, uint8_t const* buf, size_t bufLen)\n{\n // Calculate how many bytes that needs to be added to get a multiple of 3\n size_t missing = 0;\n size_t ret_size = bufLen;\n while ((ret_size % 3) != 0)\n {\n ++ret_size;\n ++missing;\n }\n\n // Expand the return string size to a multiple of 4\n ret_size = 4*ret_size/3;\n\n ret.clear();\n ret.reserve(ret_size);\n\n for (size_t i = 0; i < ret_size/4; ++i)\n {\n // Read a group of three bytes (avoid buffer overrun by replacing with 0)\n const size_t index = i*3;\n const uint8_t b3_0 = (index+0 < bufLen) ? buf[index+0] : 0;\n const uint8_t b3_1 = (index+1 < bufLen) ? buf[index+1] : 0;\n const uint8_t b3_2 = (index+2 < bufLen) ? buf[index+2] : 0;\n\n // Transform into four base 64 characters\n const uint8_t b4_0 = ((b3_0 & 0xfc) >> 2);\n const uint8_t b4_1 = ((b3_0 & 0x03) << 4) + ((b3_1 & 0xf0) >> 4);\n const uint8_t b4_2 = ((b3_1 & 0x0f) << 2) + ((b3_2 & 0xc0) >> 6);\n const uint8_t b4_3 = ((b3_2 & 0x3f) << 0);\n\n // Add the base 64 characters to the return value\n ret.push_back(to_base64[b4_0]);\n ret.push_back(to_base64[b4_1]);\n ret.push_back(to_base64[b4_2]);\n ret.push_back(to_base64[b4_3]);\n }\n\n // Replace data that is invalid (always as many as there are missing bytes)\n for (size_t i = 0; i != missing; ++i)\n ret[ret_size - i - 1] = '=';\n}\n\n\ntemplate <class Out>\nvoid base64_decode_any( Out & ret, std::string const& in)\n{\n typedef typename Out::value_type T;\n\n // Make sure the *intended* string length is a multiple of 4\n size_t encoded_size = in.size();\n\n while ((encoded_size % 4) != 0)\n ++encoded_size;\n\n const size_t N = in.size();\n ret.clear();\n ret.reserve(3*encoded_size/4);\n\n for (size_t i = 0; i < encoded_size; i += 4)\n {\n // Note: 'z' == 122\n\n // Get values for each group of four base 64 characters\n const uint8_t b4_0 = ( in[i+0] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+0])] : 0xff;\n const uint8_t b4_1 = (i+1 < N and in[i+1] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+1])] : 0xff;\n const uint8_t b4_2 = (i+2 < N and in[i+2] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+2])] : 0xff;\n const uint8_t b4_3 = (i+3 < N and in[i+3] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+3])] : 0xff;\n\n // Transform into a group of three bytes\n const uint8_t b3_0 = ((b4_0 & 0x3f) << 2) + ((b4_1 & 0x30) >> 4);\n const uint8_t b3_1 = ((b4_1 & 0x0f) << 4) + ((b4_2 & 0x3c) >> 2);\n const uint8_t b3_2 = ((b4_2 & 0x03) << 6) + ((b4_3 & 0x3f) >> 0);\n\n // Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)\n if (b4_1 != 0xff) ret.push_back( static_cast<T>(b3_0) );\n if (b4_2 != 0xff) ret.push_back( static_cast<T>(b3_1) );\n if (b4_3 != 0xff) ret.push_back( static_cast<T>(b3_2) );\n }\n}\n\nvoid base64_decode(vector<uint8_t> & out, string const& encoded_string)\n{\n base64_decode_any(out, encoded_string);\n}\n\nvoid base64_decode(string & out, string const& encoded_string)\n{\n base64_decode_any(out, encoded_string);\n}\n"
},
{
"answer_id": 37109258,
"author": "polfosol ఠ_ఠ",
"author_id": 5358284,
"author_profile": "https://Stackoverflow.com/users/5358284",
"pm_score": 5,
"selected": false,
"text": "#include <string>\n\nstatic const char* B64chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nstatic const int B64index[256] =\n{\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,\n 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 63,\n 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n};\n\nconst std::string b64encode(const void* data, const size_t &len)\n{\n std::string result((len + 2) / 3 * 4, '=');\n unsigned char *p = (unsigned char*) data;\n char *str = &result[0];\n size_t j = 0, pad = len % 3;\n const size_t last = len - pad;\n\n for (size_t i = 0; i < last; i += 3)\n {\n int n = int(p[i]) << 16 | int(p[i + 1]) << 8 | p[i + 2];\n str[j++] = B64chars[n >> 18];\n str[j++] = B64chars[n >> 12 & 0x3F];\n str[j++] = B64chars[n >> 6 & 0x3F];\n str[j++] = B64chars[n & 0x3F];\n }\n if (pad) /// Set padding\n {\n int n = --pad ? int(p[last]) << 8 | p[last + 1] : p[last];\n str[j++] = B64chars[pad ? n >> 10 & 0x3F : n >> 2];\n str[j++] = B64chars[pad ? n >> 4 & 0x03F : n << 4 & 0x3F];\n str[j++] = pad ? B64chars[n << 2 & 0x3F] : '=';\n }\n return result;\n}\n\nconst std::string b64decode(const void* data, const size_t &len)\n{\n if (len == 0) return \"\";\n\n unsigned char *p = (unsigned char*) data;\n size_t j = 0,\n pad1 = len % 4 || p[len - 1] == '=',\n pad2 = pad1 && (len % 4 > 2 || p[len - 2] != '=');\n const size_t last = (len - pad1) / 4 << 2;\n std::string result(last / 4 * 3 + pad1 + pad2, '\\0');\n unsigned char *str = (unsigned char*) &result[0];\n\n for (size_t i = 0; i < last; i += 4)\n {\n int n = B64index[p[i]] << 18 | B64index[p[i + 1]] << 12 | B64index[p[i + 2]] << 6 | B64index[p[i + 3]];\n str[j++] = n >> 16;\n str[j++] = n >> 8 & 0xFF;\n str[j++] = n & 0xFF;\n }\n if (pad1)\n {\n int n = B64index[p[last]] << 18 | B64index[p[last + 1]] << 12;\n str[j++] = n >> 16;\n if (pad2)\n {\n n |= B64index[p[last + 2]] << 6;\n str[j++] = n >> 8 & 0xFF;\n }\n }\n return result;\n}\n\nstd::string b64encode(const std::string& str)\n{\n return b64encode(str.c_str(), str.size());\n}\n\nstd::string b64decode(const std::string& str64)\n{\n return b64decode(str64.c_str(), str64.size());\n}\n"
},
{
"answer_id": 44562527,
"author": "nunojpg",
"author_id": 1590596,
"author_profile": "https://Stackoverflow.com/users/1590596",
"pm_score": 3,
"selected": false,
"text": "std::string base64_decode(const std::string_view in) {\n // table from '+' to 'z'\n const uint8_t lookup[] = {\n 62, 255, 62, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255,\n 255, 0, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n 255, 255, 255, 255, 63, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,\n 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};\n static_assert(sizeof(lookup) == 'z' - '+' + 1);\n\n std::string out;\n int val = 0, valb = -8;\n for (uint8_t c : in) {\n if (c < '+' || c > 'z')\n break;\n c -= '+';\n if (lookup[c] >= 64)\n break;\n val = (val << 6) + lookup[c];\n valb += 6;\n if (valb >= 0) {\n out.push_back(char((val >> valb) & 0xFF));\n valb -= 8;\n }\n }\n return out;\n}\n"
},
{
"answer_id": 59227838,
"author": "Macelaru Tiberiu",
"author_id": 8647757,
"author_profile": "https://Stackoverflow.com/users/8647757",
"pm_score": 2,
"selected": false,
"text": "class BinaryVector {\npublic:\n std::vector<char> bytes;\n\n uint64_t bit_count = 0;\n\npublic:\n /* Add a bit to the end */\n void push_back(bool bit);\n\n /* Return false if character is unrecognized */\n bool pushBase64Char(char b64_c);\n};\n\nvoid BinaryVector::push_back(bool bit)\n{\n if (!bit_count || bit_count % 8 == 0) {\n bytes.push_back(bit << 7);\n }\n else {\n uint8_t next_bit = 8 - (bit_count % 8) - 1;\n bytes[bit_count / 8] |= bit << next_bit;\n }\n bit_count++;\n}\n\n/* Converts one Base64 character to 6 bits */\nbool BinaryVector::pushBase64Char(char c)\n{\n uint8_t d;\n\n // A to Z\n if (c > 0x40 && c < 0x5b) {\n d = c - 65; // Base64 A is 0\n }\n // a to z\n else if (c > 0x60 && c < 0x7b) {\n d = c - 97 + 26; // Base64 a is 26\n }\n // 0 to 9\n else if (c > 0x2F && c < 0x3a) {\n d = c - 48 + 52; // Base64 0 is 52\n }\n else if (c == '+') {\n d = 0b111110;\n }\n else if (c == '/') {\n d = 0b111111;\n }\n else if (c == '=') {\n d = 0;\n }\n else {\n return false;\n }\n\n push_back(d & 0b100000);\n push_back(d & 0b010000);\n push_back(d & 0b001000);\n push_back(d & 0b000100);\n push_back(d & 0b000010);\n push_back(d & 0b000001);\n\n return true;\n}\n\nbool loadBase64(std::vector<char>& b64_bin, BinaryVector& vec)\n{\n for (char& c : b64_bin) {\n if (!vec.pushBase64Char(c)) {\n return false;\n }\n }\n return true;\n}\n\n vec.bytes"
},
{
"answer_id": 59464829,
"author": "tutralex",
"author_id": 12589146,
"author_profile": "https://Stackoverflow.com/users/12589146",
"pm_score": 2,
"selected": false,
"text": "// ---------------------------------------------------------------------------\nUnicodeString __fastcall TExample::Base64Encode(void *data, int length)\n{\n if (length <= 0)\n return L\"\";\n static const char set[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n unsigned char *in = (unsigned char*)data;\n char *pos, *out = pos = new char[((length - 1) / 3 + 1) << 2];\n while ((length -= 3) >= 0)\n {\n pos[0] = set[in[0] >> 2];\n pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];\n pos[2] = set[((in[1] & 0x0F) << 2) | (in[2] >> 6)];\n pos[3] = set[in[2] & 0x3F];\n pos += 4;\n in += 3;\n };\n if ((length & 2) != 0)\n {\n pos[0] = set[in[0] >> 2];\n if ((length & 1) != 0)\n {\n pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];\n pos[2] = set[(in[1] & 0x0F) << 2];\n }\n else\n {\n pos[1] = set[(in[0] & 0x03) << 4];\n pos[2] = '=';\n };\n pos[3] = '=';\n pos += 4;\n };\n UnicodeString code = UnicodeString(out, pos - out);\n delete[] out;\n return code;\n};\n\n// ---------------------------------------------------------------------------\nint __fastcall TExample::Base64Decode(const UnicodeString &code, unsigned char **data)\n{\n int length;\n if (((length = code.Length()) == 0) || ((length & 3) != 0))\n return 0;\n wchar_t *str = code.c_str();\n unsigned char *pos, *out = pos = new unsigned char[(length >> 2) * 3];\n while (*str != 0)\n {\n length = -1;\n int shift = 18, bits = 0;\n do\n {\n wchar_t s = str[++length];\n if ((s >= L'A') && (s <= L'Z'))\n bits |= (s - L'A') << shift;\n else if ((s >= L'a') && (s <= L'z'))\n bits |= (s - (L'a' - 26)) << shift;\n else if (((s >= L'0') && (s <= L'9')))\n bits |= (s - (L'0' - 52)) << shift;\n else if (s == L'+')\n bits |= 62 << shift;\n else if (s == L'/')\n bits |= 63 << shift;\n else if (s == L'=')\n {\n length--;\n break;\n }\n else\n {\n delete[] out;\n return 0;\n };\n }\n while ((shift -= 6) >= 0);\n pos[0] = bits >> 16;\n pos[1] = bits >> 8;\n pos[2] = bits;\n pos += length;\n str += 4;\n };\n *data = out;\n return pos - out;\n};\n//---------------------------------------------------------------------------\n"
},
{
"answer_id": 60573554,
"author": "rokstar",
"author_id": 2150412,
"author_profile": "https://Stackoverflow.com/users/2150412",
"pm_score": 1,
"selected": false,
"text": "inline char const* b64units = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\ninline char* b64encode(void const* a, int64_t b) {\n ASSERT(a != nullptr);\n if (b > 0) {\n uint8_t const* aa = static_cast<uint8_t const*>(a);\n uint8_t v = 0;\n int64_t bp = 0;\n int64_t sb = 0;\n int8_t off = 0;\n int64_t nt = ((b + 2) / 3) * 4;\n int64_t nd = (b * 8) / 6;\n int64_t tl = ((b * 8) % 6) ? 1 : 0;\n int64_t nf = nt - nd - tl;\n int64_t ri = 0;\n char* r = new char[nt + 1]();\n for (int64_t i = 0; i < nd; i++) {\n v = (aa[sb] << off) | (aa[sb + 1] >> (8 - off));\n v >>= 2;\n r[ri] = b64units[v];\n ri += 1;\n bp += 6;\n sb = (bp / 8);\n off = (bp % 8);\n }\n if (tl > 0) {\n v = (aa[sb] << off);\n v >>= 2;\n r[ri] = b64units[v];\n ri += 1;\n }\n for (int64_t i = 0; i < nf; i++) {\n r[ri] = '=';\n ri += 1;\n }\n return r;\n } else return nullptr;\n}\n let data = 'stackabuse.com';\nlet buff = new Buffer(data);\nlet base64data = buff.toString('base64');\n"
},
{
"answer_id": 65612289,
"author": "t.m.",
"author_id": 6686454,
"author_profile": "https://Stackoverflow.com/users/6686454",
"pm_score": 0,
"selected": false,
"text": "#pragma once\n\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <cstdint>\n\nnamespace base64\n{\n inline static const char kEncodeLookup[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n inline static const char kPadCharacter = '=';\n\n using byte = std::uint8_t;\n\n inline std::string encode(const std::vector<byte>& input)\n {\n std::string encoded;\n encoded.reserve(((input.size() / 3) + (input.size() % 3 > 0)) * 4);\n\n std::uint32_t temp{};\n auto it = input.begin();\n\n for(std::size_t i = 0; i < input.size() / 3; ++i)\n {\n temp = (*it++) << 16;\n temp += (*it++) << 8;\n temp += (*it++);\n encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);\n encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);\n encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6 ]);\n encoded.append(1, kEncodeLookup[(temp & 0x0000003F) ]);\n }\n\n switch(input.size() % 3)\n {\n case 1:\n temp = (*it++) << 16;\n encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);\n encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);\n encoded.append(2, kPadCharacter);\n break;\n case 2:\n temp = (*it++) << 16;\n temp += (*it++) << 8;\n encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);\n encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);\n encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6 ]);\n encoded.append(1, kPadCharacter);\n break;\n }\n\n return encoded;\n }\n\n std::vector<byte> decode(const std::string& input)\n {\n if(input.length() % 4)\n throw std::runtime_error(\"Invalid base64 length!\");\n\n std::size_t padding{};\n\n if(input.length())\n {\n if(input[input.length() - 1] == kPadCharacter) padding++;\n if(input[input.length() - 2] == kPadCharacter) padding++;\n }\n\n std::vector<byte> decoded;\n decoded.reserve(((input.length() / 4) * 3) - padding);\n\n std::uint32_t temp{};\n auto it = input.begin();\n\n while(it < input.end())\n {\n for(std::size_t i = 0; i < 4; ++i)\n {\n temp <<= 6;\n if (*it >= 0x41 && *it <= 0x5A) temp |= *it - 0x41;\n else if(*it >= 0x61 && *it <= 0x7A) temp |= *it - 0x47;\n else if(*it >= 0x30 && *it <= 0x39) temp |= *it + 0x04;\n else if(*it == 0x2B) temp |= 0x3E;\n else if(*it == 0x2F) temp |= 0x3F;\n else if(*it == kPadCharacter)\n {\n switch(input.end() - it)\n {\n case 1:\n decoded.push_back((temp >> 16) & 0x000000FF);\n decoded.push_back((temp >> 8 ) & 0x000000FF);\n return decoded;\n case 2:\n decoded.push_back((temp >> 10) & 0x000000FF);\n return decoded;\n default:\n throw std::runtime_error(\"Invalid padding in base64!\");\n }\n }\n else throw std::runtime_error(\"Invalid character in base64!\");\n\n ++it;\n }\n\n decoded.push_back((temp >> 16) & 0x000000FF);\n decoded.push_back((temp >> 8 ) & 0x000000FF);\n decoded.push_back((temp ) & 0x000000FF);\n }\n\n return decoded;\n }\n}\n"
},
{
"answer_id": 66353595,
"author": "A.Hristov",
"author_id": 12315365,
"author_profile": "https://Stackoverflow.com/users/12315365",
"pm_score": 0,
"selected": false,
"text": "const char PADDING_CHAR = '=';\nconst char* ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst uint8_t DECODED_ALPHBET[128]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,0,0,0,0,0};\n\n/**\n * Given a string, this function will encode it in 64b (with padding)\n */\nstd::string encodeBase64(const std::string& binaryText)\n{\n std::string encoded((binaryText.size()/3 + (binaryText.size()%3 > 0)) << 2, PADDING_CHAR);\n\n const char* bytes = binaryText.data();\n union\n {\n uint32_t temp = 0;\n struct\n {\n uint32_t first : 6, second : 6, third : 6, fourth : 6;\n } tempBytes;\n };\n std::string::iterator currEncoding = encoded.begin();\n\n for(uint32_t i = 0, lim = binaryText.size() / 3; i < lim; ++i, bytes+=3)\n {\n temp = bytes[0] << 16 | bytes[1] << 8 | bytes[2];\n (*currEncoding++) = ALPHABET[tempBytes.fourth];\n (*currEncoding++) = ALPHABET[tempBytes.third];\n (*currEncoding++) = ALPHABET[tempBytes.second];\n (*currEncoding++) = ALPHABET[tempBytes.first];\n }\n\n switch(binaryText.size() % 3)\n {\n case 1:\n temp = bytes[0] << 16;\n (*currEncoding++) = ALPHABET[tempBytes.fourth];\n (*currEncoding++) = ALPHABET[tempBytes.third];\n break;\n case 2:\n temp = bytes[0] << 16 | bytes[1] << 8;\n (*currEncoding++) = ALPHABET[tempBytes.fourth];\n (*currEncoding++) = ALPHABET[tempBytes.third];\n (*currEncoding++) = ALPHABET[tempBytes.second];\n break;\n }\n\n return encoded;\n}\n\n/**\n * Given a 64b padding-encoded string, this function will decode it.\n */\nstd::string decodeBase64(const std::string& base64Text)\n{\n if( base64Text.empty() )\n return \"\";\n\n assert((base64Text.size()&3) == 0 && \"The base64 text to be decoded must have a length devisible by 4!\");\n\n uint32_t numPadding = (*std::prev(base64Text.end(),1) == PADDING_CHAR) + (*std::prev(base64Text.end(),2) == PADDING_CHAR);\n\n std::string decoded((base64Text.size()*3>>2) - numPadding, '.');\n\n union\n {\n uint32_t temp;\n char tempBytes[4];\n };\n const uint8_t* bytes = reinterpret_cast<const uint8_t*>(base64Text.data());\n\n std::string::iterator currDecoding = decoded.begin();\n\n for(uint32_t i = 0, lim = (base64Text.size() >> 2) - (numPadding!=0); i < lim; ++i, bytes+=4)\n {\n temp = DECODED_ALPHBET[bytes[0]] << 18 | DECODED_ALPHBET[bytes[1]] << 12 | DECODED_ALPHBET[bytes[2]] << 6 | DECODED_ALPHBET[bytes[3]];\n (*currDecoding++) = tempBytes[2];\n (*currDecoding++) = tempBytes[1];\n (*currDecoding++) = tempBytes[0];\n }\n\n switch (numPadding)\n {\n case 2:\n temp = DECODED_ALPHBET[bytes[0]] << 18 | DECODED_ALPHBET[bytes[1]] << 12;\n (*currDecoding++) = tempBytes[2];\n break;\n \n case 1:\n temp = DECODED_ALPHBET[bytes[0]] << 18 | DECODED_ALPHBET[bytes[1]] << 12 | DECODED_ALPHBET[bytes[2]] << 6;\n (*currDecoding++) = tempBytes[2];\n (*currDecoding++) = tempBytes[1];\n break;\n }\n\n return decoded;\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19104/"
] |
180,979
|
<p>I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.</p>
<p>Lets say that I am trying to shuffle the <code>randomizer</code> array. </p>
<pre><code>int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
</code></pre>
<p>For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas? </p>
|
[
{
"answer_id": 180990,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "Arrays.asList Integer[] randomizer = new Integer[] {200,300,212,111,6,2332}; \nCollections.shuffle(Arrays.asList(randomizer));\n int[] asList int"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013/"
] |
180,985
|
<p>Why does tempuri.org exist? Why does each XML Webservice require its own namespace, unique from any other on the web?</p>
|
[
{
"answer_id": 181006,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 6,
"selected": false,
"text": "tempuri.org archive.org [WebService(Namespace=\"http://microsoft.com/webservices/\")]\npublic class MyWebService {\n // implementation\n}\n <WebService(Namespace:=\"http://microsoft.com/webservices/\")> Public Class MyWebService\n ' implementation\nEnd Class\n /**@attribute WebService(Namespace=\"http://microsoft.com/webservices/\")*/\npublic class MyWebService {\n // implementation\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
180,986
|
<p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the Python <code>re</code> module?</p>
<p>I've read the <a href="https://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match" rel="nofollow noreferrer">Python 2 documentation</a> (<a href="https://docs.python.org/3/library/re.html#search-vs-match" rel="nofollow noreferrer">Python 3 documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
|
[
{
"answer_id": 180993,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 10,
"selected": true,
"text": "re.match ^ MatchObject None search() re.search MatchObject None match search match search match search match search '^' '^' MULTILINE match pos # example code:\nstring_with_newlines = \"\"\"something\nsomeotherthing\"\"\"\n\nimport re\n\nprint re.match('some', string_with_newlines) # matches\nprint re.match('someother', \n string_with_newlines) # won't match\nprint re.match('^someother', string_with_newlines, \n re.MULTILINE) # also won't match\nprint re.search('someother', \n string_with_newlines) # finds something\nprint re.search('^someother', string_with_newlines, \n re.MULTILINE) # also finds something\n\nm = re.compile('thing$', re.MULTILINE)\n\nprint m.match(string_with_newlines) # no match\nprint m.match(string_with_newlines, pos=4) # matches\nprint m.search(string_with_newlines, \n re.MULTILINE) # also matches\n"
},
{
"answer_id": 181028,
"author": "xilun",
"author_id": 17064,
"author_profile": "https://Stackoverflow.com/users/17064",
"pm_score": 6,
"selected": false,
"text": "re.search re.match"
},
{
"answer_id": 8687988,
"author": "Dhanasekaran Anbalagan",
"author_id": 795595,
"author_profile": "https://Stackoverflow.com/users/795595",
"pm_score": 7,
"selected": false,
"text": "search match"
},
{
"answer_id": 31715754,
"author": "ldR",
"author_id": 5172000,
"author_profile": "https://Stackoverflow.com/users/5172000",
"pm_score": 5,
"selected": false,
"text": "re.match a = \"123abc\"\nt = re.match(\"[a-z]+\",a)\nt = re.search(\"[a-z]+\",a)\n re.match none re.search abc"
},
{
"answer_id": 37363575,
"author": "CODE-REaD",
"author_id": 5025060,
"author_profile": "https://Stackoverflow.com/users/5025060",
"pm_score": 5,
"selected": false,
"text": "re.match() re.search() re.match() re.match('pattern') re.search('^pattern') $ re.match()"
},
{
"answer_id": 49710946,
"author": "Jeyekomon",
"author_id": 1232660,
"author_profile": "https://Stackoverflow.com/users/1232660",
"pm_score": 6,
"selected": false,
"text": "import random\nimport re\nimport string\nimport time\n\nLENGTH = 10\nLIST_SIZE = 1000000\n\ndef generate_word():\n word = [random.choice(string.ascii_lowercase) for _ in range(LENGTH)]\n word = ''.join(word)\n return word\n\nwordlist = [generate_word() for _ in range(LIST_SIZE)]\n\nstart = time.time()\n[re.search('python', word) for word in wordlist]\nprint('search:', time.time() - start)\n\nstart = time.time()\n[re.match('(.*?)python(.*?)', word) for word in wordlist]\nprint('match:', time.time() - start)\n 'python' '(.*?)python(.*?)'"
},
{
"answer_id": 53074635,
"author": "U12-Forward",
"author_id": 8708364,
"author_profile": "https://Stackoverflow.com/users/8708364",
"pm_score": 5,
"selected": false,
"text": "search match >>> a = \"123abc\"\n>>> re.match(\"[a-z]+\",a)\nNone\n>>> re.search(\"[a-z]+\",a)\nabc\n"
},
{
"answer_id": 72683643,
"author": "Pall Arpad",
"author_id": 7381099,
"author_profile": "https://Stackoverflow.com/users/7381099",
"pm_score": 0,
"selected": false,
"text": "re.search('test', ' test') # returns a Truthy match object (because the search starts from any index) \n\nre.match('test', ' test') # returns None (because the search start from 0 index)\nre.match('test', 'test') # returns a Truthy match object (match at 0 index)\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/180986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
181,015
|
<p>I am just checking out F#, so apologies if this is a silly question, but in the VS2008 F# CTP 1.9.6.2 'Tutorial' project, both // and /// are used for commenting code.</p>
<p>Is there a functional difference between the two slash vs three slash commenting, or is it convention (as it appears in the tutorial code) to comment a function with /// and use // for everything else?</p>
|
[
{
"answer_id": 181172,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 3,
"selected": false,
"text": "/* comment */ /** documented comment */"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
181,018
|
<p>My application has no forms. It runs by calling Application.Run();</p>
|
[
{
"answer_id": 181020,
"author": "Haim Bender",
"author_id": 44972,
"author_profile": "https://Stackoverflow.com/users/44972",
"pm_score": 3,
"selected": true,
"text": "System.Windows.Forms.Application.Exit();\n"
},
{
"answer_id": 181098,
"author": "Ryan Taylor",
"author_id": 6231,
"author_profile": "https://Stackoverflow.com/users/6231",
"pm_score": 1,
"selected": false,
"text": "Environment.Exit() System.Windows.Forms.Application.Exit()"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
] |
181,029
|
<p>Has anyone been able to implement the JQuery grid plugin, jqGrid? I'm trying to implement the JSON paging, and I feel like I'm getting close, but that I am also being swamped by inconsequential details. If anyone could post some sample code, I would greatly appreciate it.</p>
|
[
{
"answer_id": 181072,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 0,
"selected": false,
"text": " [WebMethod]\n [ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n public static object GetData() {\n TestClass tc = new TestClass() { One = \"Hello\", Two = \"World\" };\n return tc;\n }\n\n\n $(\"#divResults\").click(function() {\n $.ajax({\n type: \"POST\",\n url: \"GridData_bak.aspx/GetData\",\n data: \"{}\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(test) {\n // Replace the div's content with the page method's return.\n $(\"#divResults\").text(test.d.One);\n },\n error: function(msg) {\n $(\"#divResults\").text(msg);\n }\n });\n });\n"
},
{
"answer_id": 308688,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "the setup for the grid\n $(\"#tableToFlex\").flexigrid({\n url: 'WebService.asmx/getData'}\n ... *other configs* ...);\n <WebMethod()> _\n<ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> _\nPublic Function getData(ByVal page As Integer, _\n ByVal qtype As String, _\n ByVal Query As String, _\n ByVal rp As Integer, _\n ByVal sortname As String, _\n ByVal sortorder As String) As System.Xml.XmlDocument\n 'note these parameters are inputted to determine paging and constrains for the resultant rows\n\n 'Sample list to send to the grid\n Dim list = New List(Of ApplicationStateInformation)\n 'Sample row object that holds name , surname , address, idnumber ...\n list.Add(New RowObjects( \"test1\", \"test1\", \"test1\", \"12345\"))\n list.Add(New RowObjects( \"test2\", \"test2\", \"test2\", \"12345\"))\n list.Add(New RowObjects( \"test3\", \"test3\", \"test3\", \"12345\"))\n list.Add(New RowObjects( \"test4\", \"test4\", \"test4\", \"12345\"))\n 'retun a xml doc, as we are using the xml format on the flexgrid\n\n Dim returnDoc = New System.Xml.XmlDocument()\n returnDoc.Load(New IO.StringReader(ToXmlResult(list)))\n Return returnDoc\nEnd Function\n\nPrivate Function ToXmlResult(ByVal list As List(Of RowObjects)) As String\n 'this is the xml document format the grid understands\n Dim result As String = \"<?xml version=\"\"1.0\"\" encoding=\"\"utf-8\"\"?>\" & vbCrLf\n result += \"<rows>\" & vbCrLf\n result += String.Format(\"<page>{0}</page>\" & vbCrLf, \"1\")\n result += String.Format(\"<total>{0}</total>\" & vbCrLf, \"10\")\n For Each item In list\n result += ConvertRowData(item)\n Next\n result += \"</rows>\" & vbCrLf\n Return result\nEnd Function\n\nPrivate Function ConvertRowData(ByVal row As RowObjects) As String\n\n Dim result As String = String.Format(\"<row id='{0}'>\" & vbCrLf, row.IdNumber.ToString)\n 'THESE SHOULD BE HTML ENCODED (the format arg) but I left it out\n result += String.Format(\"<cell><![CDATA[{0}]]></cell>\" & vbCrLf, row.Name)\n result += String.Format(\"<cell><![CDATA[{0}]]></cell>\" & vbCrLf, row.Surname)\n result += String.Format(\"<cell><![CDATA[{0}]]></cell>\" & vbCrLf, row.IdNumber)\n\n result += \"</row>\" & vbCrLf\n Return result\nEnd Function\n"
},
{
"answer_id": 432734,
"author": "nshaw",
"author_id": 29426,
"author_profile": "https://Stackoverflow.com/users/29426",
"pm_score": 4,
"selected": true,
"text": "case \"json\":\n gdata = JSON.stringify(gdata); //ASP.NET expects JSON as a string\n $.ajax({ url: ts.p.url, \n type: ts.p.mtype, \n dataType: \"json\", \n contentType: \"application/json; charset=utf-8\", //required by ASP.NET\n data: gdata, \n complete: function(JSON, st) { if (st == \"success\") { addJSONData(cleanUp(JSON.responseText), ts.grid.bDiv); if (loadComplete) { loadComplete(); } } }, \n error: function(xhr, st, err) { if (loadError) { loadError(xhr, st, err); } endReq(); }, \n beforeSend: function(xhr) { if (loadBeforeSend) { loadBeforeSend(xhr); } } });\n if (ts.p.loadonce || ts.p.treeGrid) { ts.p.datatype = \"local\"; }\n break;\n function cleanUp(responseText) {\n var myObject = JSON.parse(responseText); //more secure than eval\n return myObject.d; //ASP.NET special\n}\n"
},
{
"answer_id": 711631,
"author": "darren",
"author_id": 51688,
"author_profile": "https://Stackoverflow.com/users/51688",
"pm_score": 1,
"selected": false,
"text": "public class Person\n{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime Birthday { get; set; }\n\n public static IEnumerable<Person> GetABunchOfPeople()\n {\n // Get a bunch of People.\n }\n}\n public JsonResult GetABunchOfPeopleAsJson()\n{\n var rows = (Person.GetABunchOfPeople()\n .Select(c => new\n {\n id = c.ID,\n cell = new[]\n {\n c.ID.ToString(),\n c.Name,\n c.Birthday.ToShortDateString()\n }\n })).ToArray();\n\n return new JsonResult\n {\n Data = new\n {\n page = 1,\n records = rows.Length,\n rows,\n total = 1\n }\n };\n}\n url: '<%= ResolveUrl(\"~/Person/GetAllPeople\") %>',\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685/"
] |
181,036
|
<p>I'm trying to get this simple PowerShell script working, but I think something is fundamentally wrong. ;-)</p>
<pre><code>ls | ForEach { "C:\Working\tools\custom-tool.exe" $_ }
</code></pre>
<p>I basically want to get files in a directory, and pass them one by one as arguments to the custom tool.</p>
|
[
{
"answer_id": 181065,
"author": "slipsec",
"author_id": 1635,
"author_profile": "https://Stackoverflow.com/users/1635",
"pm_score": 6,
"selected": true,
"text": "ls | %{C:\\Working\\tools\\custom-tool.exe $_}\n"
},
{
"answer_id": 182154,
"author": "Jeffery Hicks",
"author_id": 25508,
"author_profile": "https://Stackoverflow.com/users/25508",
"pm_score": 3,
"selected": false,
"text": "ls | %{C:\\Working\\tools\\custom-tool.exe $_.fullname}\n"
},
{
"answer_id": 182535,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 6,
"selected": false,
"text": "ls | % { &\"C:\\Working\\tools\\custom-tool.exe\" $_.FullName }\n"
},
{
"answer_id": 188255,
"author": "EdgeVB",
"author_id": 24863,
"author_profile": "https://Stackoverflow.com/users/24863",
"pm_score": 2,
"selected": false,
"text": "gci | % { c:\\windows\\notepad.exe $_.fullname }\n gci | % { c:\\windows\\notepad.exe $_ }\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18437/"
] |
181,038
|
<p>I installed Ruby and Ruby on Rails yesterday on Vista 32bit using the directions on this site: <a href="http://rubyonrails.org/down" rel="nofollow noreferrer">http://rubyonrails.org/down</a></p>
<p>So I downloaded the installer, then Gems, then I downloaded rails with Gems.</p>
<p>Now I can't use the Gem or Ruby commands in the command line... so I assume there's something wrong with the environment variables, but I hav eno idea how to set them up in Vista or what to put.</p>
<p>Can anyone help me with this?</p>
|
[
{
"answer_id": 181053,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "PATH ruby.exe PATH c:\\ruby c:\\ruby\\bin\\"
},
{
"answer_id": 181071,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": true,
"text": "Computer Properties Advanced system settings Advanced Environment Variables... User variables for XXX PATH PATH c:\\ruby\\bin gem ruby irb"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13713/"
] |
181,046
|
<p>I am trying to learn some of the basic and advanced features of visual studio, Anyone find sites that have this type of information ?</p>
<p>I see this:</p>
<p><a href="https://stackoverflow.com/questions/86355/best-way-to-learn-visual-studio-power-features">https://stackoverflow.com/questions/86355/best-way-to-learn-visual-studio-power-features</a></p>
<p>But it seems more related to tips and advanced features.</p>
<p>All three versions ( 2003, 2005, 2008 ) </p>
|
[
{
"answer_id": 181053,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "PATH ruby.exe PATH c:\\ruby c:\\ruby\\bin\\"
},
{
"answer_id": 181071,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": true,
"text": "Computer Properties Advanced system settings Advanced Environment Variables... User variables for XXX PATH PATH c:\\ruby\\bin gem ruby irb"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
181,064
|
<p>For my current C++ project I need to detect a unique string for every monitor that is connected and active on a large number of computers. </p>
<p>Research has pointed to 2 options</p>
<ol>
<li><p>Use WMI and query the Win32_DesktopMonitor for all active monitors. Use the PNPDeviceID for unique identification of monitors.</p></li>
<li><p>Use the EnumDisplayDevices API, and dig down to get the device ID.</p></li>
</ol>
<p>I'm interested in using the device id for unique model identification because monitors using the default plug and play driver will report a generic string as the monitor name "default plug and play monitor" </p>
<p>I have been experiencing issues with the WMI method, it seems to be only returning 1 monitor on my Vista machine, looking at the doco it turns out it does not work as expected on non WDDM devices. </p>
<p>The EnumDisplayDevices seems to be a little problematic to get going when it runs from a background service (especially on Vista), If it's in session 0 it will return no info. </p>
<ul>
<li><p>Has anyone else had to do something similar (find unique model string for all connected active monitors?) </p></li>
<li><p>What approach worked best?</p></li>
</ul>
|
[
{
"answer_id": 183284,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 0,
"selected": false,
"text": "EnumDisplayDevices"
},
{
"answer_id": 183620,
"author": "akalenuk",
"author_id": 25459,
"author_profile": "https://Stackoverflow.com/users/25459",
"pm_score": 1,
"selected": false,
"text": "int disp_num = 0;\n BOOL res = TRUE;\n do {\n DISPLAY_DEVICE disp_dev_info; \n ZeroMemory( &disp_dev_info, sizeof(DISPLAY_DEVICE) );\n disp_dev_info.cb = sizeof(DISPLAY_DEVICE);\n res = EnumDisplayDevices( 0, disp_num++, &disp_dev_info, 0x00000001 );\n if(res &&\n disp_dev_info.DeviceString[0]!=0 && disp_dev_info.DeviceString[0]=='N' &&\n disp_dev_info.DeviceString[1]!=0 && disp_dev_info.DeviceString[1]=='V' && \n disp_dev_info.DeviceString[2]!=0 && disp_dev_info.DeviceString[2]=='I' && \n disp_dev_info.DeviceString[3]!=0 && disp_dev_info.DeviceString[3]=='D' && \n disp_dev_info.DeviceString[4]!=0 && disp_dev_info.DeviceString[4]=='I' && \n disp_dev_info.DeviceString[5]!=0 && disp_dev_info.DeviceString[5]=='A'){\n isNVidia = true;\n }\n int x = 0;\n }while( res != FALSE );\n"
},
{
"answer_id": 202877,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 4,
"selected": true,
"text": "CString DeviceID;\nDISPLAY_DEVICE dd; \ndd.cb = sizeof(dd); \nDWORD dev = 0; \n// device index \nint id = 1; \n// monitor number, as used by Display Properties > Settings\n\nwhile (EnumDisplayDevices(0, dev, &dd, 0))\n{\n DISPLAY_DEVICE ddMon;\n ZeroMemory(&ddMon, sizeof(ddMon));\n ddMon.cb = sizeof(ddMon);\n DWORD devMon = 0;\n\n while (EnumDisplayDevices(dd.DeviceName, devMon, &ddMon, 0))\n {\n if (ddMon.StateFlags & DISPLAY_DEVICE_ACTIVE && \n !(ddMon.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))\n {\n DeviceID.Format (L\"%s\", ddMon.DeviceID);\n DeviceID = DeviceID.Mid (8, DeviceID.Find (L\"\\\\\", 9) - 8);\n }\n devMon++;\n\n ZeroMemory(&ddMon, sizeof(ddMon));\n ddMon.cb = sizeof(ddMon);\n }\n\n ZeroMemory(&dd, sizeof(dd));\n dd.cb = sizeof(dd);\n dev++; \n}\n"
},
{
"answer_id": 7468393,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": 2,
"selected": false,
"text": "select * from Win32_PnPEntity where service=\"monitor\"\n\nAvailability | Caption | ClassGuid | CompatibleID | ConfigManagerErrorCode | ConfigManagerUserConfig | CreationClassName | Description | DeviceID | ErrorCleared | ErrorDescription | HardwareID | InstallDate | LastErrorCode | Manufacturer | Name | PNPDeviceID | PowerManagementCapabilities | PowerManagementSupported | Service | Status | StatusInfo | SystemCreationClassName | SystemName\n | Dell 2007FP (Digital) | {4d36e96e-e325-11ce-bfc1-08002be10318} | array[0..0] | 0 | False | Win32_PnPEntity | Dell 2007FP (Digital) | DISPLAY\\DELA021\\5&4F61016&0&UID257 | | | array[0..0] | | | Dell Inc. | Dell 2007FP (Digital) | DISPLAY\\DELA021\\5&4F61016&0&UID257 | | | monitor | OK | | Win32_ComputerSystem | 8HVS05J\n | Dell ST2320L_Digital | {4d36e96e-e325-11ce-bfc1-08002be10318} | array[0..0] | 0 | False | Win32_PnPEntity | Dell ST2320L_Digital | DISPLAY\\DELF023\\5&4F61016&0&UID256 | | | array[0..0] | | | Dell Inc. | Dell ST2320L_Digital | DISPLAY\\DELF023\\5&4F61016&0&UID256 | | | monitor | OK | | Win32_ComputerSystem | 8HVS05J\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
181,082
|
<p>I have followed all the instructions here: <a href="http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/" rel="noreferrer">http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/</a></p>
<p>to install & config apache
get the PHP5 packages
and get the CURL packages.</p>
<p>I run the apache and run a PHP script. no problem.
but when I run the php script with curl, it fails. </p>
<p>It returns: <code>**Call to undefined function curl_version() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\testing.php on line 5**</code></p>
<p>In which line 5 is a called to <code>curl_init()</code></p>
<p>I output the php -i to see whether the right path to extension is called. It is correctly set:</p>
<pre><code>extension_dir => C:\PHP\ext => C:\PHP\ext
cURL support => enabled
cURL Information => libcurl/7.16.0 OpenSSL/0.9.8g zlib/1.2.3
</code></pre>
<p>I even tried to run <code>curl_version()</code> but still, same kind of error comes up.<br>
It looks like the PHP can't find the CURL extension, but the <code>php.ini</code> (and also php -i) shows that it is set.</p>
<p>any idea? :)</p>
<pre><code>P.S> System I m running on:
Windows XP
Apache 2.2
PHP 5.2.6
CURL Win32 Generic Binaries: Win32 2000/XP metalink 7.19.0 binary SSL enabled Daniel Stenberg 249 KB
</code></pre>
<p>I didn't get this: </p>
<pre><code>Win32 2000/XP 7.19.0 libcurl SSL enabled Günter Knauf 1.55 MB
Should I get this one instead?
</code></pre>
<hr>
<p>The reason I need to use CURL is that it is the requirement from my project. So, I can only stick with that.
XAMPP... how does it work in Windows? Is there any site that you can recommend? Thanks.</p>
<p>I have tried a lot of things on installing cURL and check everything, but still, I'm stilling circling around the problem and have no idea what's going on. </p>
<p>The Apache server uses the right PHP.ini. and the PHP.ini has the correct extension_dir and extension=php_curl.dll
I have no idea why it doesn't work. even I follow every step for setting it up. :(</p>
|
[
{
"answer_id": 181220,
"author": "boxoft",
"author_id": 23773,
"author_profile": "https://Stackoverflow.com/users/23773",
"pm_score": 4,
"selected": false,
"text": ";extension=php_curl.dll ;"
},
{
"answer_id": 526025,
"author": "TrentCoder",
"author_id": 63908,
"author_profile": "https://Stackoverflow.com/users/63908",
"pm_score": 2,
"selected": false,
"text": " <?php\n error_reporting(E_ALL);\n ini_set('display_errors', '1');\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL,\n 'http://news.google.com/news?hl=en&topic=t&output=rss');\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n $contents = curl_exec ($ch);\n echo $contents;\n curl_close ($ch);\n ?>\n"
},
{
"answer_id": 28184708,
"author": "RizonBarns",
"author_id": 2302672,
"author_profile": "https://Stackoverflow.com/users/2302672",
"pm_score": 2,
"selected": false,
"text": "PATH=%PATH%;<Your_PHP_Path>\n PATH=%PATH%;C:\\php\n"
},
{
"answer_id": 30073534,
"author": "Nuadu",
"author_id": 4693736,
"author_profile": "https://Stackoverflow.com/users/4693736",
"pm_score": 3,
"selected": false,
"text": "extension=C:/php/ext/php_curl.dll\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196874/"
] |
181,090
|
<p>I have a tree of active record objects, something like:</p>
<pre><code>class Part < ActiveRecord::Base
has_many :sub_parts, :class_name => "Part"
def complicated_calculation
if sub_parts.size > 0
return self.sub_parts.inject(0){ |sum, current| sum + current.complicated_calculation }
else
sleep(1)
return rand(10000)
end
end
end
</code></pre>
<p>It is too costly to recalculate the complicated_calculation each time. So, I need a way to cache the value. However, if any part is changed, it needs to invalidate its cache and the cache of its parent, and grandparent, etc.</p>
<p>As a rough draft, I created a column to hold the cached calculation in the "parts" table, but this smells a little rotten. It seems like there should be a cleaner way to cache the calculated values without stuffing them along side the "real" columns.</p>
|
[
{
"answer_id": 181502,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 4,
"selected": true,
"text": "Part.sweep_complicated_cache(some_part) complicated_calculation class Part < ActiveRecord::Base\n has_many :sub_parts, :class_name => \"Part\"\n belongs_to :parent_part, :class_name => \"Part\", :foreign_key => :part_id\n\n @@MAX_PART_NESTING = 25 #pick any sanity-saving value\n\n def complicated_calculation (...)\n if cache.contains? [id, :complicated_calculation]\n cache[ [id, :complicated_calculation] ]\n else\n cache[ [id, :complicated_calculation] ] = complicated_calculation_helper (...)\n end\n end\n\n def complicated_calculation_helper\n #your implementation goes here\n end\n\n def Part.sweep_complicated_cache(start_part)\n level = 1 # keep track to prevent infinite loop in event there is a cycle in parts\n current_part = self\n\n cache[ [current_part.id, :complicated_calculation] ].delete\n while ( (level <= 1 < @@MAX_PART_NESTING) && (current_part.parent_part)) {\n current_part = current_part.parent_part)\n cache[ [current_part.id, :complicated_calculation] ].delete\n end\n end\nend\n"
},
{
"answer_id": 181675,
"author": "August Lilleaas",
"author_id": 26051,
"author_profile": "https://Stackoverflow.com/users/26051",
"pm_score": 5,
"selected": false,
"text": "class Part < ActiveRecord::Base\n has_many :sub_parts,\n :class_name => \"Part\",\n :after_add => :count_sub_parts,\n :after_remove => :count_sub_parts\n\n private\n\n def count_sub_parts\n update_attribute(:sub_part_count, calculate_sub_part_count)\n end\n\n def calculate_sub_part_count\n # perform the actual calculation here\n end\nend\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23899/"
] |
181,091
|
<p>I have an array of hashes, and I want the unique values out of it. Calling <code>Array.uniq</code> doesn't give me what I expect.</p>
<pre><code>a = [{:a => 1},{:a => 2}, {:a => 1}]
a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}]
</code></pre>
<p>Where I expected:</p>
<pre><code>[{:a => 1}, {:a => 2}]
</code></pre>
<p>In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining <code>Hash.eql?</code> and <code>Hash.hash</code>, since that is what <code>Array.uniq</code> is querying.</p>
<p>Edit:
Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values.</p>
<p>I don't like the redefine <code>Hash.eql?</code> and <code>Hash.hash</code> solution, because I would either have to redefine <code>Hash</code> globally, or redefine it for each entry in my array. Changing the definition of <code>Hash</code> for each entry would be cumbersome, especially since there may be nested hashes inside of each entry.</p>
<p>Changing <code>Hash</code> globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed.</p>
<p>Using <code>inject</code> seems like a good alternative to redefining <code>Hash</code>.</p>
|
[
{
"answer_id": 181096,
"author": "Aaron Hinni",
"author_id": 12086,
"author_profile": "https://Stackoverflow.com/users/12086",
"pm_score": 6,
"selected": true,
"text": "inject a = [{:a => 1},{:a => 2}, {:a => 1}]\na.inject([]) { |result,h| result << h unless result.include?(h); result }\n [{:a=>1}, {:a=>2}]\n"
},
{
"answer_id": 181396,
"author": "Mark Reid",
"author_id": 24057,
"author_profile": "https://Stackoverflow.com/users/24057",
"pm_score": 0,
"selected": false,
"text": "hash eql? uniq"
},
{
"answer_id": 183692,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 2,
"selected": false,
"text": "a.map {|h| h.to_a[0]}.uniq.map {|k,v| {k => v}}\n [[:a, 1], [:a, 2], [:a, 1]]\n [[:a, 1], [:a, 2]]\n"
},
{
"answer_id": 834604,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "[{:x=>1},{:x=>2},{:x=>3},{:x=>2},{:x=>1}]\n #sort_by {|t| t[:x]} [{:x=>1}, {:x=>1}, {:x=>2}, {:x=>2}, {:x=>3}]\n your_array.inject([]) do |result,item| \n result << item if !result.last||result.last[:x]!=item[:x]\n result\nend\n test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]}\n test=[]\n1000.times {test<<{:x=>rand}}\n\nBenchmark.bmbm do |bm|\n bm.report(\"sorting: \") do\n test.sort_by {|t| t[:x]}.inject([]) {|r,h| r<<h if !r.last||r.last[:x]!=h[:x]; r}\n end\n bm.report(\"inject: \") {test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]} }\nend\n Rehearsal ---------------------------------------------\nsorting: 0.010000 0.000000 0.010000 ( 0.005633)\ninject: 0.470000 0.140000 0.610000 ( 0.621973)\n------------------------------------ total: 0.620000sec\n\n user system total real\nsorting: 0.010000 0.000000 0.010000 ( 0.003839)\ninject: 0.480000 0.130000 0.610000 ( 0.612438)\n"
},
{
"answer_id": 5626441,
"author": "fl00r",
"author_id": 298624,
"author_profile": "https://Stackoverflow.com/users/298624",
"pm_score": 4,
"selected": false,
"text": "[{:a=>1}, {:a=>2}, {:a=>1}].uniq\n#=> [{:a=>1}, {:a=>2}] \n"
},
{
"answer_id": 13274328,
"author": "yoniLavi",
"author_id": 493553,
"author_profile": "https://Stackoverflow.com/users/493553",
"pm_score": 0,
"selected": false,
"text": "a [] | a"
},
{
"answer_id": 27776023,
"author": "shajin",
"author_id": 519680,
"author_profile": "https://Stackoverflow.com/users/519680",
"pm_score": 2,
"selected": false,
"text": "[{a: 1},{a: 2},{a:1}].uniq => [{a:1},{a: 2}]\n[{a: 1,b: 2},{a: 2, b: 2},{a: 1, b: 3}].uniq_by {|v| v[:a]} => [{a: 1,b: 2},{a: 2, b: 2}]\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12086/"
] |
181,095
|
<p>I would like to extract from a general HTML page, all the text (displayed or not).</p>
<p>I would like to <strong>remove</strong> </p>
<ul>
<li>any HTML tags</li>
<li>Any javascript</li>
<li>Any CSS styles</li>
</ul>
<p>Is there a regular expression (one or more) that will achieve that?</p>
|
[
{
"answer_id": 181101,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "!<body.*?>(.*)</body>!smi\n !<script.*?</script>!!smi\n!<[^>]+/[ \\t]*>!!smi\n!</?([a-z]+).*?>!!smi\n/<!--.*?-->//smi\n"
},
{
"answer_id": 181105,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": false,
"text": "<(script|style).*?</\\1>\n <.*?>\n"
},
{
"answer_id": 181116,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": "<![CDATA[ <text>"
},
{
"answer_id": 181153,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 1,
"selected": false,
"text": "document.body.innerText\n"
},
{
"answer_id": 2685805,
"author": "David Avsajanishvili",
"author_id": 322606,
"author_profile": "https://Stackoverflow.com/users/322606",
"pm_score": 2,
"selected": false,
"text": "text = \"<p>This is my> <strong>example</strong>HTML,<br /> containing tags</p>\"\nimport re\n\" \".join([t.strip() for t in re.findall(r\"<[^>]+>|[^<]+\",text) if not '<' in t])\n 'This is my> example HTML, containing tags'\n"
},
{
"answer_id": 4638642,
"author": "Ayush",
"author_id": 492645,
"author_profile": "https://Stackoverflow.com/users/492645",
"pm_score": 2,
"selected": false,
"text": "function strip_html_tags( $text ) \n{\n\n$text = preg_replace(\n array(\n // Remove invisible content\n '@<head[^>]*?>.*?</head>@siu',\n '@<style[^>]*?>.*?</style>@siu',\n '@<script[^>]*?.*?</script>@siu',\n '@<object[^>]*?.*?</object>@siu',\n '@<embed[^>]*?.*?</embed>@siu',\n '@<applet[^>]*?.*?</applet>@siu',\n '@<noframes[^>]*?.*?</noframes>@siu',\n '@<noscript[^>]*?.*?</noscript>@siu',\n '@<noembed[^>]*?.*?</noembed>@siu',\n\n // Add line breaks before & after blocks\n '@<((br)|(hr))@iu',\n '@</?((address)|(blockquote)|(center)|(del))@iu',\n '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',\n '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',\n '@</?((table)|(th)|(td)|(caption))@iu',\n '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',\n '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',\n '@</?((frameset)|(frame)|(iframe))@iu',\n ),\n array(\n ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n \"\\n\\$0\", \"\\n\\$0\", \"\\n\\$0\", \"\\n\\$0\", \"\\n\\$0\", \"\\n\\$0\",\n \"\\n\\$0\", \"\\n\\$0\",\n ),\n $text );\n\n// Remove all remaining tags and comments and return.\nreturn strip_tags( $text );\n }\n"
},
{
"answer_id": 7620686,
"author": "Shiroy",
"author_id": 756506,
"author_profile": "https://Stackoverflow.com/users/756506",
"pm_score": 1,
"selected": false,
"text": " System.Windows.Forms.WebBrowser wc = new System.Windows.Forms.WebBrowser();\n wc.DocumentText = \"<html><body>blah blah<b>foo</b></body></html>\";\n System.Windows.Forms.HtmlDocument h = wc.Document;\n Console.WriteLine(h.Body.InnerText);\n"
},
{
"answer_id": 9124295,
"author": "mahesh",
"author_id": 1186821,
"author_profile": "https://Stackoverflow.com/users/1186821",
"pm_score": 1,
"selected": false,
"text": "string decode = System.Web.HttpUtility.HtmlDecode(your_htmlfile.html);\n Regex objRegExp = new Regex(\"<(.|\\n)+?>\");\n string replace = objRegExp.Replace(g, \"\");\n replace = replace.Replace(k, string.Empty);\n replace.Trim(\"\\t\\r\\n \".ToCharArray());\n\nthen take a label and do \"label.text=replace;\" see on label out put\n"
},
{
"answer_id": 14043702,
"author": "Joe Bergevin",
"author_id": 1822711,
"author_profile": "https://Stackoverflow.com/users/1822711",
"pm_score": 3,
"selected": false,
"text": "function plaintext($html)\n{\n // remove comments and any content found in the the comment area (strip_tags only removes the actual tags).\n $plaintext = preg_replace('#<!--.*?-->#s', '', $html);\n\n // put a space between list items (strip_tags just removes the tags).\n $plaintext = preg_replace('#</li>#', ' </li>', $plaintext);\n\n // remove all script and style tags\n $plaintext = preg_replace('#<(script|style)\\b[^>]*>(.*?)</(script|style)>#is', \"\", $plaintext);\n\n // remove br tags (missed by strip_tags)\n $plaintext = preg_replace(\"#<br[^>]*?>#\", \" \", $plaintext);\n\n // remove all remaining html\n $plaintext = strip_tags($plaintext);\n\n return $plaintext;\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363/"
] |
181,097
|
<p>I wanted to do something like this:</p>
<pre><code><asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label>
</code></pre>
<p>I know that in Javascript I can do:</p>
<pre><code><span onclick="foo();">My Label</span>
</code></pre>
<p>So I'm wondering why I can't do that with a Label object.</p>
|
[
{
"answer_id": 181103,
"author": "Brian Kim",
"author_id": 5704,
"author_profile": "https://Stackoverflow.com/users/5704",
"pm_score": 7,
"selected": true,
"text": "lblMyLabel.Attributes.Add(\"onclick\", \"foo();\"); foo(); System.Web.UI.WebControls.Label LinkButton <asp:LinkButton ID=\"LinkButton1\" runat=\"server\" \n CssClass=\"imjusttext\" OnClick=\"LinkButton1_Click\">\nLinkButton\n</asp:LinkButton>\n a.imjusttext{ color: #000000; text-decoration: none; }\na.imjusttext:hover { text-decoration: none; }\n"
},
{
"answer_id": 181108,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 3,
"selected": false,
"text": "void Page_Load(object sender, EventArgs e) \n{\n lblMyLabel.Attributes.Add(\"onclick\",\n \"javascript:alert('ALERT ALERT!!!')\");\n}\n"
},
{
"answer_id": 181110,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 1,
"selected": false,
"text": "<span"
},
{
"answer_id": 181113,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "onclientclick <asp:linkbutton id=\"lblMyLink\" onclientclick=\"lblMyLink_Click\" runat=\"server\">My Label</asp:linkbutton>\n"
},
{
"answer_id": 181118,
"author": "CodeChef",
"author_id": 21786,
"author_profile": "https://Stackoverflow.com/users/21786",
"pm_score": 4,
"selected": false,
"text": "asp:label id=\"MyLabel\" runat=\"server\" onclick=\"javascript:alert('hello');\" Text=\"Click Me\";"
},
{
"answer_id": 181124,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 1,
"selected": false,
"text": "<asp:linkbutton id=\"lblMyLink\" onClick=\"lblMyLink_Click\" runat=\"server\" style=\"display:none;\">My Link</asp:linkbutton>\n<span onclick=\"document.getElementById('lblMyLink').click();\">My Label</span>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
181,106
|
<p>Is a new (or different) instance of <code>TestCase</code> object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests?</p>
<pre><code>public class MyTest extends TestCase {
public void testSomething() { ... }
public void testSomethingElse() { ... }
}
</code></pre>
<p>While running this test, how many instances of <code>MyTest</code> class is created?</p>
<p>If possible, provide a link to a document or source code where I can verify the behaviour.</p>
|
[
{
"answer_id": 181311,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 2,
"selected": false,
"text": "public class MyTest extends TestCase {\n public MyTest() { System.out.println(\"MyTest Constructor\");\n public void setUp() { System.out.println(\"MyTest setUp\");\n public void tearDown() { System.out.println(\"MyTest tearDown\");\n public void testSomething() { System.out.println(\"MyTest testSomething\");\n public void testSomethingElse() { System.out.println(\"MyTest testSomethingElse\");\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/181106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13326/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.