qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
55,860 |
<p>Okay, here is the 411 - I have the following event handler in my Global.asax.cs file:</p>
<pre><code>private void Global_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (/* logic that determines that this is an ajax call */)
{
// we want to set a cookie
Response.Cookies.Add(new HttpCookie("MyCookie", "true"));
}
}
</code></pre>
<p>That handler will run during Ajax requests (as a result of the Ajax framework I am using), as well as at other times - the condition of the if statement filters out non-Ajax events, and works just fine (it isn't relevant here, so I didn't include it for brevity's sake).</p>
<p>It suffices us to say that this works just fine - the cookie is set, I am able to read it on the client, and all is well up to that point.</p>
<p>Now for the part that drives me nuts.</p>
<p>Here is the JavaScript function I am using to delete the cookie:</p>
<pre><code>function deleteCookie(name) {
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime() - 1);
document.cookie = (name + "=; expires=" + cookieDate.toGMTString());
}
</code></pre>
<p>So, of course, at some point after the cookie is set, I delete it like so:</p>
<pre><code>deleteCookie("MyCookie");
</code></pre>
<p>Only, that doesn't do the job; the cookie still exists. So, anyone know why?</p>
|
[
{
"answer_id": 56261,
"author": "Erlend",
"author_id": 5746,
"author_profile": "https://Stackoverflow.com/users/5746",
"pm_score": 2,
"selected": false,
"text": ";expires=Thu, 01-Jan-1970 00:00:01 GMT"
},
{
"answer_id": 56740,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "var CookieUtil = {\n createCookie:function(name,value,days) {\n if (days) {\n var date = new Date();\n date.setTime(date.getTime()+(days*24*60*60*1000));\n var expires = \"; expires=\"+date.toGMTString();\n }\n else var expires = \"\";\n document.cookie = name+\"=\"+value+expires+\"; path=/\";\n },\n readCookie:function(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n },\n eraseCookie:function(name) {\n createCookie(name,\"\",-1);\n }\n};\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790/"
] |
55,869 |
<p>I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask).</p>
<p>What's the best way to determine the image format in .NET?</p>
<p>The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.</p>
|
[
{
"answer_id": 55879,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 3,
"selected": false,
"text": "file file man file /usr/share/file/magic man magic libmagic"
},
{
"answer_id": 55887,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "Image i = Image.FromFile(\"c:\\\\foo\");\nif (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) \n MessageBox.Show(\"JPEG\");\nelse if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat))\n MessageBox.Show(\"GIF\");\n//Same for the rest of the formats\n"
},
{
"answer_id": 12051761,
"author": "slobodans",
"author_id": 946580,
"author_profile": "https://Stackoverflow.com/users/946580",
"pm_score": 2,
"selected": false,
"text": "static Dictionary<Guid, string> GetImageFormatMimeTypeIndex()\n{\n Dictionary<Guid, string> ret = new Dictionary<Guid, string>();\n\n var encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();\n\n foreach(var e in encoders)\n {\n ret.Add(e.FormatID, e.MimeType);\n }\n\n return ret;\n}\n Dictionary<Guid, string> mimeTypeIndex = GetImageFormatMimeTypeIndex();\n\nFileStream imgStream = File.OpenRead(path);\nvar image = System.Drawing.Image.FromStream(imgStream);\nstring mimeType = mimeTypeIndex[image.RawFormat.Guid];\n"
},
{
"answer_id": 12451102,
"author": "Ivan Kochurkin",
"author_id": 1046374,
"author_profile": "https://Stackoverflow.com/users/1046374",
"pm_score": 5,
"selected": false,
"text": "public enum ImageFormat\n{\n bmp,\n jpeg,\n gif,\n tiff,\n png,\n unknown\n}\n\npublic static ImageFormat GetImageFormat(Stream stream)\n{\n // see http://www.mikekunz.com/image_file_header.html\n var bmp = Encoding.ASCII.GetBytes(\"BM\"); // BMP\n var gif = Encoding.ASCII.GetBytes(\"GIF\"); // GIF\n var png = new byte[] { 137, 80, 78, 71 }; // PNG\n var tiff = new byte[] { 73, 73, 42 }; // TIFF\n var tiff2 = new byte[] { 77, 77, 42 }; // TIFF\n var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg\n var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon\n\n var buffer = new byte[4];\n stream.Read(buffer, 0, buffer.Length);\n\n if (bmp.SequenceEqual(buffer.Take(bmp.Length)))\n return ImageFormat.bmp;\n\n if (gif.SequenceEqual(buffer.Take(gif.Length)))\n return ImageFormat.gif;\n\n if (png.SequenceEqual(buffer.Take(png.Length)))\n return ImageFormat.png;\n\n if (tiff.SequenceEqual(buffer.Take(tiff.Length)))\n return ImageFormat.tiff;\n\n if (tiff2.SequenceEqual(buffer.Take(tiff2.Length)))\n return ImageFormat.tiff;\n\n if (jpeg.SequenceEqual(buffer.Take(jpeg.Length)))\n return ImageFormat.jpeg;\n\n if (jpeg2.SequenceEqual(buffer.Take(jpeg2.Length)))\n return ImageFormat.jpeg;\n\n return ImageFormat.unknown;\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5277/"
] |
55,871 |
<p>Is it possible to detect when the user clicks on the browser's back button?</p>
<p>I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back</p>
<p>Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript</p>
<h3>Edit: Cut and paste from below:</h3>
<p>Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libraries and don't want to add more ajax libraries. But it uses <em>iFrames</em> which gives me a good pointer to write my own code.</p>
|
[
{
"answer_id": 33439550,
"author": "Jeffrey Harmon",
"author_id": 555329,
"author_profile": "https://Stackoverflow.com/users/555329",
"pm_score": 2,
"selected": false,
"text": "<input type=\"hidden\" id=\"needs-refresh\" value=\"no\">\n<script>\n onload=function(){\n var e = document.getElementById(\"needs-refresh\");\n if (e.value === \"yes\")\n location.reload();\n e.value = \"yes\";\n }\n</script>\n"
},
{
"answer_id": 34309128,
"author": "Drew Shardlow",
"author_id": 5686050,
"author_profile": "https://Stackoverflow.com/users/5686050",
"pm_score": 2,
"selected": false,
"text": "$wasPosted $_SESSION false $wasPosted true header(location:) $wasPosted true $wasPosted false"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3983/"
] |
55,899 |
<p>I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!)</p>
<p>I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. </p>
<p>It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?).</p>
<p>So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report.</p>
|
[
{
"answer_id": 55914,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 6,
"selected": true,
"text": "and TABLETYPE=’:b16’\n and TABLETYPE=’MT’\n SELECT \n module, \n sql_text, \n username, \n disk_reads_per_exec, \n buffer_gets, \n disk_reads, \n parse_calls, \n sorts, \n executions, \n rows_processed, \n hit_ratio, \n first_load_time, \n sharable_mem, \n persistent_mem, \n runtime_mem, \n cpu_time, \n elapsed_time, \n address, \n hash_value \nFROM \n (SELECT\n module, \n sql_text , \n u.username , \n round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec, \n s.disk_reads , \n s.buffer_gets , \n s.parse_calls , \n s.sorts , \n s.executions , \n s.rows_processed , \n 100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, \n s.first_load_time , \n sharable_mem , \n persistent_mem , \n runtime_mem, \n cpu_time, \n elapsed_time, \n address, \n hash_value \n FROM\n sys.v_$sql s, \n sys.all_users u \n WHERE\n s.parsing_user_id=u.user_id \n and UPPER(u.username) not in ('SYS','SYSTEM') \n ORDER BY\n 4 desc) \nWHERE\n rownum <= 20;\n SELECT\n *\nFROM\n sys.v_$sqltext\nWHERE\n address = 'C0000000372B3C28'\n and hash_value = '1272580459'\nORDER BY \n address, hash_value, command_type, piece\n;\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/480/"
] |
55,901 |
<p>Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand? </p>
<p>I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time.</p>
|
[
{
"answer_id": 14988400,
"author": "Mike Davis",
"author_id": 641879,
"author_profile": "https://Stackoverflow.com/users/641879",
"pm_score": 6,
"selected": false,
"text": "\"location\": {\n \"lat\": 37.77492950,\n \"lng\": -122.41941550\n}\n {\n \"status\": \"OK\",\n \"dstOffset\": 0.0,\n \"rawOffset\": -28800.0, \n \"timeZoneId\": \"America/Los_Angeles\",\n \"timeZoneName\": \"Pacific Standard Time\"\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808/"
] |
55,956 |
<p>is there an alternative for <code>mysql_insert_id()</code> php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....</p>
|
[
{
"answer_id": 55959,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO table (col1, col2) VALUES (1, 2) RETURNING pkey_col\n"
},
{
"answer_id": 56055,
"author": "Vertigo",
"author_id": 5468,
"author_profile": "https://Stackoverflow.com/users/5468",
"pm_score": 2,
"selected": false,
"text": "$res=pg_query(\"SELECT nextval('foo_key_seq') as key\");\n$row=pg_fetch_array($res, 0);\n$key=$row['key'];\n// now we have the serial value in $key, let's do the insert\npg_query(\"INSERT INTO foo (key, foo) VALUES ($key, 'blah blah')\");\n"
},
{
"answer_id": 56133,
"author": "angch",
"author_id": 5386,
"author_profile": "https://Stackoverflow.com/users/5386",
"pm_score": 6,
"selected": true,
"text": " * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2. \n\n * INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1\n\n * $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL)\n pg_last_oid() // yes, we're not using pg_insert()\n$result = pg_query($db, \"INSERT INTO foo (bar) VALUES (123) RETURNING foo_id\");\n$insert_row = pg_fetch_row($result);\n$insert_id = $insert_row[0];\n $result = pg_execute($db, \"INSERT INTO foo (bar) values (123);\");\n$insert_query = pg_query(\"SELECT lastval();\");\n$insert_row = pg_fetch_row($insert_query);\n$insert_id = $insert_row[0];\n $insert_query = pg_query($db, \"SELECT nextval('foo_seq');\");\n$insert_row = pg_fetch_row($insert_query);\n$insert_id = $insert_row[0];\n$result = pg_execute($db, \"INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);\");\n"
},
{
"answer_id": 5863620,
"author": "Jenaro",
"author_id": 634605,
"author_profile": "https://Stackoverflow.com/users/634605",
"pm_score": 2,
"selected": false,
"text": "$result = pg_query($db, \"INSERT INTO foo (bar) VALUES (123) RETURNING foo_id\");\n$insert_row = pg_fetch_result($result, 0, 'foo_id');\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742/"
] |
55,964 |
<p>How can I make a major upgrade to an installation set (MSI) built with <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> install into the same folder as the original installation?</p>
<p>The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder).</p>
<p>Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example?</p>
<p>Or is there some easier way to achieve this in <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="noreferrer">MSI</a> or WiX?</p>
<p>As reference, I my current WiX file is below:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi">
<Product Id="a2298d1d-ba60-4c4d-92e3-a77413f54a53"
Name="MyCompany Integration Framework 1.0.0"
Language="1033"
Version="1.0.0"
Manufacturer="MyCompany"
UpgradeCode="9071eacc-9b5a-48e3-bb90-8064d2b2c45d">
<!-- Package information -->
<Package Keywords="Installer"
Id="e85e6190-1cd4-49f5-8924-9da5fcb8aee8"
Description="Installs MyCompany Integration Framework 1.0.0"
Comments="Installs MyCompany Integration Framework 1.0.0"
InstallerVersion="100"
Compressed="yes" />
<Upgrade Id='9071eacc-9b5a-48e3-bb90-8064d2b2c45d'>
<UpgradeVersion Property="PATCHFOUND"
OnlyDetect="no"
Minimum="0.0.1"
IncludeMinimum="yes"
Maximum="1.0.0"
IncludeMaximum="yes"/>
</Upgrade>
<!-- Useless but necessary... -->
<Media Id="1" Cabinet="MyCompany.cab" EmbedCab="yes" />
<!-- Precondition: .NET 2 must be installed -->
<Condition Message='This setup requires the .NET Framework 2 or higher.'>
<![CDATA[MsiNetAssemblySupport >= "2.0.50727"]]>
</Condition>
<Directory Id="TARGETDIR"
Name="SourceDir">
<Directory Id="MyCompany"
Name="MyCompany">
<Directory Id="INSTALLDIR"
Name="Integrat"
LongName="MyCompany Integration Framework">
<Component Id="MyCompanyDllComponent"
Guid="4f362043-03a0-472d-a84f-896522ce7d2b"
DiskId="1">
<File Id="MyCompanyIntegrationDll"
Name="IbIntegr.dll"
src="..\Build\MyCompany.Integration.dll"
Vital="yes"
LongName="MyCompany.Integration.dll" />
<File Id="MyCompanyServiceModelDll"
Name="IbSerMod.dll"
src="..\Build\MyCompany.ServiceModel.dll"
Vital="yes"
LongName="MyCompany.ServiceModel.dll" />
</Component>
<!-- More components -->
</Directory>
</Directory>
</Directory>
<Feature Id="MyCompanyProductFeature"
Title='MyCompany Integration Framework'
Description='The complete package'
Display='expand'
Level="1"
InstallDefault='local'
ConfigurableDirectory="INSTALLDIR">
<ComponentRef Id="MyCompanyDllComponent" />
</Feature>
<!-- Task scheduler application. It has to be used as a property -->
<Property Id="finaltaskexe"
Value="MyCompany.Integration.Host.exe" />
<Property Id="WIXUI_INSTALLDIR"
Value="INSTALLDIR" />
<InstallExecuteSequence>
<!-- command must be executed: MyCompany.Integration.Host.exe /INITIALCONFIG parameters.xml -->
<Custom Action='PropertyAssign'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<Custom Action='LaunchFile'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<RemoveExistingProducts Before='CostInitialize' />
</InstallExecuteSequence>
<!-- execute comand -->
<CustomAction Id='PropertyAssign'
Property='PathProperty'
Value='[INSTALLDIR][finaltaskexe]' />
<CustomAction Id='LaunchFile'
Property='PathProperty'
ExeCommand='/INITIALCONFIG "[INSTALLDIR]parameters.xml"'
Return='asyncNoWait' />
<!-- User interface information -->
<UIRef Id="WixUI_InstallDir" />
<UIRef Id="WixUI_ErrorProgressText" />
</Product>
</Wix>
</code></pre>
|
[
{
"answer_id": 56123,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 6,
"selected": true,
"text": "<Property Id=\"INSTALLDIR\">\n <RegistrySearch Id='AcmeFoobarRegistry' Type='raw'\n Root='HKLM' Key='Software\\Acme\\Foobar 1.0' Name='InstallDir' />\n</Property>\n <RegistryKey\n Key=\"Software\\Software\\Acme\\Foobar 1.0\"\n Root=\"HKLM\">\n <RegistryValue Id=\"FoobarRegInstallDir\"\n Type=\"string\"\n Name=\"InstallDir\"\n Value=\"[INSTALLDIR]\" />\n</RegistryKey> \n"
},
{
"answer_id": 8894372,
"author": "Serge SB",
"author_id": 1153863,
"author_profile": "https://Stackoverflow.com/users/1153863",
"pm_score": 3,
"selected": false,
"text": "<RegistryKey Id=\"FoobarRegRoot\"\n Action=\"createAndRemoveOnUninstall\"\n Key=\"Software\\Software\\Acme\\Foobar 1.0\"\n Root=\"HKLM\">\n <RegistryValue Id=\"FoobarRegInstallDir\"\n Type=\"string\"\n Name=\"InstallDir\"\n Value=\"[INSTALLDIR]\" />\n</RegistryKey>\n"
},
{
"answer_id": 23121035,
"author": "Jamie",
"author_id": 645431,
"author_profile": "https://Stackoverflow.com/users/645431",
"pm_score": 2,
"selected": false,
"text": "<RegistryValue\n Root=\"HKMU\"\n Key=\"Software\\[Manufacturer]\\[ProductName]\"\n Name=\"InstallDir\"\n Type=\"string\"\n Value=\"[INSTALLDIR]\"\n KeyPath=\"yes\" />\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4683/"
] |
55,978 |
<p>I know how to test an object to see if it is of a type, using the IS keyword e.g.</p>
<pre><code>if (foo is bar)
{
//do something here
}
</code></pre>
<p>but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result. </p>
<p>BTW - I have a horrible feeling this is soooo obvious, so apologies in advance...</p>
|
[
{
"answer_id": 55980,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "if (!(foo is bar)) {\n}\n"
},
{
"answer_id": 55981,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "if (!(foo is bar)) ...\nif (foo.GetType() != bar.GetType()) .. // foo & bar should be on the same level of type hierarchy\n"
},
{
"answer_id": 55991,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "bar aBar = foo as bar; // aBar is null if foo is not bar\n"
},
{
"answer_id": 85100,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 1,
"selected": false,
"text": "public class Foo : Bar {}\n Foo foo = new Foo();\n if(!(foo.GetType() == tyepof(Bar))) {...}\n Bar bar = foo as Bar;\nif(bar == null) {/* foo is not a bar */}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
55,984 |
<p>What is the difference between <strong><code>const</code></strong> and <strong><code>readonly</code></strong> in C#? </p>
<p>When would you use one over the other?</p>
|
[
{
"answer_id": 55987,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 4,
"selected": false,
"text": "const readonly"
},
{
"answer_id": 56024,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 12,
"selected": true,
"text": "const readonly const static ClassName.ConstantName AssemblyA public class Const_V_Readonly\n{\n public const int I_CONST_VALUE = 2;\n public readonly int I_RO_VALUE;\n public Const_V_Readonly()\n {\n I_RO_VALUE = 3;\n }\n}\n AssemblyB AssemblyA const AssemblyB I_CONST_VALUE AssemblyB readonly ref AssemblyB AssemblyB I_RO_VALUE AssemblyA const public const int CM_IN_A_METER = 100;\n readonly public readonly float PI = 3.14;\n"
},
{
"answer_id": 56233,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "readonly public class Const_V_Readonly\n{\n public const int I_CONST_VALUE = 2;\n public readonly char[] I_RO_VALUE = new Char[]{'a', 'b', 'c'};\n\n public UpdateReadonly()\n {\n I_RO_VALUE[0] = 'V'; //perfectly legal and will update the value\n I_RO_VALUE = new char[]{'V'}; //will cause compiler error\n }\n}\n"
},
{
"answer_id": 82893,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 3,
"selected": false,
"text": "public static class Text {\n public const string ConstDescription = \"This can be used.\";\n public readonly static string ReadonlyDescription = \"Cannot be used.\";\n}\n\npublic class Foo \n{\n [Description(Text.ConstDescription)]\n public int BarThatBuilds {\n { get; set; }\n }\n\n [Description(Text.ReadOnlyDescription)]\n public int BarThatDoesNotBuild {\n { get; set; }\n }\n}\n"
},
{
"answer_id": 217058,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 5,
"selected": false,
"text": "public class Sample {\n private readonly string ro;\n\n public Sample() {\n ro = \"set\";\n }\n\n public Sample(string value) : this() {\n ro = value; // this works even though it was set in the no-arg ctor\n }\n}\n"
},
{
"answer_id": 1557937,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 4,
"selected": false,
"text": "var fi = this.GetType()\n .BaseType\n .GetField(\"_someField\", \n BindingFlags.Instance | BindingFlags.NonPublic);\nfi.SetValue(this, 1);\n"
},
{
"answer_id": 5057030,
"author": "Greg",
"author_id": 431780,
"author_profile": "https://Stackoverflow.com/users/431780",
"pm_score": 2,
"selected": false,
"text": "const readonly"
},
{
"answer_id": 6082004,
"author": "Deepthi",
"author_id": 763996,
"author_profile": "https://Stackoverflow.com/users/763996",
"pm_score": 6,
"selected": false,
"text": "const readonly"
},
{
"answer_id": 12458557,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 5,
"selected": false,
"text": "const public class MyClass\n{\n public const double PI1 = 3.14159;\n}\n readonly readonly public class MyClass1\n{\n public readonly double PI2 = 3.14159;\n\n //or\n\n public readonly double PI3;\n\n public MyClass2()\n {\n PI3 = 3.14159;\n }\n}\n static"
},
{
"answer_id": 19064906,
"author": "Ramesh Rajendran",
"author_id": 2218635,
"author_profile": "https://Stackoverflow.com/users/2218635",
"pm_score": 2,
"selected": false,
"text": "struct Test\n{\n public const double Pi = 3.14;\n public const int Zero = 0;\n}\n public class Color\n{\n public static Color Black = new Color(0, 0, 0);\n public static Color White = new Color(255, 255, 255);\n public static Color Red = new Color(255, 0, 0);\n public static Color Green = new Color(0, 255, 0);\n public static Color Blue = new Color(0, 0, 255);\n private byte red, green, blue;\n\n public Color(byte r, byte g, byte b) {\n red = r;\n green = g;\n blue = b;\n }\n}\n public class Color\n{\n public static readonly Color Black = new Color(0, 0, 0);\n public static readonly Color White = new Color(255, 255, 255);\n public static readonly Color Red = new Color(255, 0, 0);\n public static readonly Color Green = new Color(0, 255, 0);\n public static readonly Color Blue = new Color(0, 0, 255);\n private byte red, green, blue;\n\n public Color(byte r, byte g, byte b) {\n red = r;\n green = g;\n blue = b;\n }\n}\n public class A\n{\n public static const C = 0;\n}\n public class B\n{\n static void Main() {\n Console.WriteLine(A.C);\n }\n}\n"
},
{
"answer_id": 27484700,
"author": "Chirag",
"author_id": 2004144,
"author_profile": "https://Stackoverflow.com/users/2004144",
"pm_score": 3,
"selected": false,
"text": "public const DateTime dt = DateTime.Today; //throws compilation error\npublic const string Name = string.Empty; //throws compilation error\npublic readonly string Name = string.Empty; //No error, legal\n class A\n{\n public readonly int Id;\n\n public A(int i)\n {\n Id = i;\n }\n}\n A objOne = new A(5);\nA objTwo = new A(10);\n"
},
{
"answer_id": 56450673,
"author": "Ryan Efendy",
"author_id": 5265992,
"author_profile": "https://Stackoverflow.com/users/5265992",
"pm_score": 3,
"selected": false,
"text": "const readonly const readonly App.config"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
56,011 |
<p>According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?</p>
|
[
{
"answer_id": 56041,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 5,
"selected": false,
"text": "\"You're able to do this\" 'He said \"Hi!\"' '' \"\" \" ' \"\"\"these\"\"\" '''these'''"
},
{
"answer_id": 56073,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 7,
"selected": false,
"text": "' '''docstrings''' \"\"\"this creates some fluff\"\"\" ' \"\"\"docstrings\"\"\""
},
{
"answer_id": 56190,
"author": "Will Harris",
"author_id": 4702,
"author_profile": "https://Stackoverflow.com/users/4702",
"pm_score": 10,
"selected": true,
"text": "LIGHT_MESSAGES = {\n 'English': \"There are %(number_of_lights)s lights.\",\n 'Pirate': \"Arr! Thar be %(number_of_lights)s lights.\"\n}\n\ndef lights_message(language, number_of_lights):\n \"\"\"Return a language-appropriate string reporting the light count.\"\"\"\n return LIGHT_MESSAGES[language] % locals()\n\ndef is_pirate(message):\n \"\"\"Return True if the given message sounds piratical.\"\"\"\n return re.search(r\"(?i)(arr|avast|yohoho)!\", message) is not None\n"
},
{
"answer_id": 2091077,
"author": "kn3l",
"author_id": 128618,
"author_profile": "https://Stackoverflow.com/users/128618",
"pm_score": -1,
"selected": false,
"text": "' \" / \\ \\\\ f = open('c:\\word.txt', 'r')\nf = open(\"c:\\word.txt\", \"r\")\nf = open(\"c:/word.txt\", \"r\")\nf = open(\"c:\\\\\\word.txt\", \"r\")\n \\k \\w \\t \\n \\\\ \\\" r im_raw = r'c:\\temp.txt'\nnon_raw = 'c:\\\\temp.txt'\nanother_way = 'c:/temp.txt'\n"
},
{
"answer_id": 4776742,
"author": "Michael",
"author_id": 584811,
"author_profile": "https://Stackoverflow.com/users/584811",
"pm_score": 3,
"selected": false,
"text": "mystringliteral1=\"this is a string with 'quotes'\"\nmystringliteral2='this is a string with \"quotes\"'\nmystringliteral3=\"\"\"this is a string with \"quotes\" and more 'quotes'\"\"\"\nmystringliteral4='''this is a string with 'quotes' and more \"quotes\"'''\nmystringliteral5='this is a string with \\\"quotes\\\"'\nmystringliteral6='this is a string with \\042quotes\\042'\nmystringliteral6='this is a string with \\047quotes\\047'\n\nprint mystringliteral1\nprint mystringliteral2\nprint mystringliteral3\nprint mystringliteral4\nprint mystringliteral5\nprint mystringliteral6\n this is a string with 'quotes'\nthis is a string with \"quotes\"\nthis is a string with \"quotes\" and more 'quotes'\nthis is a string with 'quotes' and more \"quotes\"\nthis is a string with \"quotes\"\nthis is a string with 'quotes'\n"
},
{
"answer_id": 7514799,
"author": "yurisich",
"author_id": 881224,
"author_profile": "https://Stackoverflow.com/users/881224",
"pm_score": 4,
"selected": false,
"text": "\"If you're going to use apostrophes, \n ^\n\nyou'll definitely want to use double quotes\".\n ^\n"
},
{
"answer_id": 16048319,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 0,
"selected": false,
"text": "' \" \"\"\" ''' \" ' \" A B C AA BB CC"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
56,037 |
<p>I am working with fixtures on rails and I want one of the fixture fields to be blank.</p>
<p>Example:</p>
<pre><code>two:
name: test
path: - I want this blank but not to act as a group heading.
test: 4
</code></pre>
<p>But, I do not know how to leave <code>path:</code> blank without it acting as a group title. Does anybody know how to do that?</p>
|
[
{
"answer_id": 56060,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": 1,
"selected": false,
"text": "path: \\\"\\\"\n"
},
{
"answer_id": 56519,
"author": "Tom",
"author_id": 4753,
"author_profile": "https://Stackoverflow.com/users/4753",
"pm_score": 4,
"selected": true,
"text": "\ntwo:\n name: test\n path: \n test: 4\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
56,045 |
<p>I'm having some internationalisation woes:</p>
<p>My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database.</p>
<p>After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger.</p>
<p>However Struts2/Tiles is rendering these strings as ???? in the HTML sent to the browser.</p>
<p>The charset directive is present in the HTML header:
</p>
<p>Perhaps I need to add something to my struts2 or tiles configurations?</p>
|
[
{
"answer_id": 56626,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 1,
"selected": true,
"text": "<%@ page contentType=\"text/html; charset=UTF-8\" %>\n"
},
{
"answer_id": 78724,
"author": "chickeninabiscuit",
"author_id": 3966,
"author_profile": "https://Stackoverflow.com/users/3966",
"pm_score": 1,
"selected": false,
"text": "<%@ page contentType=\"text/html; charset=UTF-8\" %> TilesDispatchExtensionServlet"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3966/"
] |
56,052 |
<p>EditPad Lite has a nice feature (<kbd>CTRL</kbd>-<kbd>E</kbd>, <kbd>CTRL</kbd>-<kbd>I</kbd>) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code.</p>
<p>What is the best way to get this functionality in Vim?</p>
<p>(I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.)</p>
|
[
{
"answer_id": 56061,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 8,
"selected": true,
"text": ":r! date\n Thu Sep 11 10:47:30 CEST 2008\n :r! date \"+\\%Y-\\%m-\\%d \\%H:\\%M:\\%S\"\n 2008-09-11 10:50:56\n"
},
{
"answer_id": 56064,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": ":map <F3> :r! date +\"\\%Y-\\%m-\\%d \\%H:\\%M:\\%S\"<cr>\n <F3> \n"
},
{
"answer_id": 56069,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 2,
"selected": false,
"text": "\nmap <F12> :r! date +\\%s<cr>\n"
},
{
"answer_id": 58604,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 7,
"selected": false,
"text": "vimrc nmap <F3> i<C-R>=strftime(\"%Y-%m-%d %a %I:%M %p\")<CR><Esc>\nimap <F3> <C-R>=strftime(\"%Y-%m-%d %a %I:%M %p\")<CR>\n 2016-01-25 Mo 12:44"
},
{
"answer_id": 2979150,
"author": "intuited",
"author_id": 192812,
"author_profile": "https://Stackoverflow.com/users/192812",
"pm_score": 3,
"selected": false,
"text": "^R=strftime(\"%FT%T%z\")\n :r !date --rfc-3339=s\n ns s tr ' ' T :source somefile.vim\n somefile.vim"
},
{
"answer_id": 7681121,
"author": "luser droog",
"author_id": 733077,
"author_profile": "https://Stackoverflow.com/users/733077",
"pm_score": 4,
"selected": false,
"text": ":r! !!date"
},
{
"answer_id": 22578234,
"author": "user3449771",
"author_id": 3449771,
"author_profile": "https://Stackoverflow.com/users/3449771",
"pm_score": 3,
"selected": false,
"text": ":iab <expr> tds strftime(\"%F %b %T\")\n %b %F %Y%m%d"
},
{
"answer_id": 24840035,
"author": "byte-pirate",
"author_id": 1637043,
"author_profile": "https://Stackoverflow.com/users/1637043",
"pm_score": 3,
"selected": false,
"text": "!!date\n !!date /t\n"
},
{
"answer_id": 57789091,
"author": "luator",
"author_id": 2095383,
"author_profile": "https://Stackoverflow.com/users/2095383",
"pm_score": 2,
"selected": false,
"text": ":Date r!date command Date execute \"normal i<C-R>=strftime('%F %T')<CR><ESC>\"\n normal a"
},
{
"answer_id": 66021073,
"author": "mmrtnt",
"author_id": 9302794,
"author_profile": "https://Stackoverflow.com/users/9302794",
"pm_score": 1,
"selected": false,
"text": "map T :r! date +\"\\%m/\\%d/\\%Y \\%H:\\%M\" <CR>\"kkddo<CR>\n map T \"=strftime(\"%m/%d/%y %H:%M\")<CR>po<CR>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
56,078 |
<p>I got a Function that returns a <code>Collection<string></code>, and that calls itself recursively to eventually return one big <code>Collection<string></code>.</p>
<p>Now, i just wonder what the best approach to merge the lists? <code>Collection.CopyTo()</code> only copies to string[], and using a <code>foreach()</code> loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls <code>Contains()</code> on the <code>Collection</code>.</p>
<p>I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a <code>Collection</code>, it can be pretty much any suitable data type.</p>
<p>Only exclusion, I'm bound to Visual Studio 2005 and .net 3.0, so no LINQ.</p>
<p><strong>Edit:</strong> To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching.</p>
|
[
{
"answer_id": 56092,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "HashSet<T> HashSet<T> HashSet<T> Dictionary<TKey, TValue>"
},
{
"answer_id": 56100,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 5,
"selected": true,
"text": "public IEnumerable<string> Combine(IEnumerable<string> col1, IEnumerable<string> col2)\n{\n foreach(string item in col1)\n yield return item;\n\n foreach(string item in col2)\n yield return item;\n}\n"
},
{
"answer_id": 56108,
"author": "Matthew M. Osborn",
"author_id": 5235,
"author_profile": "https://Stackoverflow.com/users/5235",
"pm_score": 1,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n Collection<string> myitems = new Collection<string>();\n myMthod(ref myitems);\n Console.WriteLine(myitems.Count.ToString());\n Console.ReadLine();\n }\n\n static void myMthod(ref Collection<string> myitems)\n {\n myitems.Add(\"string\");\n if(myitems.Count <5)\n myMthod(ref myitems);\n }\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
56,087 |
<p>I know about the "cooperative" threading of ruby using <a href="http://en.wikipedia.org/wiki/Green_threads" rel="noreferrer">green threads</a>. How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing?</p>
|
[
{
"answer_id": 57802,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 10,
"selected": true,
"text": "Process Process.fork"
},
{
"answer_id": 21531941,
"author": "user454322",
"author_id": 454322,
"author_profile": "https://Stackoverflow.com/users/454322",
"pm_score": 3,
"selected": false,
"text": "Blocks lambdas Procs (jalcazar@mac ~)$ ps -M 69877\nUSER PID TT %CPU STAT PRI STIME UTIME COMMAND\njalcazar 69877 s002 0.0 S 31T 0:00.01 0:00.04 /Users/jalcazar/.rvm/rubies/ruby-2.1.0/bin/ruby threads.rb\n 69877 0.0 S 31T 0:00.01 0:00.00 \n 69877 33.4 S 31T 0:00.01 0:08.73 \n 69877 43.1 S 31T 0:00.01 0:08.73 \n 69877 22.8 R 31T 0:00.01 0:08.65 \n R R (jalcazar@mac ~)$ ps -M 72286\nUSER PID TT %CPU STAT PRI STIME UTIME COMMAND\njalcazar 72286 s002 0.0 S 31T 0:00.01 0:00.01 /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java -Djdk.home= -Djruby.home=/Users/jalcazar/.rvm/rubies/jruby-1.7.10 -Djruby.script=jruby -Djruby.shell=/bin/sh -Djffi.boot.library.path=/Users/jalcazar/.rvm/rubies/jruby-1.7.10/lib/jni:/Users/jalcazar/.rvm/rubies/jruby-1.7.10/lib/jni/Darwin -Xss2048k -Dsun.java.command=org.jruby.Main -cp -Xbootclasspath/a:/Users/jalcazar/.rvm/rubies/jruby-1.7.10/lib/jruby.jar -Xmx1924M -XX:PermSize=992m -Dfile.encoding=UTF-8 org/jruby/Main threads.rb\n 72286 0.0 S 31T 0:00.00 0:00.00 \n 72286 0.0 S 33T 0:00.00 0:00.00 \n 72286 0.0 S 31T 0:00.09 0:02.34 \n 72286 7.9 S 31T 0:00.15 0:04.63 \n 72286 0.0 S 31T 0:00.00 0:00.00 \n 72286 0.0 S 31T 0:00.00 0:00.00 \n 72286 0.0 S 31T 0:00.00 0:00.00 \n 72286 0.0 S 31T 0:00.04 0:01.68 \n 72286 0.0 S 31T 0:00.03 0:01.54 \n 72286 0.0 S 31T 0:00.00 0:00.00 \n 72286 0.0 S 31T 0:00.01 0:00.01 \n 72286 0.0 S 31T 0:00.00 0:00.01 \n 72286 0.0 S 31T 0:00.00 0:00.03 \n 72286 74.2 R 31T 0:09.21 0:37.73 \n 72286 72.4 R 31T 0:09.24 0:37.71 \n 72286 74.7 R 31T 0:09.24 0:37.80 \n (jalcazar@mac ~)$ ps -M 38293\nUSER PID TT %CPU STAT PRI STIME UTIME COMMAND\njalcazar 38293 s002 0.0 R 0T 0:00.02 0:00.10 /Users/jalcazar/.rvm/rubies/macruby-0.12/usr/bin/macruby threads.rb\n 38293 0.0 S 33T 0:00.00 0:00.00 \n 38293 100.0 R 31T 0:00.04 0:21.92 \n 38293 100.0 R 31T 0:00.04 0:21.95 \n 38293 100.0 R 31T 0:00.04 0:21.99 \n (jalcazar@mac ~)$ ps -M 70032\nUSER PID TT %CPU STAT PRI STIME UTIME COMMAND\njalcazar 70032 s002 100.0 R 31T 0:00.08 0:26.62 /Users/jalcazar/.rvm/rubies/ruby-1.8.7-p374/bin/ruby threads.rb\n"
},
{
"answer_id": 28664487,
"author": "GroovyCakes",
"author_id": 736524,
"author_profile": "https://Stackoverflow.com/users/736524",
"pm_score": 2,
"selected": false,
"text": "def eratosthenes(n)\n nums = [nil, nil, *2..n]\n (2..Math.sqrt(n)).each do |i|\n (i**2..n).step(i){|m| nums[m] = nil} if nums[i]\n end\n nums.compact\nend\n\nMAX_PRIME=10000000\nTHREADS=8\nthreads = []\n\n1.upto(THREADS) do |num|\n puts \"Starting thread #{num}\"\n threads[num]=Thread.new { eratosthenes MAX_PRIME }\nend\n\n1.upto(THREADS) do |num|\n threads[num].join\nend\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] |
56,091 |
<p>Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following:</p>
<pre><code>class MyClass
{
protected:
bool CaseMethod1( int abc, const std::string& str )
{
cout << "case 1:" << str;
return true;
}
bool CaseMethod2( int abc, const std::string& str )
{
cout << "case 2:" << str;
return true;
}
bool CaseMethod3( int abc, const std::string& str )
{
cout << "case 3:" << str;
return true;
}
public:
bool TestSwitch( int num )
{
bool ( MyClass::*CaseMethod )( int, const std::string& );
switch ( num )
{
case 1: CaseMethod = &MyClass::CaseMethod1;
break;
case 2: CaseMethod = &MyClass::CaseMethod2;
break;
case 3: CaseMethod = &MyClass::CaseMethod3;
break;
}
...
bool res = CaseMethod( 999, "hello world" );
...
reurn res;
}
};
</code></pre>
<p>My question is - <strong>is this the correct way to go about this?</strong> Should I consider anything that <em>Boost</em> has to offer?</p>
<p>Edit...</p>
<p>Ok, my mistake - I should be calling the method like so:</p>
<pre><code>bool res = ( (*this).*CaseMethod )( 999, "Hello World" );
</code></pre>
|
[
{
"answer_id": 56101,
"author": "Paulius",
"author_id": 1353085,
"author_profile": "https://Stackoverflow.com/users/1353085",
"pm_score": 1,
"selected": false,
"text": "bool res = this->*CaseMethod( 999, \"hello world\" );\n"
},
{
"answer_id": 56111,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 4,
"selected": true,
"text": "bool res = (this->*CaseMethod)( 999, \"hello world\" );\n boost::function<bool(int,std::string)> f=\n boost::bind(&MyClass::CaseMethod1,this,_1,_2);\n this this boost::function<bool(MyClass*,int,std::string)> f=\n boost::bind(&MyClass::CaseMethod1,_1,_2,_3);\n"
},
{
"answer_id": 57045,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 2,
"selected": false,
"text": "this->*Methods[num]( 999, \"hello world\" );\n"
},
{
"answer_id": 58798,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 0,
"selected": false,
"text": "class Base { virtual bool Method(int i, const string& s) = 0; };\n class Case1 : public Base { virtual bool Method(..) { /* implement */; } };\n Base* CreateBase(int which_num) { /* metacode: return new Case[which_num]; */ }\n// ... later, when you want to actually call your method ...\nBase* base = CreateBase(23);\nbase->Method(999, \"hello world!\");\ndelete base; // Or use a scoped pointer.\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2958/"
] |
56,096 |
<p>I have a project which is source controlled using Subversion and VisualSVN. Since the version of web.config is different on the server and the developers' computers I want the file to remain on the computers but to be ignored by Subversion. I added it to the svn:ignore but it still remains (and still has a red exclamation mark too since we are not committing it).</p>
<p>How can I remove it from Subversion safely without it being deleted from the files system</p>
<p>Thanks,
Adin</p>
|
[
{
"answer_id": 56142,
"author": "ibz",
"author_id": 5475,
"author_profile": "https://Stackoverflow.com/users/5475",
"pm_score": 1,
"selected": false,
"text": "svn rm --force web.config\nsvn commit\n"
},
{
"answer_id": 2685099,
"author": "Gökhan Ercan",
"author_id": 7751,
"author_profile": "https://Stackoverflow.com/users/7751",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\"?>\n <project name=\"Project1\" default=\"build\">\n <target name=\"init\" depends=\"clean\" />\n <target name=\"clean\" />\n <target name=\"checkout\"/>\n <target name=\"compile\"/>\n <target name=\"deploy\"/>\n <target name=\"test\"/>\n <target name=\"inspect\"/>\n <target name=\"build\" depends=\"init, checkout\">\n <call target=\"compile\" />\n <call target=\"inspect\" />\n <call target=\"test\" />\n <call target=\"deploy\" />\n </target>\n\n <copy file=\"..\\TestDeployments\\Project1\\Project1.Solution\\Project1.Web.UI\\web.Test.config\" \n tofile=\"..\\TestDeployments\\Project1\\Project1.Solution\\Project1.Web.UI\\web.config\" \n overwrite=\"true\" \n />\n <delete file=\"..\\TestDeployments\\Project1\\Project1.Solution\\Project1.Web.UI\\web.Test.config\" />\n\n </project>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5754/"
] |
56,107 |
<p>I'm looking for a library/method to parse an html file with more html specific features than generic xml parsing libraries.</p>
|
[
{
"answer_id": 56228,
"author": "Erlend",
"author_id": 5746,
"author_profile": "https://Stackoverflow.com/users/5746",
"pm_score": 5,
"selected": false,
"text": "using mshtml;\n...\nobject[] oPageText = { html };\nHTMLDocument doc = new HTMLDocumentClass();\nIHTMLDocument2 doc2 = (IHTMLDocument2)doc;\ndoc2.write(oPageText);\n"
},
{
"answer_id": 56276,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "HTMLDocument"
},
{
"answer_id": 56629,
"author": "Alan",
"author_id": 5846,
"author_profile": "https://Stackoverflow.com/users/5846",
"pm_score": 3,
"selected": false,
"text": "var wb = new WebBrowser()\n var doc = wb.Browser.Document\nvar elem = doc.GetElementById(elementId);\nobject obj = elem.DomElement;\nSystem.Reflection.MethodInfo mi = obj.GetType().GetMethod(\"click\");\nmi.Invoke(obj, new object[0]);\n"
},
{
"answer_id": 624410,
"author": "Frank Schwieterman",
"author_id": 32203,
"author_profile": "https://Stackoverflow.com/users/32203",
"pm_score": 3,
"selected": false,
"text": " IEnumerable<XNode> auctionNodes = Majestic12ToXml.Majestic12ToXml.ConvertNodesToXml(byteArrayOfAuctionHtml);\n\n foreach (XElement anchorTag in auctionNodes.OfType<XElement>().DescendantsAndSelf(\"a\")) {\n\n if (anchorTag.Attribute(\"href\") == null)\n continue;\n\n Console.WriteLine(anchorTag.Attribute(\"href\").Value);\n }\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Majestic12;\nusing System.IO;\nusing System.Xml.Linq;\nusing System.Diagnostics;\nusing System.Text.RegularExpressions;\n\nnamespace Majestic12ToXml {\npublic class Majestic12ToXml {\n\n static public IEnumerable<XNode> ConvertNodesToXml(byte[] htmlAsBytes) {\n\n HTMLparser parser = OpenParser();\n parser.Init(htmlAsBytes);\n\n XElement currentNode = new XElement(\"document\");\n\n HTMLchunk m12chunk = null;\n\n int xmlnsAttributeIndex = 0;\n string originalHtml = \"\";\n\n while ((m12chunk = parser.ParseNext()) != null) {\n\n try {\n\n Debug.Assert(!m12chunk.bHashMode); // popular default for Majestic-12 setting\n\n XNode newNode = null;\n XElement newNodesParent = null;\n\n switch (m12chunk.oType) {\n case HTMLchunkType.OpenTag:\n\n // Tags are added as a child to the current tag, \n // except when the new tag implies the closure of \n // some number of ancestor tags.\n\n newNode = ParseTagNode(m12chunk, originalHtml, ref xmlnsAttributeIndex);\n\n if (newNode != null) {\n currentNode = FindParentOfNewNode(m12chunk, originalHtml, currentNode);\n\n newNodesParent = currentNode;\n\n newNodesParent.Add(newNode);\n\n currentNode = newNode as XElement;\n }\n\n break;\n\n case HTMLchunkType.CloseTag:\n\n if (m12chunk.bEndClosure) {\n\n newNode = ParseTagNode(m12chunk, originalHtml, ref xmlnsAttributeIndex);\n\n if (newNode != null) {\n currentNode = FindParentOfNewNode(m12chunk, originalHtml, currentNode);\n\n newNodesParent = currentNode;\n newNodesParent.Add(newNode);\n }\n }\n else {\n XElement nodeToClose = currentNode;\n\n string m12chunkCleanedTag = CleanupTagName(m12chunk.sTag, originalHtml);\n\n while (nodeToClose != null && nodeToClose.Name.LocalName != m12chunkCleanedTag)\n nodeToClose = nodeToClose.Parent;\n\n if (nodeToClose != null)\n currentNode = nodeToClose.Parent;\n\n Debug.Assert(currentNode != null);\n }\n\n break;\n\n case HTMLchunkType.Script:\n\n newNode = new XElement(\"script\", \"REMOVED\");\n newNodesParent = currentNode;\n newNodesParent.Add(newNode);\n break;\n\n case HTMLchunkType.Comment:\n\n newNodesParent = currentNode;\n\n if (m12chunk.sTag == \"!--\")\n newNode = new XComment(m12chunk.oHTML);\n else if (m12chunk.sTag == \"![CDATA[\")\n newNode = new XCData(m12chunk.oHTML);\n else\n throw new Exception(\"Unrecognized comment sTag\");\n\n newNodesParent.Add(newNode);\n\n break;\n\n case HTMLchunkType.Text:\n\n currentNode.Add(m12chunk.oHTML);\n break;\n\n default:\n break;\n }\n }\n catch (Exception e) {\n var wrappedE = new Exception(\"Error using Majestic12.HTMLChunk, reason: \" + e.Message, e);\n\n // the original html is copied for tracing/debugging purposes\n originalHtml = new string(htmlAsBytes.Skip(m12chunk.iChunkOffset)\n .Take(m12chunk.iChunkLength)\n .Select(B => (char)B).ToArray()); \n\n wrappedE.Data.Add(\"source\", originalHtml);\n\n throw wrappedE;\n }\n }\n\n while (currentNode.Parent != null)\n currentNode = currentNode.Parent;\n\n return currentNode.Nodes();\n }\n\n static XElement FindParentOfNewNode(Majestic12.HTMLchunk m12chunk, string originalHtml, XElement nextPotentialParent) {\n\n string m12chunkCleanedTag = CleanupTagName(m12chunk.sTag, originalHtml);\n\n XElement discoveredParent = null;\n\n // Get a list of all ancestors\n List<XElement> ancestors = new List<XElement>();\n XElement ancestor = nextPotentialParent;\n while (ancestor != null) {\n ancestors.Add(ancestor);\n ancestor = ancestor.Parent;\n }\n\n // Check if the new tag implies a previous tag was closed.\n if (\"form\" == m12chunkCleanedTag) {\n\n discoveredParent = ancestors\n .Where(XE => m12chunkCleanedTag == XE.Name)\n .Take(1)\n .Select(XE => XE.Parent)\n .FirstOrDefault();\n }\n else if (\"td\" == m12chunkCleanedTag) {\n\n discoveredParent = ancestors\n .TakeWhile(XE => \"tr\" != XE.Name)\n .Where(XE => m12chunkCleanedTag == XE.Name)\n .Take(1)\n .Select(XE => XE.Parent)\n .FirstOrDefault();\n }\n else if (\"tr\" == m12chunkCleanedTag) {\n\n discoveredParent = ancestors\n .TakeWhile(XE => !(\"table\" == XE.Name\n || \"thead\" == XE.Name\n || \"tbody\" == XE.Name\n || \"tfoot\" == XE.Name))\n .Where(XE => m12chunkCleanedTag == XE.Name)\n .Take(1)\n .Select(XE => XE.Parent)\n .FirstOrDefault();\n }\n else if (\"thead\" == m12chunkCleanedTag\n || \"tbody\" == m12chunkCleanedTag\n || \"tfoot\" == m12chunkCleanedTag) {\n\n\n discoveredParent = ancestors\n .TakeWhile(XE => \"table\" != XE.Name)\n .Where(XE => m12chunkCleanedTag == XE.Name)\n .Take(1)\n .Select(XE => XE.Parent)\n .FirstOrDefault();\n }\n\n return discoveredParent ?? nextPotentialParent;\n }\n\n static string CleanupTagName(string originalName, string originalHtml) {\n\n string tagName = originalName;\n\n tagName = tagName.TrimStart(new char[] { '?' }); // for nodes <?xml >\n\n if (tagName.Contains(':'))\n tagName = tagName.Substring(tagName.LastIndexOf(':') + 1);\n\n return tagName;\n }\n\n static readonly Regex _startsAsNumeric = new Regex(@\"^[0-9]\", RegexOptions.Compiled);\n\n static bool TryCleanupAttributeName(string originalName, ref int xmlnsIndex, out string result) {\n\n result = null;\n string attributeName = originalName;\n\n if (string.IsNullOrEmpty(originalName))\n return false;\n\n if (_startsAsNumeric.IsMatch(originalName))\n return false;\n\n //\n // transform xmlns attributes so they don't actually create any XML namespaces\n //\n if (attributeName.ToLower().Equals(\"xmlns\")) {\n\n attributeName = \"xmlns_\" + xmlnsIndex.ToString(); ;\n xmlnsIndex++;\n }\n else {\n if (attributeName.ToLower().StartsWith(\"xmlns:\")) {\n attributeName = \"xmlns_\" + attributeName.Substring(\"xmlns:\".Length);\n } \n\n //\n // trim trailing \\\"\n //\n attributeName = attributeName.TrimEnd(new char[] { '\\\"' });\n\n attributeName = attributeName.Replace(\":\", \"_\");\n }\n\n result = attributeName;\n\n return true;\n }\n\n static Regex _weirdTag = new Regex(@\"^<!\\[.*\\]>$\"); // matches \"<![if !supportEmptyParas]>\"\n static Regex _aspnetPrecompiled = new Regex(@\"^<%.*%>$\"); // matches \"<%@ ... %>\"\n static Regex _shortHtmlComment = new Regex(@\"^<!-.*->$\"); // matches \"<!-Extra_Images->\"\n\n static XElement ParseTagNode(Majestic12.HTMLchunk m12chunk, string originalHtml, ref int xmlnsIndex) {\n\n if (string.IsNullOrEmpty(m12chunk.sTag)) {\n\n if (m12chunk.sParams.Length > 0 && m12chunk.sParams[0].ToLower().Equals(\"doctype\"))\n return new XElement(\"doctype\");\n\n if (_weirdTag.IsMatch(originalHtml))\n return new XElement(\"REMOVED_weirdBlockParenthesisTag\");\n\n if (_aspnetPrecompiled.IsMatch(originalHtml))\n return new XElement(\"REMOVED_ASPNET_PrecompiledDirective\");\n\n if (_shortHtmlComment.IsMatch(originalHtml))\n return new XElement(\"REMOVED_ShortHtmlComment\");\n\n // Nodes like \"<br <br>\" will end up with a m12chunk.sTag==\"\"... We discard these nodes.\n return null;\n }\n\n string tagName = CleanupTagName(m12chunk.sTag, originalHtml);\n\n XElement result = new XElement(tagName);\n\n List<XAttribute> attributes = new List<XAttribute>();\n\n for (int i = 0; i < m12chunk.iParams; i++) {\n\n if (m12chunk.sParams[i] == \"<!--\") {\n\n // an HTML comment was embedded within a tag. This comment and its contents\n // will be interpreted as attributes by Majestic-12... skip this attributes\n for (; i < m12chunk.iParams; i++) {\n\n if (m12chunk.sTag == \"--\" || m12chunk.sTag == \"-->\")\n break;\n }\n\n continue;\n }\n\n if (m12chunk.sParams[i] == \"?\" && string.IsNullOrEmpty(m12chunk.sValues[i]))\n continue;\n\n string attributeName = m12chunk.sParams[i];\n\n if (!TryCleanupAttributeName(attributeName, ref xmlnsIndex, out attributeName))\n continue;\n\n attributes.Add(new XAttribute(attributeName, m12chunk.sValues[i]));\n }\n\n // If attributes are duplicated with different values, we complain.\n // If attributes are duplicated with the same value, we remove all but 1.\n var duplicatedAttributes = attributes.GroupBy(A => A.Name).Where(G => G.Count() > 1);\n\n foreach (var duplicatedAttribute in duplicatedAttributes) {\n\n if (duplicatedAttribute.GroupBy(DA => DA.Value).Count() > 1)\n throw new Exception(\"Attribute value was given different values\");\n\n attributes.RemoveAll(A => A.Name == duplicatedAttribute.Key);\n attributes.Add(duplicatedAttribute.First());\n }\n\n result.Add(attributes);\n\n return result;\n }\n\n static HTMLparser OpenParser() {\n HTMLparser oP = new HTMLparser();\n\n // The code+comments in this function are from the Majestic-12 sample documentation.\n\n // ...\n\n // This is optional, but if you want high performance then you may\n // want to set chunk hash mode to FALSE. This would result in tag params\n // being added to string arrays in HTMLchunk object called sParams and sValues, with number\n // of actual params being in iParams. See code below for details.\n //\n // When TRUE (and its default) tag params will be added to hashtable HTMLchunk (object).oParams\n oP.SetChunkHashMode(false);\n\n // if you set this to true then original parsed HTML for given chunk will be kept - \n // this will reduce performance somewhat, but may be desireable in some cases where\n // reconstruction of HTML may be necessary\n oP.bKeepRawHTML = false;\n\n // if set to true (it is false by default), then entities will be decoded: this is essential\n // if you want to get strings that contain final representation of the data in HTML, however\n // you should be aware that if you want to use such strings into output HTML string then you will\n // need to do Entity encoding or same string may fail later\n oP.bDecodeEntities = true;\n\n // we have option to keep most entities as is - only replace stuff like \n // this is called Mini Entities mode - it is handy when HTML will need\n // to be re-created after it was parsed, though in this case really\n // entities should not be parsed at all\n oP.bDecodeMiniEntities = true;\n\n if (!oP.bDecodeEntities && oP.bDecodeMiniEntities)\n oP.InitMiniEntities();\n\n // if set to true, then in case of Comments and SCRIPT tags the data set to oHTML will be\n // extracted BETWEEN those tags, rather than include complete RAW HTML that includes tags too\n // this only works if auto extraction is enabled\n oP.bAutoExtractBetweenTagsOnly = true;\n\n // if true then comments will be extracted automatically\n oP.bAutoKeepComments = true;\n\n // if true then scripts will be extracted automatically: \n oP.bAutoKeepScripts = true;\n\n // if this option is true then whitespace before start of tag will be compressed to single\n // space character in string: \" \", if false then full whitespace before tag will be returned (slower)\n // you may only want to set it to false if you want exact whitespace between tags, otherwise it is just\n // a waste of CPU cycles\n oP.bCompressWhiteSpaceBeforeTag = true;\n\n // if true (default) then tags with attributes marked as CLOSED (/ at the end) will be automatically\n // forced to be considered as open tags - this is no good for XML parsing, but I keep it for backwards\n // compatibility for my stuff as it makes it easier to avoid checking for same tag which is both closed\n // or open\n oP.bAutoMarkClosedTagsWithParamsAsOpen = false;\n\n return oP;\n }\n}\n} \n"
},
{
"answer_id": 2495482,
"author": "P M",
"author_id": 299367,
"author_profile": "https://Stackoverflow.com/users/299367",
"pm_score": 0,
"selected": false,
"text": "script SS_URLs.txt URL(\"http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c\")\n http://sstatic.net/so/all.css\nhttp://sstatic.net/so/favicon.ico\nhttp://sstatic.net/so/apple-touch-icon.png\n.\n.\n.\n"
},
{
"answer_id": 6244203,
"author": "majmun",
"author_id": 784885,
"author_profile": "https://Stackoverflow.com/users/784885",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Threading;\n\nclass ParseHTML\n{\n public ParseHTML() { }\n private string ReturnString;\n\n public string doParsing(string html)\n {\n Thread t = new Thread(TParseMain);\n t.ApartmentState = ApartmentState.STA;\n t.Start((object)html);\n t.Join();\n return ReturnString;\n }\n\n private void TParseMain(object html)\n {\n WebBrowser wbc = new WebBrowser();\n wbc.DocumentText = \"feces of a dummy\"; //;magic words \n HtmlDocument doc = wbc.Document.OpenNew(true);\n doc.Write((string)html);\n this.ReturnString = doc.Body.InnerHtml + \" do here something\";\n return;\n }\n}\n string myhtml = \"<HTML><BODY>This is a new HTML document.</BODY></HTML>\";\nConsole.WriteLine(\"before:\" + myhtml);\nmyhtml = (new ParseHTML()).doParsing(myhtml);\nConsole.WriteLine(\"after:\" + myhtml);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
56,112 |
<p>I have written a Silverlight 2 application communicating with a WCF service (BasicHttpBinding). The site hosting the Silverlight content is protected using a ASP.NET Membership Provider. I can access the current user using HttpContext.Current.User.Identity.Name from my WCF service, and I have turned on AspNetCompatibilityRequirementsMode. </p>
<p>I now want to write a Windows application using the exact same web service. To handle authentication I have enabled the <a href="http://msdn.microsoft.com/en-us/library/bb386582.aspx" rel="noreferrer">Authentication service</a>, and can call "login" to authenticate my user... Okey, all good... But how the heck do I get that authentication cookie set on my other service client?! </p>
<p>Both services are hosted on the same domain </p>
<ul>
<li>MyDataService.svc <- the one dealing with my data</li>
<li>AuthenticationService.svc <- the one the windows app has to call to authenticate.</li>
</ul>
<p>I don't want to create a new service for the windows client, or use another binding...</p>
<p>The Client Application Services is another alternative, but all the examples is limited to show how to get the user, roles and his profile... But once we're authenticated using the Client Application Services there should be a way to get that authentication cookie attached to my service clients when calling back to the same server.</p>
<p>According to input from colleagues the solution is adding a wsHttpBinding end-point, but I'm hoping I can get around that...</p>
|
[
{
"answer_id": 57760,
"author": "Jonas Follesø",
"author_id": 1199387,
"author_profile": "https://Stackoverflow.com/users/1199387",
"pm_score": 4,
"selected": true,
"text": "var authService = new AuthService.AuthenticationServiceClient();\nvar diveService = new DiveLogService.DiveLogServiceClient();\n\nstring cookieHeader = \"\";\nusing (OperationContextScope scope = new OperationContextScope(authService.InnerChannel))\n{\n HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();\n OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;\n bool isGood = authService.Login(\"jonas\", \"jonas\", string.Empty, true);\n MessageProperties properties = OperationContext.Current.IncomingMessageProperties;\n HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];\n cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie]; \n}\n\nusing (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel))\n{\n HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();\n OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);\n httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);\n var res = diveService.GetDives();\n} \n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] |
56,118 |
<p>I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians.</p>
<p>I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks.</p>
<p><img src="https://i.stack.imgur.com/B0nfz.jpg" alt="triangle"></p>
|
[
{
"answer_id": 56126,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "180 - arctan(x/y) //Degrees\npi - arctan(x/y) //radians\n"
},
{
"answer_id": 56131,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "sqrt(x^2 + y^2)"
},
{
"answer_id": 56239,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 1,
"selected": false,
"text": "a y h 180 - a PI - a cos(a) = y/h\nsin(a) = x/h\ntan(a) = x/y\n a = arctan(x/y)\n 180 - arctan(x/y)\n"
},
{
"answer_id": 57362,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 4,
"selected": true,
"text": "var h:Number = Math.sqrt(x*x + y*y);\nvar z:Number = Math.atan2(y, x);\n var h:Number = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
56,124 |
<p>Can I run a 64-bit VMware image on a 32-bit machine?</p>
<p>I've googled this, but there doesn't seem to be a conclusive answer.</p>
<p>I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms.</p>
|
[
{
"answer_id": 56332,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 5,
"selected": false,
"text": "$ cd /path/to/vmware/guestos\n$ for i in \\`ls *[0-9].vmdk\\`; do qemu-img convert -f vmdk $i -O raw {i/vmdk/raw};done\n$ cat *.raw >> guestos.img\n qemu -m 256 -hda guestos.img\n -f qcow for i in `ls *[0-9].vmdk`; do qemu-img convert -f vmdk $i -O qcow ${i/vmdk/qcow}; done && cat *.qcow >> debian.img\n"
},
{
"answer_id": 13299051,
"author": "Knapsu",
"author_id": 1325136,
"author_profile": "https://Stackoverflow.com/users/1325136",
"pm_score": 1,
"selected": false,
"text": "egrep '(vmx|svm)' /proc/cpuinfo\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078/"
] |
56,149 |
<p>How do you store file permissions in a repository? A few files need to be read-only to stop a third party program from trashing it but after checking out of the repository they are set to read-write.</p>
<p>I looked on google and found a <a href="http://mamchenkov.net/wordpress/2005/04/27/subversion-and-file-permissions/" rel="noreferrer">blog post from 2005</a> that states that Subversion doesn't store file-permissions. There are patches and hook-scripts listed (only one url still exists). Three years later does Subversion still not store file permissions and are hooks the only way to go about this? (I've never done hooks and rather use something that is native to Subversion.)</p>
|
[
{
"answer_id": 56158,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": -1,
"selected": false,
"text": "svn lock"
},
{
"answer_id": 56217,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 0,
"selected": false,
"text": "svn svn svn svn PATH"
},
{
"answer_id": 9424852,
"author": "Will B.",
"author_id": 1144627,
"author_profile": "https://Stackoverflow.com/users/1144627",
"pm_score": 2,
"selected": false,
"text": "Owner, Group, Folders, Files\ndefault: <user> www-user 750 640\n/path/to/file: <user> non-www 770 770\n/path/to/file2: <user> <user> 700 700\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] |
56,168 |
<p>The code in <a href="https://stackoverflow.com/questions/17181/test-cases-vs-assertion-statement">this question</a> made me think</p>
<pre><code>assert(value>0); //Precondition
if (value>0)
{
//Doit
}
</code></pre>
<p>I never write the if-statement. Asserting is enough/all you <em>can</em> do.
"Crash early, crash often"</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">CodeComplete</a> states:</p>
<ul>
<li>The assert-statement makes the application Correct </li>
<li>The if-test makes the application Robust</li>
</ul>
<p>I don't think you've made an application more robust by correcting invalid input values, or skipping code:</p>
<pre><code>assert(value >= 0 ); //Precondition
assert(value <= 90); //Precondition
if(value < 0) //Just in case
value = 0;
if (value > 90) //Just in case
value = 90;
//Doit
</code></pre>
<p>These corrections are based on assumptions you made about the outside world.
Only the caller knows what "a valid input value" is for your function, and he must check its validity before he calls your function.</p>
<p>To paraphrase <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">CodeComplete</a>:
"Real-world programs <em>become</em> too messy when we <em>don't</em> rely solely on assertions."</p>
<p>Question: Am I wrong, stuborn, stupid, too non-defensive...</p>
|
[
{
"answer_id": 56174,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 2,
"selected": false,
"text": "assert(value>0);\nif(value<=0) throw new ArgumentOutOfRangeException(\"value\");\n//do stuff\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163/"
] |
56,195 |
<p>How to obtain Vista Edition programmatically, that is Home Basic, Home Premium, Business or Ultimate ?</p>
|
[
{
"answer_id": 56251,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 1,
"selected": false,
"text": "[Environment.OSVersion][1]\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5383/"
] |
56,208 |
<p>I've having trouble directly accessing the <strong>Win32_OperatingSystem</strong> management class that is exposed via WMI.</p>
<p>It is a singleton class, and I'm pretty certain "Win32_OperatingSystem=@" is the correct path syntax to get the instance of a singleton.</p>
<p>The call to InvokeMethod produces the exception listed at the bottom of the question, as does accessing the ClassPath property (commented line).</p>
<p>What am I doing wrong?</p>
<p>[I'm aware that I can use ManagementObjectSearcher/ObjectQuery to return a collection of Win32_OperatingSystem (which would contain only one), but since I know it is a singleton, I want to access it directly.]</p>
<hr>
<pre><code>ManagementScope cimv2 = InitScope(string.Format(@"\\{0}\root\cimv2", this.Name));
ManagementObject os = new ManagementObject(
cimv2,
new ManagementPath("Win32_OperatingSystem=@"),
new ObjectGetOptions());
//ManagementPath p = os.ClassPath;
os.InvokeMethod("Reboot", null);
</code></pre>
<hr>
<p>System.Management.ManagementException was caught
Message="Invalid object path "
Source="System.Management"
StackTrace:
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementBaseObject.get_wbemObject()
at System.Management.ManagementObject.get_ClassPath()
at System.Management.ManagementObject.GetMethodParameters(String methodName, ManagementBaseObject& inParameters, IWbemClassObjectFreeThreaded& inParametersClass, IWbemClassObjectFreeThreaded& outParametersClass)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)</p>
<hr>
<p>Thanks for the replies.</p>
<p><strong>Nick</strong> - I don't know how to go about doing that :)</p>
<p><strong>Uros</strong> - I was under the impression that it was a singleton class because of <a href="http://msdn.microsoft.com/en-us/library/aa394239.aspx" rel="nofollow noreferrer">this</a> MSDN page. Also, opening the class in the WBEMTest utility shows <a href="http://img247.imageshack.us/img247/5686/64933271au3.png" rel="nofollow noreferrer">this</a>.</p>
<hr>
<p>The instances dialog shows: "1 objects" and "max. batch: 1" in those fields and lists "Win32_OperatingSystem=@"</p>
<p>The ManagementScope is verified as working, so I don't know what's up. I'm a WMI novice, but this seems like one of the simplest use cases!</p>
|
[
{
"answer_id": 65735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "ManagementObject OS = new ManagementObject(@\"Win32_OperatingSystem.Name='OSname'\")\n"
},
{
"answer_id": 90709,
"author": "Nick Randell",
"author_id": 5932,
"author_profile": "https://Stackoverflow.com/users/5932",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Management;\n\nnamespace WmiPlay\n{\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n ManagementScope cimv2 = new ManagementScope(@\"\\\\.\\root\\cimv2\");\n ManagementObject os = new ManagementObject(cimv2, new ManagementPath(\"Win32_OperatingSystem=@\"), new ObjectGetOptions());\n Console.Out.WriteLine(os);\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine(ex);\n }\n }\n }\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82/"
] |
56,215 |
<p>Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.</p>
<p>Problem 1 :</p>
<p><strong>Product of everything except current</strong> </p>
<p>Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]</p>
<p>For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.</p>
<p>IMPORTANT: Your algorithm must run in linear time.</p>
<p>Problem 2 : ( the topic was in one of Jeff posts )</p>
<p><strong>Shuffle card deck evenly</strong></p>
<ol>
<li><p>Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).</p></li>
<li><p>Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()</p></li>
<li><p>What is the complexity of your algorithm (as a function of the number n of cards in the deck)?</p></li>
<li><p>Explain how you would test that the cards are evenly shuffled by your method (black box testing).</p></li>
</ol>
<p>P.S. I had two hours to code the solutions</p>
|
[
{
"answer_id": 56270,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 3,
"selected": false,
"text": "int countZeroes (int[] vec) {\nint ret = 0;\nforeach(int i in vec) if (i == 0) ret++;\n\nreturn ret;\n}\n\nint[] mysticCalc(int[] values, int[] indexes) {\n int zeroes = countZeroes(values); \n int[] retval = new int[values.length];\n int product = 1;\n\n if (zeroes >= 2) { // 2 or more zeroes, all results will be 0\n for (int i = 0; i > values.length; i++) {\n retval[i] = 0; \n }\n return retval;\n }\n foreach (int i in values) {\n if (i != 0) product *= i; // we have at most 1 zero, dont include in product;\n }\n int indexcounter = 0;\n foreach(int idx in indexes) {\n if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0\n retval[indexcounter] = 0;\n }\n else if (zeroes == 1) { // One zero on this index. result is product\n retval[indexcounter] = product;\n }\n else { // No zeros. Return product/value at index\n retval[indexcounter] = product / values[idx];\n }\n indexcouter++;\n } \n return retval;\n}\n"
},
{
"answer_id": 56275,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "void product_except_current(int input[], int index[], int out[], \n int len) {\n int prod = 1, nzeros = 0, izero = -1;\n\n for (int i = 0; i < len; ++i) \n if ((out[i] = input[index[i]]) != 0)\n // compute product of non-zero elements \n prod *= out[i]; // ignore possible overflow problem\n else {\n if (++nzeros == 2) \n // if number of zeros greater than 1 then out[i] = 0 for all i\n break; \n izero = i; // save index of zero-valued element\n }\n\n // \n for (int i = 0; i < len; ++i) \n out[i] = nzeros ? 0 : prod / out[i]; \n\n if (nzeros == 1)\n out[izero] = prod; // the only non-zero-valued element\n}\n"
},
{
"answer_id": 56291,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 0,
"selected": false,
"text": " public static void shuffle (int[] array) \n {\n Random rng = new Random(); // i.e., java.util.Random.\n int n = array.length; // The number of items left to shuffle (loop invariant).\n while (n > 1) \n {\n int k = rng.nextInt(n); // 0 <= k < n.\n n--; // n is now the last pertinent index;\n int temp = array[n]; // swap array[n] with array[k] (does nothing if k == n).\n array[n] = array[k];\n array[k] = temp;\n }\n }\n"
},
{
"answer_id": 56379,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "#include <algorithm>\n\nclass Deck {\n // each card is 8-bit: 4-bit for suit, 4-bit for value\n // suits and values are extracted using bit-magic\n char cards[52];\n public:\n // ...\n void shuffle() {\n std::random_shuffle(cards, cards + 52);\n }\n // ...\n};\n // ...\n int main() {\n typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;\n Map freqs; \n Deck d;\n const size_t ntests = 100000;\n\n // compute frequencies of events: card at position\n for (size_t i = 0; i < ntests; ++i) {\n d.shuffle();\n size_t pos = 0;\n for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos) \n ++freqs[std::make_pair(pos, *j)]; \n }\n\n // if Deck.shuffle() is correct then all frequencies must be similar\n for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)\n std::cout << \"pos=\" << j->first.first << \" card=\" << j->first.second \n << \" freq=\" << j->second << std::endl; \n }\n"
},
{
"answer_id": 56549,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "IEnumerable<int> ProductExcept(List<int> l, List<int> indexes) {\n if (l.Count(i => i == 0) == 1) {\n int singleZeroProd = l.Aggregate(1, (x, y) => y != 0 ? x * y : x);\n return from i in indexes select l[i] == 0 ? singleZeroProd : 0;\n } else {\n int prod = l.Aggregate(1, (x, y) => x * y);\n return from i in indexes select prod == 0 ? 0 : prod / l[i];\n }\n}\n"
},
{
"answer_id": 56940,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "public enum CardValue { A, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, J, Q, K }\npublic enum Suit { Spades, Hearts, Diamonds, Clubs }\n\npublic class Card {\n public Card(CardValue value, Suit suit) {\n Value = value;\n Suit = suit;\n }\n\n public CardValue Value { get; private set; }\n public Suit Suit { get; private set; }\n}\n\npublic class Deck : IEnumerable<Card> {\n public Deck() {\n initialiseDeck();\n Shuffle();\n }\n\n private Card[] cards = new Card[52];\n\n private void initialiseDeck() {\n for (int i = 0; i < 4; ++i) {\n for (int j = 0; j < 13; ++j) {\n cards[i * 13 + j] = new Card((CardValue)j, (Suit)i);\n }\n }\n }\n\n public void Shuffle() {\n Random random = new Random();\n\n for (int i = 0; i < 52; ++i) {\n int j = random.Next(51 - i);\n // Swap the cards.\n Card temp = cards[51 - i];\n cards[51 - i] = cards[j];\n cards[j] = temp;\n }\n }\n\n public IEnumerator<Card> GetEnumerator() {\n foreach (Card c in cards) yield return c;\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {\n foreach (Card c in cards) yield return c;\n }\n}\n\nclass Program {\n static void Main(string[] args) {\n foreach (Card c in new Deck()) {\n Console.WriteLine(\"{0} of {1}\", c.Value, c.Suit);\n }\n\n Console.ReadKey(true);\n }\n}\n"
},
{
"answer_id": 292078,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 1,
"selected": false,
"text": "import Array\n\nproblem1 input index = [(left!i) * (right!(i+1)) | i <- index]\n where left = scanWith scanl\n right = scanWith scanr\n scanWith scan = listArray (0, length input) (scan (*) 1 input)\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
56,224 |
<p>I have an application that reads a table from a database. </p>
<p>I issue an SQL query to get a result set, based on a unique string value I glean from the results, I use a case/switch statement to generate certain objects (they inherit TreeNode BTW). These created objects get shunted into a Dictionary object to be used later.</p>
<p>Whilst generating these objects I use some of the values from the result set to populate values in the object via the setters.</p>
<p>I query the Dictionary to return a particular object type and use it to populate a treeview. However it is not possible to populate 2 objects of the same type in a treeview from the Dictionary object (you get a runtime error - which escapes me at the moment, something to with referencing the same object). So what I have to do is use a memberwiseClone and implement IClonable to get around this. </p>
<p>Am I doing this right? Is there a better way - because I think this is causing my program to be real slow at this point. At the very least I think its a bit clunky - any advice from people who know more than me - greatly appreciated.</p>
|
[
{
"answer_id": 56299,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": true,
"text": "TreeNode TreeNode"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
56,227 |
<p>I would like to start tagging my deployed binaries with the latest SVN revision number.</p>
<p>However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number.</p>
<p>Using <code>svn info</code> on the root doesn't work (it just reports the version of that directory, not files in subdirectories):</p>
<p>I was wondering if there is a shortcut using the <code>svn</code> command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)?</p>
<p>I also understand that one alternative approach is to keep a <em>version file</em> with the <code>svn:keywords</code>. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts.</p>
<p><strong>Answer</strong> I see my problem lied with not doing a proper <code>svn up</code> before calling <code>svn info</code> in the root directory:</p>
<pre><code>$ svn info
Path: .
...
Last Changed Author: fak
Last Changed Rev: 713
Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up
At revision 721.
$ svn info
Path: .
...
Revision: 721
Last Changed Author: reuben
Last Changed Rev: 721
Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008)
</code></pre>
|
[
{
"answer_id": 56240,
"author": "Charles Miller",
"author_id": 3052,
"author_profile": "https://Stackoverflow.com/users/3052",
"pm_score": 6,
"selected": true,
"text": "$ svn up\n...stuff...\nUpdated to revision 66593.\n $ svn info\nPath: .\nURL: https://svn.example.com/svn/myproject/trunk\nRepository Root: https://svn.example.com/svn/\nRepository UUID: d2a7a951-c712-0410-832a-9abccabd3052\nRevision: 66593\nNode Kind: directory\nSchedule: normal\nLast Changed Author: bnguyen\nLast Changed Rev: 66591\nLast Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)\n"
},
{
"answer_id": 56258,
"author": "jan",
"author_id": 1163,
"author_profile": "https://Stackoverflow.com/users/1163",
"pm_score": 2,
"selected": false,
"text": " <SvnVersion LocalPath=\"$(MSBuildProjectDirectory)\" ToolPath=\"installationpath\\of\\subversion\\bin\">\n <Output TaskParameter=\"Revision\" PropertyName=\"Revision\" />\n </SvnVersion>\n <Message Text=\"Version: $(Major).$(Minor).$(Build).$(Revision)\"/>\n...\n AssemblyVersion=\"$(Major).$(Minor).$(Build).$(Revision)\"\n AssemblyFileVersion=\"$(Major).$(Minor).$(Build).$(Revision)\"\n"
},
{
"answer_id": 56267,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": false,
"text": "svn update svn info svn info URL-to-source"
},
{
"answer_id": 249905,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 5,
"selected": false,
"text": "svnversion svnversion -c /path/to/your-projects-local-working-copy/. | sed -e 's/[MS]//g' -e 's/^[[:digit:]]*://'\n svnversion sed svn info -R svn info -R /path/to/your-projects-local-working-copy/. | awk '/^Last Changed Rev:/ {print $NF}' | sort -n | tail -n 1\n \"Last Changed Rev\" svn update svn info /path/to/your-projects-local-working-copy/.@HEAD | awk '/^Last Changed Rev:/ {print $NF}'\n"
},
{
"answer_id": 250254,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 3,
"selected": false,
"text": "svnversion"
},
{
"answer_id": 13057020,
"author": "Daniel Sokolowski",
"author_id": 913223,
"author_profile": "https://Stackoverflow.com/users/913223",
"pm_score": 0,
"selected": false,
"text": "svn info svnversion repo_root# find ./ | xargs -l svn info | grep 'Revision: ' | sort\n...\nRevision: 86\nRevision: 86\nRevision: 89\nRevision: 90\nroot@fairware:/home/stage_vancity#\n"
},
{
"answer_id": 14368458,
"author": "Maria Ananieva",
"author_id": 1985264,
"author_profile": "https://Stackoverflow.com/users/1985264",
"pm_score": 1,
"selected": false,
"text": "@for /f \"tokens=4\" %%f in ('svn info %SVNURL% ^|find \"Last Changed Rev:\"') do set lastPathRev=%%f\n\necho trunk rev no: %lastPathRev%\n"
},
{
"answer_id": 34048048,
"author": "KymikoLoco",
"author_id": 2196304,
"author_profile": "https://Stackoverflow.com/users/2196304",
"pm_score": 2,
"selected": false,
"text": "X:\\trunk>svn info -r COMMITTED | for /F \"tokens=2\" %r in ('findstr /R \"^Revision\"') DO @echo %r\n67000\n svn info -r COMMITTED X:\\Trunk>svn info -r COMMITTED\nPath: trunk\nURL: https://svn.example.com/svn/myproject/trunk\nRepository Root: https://svn.example.com/svn/\nRepository UUID: d2a7a951-c712-0410-832a-9abccabd3052\nRevision: 67400\nNode Kind: directory\nLast Changed Author: example\nLast Changed Rev: 67400\nLast Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)\n findstr svn info Revision: 67000\n echo 67000\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
56,229 |
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p>
<p>This is similar to what I'm actually doing:</p>
<pre><code>import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love &aacute; letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &amp;aacute;
letters'</script></head><body><h1>And I like the fact that 3 &gt; 1</h1>
</body></html>
</code></pre>
|
[
{
"answer_id": 56262,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "html(head(script(type='text/javascript', content='var a = ...')),\nbody(h1('And I like the fact that 3 < 1'), p('just some paragraph'))\n from magictree import html, head, script, body, h1, p\nroot = html(\n head(\n script('''var a = 'I love &aacute; letters''', \n type='text/javascript')),\n body(\n h1('And I like the fact that 3 > 1')))\n\n# root is a plain Element object, like those created with ET.Element...\n# so you can write it out using ElementTree :)\ntree = ET.ElementTree(root)\ntree.write('foo.xhtml')\n magictree Element"
},
{
"answer_id": 56269,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 5,
"selected": false,
"text": ">>> from lxml import etree\n\n>>> from lxml.builder import E\n\n>>> def CLASS(*args): # class is a reserved word in Python\n... return {\"class\":' '.join(args)}\n\n>>> html = page = (\n... E.html( # create an Element called \"html\"\n... E.head(\n... E.title(\"This is a sample document\")\n... ),\n... E.body(\n... E.h1(\"Hello!\", CLASS(\"title\")),\n... E.p(\"This is a paragraph with \", E.b(\"bold\"), \" text in it!\"),\n... E.p(\"This is another paragraph, with a\", \"\\n \",\n... E.a(\"link\", href=\"http://www.python.org\"), \".\"),\n... E.p(\"Here are some reserved characters: <spam&egg>.\"),\n... etree.XML(\"<p>And finally an embedded XHTML fragment.</p>\"),\n... )\n... )\n... )\n\n>>> print(etree.tostring(page, pretty_print=True))\n<html>\n <head>\n <title>This is a sample document</title>\n </head>\n <body>\n <h1 class=\"title\">Hello!</h1>\n <p>This is a paragraph with <b>bold</b> text in it!</p>\n <p>This is another paragraph, with a\n <a href=\"http://www.python.org\">link</a>.</p>\n <p>Here are some reservered characters: <spam&egg>.</p>\n <p>And finally an embedded XHTML fragment.</p>\n </body>\n</html>\n"
},
{
"answer_id": 56470,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 4,
"selected": true,
"text": "from xml.dom.minidom import parseString\n\ndoc = parseString(\"\"\"<html>\n <head>\n <script type=\"text/javascript\">\n var a = 'I love &aacute; letters'\n </script>\n </head>\n <body>\n <h1>And I like the fact that 3 > 1</h1>\n </body>\n </html>\"\"\")\n\nwith open(\"foo.xhtml\", \"w\") as f:\n f.write( doc.toxml() )\n var a = '%(message)s'\n </html>\"\"\" % {\"message\": \"I love &aacute; letters\"})\n"
},
{
"answer_id": 58460,
"author": "DaveP",
"author_id": 3577,
"author_profile": "https://Stackoverflow.com/users/3577",
"pm_score": 0,
"selected": false,
"text": "#\n#Output the XML entry\n#\ndef genFileOLD(out,label,term,idval):\n filename=entryTime() + \".html\"\n writer=MarkupWriter(out, indent=u\"yes\")\n writer.startDocument()\n #Test element and attribute writing\n ans=namespace=u'http://www.w3.org/2005/Atom'\n xns=namespace=u'http://www.w3.org/1999/xhtml'\n writer.startElement(u'entry',\n ans,\n extraNss={u'x':u'http://www.w3.org/1999/xhtml' ,\n u'dc':u'http://purl.org/dc/elements/1.1'})\n #u'a':u'http://www.w3.org/2005/Atom',\n #writer.attribute(u'xml:lang',unicode(\"en-UK\"))\n\n writer.simpleElement(u'title',ans,content=unicode(label))\n #writer.simpleElement(u'a:subtitle',ans,content=u' ')\n id=unicode(\"http://www.dpawson.co.uk/nodesets/\"+afn.split(\".\")[0])\n writer.simpleElement(u'id',ans,content=id)\n writer.simpleElement(u'updated',ans,content=unicode(dtime()))\n writer.startElement(u'author',ans)\n writer.simpleElement(u'name',ans,content=u'Dave ')\n writer.simpleElement(u'uri',ans,\n content=u'http://www.dpawson.co.uk/nodesets/'+afn+\".xml\")\n writer.endElement(u'author')\n writer.startElement(u'category', ans)\n if (prompt):\n label=unicode(raw_input(\"Enter label \"))\n writer.attribute(u'label',unicode(label))\n if (prompt):\n term = unicode(raw_input(\"Enter term to use \"))\n writer.attribute(u'term', unicode(term))\n writer.endElement(u'category')\n writer.simpleElement(u'rights',ans,content=u'\\u00A9 Dave 2005-2008')\n writer.startElement(u'link',ans)\n writer.attribute(u'href',\n unicode(\"http://www.dpawson.co.uk/nodesets/entries/\"+afn+\".html\"))\n writer.attribute(u'rel',unicode(\"alternate\"))\n writer.endElement(u'link')\n writer.startElement(u'published', ans)\n dt=dtime()\n dtu=unicode(dt)\n writer.text(dtu)\n writer.endElement(u'published')\n writer.simpleElement(u'summary',ans,content=unicode(label))\n writer.startElement(u'content',ans)\n writer.attribute(u'type',unicode(\"xhtml\"))\n writer.startElement(u'div',xns)\n writer.simpleElement(u'h3',xns,content=unicode(label))\n writer.endElement(u'div')\n writer.endElement(u'content')\n writer.endElement(u'entry')\n"
},
{
"answer_id": 62157,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "from xml.sax import saxutils\nfrom xml.dom.minidom import parseString\nfrom xml.parsers.expat import ExpatError\n\nxml = '''<?xml version=\"1.0\" encoding=\"%s\"?>\\n\n<contents title=\"%s\" crawl_date=\"%s\" in_text_date=\"%s\" \nurl=\"%s\">\\n<main_post>%s</main_post>\\n</contents>''' %\n(self.encoding, saxutils.escape(title), saxutils.escape(time), \nsaxutils.escape(date), saxutils.escape(url), saxutils.escape(contents))\ntry:\n minidoc = parseString(xml)\ncatch ExpatError:\n print \"Invalid xml\"\n"
},
{
"answer_id": 3098902,
"author": "oasisbob",
"author_id": 335903,
"author_profile": "https://Stackoverflow.com/users/335903",
"pm_score": 5,
"selected": false,
"text": "from elementtree.SimpleXMLWriter import XMLWriter\nimport sys\n\nw = XMLWriter(sys.stdout)\nhtml = w.start(\"html\")\n\nw.start(\"head\")\nw.element(\"title\", \"my document\")\nw.element(\"meta\", name=\"generator\", value=\"my application 1.0\")\nw.end()\n\nw.start(\"body\")\nw.element(\"h1\", \"this is a heading\")\nw.element(\"p\", \"this is a paragraph\")\n\nw.start(\"p\")\nw.data(\"this is \")\nw.element(\"b\", \"bold\")\nw.data(\" and \")\nw.element(\"i\", \"italic\")\nw.data(\".\")\nw.end(\"p\")\n\nw.close(html)\n"
},
{
"answer_id": 7060046,
"author": "Mikhail Korobov",
"author_id": 114795,
"author_profile": "https://Stackoverflow.com/users/114795",
"pm_score": 3,
"selected": false,
"text": "import xmlwitch\nxml = xmlwitch.Builder(version='1.0', encoding='utf-8')\nwith xml.feed(xmlns='http://www.w3.org/2005/Atom'):\n xml.title('Example Feed')\n xml.updated('2003-12-13T18:30:02Z')\n with xml.author:\n xml.name('John Doe')\n xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6')\n with xml.entry:\n xml.title('Atom-Powered Robots Run Amok')\n xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a')\n xml.updated('2003-12-13T18:30:02Z')\n xml.summary('Some text.')\nprint(xml)\n"
},
{
"answer_id": 19728898,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": ">>> from xml.sax.saxutils import XMLGenerator\n>>> import StringIO\n>>> w = XMLGenerator(out, 'utf-8')\n>>> w.startDocument()\n>>> w.startElement(\"test\", {'bar': 'baz'})\n>>> w.characters(\"Foo\")\n>>> w.endElement(\"test\")\n>>> w.endDocument()\n>>> print out.getvalue()\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<test bar=\"baz\">Foo</test>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
56,271 |
<p>I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this:</p>
<pre><code><system.web>
<authentication mode="Forms">
<forms loginUrl="Default.aspx" path="/" protection="All" timeout="360" name="MyAppName" cookieless="UseCookies" />
</authentication>
<authorization >
<allow users="*"/>
</authorization>
</system.web>
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
</code></pre>
<p>Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role.</p>
<p>User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory.</p>
<p>Based on this <a href="http://support.microsoft.com/kb/311495" rel="nofollow noreferrer">MS KB article</a> along with other webpages giving the same information, I have added the following code to my Global.asax file:</p>
<pre><code>protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
if (HttpContext.Current.User != null) {
if (Request.IsAuthenticated == true) {
// Debug#1
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
// In this case, ticket.UserData = "Admin"
string[] roles = new string[1] { ticket.UserData };
FormsIdentity id = new FormsIdentity(ticket);
Context.User = new System.Security.Principal.GenericPrincipal(id, roles);
// Debug#2
}
}
}
</code></pre>
<p>However, when I try to log in, I am unable to access the Admin folder (get redirected to login page). </p>
<p>Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly.</p>
<p>After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page_Load of the login, it returns false. So somewhere after Application_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost).</p>
<p>What am I doing wrong, and how can I get it to work properly?</p>
<hr>
<p><strong>Update: I entered the <a href="https://stackoverflow.com/questions/56271/contextuser-losing-roles-after-being-assigned-in-globalasaxapplicationauthentic#57040">solution below</a></strong></p>
|
[
{
"answer_id": 57040,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 4,
"selected": true,
"text": "<system.web>\n <roleManager enabled=\"true\" />\n</system.web>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] |
56,279 |
<p>We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's.
The way we're doing it now is with code I found <a href="http://forums.asp.net/p/931180/1092188.aspx#1092188" rel="nofollow noreferrer">here</a> that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system.
Does anyone know of any way to do this?</p>
|
[
{
"answer_id": 56281,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": true,
"text": "Render WebContext WebRequest Render curl wget"
},
{
"answer_id": 66312,
"author": "Lea Cohen",
"author_id": 278,
"author_profile": "https://Stackoverflow.com/users/278",
"pm_score": 2,
"selected": false,
"text": "TextWriter textWriter = new StringWriter();\nServer.Execute(\"myOtherPage.aspx\", textWriter);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] |
56,303 |
<p>I need to specify a date value in a sybase where clause. For example:</p>
<pre><code>select *
from data
where dateVal < [THE DATE]
</code></pre>
|
[
{
"answer_id": 56310,
"author": "cmsherratt",
"author_id": 3512,
"author_profile": "https://Stackoverflow.com/users/3512",
"pm_score": 5,
"selected": false,
"text": "select * from data \nwhere dateVal < convert(datetime, '01/01/2008', 103)\n"
},
{
"answer_id": 74525,
"author": "Jose B.",
"author_id": 5413,
"author_profile": "https://Stackoverflow.com/users/5413",
"pm_score": 2,
"selected": false,
"text": "Select \n cast('2008-09-16' as date)\n convert(date,'16/09/2008',103)\n date('2008-09-16')\nfrom dummy;\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512/"
] |
56,324 |
<p>I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that.</p>
<p>Currently I clear the screen using</p>
<pre><code>#ifdef __WIN32
system( "cls" );
#else
system( "clear" );
#endif
</code></pre>
<p>Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'.</p>
|
[
{
"answer_id": 425208,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 0,
"selected": false,
"text": "printf \"\\x[0;0H\"\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5330/"
] |
56,334 |
<p>Suppose that two tables exist: <code>users</code> and <code>groups</code>.</p>
<p><strong>How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?</strong></p>
<p>The result of the search must distinguish between the two types.</p>
|
[
{
"answer_id": 56336,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": true,
"text": "UNION SELECT \"group\" type, name\n FROM groups\n WHERE name LIKE \"%$text%\"\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE name LIKE \"%$text%\"\n"
},
{
"answer_id": 56389,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": false,
"text": "UNION ALL"
},
{
"answer_id": 56423,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 1,
"selected": false,
"text": " SELECT \"group\" type, name\n FROM groups\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] |
56,340 |
<p>I have a class in system-C with some data members as such: </p>
<pre><code>long double x[8];
</code></pre>
<p>I'm initializing it in the construction like this:</p>
<pre><code>for (i = 0; i < 8; ++i) {
x[i] = 0;
}
</code></pre>
<p>But the first time I use it in my code I have garbage there.</p>
<p>Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?</p>
<p>Edit:
@Prakash:
Actually, this is a typo in the <em>question</em>, but not in my code... Thanks!</p>
|
[
{
"answer_id": 56336,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": true,
"text": "UNION SELECT \"group\" type, name\n FROM groups\n WHERE name LIKE \"%$text%\"\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE name LIKE \"%$text%\"\n"
},
{
"answer_id": 56389,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": false,
"text": "UNION ALL"
},
{
"answer_id": 56423,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 1,
"selected": false,
"text": " SELECT \"group\" type, name\n FROM groups\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] |
56,342 |
<p>We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.</p>
<p>We'll need to support more 'formats' in the future too.</p>
<p>Do we go for a solution using:</p>
<ul>
<li>Regex</li>
<li>Simply string searching (using string.IndexOf etc)</li>
<li>Lex/ Yacc</li>
<li>Other</li>
</ul>
<p>The overall solution will be developed in C# 2.0 (hopefully 3.5)</p>
|
[
{
"answer_id": 56398,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 0,
"selected": false,
"text": "IndexOf if(s.IndexOf(\"search1\")>-1 || s.IndexOf(\"search2\")>-1 ||..."
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5791/"
] |
56,347 |
<p>I'm returning to c++ after being away for a bit and trying to dust off the old melon. </p>
<p>In Java Iterator is an interface to a container having methods: <code>hasNext()</code>, <code>next()</code> and <code>remove()</code>. The presence of <code>hasNext()</code> means it <strong>has the concept of a limit</strong> for the container being traversed.</p>
<pre><code>//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
System.out.println(iter.next());
}
</code></pre>
<p>In the C++ standard template library, iterators seem to represent a datatype or class the supports the <code>operator++</code> and <code>operator==</code> but has <strong>no concept of a limit</strong> built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.</p>
<pre><code>vector<int> vec;
vector<int>::iterator iter;
// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);
for (iter= v.begin(); iter != v.end(); iter++)
{
cout << *i << " "; //Should output 1 4 8
}
</code></pre>
<p>The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.</p>
<p>It there any further subtlety to this that I am missing?</p>
|
[
{
"answer_id": 56370,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": true,
"text": "transform"
},
{
"answer_id": 161439,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 4,
"selected": false,
"text": "// for each element in vec\nfor(iter a = vec.begin(); a != vec.end(); ++a){\n // critical step! We will revisit 'a' later.\n iter cur = a; \n unsigned i = 0;\n // print 3 elements\n for(; cur != vec.end() && i < 3; ++cur, ++i){\n cout << *cur << \" \";\n }\n cout << \"\\n\";\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
56,357 |
<p>I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using </p>
<blockquote>
<p><code>aspnet_compiler.exe -nologo -v ${Appname} -u ${target}</code></p>
</blockquote>
<p>I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached).</p>
<p>I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea.</p>
<p>I couldn't find much on MSDN. How do you compile your websites for production?</p>
|
[
{
"answer_id": 56365,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<compilation debug=false>"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] |
56,362 |
<p>I'm starting to learn ruby. I'm also a day-to-day C++ dev.
For C++ projects I usually go with following dir structure</p>
<pre><code>/
-/bin <- built binaries
-/build <- build time temporary object (eg. .obj, cmake intermediates)
-/doc <- manuals and/or Doxygen docs
-/src
--/module-1
--/module-2
-- non module specific sources, like main.cpp
- IDE project files (.sln), etc.
</code></pre>
<p>What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?</p>
|
[
{
"answer_id": 56448,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "- src/\n some_ruby_file.rb:\n require 'spider'\n Spider.do_something\n\n+ doc/\n\n- lib/\n - spider/\n spider.rb:\n $: << File.expand_path(File.dirname(__FILE__))\n module Spider\n # anything that needs to be done before including submodules\n end\n\n require 'spider/some_helper'\n require 'spider/some/other_helper'\n ...\n - src/\n some_ruby_file.rb:\n require 'spider'\n Spider.include_all\n Spider.do_something\n\n+ doc/\n\n- lib\n - spider/\n spider.rb:\n $: << File.expand_path(File.dirname(__FILE__))\n module Spider\n def self.include_all\n require 'spider/some_helper'\n require 'spider/some/other_helper'\n ...\n end\n end\n"
},
{
"answer_id": 62964,
"author": "François Beausoleil",
"author_id": 7355,
"author_profile": "https://Stackoverflow.com/users/7355",
"pm_score": 5,
"selected": true,
"text": "$ bundle gem --coc --mit --test=minitest --exe spider\nCreating gem 'spider'...\nMIT License enabled in config\nCode of conduct enabled in config\n create spider/Gemfile\n create spider/lib/spider.rb\n create spider/lib/spider/version.rb\n create spider/spider.gemspec\n create spider/Rakefile\n create spider/README.md\n create spider/bin/console\n create spider/bin/setup\n create spider/.gitignore\n create spider/.travis.yml\n create spider/test/test_helper.rb\n create spider/test/spider_test.rb\n create spider/LICENSE.txt\n create spider/CODE_OF_CONDUCT.md\n create spider/exe/spider\nInitializing git repo in /Users/francois/Projects/spider\nGem 'spider' was successfully created. For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html\n lib/\n spider/\n base.rb\n crawler/\n base.rb\n spider.rb\n require \"spider/base\"\n require \"crawler/base\"\n --coc --exe --mit"
},
{
"answer_id": 14019444,
"author": "trans",
"author_id": 1086638,
"author_profile": "https://Stackoverflow.com/users/1086638",
"pm_score": 4,
"selected": false,
"text": " lib/\n foo.rb\n foo/\n share/\n foo/\n test/\n helper.rb\n test_foo.rb\n HISTORY.md (or CHANGELOG.md)\n LICENSE.txt\n README.md\n foo.gemspec\n share/ data/ lib/ test/ spec/ features/ demo/ foo.gemspec .gemspec bin/\n foo\n man/\n foo.1\n foo.1.md or foo.1.ronn\n Gemfile\n Rakefile\n Gemfile Rakefile VERSION\n MANIFEST\n VERSION MANIFEST Manifest.txt config/\n doc/ (or docs/)\n script/\n log/\n pkg/\n task/ (or tasks/)\n vendor/\n web/ (or site/)\n config/ doc/ script/ log/ pkg/ foo-1.0.0.gem task/ foo.rake foo.watchr vendor/ web/ .document\n .gitignore\n .yardopts\n .travis.yml\n .index var/ work work/\n NOTES.md\n consider/\n reference/\n sandbox/\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5731/"
] |
56,373 |
<p>I am writing a unit test to check that a private method will close a stream.</p>
<p>The unit test calls methodB and the variable something is null</p>
<p>The unit test doesn't mock the class on test</p>
<p>The private method is within a public method that I am calling.</p>
<p>Using emma in eclipse (via the eclemma plugin) the method call is displayed as not being covered even though the code within the method is</p>
<p>e.g</p>
<pre><code>public methodA(){
if (something==null) {
methodB(); //Not displayed as covered
}
}
private methodB(){
lineCoveredByTest; //displayed as covered
}
</code></pre>
<p>Why would the method call not be highlighted as being covered?</p>
|
[
{
"answer_id": 56816,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 0,
"selected": false,
"text": "methodB() methodA() methodB() methodC()"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
56,375 |
<p>Put differently:</p>
<p>Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?</p>
<p>As far as I understand, generic collections not only are type-safe, but their performance is better.</p>
<hr>
<p>Here's a comprehensive article on the topic: <a href="http://msdn.microsoft.com/en-us/library/ms364091%28VS.80%29.aspx" rel="noreferrer">An Extensive Examination of Data Structures Using C# 2.0</a>.</p>
|
[
{
"answer_id": 56381,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "List<Object>"
},
{
"answer_id": 70542386,
"author": "user17804168",
"author_id": 17804168,
"author_profile": "https://Stackoverflow.com/users/17804168",
"pm_score": 0,
"selected": false,
"text": "public int Add(object myItem)\n{\n if (!(myItem is MyItemClass))\n throw new ArgumentException(nameof(myItem));\n\n // code to add to the ArrayList\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670/"
] |
56,391 |
<p>Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.</p>
<p>The problem is that I have no idea about what have to be done on the server side.</p>
<p>I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?</p>
<p>Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/56391/automatically-checking-for-a-new-version-of-my-application/56418#56418">pilif</a> : thanks for your detailed answer. There is still something which is unclear for me :</p>
<blockquote>
<p>like</p>
<p><code>http://www.example.com/update?version=1.2.4</code></p>
<p>Then you can return what ever you want, probably also the download-URL of the installer of the new version.</p>
</blockquote>
<p>How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the <code>?version=1.2.4</code> part in order to return something accordingly ?</p>
|
[
{
"answer_id": 56418,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": true,
"text": "http://www.example.com/update?version=1.2.4\n"
},
{
"answer_id": 56593,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 1,
"selected": false,
"text": "$version = $_GET['version']; \n$filename = \"yourprogram\" . $version . \".exe\";\n$filesize = filesize($filename);\nheader(\"Pragma: public\");\nheader(\"Expires: 0\");\nheader(\"Cache-Control: post-check=0, pre-check=0\");\nheader(\"Content-type: application-download\");\nheader('Content-Length: ' . $filesize);\nheader('Content-Disposition: attachment; filename=\"' . basename($filename).'\"');\nheader(\"Content-Transfer-Encoding: binary\");\n"
},
{
"answer_id": 56997,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 3,
"selected": false,
"text": "<?php\n if (version_compare($_GET['version'], \"1.4.0\") < 0){\n echo \"http://www.example.com/update.exe\";\n }else{\n echo \"no update\";\n }\n?>\n result = makeHTTPRequest(\"http://www.example.com/update?version=\" + getExeVersion());\nif result != \"no update\" then\n updater = downloadUpdater(result);\n ShellExecute(updater);\n ExitApplication;\nend;\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2796/"
] |
56,402 |
<p>I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments.</p>
<p>For horizontal alignment I can use <code>text-anchor</code> with <code>left</code>, <code>middle</code> or <code>right</code>. I can't find a equivalent for vertical alignment; <code>alignment-baseline</code> doesn't seem to do it, so at present I'm using <code>dy="0.5ex"</code> as a kludge for centre alignment.</p>
<p>Is there a proper manner for aligning with the vertical centre or top of the text?</p>
|
[
{
"answer_id": 73257,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 7,
"selected": true,
"text": "<path d=\"M10, 20 L17, 20\"\n style=\"fill:none; color:black; stroke:black; stroke-width:1.00\"/>\n<text fill=\"black\" font-family=\"sans-serif\" font-size=\"16\"\n x=\"27\" y=\"20\" style=\"dominant-baseline: central;\">\n Vertical\n</text>\n\n<path d=\"M60, 40 L60, 47\"\n style=\"fill:none; color:red; stroke:red; stroke-width:1.00\"/>\n<text fill=\"red\" font-family=\"sans-serif\" font-size=\"16\"\n x=\"60\" y=\"70\" style=\"text-anchor: middle;\">\n Horizontal\n</text>\n\n<path d=\"M60, 90 L60, 97\"\n style=\"fill:none; color:blue; stroke:blue; stroke-width:1.00\"/>\n<text fill=\"blue\" font-family=\"sans-serif\" font-size=\"16\"\n x=\"60\" y=\"97\" style=\"text-anchor: middle; dominant-baseline: hanging;\">\n Bit of Both\n</text>\n"
},
{
"answer_id": 23681125,
"author": "mjswensen",
"author_id": 926279,
"author_profile": "https://Stackoverflow.com/users/926279",
"pm_score": 2,
"selected": false,
"text": "alignment-baseline central middle"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5764/"
] |
56,411 |
<p>First off, this question is ripped out from <a href="https://stackoverflow.com/questions/56215/interesting-interview-questions#56291">this</a> question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me.</p>
<p>Assume that you have a algorithm that generates randomness. Now how do you test it?
Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm?</p>
<p>To add some theory to the problem -
A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!.</p>
<p>What is the chance that you, after shuffling, will get A, K, Q, J ... of each suit in a sequence? Answer 1 / 52!</p>
<p>So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more...</p>
<p>How would you black box test a shuffling algorithm for randomness?</p>
|
[
{
"answer_id": 56509,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": " // ...\n int main() {\n typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;\n Map freqs; \n Deck d;\n const size_t ntests = 100000;\n\n // compute frequencies of events: card at position\n for (size_t i = 0; i < ntests; ++i) {\n d.shuffle();\n size_t pos = 0;\n for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos) \n ++freqs[std::make_pair(pos, *j)]; \n }\n\n // if Deck.shuffle() is correct then all frequencies must be similar\n for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)\n std::cout << \"pos=\" << j->first.first << \" card=\" << j->first.second \n << \" freq=\" << j->second << std::endl; \n }\n"
},
{
"answer_id": 56576,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 3,
"selected": false,
"text": "/**\n * This is a rudimentary check to ensure that the output of a given RNG\n * is approximately uniformly distributed. If the RNG output is not\n * uniformly distributed, this method will return a poor estimate for the\n * value of pi.\n * @param rng The RNG to test.\n * @param iterations The number of random points to generate for use in the\n * calculation. This value needs to be sufficiently large in order to\n * produce a reasonably accurate result (assuming the RNG is uniform).\n * Less than 10,000 is not particularly useful. 100,000 should be sufficient.\n * @return An approximation of pi generated using the provided RNG.\n */\npublic static double calculateMonteCarloValueForPi(Random rng,\n int iterations)\n{\n // Assumes a quadrant of a circle of radius 1, bounded by a box with\n // sides of length 1. The area of the square is therefore 1 square unit\n // and the area of the quadrant is (pi * r^2) / 4.\n int totalInsideQuadrant = 0;\n // Generate the specified number of random points and count how many fall\n // within the quadrant and how many do not. We expect the number of points\n // in the quadrant (expressed as a fraction of the total number of points)\n // to be pi/4. Therefore pi = 4 * ratio.\n for (int i = 0; i < iterations; i++)\n {\n double x = rng.nextDouble();\n double y = rng.nextDouble();\n if (isInQuadrant(x, y))\n {\n ++totalInsideQuadrant;\n }\n }\n // From these figures we can deduce an approximate value for Pi.\n return 4 * ((double) totalInsideQuadrant / iterations);\n}\n\n/**\n * Uses Pythagoras' theorem to determine whether the specified coordinates\n * fall within the area of the quadrant of a circle of radius 1 that is\n * centered on the origin.\n * @param x The x-coordinate of the point (must be between 0 and 1).\n * @param y The y-coordinate of the point (must be between 0 and 1).\n * @return True if the point is within the quadrant, false otherwise.\n */\nprivate static boolean isInQuadrant(double x, double y)\n{\n double distance = Math.sqrt((x * x) + (y * y));\n return distance <= 1;\n}\n"
},
{
"answer_id": 56731,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": -1,
"selected": false,
"text": "// A card has a Number 0-51 and a position 0-51\nint[][] StatMatrix = new int[52][52]; // Assume all are set to 0 as starting values\nShuffleCards();\nForEach (card in Cards) {\n StatMatrix[Card.Position][Card.Number]++;\n}\n statMatrix[position][card] / numberOfShuffle = 1/52.\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4165/"
] |
56,430 |
<p>I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (<strong>FROM WINDOWS</strong>, not fox):</p>
<p>Windows-No disk
Exception Processing Message c0000012 Parameters .....</p>
<p>Any help please
Nelson Marmol</p>
|
[
{
"answer_id": 56487,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": false,
"text": "Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on. \n\nYou can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.\n\n\nSYS(2450 [, 0 | 1 ])\n\n\n\nParameters\n0 \nSearch along path and default locations before searching in the application. (Default)\n\n1 \nSearch within the application for the specified procedure or UDF before searching the path and default locations.\n"
},
{
"answer_id": 1150726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "THIS.Icon=<path to file>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
56,443 |
<p>I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.</p>
<p>Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.</p>
|
[
{
"answer_id": 56483,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 6,
"selected": true,
"text": "comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));\n MyEnum value = (MyEnum)comboBox1.SelectedValue;\n DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();\ncol.Name = \"My Enum Column\";\ncol.DataSource = Enum.GetValues(typeof(MyEnum));\ncol.ValueType = typeof(MyEnum);\ndataGridView1.Columns.Add(col);\n"
},
{
"answer_id": 56613,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Enum.GetValues(typeof(EnumeratorName)) dataGridViewComboBoxColumn.Items.Add(EnumeratorValue)\n BindingList<Your Class> IList"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4660/"
] |
56,446 |
<p>Although perhaps a bizare thing to want to do, I need to create an Array in .Net with a lower bound > 0. This at first seems to be possible, using:</p>
<pre><code>Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
</code></pre>
<p>Produces the desired results (an array of objects with a lower bound set to 9). However the created array instance can no longer be passed to other methods expecting <code>Object[]</code> giving me an error saying that:</p>
<p><code>System.Object[*]</code> can not be cast into a <code>System.Object[]</code>. What is this difference in array types and how can I overcome this?</p>
<p>Edit: test code = </p>
<pre><code>Object x = Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
Object[] y = (Object[])x;
</code></pre>
<p>Which fails with: "Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'."</p>
<p>I would also like to note that this approach <strong>DOES</strong> work when using multiple dimensions:</p>
<pre><code>Object x = Array.CreateInstance(typeof(Object), new int[] {2,2}, new int[] {9,9});
Object[,] y = (Object[,])x;
</code></pre>
<p>Which works fine.</p>
|
[
{
"answer_id": 56495,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 2,
"selected": false,
"text": "class ConstrainedArray<T> : IEnumerable<T> where T : new()\n{\n public ConstrainedArray(int min, int max)\n {\n array = new T[max - min];\n }\n\n public T this [int index]\n {\n get { return array[index - Min]; }\n set { array[index - Min] = value; }\n }\n\n public int Min {get; private set;}\n public int Max {get; private set;}\n\n T[] array;\n\n public IEnumerator<T> GetEnumerator()\n {\n return array.GetEnumarator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return array.GetEnumarator();\n }\n\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] |
56,472 |
<p>I'm trying to send messages to Objective-C objects in gdb.</p>
<pre><code>(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.
</code></pre>
<p>I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?</p>
|
[
{
"answer_id": 57279,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 1,
"selected": false,
"text": "$esi p (NSUInteger)[(NSArray *)$esi count]\n"
},
{
"answer_id": 58687,
"author": "asksol",
"author_id": 5577,
"author_profile": "https://Stackoverflow.com/users/5577",
"pm_score": 0,
"selected": false,
"text": "(gdb) p (NSUInteger)[(NSObject*)$esi retainCount]\nNo symbol table is loaded. Use the \"file\" command.\n(gdb) p [(NSArray *)$esi count]\nNo symbol \"NSArray\" in current context.\n (gdb) add-symbol-file /System/Library/Frameworks/Foundation.framework/Foundation \nadd symbol table from file \"/System/Library/Frameworks/Foundation.framework/Foundation\"? (y or n) y\nReading symbols from /System/Library/Frameworks/Foundation.framework/Foundation...done.\n (gdb) p [(NSArray *)$esi count]\nNo symbol \"NSArray\" in current context.\n (gdb) p $eax\n$11 = 367589056\n(gdb) po $eax\n<NSCFArray 0x15e8f6c0>(\n file://localhost/Users/ask/Documents/composing-fractals.pdf\n)\n\n(gdb) p (int)[$eax retainCount]\n$12 = 1\n"
},
{
"answer_id": 61947,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 4,
"selected": true,
"text": "(gdb) print (int)[receivedData count]\nTarget does not respond to this message selector.\n\n(gdb) print (int)[receivedData performSelector:@selector(count) ]\n2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]:\nunrecognized selector sent to instance 0x105f2e0\n (gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ]\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5577/"
] |
56,478 |
<p>I am looking for a way to interact with a standalone full version of Windows Media Player.<br>
Mostly I need to know the Path of the currently played track.</p>
<p>The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in .Net(C#) without any heavy use of pinvoke, which I am not really comfortable with.</p>
<p>Thanks</p>
<p>Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user</p>
|
[
{
"answer_id": 56494,
"author": "Markus Olsson",
"author_id": 2114,
"author_profile": "https://Stackoverflow.com/users/2114",
"pm_score": 3,
"selected": false,
"text": "using WMPLib;\n var Player = new WindowsMediaPlayer();\n// Load a playlist or file and then get the title \nvar title = Player.controls.currentItem.name;\n"
},
{
"answer_id": 56504,
"author": "Dave Arkell",
"author_id": 4002,
"author_profile": "https://Stackoverflow.com/users/4002",
"pm_score": 1,
"selected": false,
"text": "WMPplayer.URL = stringPathToFile;\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798/"
] |
56,500 |
<p>I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put</p>
<pre><code>extern "C" _declspec(dllexport) char* MyNewVariable = 0;
</code></pre>
<p>which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including</p>
<pre><code>_declspec(dllimport) char* MyNewVariable;
</code></pre>
<p>but that just gives me a linker error:</p>
<p>unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA)</p>
<pre><code>extern "C" _declspec(dllimport) char* MyNewVariable;
</code></pre>
<p>as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:</p>
<p>unresolved external symbol __imp__MyNewVariable</p>
<p>How do I write the declaration so that the C++ DLL variable is accessible from the C app?</p>
<hr>
<h2>The Answer</h2>
<p>As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.</p>
|
[
{
"answer_id": 56513,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 2,
"selected": false,
"text": "#ifdef __cplusplus\nextern \"C\" {\n#endif\ndeclspec(dllimport) char MyNewVariable;\n#ifdef __cplusplus\n}\n#endif\n"
},
{
"answer_id": 56514,
"author": "botismarius",
"author_id": 4528,
"author_profile": "https://Stackoverflow.com/users/4528",
"pm_score": 4,
"selected": true,
"text": ".lib extern \"C\" { declspec(dllimport) char MyNewVariable; }\n"
},
{
"answer_id": 56535,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "__declspec(dllimport) LoadLibrary() GetProcAddress()"
},
{
"answer_id": 56541,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 1,
"selected": false,
"text": "__imp_?MyNewVariable@@3PADA"
},
{
"answer_id": 56550,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 1,
"selected": false,
"text": "extern \"C\""
},
{
"answer_id": 56649,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "extern \"C\" char* MyNewVariable;\n"
},
{
"answer_id": 57055,
"author": "Bart",
"author_id": 4343,
"author_profile": "https://Stackoverflow.com/users/4343",
"pm_score": 1,
"selected": false,
"text": "extern \"C\" _declspec(dllexport) char* MyNewVariable = 0;\n extern \"C\" _declspec(dllimport) char* MyNewVariable;\n #ifdef __cplusplus\nextern \"C\" {\n#endif\n#ifdef dll_source_file\n#define EXPORTED declspec(dllexport) \n#else\n#define EXPORTED declspec(dllimport) \n#endif dll_source_file\n#ifdef __cplusplus\n}\n#endif\n\nEXPORTED char* MyNewVariable;\n #define dll_source_code \n#include \"universal_header.h\"\n\nEXPORTED char* MyNewVariable = 0;\n #include \"universal_header.h\"\n...\nMyNewVariable = \"Hello, world\";\n #include \"export_magic.h\"\n\nEXPORTED char *MyNewVariable;\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5816/"
] |
56,518 |
<p>In C# are the nullable primitive types (i.e. <code>bool?</code>) just aliases for their corresponding <code>Nullable<T></code> type or is there a difference between the two?</p>
|
[
{
"answer_id": 56520,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 3,
"selected": false,
"text": "Nullable<T> Nullable<bool> bool? Nullable<bool>"
},
{
"answer_id": 56523,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "bool Nullable<> HasValue Value Nullable<bool> bool?"
},
{
"answer_id": 56525,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 5,
"selected": false,
"text": "bool? b = null Nullable<bool> b = null ?"
},
{
"answer_id": 56526,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": false,
"text": "bool? myValue = true;\nbool hasValue = false;\n\nif (myValue.HasValue && myValue.Value)\n{\n hasValue = true;\n}\n if (myValue)\n{\n hasValue = true;\n}\n"
},
{
"answer_id": 56539,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 7,
"selected": true,
"text": "Nullable<bool>"
},
{
"answer_id": 14610056,
"author": "svick",
"author_id": 41071,
"author_profile": "https://Stackoverflow.com/users/41071",
"pm_score": 3,
"selected": false,
"text": "Nullable<T>"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] |
56,521 |
<p>I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type <code>double?</code> (or <code>Nullable<double></code>). It's nullable to support the case where the user doesn't enter anything.</p>
<p>The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():</p>
<pre><code>this.numericTextBox1.Value = 1;
</code></pre>
<p>Remember 'Value' is of type <code>Nullable<double></code>. This generates the following warning whenever I try to reopen the form in the Designer:</p>
<pre><code>Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.
</code></pre>
<p>As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 56528,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": -1,
"selected": false,
"text": "[DefaultValue(new Nullable<double>(1))] \npublic double? Value ...\n"
},
{
"answer_id": 56533,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 3,
"selected": true,
"text": "[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n"
},
{
"answer_id": 12729701,
"author": "Svetlin Ralchev",
"author_id": 538886,
"author_profile": "https://Stackoverflow.com/users/538886",
"pm_score": 2,
"selected": false,
"text": "public class CategoricalDataPointCodeDomSerializer : CodeDomSerializer\n{\n public override object Deserialize(IDesignerSerializationManager manager, object codeObject)\n {\n CodeStatementCollection collection = codeObject as CodeStatementCollection;\n\n if (collection != null)\n {\n foreach (CodeStatement statement in collection)\n {\n CodeAssignStatement codeAssignment = statement as CodeAssignStatement;\n\n if (codeAssignment != null)\n {\n CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression;\n CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression;\n\n if (properyRef != null && properyRef.PropertyName == \"Value\" && primitiveExpression != null && primitiveExpression.Value != null)\n {\n primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value);\n break;\n }\n }\n }\n }\n\n return base.Deserialize(manager, codeObject);\n }\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
56,547 |
<p>How do you perform a CROSS JOIN with LINQ to SQL?</p>
|
[
{
"answer_id": 679174,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "var combo = from Person in people\n from Car in cars\n select new {Person, Car};\n"
},
{
"answer_id": 11395783,
"author": "Rzv.im",
"author_id": 1474780,
"author_profile": "https://Stackoverflow.com/users/1474780",
"pm_score": 5,
"selected": false,
"text": "SelectMany var names = new string[] { \"Ana\", \"Raz\", \"John\" };\nvar numbers = new int[] { 1, 2, 3 };\nvar newList=names.SelectMany(\n x => numbers,\n (y, z) => { return y + z + \" test \"; });\nforeach (var item in newList)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 18937903,
"author": "amoss",
"author_id": 208068,
"author_profile": "https://Stackoverflow.com/users/208068",
"pm_score": 4,
"selected": false,
"text": "Tuple public static IEnumerable<Tuple<T1, T2>> CrossJoin<T1, T2>(IEnumerable<T1> sequence1, IEnumerable<T2> sequence2)\n{\n return sequence1.SelectMany(t1 => sequence2.Select(t2 => Tuple.Create(t1, t2)));\n}\n"
},
{
"answer_id": 36089869,
"author": "Denis",
"author_id": 400589,
"author_profile": "https://Stackoverflow.com/users/400589",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<Tuple<T1, T2>> CrossJoin<T1, T2>(this IEnumerable<T1> sequence1, IEnumerable<T2> sequence2)\n{\n return sequence1.SelectMany(t1 => sequence2.Select(t2 => Tuple.Create(t1, t2)));\n}\n vals1.CrossJoin(vals2)\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556/"
] |
56,554 |
<p>Let's say I want to represent <code>\q</code> (or any other particular "backslash-escaped character"). That is, I want to match <code>\q</code> but not <code>\\q</code>, since the latter is a backslash-escaped backslash followed by a <code>q</code>. Yet <code>\\\q</code> would match, since it's a backslash-escaped backslash followed by a backslash-escaped <code>q</code>. (Well, it would match the <code>\q</code> at the end, not the <code>\\</code> at the beginning.)</p>
<p>I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.</p>
|
[
{
"answer_id": 56668,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": -1,
"selected": false,
"text": "(?:[\\\\][\\\\])(?!(([\\\\](?![\\\\])[a-zA-Z])))\n"
},
{
"answer_id": 56842,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "/(?<!\\\\)(?:\\\\\\\\)*\\\\q/\n ?: (\\\\\\\\)"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
56,561 |
<p>What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on <a href="http://blogs.msdn.com/slippman/archive/2004/06/02/147090.aspx" rel="noreferrer">Stan Lippman's blog</a>, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"?</p>
|
[
{
"answer_id": 56779,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 6,
"selected": false,
"text": " using namespace system;\n const char* charstr = \"Hello, world!\";\n String^ clistr = gcnew String(charstr);\n Console::WriteLine(clistr);\n IntPtr p = Marshal::StringToHGlobalAnsi(clistr);\n char *pNewCharStr = static_cast<char*>(p.ToPointer());\n cout << pNewCharStr << endl;\n Marshal::FreeHGlobal(p);\n"
},
{
"answer_id": 6205115,
"author": "dko",
"author_id": 704974,
"author_profile": "https://Stackoverflow.com/users/704974",
"pm_score": 0,
"selected": false,
"text": "void MarshalString ( String ^ s, wstring& os ) {\n using namespace Runtime::InteropServices;\n const wchar_t* char = (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();\n os = char;\n}\nQString SystemStringToQt( System::String^ str)\n{\n wstring t;\n MarshalString(str, t);\n QString r = QString::fromUcs2((const ushort*)t.c_str());\n return r;\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] |
56,568 |
<p>How do you actually perform datetime operations such as adding date, finding difference, find out how many days excluding weekends in an interval? I personally started to pass some of these operations to my postgresql dbms as typically I would only need to issue one sql statement to obtain an answer, however, to do it in PHP way I would have to write a lot more code that means more chances for errors to occur...</p>
<p>Are there any libraries in PHP that does datetime operation in a way that don't require a lot of code? that beats sql in a situation where 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet_lang' that is solved by making this query?</p>
<pre class="lang-sql prettyprint-override"><code>SELECT COUNT(*) AS total_days
FROM (SELECT date '2008-8-26' + generate_series(0,
(date '2008-9-1' - date '2008-8-26')) AS all_days) AS calendar
WHERE EXTRACT(isodow FROM all_days) < 6;
</code></pre>
|
[
{
"answer_id": 56606,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 1,
"selected": false,
"text": "now = time();\ntomorrow = now + 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds\n"
},
{
"answer_id": 56900,
"author": "Rushi",
"author_id": 3983,
"author_profile": "https://Stackoverflow.com/users/3983",
"pm_score": 0,
"selected": false,
"text": "if ($timestamp_diff < (60*60*24*7)) {\n echo floor($timestamp_diff/60/60/24).\" Days\";\n} elseif ($timestamp_diff > (60*60*24*7*4)) {\n echo floor($timestamp_diff/60/60/24/7).\" Weeks\";\n} else {\n $total_months = $months = floor($timestamp_diff/60/60/24/30);\n if($months >= 12) {\n $months = ($total_months % 12);\n $years = ($total_months - $months)/12;\n echo $years . \" Years \";\n }\n if($months > 0)\n echo $months . \" Months\";\n}\n?>\n"
},
{
"answer_id": 57039,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 2,
"selected": false,
"text": "PEAR::Date PEAR::Calendar"
},
{
"answer_id": 58545,
"author": "ralfe",
"author_id": 340241,
"author_profile": "https://Stackoverflow.com/users/340241",
"pm_score": 0,
"selected": false,
"text": "mktime() mktime() $tomorrow = date(\"Y-m-d\", mktime(0, 0, 0, date(\"m\"), date(\"d\") + 1, date(\"Y\")));\n mktime()"
},
{
"answer_id": 58603,
"author": "Vertigo",
"author_id": 5468,
"author_profile": "https://Stackoverflow.com/users/5468",
"pm_score": 0,
"selected": false,
"text": "$days = (strtotime(\"2008-09-10\") - strtotime(\"2008-09-12\")) / (60 * 60 * 24);\n function isWorkDay($date)\n{\n // check if workday and return true if so\n}\n\nfunction numberOfWorkDays($startdate, $enddate)\n{\n $workdays = 0;\n $tmp = strtotime($startdate);\n $end = strtotime($enddate);\n while($tmp <= $end)\n {\n if ( isWorkDay( date(\"Y-m-d\",$tmp) ) ) $workdays++;\n $tmp += 60*60*24;\n }\n return $workdays;\n}\n list($year, $month, day) = explode(\"-\", $date);\n"
},
{
"answer_id": 201180,
"author": "user13414",
"author_id": 13414,
"author_profile": "https://Stackoverflow.com/users/13414",
"pm_score": 3,
"selected": true,
"text": "$tryme = new Extended_DateTime('2007-8-26');\n$newer = new Extended_DateTime('2008-9-1');\n\nprint 'Weekdays From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_WeekdaysFromThisTo($newer) .\"\\n\";\n/* Output: Weekdays From 2007-08-26 To 2008-09-01: 265 */\nprint 'All Days From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_AllDaysFromThisTo($newer) .\"\\n\";\n/* Output: All Days From 2007-08-26 To 2008-09-01: 371 */\n$timefrom = $tryme->find_TimeFromThisTo($newer);\nprint 'Between '.$tryme->format('Y-m-d').' and '.$newer->format('Y-m-d').' there are '.\n $timefrom['years'].' years, '.$timefrom['months'].' months, and '.$timefrom['days'].\n ' days.'.\"\\n\";\n/* Output: Between 2007-08-26 and 2008-09-01 there are 1 years, 0 months, and 5 days. */\n\nclass Extended_DateTime extends DateTime {\n\n public function find_TimeFromThisTo($newer) {\n $timefrom = array('years'=>0,'months'=>0,'days'=>0);\n\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n\n $timefrom['years'] = $this->find_YearsFromThisTo($testnewer);\n $mod = '-'.$timefrom['years'].' years';\n $testnewer -> modify($mod);\n\n $timefrom['months'] = $this->find_MonthsFromThisTo($testnewer);\n $mod = '-'.$timefrom['months'].' months';\n $testnewer -> modify($mod);\n\n $timefrom['days'] = $this->find_AllDaysFromThisTo($testnewer);\n return $timefrom;\n } // end function find_TimeFromThisTo\n\n\n public function find_YearsFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))\n return FALSE;\n $count = 0;\n\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n\n $testnewer -> modify ('-1 year');\n while ( $this->format('U') < $testnewer->format('U')) {\n $count ++;\n $testnewer -> modify ('-1 year');\n }\n return $count;\n } // end function find_YearsFromThisTo\n\n\n public function find_MonthsFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))\n return FALSE;\n\n $count = 0;\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n $testnewer -> modify ('-1 month');\n\n while ( $this->format('U') < $testnewer->format('U')) {\n $count ++;\n $testnewer -> modify ('-1 month');\n }\n return $count;\n } // end function find_MonthsFromThisTo\n\n\n public function find_AllDaysFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))\n return FALSE;\n\n $count = 0;\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n $testnewer -> modify ('-1 day');\n\n while ( $this->format('U') < $testnewer->format('U')) {\n $count ++;\n $testnewer -> modify ('-1 day');\n }\n return $count;\n } // end function find_AllDaysFromThisTo\n\n\n public function find_WeekdaysFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))\n return FALSE;\n\n $count = 0;\n\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n $testnewer -> modify ('-1 day');\n\n while ( $this->format('U') < $testnewer->format('U')) {\n // If the calculated day is not Sunday or Saturday, count this day\n if ($testnewer->format('w') != '0' && $testnewer->format('w') != '6')\n $count ++;\n $testnewer -> modify ('-1 day');\n }\n return $count;\n } // end function find_WeekdaysFromThisTo\n\n public function set_Day($newday) {\n if (is_int($newday) && $newday > 0 && $newday < 32 && checkdate($this->format('m'),$newday,$this->format('Y')))\n $this->setDate($this->format('Y'),$this->format('m'),$newday);\n } // end function set_Day\n\n\n public function set_Month($newmonth) {\n if (is_int($newmonth) && $newmonth > 0 && $newmonth < 13)\n $this->setDate($this->format('Y'),$newmonth,$this->format('d'));\n } // end function set_Month\n\n\n public function set_Year($newyear) {\n if (is_int($newyear) && $newyear > 0)\n $this->setDate($newyear,$this->format('m'),$this->format('d'));\n } // end function set_Year\n} // end class Extended_DateTime\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742/"
] |
56,574 |
<p>A while back I was reading the W3C article on '<a href="http://www.w3.org/International/articles/text-reuse/" rel="noreferrer">Re-using Strings in Scripted Content</a>', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code.</p>
<p>To take their example, we might have some code like this...</p>
<pre><code>print "The printer is ";
if (printer.working) {
print "on.\n";
} else {
print "off.\n";
}
print "The stapler is ";
if (stapler.working) {
print "on.\n";
} else {
print "off.\n";
}
</code></pre>
<p>My instinct would be to eliminate the repetition roughly as follows...</p>
<pre><code>report-state(printer, "printer");
report-state(stapler, "stapler");
function report-state(name, object) {
print "The "+name+" is ";
if (object.working) {
print "on\n";
} else {
print "off\n";
}
}
</code></pre>
<p>...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases.</p>
<p>So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code?</p>
<p>Part of me wants to argue that internationalisation is one of those extreme programming “<a href="http://www.extremeprogramming.org/rules/early.html" rel="noreferrer">you arent gonna need it</a>” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.</p>
|
[
{
"answer_id": 56617,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 5,
"selected": true,
"text": "The printer is on\nThe printer is off\nThe stapler is on\nThe stapler is off\n"
},
{
"answer_id": 103623,
"author": "user19050",
"author_id": 19050,
"author_profile": "https://Stackoverflow.com/users/19050",
"pm_score": 3,
"selected": false,
"text": " The printer is on: Imprimanta este pornită // feminine\n The printer is off: Imprimanta este oprită\n The stapler is on: Perforatorul este pornit // masculine\n The stapler is off: Perforatorul este oprit\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
56,589 |
<p>Does a new <code>SessionFactor</code>y and <code>Session</code> object have to be created for each database? I have a data store for my application data, and a separate data store for my employee security, which is used to validate users. Do I have to create a new SessionFactory ans Session object for calls to the 2 different databases?</p>
|
[
{
"answer_id": 45129618,
"author": "Frédéric",
"author_id": 1178314,
"author_profile": "https://Stackoverflow.com/users/1178314",
"pm_score": 0,
"selected": false,
"text": "OpenSession catalog <class> schema schema catalog linkedServerName.DbName"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
56,591 |
<p>Ok, this is bit of an obscure question, but hopefully someone can help me out with it.</p>
<p>The system I'm working on builds a dynamic SQL string for execution inside a stored procedure, and part of that dynamic SQL defining column aliases, which themselves are actually values retrieved from another table of user generated data.</p>
<p>So, for example, the string might look something like;</p>
<pre><code>SELECT table1.Col1 AS "This is an alias" FROM table1
</code></pre>
<p>This works fine. However, the value that is used for the alias can potentially contain a double quote character, which breaks the outer quotes. I thought that I could maybe escape double quotes inside the alias somehow, but I've had no luck figuring out how to do so. Backslash doesn't work, and using two double quotes in a row results in this error;</p>
<pre><code>SQL Error: ORA-03001: unimplemented feature
03001. 00000 - "unimplemented feature"
*Cause: This feature is not implemented.
</code></pre>
<p>Has anyone had any experience with this issue before?
Cheers for any insight anyone has.</p>
<p>p.s. the quotes are needed around the aliases because they can contain spaces.</p>
|
[
{
"answer_id": 56636,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "select 'test\"columnname\"' from dual\n 'TESTCOLUMNNAME'\n--------------------------------\ntest\"columnname\n"
},
{
"answer_id": 56711,
"author": "ibz",
"author_id": 5475,
"author_profile": "https://Stackoverflow.com/users/5475",
"pm_score": 3,
"selected": true,
"text": "SELECT table1.Col1 AS \"This is |not| an alias\" FROM table1\n"
},
{
"answer_id": 2182542,
"author": "swissunix",
"author_id": 251361,
"author_profile": "https://Stackoverflow.com/users/251361",
"pm_score": 2,
"selected": false,
"text": "select q'#someone's quote#' from dual;\n"
},
{
"answer_id": 18954073,
"author": "Artem",
"author_id": 2806242,
"author_profile": "https://Stackoverflow.com/users/2806242",
"pm_score": 0,
"selected": false,
"text": "select 1 as \"University ''John Smith''\" from dual;"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827/"
] |
56,615 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/361635/debugging-javascript-in-ie7">Debugging JavaScript in IE7</a> </p>
</blockquote>
<p>Firefox has Web Developer plugin and Firebug for troubleshooting html/css/javascript issues. Google Chrome and Safari have a very similar console and right-click options for "Inspect Element".</p>
<p>Does IE7 have anything similar for troubleshooting layout/html/css issues?</p>
|
[
{
"answer_id": 1433745,
"author": "Esteban Küber",
"author_id": 34813,
"author_profile": "https://Stackoverflow.com/users/34813",
"pm_score": 4,
"selected": false,
"text": "javascript:var%20firebug=document.createElement('script');firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);\n"
},
{
"answer_id": 5791859,
"author": "81prelude",
"author_id": 725565,
"author_profile": "https://Stackoverflow.com/users/725565",
"pm_score": 1,
"selected": false,
"text": "Tools | Manage Add-Ons | Enable or Disable Add-ons IE menu | Customize Command Bar | Add or Remove Commands"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
56,628 |
<p>I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?</p>
|
[
{
"answer_id": 985032,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "DBCC ShrinkFile(yourLogical_LogFileName, 50)\n"
},
{
"answer_id": 2898241,
"author": "ripvlan",
"author_id": 349079,
"author_profile": "https://Stackoverflow.com/users/349079",
"pm_score": 3,
"selected": false,
"text": "DBCC ShrinkFile ({logicalLogName}, TRUNCATEONLY)"
},
{
"answer_id": 4584599,
"author": "Muhammad Imran",
"author_id": 561245,
"author_profile": "https://Stackoverflow.com/users/561245",
"pm_score": 1,
"selected": false,
"text": "USE DatabaseName\n\nGO\n\nDBCC SHRINKFILE( TransactionLogName, 1)\n\nBACKUP LOG DatabaseName WITH TRUNCATE_ONLY\n\nDBCC SHRINKFILE( TransactionLogName, 1)\n\nGO \n"
},
{
"answer_id": 4656532,
"author": "Peter Nazarov",
"author_id": 479858,
"author_profile": "https://Stackoverflow.com/users/479858",
"pm_score": -1,
"selected": false,
"text": "DECLARE @DB_Name nvarchar(255);\nDECLARE @DB_LogFileName nvarchar(255);\nSET @DB_Name = '<Database Name>'; --Input Variable\nSET @DB_LogFileName = '<LogFileEntryName>'; --Input Variable\nEXEC \n(\n'USE ['+@DB_Name+']; '+\n'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +\n'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2) ' +\n'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +\n'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2)'\n)\nGO\n"
},
{
"answer_id": 7952692,
"author": "Rui Lima",
"author_id": 565977,
"author_profile": "https://Stackoverflow.com/users/565977",
"pm_score": 8,
"selected": false,
"text": "-- DON'T FORGET TO BACKUP THE DB :D (Check [here][1]) \n\n\nUSE AdventureWorks2008R2;\nGO\n-- Truncate the log by changing the database recovery model to SIMPLE.\nALTER DATABASE AdventureWorks2008R2\nSET RECOVERY SIMPLE;\nGO\n-- Shrink the truncated log file to 1 MB.\nDBCC SHRINKFILE (AdventureWorks2008R2_Log, 1);\nGO\n-- Reset the database recovery model.\nALTER DATABASE AdventureWorks2008R2\nSET RECOVERY FULL;\nGO\n"
},
{
"answer_id": 14628788,
"author": "Rachel",
"author_id": 302677,
"author_profile": "https://Stackoverflow.com/users/302677",
"pm_score": 3,
"selected": false,
"text": "FULL BACKUP BACKUP LOG MyDatabaseName \nTO DISK='C:\\DatabaseBackups\\MyDatabaseName_backup_2013_01_31_095212_8797154.trn'\n\nDBCC SHRINKFILE (N'MyDatabaseName_Log', 200)\n"
},
{
"answer_id": 15476656,
"author": "Michael Dalton",
"author_id": 2182233,
"author_profile": "https://Stackoverflow.com/users/2182233",
"pm_score": 6,
"selected": false,
"text": "USE DATABASE_NAME;\nGO\n\nALTER DATABASE DATABASE_NAME\nSET RECOVERY SIMPLE;\nGO\n--First parameter is log file name and second is size in MB\nDBCC SHRINKFILE (DATABASE_NAME_Log, 1);\n\nALTER DATABASE DATABASE_NAME\nSET RECOVERY FULL;\nGO\n"
},
{
"answer_id": 18292136,
"author": "Aaron Bertrand",
"author_id": 61305,
"author_profile": "https://Stackoverflow.com/users/61305",
"pm_score": 11,
"selected": true,
"text": "FULL ALTER DATABASE testdb SET RECOVERY FULL;\n DECLARE @path NVARCHAR(255) = N'\\\\backup_share\\log\\testdb_' \n + CONVERT(CHAR(8), GETDATE(), 112) + '_'\n + REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','')\n + '.trn';\n\nBACKUP LOG foo TO DISK = @path WITH INIT, COMPRESSION;\n \\\\backup_share\\ SHRINKFILE USE [master];\nGO\nALTER DATABASE Test1 \n MODIFY FILE\n (NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB);\nGO\n USE yourdb;\nGO\nDBCC SHRINKFILE(yourdb_log, 200);\nGO\n SIMPLE ALTER DATABASE testdb SET RECOVERY SIMPLE;\n SIMPLE FULL CHECKPOINT CHECKPOINT USE yourdb;\nGO\nCHECKPOINT;\nGO\nCHECKPOINT; -- run twice to ensure file wrap-around\nGO\nDBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBs\nGO\n TRUNCATE_ONLY SHRINKFILE TRUNCATE_ONLY FULL DBCC SHRINKDATABASE DBCC SHRINKFILE ALTER DATABASE ... MODIFY FILE ALTER DATABASE"
},
{
"answer_id": 52846837,
"author": "hey",
"author_id": 2349661,
"author_profile": "https://Stackoverflow.com/users/2349661",
"pm_score": 0,
"selected": false,
"text": "alter database <database_name> set emergency;\nuse <database_name>;\ncheckpoint;\ncheckpoint;\nalter database <database_name> set online;\ndbcc shrinkfile(<database_name>_log, 200);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
56,630 |
<p>Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click <a href="http://news.slashdot.org/news/08/09/10/2257242.shtml" rel="nofollow noreferrer">here</a>.)</p>
<p>My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?</p>
|
[
{
"answer_id": 56759,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": true,
"text": "var MenuManager = Class.create({\n initialize: function initialize(menuElt) {\n this.menu = $(menuElt);\n this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };\n registerEvent(document, 'scroll', this.handleScroll.bind(this));\n this.handleScroll();\n },\n handleScroll: function handleScroll() {\n this.scrollOffset = document.viewport.getScrollOffsets().top;\n if (this.scrollOffset > this.homePosn.y) {\n this.menu.style.position = 'fixed';\n this.menu.style.top = 0;\n this.menu.style.left = this.homePosn.x;\n } else {\n this.menu.style.position = 'absolute';\n this.menu.style.top = null;\n this.menu.style.left = null;\n }\n }\n});\n"
},
{
"answer_id": 475955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "var TableHeaderManager = Class.create({\n initialize: function initialize(headerElt) {\n this.tableHeader = $(headerElt);\n this.homePosn = { x: this.tableHeader.cumulativeOffset()[0], y: this.tableHeader.cumulativeOffset()[1] };\n Event.observe(window, 'scroll', this.handleScroll.bind(this));\n this.handleScroll();\n },\n handleScroll: function handleScroll() {\n this.scrollOffset = document.viewport.getScrollOffsets().top;\n if (this.scrollOffset > this.homePosn.y) {\n this.tableHeader.style.position = 'fixed';\n this.tableHeader.style.top = 0;\n this.tableHeader.style.left = this.homePosn.x;\n } else {\n this.tableHeader.style.position = 'absolute';\n this.tableHeader.style.top = null;\n this.tableHeader.style.left = null;\n }\n }\n});\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257/"
] |
56,638 |
<p>I want to convert a number that is in <a href="https://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Time" rel="nofollow noreferrer">PRTime</a> format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a <code>DateTime</code>.</p>
<p>Note that this is slightly different than the usual "number of milliseconds since 1/1/1970".</p>
|
[
{
"answer_id": 56674,
"author": "Barry",
"author_id": 845,
"author_profile": "https://Stackoverflow.com/users/845",
"pm_score": 3,
"selected": true,
"text": "Dim prTimeInMillis As UInt64\nprTimeInMillis = prTime/1000\n\nDim prDateTime As New DateTime(1970, 1, 1)\nprDateTime = prDateTime.AddMilliseconds(prTimeInMillis)\n"
},
{
"answer_id": 56753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "private static DateTime epoch = new DateTime(1970, 1, 1);\n\nprivate static DateTime ConvertPrTime(long time)\n{\n return new DateTime(epoch.Ticks + (time*10), DateTimeKind.Utc);\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842864/"
] |
56,642 |
<p>I am building on C++ dll, by writing code in C#.</p>
<p>I get an error, saying </p>
<blockquote>
<p>LoaderLock was detected Message:
Attempting managed execution inside OS
Loader lock. Do not attempt to run
managed code inside a DllMain or image
initialization function since doing so
can cause the application to hang.</p>
</blockquote>
<p>I tried seraching what this error exactly means, but I am drawing pointless articles, mostly saying that it's just a warning, and I should switch that off in Visual Studio.
The other solutions seem to be due to ITunes, or this problem occurring when programming with DirectX. My problem is connected to neither.</p>
<p>Can anybody explain, what this actually means?</p>
|
[
{
"answer_id": 31322244,
"author": "Stefan Wanitzek",
"author_id": 1995301,
"author_profile": "https://Stackoverflow.com/users/1995301",
"pm_score": 2,
"selected": false,
"text": "m_ComObject = Activator.CreateInstance(Type.GetTypeFromProgID(\"Fancy.McDancy\"));\n ThreadStart threadRef = new ThreadStart(delegate { m_ComObject = Activator.CreateInstance(Type.GetTypeFromProgID(\"Fancy.McDancy\")); });\nThread myThread = new Thread(threadRef);\n\nmyThread.Start();\nmyThread.Join(); // for synchronization\n"
},
{
"answer_id": 36120918,
"author": "seva titov",
"author_id": 656346,
"author_profile": "https://Stackoverflow.com/users/656346",
"pm_score": 4,
"selected": false,
"text": "#pragma unmanaged #pragma unmanaged\n\nBOOL APIENTRY DllMain(HMODULE hModule,\n DWORD ul_reason_for_call,\n LPVOID lpReserved\n )\n{\n ... // your implementation here\n}\n #pragma unmanaged 1> Generating Code...\n1>E:\\src\\mixedmodedll\\dllmain.cpp : warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock, including the DLL entrypoint and calls reached from the DLL entrypoint\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/895/"
] |
56,644 |
<p>I want to automate a Windows 2000+ server reboot process using Task Scheduler or similar tool to remotely reboot a server and wait for it to come back up. I can issue <code>shutdown</code> or <code>psshutdown</code> to remotely reboot, but I want something better than <code>sleep</code> to wait for it to come back. I need to verify it is back online within <code>n</code> minutes or throw an error.</p>
<p>By 'back online', I would like to verify more than just that it can be pinged, but perhaps its RFC service is responding or some other determinate vital sign.</p>
<p>I'd prefer an NT script approach, but I'm not ruling out writing a custom tool to do this.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 56660,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "psservice \\\\someothermachine query spooler\n"
},
{
"answer_id": 56666,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "sc \"\\\\server_name\" query EventSystem\n"
},
{
"answer_id": 56719,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "psservice sc query findstr \"RUNNING\""
},
{
"answer_id": 148431,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 3,
"selected": false,
"text": "'\n' Remotely reboot a server and\n' wait for server to come back up.\n'\n' Usage: cscript /nologo /E:VBScript RebootWait.vbs <Server Name>\n'\n' Shawn Poulson, 2008.09.11\n'\n\n'\n' Get server name from command line\n'\nIf WScript.Arguments.Count <> 1 Then\n ShowUsage()\n WScript.Quit(1)\nEnd If\n\nServerName = WScript.Arguments(0)\n\n'\n' Verify server is currently up\n'\nWScript.StdOut.WriteLine Now & \": Verify server '\" & ServerName & \"' is currently up...\"\nIf Not IsAvailable(ServerName) Then\n WScript.StdOut.WriteLine \"Error: Server is down. Reboot aborted!\"\n WScript.Quit(1)\nEnd If\nWScript.StdOut.WriteLine Now & \": Server is up.\"\n\n'\n' Reboot server\n'\nWScript.StdOut.WriteLine Now & \": Rebooting server '\" & ServerName & \"'...\"\nRebootStatus = RebootServer(ServerName)\nIf RebootStatus < 0 Then\n WScript.StdOut.WriteLine \"Error: Reboot returned error \" & RebootStatus\n WScript.Quit(1)\nEnd If\nWScript.StdOut.WriteLine Now & \": Reboot command was successful\"\n\n'\n' Wait for server to come down\n'\nWScript.StdOut.Write Now & \": Waiting for server '\" & ServerName & \"' to go down...\"\nWaitCount = 0\nDo While IsAvailable(ServerName)\n WaitCount = WaitCount + 1\n If WaitCount > 60 Then ' 5 min timeout\n WScript.StdOut.WriteLine \"Error: Timeout waiting for server to come down!\"\n WScript.Quit(1)\n End If\n WScript.StdOut.Write(\".\")\n WScript.Sleep(5000)\nLoop\nWScript.StdOut.WriteLine \"Success!\"\nWScript.StdOut.WriteLine Now & \": Server is down.\"\n\n'\n' Wait for server to come back up\n'\nWScript.StdOut.Write Now & \": Waiting for server '\" & ServerName & \"' to come back up...\"\nWaitCount = 0\nDo While Not IsAvailable(ServerName)\n WaitCount = WaitCount + 1\n If WaitCount > 240 Then ' 20 min timeout\n WScript.StdOut.WriteLine \"Error: Timeout waiting for server to come back up!\"\n WScript.Quit(1)\n End If\n WScript.StdOut.Write(\".\")\n WScript.Sleep(5000)\nLoop\nWScript.StdOut.WriteLine \"Success!\"\nWScript.StdOut.WriteLine Now & \": Server is back up after reboot.\"\n\n'\n' Success!\n'\nWScript.Quit(0)\n\n\nSub ShowUsage()\n WScript.Echo \"Usage: \" & WScript.ScriptName & \" <Server name>\"\nEnd Sub\n\n' Returns:\n' 1 = Successfully issued reboot command\n' -2 = Could not reach server\n' -3 = Reboot command failed\nFunction RebootServer(ServerName)\n Dim OpSystem\n On Error Resume Next\n For Each OpSystem in GetObject(\"winmgmts:{(Shutdown)}!\\\\\" & ServerName & \"\\root\\CIMV2\").ExecQuery(\"select * from Win32_OperatingSystem where Primary=true\")\n On Error GoTo 0\n\n If IsObject(OpSystem) Then\n ' Invoke forced reboot\n If OpSystem.Win32Shutdown(6, 0) = 0 Then\n ' Success\n RebootServer = 1\n Else\n ' Command failed\n RebootServer = -3\n End If\n\n Else\n RebootServer = -2\n\n End If\n Next\nEnd Function\n\n' Return True if available\nFunction IsAvailable(ServerName)\n ' Use Windows RPC service state as vital sign\n IsAvailable = (GetServiceState(ServerName, \"RpcSs\") = \"Running\")\nEnd Function\n\n' Return one of:\n' Stopped, Start Pending, Stop Pending,\n' Running, Continue Pending, Pause Pending,\n' Paused, Unknown\nFunction GetServiceState(ServerName, ServiceName)\n Dim Service\n On Error Resume Next\n Set Service = GetObject(\"winmgmts:\\\\\" & ServerName & \"\\root\\CIMV2:Win32_Service='\" & ServiceName & \"'\")\n On Error GoTo 0\n If IsObject(Service) Then GetServiceState = Service.State\nEnd Function\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
] |
56,648 |
<p>If you have an <code>NSMutableArray</code>, how do you shuffle the elements randomly?</p>
<p>(I have my own answer for this, which is posted below, but I'm new to Cocoa and I'm interested to know if there is a better way.)</p>
<hr>
<p>Update: As noted by @Mukesh, as of iOS 10+ and macOS 10.12+, there is an <code>-[NSMutableArray shuffledArray]</code> method that can be used to shuffle. See <a href="https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc" rel="noreferrer">https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc</a> for details. (But note that this creates a new array, rather than shuffling the elements in place.)</p>
|
[
{
"answer_id": 56656,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 8,
"selected": false,
"text": "(arc4random() % nElements) arc4random_uniform(nElements) // NSMutableArray_Shuffling.h\n\n#if TARGET_OS_IPHONE\n#import <UIKit/UIKit.h>\n#else\n#include <Cocoa/Cocoa.h>\n#endif\n\n// This category enhances NSMutableArray by providing\n// methods to randomly shuffle the elements.\n@interface NSMutableArray (Shuffling)\n- (void)shuffle;\n@end\n\n\n// NSMutableArray_Shuffling.m\n\n#import \"NSMutableArray_Shuffling.h\"\n\n@implementation NSMutableArray (Shuffling)\n\n- (void)shuffle\n{\n NSUInteger count = [self count];\n if (count <= 1) return;\n for (NSUInteger i = 0; i < count - 1; ++i) {\n NSInteger remainingCount = count - i;\n NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);\n [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];\n }\n}\n\n@end\n"
},
{
"answer_id": 1299049,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "int randomSort(id obj1, id obj2, void *context ) {\n // returns random number -1 0 1\n return (random()%3 - 1); \n}\n\n- (void)shuffle {\n // call custom sort function\n [puzzles sortUsingFunction:randomSort context:nil];\n\n // show in log how is our array sorted\n int i = 0;\n for (Puzzle * puzzle in puzzles) {\n NSLog(@\" #%d has index %d\", i, puzzle.index);\n i++;\n }\n}\n #0 has index #6\n #1 has index #3\n #2 has index #9\n #3 has index #15\n #4 has index #8\n #5 has index #0\n #6 has index #1\n #7 has index #4\n #8 has index #7\n #9 has index #12\n #10 has index #14\n #11 has index #16\n #12 has index #17\n #13 has index #10\n #14 has index #11\n #15 has index #13\n #16 has index #5\n #17 has index #2\n"
},
{
"answer_id": 10334720,
"author": "kal",
"author_id": 1358836,
"author_profile": "https://Stackoverflow.com/users/1358836",
"pm_score": -1,
"selected": false,
"text": "NSUInteger randomIndex = arc4random() % [theArray count];\n"
},
{
"answer_id": 10874468,
"author": "gregoltsov",
"author_id": 1226722,
"author_profile": "https://Stackoverflow.com/users/1226722",
"pm_score": 5,
"selected": false,
"text": "arc4random_uniform() // NSMutableArray+Shuffling.h\n#import <Foundation/Foundation.h>\n\n/** This category enhances NSMutableArray by providing methods to randomly\n * shuffle the elements using the Fisher-Yates algorithm.\n */\n@interface NSMutableArray (Shuffling)\n- (void)shuffle;\n@end\n\n// NSMutableArray+Shuffling.m\n#import \"NSMutableArray+Shuffling.h\"\n\n@implementation NSMutableArray (Shuffling)\n\n- (void)shuffle\n{\n NSUInteger count = [self count];\n for (uint i = 0; i < count - 1; ++i)\n {\n // Select a random element between i and end of array to swap with.\n int nElements = count - i;\n int n = arc4random_uniform(nElements) + i;\n [self exchangeObjectAtIndex:i withObjectAtIndex:n];\n }\n}\n\n@end\n"
},
{
"answer_id": 18789993,
"author": "Denis Kutlubaev",
"author_id": 751641,
"author_profile": "https://Stackoverflow.com/users/751641",
"pm_score": 2,
"selected": false,
"text": "#import <SSCategories.h>\nNSMutableArray *tableData = [NSMutableArray arrayWithArray:[temp shuffledArray]];\n"
},
{
"answer_id": 22558992,
"author": "Gamma-Point",
"author_id": 275047,
"author_profile": "https://Stackoverflow.com/users/275047",
"pm_score": 1,
"selected": false,
"text": "sequenceSelected - (void)shuffleSequenceSelected {\n [sequenceSelected shuffle];\n [self shuffleSequenceSelectedLoop];\n}\n\n- (void)shuffleSequenceSelectedLoop {\n NSUInteger count = sequenceSelected.count;\n for (NSUInteger i = 1; i < count-1; i++) {\n // Select a random element between i and end of array to swap with.\n NSInteger nElements = count - i;\n NSInteger n;\n if (i < count-2) { // i is between second and second last element\n obj *A = [sequenceSelected objectAtIndex:i-1];\n obj *B = [sequenceSelected objectAtIndex:i];\n if (A == B) { // shuffle if current & previous same\n do {\n n = arc4random_uniform(nElements) + i;\n B = [sequenceSelected objectAtIndex:n];\n } while (A == B);\n [sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:n];\n }\n } else if (i == count-2) { // second last value to be shuffled with last value\n obj *A = [sequenceSelected objectAtIndex:i-1];// previous value\n obj *B = [sequenceSelected objectAtIndex:i]; // second last value\n obj *C = [sequenceSelected lastObject]; // last value\n if (A == B && B == C) {\n //reshufle\n sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];\n [self shuffleSequenceSelectedLoop];\n return;\n }\n if (A == B) {\n if (B != C) {\n [sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:count-1];\n } else {\n // reshuffle\n sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];\n [self shuffleSequenceSelectedLoop];\n return;\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 26380905,
"author": "fcortes",
"author_id": 1016865,
"author_profile": "https://Stackoverflow.com/users/1016865",
"pm_score": -1,
"selected": false,
"text": "shuffle() - (void)shuffle\n{\n NSUInteger count = [self count];\n for (NSUInteger i = 0; i < count; ++i) {\n NSInteger exchangeIndex = arc4random_uniform(count);\n if (i != exchangeIndex) {\n [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];\n }\n }\n}\n"
},
{
"answer_id": 28414220,
"author": "uucp",
"author_id": 4547023,
"author_profile": "https://Stackoverflow.com/users/4547023",
"pm_score": -1,
"selected": false,
"text": "- (NSArray *)shuffledArray:(NSArray *)array\n{\n return [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {\n if (arc4random() % 2) {\n return NSOrderedAscending;\n } else {\n return NSOrderedDescending;\n }\n }];\n}\n"
},
{
"answer_id": 33840745,
"author": "Cœur",
"author_id": 1033581,
"author_profile": "https://Stackoverflow.com/users/1033581",
"pm_score": 4,
"selected": false,
"text": "@implementation NSMutableArray (Shuffle)\n// Fisher-Yates shuffle\n- (void)shuffle\n{\n for (NSUInteger i = self.count; i > 1; i--)\n [self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)];\n}\n@end\n extension Array {\n /// Fisher-Yates shuffle\n mutating func shuffle() {\n for i in stride(from: count - 1, to: 0, by: -1) {\n swapAt(i, Int(arc4random_uniform(UInt32(i + 1))))\n }\n }\n}\n extension Array {\n /// Fisher-Yates shuffle\n mutating func shuffle() {\n for i in stride(from: count - 1, to: 0, by: -1) {\n let j = Int(arc4random_uniform(UInt32(i + 1)))\n (self[i], self[j]) = (self[j], self[i])\n }\n }\n}\n GameplayKit"
},
{
"answer_id": 40613895,
"author": "andreacipriani",
"author_id": 872908,
"author_profile": "https://Stackoverflow.com/users/872908",
"pm_score": 4,
"selected": false,
"text": "GameplayKit shuffled let shuffledArray = array.shuffled()\n"
},
{
"answer_id": 43801201,
"author": "Cœur",
"author_id": 1033581,
"author_profile": "https://Stackoverflow.com/users/1033581",
"pm_score": 2,
"selected": false,
"text": "shuffled() import GameplayKit\n\nextension Array {\n @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)\n func shuffled() -> [Element] {\n return (self as NSArray).shuffled() as! [Element]\n }\n @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)\n mutating func shuffle() {\n replaceSubrange(0..<count, with: shuffled())\n }\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
56,657 |
<p>I am curious whether it is OK to copy a directory that is under version control and start working on both copies.</p>
<p>I know it can be different from one VCS to another, but I intentionally don't specify any VCS since I am curious about different cases.</p>
<p>I was talking to a coworker recently about doing it in SVN. I think it should be OK, but I am still not 100% sure, since I don't know what exactly SVN is storing in the working copy.</p>
<p>However, if we talk about the DVCS world, things might be even more unclear, since every working copy is a repository by itself. Being faced with doing this in bzr now, I decided to ask the question.</p>
<p>Later edit:</p>
<p>Some people asked why I would want to do that. Here is the whole story:</p>
<p>In the case of SVN it was because being out of the office, the connection to the SVN server was really slow, so me and my coworker decided to check out the sources only once and make a local copy. That's what we did and it worked OK, but I am still wondering whether it is guaranteed to work, or it just happened.</p>
<p>In the bzr case, I am planning to move the "main" repo to another server. So I was thinking to just copy it there and start considering that the main repo. I guess the safest is to make a clone though.</p>
|
[
{
"answer_id": 56792,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": ".svn .svn clean up switch .svn svn"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] |
56,658 |
<h3>Summary</h3>
<p>What's the best way to ensure a table cell cannot be less than a certain minimum width. </p>
<h3>Example</h3>
<p>I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.</p>
<h3>Browser compatibility</h3>
<p>I possible I would like to find a solution that works in</p>
<ul>
<li>IE 6-8</li>
<li>FF 2-3</li>
<li>Safari</li>
</ul>
<p>In order of preference.</p>
|
[
{
"answer_id": 56663,
"author": "James B",
"author_id": 2951,
"author_profile": "https://Stackoverflow.com/users/2951",
"pm_score": 7,
"selected": true,
"text": "td { min-width: 100px; }\n"
},
{
"answer_id": 56667,
"author": "Jeffrey04",
"author_id": 5742,
"author_profile": "https://Stackoverflow.com/users/5742",
"pm_score": 2,
"selected": false,
"text": "min-width: 100px\n nowrap=\"nowrap\"\n"
},
{
"answer_id": 56738,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "td {\n min-width: 100px;\n _width: 100px;/* IE6 hack */\n}\n"
},
{
"answer_id": 1007998,
"author": "Dean Peters",
"author_id": 441512,
"author_profile": "https://Stackoverflow.com/users/441512",
"pm_score": 2,
"selected": false,
"text": " min-width: 193px;\n width:auto !important; \n _width: 193px; /* IE6 hack */\n"
},
{
"answer_id": 5098023,
"author": "Prof",
"author_id": 629157,
"author_profile": "https://Stackoverflow.com/users/629157",
"pm_score": 2,
"selected": false,
"text": "{\nwidth (or height): auto !important;\nwidth (or height): 200px;\nmin-width (or min-height): 200px;\n}\n"
},
{
"answer_id": 7225831,
"author": "Partack",
"author_id": 478222,
"author_profile": "https://Stackoverflow.com/users/478222",
"pm_score": 3,
"selected": false,
"text": "<div> <td> <div> min-width <div>"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
] |
56,677 |
<p>I have 150+ SQL queries in separate text files that I need to analyze (just the actual SQL code, not the data results) in order to identify all column names and table names used. Preferably with the number of times each column and table makes an appearance. Writing a brand new SQL parsing program is trickier than is seems, with nested SELECT statements and the like. </p>
<p>There has to be a program, or code out there that does this (or something close to this), but I have not found it.</p>
|
[
{
"answer_id": 309912,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 2,
"selected": false,
"text": "SELECT TOP 0 * FROM MY_TABLE\n"
},
{
"answer_id": 50530231,
"author": "Dexygen",
"author_id": 34806,
"author_profile": "https://Stackoverflow.com/users/34806",
"pm_score": 0,
"selected": false,
"text": "FETCH FIRST 1 ROW ONLY"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5854/"
] |
56,680 |
<p>I have been writing Flex applications for a few months now and luckily have not needed a full debugger as of yet, so far I have just used a few Alert boxes...</p>
<p>Is there an available debugger that is included in the free Flex SDK? I am not using FlexBuilder (I have been using Emacs and compiling with ant).</p>
<p>If not, how do you debug Flex applications without FlexBuilder? (note: I have no intentions of using flexbuilder)</p>
|
[
{
"answer_id": 56929,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 4,
"selected": true,
"text": "fdb"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
56,684 |
<p>I want Windows Update to automatically download and install updates on my Vista machine, however I don't want to be bothered by the system tray reboot prompts (which can, at best, only be postponed by 4 hours).</p>
<p>I have performed the registry hack described <a href="http://www.howtogeek.com/howto/windows-vista/prevent-windows-update-from-forcibly-rebooting-your-computer/" rel="noreferrer">here</a> to prevent Windows forcibly rebooting my machine, which is a good start. However, is there any way to get rid of the reboot prompts altogether, or decrease their frequency?</p>
|
[
{
"answer_id": 56691,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " sc stop wuauserv \n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
] |
56,687 |
<p>In our application, we are using RMI for client-server communication in very different ways:</p>
<ol>
<li>Pushing data from the server to the client to be displayed.</li>
<li>Sending control information from the client to the server.</li>
<li>Callbacks from those control messages code paths that reach back from the server to the client (sidebar note - this is a side-effect of some legacy code and is not our long-term intent).</li>
</ol>
<p>What we would like to do is ensure that all of our RMI-related code will use only a known specified inventory of ports. This includes the registry port (commonly expected to be 1099), the server port and any ports resulting from the callbacks.</p>
<p>Here is what we already know:</p>
<ol>
<li>LocateRegistry.getRegistry(1099) or Locate.createRegistry(1099) will ensure that the registry is listening in on 1099.</li>
<li>Using the UnicastRemoteObject constructor / exportObject static method with a port argument will specify the server port.</li>
</ol>
<p>These points are also covered in this <a href="http://forums.sun.com/thread.jspa?threadID=370039&messageID=1566073" rel="noreferrer">Sun forum post</a>. </p>
<p>What we don't know is: how do we ensure that the client connections back to the server resulting from the callbacks will only connect on a specified port rather than defaulting to an anonymous port?</p>
<p>EDIT: Added a longish answer summarizing my findings and how we solved the problem. Hopefully, this will help anyone else with similar issues.</p>
<p>SECOND EDIT: It turns out that in my application, there seems to be a race condition in my creation and modification of socket factories. I had wanted to allow the user to override my default settings in a Beanshell script. Sadly, it appears that my script is being run significantly after the first socket is created by the factory. As a result, I'm getting a mix of ports from the set of defaults and the user settings. More work will be required that's out of the scope of this question but I thought I would point it out as a point of interest for others who might have to tread these waters at some point....</p>
|
[
{
"answer_id": 303081,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 1,
"selected": false,
"text": "UnicastRemoteObject public class RemoteObjectWrapped extends UnicastRemoteObject {\n// ....\nprivate RemoteObjectWrapped(final boolean callback) throws RemoteException {\n super((callback ? RemoteConnectionParameters.getCallbackPort() : RemoteConnectionParameters.getServerSidePort()),\n (callback ? CALLBACK_CLIENT_SOCKET_FACTORY : CLIENT_SOCKET_FACTORY),\n (callback ? CALLBACK_SERVER_SOCKET_FACTORY : SERVER_SOCKET_FACTORY));\n}\n// ....\n}\n public class SpecifiedServerSocketFactory implements RMIServerSocketFactory {\n/** Always use this port when specified. */\nprivate int serverPort;\n/**\n * @param ignoredPort This port is ignored. \n * @return a {@link ServerSocket} if we managed to create one on the correct port.\n * @throws java.io.IOException\n */\n@Override\npublic ServerSocket createServerSocket(final int ignoredPort) throws IOException {\n try {\n final ServerSocket serverSocket = new ServerSocket(this.serverPort);\n return serverSocket;\n } catch (IOException ioe) {\n throw new IOException(\"Failed to open server socket on port \" + serverPort, ioe);\n }\n}\n// ....\n}\n public class SpecifiedClientSocketFactory implements RMIClientSocketFactory, Serializable {\n/** Serialization hint */\npublic static final long serialVersionUID = 1L;\n/** This is the remote port to which we will always connect. */\nprivate int remotePort;\n/** Storing the host just for reference. */\nprivate String remoteHost = \"HOST NOT YET SET\";\n// ....\n/**\n * @param host The host to which we are trying to connect\n * @param ignoredPort This port is ignored. \n * @return A new Socket if we managed to create one to the host.\n * @throws java.io.IOException\n */\n@Override\npublic Socket createSocket(final String host, final int ignoredPort) throws IOException {\n try {\n final Socket socket = new Socket(host, remotePort);\n this.remoteHost = host;\n return socket;\n } catch (IOException ioe) {\n throw new IOException(\"Failed to open a socket back to host \" + host + \" on port \" + remotePort, ioe);\n }\n}\n// ....\n}\n"
},
{
"answer_id": 2455094,
"author": "Iraklis",
"author_id": 172467,
"author_profile": "https://Stackoverflow.com/users/172467",
"pm_score": 0,
"selected": false,
"text": "System.getProperties().put(\"java.rmi.server.hostname\", IP 80.80.80.10);\nMyService rmiserver = new MyService();\nMyService stub = (MyService) UnicastRemoteObject.exportObject(rmiserver, 6620);\nLocateRegistry.createRegistry(1099);\nRegistry registry = LocateRegistry.getRegistry();\nregistry.rebind(\"FAManagerService\", stub);\n System.getProperties().put(\"java.rmi.server.hostname\", 70.70.70.20);\nUnicastRemoteObject.exportObject(this, 1999);\nMyService server = (MyService) Naming.lookup(\"rmi://\" + serverIP + \"/MyService \");\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5812/"
] |
56,692 |
<p>Consider the class below that represents a Broker:</p>
<pre><code>public class Broker
{
public string Name = string.Empty;
public int Weight = 0;
public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}
</code></pre>
<p>I'd like to randomly select a Broker from an array, taking into account their weights.</p>
<p>What do you think of the code below?</p>
<pre><code>class Program
{
private static Random _rnd = new Random();
public static Broker GetBroker(List<Broker> brokers, int totalWeight)
{
// totalWeight is the sum of all brokers' weight
int randomNumber = _rnd.Next(0, totalWeight);
Broker selectedBroker = null;
foreach (Broker broker in brokers)
{
if (randomNumber <= broker.Weight)
{
selectedBroker = broker;
break;
}
randomNumber = randomNumber - broker.Weight;
}
return selectedBroker;
}
static void Main(string[] args)
{
List<Broker> brokers = new List<Broker>();
brokers.Add(new Broker("A", 10));
brokers.Add(new Broker("B", 20));
brokers.Add(new Broker("C", 20));
brokers.Add(new Broker("D", 10));
// total the weigth
int totalWeight = 0;
foreach (Broker broker in brokers)
{
totalWeight += broker.Weight;
}
while (true)
{
Dictionary<string, int> result = new Dictionary<string, int>();
Broker selectedBroker = null;
for (int i = 0; i < 1000; i++)
{
selectedBroker = GetBroker(brokers, totalWeight);
if (selectedBroker != null)
{
if (result.ContainsKey(selectedBroker.Name))
{
result[selectedBroker.Name] = result[selectedBroker.Name] + 1;
}
else
{
result.Add(selectedBroker.Name, 1);
}
}
}
Console.WriteLine("A\t\t" + result["A"]);
Console.WriteLine("B\t\t" + result["B"]);
Console.WriteLine("C\t\t" + result["C"]);
Console.WriteLine("D\t\t" + result["D"]);
result.Clear();
Console.WriteLine();
Console.ReadLine();
}
}
}
</code></pre>
<p>I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.</p>
<p>Is there a more accurate algorithm?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 56735,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "< <= if (randomNumber < broker.Weight)\n totalWeight"
},
{
"answer_id": 57508,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "List<Broker> brokers = new List<Broker>();\nfor (int i=0; i<10; i++)\n brokers.Add(new Broker(\"A\", 10));\nfor (int i=0; i<20; i++)\n brokers.Add(new Broker(\"B\", 20));\nfor (int i=0; i<20; i++)\n brokers.Add(new Broker(\"C\", 20));\nfor (int i=0; i<10; i++)\n brokers.Add(new Broker(\"D\", 10));\n int randomNumber = _rnd.Next(0, brokers.length);\nselectedBroker = brokers[randomNumber];\n"
},
{
"answer_id": 58113,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Broker selected = null;\nint s = 0;\nforeach(Broker broker in brokers) {\n s += broker.Weight;\n if (broker.Weight <= _rnd.Next(0,s)) {\n selected = broker;\n }\n}\n"
},
{
"answer_id": 3899874,
"author": "Cagatay",
"author_id": 425885,
"author_profile": "https://Stackoverflow.com/users/425885",
"pm_score": 4,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n var books = new List<Book> {\n new Book{Isbn=1,Name=\"A\",Weight=1},\n new Book{Isbn=2,Name=\"B\",Weight=100},\n new Book{Isbn=3,Name=\"C\",Weight=1000},\n new Book{Isbn=4,Name=\"D\",Weight=10000},\n new Book{Isbn=5,Name=\"E\",Weight=100000}};\n\n Book randomlySelectedBook = WeightedRandomization.Choose(books);\n }\n}\n\npublic static class WeightedRandomization\n{\n public static T Choose<T>(List<T> list) where T : IWeighted\n {\n if (list.Count == 0)\n {\n return default(T);\n }\n\n int totalweight = list.Sum(c => c.Weight);\n Random rand = new Random();\n int choice = rand.Next(totalweight);\n int sum = 0;\n\n foreach (var obj in list)\n {\n for (int i = sum; i < obj.Weight + sum; i++)\n {\n if (i >= choice)\n {\n return obj;\n }\n }\n sum += obj.Weight;\n }\n\n return list.First();\n }\n}\n\npublic interface IWeighted\n{\n int Weight { get; set; }\n}\n\npublic class Book : IWeighted\n{\n public int Isbn { get; set; }\n public string Name { get; set; }\n public int Weight { get; set; }\n}\n"
},
{
"answer_id": 8720099,
"author": "Jordan",
"author_id": 443602,
"author_profile": "https://Stackoverflow.com/users/443602",
"pm_score": 0,
"selected": false,
"text": "public static class WeightedEx\n{\n /// <summary>\n /// Select an item from the given sequence according to their respective weights.\n /// </summary>\n /// <typeparam name=\"TItem\">Type of item item in the given sequence.</typeparam>\n /// <param name=\"a_source\">Given sequence of weighted items.</param>\n /// <returns>Randomly picked item.</returns>\n public static TItem PickWeighted<TItem>(this IEnumerable<TItem> a_source)\n where TItem : IWeighted\n {\n if (!a_source.Any())\n return default(TItem);\n\n var source= a_source.OrderBy(i => i.Weight);\n\n double dTotalWeight = source.Sum(i => i.Weight);\n\n Random rand = new Random();\n\n while (true)\n {\n double dRandom = rand.NextDouble() * dTotalWeight;\n\n foreach (var item in source)\n {\n if (dRandom < item.Weight)\n return item;\n\n dRandom -= item.Weight;\n }\n }\n }\n}\n\n/// <summary>\n/// IWeighted: Implementation of an item that is weighted.\n/// </summary>\npublic interface IWeighted\n{\n double Weight { get; }\n}\n"
},
{
"answer_id": 11930875,
"author": "necrogt4",
"author_id": 1594818,
"author_profile": "https://Stackoverflow.com/users/1594818",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Linq;\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic static class IEnumerableExtensions {\n \n public static T RandomElementByWeight<T>(this IEnumerable<T> sequence, Func<T, float> weightSelector) {\n float totalWeight = sequence.Sum(weightSelector);\n // The weight we are after...\n float itemWeightIndex = (float)new Random().NextDouble() * totalWeight;\n float currentWeightIndex = 0;\n\n foreach(var item in from weightedItem in sequence select new { Value = weightedItem, Weight = weightSelector(weightedItem) }) {\n currentWeightIndex += item.Weight;\n \n // If we've hit or passed the weight we are after for this item then it's the one we want....\n if(currentWeightIndex >= itemWeightIndex)\n return item.Value;\n \n }\n \n return default(T);\n \n }\n \n}\n Dictionary<string, float> foo = new Dictionary<string, float>();\n foo.Add(\"Item 25% 1\", 0.5f);\n foo.Add(\"Item 25% 2\", 0.5f);\n foo.Add(\"Item 50%\", 1f);\n \n for(int i = 0; i < 10; i++)\n Console.WriteLine(this, \"Item Chosen {0}\", foo.RandomElementByWeight(e => e.Value));\n"
},
{
"answer_id": 30948171,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 3,
"selected": false,
"text": "IWeightedRandomizer<string> randomizer = new DynamicWeightedRandomizer<string>();\nrandomizer[\"Joe\"] = 1;\nrandomizer[\"Ryan\"] = 2;\nrandomizer[\"Jason\"] = 2;\n\nstring name1 = randomizer.RandomWithReplacement();\n//name1 has a 20% chance of being \"Joe\", 40% of \"Ryan\", 40% of \"Jason\"\n\nstring name2 = randomizer.RandomWithRemoval();\n//Same as above, except whichever one was chosen has been removed from the list.\n"
},
{
"answer_id": 37174530,
"author": "Lord of the Goo",
"author_id": 277389,
"author_profile": "https://Stackoverflow.com/users/277389",
"pm_score": 0,
"selected": false,
"text": " // Author: Giovanni Costagliola <[email protected]>\n\n using System;\n using System.Collections.Generic;\n using System.Linq;\n\n namespace Utils\n {\n /// <summary>\n /// Represent a Weighted Item.\n /// </summary>\n public interface IWeighted\n {\n /// <summary>\n /// A positive weight. It's up to the implementer ensure this requirement\n /// </summary>\n int Weight { get; }\n }\n\n /// <summary>\n /// Pick up an element reflecting its weight.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n public class RandomWeightedPicker<T> where T:IWeighted\n {\n private readonly IEnumerable<T> items;\n private readonly int totalWeight;\n private Random random = new Random();\n\n /// <summary>\n /// Initiliaze the structure. O(1) or O(n) depending by the options, default O(n).\n /// </summary>\n /// <param name=\"items\">The items</param>\n /// <param name=\"checkWeights\">If <c>true</c> will check that the weights are positive. O(N)</param>\n /// <param name=\"shallowCopy\">If <c>true</c> will copy the original collection structure (not the items). Keep in mind that items lifecycle is impacted.</param>\n public RandomWeightedPicker(IEnumerable<T> items, bool checkWeights = true, bool shallowCopy = true)\n {\n if (items == null) throw new ArgumentNullException(\"items\");\n if (!items.Any()) throw new ArgumentException(\"items cannot be empty\");\n if (shallowCopy)\n this.items = new List<T>(items);\n else\n this.items = items;\n if (checkWeights && this.items.Any(i => i.Weight <= 0))\n {\n throw new ArgumentException(\"There exists some items with a non positive weight\");\n }\n totalWeight = this.items.Sum(i => i.Weight);\n }\n /// <summary>\n /// Pick a random item based on its chance. O(n)\n /// </summary>\n /// <param name=\"defaultValue\">The value returned in case the element has not been found</param>\n /// <returns></returns>\n public T PickAnItem()\n {\n int rnd = random.Next(totalWeight);\n return items.First(i => (rnd -= i.Weight) < 0);\n }\n\n /// <summary>\n /// Resets the internal random generator. O(1)\n /// </summary>\n /// <param name=\"seed\"></param>\n public void ResetRandomGenerator(int? seed)\n {\n random = seed.HasValue ? new Random(seed.Value) : new Random();\n }\n }\n}\n"
},
{
"answer_id": 55612460,
"author": "user2796283",
"author_id": 2796283,
"author_profile": "https://Stackoverflow.com/users/2796283",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class WeightedList<T>\n{\n private readonly Dictionary<T,int> _items = new Dictionary<T,int>();\n\n // Doesn't allow items with zero weight; to remove an item, set its weight to zero\n public void SetWeight(T item, int weight)\n {\n if (_items.ContainsKey(item))\n {\n if (weight != _items[item])\n {\n if (weight > 0)\n {\n _items[item] = weight;\n }\n else\n {\n _items.Remove(item);\n }\n\n _totalWeight = null; // Will recalculate the total weight later\n }\n }\n else if (weight > 0)\n {\n _items.Add(item, weight);\n\n _totalWeight = null; // Will recalculate the total weight later\n }\n }\n\n public int GetWeight(T item)\n {\n return _items.ContainsKey(item) ? _items[item] : 0;\n }\n\n private int? _totalWeight;\n public int totalWeight\n {\n get\n {\n if (!_totalWeight.HasValue) _totalWeight = _items.Sum(x => x.Value);\n\n return _totalWeight.Value;\n }\n }\n\n public T Random\n {\n get\n {\n var temp = 0;\n var random = new Random().Next(totalWeight);\n\n foreach (var item in _items)\n {\n temp += item.Value;\n\n if (random < temp) return item.Key;\n }\n\n throw new Exception($\"unable to determine random {typeof(T)} at {random} in {totalWeight}\");\n }\n }\n}\n"
},
{
"answer_id": 60995361,
"author": "zhe",
"author_id": 90180,
"author_profile": "https://Stackoverflow.com/users/90180",
"pm_score": 2,
"selected": false,
"text": "public static class RandomTools\n{\n public static T PickRandomItemWeighted<T>(IList<(T Item, int Weight)> items)\n {\n if ((items?.Count ?? 0) == 0)\n {\n return default;\n }\n\n int offset = 0;\n (T Item, int RangeTo)[] rangedItems = items\n .OrderBy(item => item.Weight)\n .Select(entry => (entry.Item, RangeTo: offset += entry.Weight))\n .ToArray();\n\n int randomNumber = new Random().Next(items.Sum(item => item.Weight)) + 1;\n return rangedItems.First(item => randomNumber <= item.RangeTo).Item;\n }\n}\n"
},
{
"answer_id": 71134909,
"author": "RWolfe",
"author_id": 3915050,
"author_profile": "https://Stackoverflow.com/users/3915050",
"pm_score": 0,
"selected": false,
"text": "private static Random _Rng = new Random();\npublic static Broker GetBroker(List<Broker> brokers){\n List<Broker> weightedBrokerList = new List<Broker>();\n foreach(Broker broker in brokers) {\n for(int i=0;i<broker.Weight;i++) {\n weightedBrokerList.Add(broker);\n }\n }\n return weightedBrokerList[_Rng.Next(weightedBrokerList.Count)];\n}\n"
},
{
"answer_id": 72568836,
"author": "Chris",
"author_id": 8291038,
"author_profile": "https://Stackoverflow.com/users/8291038",
"pm_score": 2,
"selected": false,
"text": "O(1) O(n) O(n) IList WeightedList<string> myList = new();\nmyList.Add(\"Hello\", 1);\nmyList.Add(\"World\", 2);\nConsole.WriteLine(myList.Next()); // Hello 33%, World 66%\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868/"
] |
56,708 |
<p>What would be the best way to write Objective-C on the Windows platform?</p>
<p>Cygwin and gcc? Is there a way I can somehow integrate this into Visual Studio?</p>
<p>Along those lines - are there any suggestions as to how to link in and use the Windows SDK for something like this. Its a different beast but I know I can write assembly and link in the Windows DLLs giving me accessibility to those calls but I don't know how to do this without googling and getting piecemeal directions.</p>
<p>Is anyone aware of a good online or book resource to do or explain these kinds of things?</p>
|
[
{
"answer_id": 9849288,
"author": "teshguru",
"author_id": 1246951,
"author_profile": "https://Stackoverflow.com/users/1246951",
"pm_score": 6,
"selected": false,
"text": "GNUstep MSYS Subsystem GNUstep Core GNUstep Devel C:\\GNUstep\\GNUstep\\System\\Library\\Headers\\Foundation Foundation.h gcc -v GNUstep MSYS bin GNUstep MSYS PATH #include <Foundation/Foundation.h>\n\nint main(void)\n{\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n NSLog(@\"Hello World!.\");\n [pool drain];\n return;\n}\n cd gcc -o helloworld.exe <HELLOWORLD>.m -I /GNUstep/GNUstep/System/Library/Headers -L /GNUstep/GNUstep/System/Library/Libraries -std=c99 -lobjc -lgnustep-base -fconstant-string-class=NSConstantString\n helloworld"
},
{
"answer_id": 12851935,
"author": "Ephemera",
"author_id": 1618592,
"author_profile": "https://Stackoverflow.com/users/1618592",
"pm_score": 3,
"selected": false,
"text": "gcc MyFile.m -lobjc -std=c99 -fobjc-exceptions -fconstant-string-class=clsname (etc, additional flags, see documentation) -mwindows g++ -mwindows MyFile.cpp"
},
{
"answer_id": 35720947,
"author": "Bass",
"author_id": 1343979,
"author_profile": "https://Stackoverflow.com/users/1343979",
"pm_score": 0,
"selected": false,
"text": "ctags --langmap=ObjectiveC:.m.h etags Makefile"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910/"
] |
56,722 |
<p>Just got a request from my boss for an application I'm working on. Basically we're getting an email address setup for an external client to submit excel files to. </p>
<p>What I need is a way to automatically pick up any email sent to this address, so I can take the attachment, process it and save it to a folder.</p>
<p>Any information of even where to start would be helpful.\</p>
<p>Note: We're using a lotus notes server to do this, but a generic way would be more helpful (If possible).</p>
|
[
{
"answer_id": 76684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Dim doc As NotesDocument\nDim rtitem As Variant\n'...set value of doc...\nSet rtitem = doc.GetFirstItem( \"Body\" )\nIf ( rtitem.Type = RICHTEXT ) Then\n Forall o In rtitem.EmbeddedObjects\n If ( o.Type = EMBED_ATTACHMENT ) Then\n Call o.ExtractFile( \"c:\\samples\\\" & o.Source )\n Call o.Remove\n Call doc.Save( False, True )\n End If\n End Forall\nEnd If\n"
},
{
"answer_id": 278314,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "Wiser wiser = new Wiser();\nwiser.setPort(2500);\nwiser.start();\n for (WiserMessage message : wiser.getMessages())\n{\n String envelopeSender = message.getEnvelopeSender();\n String envelopeReceiver = message.getEnvelopeReceiver();\n\n MimeMessage mess = message.getMimeMessage();\n\n // mail processing goes here\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1419/"
] |
56,723 |
<p>When using an aggregate control in some reports you would prefer to see a blank field instead of 0. There does not appear to be a way to do this automatically. Does anyone have a way that this can be done. Note, you want to maintain the '0' value for the field in cases when you export, but you want to show a blank when rendering to PDF or HTML.</p>
|
[
{
"answer_id": 56976,
"author": "Scott Rosenbaum",
"author_id": 5412,
"author_profile": "https://Stackoverflow.com/users/5412",
"pm_score": 3,
"selected": false,
"text": "function hideText (dataControl){\n if (dataControl.getValue() == 0) {\n var color = dataControl.getStyle().getBackgroundColor();\n var parentItem = dataControl.getParent();\n do {\n if (color == null && parentItem != null) {\n color = parentItem.getStyle().getBackgroundColor();\n parentItem = parentItem.getParent();\n } else {\n break;\n }\n\n } while (color == null);\n dataControl.getStyle().color = color;\n }\n}\n hideText(this);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5412/"
] |
56,729 |
<p>Can somebody give me a complete and working example of calling the <code>AllocateAndInitializeSid</code> function from C# code?</p>
<p>I found <a href="http://msdn.microsoft.com/en-us/library/aa375213(VS.85).aspx" rel="nofollow noreferrer">this</a>: </p>
<pre><code>BOOL WINAPI AllocateAndInitializeSid(
__in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
__in BYTE nSubAuthorityCount,
__in DWORD dwSubAuthority0,
__in DWORD dwSubAuthority1,
__in DWORD dwSubAuthority2,
__in DWORD dwSubAuthority3,
__in DWORD dwSubAuthority4,
__in DWORD dwSubAuthority5,
__in DWORD dwSubAuthority6,
__in DWORD dwSubAuthority7,
__out PSID *pSid
);
</code></pre>
<p>and I don't know how to construct the signature of this method - what should I do with <code>PSID_IDENTIFIER_AUTHORITY</code> and <code>PSID</code> types? How should I pass them - using <code>ref</code> or <code>out</code>?</p>
|
[
{
"answer_id": 58180,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 3,
"selected": true,
"text": " [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\n public struct SidIdentifierAuthority {\n\n /// BYTE[6]\n [System.Runtime.InteropServices.MarshalAsAttribute(\n System.Runtime.InteropServices.UnmanagedType.ByValArray, \n SizeConst = 6, \n ArraySubType = \n System.Runtime.InteropServices.UnmanagedType.I1)]\n public byte[] Value;\n }\n\n public partial class NativeMethods {\n\n /// Return Type: BOOL->int\n ///pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY->_SID_IDENTIFIER_AUTHORITY*\n ///nSubAuthorityCount: BYTE->unsigned char\n ///nSubAuthority0: DWORD->unsigned int\n ///nSubAuthority1: DWORD->unsigned int\n ///nSubAuthority2: DWORD->unsigned int\n ///nSubAuthority3: DWORD->unsigned int\n ///nSubAuthority4: DWORD->unsigned int\n ///nSubAuthority5: DWORD->unsigned int\n ///nSubAuthority6: DWORD->unsigned int\n ///nSubAuthority7: DWORD->unsigned int\n ///pSid: PSID*\n [System.Runtime.InteropServices.DllImportAttribute(\"advapi32.dll\", EntryPoint = \"AllocateAndInitializeSid\")]\n [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]\n public static extern bool AllocateAndInitializeSid(\n [System.Runtime.InteropServices.InAttribute()] \n ref SidIdentifierAuthority pIdentifierAuthority, \n byte nSubAuthorityCount, \n uint nSubAuthority0, \n uint nSubAuthority1, \n uint nSubAuthority2, \n uint nSubAuthority3, \n uint nSubAuthority4, \n uint nSubAuthority5, \n uint nSubAuthority6, \n uint nSubAuthority7, \n out System.IntPtr pSid);\n\n }\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95/"
] |
56,737 |
<p>Is the standard Java 1.6 <a href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">javax.xml.parsers.DocumentBuilder</a> class thread safe? Is it safe to call the parse() method from several threads in parallel?</p>
<p>The JavaDoc doesn't mention the issue, but the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">JavaDoc for the same class</a> in Java 1.4 specifically says that it <em>isn't</em> meant to be concurrent; so can I assume that in 1.6 it is?</p>
<p>The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.</p>
|
[
{
"answer_id": 56815,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": true,
"text": "private static final ThreadLocal<DocumentBuilder> builderLocal =\n new ThreadLocal<DocumentBuilder>() {\n @Override protected DocumentBuilder initialValue() {\n try {\n return\n DocumentBuilderFactory\n .newInstance(\n \"xx.MyDocumentBuilderFactory\",\n getClass().getClassLoader()\n ).newDocumentBuilder();\n } catch (ParserConfigurationException exc) {\n throw new IllegalArgumentException(exc);\n }\n }\n };\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1605/"
] |
56,741 |
<p>Is there a way to access file system info via some type of Windows API? If not what other methods are available to a user mode developer?</p>
|
[
{
"answer_id": 56882,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 3,
"selected": true,
"text": "DeviceIoControl() DeviceIoControl()"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
56,761 |
<p>Is there a keyboard shortcut in Access 2003 that will run a query while in design or sql mode?</p>
|
[
{
"answer_id": 56921,
"author": "Buggabill",
"author_id": 2106,
"author_profile": "https://Stackoverflow.com/users/2106",
"pm_score": 1,
"selected": false,
"text": "Public Function RunMyQuery() As Boolean\n SendKeys \"%Q\" & \"R\"\n RunMyQuery = True\nEnd Function\n"
},
{
"answer_id": 66891,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 2,
"selected": false,
"text": "DoCmd.RunCommand acCmdRun \n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2106/"
] |
56,767 |
<p>Is there a difference (performance, overhead) between these two ways of merging data sets?</p>
<pre><code>MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);
</code></pre>
<p>and</p>
<pre><code>MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);
</code></pre>
<p>Which do you recommend?</p>
|
[
{
"answer_id": 56772,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "MyTypedDataSet ds1 = new MyTypedDataSet();\nds1.Merge(anotherDataSet);\n//ds1 is a copy of anotherDataSet\nds1.Tables.Add(\"test\")\n\n//anotherDataSet does not contain the new table\n\nMyTypedDataSet ds2 = anotherDataSet;\n//ds12 actually points to anotherDataSet\nds2.Tables.Add(\"test\");\n\n//anotherDataSet now contains the new table\n MyClass o1 = new MyClass();\no1.LoadFrom( /* some data */ );\n\n//vs\n\nMyClass o2 = new MyClass( /* some data */ );\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] |
56,769 |
<p>I am currently designing an application that has one module which will load large amounts of data from a database and reduce it to a much smaller set by various calculations depending on the circumstances.</p>
<p>Many of the more intensive operations behave deterministically and would lend themselves to parallel processing.</p>
<p>Provided I have a loop that iterates over a large number of data chunks arriving from the db and for each one call a deterministic function without side effects, how would I make it so that the program does not wait for the function to return but rather sets the next calls going, so they could be processed in parallel? A naive approach to demonstrate the principle would do me for now.</p>
<p>I have read Google's MapReduce paper and while I could use the overall principle in a number of places, I won't, for now, target large clusters, rather it's going to be a single multi-core or multi-CPU machine for version 1.0. So currently, I'm not sure if I can actually use the library or would have to roll a dumbed-down basic version myself.</p>
<p>I am at an early stage of the design process and so far I am targeting C-something (for the speed critical bits) and Python (for the productivity critical bits) as my languages. If there are compelling reasons, I might switch, but so far I am contented with my choice.</p>
<p>Please note that I'm aware of the fact that it might take longer to retrieve the next chunk from the database than to process the current one and the whole process would then be I/O-bound. I would, however, assume for now that it isn't and in practice use a db cluster or memory caching or something else to be not I/O-bound at this point.</p>
|
[
{
"answer_id": 66302,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "import processing\n\ndef worker(i):\n return i*i\nnum_workers = 2\npool = processing.Pool(num_workers)\nresult = pool.imap(worker, range(100000))\n results = []\nfor i in range(10000):\n results.append(pool.apply_async(worker, i))\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
56,770 |
<p>I'm creating an ASP.NET web site where all pages hang off a database-driven tree-hierarchy. Pages typically present HTML content. But, some will execute programming.</p>
<p><em>Examples:</em> <br></p>
<ol>
<li>a "contact us" form </li>
<li>a report generator</li>
</ol>
<p>How should I represent/reference the programming within the database? Should I have a varchar value of a Web User Control (.ascx) name? Or a Web Form (.aspx) name? Something else? Or should it just be an integer or other such ID in a dictionary within my application?</p>
<p>Can I make an ASP.NET Site Map Provider with this structure?</p>
<p>See more information here: <a href="https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation">Which is the best database schema for my navigation?</a></p>
|
[
{
"answer_id": 57207,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 2,
"selected": false,
"text": "<my:contact-us-form/> .ascx"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
56,786 |
<p>We have a 42U rack which is getting a load of new 1U and 2U servers real soon. One of the guys here reckons that you need to leave a gap between the servers (of 1U) to aid cooling.</p>
<p>Question is, do you? When looking around the datacenter, no-one else seems to be, and it also diminishes how much we can fit in. We're using Dell 1850 and 2950 hardware.</p>
|
[
{
"answer_id": 57113,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 2,
"selected": false,
"text": "TOP OF RACK\n===============\n===============\n===============\n===============\n===============\n======== (Shallow equipment, trapped hot air)\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4787/"
] |
56,810 |
<p>I have used fork() in C to start another process. How do I start a new thread?</p>
|
[
{
"answer_id": 56825,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 7,
"selected": true,
"text": "int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *\n (*start_routine)(void *), void * arg);\n"
},
{
"answer_id": 52453291,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "atomic_int #include <stdio.h>\n#include <threads.h>\n#include <stdatomic.h>\n\natomic_int atomic_counter;\nint non_atomic_counter;\n\nint mythread(void* thr_data) {\n (void)thr_data;\n for(int n = 0; n < 1000; ++n) {\n ++non_atomic_counter;\n ++atomic_counter;\n // for this example, relaxed memory order is sufficient, e.g.\n // atomic_fetch_add_explicit(&atomic_counter, 1, memory_order_relaxed);\n }\n return 0;\n}\n\nint main(void) {\n thrd_t thr[10];\n for(int n = 0; n < 10; ++n)\n thrd_create(&thr[n], mythread, NULL);\n for(int n = 0; n < 10; ++n)\n thrd_join(thr[n], NULL);\n printf(\"atomic %d\\n\", atomic_counter);\n printf(\"non-atomic %d\\n\", non_atomic_counter);\n}\n gcc -ggdb3 -std=c11 -Wall -Wextra -pedantic -o main.out main.c -pthread\n./main.out\n atomic 10000\nnon-atomic 4341\n gdb -batch -ex \"disassemble/rs mythread\" main.out\n 17 ++non_atomic_counter;\n 0x00000000004007e8 <+8>: 83 05 65 08 20 00 01 addl $0x1,0x200865(%rip) # 0x601054 <non_atomic_counter>\n\n18 __atomic_fetch_add(&atomic_counter, 1, __ATOMIC_SEQ_CST);\n 0x00000000004007ef <+15>: f0 83 05 61 08 20 00 01 lock addl $0x1,0x200861(%rip) # 0x601058 <atomic_counter>\n f0 aarch64-linux-gnu-gcc 11 ++non_atomic_counter;\n 0x0000000000000a28 <+24>: 60 00 40 b9 ldr w0, [x3]\n 0x0000000000000a2c <+28>: 00 04 00 11 add w0, w0, #0x1\n 0x0000000000000a30 <+32>: 60 00 00 b9 str w0, [x3]\n\n12 ++atomic_counter;\n 0x0000000000000a34 <+36>: 40 fc 5f 88 ldaxr w0, [x2]\n 0x0000000000000a38 <+40>: 00 04 00 11 add w0, w0, #0x1\n 0x0000000000000a3c <+44>: 40 fc 04 88 stlxr w4, w0, [x2]\n 0x0000000000000a40 <+48>: a4 ff ff 35 cbnz w4, 0xa34 <mythread+36>\n cbnz stlxr std::atomic #define _XOPEN_SOURCE 700\n#include <assert.h>\n#include <stdlib.h>\n#include <pthread.h>\n\nenum CONSTANTS {\n NUM_THREADS = 1000,\n NUM_ITERS = 1000\n};\n\nint global = 0;\nint fail = 0;\npthread_mutex_t main_thread_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nvoid* main_thread(void *arg) {\n int i;\n for (i = 0; i < NUM_ITERS; ++i) {\n if (!fail)\n pthread_mutex_lock(&main_thread_mutex);\n global++;\n if (!fail)\n pthread_mutex_unlock(&main_thread_mutex);\n }\n return NULL;\n}\n\nint main(int argc, char **argv) {\n pthread_t threads[NUM_THREADS];\n int i;\n fail = argc > 1;\n for (i = 0; i < NUM_THREADS; ++i)\n pthread_create(&threads[i], NULL, main_thread, NULL);\n for (i = 0; i < NUM_THREADS; ++i)\n pthread_join(threads[i], NULL);\n assert(global == NUM_THREADS * NUM_ITERS);\n return EXIT_SUCCESS;\n}\n gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c -pthread\n./main.out\n./main.out 1\n __atomic_* __atomic_* #define _XOPEN_SOURCE 700\n#include <pthread.h>\n#include <stdatomic.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Constants {\n NUM_THREADS = 1000,\n};\n\nint atomic_counter;\nint non_atomic_counter;\n\nvoid* mythread(void *arg) {\n (void)arg;\n for (int n = 0; n < 1000; ++n) {\n ++non_atomic_counter;\n __atomic_fetch_add(&atomic_counter, 1, __ATOMIC_SEQ_CST);\n }\n return NULL;\n}\n\nint main(void) {\n int i;\n pthread_t threads[NUM_THREADS];\n for (i = 0; i < NUM_THREADS; ++i)\n pthread_create(&threads[i], NULL, mythread, NULL);\n for (i = 0; i < NUM_THREADS; ++i)\n pthread_join(threads[i], NULL);\n printf(\"atomic %d\\n\", atomic_counter);\n printf(\"non-atomic %d\\n\", non_atomic_counter);\n}\n gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c -pthread\n./main.out\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
56,812 |
<p>I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself).</p>
<p>The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF:</p>
<pre><code>"Cannot perform web service invocation GetList.
The fault returned when invoking the web service operation is:
'AxisFault
faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog."
</code></pre>
<p>The standard for UTF-8 encoding optionally includes the BOM character (<a href="http://unicode.org/faq/utf_bom.html#29" rel="nofollow noreferrer">http://unicode.org/faq/utf_bom.html#29</a>). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there’s no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn’t handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (<a href="http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942" rel="nofollow noreferrer">http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942</a>).</p>
<p>Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th).<br />
<a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments" rel="nofollow noreferrer">http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments</a></p>
|
[
{
"answer_id": 73634,
"author": "Dan Cramer",
"author_id": 3274,
"author_profile": "https://Stackoverflow.com/users/3274",
"pm_score": 2,
"selected": false,
"text": "<!--- Remove BOM from the start of the string, if it exists --->\n<cfif Left(responseText, 1) EQ chr(65279)>\n<cfset responseText = mid(xmlText, 2, len(responseText))>\n</cfif>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5849/"
] |
56,820 |
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="noreferrer">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p>
<pre><code>n = 5.59
round(n, 1) # 5.6
</code></pre>
<p>But, in actuality, good old floating point weirdness creeps in and you get:</p>
<pre><code>5.5999999999999996
</code></pre>
<p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html" rel="noreferrer">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html" rel="noreferrer">See here also</a>.</p>
<p>Short of creating my own round library, is there any way around this?</p>
|
[
{
"answer_id": 56832,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": -1,
"selected": false,
"text": "round(n,1)+epsilon\n"
},
{
"answer_id": 56833,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 8,
"selected": true,
"text": "'%.1f' % round(n, 1) # Gives you '5.6'\n"
},
{
"answer_id": 56840,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 4,
"selected": false,
"text": ">>> n = 5.59\n>>> int(n * 10) / 10.0\n5.5\n>>> int(n * 10 + 0.5)\n56\n"
},
{
"answer_id": 56841,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "% mystring = \"%.2f\" % 5.5999\n"
},
{
"answer_id": 56844,
"author": "Tomi Kyöstilä",
"author_id": 616,
"author_profile": "https://Stackoverflow.com/users/616",
"pm_score": 4,
"selected": false,
"text": "str(round(n, 1)) round(n, 1)"
},
{
"answer_id": 56849,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 2,
"selected": false,
"text": "print '%.1f' % 5.59 # returns 5.6\n"
},
{
"answer_id": 56850,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": false,
"text": "\"%.1f\" % n\n"
},
{
"answer_id": 57704,
"author": "Will Harris",
"author_id": 4702,
"author_profile": "https://Stackoverflow.com/users/4702",
"pm_score": 5,
"selected": false,
"text": "round(5.59, 1) >>> 5.6\n5.5999999999999996\n>>> \n"
},
{
"answer_id": 15398691,
"author": "Robert Griesmeyer",
"author_id": 2070300,
"author_profile": "https://Stackoverflow.com/users/2070300",
"pm_score": 5,
"selected": false,
"text": "from decimal import Decimal, ROUND_UP\n\nDecimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)\n"
},
{
"answer_id": 17296776,
"author": "Alexandre Lymberopoulos",
"author_id": 2519948,
"author_profile": "https://Stackoverflow.com/users/2519948",
"pm_score": 3,
"selected": false,
"text": "print \"%.2f\" % (round((2*4.4+3*5.6+3*4.4)/8,2),)\n print \"Media = %.1f\" % (round((2*4.4+3*5.6+3*4.4)/8,1),)\n print \"Media = %.20f\" % (round((2*4.4+3*5.6+3*4.4)/8,20),)\n"
},
{
"answer_id": 33771679,
"author": "Станислав Повышев",
"author_id": 2491847,
"author_profile": "https://Stackoverflow.com/users/2491847",
"pm_score": 2,
"selected": false,
"text": "format(5.59, '.1f') # to display\nfloat(format(5.59, '.1f')) #to round\n"
},
{
"answer_id": 42443001,
"author": "Gildas",
"author_id": 5318186,
"author_profile": "https://Stackoverflow.com/users/5318186",
"pm_score": 2,
"selected": false,
"text": "int(round( x , 0))\n >>> int(round(5.59,0))\n6\n"
},
{
"answer_id": 49164892,
"author": "Dondon Jie",
"author_id": 7866170,
"author_profile": "https://Stackoverflow.com/users/7866170",
"pm_score": 1,
"selected": false,
"text": "x1 = 5.63\nx2 = 5.65\nprint(float('%.2f' % round(x1,1))) # gives you '5.6'\nprint(float('%.2f' % round(x2,1))) # gives you '5.7'\n 5.6\n5.7\n"
},
{
"answer_id": 49777226,
"author": "Syed Is Saqlain",
"author_id": 5280048,
"author_profile": "https://Stackoverflow.com/users/5280048",
"pm_score": 1,
"selected": false,
"text": "import re\n\n\ndef custom_round(num, precision=0):\n # Get the type of given number\n type_num = type(num)\n # If the given type is not a valid number type, raise TypeError\n if type_num not in [int, float, Decimal]:\n raise TypeError(\"type {} doesn't define __round__ method\".format(type_num.__name__))\n # If passed number is int, there is no rounding off.\n if type_num == int:\n return num\n # Convert number to string.\n str_num = str(num).lower()\n # We will remove negative context from the number and add it back in the end\n negative_number = False\n if num < 0:\n negative_number = True\n str_num = str_num[1:]\n # If number is in format 1e-12 or 2e+13, we have to convert it to\n # to a string in standard decimal notation.\n if 'e-' in str_num:\n # For 1.23e-7, e_power = 7\n e_power = int(re.findall('e-[0-9]+', str_num)[0][2:])\n # For 1.23e-7, number = 123\n number = ''.join(str_num.split('e-')[0].split('.'))\n zeros = ''\n # Number of zeros = e_power - 1 = 6\n for i in range(e_power - 1):\n zeros = zeros + '0'\n # Scientific notation 1.23e-7 in regular decimal = 0.000000123\n str_num = '0.' + zeros + number\n if 'e+' in str_num:\n # For 1.23e+7, e_power = 7\n e_power = int(re.findall('e\\+[0-9]+', str_num)[0][2:])\n # For 1.23e+7, number_characteristic = 1\n # characteristic is number left of decimal point.\n number_characteristic = str_num.split('e+')[0].split('.')[0]\n # For 1.23e+7, number_mantissa = 23\n # mantissa is number right of decimal point.\n number_mantissa = str_num.split('e+')[0].split('.')[1]\n # For 1.23e+7, number = 123\n number = number_characteristic + number_mantissa\n zeros = ''\n # Eg: for this condition = 1.23e+7\n if e_power >= len(number_mantissa):\n # Number of zeros = e_power - mantissa length = 5\n for i in range(e_power - len(number_mantissa)):\n zeros = zeros + '0'\n # Scientific notation 1.23e+7 in regular decimal = 12300000.0\n str_num = number + zeros + '.0'\n # Eg: for this condition = 1.23e+1\n if e_power < len(number_mantissa):\n # In this case, we only need to shift the decimal e_power digits to the right\n # So we just copy the digits from mantissa to characteristic and then remove\n # them from mantissa.\n for i in range(e_power):\n number_characteristic = number_characteristic + number_mantissa[i]\n number_mantissa = number_mantissa[i:]\n # Scientific notation 1.23e+1 in regular decimal = 12.3\n str_num = number_characteristic + '.' + number_mantissa\n # characteristic is number left of decimal point.\n characteristic_part = str_num.split('.')[0]\n # mantissa is number right of decimal point.\n mantissa_part = str_num.split('.')[1]\n # If number is supposed to be rounded to whole number,\n # check first decimal digit. If more than 5, return\n # characteristic + 1 else return characteristic\n if precision == 0:\n if mantissa_part and int(mantissa_part[0]) >= 5:\n return type_num(int(characteristic_part) + 1)\n return type_num(characteristic_part)\n # Get the precision of the given number.\n num_precision = len(mantissa_part)\n # Rounding off is done only if number precision is\n # greater than requested precision\n if num_precision <= precision:\n return num\n # Replace the last '5' with 6 so that rounding off returns desired results\n if str_num[-1] == '5':\n str_num = re.sub('5$', '6', str_num)\n result = round(type_num(str_num), precision)\n # If the number was negative, add negative context back\n if negative_number:\n result = result * -1\n return result\n"
},
{
"answer_id": 60294994,
"author": "Tali Oat",
"author_id": 4609659,
"author_profile": "https://Stackoverflow.com/users/4609659",
"pm_score": 2,
"selected": false,
"text": "round() print(round(61.295, 2))\nprint(round(1.295, 2))\n 61.3\n1.29\n math.ceil() math.floor() from math import ceil\ndecimal_count = 2\nprint(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)\nprint(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)\n 61.3\n1.3\n"
},
{
"answer_id": 61820474,
"author": "conmak",
"author_id": 12014156,
"author_profile": "https://Stackoverflow.com/users/12014156",
"pm_score": 2,
"selected": false,
"text": "def hard_round(number, decimal_places=0):\n \"\"\"\n Function:\n - Rounds a float value to a specified number of decimal places\n - Fixes issues with floating point binary approximation rounding in python\n Requires:\n - `number`:\n - Type: int|float\n - What: The number to round\n Optional:\n - `decimal_places`:\n - Type: int \n - What: The number of decimal places to round to\n - Default: 0\n Example:\n ```\n hard_round(5.6,1)\n ```\n \"\"\"\n return int(number*(10**decimal_places)+0.5)/(10**decimal_places)\n"
},
{
"answer_id": 65786552,
"author": "Irfan wani",
"author_id": 13789135,
"author_profile": "https://Stackoverflow.com/users/13789135",
"pm_score": 0,
"selected": false,
"text": "float_number = 12.234325335563\nrounded = round(float_number, 3) # 3 is the number of decimal places to be returned.You can pass any number in place of 3 depending on how many decimal places you want to return.\nprint(rounded)\n 12.234\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
56,837 |
<p>My problem is that my XML document contains snippets of XHTML within it and while passing it through an XSLT I would like it to render those snippets without mangling them.</p>
<p>I've tried wrapping the snippet in a CDATA but it doesn't work since less than and greater than are translated to < and > as opposed to being echoed directly.</p>
<p>What's the XSL required for doing this?</p>
|
[
{
"answer_id": 58471,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n"
},
{
"answer_id": 13282569,
"author": "Alexis Wilke",
"author_id": 212378,
"author_profile": "https://Stackoverflow.com/users/212378",
"pm_score": 2,
"selected": false,
"text": "<xsl:copy-of select=\"this/tag/here\"/>\n <xsl:copy-of select=\"this/tag/here/*\"/>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
56,843 |
<p>I'm looking for a builder for <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html" rel="noreferrer">HQL</a> in Java. I want to get rid of things like:</p>
<pre><code>StringBuilder builder = new StringBuilder()
.append("select stock from ")
.append( Stock.class.getName() )
.append( " as stock where stock.id = ")
.append( id );
</code></pre>
<p>I'd rather have something like:</p>
<pre><code>HqlBuilder builder = new HqlBuilder()
.select( "stock" )
.from( Stock.class.getName() ).as( "stock" )
.where( "stock.id" ).equals( id );
</code></pre>
<p>I googled a bit, and I couldn't find one.</p>
<p>I wrote a quick & dumb <code>HqlBuilder</code> that suits my needs for now, but I'd love to find one that has more users and tests than me alone.</p>
<p>Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:</p>
<pre><code>select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.someValue = bonus.id
</code></pre>
<p>ie. select all stocks whose property <code>someValue</code> points to <em>any</em> bonus from the Bonus table.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 56883,
"author": "Alex Argo",
"author_id": 5885,
"author_profile": "https://Stackoverflow.com/users/5885",
"pm_score": 2,
"selected": false,
"text": "List<Stock> stocks = session.createCriteria(Stock.class)\n .add(Property.forName(\"id\").eq(id))\n .list();\n DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class) \n .add(Property.forName(\"id\").eq(id));\n DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class)\n .createCriteria(\"Stock\")\n .add(Property.forName(\"id\").eq(id)));\n"
},
{
"answer_id": 56937,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "select stock\nfrom com.something.Stock as stock, com.something.Bonus as bonus\nwhere stock.bonus.id = bonus.id\n Stock Bonus bonus Stock Criteria.list() Stock stock.getBonus() select stock\nfrom com.something.Stock as stock\nwhere stock.bonus.value > 1000000\n Criteria.createAlias() session.createCriteria(Stock.class).createAlias(\"bonus\", \"b\")\n .add(Restrictions.gt(\"b.value\", 1000000)).list()\n"
},
{
"answer_id": 57100,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 4,
"selected": true,
"text": "DetachedCriteria IN someValue DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class);\nList stocks = session.createCriteria(Stock.class)\n .add(Property.forName(\"someValue\").in(bonuses)).list();\n select stock\nfrom com.something.Stock as stock\nwhere stock.someValue in (select bonus.id from com.something.Bonus as bonus)\n someValue"
},
{
"answer_id": 57141,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": false,
"text": "Person person = session.getNamedQuery(\"Person.findByName\")\n .setString(0, \"Marcio\")\n .list();\n"
},
{
"answer_id": 586392,
"author": "Josh",
"author_id": 56887,
"author_profile": "https://Stackoverflow.com/users/56887",
"pm_score": 2,
"selected": false,
"text": "QueryBuilder qb = new QueryBuilder();\nqb.select(\"img\");\nqb.from(\"Image\", \"img\");\nqb.join(\"img.pixels\", \"pix\", true, false);\n\n// Can't join anymore after this\nqb.where(); // First\nqb.append(\"(\");\nqb.and(\"pt.details.creationTime > :time\");\nqb.param(\"time\", new Date());\nqb.append(\")\");\nqb.and(\"img.id in (:ids)\");\nqb.paramList(\"ids\", new HashSet());\nqb.order(\"img.id\", true);\nqb.order(\"this.details.creationEvent.time\", false);\n"
},
{
"answer_id": 1880122,
"author": "Guillaume",
"author_id": 228689,
"author_profile": "https://Stackoverflow.com/users/228689",
"pm_score": 2,
"selected": false,
"text": "...\nHqlBuilder select(String alias);\nHqlBuilder select(String alias, String property);\nHqlBuilder from(Class<?> entityClass, String alias);\nHqlBuilder fromFetch(String joinAlias, String joinRelationship, String alias);\nHqlBuilder where(String alias, String property, Operator operator, Object value);\nHqlBuilder where(String alias, Operator operator, Object value);\nHqlBuilder where(String alias1, Operator operator, String alias2);\nHqlBuilder whereIn(String alias, String property, Set<?> values);\nHqlBuilder whereIn(String alias, Set<?> values);\nHqlBuilder where(Clause clause);\nHqlBuilder orderBy(String alias, String property);\nHqlBuilder orderBy(String alias, SortDirection sortDirection);\nHqlBuilder orderBy(String alias, String property, SortDirection sortDirection);\nString toHql();\n...\n"
},
{
"answer_id": 2044946,
"author": "Timo Westkämper",
"author_id": 252552,
"author_profile": "https://Stackoverflow.com/users/252552",
"pm_score": 3,
"selected": false,
"text": "HQLQuery query = new HibernateQuery(session);\nList<Stock> s = query.from(stock, bonus)\n .where(stock.someValue.eq(bonus.id))\n .list(stock);\n"
},
{
"answer_id": 8372768,
"author": "ebelanger",
"author_id": 1028380,
"author_profile": "https://Stackoverflow.com/users/1028380",
"pm_score": 3,
"selected": false,
"text": "import static org.torpedoquery.jpa.Torpedo.*;\n\nBonus bonus = from(Bonus.class);\nQuery subQuery = select(bonus.getId());\n\nStock stock = from(Stock.class);\nwhere(stock.getSomeValue()).in(subQuery);\n\nList<Stock> stocks = select(stock).list(entityManager);\n"
},
{
"answer_id": 17545743,
"author": "tglman",
"author_id": 810633,
"author_profile": "https://Stackoverflow.com/users/810633",
"pm_score": 1,
"selected": false,
"text": "EntityManager em = ...\nCriteriaBuilder qb = em.getCriteriaBuilder();\nCriteriaQuery<Stock> c = qb.createQuery(Stock.class);\nRoot<Stock> = c.from(Stock.class);\nPredicate condition = qb.eq(p.get(Stock_.id), id);\nc.where(condition);\nTypedQuery<Stock> q = em.createQuery(c); \nList<Stock> result = q.getResultList();\n EntityManager em = ...\nObjectQuery<Stock> query = new GenericObjectQuery<Stock>(Stock.class);\nStock toSearch = query.target();\nquery.eq(toSearch.getId(),id);\nList<Stock> res = (List<Stock>)JPAObjectQuery.execute(query, em);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] |
56,856 |
<p>My application has a need to let the user choose a date from a list of dates conforming to a certain pattern. For instance, they may need to choose a monday from a list Monday's for a month. Is there a way to get a <code>UIDatePicker</code> to limit date choices to a certain subset or should I just use a <code>UIPickerView</code>?</p>
|
[
{
"answer_id": 59152,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 4,
"selected": true,
"text": "UIDatePicker UIPickerView"
},
{
"answer_id": 16299518,
"author": "Desdenova",
"author_id": 771231,
"author_profile": "https://Stackoverflow.com/users/771231",
"pm_score": 0,
"selected": false,
"text": "UIDatePicker minimumDate maximumDate UIPickerView"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967/"
] |
56,860 |
<p>I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?</p>
|
[
{
"answer_id": 56904,
"author": "NotMyself",
"author_id": 303,
"author_profile": "https://Stackoverflow.com/users/303",
"pm_score": 9,
"selected": false,
"text": "Tiles ThreeDBoard Board Board Height Width ThreeDBoard Board AddUnit GetTile GetUnits Board ThreeDBoard Board Board ThreeDBoard Board Board ThreeDBoard Board Board"
},
{
"answer_id": 58967,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 6,
"selected": false,
"text": "void DrawShape(const Shape& s)\n{\n if (typeid(s) == typeid(Square))\n DrawSquare(static_cast<Square&>(s)); \n else if (typeid(s) == typeid(Circle))\n DrawCircle(static_cast<Circle&>(s));\n}\n DrawShape Shape Shape Rectangle class Rectangle\n{\n public:\n void SetWidth(double w) {itsWidth=w;}\n void SetHeight(double h) {itsHeight=w;}\n double GetHeight() const {return itsHeight;}\n double GetWidth() const {return itsWidth;}\n private:\n double itsWidth;\n double itsHeight;\n};\n Square Rectangle Square SetWidth SetHeight Square SetWidth SetHeight void f(Rectangle& r)\n{\n r.SetWidth(32); // calls Rectangle::SetWidth\n}\n Square Square"
},
{
"answer_id": 59006,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "class Rectangle {\n int getHeight()\n void setHeight(int value) {\n postcondition: width didn’t change\n }\n int getWidth()\n void setWidth(int value) {\n postcondition: height didn’t change\n }\n}\n\nclass Square extends Rectangle { }\n Rectangle void invariant(Rectangle r) {\n r.setHeight(200)\n r.setWidth(100)\n assert(r.getHeight() == 200 and r.getWidth() == 100)\n}\n Square Rectangle"
},
{
"answer_id": 274990,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 5,
"selected": false,
"text": "class Base:\n def Foo(self, arg): \n # *... do stuff*\n\nclass Derived(Base):\n def Foo(self, arg):\n # *... do stuff*\n"
},
{
"answer_id": 584732,
"author": "m-sharp",
"author_id": 28678,
"author_profile": "https://Stackoverflow.com/users/28678",
"pm_score": 11,
"selected": true,
"text": "Square Rectangle Square Rectangle Square Rectangle SetWidth SetHeight Rectangle Rectangle Square SetWidth SetHeight Square Rectangle Square Rectangle"
},
{
"answer_id": 8279878,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": 5,
"selected": false,
"text": "T S S extends T S T T S T S val id : T = new S() // id thinks it's a T, but is a S\n T Rectangle S Square val rect : Rectangle = new Square(5) // thinks it's a Rectangle, but is a Square\nval rect2 : Rectangle = rect.setWidth(10) // height is 10, LSP violation\n class Rectangle( val width : Int, val height : Int )\n{\n def setWidth( w : Int ) = new Rectangle(w, height)\n def setHeight( h : Int ) = new Rectangle(width, h)\n}\n\nclass Square( val side : Int ) extends Rectangle(side, side)\n{\n override def setWidth( s : Int ) = new Square(s)\n override def setHeight( s : Int ) = new Square(s)\n}\n S Si S Ti T So S To T T T Ti To S Ti Si So To Si Ti Xi Si Ti T T"
},
{
"answer_id": 15625091,
"author": "avandeursen",
"author_id": 165292,
"author_profile": "https://Stackoverflow.com/users/165292",
"pm_score": 4,
"selected": false,
"text": "ATest BTest"
},
{
"answer_id": 38933690,
"author": "Cù Đức Hiếu",
"author_id": 2827960,
"author_profile": "https://Stackoverflow.com/users/2827960",
"pm_score": 5,
"selected": false,
"text": " public class SuperType\n {\n public string Name { get; private set; }\n public SuperType(string name, int age)\n {\n Name = name;\n Age = age;\n }\n }\n public class SubType : SuperType\n {\n public void ChangeName(string newName)\n {\n var propertyType = base.GetType().GetProperty(\"Name\").SetValue(this, newName);\n }\n }\n"
},
{
"answer_id": 44913313,
"author": "maysara",
"author_id": 5503714,
"author_profile": "https://Stackoverflow.com/users/5503714",
"pm_score": 9,
"selected": false,
"text": "public class Bird{\n public void fly(){}\n}\npublic class Duck extends Bird{}\n public class Ostrich extends Bird{}\n public class Bird{}\npublic class FlyingBirds extends Bird{\n public void fly(){}\n}\npublic class Duck extends FlyingBirds{}\npublic class Ostrich extends Bird{} \n"
},
{
"answer_id": 46638860,
"author": "inf3rno",
"author_id": 607033,
"author_profile": "https://Stackoverflow.com/users/607033",
"pm_score": 2,
"selected": false,
"text": "r = new Rectangle();\n// ...\nr.setDimensions(1,2);\nr.fill(colors.red());\ncanvas.draw(r);\n Square class Square extends Rectangle {\n setDimensions(width, height){\n assert(width == height);\n super.setDimensions(width, height);\n }\n} \n Rectangle Square r = new Square();\n// ...\nr.setDimensions(1,2); // assertion width == height failed\nr.fill(colors.red());\ncanvas.draw(r);\n Square Rectangle width == height Rectangle Rectangle Rectangle"
},
{
"answer_id": 46995392,
"author": "Lukas Lukac",
"author_id": 1162217,
"author_profile": "https://Stackoverflow.com/users/1162217",
"pm_score": 5,
"selected": false,
"text": "class ItemsRepository\n{\n /**\n * @return int Returns number of deleted rows\n */\n public function delete()\n {\n // perform a delete query\n $numberOfDeletedRows = 10;\n\n return $numberOfDeletedRows;\n }\n}\n class BadlyExtendedItemsRepository extends ItemsRepository\n{\n /**\n * @return void Was suppose to return an INT like parent, but did not, breaks LSP\n */\n public function delete()\n {\n // perform a delete query\n $numberOfDeletedRows = 10;\n\n // we broke the behaviour of the parent class\n return;\n }\n}\n /**\n * Class ItemsService is a client for public ItemsRepository \"API\" (the public delete method).\n *\n * Technically, I am able to pass into a constructor a sub-class of the ItemsRepository\n * but if the sub-class won't abide the base class API, the client will get broken.\n */\nclass ItemsService\n{\n /**\n * @var ItemsRepository\n */\n private $itemsRepository;\n\n /**\n * @param ItemsRepository $itemsRepository\n */\n public function __construct(ItemsRepository $itemsRepository)\n {\n $this->itemsRepository = $itemsRepository;\n }\n\n /**\n * !!! Notice how this is suppose to return an int. My clients expect it based on the\n * ItemsRepository API in the constructor !!!\n *\n * @return int\n */\n public function delete()\n {\n return $this->itemsRepository->delete();\n }\n} \n class ItemsController\n{\n /**\n * Valid delete action when using the base class.\n */\n public function validDeleteAction()\n {\n $itemsService = new ItemsService(new ItemsRepository());\n $numberOfDeletedItems = $itemsService->delete();\n\n // $numberOfDeletedItems is an INT :)\n }\n\n /**\n * Invalid delete action when using a subclass.\n */\n public function brokenDeleteAction()\n {\n $itemsService = new ItemsService(new BadlyExtendedItemsRepository());\n $numberOfDeletedItems = $itemsService->delete();\n\n // $numberOfDeletedItems is a NULL :(\n }\n}\n"
},
{
"answer_id": 48855491,
"author": "Steve Chamaillard",
"author_id": 3887300,
"author_profile": "https://Stackoverflow.com/users/3887300",
"pm_score": 5,
"selected": false,
"text": "<?php\n\ninterface Database \n{\n public function selectQuery(string $sql): array;\n}\n\nclass SQLiteDatabase implements Database\n{\n public function selectQuery(string $sql): array\n {\n // sqlite specific code\n\n return $result;\n }\n}\n\nclass MySQLDatabase implements Database\n{\n public function selectQuery(string $sql): array\n {\n // mysql specific code\n\n return $result; \n }\n}\n <?php\n\ninterface Database \n{\n public function selectQuery(string $sql): array;\n}\n\nclass SQLiteDatabase implements Database\n{\n public function selectQuery(string $sql): array\n {\n // sqlite specific code\n\n return $result;\n }\n}\n\nclass MySQLDatabase implements Database\n{\n public function selectQuery(string $sql): array\n {\n // mysql specific code\n\n return ['result' => $result]; // This violates LSP !\n }\n}\n"
},
{
"answer_id": 50445304,
"author": "GauRang Omar",
"author_id": 6653785,
"author_profile": "https://Stackoverflow.com/users/6653785",
"pm_score": 3,
"selected": false,
"text": " // Violation of Likov's Substitution Principle\nclass Rectangle {\n protected int m_width;\n protected int m_height;\n\n public void setWidth(int width) {\n m_width = width;\n }\n\n public void setHeight(int height) {\n m_height = height;\n }\n\n public int getWidth() {\n return m_width;\n }\n\n public int getHeight() {\n return m_height;\n }\n\n public int getArea() {\n return m_width * m_height;\n }\n}\n\nclass Square extends Rectangle {\n public void setWidth(int width) {\n m_width = width;\n m_height = width;\n }\n\n public void setHeight(int height) {\n m_width = height;\n m_height = height;\n }\n\n}\n\nclass LspTest {\n private static Rectangle getNewRectangle() {\n // it can be an object returned by some factory ...\n return new Square();\n }\n\n public static void main(String args[]) {\n Rectangle r = LspTest.getNewRectangle();\n\n r.setWidth(5);\n r.setHeight(10);\n // user knows that r it's a rectangle.\n // It assumes that he's able to set the width and height as for the base\n // class\n\n System.out.println(r.getArea());\n // now he's surprised to see that the area is 100 instead of 50.\n }\n}\n"
},
{
"answer_id": 51811062,
"author": "Vadim Samokhin",
"author_id": 618020,
"author_profile": "https://Stackoverflow.com/users/618020",
"pm_score": 2,
"selected": false,
"text": "interface Account\n{\n /**\n * Withdraw $money amount from this account.\n *\n * @param Money $money\n * @return mixed\n */\n public function withdraw(Money $money);\n}\nclass DefaultAccount implements Account\n{\n private $balance;\n public function withdraw(Money $money)\n {\n if (!$this->enoughMoney($money)) {\n return;\n }\n $this->balance->subtract($money);\n }\n}\n interface Account\n{\n /**\n * Withdraw $money amount from this account if its balance is enough.\n * Otherwise do nothing.\n *\n * @param Money $money\n * @return mixed\n */\n public function withdraw(Money $money);\n}\n class Client\n{\n public function go(Account $account, Money $money)\n {\n if ($account instanceof DefaultAccount && !$account->hasEnoughMoney($money)) {\n return;\n }\n $account->withdraw($money);\n }\n}\n hasEnoughMoney()"
},
{
"answer_id": 54615672,
"author": "Khaled Qasem",
"author_id": 8550140,
"author_profile": "https://Stackoverflow.com/users/8550140",
"pm_score": 5,
"selected": false,
"text": "class TrasportationDevice\n{\n String name;\n String getName() { ... }\n void setName(String n) { ... }\n\n double speed;\n double getSpeed() { ... }\n void setSpeed(double d) { ... }\n\n Engine engine;\n Engine getEngine() { ... }\n void setEngine(Engine e) { ... }\n\n void startEngine() { ... }\n}\n\nclass Car extends TransportationDevice\n{\n @Override\n void startEngine() { ... }\n}\n class Bicycle extends TransportationDevice\n{\n @Override\n void startEngine() /*problem!*/\n}\n class TrasportationDevice\n{\n String name;\n String getName() { ... }\n void setName(String n) { ... }\n\n double speed;\n double getSpeed() { ... }\n void setSpeed(double d) { ... }\n}\n class DevicesWithoutEngines extends TransportationDevice\n{ \n void startMoving() { ... }\n}\n class DevicesWithEngines extends TransportationDevice\n{ \n Engine engine;\n Engine getEngine() { ... }\n void setEngine(Engine e) { ... }\n\n void startEngine() { ... }\n}\n class Car extends DevicesWithEngines\n{\n @Override\n void startEngine() { ... }\n}\n class Bicycle extends DevicesWithoutEngines\n{\n @Override\n void startMoving() { ... }\n}\n"
},
{
"answer_id": 55549272,
"author": "Zahra.HY",
"author_id": 5723268,
"author_profile": "https://Stackoverflow.com/users/5723268",
"pm_score": 2,
"selected": false,
"text": "public interface CustomerLayout{\n\n public void render();\n}\n\n\npublic FreeCustomer implements CustomerLayout {\n ...\n @Override\n public void render(){\n //code\n }\n}\n\n\npublic PremiumCustomer implements CustomerLayout{\n ...\n @Override\n public void render(){\n if(!hasSeenAd)\n return; //it isn`t rendered in this case\n //code\n }\n}\n\npublic void renderView(CustomerLayout layout){\n layout.render();\n}\n public interface CustomerLayout{\n public void render();\n}\n\n\npublic FreeCustomer implements CustomerLayout {\n ...\n @Override\n public void render(){\n //code\n }\n}\n\n\npublic PremiumCustomer implements CustomerLayout{\n ...\n @Override\n public void render(){\n if(!hasSeenAd)\n showAd();//it has a specific behavior based on its requirement\n //code\n }\n}\n\npublic void renderView(CustomerLayout layout){\n layout.render();\n}\n"
},
{
"answer_id": 55862359,
"author": "prady00",
"author_id": 1138654,
"author_profile": "https://Stackoverflow.com/users/1138654",
"pm_score": 0,
"selected": false,
"text": "interface Planet{\n}\n class Earth implements Planet {\n public $radius;\n public function construct($radius) {\n $this->radius = $radius;\n }\n}\n $planet = new Earth(6371);\n$calc = new SurfaceAreaCalculator($planet);\n$calc->output();\n class LiveablePlanet extends Earth{\n public function color(){\n }\n}\n $planet = new LiveablePlanet(6371); // Earlier we were using Earth here\n$calc = new SurfaceAreaCalculator($planet);\n$calc->output();\n"
},
{
"answer_id": 59896294,
"author": "johannesMatevosyan",
"author_id": 3578809,
"author_profile": "https://Stackoverflow.com/users/3578809",
"pm_score": 4,
"selected": false,
"text": "Cat Dog Animal Cat Dog"
},
{
"answer_id": 60494181,
"author": "Ivan Porta",
"author_id": 6613232,
"author_profile": "https://Stackoverflow.com/users/6613232",
"pm_score": 3,
"selected": false,
"text": "public class Rectangle \n{ \n private double width;\n\n private double height; \n\n public double Width \n { \n get \n { \n return width; \n } \n set \n { \n width = value; \n }\n } \n\n public double Height \n { \n get \n { \n return height; \n } \n set \n { \n height = value; \n } \n } \n}\n public class Square : Rectangle\n{\n} \n public class Square : Rectangle\n{\n public double SetWidth \n { \n set \n { \n base.Width = value; \n base.Height = value; \n } \n } \n\n public double SetHeight \n { \n set \n { \n base.Height = value; \n base.Width = value; \n } \n } \n}\n Square s = new Square(); \ns.SetWidth(1); // Sets width and height to 1. \ns.SetHeight(2); // sets width and height to 2. \n public void A(Rectangle r) \n{ \n r.SetWidth(32); // calls Rectangle.SetWidth \n} \n"
},
{
"answer_id": 64789005,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 2,
"selected": false,
"text": "function (method) types //Swift function\nfunc foo(parameter: Class1) -> Class2\n\n//function type\n(Class1) -> Class2\n\n//Precondition\nClass1\n\n//Postcondition\nClass2\n //C3 -> C2 -> C1\n\nclass C1 {}\nclass C2: C1 {}\nclass C3: C2 {}\n parameter type returned type class A {\n func foo(a: C2) -> C2 {\n return C2()\n }\n}\n\nclass B: A {\n override func foo(a: C1) -> C3 {\n return C3()\n }\n}\n class A {\n public C2 foo(C2 a) {\n return new C2();\n }\n}\n\nclass B extends A {\n @Override\n public C3 foo(C2 a) { //You are available pass only C2 as parameter\n return new C3();\n }\n}\n"
},
{
"answer_id": 64950848,
"author": "Sarmad Sohail",
"author_id": 12785637,
"author_profile": "https://Stackoverflow.com/users/12785637",
"pm_score": 3,
"selected": false,
"text": "public class Plane{\n\n public void startEngine(){} \n\n} \npublic class FighterJet extends Plane{}\n \npublic class PaperPlane extends Plane{}\n FighterPlane PaperPlane Plane startEngine() FighterPlane PaperPlane LSP PaperPlane Plane public class Plane{ \n} \npublic class RealPlane{\n\n public void startEngine(){} \n\n}\npublic class FighterJet extends RealPlane{} \npublic class PaperPlane extends Plane{}\n"
},
{
"answer_id": 69253204,
"author": "jferard",
"author_id": 6914441,
"author_profile": "https://Stackoverflow.com/users/6914441",
"pm_score": 3,
"selected": false,
"text": "Circle ColoredCircle class Circle {\n private int radius;\n\n public Circle(int radius) {\n if (radius < 0) {\n throw new RuntimeException(\"Radius should be >= 0\");\n }\n this.radius = radius;\n }\n\n public int getRadius() {\n return this.radius;\n }\n}\n class ColoredCircle extends Circle {\n private Color color; // defined elsewhere\n\n public ColoredCircle(int radius, Color color) {\n super(radius);\n this.color = color;\n }\n\n public Color getColor() {\n return this.color;\n }\n}\n Circle ColoredCircle o1 Circle o2 Circle o2 o1 Circle ColoredCircle Circle o2 o1 color radius o1 o2 CircleColor Circle Circle Square Circle class Square extends Circle {\n private int sideSize;\n\n public Square(int sideSize) {\n super(0);\n this.sideSize = sideSize;\n }\n\n @Override\n public int getRadius() {\n return -1; // I'm a square, I don't care\n }\n\n public int getSideSize() {\n return this.sideSize;\n }\n}\n public class Liskov {\n public static void program(Circle c) {\n System.out.println(\"The radius is \"+c.getRadius());\n }\n Circle Square public static void main(String [] args){\n Liskov.program(new Circle(2)); // prints \"The radius is 2\"\n Liskov.program(new Square(2)); // prints \"The radius is -1\"\n }\n}\n Square Circle Square Circle Circle Circle Circle new Square(2) Square Circle Square.getRadius() String List o2 o1 o1 o2 x f o2.f(x) o1.f(x) o1.f(x) o2.f(x) o1.f(x) o1 o2.f(x) o2 f S.f T.f S.f T.f Counter Counter.counter() Random Random.gaussian()"
},
{
"answer_id": 70356938,
"author": "DRAGON-PARTY",
"author_id": 12232720,
"author_profile": "https://Stackoverflow.com/users/12232720",
"pm_score": 0,
"selected": false,
"text": "@Override\npublic void setHeight(double height) {\n this.height = height;\n this.width = height; // since it's a square\n}\n\n@Override\npublic void setWidth(double width) {\n setHeight(width);\n}\n class Family:\n-- getChildrenCount()\n\nclass FamilyWithKids extends Family:\n-- getChildrenCount() { return childrenCount; } // always > 0\n\nclass DeadFamilyWithKids extends FamilyWithKids:\n-- getChildrenCount() { return 0; }\n-- getChildrenCountWhenAlive() { return childrenCountWhenAlive; }\n DeadFamilyWithKids FamilyWithKids getChildrenCount() 0 FamilyWithKids 0"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303/"
] |
56,865 |
<p>A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?</p>
<p>I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like. </p>
<p>(Any sample web service can be chosen as an example.)</p>
|
[
{
"answer_id": 57090,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "import org.restlet.Client;\nimport org.restlet.data.Protocol;\nimport org.restlet.data.Reference;\nimport org.restlet.data.Response;\nimport org.restlet.resource.DomRepresentation;\nimport org.w3c.dom.Node;\n\n/**\n * Uses YAHOO!'s RESTful web service with XML.\n */\npublic class YahooSearch {\n private static final String BASE_URI = \"http://api.search.yahoo.com/WebSearchService/V1/webSearch\";\n\n public static void main(final String[] args) {\n if (1 != args.length) {\n System.err.println(\"You need to pass a search term!\");\n } else {\n final String term = Reference.encode(args[0]);\n final String uri = BASE_URI + \"?appid=restbook&query=\" + term;\n final Response response = new Client(Protocol.HTTP).get(uri);\n final DomRepresentation document = response.getEntityAsDom();\n\n document.setNamespaceAware(true);\n document.putNamespace(\"y\", \"urn:yahoo:srch\");\n\n final String expr = \"/y:ResultSet/y:Result/y:Title/text()\";\n for (final Node node : document.getNodes(expr)) {\n System.out.println(node.getTextContent());\n }\n }\n }\n}\n"
},
{
"answer_id": 57163,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "final Response response = new Client(Protocol.HTTP).get(uri);\n"
},
{
"answer_id": 58591,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": true,
"text": "HttpClient client = new HttpClient();\nHttpMethod method = new GetMethod(\"http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&query=HttpClient\");\nclient.executeMethod(method);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
56,867 |
<p>When should I use an interface and when should I use a base class? </p>
<p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p>
<p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p>
|
[
{
"answer_id": 56887,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "override new UserControl PetBase PetBase"
},
{
"answer_id": 56912,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 10,
"selected": true,
"text": "public abstract class Mammal\n public class Dog : Mammal\npublic class Cat : Mammal\n public class Giraffe : Mammal\npublic class Rhinoceros : Mammal\npublic class Hippopotamus : Mammal\n Feed() Mate() public interface IPettable\n{\n IList<Trick> Tricks{get; set;}\n void Bathe();\n void Train(Trick t);\n}\n public class Dog : Mammal, IPettable\npublic class Cat : Mammal, IPettable\n"
},
{
"answer_id": 65939,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 7,
"selected": false,
"text": "Foo IDisposable"
},
{
"answer_id": 260213,
"author": "Parappa",
"author_id": 9974,
"author_profile": "https://Stackoverflow.com/users/9974",
"pm_score": 2,
"selected": false,
"text": "public class Pet\n{\n void Bathe();\n void Train(Trick t);\n}\n\npublic class Dog\n{\n private Pet pet;\n\n public void Bathe() { pet.Bathe(); }\n public void Train(Trick t) { pet.Train(t); }\n}\n\npublic class Cat\n{\n private Pet pet;\n\n public void Bathe() { pet.Bathe(); }\n public void Train(Trick t) { pet.Train(t); }\n}\n"
},
{
"answer_id": 25577574,
"author": "x19",
"author_id": 1817640,
"author_profile": "https://Stackoverflow.com/users/1817640",
"pm_score": 0,
"selected": false,
"text": "public abstract class CloneableType\n{\n// Only derived types can support this\n// \"polymorphic interface.\" Classes in other\n// hierarchies have no access to this abstract\n// member.\n public abstract object Clone();\n}\n // Nope! Multiple inheritance is not possible in C#\n// for classes.\npublic class MiniVan : Car, CloneableType\n{\n}\n public interface ICloneable\n{\nobject Clone();\n}\n"
},
{
"answer_id": 27388452,
"author": "Jason Roell",
"author_id": 1253072,
"author_profile": "https://Stackoverflow.com/users/1253072",
"pm_score": 3,
"selected": false,
"text": "public abstract class Dog\n{\n public virtual void Bark()\n {\n Console.WriteLine(\"Base Class implementation of Bark\");\n }\n}\n\npublic class GoldenRetriever : Dog\n{\n // the Bark method is inherited from the Dog class\n}\n\npublic class Poodle : Dog\n{\n // here we are overriding the base functionality of Bark with our new implementation\n // specific to the Poodle class\n public override void Bark()\n {\n Console.WriteLine(\"Poodle's implementation of Bark\");\n }\n}\n\n// Add a list of dogs to a collection and call the bark method.\n\nvoid Main()\n{\n var poodle = new Poodle();\n var goldenRetriever = new GoldenRetriever();\n\n var dogs = new List<Dog>();\n dogs.Add(poodle);\n dogs.Add(goldenRetriever);\n\n foreach (var dog in dogs)\n {\n dog.Bark();\n }\n}\n\n// Output will be:\n// Poodle's implementation of Bark\n// Base Class implementation of Bark\n\n// \n // Create ISwimable interface\npublic interface ISwimable\n{\n public void Swim();\n}\n\n// Have Human implement ISwimable Interface\npublic class Human : ISwimable\n\n public void Swim()\n {\n //Human's implementation of Swim\n Console.WriteLine(\"I'm a human swimming!\");\n }\n\n// Have Duck implement ISwimable interface\npublic class Duck: ISwimable\n{\n public void Swim()\n {\n // Duck's implementation of Swim\n Console.WriteLine(\"Quack! Quack! I'm a Duck swimming!\")\n }\n}\n\n//Now they can both be used in places where you just need an object that has the ability \"to swim\"\n\npublic void ShowHowYouSwim(ISwimable somethingThatCanSwim)\n{\n somethingThatCanSwim.Swim();\n}\n\npublic void Main()\n{\n var human = new Human();\n var duck = new Duck();\n\n var listOfThingsThatCanSwim = new List<ISwimable>();\n\n listOfThingsThatCanSwim.Add(duck);\n listOfThingsThatCanSwim.Add(human);\n\n foreach (var something in listOfThingsThatCanSwim)\n {\n ShowHowYouSwim(something);\n }\n}\n\n // So at runtime the correct implementation of something.Swim() will be called\n // Output:\n // Quack! Quack! I'm a Duck swimming!\n // I'm a human swimming!\n"
},
{
"answer_id": 34608857,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 1,
"selected": false,
"text": "abstract non abstract interface abstract abstract abstract class PetBase implements IPet {\n// Add all abstract methods in IPet interface and keep base class clean. \n Base class will contain only non abstract methods and static methods.\n}\n abstract class PetBase implements IPet {\n // Add all abstract methods in IPet\n }\n\n /*If ISheds,IBarks is common for Pets, your PetBase can implement ISheds,IBarks. \n Respective implementations of PetBase can change the behaviour in their concrete classes*/\n\n abstract class PetBase implements IPet,ISheds,IBarks {\n // Add all abstract methods in respective interfaces\n }\n"
},
{
"answer_id": 35803354,
"author": "Adam Hughes",
"author_id": 4076764,
"author_profile": "https://Stackoverflow.com/users/4076764",
"pm_score": 2,
"selected": false,
"text": "1. You have a general interface (eg IPet)\n2. You have a implementation that is less general (eg Mammal)\n3. You have many concrete members (eg Cat, Dog, Ape)\n public interface IPet{\n\n public boolean hasHair();\n\n public boolean walksUprights();\n\n public boolean hasNipples();\n}\n public abstract class Mammal() implements IPet{\n\n @override\n public walksUpright(){\n throw new NotSupportedException(\"Walks Upright not implemented\");\n }\n\n @override\n public hasNipples(){return true}\n\n @override\n public hasHair(){return true}\n public class Ape extends Mammal(){\n\n @override\n public walksUpright(return true)\n}\n\npublic class Catextends Mammal(){\n\n @override\n public walksUpright(return false)\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2871/"
] |
56,895 |
<p>How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.</p>
<hr>
<p>As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.</p>
|
[
{
"answer_id": 57313,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 1,
"selected": false,
"text": "SELECT /*+RULE*/ FROM yourtable\n"
},
{
"answer_id": 93489,
"author": "Doug Porter",
"author_id": 4311,
"author_profile": "https://Stackoverflow.com/users/4311",
"pm_score": 5,
"selected": true,
"text": "select c1,c2,c3, \n count(src1) CNT1, \n count(src2) CNT2\n from (select a.*, \n 1 src1, \n to_number(null) src2 \n from a\n union all\n select b.*, \n to_number(null) src1, \n 2 src2 \n from b\n )\ngroup by c1,c2,c3\nhaving count(src1) <> count(src2);\n"
},
{
"answer_id": 2122095,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 1,
"selected": false,
"text": "select * from ((<query 1> MINUS <query 2>) UNION ALL (<query 2> MINUS <query 1>))\n #!/bin/sh\n\nCONNSTR=$1\necho query 1, no semicolon, eof to end:; Q1=`cat` \necho query 2, no semicolon, eof to end:; Q2=`cat`\n\nT=\"(($Q1 MINUS $Q2) UNION ALL ($Q2 MINUS $Q1));\"\n\necho select 'count(*)' from $T | sqlplus -S -L $CONNSTR\n"
},
{
"answer_id": 5730066,
"author": "tbone",
"author_id": 534120,
"author_profile": "https://Stackoverflow.com/users/534120",
"pm_score": 1,
"selected": false,
"text": "SQL> create table test_tabA\n(\ncol1 number\n)\n\nTable created.\n\nSQL> create table test_tabB\n(\ncol1 number\n)\n\nTable created.\n\nSQL> -- insert 1 row\n\nSQL> insert into test_tabA values (1)\n\n1 row created.\n\nSQL> commit\n\nCommit complete.\n\nSQL> -- Not exists query:\n\nSQL> select * from test_tabA a\nwhere not exists\n(select 'x' from test_tabB b\nwhere b.col1 = a.col1)\n\n COL1\n\n----------\n\n 1\n\n1 row selected.\n\nSQL> -- Not IN query:\n\nSQL> select * from test_tabA a\nwhere col1 not in\n(select col1\nfrom test_tabB b)\n\n COL1\n\n----------\n\n 1\n\n1 row selected.\n\n\n-- THEY MUST BE THE SAME!!! (or maybe not...)\n\n\nSQL> -- insert a NULL to test_tabB\n\nSQL> insert into test_tabB values (null)\n\n1 row created.\n\nSQL> commit\n\nCommit complete.\n\nSQL> -- Not exists query:\n\nSQL> select * from test_tabA a\nwhere not exists\n(select 'x' from test_tabB b\nwhere b.col1 = a.col1)\n\n\n COL1\n\n----------\n\n 1\n\n1 row selected.\n\nSQL> -- Not IN query:\n\nSQL> select * from test_tabA a\nwhere col1 not in\n(select col1\nfrom test_tabB b)\n\n**no rows selected.**\n"
},
{
"answer_id": 45584198,
"author": "Sander van den Oord",
"author_id": 3489155,
"author_profile": "https://Stackoverflow.com/users/3489155",
"pm_score": 4,
"selected": false,
"text": "(select * from query1 MINUS select * from query2) \nUNION ALL\n(select * from query2 MINUS select * from query1)\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] |
56,905 |
<p>Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object. </p>
<p>Here is the scenario with simplified code:</p>
<ol>
<li><p><code>Default.aspx</code></p></li>
<li><p><code>MainScript.js</code></p>
<pre><code>function getObject(){
return new Array();
}
function function1(obj){
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
function function2(){
var obj=getObject();
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
</code></pre></li>
<li><p><code>Content.aspx</code></p></li>
<li><p><code>ContentScript.js</code></p>
<pre><code>function serializeObject(){
var obj=window.top.getObject();
window.top.function1(obj); // <– This works fine
obj=new Array();
window.top.function1(obj); // <– this causes an Out of Stack Space error
}
</code></pre></li>
</ol>
<p>The code for the sample pages and JavaScript is <a href="http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/" rel="nofollow noreferrer">here</a>.</p>
<p>Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.</p>
<p>A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx). </p>
<p>Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 194249,
"author": "Kevin Hakanson",
"author_id": 22514,
"author_profile": "https://Stackoverflow.com/users/22514",
"pm_score": 1,
"selected": false,
"text": " var obj = [];\n obj.push(1);\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] |
56,913 |
<p>I have a whole bunch of files with filenames using our lovely Swedish letters <strong>å å</strong> and <strong>ö</strong>.
For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace <strong>å</strong> with <strong>a</strong>, <strong>ö</strong> with <strong>o</strong> and so on. </p>
<p>This is charset troubles at their worst.</p>
<p>I have a set of test files:</p>
<pre><code>files\Copy of New Text Documen åäö t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase åäöÅÄÖéÉ.txt
</code></pre>
<p>I'm basing my script on this line, piping it's results into various commands</p>
<pre><code>for %%X in (files\*.txt) do (echo %%X)
</code></pre>
<p>The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output:</p>
<pre><code>files\Copy of New Text Documen †„” t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase †„”Ž™‚.txt
</code></pre>
<p>So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either.</p>
<p>How would you solve this problem? I'm open to any type of tools, commandline or otherwise…</p>
<p><strong>EDIT:</strong> This is a one time problem, so I'm looking for a quick 'n ugly fix</p>
|
[
{
"answer_id": 57049,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "$mapping = @{ \n \"å\" = \"a\"\n \"ä\" = \"a\"\n \"ö\" = \"o\"\n}\n\nGet-ChildItem -Recurse . *.txt | Foreach-Object { \n $newname = $_.Name \n foreach ($l in $mapping.Keys) {\n $newname = $newname.Replace( $l, $mapping[$l] )\n $newname = $newname.Replace( $l.ToUpper(), $mapping[$l].ToUpper() )\n }\n Rename-Item -WhatIf $_.FullName $newname # remove the -WhatIf when you're ready to do it for real.\n}\n"
},
{
"answer_id": 57359,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": true,
"text": "# -*- coding: cp1252 -*-\n\nimport os, shutil\n\nbase_dir = \"g:\\\\awk\\\\\" # Base Directory (includes subdirectories)\nchar_table_1 = \"áéíóúñ\"\nchar_table_2 = \"aeioun\"\n\nadirs = os.walk (base_dir)\n\nfor adir in adirs:\n dir = adir[0] + \"\\\\\" # Directory\n # print \"\\nDir : \" + dir\n\n for file in adir[2]: # List of files\n if os.access(dir + file, os.R_OK):\n file2 = file\n for i in range (0, len(char_table_1)):\n file2 = file2.replace (char_table_1[i], char_table_2[i])\n\n if file2 <> file:\n # Different, rename\n print dir + file, \" => \", file2\n shutil.move (dir + file, dir + file2)\n\n###\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/914/"
] |
56,923 |
<p>Just what the title says, I need to change the password for an existing sql server login and I want to do it via sql script.</p>
|
[
{
"answer_id": 6172468,
"author": "bkaid",
"author_id": 265570,
"author_profile": "https://Stackoverflow.com/users/265570",
"pm_score": 3,
"selected": false,
"text": "alter login mylogin with password = 'mylogin'\n"
},
{
"answer_id": 10925471,
"author": "Nagendra Mishr",
"author_id": 1441254,
"author_profile": "https://Stackoverflow.com/users/1441254",
"pm_score": 5,
"selected": false,
"text": "alter login mylogin with password = 'mylogin'\n alter login mylogin with password = 'mylogin' old_password='oldpassword'\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642688/"
] |
56,943 |
<p>I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.</p>
<pre><code>if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
</code></pre>
|
[
{
"answer_id": 56970,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": -1,
"selected": false,
"text": "int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType) JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION"
},
{
"answer_id": 63063,
"author": "Carlos Carrasco",
"author_id": 7027,
"author_profile": "https://Stackoverflow.com/users/7027",
"pm_score": 4,
"selected": true,
"text": "public class MyPrompter implements CommandListener {\n\n private Alert yesNoAlert;\n\n private Command softKey1;\n private Command softKey2;\n\n private boolean status;\n\n public MyPrompter() {\n yesNoAlert = new Alert(\"Attention\");\n yesNoAlert.setString(\"Are you sure?\");\n softKey1 = new Command(\"No\", Command.BACK, 1);\n softKey2 = new Command(\"Yes\", Command.OK, 1);\n yesNoAlert.addCommand(softKey1);\n yesNoAlert.addCommand(softKey2);\n yesNoAlert.setCommandListener(this);\n status = false;\n }\n\n public Displayable getDisplayable() {\n return yesNoAlert;\n }\n\n public boolean getStatus() {\n return status;\n }\n\n public void commandAction(Command c, Displayable d) {\n status = c.getCommandType() == Command.OK;\n // maybe do other stuff here. remember this is asynchronous\n }\n\n};\n MyPrompter prompt = new MyPrompter();\nDisplay.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5896/"
] |
56,946 |
<p>Say I have:</p>
<pre><code><ul>
<li id="x">
<a href="x">x</a>
</li>
<li id="y">
<a href="y">y</a>
<ul>
<li id="z">
<a href="z">z</a>
</li>
</ul>
</li>
</ul>
</code></pre>
<p>I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.</p>
<p>Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 58329,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 1,
"selected": false,
"text": "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n\n <xsl:variable name=\"ancestors\" select=\"descendant::li[@id = 'z']/ancestor::li\"/>\n\n <xsl:template match=\"li\">\n <xsl:copy>\n <!-- test if current li is in the $ancestors node-list -->\n <xsl:if test=\"count($ancestors | .) = count($ancestors)\">\n <xsl:attribute name=\"class\">ancestor</xsl:attribute>\n </xsl:if>\n <xsl:apply-templates select=\"node() | @*\"/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"node() | @*\">\n <xsl:copy>\n <xsl:apply-templates select=\"node() | @*\"/>\n </xsl:copy>\n </xsl:template>\n\n</xsl:stylesheet>\n"
},
{
"answer_id": 58365,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "$(\"#z\").parent().parent().addClass(\"foo\");\n"
},
{
"answer_id": 59496,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 0,
"selected": false,
"text": "$('#z').parents('li').addClass('myClass');"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
56,947 |
<p>In follow up to <a href="https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly">this question</a>, it appears that some numbers cannot be represented by floating point at all, and instead are approximated.</p>
<p>How are floating point numbers stored?</p>
<p>Is there a common standard for the different sizes?</p>
<p>What kind of gotchas do I need to watch out for if I use floating point?</p>
<p>Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?</p>
|
[
{
"answer_id": 56962,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "BigDecimal"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/56947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.