qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
40,873 |
<p>I have a table which is full of arbitrarily formatted phone numbers, like this</p>
<pre><code>027 123 5644
021 393-5593
(07) 123 456
042123456
</code></pre>
<p>I need to search for a phone number in a similarly arbitrary format ( e.g. <code>07123456</code> should find the entry <code>(07) 123 456</code></p>
<p>The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby)</p>
<pre><code>digits_only = lambda{ |n| n.gsub /[^\d]/, '' }
needle = digits_only[input_phone_number]
haystack.map(&digits_only).include?(needle)
</code></pre>
<p>The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want.</p>
<p>Currently I can think of 2 'solutions'</p>
<ul>
<li>Hack together a franken-query of <code>CONCAT</code> and <code>SUBSTR</code></li>
<li>Insert a <code>%</code> between every character of the needle ( so it's like this: <code>%0%7%1%2%3%4%5%6%</code> )</li>
</ul>
<p>However, neither of these seem like particularly elegant solutions.<br />
Hopefully someone can help or I might be forced to use the %%%%%% solution</p>
<h3>Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over.</h3>
<p>If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback!</p>
<hr />
<blockquote>
<p>could you use a "replace" function to strip out any instances of "(", "-" and " ",</p>
</blockquote>
<p>I'm not concerned about the result being numeric.
The main characters I need to consider are <code>+</code>, <code>-</code>, <code>(</code>, <code>)</code> and <code>space</code>
So would that solution look like this?</p>
<pre><code>SELECT * FROM people
WHERE
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+')
LIKE '123456'
</code></pre>
<p>Wouldn't that be terribly slow?</p>
|
[
{
"answer_id": 40904,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "\"(027) 123 456\" 027 12 3456 027123456 \"^[\\D]+0[\\D]+2[\\D]+7[\\D]+1[\\D]+2[\\D]+3[\\D]+4[\\D]+5[\\D]+6$\"\n \\D"
},
{
"answer_id": 40938,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "mre = mobile_number && ('%' + mobile_number.gsub(/\\D/, '').scan(/./m).join('%'))\n\nfind(:first, :conditions => ['trim(mobile_phone) like ?', mre])\n"
},
{
"answer_id": 4585143,
"author": "Michael Bagryantcev",
"author_id": 529115,
"author_profile": "https://Stackoverflow.com/users/529115",
"pm_score": 2,
"selected": false,
"text": "$tmp_phone = '';\nfor ($i=0; $i < strlen($phone); $i++)\n if (is_numeric($phone[$i]))\n $tmp_phone .= '%'.$phone[$i];\n$tmp_phone .= '%';\n$search_condition .= \" and phone LIKE '\" . $tmp_phone . \"' \";\n"
},
{
"answer_id": 18870782,
"author": "Sathish",
"author_id": 1064360,
"author_profile": "https://Stackoverflow.com/users/1064360",
"pm_score": 0,
"selected": false,
"text": "DELIMITER //\n\nCREATE FUNCTION udfn_GetPhoneRegex\n( \n var_Input VARCHAR(25)\n)\nRETURNS VARCHAR(200)\n\nBEGIN\n DECLARE iterator INT DEFAULT 1;\n DECLARE phoneregex VARCHAR(200) DEFAULT '';\n\n DECLARE output VARCHAR(25) DEFAULT '';\n\n\n WHILE iterator < (LENGTH(var_Input) + 1) DO\n IF SUBSTRING(var_Input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN\n SET output = CONCAT(output, SUBSTRING(var_Input, iterator, 1));\n END IF;\n SET iterator = iterator + 1;\n END WHILE;\n SET output = RIGHT(output,10);\n SET iterator = 1;\n WHILE iterator < (LENGTH(output) + 1) DO\n SET phoneregex = CONCAT(phoneregex,'[^0-9]*',SUBSTRING(output, iterator, 1));\n SET iterator = iterator + 1;\n END WHILE;\n SET phoneregex = CONCAT(phoneregex,'$');\n RETURN phoneregex;\nEND//\nDELIMITER ;\n DECLARE var_PhoneNumberRegex VARCHAR(200);\nSET var_PhoneNumberRegex = udfn_GetPhoneRegex('+ 123 555 7890');\nSELECT * FROM Customer WHERE phonenumber REGEXP var_PhoneNumberRegex;\n"
},
{
"answer_id": 21316683,
"author": "Nihal",
"author_id": 3229181,
"author_profile": "https://Stackoverflow.com/users/3229181",
"pm_score": 3,
"selected": false,
"text": "select * from phone_table where phone1 REGEXP \"07[^0-9]*123[^0-9]*456\"\n phonenumber"
},
{
"answer_id": 60871662,
"author": "Bréndal Teixeira",
"author_id": 5221538,
"author_profile": "https://Stackoverflow.com/users/5221538",
"pm_score": 2,
"selected": false,
"text": "SELECT REGEXP_REPLACE(column_name, '[^0-9]', '') phone_formatted FROM table_name\n SELECT phone_formatted FROM (\n SELECT REGEXP_REPLACE(column_name, '[^0-9]', '') phone_formatted FROM table_name\n) AS result WHERE phone_formatted = 9999999999\n"
},
{
"answer_id": 70549733,
"author": "ideaztech",
"author_id": 3131411,
"author_profile": "https://Stackoverflow.com/users/3131411",
"pm_score": 1,
"selected": false,
"text": "$phone = '(456) 584-5874' // can be any format\n$phone = preg_replace('/[^0-9]/', '', $phone); // strip non-numeric characters\n$len = strlen($phone); // get length of phone number\nfor ($i = 0; $i < $len - 1; $i++) {\n $regex .= $phone[$i] . \"[^[:digit:]]*\";\n}\n$regex .= $phone[$len - 1];\n $sql = \"SELECT Client FROM tb_clients WHERE Phone RLIKE '$regex'\"\n"
},
{
"answer_id": 71467126,
"author": "Meloman",
"author_id": 2282880,
"author_profile": "https://Stackoverflow.com/users/2282880",
"pm_score": 0,
"selected": false,
"text": "phone mobile /^(\\+[0-9][0-9]\\s*|0|)7.*/mgix\n UPDATE `contact` \nSET `mobile` = `phone`,\n `phone` = ''\nWHERE `phone` REGEXP '^(\\\\+[\\D+][0-9]\\\\s*|0|)(7.*)$'\n -/.()"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/40873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] |
40,884 |
<p>How can I go about storing a vb.net user defined object in a sql database. I am not trying to replicate the properties with columns. I mean something along the lines of converting or encoding my object to a byte array and then storing that in a field in the db. Like when you store an instance of an object in session, but I need the info to persist past the current session. </p>
<hr>
<p>@Orion Edwards</p>
<blockquote>
<p>It's not a matter of stances. It's because one day, you will change your code. Then you will try de-serialize the old object, and YOUR PROGRAM WILL CRASH.</p>
</blockquote>
<p>My Program will not "CRASH", it will throw an exception. Lucky for me .net has a whole set of classes dedicated for such an occasion. At which time I will refresh my stale data and put it back in the db. That is the point of this one field (or stance, as the case may be).</p>
|
[
{
"answer_id": 41126,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 0,
"selected": false,
"text": " #'res is my object to serialize\n Dim xml_serializer As System.Xml.Serialization.XmlSerializer\n Dim string_writer As New System.IO.StringWriter()\n xml_serializer = New System.Xml.Serialization.XmlSerializer(res.GetType)\n xml_serializer.Serialize(string_writer, res)\n #'string_writer and xml_serializer from above\n Dim serialization As String = string_writer.ToString\n Dim string_reader As System.IO.StringReader\n string_reader = New System.IO.StringReader(serialization)\n Dim res2 As testsedie.EligibilityResponse\n res2 = xml_serializer.Deserialize(string_reader)\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/40884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777/"
] |
40,912 |
<p>I'm looking for a way to check within <code>pageLoad()</code> if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time.</p>
<p>This is similar to <code>Page.IsPostback</code> property within code behind page.</p>
<p>TIA,
Ricky</p>
|
[
{
"answer_id": 40981,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 2,
"selected": false,
"text": " function pageLoad(sender, arg) {\n if (!arg.get_isPartialLoad()) {\n //code to be executed only on the first load\n }\n }\n"
},
{
"answer_id": 45189,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": true,
"text": "Sys.Application.add_init(AppInit);\n\nfunction AppInit() {\n Sys.Application.add_load(RunOnce);\n}\n\nfunction RunOnce() {\n // This will only happen once per GET request to the page.\n\n Sys.Application.remove_load(RunOnce);\n}\n"
},
{
"answer_id": 75248,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 0,
"selected": false,
"text": "public static bool isAjaxRequest(System.Web.HttpRequest request)\n {//Checks to see if the request is an Ajax request\n if (request.ServerVariables[\"HTTP_X_MICROSOFTAJAX\"] != null ||\n request.Form[\"__CALLBACKID\"] != null)\n return true;\n else\n return false;\n }\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/40912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4191/"
] |
40,913 |
<p>I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: </p>
<pre><code><DataTable>
<Row>
<text>foo</text>
</Row>
<Row>
<text>bar</text>
</Row>
</DataTable>
</code></pre>
<p>When the webservice result event is fired I do something like this:</p>
<pre><code>for(var i:int=0;i&lt;event.result.DataTable.Row.length;i++)
{
if(event.result.DataTable.Row[i].text == "foo")
mx.controls.Alert.show('foo found!');
}
</code></pre>
<p>This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the <em>event.DataTable.Row</em> object is not an error and the code subsequently breaks. </p>
<p>What is the proper way to loop through the <em>HTTPService</em> result object? Do I need to convert it to some type of <em>XMLList</em> collection or an <em>ArrayCollection</em>? I have tried setting the resultFormat to <em>e4x</em> and that has yet to fix the problem...</p>
<p>Thanks.</p>
|
[
{
"answer_id": 40930,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 2,
"selected": false,
"text": "if (exists(event.result.DataTable) && exists(event.result.DataTable.Row)){\n if (exists(event.result.DataTable.Row.length)) {\n for(var i:int=0;i<event.result.DataTable.Row.length;i++)\n {\n if (exists(event.result.DataTable.Row[i].text)\n && \"foo\" == event.result.DataTable.Row[i].text)\n mx.controls.Alert.show('foo found!');\n }\n }\n if (exists(event.result.DataTable.Row.text)\n && \"foo\" == event.result.DataTable.Row.text)\n mx.controls.Alert.show('foo found!');\n}\n"
},
{
"answer_id": 40937,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 1,
"selected": false,
"text": "var returnedXml:Xml = new Xml(event.result.toString());\n"
},
{
"answer_id": 41222,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": true,
"text": "event.result.DataTable.Row.length\n length XMLList event.result.DataTable.Row.length()\n for each XMLList for each ( var node : XML in event.result.DataTable.Row )\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/40913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
40,923 |
<p>I have a framework written in Perl that sets a bunch of environment variables to support interprocess (typically it is sub process) communication. We keep a sets of key/value pairs in XML-ish files. We tried to make the key names camel-case <code>somethingLikeThis</code>. This all works well.</p>
<p>Recently we have had occasion to pass control (chain) processes from Windows to UNIX. When we spit out the <code>%ENV</code> hash to a file from Windows the <code>somethingLikeThis</code> key becomes <code>SOMETHINGLIKETHIS</code>. When the Unix process picks up the file and reloads the environment and looks up the value of <code>$ENV{somethingLikeThis}</code> it does not exist since UNIX is case sensitive (from the Windows side the same code works fine). </p>
<p>We have since gone back and changed all the keys to UPPERCASE and solved the problem, but that was tedious and caused pain to the users. Is there a way to make Perl on Windows preserve the character case of the keys of the environment hash?</p>
|
[
{
"answer_id": 73849,
"author": "piCookie",
"author_id": 8763,
"author_profile": "https://Stackoverflow.com/users/8763",
"pm_score": 2,
"selected": false,
"text": "my %env = map {/(.*?)=(.*)/;} `set`;\nprint join(' ', sort keys %env);\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/40923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
40,943 |
<p>What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?</p>
<p>I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?</p>
|
[
{
"answer_id": 40945,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 5,
"selected": false,
"text": "header('Content-type: application/pdf');\nheader('Content-Disposition: attachment; filename=\"' . basename($filename) . '\"');\nheader('Content-Transfer-Encoding: binary');\nreadfile($filename);\n"
},
{
"answer_id": 40947,
"author": "Robert Swisher",
"author_id": 1852,
"author_profile": "https://Stackoverflow.com/users/1852",
"pm_score": 7,
"selected": true,
"text": "header(\"Content-Disposition: attachment; filename=\\\"\" . basename($File) . \"\\\"\");\nheader(\"Content-Type: application/octet-stream\");\nheader(\"Content-Length: \" . filesize($File));\nheader(\"Connection: close\");\n"
},
{
"answer_id": 8349390,
"author": "vdbuilder",
"author_id": 1076318,
"author_profile": "https://Stackoverflow.com/users/1076318",
"pm_score": 4,
"selected": false,
"text": "<?php\n header('Content-Type: application/download');\n header('Content-Disposition: attachment; filename=\"example.txt\"');\n header(\"Content-Length: \" . filesize(\"example.txt\"));\n\n $fp = fopen(\"example.txt\", \"r\");\n fpassthru($fp);\n fclose($fp);\n?>\n"
},
{
"answer_id": 10014110,
"author": "Omidoo",
"author_id": 879163,
"author_profile": "https://Stackoverflow.com/users/879163",
"pm_score": 0,
"selected": false,
"text": "$file_name = \"a.txt\";\n\n// extracting the extension:\n$ext = substr($file_name, strpos($file_name,'.')+1);\n\nheader('Content-disposition: attachment; filename='.$file_name);\n\nif(strtolower($ext) == \"txt\")\n{\n header('Content-type: text/plain'); // works for txt only\n}\nelse\n{\n header('Content-type: application/'.$ext); // works for all extensions except txt\n}\nreadfile($decrypted_file_path);\n"
},
{
"answer_id": 68258678,
"author": "gtamborero",
"author_id": 3577257,
"author_profile": "https://Stackoverflow.com/users/3577257",
"pm_score": 1,
"selected": false,
"text": "<?php\n$file = ABSPATH . 'pdf.pdf'; // Where ABSPATH is the absolute server path, not url\n//echo $file; //Be sure you are echoing the absolute path and file name\n$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */\n\nheader('Content-type: application/pdf');\nheader('Content-Disposition: inline; filename=\"' . $filename . '\"');\nheader('Content-Transfer-Encoding: binary');\nheader('Content-Length: ' . filesize($file));\nheader('Accept-Ranges: bytes');\n@readfile($file);\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/40943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
40,957 |
<p>I'm early in development on a web application built in VS2008. I have both a desktop PC (where most of the work gets done) and a laptop (for occasional portability) on which I use AnkhSVN to keep the project code synced. What's the best way to keep my development database (SQL Server Express) synced up as well?</p>
<p>I have a VS database project in SVN containing create scripts which I re-generate when the schema changes. The original idea was to recreate the DB whenever something changed, but it's quickly becoming a pain. Also, I'd lose all the sample rows I entered to make sure data is being displayed properly.</p>
<p>I'm considering putting the .MDF and .LDF files under source control, but I doubt SQL Server Express will handle it gracefully if I do an SVN Update and the files get yanked out from under it, replaced with newer copies. Sticking a couple big binary files into source control doesn't seem like an elegant solution either, even if it is just a throwaway development database. Any suggestions?</p>
|
[
{
"answer_id": 40963,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "use master\ngo\n\nif exists (select * from master.dbo.sysdatabases where name = 'your_db')\nbegin\n alter database your_db set SINGLE_USER with rollback IMMEDIATE\n drop database your_db\nend\n\nrestore database your_db\nfrom disk = 'path\\to\\your\\bak\\file'\nwith move 'Name of dat file' to 'path\\to\\mdf\\file',\n move 'Name of log file' to 'path\\to\\ldf\\file'\ngo\n osql -E -i restore.sql\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/40957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160/"
] |
40,962 |
<p>I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?</p>
|
[
{
"answer_id": 41579,
"author": "Ed Schwehm",
"author_id": 1206,
"author_profile": "https://Stackoverflow.com/users/1206",
"pm_score": 0,
"selected": false,
"text": "private Form pForm;\npublic ChildForm(ref Form parentForm)\n{\n pForm = parentForm;\n}\n\nprivate closeParent()\n{\n if (this.pForm != null)\n this.pForm.Close();\n this.pForm = null;\n}\n"
},
{
"answer_id": 42107,
"author": "Jason Von Ruden",
"author_id": 2062,
"author_profile": "https://Stackoverflow.com/users/2062",
"pm_score": 3,
"selected": false,
"text": " private void btnOpenForm_Click(object sender, EventArgs e)\n {\n Form2 frm2 = new Form2();\n frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);\n frm2.Show();\n this.Hide();\n }\n\n\n private void frm2_FormClosed(object sender, FormClosedEventArgs e)\n {\n this.Close();\n }\n"
},
{
"answer_id": 45595945,
"author": "Keyur Sureliya",
"author_id": 4454558,
"author_profile": "https://Stackoverflow.com/users/4454558",
"pm_score": 0,
"selected": false,
"text": "Process.Start(\"Your_App's_EXE_Full_Path.exe\"); string FullPath = Environment.CurrentDirectory + \"\\\\YourAppName.exe\"; Process.Start(FullPath); this.Close();"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/40962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2062/"
] |
40,966 |
<p>I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).</p>
<p>Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?</p>
<p>For example:</p>
<pre><code>function updateDOM(id) {
// updates the id element based on form state
}
</code></pre>
<p>should I invoke it via:</p>
<pre><code>window.onload = function() { updateDOM("myElement"); };
</code></pre>
<p>or:</p>
<pre><code><div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
</code></pre>
<p>The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.</p>
<p>Any thoughts? Is one version really better than the other?</p>
|
[
{
"answer_id": 40972,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "onload"
},
{
"answer_id": 41008,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "onload"
},
{
"answer_id": 41011,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "window.addEvent('domready', function() {\n alert(\"The DOM is ready.\");\n});\n"
},
{
"answer_id": 41013,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 4,
"selected": false,
"text": "$(document).ready(function(){\n // manipulate the DOM all you want here\n});\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/40966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
40,999 |
<p>Here's a quick question I've been banging my head against today.</p>
<p>I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. </p>
<p>Here's the current solution:</p>
<pre><code> string transformXML = @"pathToXslDocument";
XmlDocument originalXml = new XmlDocument();
XmlDocument transformedXml = new XmlDocument();
XslCompiledTransform transformer = new XslCompiledTransform();
DataSet ds = new DataSet();
string filepath;
originalXml.LoadXml(ds.GetXml()); //data loaded prior
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
transformer.Load(transformXML);
transformer.Transform(originalXml, writer); //no need to select the node
transformedXml.LoadXml(sb.ToString());
transformedXml.Save(filepath);
writer.Close();
</code></pre>
<p>Here's the original code:</p>
<pre><code>BufferedStream stream = new BufferedStream(new MemoryStream());
DataSet ds = new DataSet();
da.Fill(ds);
ds.WriteXml(stream);
StreamReader sr = new StreamReader(stream, true);
stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset.
XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load(@"<path to xsl file>");
transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null)
</code></pre>
<p>For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader.</p>
<p>My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML?</p>
<p>Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.</p>
|
[
{
"answer_id": 41012,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": " BufferedStream stream = new BufferedStream(new MemoryStream());\n stream.Write(Encoding.ASCII.GetBytes(\"<xml>foo</xml>\"), 0, \"<xml>foo</xml>\".Length);\n stream.Seek(0, SeekOrigin.Begin);\n StreamReader sr = new StreamReader(stream);\n XmlReader reader = XmlReader.Create(sr);\n while (reader.Read())\n {\n Console.WriteLine(reader.Value);\n }\n stream.Close();\n"
},
{
"answer_id": 41020,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument();\norgDoc.LoadXml(orgXML);\n\n// MUST SELECT THE ROOT NODE\nXmlNode transNode = orgDoc.SelectSingleNode(\"/\");\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nXmlWriter writer = XmlWriter.Create(sb);\n\nSystem.IO.StringReader stream = new System.IO.StringReader(transformXML);\nXmlReader reader = XmlReader.Create(stream);\n\nSystem.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();\ntrans.Load(reader);\ntrans.Transform(transNode, writer);\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(sb.ToString());\n\nreturn doc;\n"
},
{
"answer_id": 28757385,
"author": "user1453680",
"author_id": 1453680,
"author_profile": "https://Stackoverflow.com/users/1453680",
"pm_score": 0,
"selected": false,
"text": "using (MemoryStream memStream = new MemoryStream())\n {\n memStream.Write(Encoding.UTF8.GetBytes(xmlBody), 0, xmlBody.Length);\n memStream.Seek(0, SeekOrigin.Begin);\n\n using (StreamReader reader = new StreamReader(memStream))\n {\n // xml reader setting.\n XmlReaderSettings xmlReaderSettings = new XmlReaderSettings()\n {\n IgnoreComments = true,\n IgnoreWhitespace = true,\n\n };\n\n // xml reader create.\n using (XmlReader xmlReader = XmlReader.Create(reader, xmlReaderSettings))\n { \n XmlSerializer xmlSerializer = new XmlSerializer(typeof(LoginInfo));\n myObject = (LoginInfo)xmlSerializer.Deserialize(xmlReader);\n\n }\n\n } \n }\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/40999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2916/"
] |
41,010 |
<p><strong>A Little Background Information</strong>:<br>
I've been looking at a few PHP framework recently, and it came down to two. The Zend Framework or CodeIgniter. </p>
<p>I prefer CodeIgniter, because of its simple design. It's very bare bone, and it is just kept simple. The thing I don't like though is the weak template system. The template system is important for me, because I will be working with another designer. Being able to give him a good template system is a big plus.</p>
<p>Zend was the second choice, because of the better template system that is built in. Zend is a different beast though compared to CodeIgniter. It emphasis "loose coupling between modules", but is a bigger framework. I don't like to feel like I have many things running under the hood that I never use. That is unnecessary overhead in my opinion, so I thought about putting a template system into CodeIgniter: Smarty.</p>
<p><strong>Question(s)</strong>: How easy/hard is the process to integrate Smarty into CodeIgniter? From my initial scan of the CodeIgniter documentation, I can see that the layout of the framework is easy enough to understand, and I anticipate no problems. I want to know if anyone has used it before, and therefore are aware of any "gotchas" you my have experienced that is going to make this harder than it should be or impossible to pull off. I also want to know if this is a good thing to do at all. Is the template system in CodeIgniter enough for normal use? Are there any other template modules that are good for CodeIgniter aside from Smarty? I better off with Zend Framework? Is any wheel being invented here?</p>
|
[
{
"answer_id": 30263642,
"author": "Luca Mori Polpettini",
"author_id": 2270716,
"author_profile": "https://Stackoverflow.com/users/2270716",
"pm_score": 0,
"selected": false,
"text": "<?php\nif ( ! defined('BASEPATH')) exit('No direct script access allowed');\n\nrequire_once(APPPATH.'third_party/smarty/Smarty.class.php');\n\nclass Custom_smarty extends Smarty {\n\n function __construct()\n {\n parent::__construct();\n $this->setTemplateDir(APPPATH.'views/templates/'); \n $this->setCompileDir(APPPATH.'views/templates_c/');\n }\n}\n?>\n $autoload['libraries'] = array('custom_smarty');\n $this->custom_smarty->display('test.tpl'); sudo chmod -R 777 templates_c"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
] |
41,018 |
<p>Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application?</p>
|
[
{
"answer_id": 12075345,
"author": "anataliocs",
"author_id": 555177,
"author_profile": "https://Stackoverflow.com/users/555177",
"pm_score": 2,
"selected": false,
"text": "dataSource {\n pooled = true\n driverClassName = \"org.h2.Driver\"\n username = \"sa\"\n password = \"\"\n}\ndataSource_mysql {\n dialect = org.hibernate.dialect.MySQLInnoDBDialect\n driverClassName = 'com.mysql.jdbc.Driver'\n username = \"user\"\n password = \"pass\"\n url = \"jdbc:mysql://mysqldb.com/DBNAME\"\n}\nhibernate {\n cache.use_second_level_cache = true\n cache.use_query_cache = false\n cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'\n}\n\n// environment specific settings\nenvironments {\n development {\n dataSource {\n configClass = HibernateFilterDomainConfiguration.class\n dbCreate = \"update\" // one of 'create', 'create-drop', 'update', 'validate', ''\n url = \"jdbc:h2:file:../devDb;MVCC=TRUE\"\n sqlLogging = true\n }\n }\n test {\n dataSource_mysql {\n configClass = HibernateFilterDomainConfiguration.class\n dbCreate = \"create\" // one of 'create', 'create-drop', 'update', 'validate', ''\n sqlLogging = true\n }\n }\n production {\n dataSource {\n dbCreate = \"update\"\n url = \"jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000\"\n pooled = true\n properties {\n maxActive = -1\n minEvictableIdleTimeMillis=1800000\n timeBetweenEvictionRunsMillis=1800000\n numTestsPerEvictionRun=3\n testOnBorrow=true\n testWhileIdle=true\n testOnReturn=true\n validationQuery=\"SELECT 1\"\n }\n }\n }\n}\n"
},
{
"answer_id": 14894944,
"author": "Sushanth CS",
"author_id": 363345,
"author_profile": "https://Stackoverflow.com/users/363345",
"pm_score": 5,
"selected": false,
"text": "development {\n dataSource {//DEFAULT data source\n .\n .\n }\ndataSource_admin { //Convention is dataSource_name\n url = \"//db url\"\n driverClassName = \"oracle.jdbc.driver.OracleDriver\" \n username = \"test\"\n password = 'test123'\n }\ndataSource_users {\n\n }\n}\n class Role{\n static mapping = {\n datasource 'users'\n }\n}\n\n class Product{\n static mapping = {\n datasource 'admin'\n }\n }\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453/"
] |
41,027 |
<p>I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list.</p>
<p>The produced HTML needs to be standards compliant as well.</p>
<p>I have tried <a href="http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html" rel="noreferrer">liScroll</a> but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists.</p>
<p>I have also tried <a href="http://www.mioplanet.com/rsc/newsticker_javascript.htm" rel="noreferrer">this News Ticker</a> but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle.</p>
<p>Any suggestions are appreciated.</p>
<p><strong>Edit</strong></p>
<p>So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible.</p>
<p>Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping.</p>
|
[
{
"answer_id": 40595802,
"author": "tj001",
"author_id": 7052915,
"author_profile": "https://Stackoverflow.com/users/7052915",
"pm_score": 0,
"selected": false,
"text": "<li> </li>"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
41,039 |
<p>Is there a way to search the latest version of every file in TFS for a specific string or regex? This is probably the only thing I miss from Visual Source Safe... </p>
<p>Currently I perform a Get Latest on the entire codebase and use Windows Search, but this gets quite painful with over 1GB of code in 75,000 files. </p>
<p><strong>EDIT</strong>: Tried the powertools mentioned, but the "Wildcard Search" option appears to only search filenames and not contents.</p>
<p><strong>UPDATE</strong>: We have implemented a customised search option in an existing MOSS (Search Server) installation. </p>
|
[
{
"answer_id": 78966,
"author": "granth",
"author_id": 11210,
"author_profile": "https://Stackoverflow.com/users/11210",
"pm_score": 7,
"selected": true,
"text": "foo foo OR bar class:WebRequest"
},
{
"answer_id": 23023410,
"author": "Vijayanand Settin",
"author_id": 2125810,
"author_profile": "https://Stackoverflow.com/users/2125810",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.TeamFoundation.Client;\nusing Microsoft.TeamFoundation.VersionControl.Client;\nusing Microsoft.TeamFoundation.Framework.Client;\nusing System.IO;\n\nnamespace TFSSearch\n{\nclass Program\n{\n static string[] textPatterns = new[] { \"void main(\", \"exception\", \"RegisterScript\" }; //Text to search\n static string[] filePatterns = new[] { \"*.cs\", \"*.xml\", \"*.config\", \"*.asp\", \"*.aspx\", \"*.js\", \"*.htm\", \"*.html\", \n \"*.vb\", \"*.asax\", \"*.ashx\", \"*.asmx\", \"*.ascx\", \"*.master\", \"*.svc\"}; //file extensions\n\n static void Main(string[] args)\n {\n try\n {\n var tfs = TfsTeamProjectCollectionFactory\n .GetTeamProjectCollection(new Uri(\"http://{tfsserver}:8080/tfs/}\")); // one some servers you also need to add collection path (if it not the default collection)\n\n tfs.EnsureAuthenticated();\n\n var versionControl = tfs.GetService<VersionControlServer>();\n\n\n StreamWriter outputFile = new StreamWriter(@\"C:\\Find.txt\");\n var allProjs = versionControl.GetAllTeamProjects(true);\n foreach (var teamProj in allProjs)\n {\n foreach (var filePattern in filePatterns)\n {\n var items = versionControl.GetItems(teamProj.ServerItem + \"/\" + filePattern, RecursionType.Full).Items\n .Where(i => !i.ServerItem.Contains(\"_ReSharper\")); //skipping resharper stuff\n foreach (var item in items)\n {\n List<string> lines = SearchInFile(item);\n if (lines.Count > 0)\n {\n outputFile.WriteLine(\"FILE:\" + item.ServerItem);\n outputFile.WriteLine(lines.Count.ToString() + \" occurence(s) found.\");\n outputFile.WriteLine();\n }\n foreach (string line in lines)\n {\n outputFile.WriteLine(line);\n }\n if (lines.Count > 0)\n {\n outputFile.WriteLine();\n }\n }\n }\n outputFile.Flush();\n }\n }\n catch (Exception e)\n {\n string ex = e.Message;\n Console.WriteLine(\"!!EXCEPTION: \" + e.Message);\n Console.WriteLine(\"Continuing... \");\n }\n Console.WriteLine(\"========\");\n Console.Read();\n }\n\n // Define other methods and classes here\n private static List<string> SearchInFile(Item file)\n {\n var result = new List<string>();\n\n try\n {\n var stream = new StreamReader(file.DownloadFile(), Encoding.Default);\n\n var line = stream.ReadLine();\n var lineIndex = 0;\n\n while (!stream.EndOfStream)\n {\n if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))\n result.Add(\"=== Line \" + lineIndex + \": \" + line.Trim());\n\n line = stream.ReadLine();\n lineIndex++;\n }\n }\n catch (Exception e)\n {\n string ex = e.Message;\n Console.WriteLine(\"!!EXCEPTION: \" + e.Message);\n Console.WriteLine(\"Continuing... \");\n }\n\n return result;\n }\n}\n}\n"
},
{
"answer_id": 35325425,
"author": "deadlydog",
"author_id": 602585,
"author_profile": "https://Stackoverflow.com/users/602585",
"pm_score": 3,
"selected": false,
"text": "Code Search"
},
{
"answer_id": 39671659,
"author": "Greg",
"author_id": 3166138,
"author_profile": "https://Stackoverflow.com/users/3166138",
"pm_score": 1,
"selected": false,
"text": "$/ sql *.sql \"$/myproject/*.sql\""
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952/"
] |
41,045 |
<p>As a general rule, I prefer using value rather than pointer semantics in C++ (ie using <code>vector<Class></code> instead of <code>vector<Class*></code>). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.</p>
<p>Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.</p>
<pre><code>#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : parent_mem(1) {}
virtual void write() { cout << "Parent: " << parent_mem << endl; }
int parent_mem;
};
class Child : public Parent
{
public:
Child() : child_mem(2) { parent_mem = 2; }
void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }
int child_mem;
};
int main(int, char**)
{
// I can have a polymorphic container with pointer semantics
vector<Parent*> pointerVec;
pointerVec.push_back(new Parent());
pointerVec.push_back(new Child());
pointerVec[0]->write();
pointerVec[1]->write();
// Output:
//
// Parent: 1
// Child: 2, 2
// But I can't do it with value semantics
vector<Parent> valueVec;
valueVec.push_back(Parent());
valueVec.push_back(Child()); // gets turned into a Parent object :(
valueVec[0].write();
valueVec[1].write();
// Output:
//
// Parent: 1
// Parent: 2
}
</code></pre>
<p>My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?</p>
|
[
{
"answer_id": 41059,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 6,
"selected": true,
"text": "vector<shared_ptr<Parent>> vec;\nvec.push_back(shared_ptr<Parent>(new Child()));\n"
},
{
"answer_id": 41103,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 3,
"selected": false,
"text": " // But you sort of can do it with boost::any.\n\n vector<any> valueVec;\n\n valueVec.push_back(any(Parent()));\n valueVec.push_back(any(Child())); // remains a Child, wrapped in an Any.\n\n Parent p = any_cast<Parent>(valueVec[0]);\n Child c = any_cast<Child>(valueVec[1]);\n p.write();\n c.write();\n\n // Output:\n //\n // Parent: 1\n // Child: 2, 2\n\n // Now try casting the child as a parent.\n try {\n Parent p2 = any_cast<Parent>(valueVec[1]);\n p2.write();\n }\n catch (const boost::bad_any_cast &e)\n {\n cout << e.what() << endl;\n }\n\n // Output:\n // boost::bad_any_cast: failed conversion using boost::any_cast\n"
},
{
"answer_id": 49720854,
"author": "dragly",
"author_id": 632150,
"author_profile": "https://Stackoverflow.com/users/632150",
"pm_score": 3,
"selected": false,
"text": "class Shape\n{\npublic:\n template<typename T>\n Shape(T t)\n : container(std::make_shared<Model<T>>(std::move(t)))\n {}\n\n friend void draw(const Shape &shape)\n {\n shape.container->drawImpl();\n }\n // add more functions similar to draw() here if you wish\n // remember also to add a wrapper in the Concept and Model below\n\nprivate:\n struct Concept\n {\n virtual ~Concept() = default;\n virtual void drawImpl() const = 0;\n };\n\n template<typename T>\n struct Model : public Concept\n {\n Model(T x) : m_data(move(x)) { }\n void drawImpl() const override\n {\n draw(m_data);\n }\n T m_data;\n };\n\n std::shared_ptr<const Concept> container;\n};\n struct Circle\n{\n const double radius = 4.0;\n};\n\nstruct Rectangle\n{\n const double width = 2.0;\n const double height = 3.0;\n};\n\nvoid draw(const Circle &circle)\n{\n cout << \"Drew circle with radius \" << circle.radius << endl;\n}\n\nvoid draw(const Rectangle &rectangle)\n{\n cout << \"Drew rectangle with width \" << rectangle.width << endl;\n}\n Circle Rectangle std::vector<Shape> int main() {\n std::vector<Shape> shapes;\n shapes.emplace_back(Circle());\n shapes.emplace_back(Rectangle());\n for (const auto &shape : shapes) {\n draw(shape);\n }\n return 0;\n}\n int main() {\n Shape a = Circle();\n Shape b = Rectangle();\n b = a;\n draw(a);\n draw(b);\n return 0;\n}\n Drew rectangle with width 2\nDrew rectangle with width 2\n shared_ptr unique_ptr"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994/"
] |
41,089 |
<p>I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this?</p>
<p>I have:</p>
<pre><code>Dim b As CommandButton
Set b = ocx.GetButton("btnPrint")
SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd
</code></pre>
<p>but it doesn't seem to work.</p>
|
[
{
"answer_id": 41521,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 3,
"selected": true,
"text": "Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n CommandButton CheckBox CommandButton Value Click ToggleButton"
},
{
"answer_id": 41543,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "CMyWindow::OnLButtonDown()\n{\n this->FooBar();\n}\n #define WM_FOOBAR WM_APP + 1\n SendMessage SendMessage(WM_FOOBAR, ...)"
},
{
"answer_id": 42802,
"author": "dan gibson",
"author_id": 4495,
"author_profile": "https://Stackoverflow.com/users/4495",
"pm_score": 0,
"selected": false,
"text": "Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n WM_LBUTTONDOWN"
},
{
"answer_id": 156328,
"author": "sharvell",
"author_id": 23095,
"author_profile": "https://Stackoverflow.com/users/23095",
"pm_score": 0,
"selected": false,
"text": "Private Declare Function SendMessage Lib \"user32\" Alias \"SendMessageA\" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long\nConst WM_KEYDOWN As Integer = &H100\nConst WM_KEYUP As Integer = &H101\nConst VK_SPACE = &H20\n\nPrivate Sub cmdCommand1_Click()\n Dim b As CommandButton\n Set b = ocx.GetButton(\"btnPrint\")\n SendMessage b.hWnd, WM_KEYDOWN, VK_SPACE, 0&\n SendMessage b.hWnd, WM_KEYUP, VK_SPACE, 0&\nEnd Sub\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4495/"
] |
41,097 |
<p>The question sort of says it all.</p>
<p>Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. </p>
<p>Bonus points for parsimonious and readable code samples. </p>
|
[
{
"answer_id": 41521,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 3,
"selected": true,
"text": "Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n CommandButton CheckBox CommandButton Value Click ToggleButton"
},
{
"answer_id": 41543,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "CMyWindow::OnLButtonDown()\n{\n this->FooBar();\n}\n #define WM_FOOBAR WM_APP + 1\n SendMessage SendMessage(WM_FOOBAR, ...)"
},
{
"answer_id": 42802,
"author": "dan gibson",
"author_id": 4495,
"author_profile": "https://Stackoverflow.com/users/4495",
"pm_score": 0,
"selected": false,
"text": "Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n WM_LBUTTONDOWN"
},
{
"answer_id": 156328,
"author": "sharvell",
"author_id": 23095,
"author_profile": "https://Stackoverflow.com/users/23095",
"pm_score": 0,
"selected": false,
"text": "Private Declare Function SendMessage Lib \"user32\" Alias \"SendMessageA\" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long\nConst WM_KEYDOWN As Integer = &H100\nConst WM_KEYUP As Integer = &H101\nConst VK_SPACE = &H20\n\nPrivate Sub cmdCommand1_Click()\n Dim b As CommandButton\n Set b = ocx.GetButton(\"btnPrint\")\n SendMessage b.hWnd, WM_KEYDOWN, VK_SPACE, 0&\n SendMessage b.hWnd, WM_KEYUP, VK_SPACE, 0&\nEnd Sub\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069/"
] |
41,107 |
<p>I've been looking for a <em>simple</em> Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over <code>500K+</code> generation (my needs don't really require anything much more sophisticated). </p>
<p>Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like <code>"AEYGF7K0DM1X"</code>. </p>
|
[
{
"answer_id": 41156,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 12,
"selected": true,
"text": "public class RandomString {\n\n /**\n * Generate a random string.\n */\n public String nextString() {\n for (int idx = 0; idx < buf.length; ++idx)\n buf[idx] = symbols[random.nextInt(symbols.length)];\n return new String(buf);\n }\n\n public static final String upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n public static final String lower = upper.toLowerCase(Locale.ROOT);\n\n public static final String digits = \"0123456789\";\n\n public static final String alphanum = upper + lower + digits;\n\n private final Random random;\n\n private final char[] symbols;\n\n private final char[] buf;\n\n public RandomString(int length, Random random, String symbols) {\n if (length < 1) throw new IllegalArgumentException();\n if (symbols.length() < 2) throw new IllegalArgumentException();\n this.random = Objects.requireNonNull(random);\n this.symbols = symbols.toCharArray();\n this.buf = new char[length];\n }\n\n /**\n * Create an alphanumeric string generator.\n */\n public RandomString(int length, Random random) {\n this(length, random, alphanum);\n }\n\n /**\n * Create an alphanumeric strings from a secure generator.\n */\n public RandomString(int length) {\n this(length, new SecureRandom());\n }\n\n /**\n * Create session identifiers.\n */\n public RandomString() {\n this(21);\n }\n\n}\n RandomString gen = new RandomString(8, ThreadLocalRandom.current());\n RandomString session = new RandomString();\n String easy = RandomString.digits + \"ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx\";\nRandomString tickets = new RandomString(23, new SecureRandom(), easy);\n"
},
{
"answer_id": 41177,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 5,
"selected": false,
"text": "import static java.lang.Math.round;\nimport static java.lang.Math.random;\nimport static java.lang.Math.pow;\nimport static java.lang.Math.abs;\nimport static java.lang.Math.min;\nimport static org.apache.commons.lang.StringUtils.leftPad\n\npublic class RandomAlphaNum {\n public static String gen(int length) {\n StringBuffer sb = new StringBuffer();\n for (int i = length; i > 0; i -= 12) {\n int n = min(12, abs(i));\n sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));\n }\n return sb.toString();\n }\n}\n scala> RandomAlphaNum.gen(42)\nres3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy\n"
},
{
"answer_id": 41762,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 10,
"selected": false,
"text": "uuid.replace(\"-\", \"\") import java.util.UUID;\n\npublic class randomStringGenerator {\n public static void main(String[] args) {\n System.out.println(generateString());\n }\n\n public static String generateString() {\n String uuid = UUID.randomUUID().toString();\n return \"uuid = \" + uuid;\n }\n}\n uuid = 2d7428a6-b58c-4008-8575-f05549f16316\n"
},
{
"answer_id": 41772,
"author": "Todd",
"author_id": 3803,
"author_profile": "https://Stackoverflow.com/users/3803",
"pm_score": 3,
"selected": false,
"text": "/**\n * Generate a random hex encoded string token of the specified length\n * \n * @param length\n * @return random hex string\n */\npublic static synchronized String generateUniqueToken(Integer length){ \n byte random[] = new byte[length];\n Random randomGenerator = new Random();\n StringBuffer buffer = new StringBuffer();\n\n randomGenerator.nextBytes(random);\n\n for (int j = 0; j < random.length; j++) {\n byte b1 = (byte) ((random[j] & 0xf0) >> 4);\n byte b2 = (byte) (random[j] & 0x0f);\n if (b1 < 10)\n buffer.append((char) ('0' + b1));\n else\n buffer.append((char) ('A' + (b1 - 10)));\n if (b2 < 10)\n buffer.append((char) ('0' + b2));\n else\n buffer.append((char) ('A' + (b2 - 10)));\n }\n return (buffer.toString());\n}\n\n@Test\npublic void testGenerateUniqueToken(){\n Set set = new HashSet();\n String token = null;\n int size = 16;\n\n /* Seems like we should be able to generate 500K tokens \n * without a duplicate \n */\n for (int i=0; i<500000; i++){\n token = Utility.generateUniqueToken(size);\n\n if (token.length() != size * 2){\n fail(\"Incorrect length\");\n } else if (set.contains(token)) {\n fail(\"Duplicate token generated\");\n } else{\n set.add(token);\n }\n }\n}\n"
},
{
"answer_id": 43496,
"author": "cmsherratt",
"author_id": 3512,
"author_profile": "https://Stackoverflow.com/users/3512",
"pm_score": 9,
"selected": false,
"text": "org.apache.commons.text.RandomStringGenerator RandomStringGenerator randomStringGenerator =\n new RandomStringGenerator.Builder()\n .withinRange('0', 'z')\n .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)\n .build();\nrandomStringGenerator.generate(12); // toUpperCase() if you want\n RandomStringUtils"
},
{
"answer_id": 157202,
"author": "maxp",
"author_id": 21152,
"author_profile": "https://Stackoverflow.com/users/21152",
"pm_score": 9,
"selected": false,
"text": "static final String AB = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\nstatic SecureRandom rnd = new SecureRandom();\n\nString randomString(int len){\n StringBuilder sb = new StringBuilder(len);\n for(int i = 0; i < len; i++)\n sb.append(AB.charAt(rnd.nextInt(AB.length())));\n return sb.toString();\n}\n"
},
{
"answer_id": 1016930,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class AlphaNumericGenerator {\n\n public static void main(String[] args) {\n java.util.Random r = new java.util.Random();\n int i = 1, n = 0;\n char c;\n String str = \"\";\n for (int t = 0; t < 3; t++) {\n while (true) {\n i = r.nextInt(10);\n if (i > 5 && i < 10) {\n\n if (i == 9) {\n i = 90;\n n = 90;\n break;\n }\n if (i != 90) {\n n = i * 10 + r.nextInt(10);\n while (n < 65) {\n n = i * 10 + r.nextInt(10);\n }\n }\n break;\n }\n }\n c = (char)n;\n\n str = String.valueOf(c) + str;\n }\n\n while(true){\n i = r.nextInt(10000000);\n if(i > 999999)\n break;\n }\n str = str + i;\n System.out.println(str);\n }\n}\n"
},
{
"answer_id": 1439556,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "Long.toHexString(Double.doubleToLongBits(Math.random()));\n"
},
{
"answer_id": 2178588,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 5,
"selected": false,
"text": "// \"0123456789\" + \"ABCDE...Z\"\nString validCharacters = $('0', '9').join() + $('A', 'Z').join();\n\nString randomString(int length) {\n return $(validCharacters).shuffle().slice(length).toString();\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n for (int i : $(5)) {\n System.out.println(randomString(12));\n }\n}\n DKL1SBH9UJWC\nJH7P0IT21EA5\n5DTI72EO6SFU\nHQUMJTEBNF7Y\n1HCR6SKYWGT7\n"
},
{
"answer_id": 6530353,
"author": "Suganya",
"author_id": 822390,
"author_profile": "https://Stackoverflow.com/users/822390",
"pm_score": 3,
"selected": false,
"text": "import java.util.*;\nimport javax.swing.*;\n\npublic class alphanumeric {\n public static void main(String args[]) {\n String nval, lenval;\n int n, len;\n\n nval = JOptionPane.showInputDialog(\"Enter number of codes you require: \");\n n = Integer.parseInt(nval);\n\n lenval = JOptionPane.showInputDialog(\"Enter code length you require: \");\n len = Integer.parseInt(lenval);\n\n find(n, len);\n }\n\n public static void find(int n, int length) {\n String str1 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n StringBuilder sb = new StringBuilder(length);\n Random r = new Random();\n\n System.out.println(\"\\n\\t Unique codes are \\n\\n\");\n for(int i=0; i<n; i++) {\n for(int j=0; j<length; j++) {\n sb.append(str1.charAt(r.nextInt(str1.length())));\n }\n System.out.println(\" \" + sb.toString());\n sb.delete(0, length);\n }\n }\n}\n"
},
{
"answer_id": 7816591,
"author": "Jameskittu",
"author_id": 367407,
"author_profile": "https://Stackoverflow.com/users/367407",
"pm_score": 3,
"selected": false,
"text": "import java.util.Date;\nimport java.util.Random;\n\npublic class RandomGenerator {\n\n private static Random random = new Random((new Date()).getTime());\n\n public static String generateRandomString(int length) {\n char[] values = {'a','b','c','d','e','f','g','h','i','j',\n 'k','l','m','n','o','p','q','r','s','t',\n 'u','v','w','x','y','z','0','1','2','3',\n '4','5','6','7','8','9'};\n\n String out = \"\";\n\n for (int i=0;i<length;i++) {\n int idx=random.nextInt(values.length);\n out += values[idx];\n }\n return out;\n }\n}\n"
},
{
"answer_id": 10177396,
"author": "cmpbah",
"author_id": 1336707,
"author_profile": "https://Stackoverflow.com/users/1336707",
"pm_score": 4,
"selected": false,
"text": "import java.util.Random;\n\npublic class passGen{\n // Version 1.0\n private static final String dCase = \"abcdefghijklmnopqrstuvwxyz\";\n private static final String uCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n private static final String sChar = \"!@#$%^&*\";\n private static final String intChar = \"0123456789\";\n private static Random r = new Random();\n private static StringBuilder pass = new StringBuilder();\n\n public static void main (String[] args) {\n System.out.println (\"Generating pass...\");\n while (pass.length () != 16){\n int rPick = r.nextInt(4);\n if (rPick == 0){\n int spot = r.nextInt(26);\n pass.append(dCase.charAt(spot));\n } else if (rPick == 1) {\n int spot = r.nextInt(26);\n pass.append(uCase.charAt(spot));\n } else if (rPick == 2) {\n int spot = r.nextInt(8);\n pass.append(sChar.charAt(spot));\n } else {\n int spot = r.nextInt(10);\n pass.append(intChar.charAt(spot));\n }\n }\n System.out.println (\"Generated Pass: \" + pass.toString());\n }\n}\n"
},
{
"answer_id": 10189194,
"author": "user unknown",
"author_id": 312172,
"author_profile": "https://Stackoverflow.com/users/312172",
"pm_score": 5,
"selected": false,
"text": "Random r = new java.util.Random ();\nString s = Long.toString (r.nextLong () & Long.MAX_VALUE, 36);\n"
},
{
"answer_id": 10361524,
"author": "Bhavik Ambani",
"author_id": 1145285,
"author_profile": "https://Stackoverflow.com/users/1145285",
"pm_score": 1,
"selected": false,
"text": "public class RandomStringGenerator{\n\n private static int randomStringLength = 25 ;\n private static boolean allowSpecialCharacters = true ;\n private static String specialCharacters = \"!@$%*-_+:\";\n private static boolean allowDuplicates = false ;\n\n private static boolean isAlphanum = false;\n private static boolean isNumeric = false;\n private static boolean isAlpha = false;\n private static final String alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n private static boolean mixCase = false;\n private static final String capAlpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n private static final String num = \"0123456789\";\n\n public static String getRandomString() {\n String returnVal = \"\";\n int specialCharactersCount = 0;\n int maxspecialCharacters = randomStringLength/4;\n\n try {\n StringBuffer values = buildList();\n for (int inx = 0; inx < randomStringLength; inx++) {\n int selChar = (int) (Math.random() * (values.length() - 1));\n if (allowSpecialCharacters)\n {\n if (specialCharacters.indexOf(\"\" + values.charAt(selChar)) > -1)\n {\n specialCharactersCount ++;\n if (specialCharactersCount > maxspecialCharacters)\n {\n while (specialCharacters.indexOf(\"\" + values.charAt(selChar)) != -1)\n {\n selChar = (int) (Math.random() * (values.length() - 1));\n }\n }\n }\n }\n returnVal += values.charAt(selChar);\n if (!allowDuplicates) {\n values.deleteCharAt(selChar);\n }\n }\n } catch (Exception e) {\n returnVal = \"Error While Processing Values\";\n }\n return returnVal;\n }\n\n private static StringBuffer buildList() {\n StringBuffer list = new StringBuffer(0);\n if (isNumeric || isAlphanum) {\n list.append(num);\n }\n if (isAlpha || isAlphanum) {\n list.append(alphabet);\n if (mixCase) {\n list.append(capAlpha);\n }\n }\n if (allowSpecialCharacters)\n {\n list.append(specialCharacters);\n }\n int currLen = list.length();\n String returnVal = \"\";\n for (int inx = 0; inx < currLen; inx++) {\n int selChar = (int) (Math.random() * (list.length() - 1));\n returnVal += list.charAt(selChar);\n list.deleteCharAt(selChar);\n }\n list = new StringBuffer(returnVal);\n return list;\n } \n\n}\n"
},
{
"answer_id": 11577455,
"author": "Manish Singh",
"author_id": 518493,
"author_profile": "https://Stackoverflow.com/users/518493",
"pm_score": 7,
"selected": false,
"text": "RandomStringUtils.randomAlphanumeric(20).toUpperCase();\n"
},
{
"answer_id": 11629612,
"author": "Ugo Matrangolo",
"author_id": 1548481,
"author_profile": "https://Stackoverflow.com/users/1548481",
"pm_score": 2,
"selected": false,
"text": "(for (i <- 0 until rnd.nextInt(64)) yield { \n ('0' + rnd.nextInt(64)).asInstanceOf[Char] \n}) mkString(\"\")\n"
},
{
"answer_id": 12792917,
"author": "rina",
"author_id": 1730605,
"author_profile": "https://Stackoverflow.com/users/1730605",
"pm_score": 4,
"selected": false,
"text": "public static String generateSessionKey(int length){\n String alphabet =\n new String(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"); // 9\n\n int n = alphabet.length(); // 10\n\n String result = new String();\n Random r = new Random(); // 11\n\n for (int i=0; i<length; i++) // 12\n result = result + alphabet.charAt(r.nextInt(n)); //13\n\n return result;\n}\n"
},
{
"answer_id": 12891357,
"author": "hridayesh",
"author_id": 1169187,
"author_profile": "https://Stackoverflow.com/users/1169187",
"pm_score": 2,
"selected": false,
"text": "import org.apache.commons.lang.RandomStringUtils;\nRandomStringUtils.randomAlphanumeric(64);\n"
},
{
"answer_id": 13072330,
"author": "Michael Allen",
"author_id": 308474,
"author_profile": "https://Stackoverflow.com/users/308474",
"pm_score": 5,
"selected": false,
"text": "import java.util.UUID\n\nUUID.randomUUID().toString();\n"
},
{
"answer_id": 13171599,
"author": "Prasobh.Kollattu",
"author_id": 1037363,
"author_profile": "https://Stackoverflow.com/users/1037363",
"pm_score": 2,
"selected": false,
"text": "private static final String NUMBERS = \"0123456789\";\nprivate static final String UPPER_ALPHABETS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nprivate static final String LOWER_ALPHABETS = \"abcdefghijklmnopqrstuvwxyz\";\nprivate static final String SPECIALCHARACTERS = \"@#$%&*\";\nprivate static final int MINLENGTHOFPASSWORD = 8;\n\npublic static String getRandomPassword() {\n StringBuilder password = new StringBuilder();\n int j = 0;\n for (int i = 0; i < MINLENGTHOFPASSWORD; i++) {\n password.append(getRandomPasswordCharacters(j));\n j++;\n if (j == 3) {\n j = 0;\n }\n }\n return password.toString();\n}\n\nprivate static String getRandomPasswordCharacters(int pos) {\n Random randomNum = new Random();\n StringBuilder randomChar = new StringBuilder();\n switch (pos) {\n case 0:\n randomChar.append(NUMBERS.charAt(randomNum.nextInt(NUMBERS.length() - 1)));\n break;\n case 1:\n randomChar.append(UPPER_ALPHABETS.charAt(randomNum.nextInt(UPPER_ALPHABETS.length() - 1)));\n break;\n case 2:\n randomChar.append(SPECIALCHARACTERS.charAt(randomNum.nextInt(SPECIALCHARACTERS.length() - 1)));\n break;\n case 3:\n randomChar.append(LOWER_ALPHABETS.charAt(randomNum.nextInt(LOWER_ALPHABETS.length() - 1)));\n break;\n }\n return randomChar.toString();\n}\n"
},
{
"answer_id": 13678355,
"author": "Vin",
"author_id": 1621446,
"author_profile": "https://Stackoverflow.com/users/1621446",
"pm_score": 2,
"selected": false,
"text": "public static String getRandomString(int length)\n{\n String randomStr = UUID.randomUUID().toString();\n while(randomStr.length() < length) {\n randomStr += UUID.randomUUID().toString();\n }\n return randomStr.substring(0, length);\n}\n"
},
{
"answer_id": 13686133,
"author": "Jamie",
"author_id": 1385083,
"author_profile": "https://Stackoverflow.com/users/1385083",
"pm_score": 1,
"selected": false,
"text": "new StringBuilder(int capacity);\n public static String randomString(int length)\n{\n SecureRandom random = new SecureRandom();\n char[] chars = new char[length];\n for(int i=0; i<chars.length; i++)\n {\n int v = random.nextInt(10 + 26 + 26);\n char c;\n if (v < 10)\n {\n c = (char)('0' + v);\n }\n else if (v < 36)\n {\n c = (char)('a' - 10 + v);\n }\n else\n {\n c = (char)('A' - 36 + v);\n }\n chars[i] = c;\n }\n return new String(chars);\n}\n"
},
{
"answer_id": 14021567,
"author": "duggu",
"author_id": 1722818,
"author_profile": "https://Stackoverflow.com/users/1722818",
"pm_score": 2,
"selected": false,
"text": "public static String randomSeriesForThreeCharacter() {\n Random r = new Random();\n String value = \"\";\n char random_Char ;\n for(int i=0; i<10; i++)\n {\n random_Char = (char) (48 + r.nextInt(74));\n value = value + random_char;\n }\n return value;\n}\n"
},
{
"answer_id": 14241303,
"author": "Burak T",
"author_id": 1962854,
"author_profile": "https://Stackoverflow.com/users/1962854",
"pm_score": 1,
"selected": false,
"text": "char[] chars = new char[62]; // Sum of letters and numbers\n\nint i = 0;\n\nfor(char c = 'a'; c <= 'z'; c++) { // For letters\n chars[i++] = c;\n}\n\nfor(char c = '0'; c <= '9';c++) { // For numbers\n chars[i++] = c;\n}\n\nfor(char c = 'A'; c <= 'Z';c++) { // For capital letters\n chars[i++] = c;\n}\n\nint numberOfCodes = 0;\nString code = \"\";\nwhile (numberOfCodes < 1) { // Enter how much you want to generate at one time\n int numChars = 8; // Enter how many digits you want in your password\n\n for(i = 0; i < numChars; i++) {\n char c = chars[(int)(Math.random() * chars.length)];\n code = code + c;\n }\n System.out.println(\"Code is:\" + code);\n}\n"
},
{
"answer_id": 17926222,
"author": "neuhaus",
"author_id": 2630572,
"author_profile": "https://Stackoverflow.com/users/2630572",
"pm_score": 2,
"selected": false,
"text": "Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));\n"
},
{
"answer_id": 21604071,
"author": "deepakmodak",
"author_id": 1424605,
"author_profile": "https://Stackoverflow.com/users/1424605",
"pm_score": 3,
"selected": false,
"text": "StringBuilder.append public static String getRandomString(int length) {\n final String characters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+\";\n StringBuilder result = new StringBuilder();\n\n while(length > 0) {\n Random rand = new Random();\n result.append(characters.charAt(rand.nextInt(characters.length())));\n length--;\n }\n return result.toString();\n}\n"
},
{
"answer_id": 27120868,
"author": "Howard Lovatt",
"author_id": 1481689,
"author_profile": "https://Stackoverflow.com/users/1481689",
"pm_score": 4,
"selected": false,
"text": "static final Random random = new Random(); // Or SecureRandom\nstatic final int startChar = (int) '!';\nstatic final int endChar = (int) '~';\n\nstatic String randomString(final int maxLength) {\n final int length = random.nextInt(maxLength + 1);\n return random.ints(length, startChar, endChar + 1)\n .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)\n .toString();\n}\n"
},
{
"answer_id": 27350150,
"author": "Steven L",
"author_id": 681122,
"author_profile": "https://Stackoverflow.com/users/681122",
"pm_score": -1,
"selected": false,
"text": "public static String generatePassword(int passwordLength) {\n int asciiFirst = 33;\n int asciiLast = 126;\n Integer[] exceptions = { 34, 39, 96 };\n\n List<Integer> exceptionsList = Arrays.asList(exceptions);\n SecureRandom random = new SecureRandom();\n StringBuilder builder = new StringBuilder();\n for (int i=0; i<passwordLength; i++) {\n int charIndex;\n\n do {\n charIndex = random.nextInt(asciiLast - asciiFirst + 1) + asciiFirst;\n }\n while (exceptionsList.contains(charIndex));\n\n builder.append((char) charIndex);\n }\n return builder.toString();\n}\n"
},
{
"answer_id": 31214709,
"author": "Kristian Kraljic",
"author_id": 1338417,
"author_profile": "https://Stackoverflow.com/users/1338417",
"pm_score": 4,
"selected": false,
"text": "/*\n * The random generator used by this class to create random keys.\n * In a holder class to defer initialization until needed.\n */\nprivate static class RandomHolder {\n static final Random random = new SecureRandom();\n public static String randomKey(int length) {\n return String.format(\"%\"+length+\"s\", new BigInteger(length*5/*base 32,2^5*/, random)\n .toString(32)).replace('\\u0020', '0');\n }\n}\n length*5 BigInteger 0 to (2^numBits - 1) 2^5-1=31 2^6-1=63 2^6 2^5 2^(length*numBits)-1"
},
{
"answer_id": 38776878,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "package password.generater;\n\nimport java.util.Random;\n\n/**\n *\n * @author dell\n */\npublic class PasswordGenerater {\n\n /**\n * @param args the command line arguments\n */\n public static void main(String[] args) {\n int length= 11;\n System.out.println(generatePswd(length));\n\n // TODO code application logic here\n }\n static char[] generatePswd(int len){\n System.out.println(\"Your Password \");\n String charsCaps=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; \n String Chars=\"abcdefghijklmnopqrstuvwxyz\";\n String nums=\"0123456789\";\n String symbols=\"!@#$%^&*()_+-=.,/';:?><~*/-+\";\n String passSymbols=charsCaps + Chars + nums +symbols;\n Random rnd=new Random();\n char[] password=new char[len];\n\n for(int i=0; i<len;i++){\n password[i]=passSymbols.charAt(rnd.nextInt(passSymbols.length()));\n }\n return password;\n\n }\n}\n"
},
{
"answer_id": 40852832,
"author": "user_3380739",
"author_id": 3380739,
"author_profile": "https://Stackoverflow.com/users/3380739",
"pm_score": 3,
"selected": false,
"text": "String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())\n N.uuid() // E.g.: \"e812e749-cf4c-4959-8ee1-57829a69a80f\". length is 36.\nN.guid() // E.g.: \"0678ce04e18945559ba82ddeccaabfcd\". length is 32 without '-'\n"
},
{
"answer_id": 44227131,
"author": "Patrick",
"author_id": 774398,
"author_profile": "https://Stackoverflow.com/users/774398",
"pm_score": 6,
"selected": false,
"text": "SecureRandom /dev/random SecureRandom rnd = new SecureRandom();\nbyte[] token = new byte[byteLength];\nrnd.nextBytes(token);\n SecureRandom UUID String Base64 XfJhfv3C0P6ag7y9VQxSbw== Base32 A-Z 2-7 WUPIL5DQTZGMF4D3NX5L7LNFOY Base16 Base32 0-9 A F 4fa3dd0f57cb3bf331441ed285b27735 SecureRandom hex base32 public static String generateRandomHexToken(int byteLength) {\n SecureRandom secureRandom = new SecureRandom();\n byte[] token = new byte[byteLength];\n secureRandom.nextBytes(token);\n return new BigInteger(1, token).toString(16); // Hexadecimal encoding\n}\n\n//generateRandomHexToken(16) -> 2189df7475e96aa3982dbeab266497cd\n public static String generateRandomBase64Token(int byteLength) {\n SecureRandom secureRandom = new SecureRandom();\n byte[] token = new byte[byteLength];\n secureRandom.nextBytes(token);\n return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding\n}\n\n//generateRandomBase64Token(16) -> EEcCCAYuUcQk7IuzdaPzrg\n long IdMask<Long> idMask = IdMasks.forLongIds(Config.builder(key).build());\nString maskedId = idMask.mask(id);\n// Example: NPSBolhMyabUBdTyanrbqT8\nlong originalId = idMask.unmask(maskedId);\n"
},
{
"answer_id": 44866347,
"author": "kyxap",
"author_id": 975638,
"author_profile": "https://Stackoverflow.com/users/975638",
"pm_score": -1,
"selected": false,
"text": "String generateRandomStr(int min, int max, int size) {\n String result = \"\";\n for (int i = 0; i < size; i++) {\n result += String.valueOf((char)(new Random().nextInt((max - min) + 1) + min));\n }\n return result;\n}\n generateRandomStr(65, 90, 100)); TVLPFQJCYFXQDCQSLKUKKILKKHAUFYEXLUQFHDWNMRBIRRRWNXNNZQTINZPCTKLHGHVYWRKEOYNSOFPZBGEECFMCOKWHLHCEWLDZ\n"
},
{
"answer_id": 48909646,
"author": "Patrik Bego",
"author_id": 2306839,
"author_profile": "https://Stackoverflow.com/users/2306839",
"pm_score": 3,
"selected": false,
"text": "public String randomString(int length, String characterSet) {\n return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n for (int q = 0; q < 5; q++) {\n System.out.println(randomString(10, \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")); // The character set can basically be anything\n }\n}\n public String randomString(int length, String characterSet) {\n StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed\n for (int i = 0; i < length; i++) {\n int randomInt = new SecureRandom().nextInt(characterSet.length());\n sb.append(characterSet.substring(randomInt, randomInt + 1));\n }\n return sb.toString();\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n for (int q = 0; q < 5; q++) {\n System.out.println(randomString(10, \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")); // The character set can basically be anything\n }\n}\n UUID.randomUUID().toString().replace(\"-\", \"\")\n"
},
{
"answer_id": 49056893,
"author": "aaronvargas",
"author_id": 114549,
"author_profile": "https://Stackoverflow.com/users/114549",
"pm_score": 0,
"selected": false,
"text": "public static String randString(int length) {\n return UUID.randomUUID().toString().replace(\"-\", \"\").substring(0, Math.min(length, 32)) + (length > 32 ? randString(length - 32) : \"\");\n}\n"
},
{
"answer_id": 51896107,
"author": "Prasad Parab",
"author_id": 6359611,
"author_profile": "https://Stackoverflow.com/users/6359611",
"pm_score": 2,
"selected": false,
"text": "public static String getRandomString(int length) {\n char[] chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST\".toCharArray();\n\n StringBuilder sb = new StringBuilder();\n Random random = new Random();\n for (int i = 0; i < length; i++) {\n char c = chars[random.nextInt(chars.length)];\n sb.append(c);\n }\n String randomStr = sb.toString();\n\n return randomStr;\n}\n"
},
{
"answer_id": 53487039,
"author": "FileInputStream",
"author_id": 9139738,
"author_profile": "https://Stackoverflow.com/users/9139738",
"pm_score": 2,
"selected": false,
"text": " public String generateRandomString(int length) {\n String randomString = \"\";\n\n final char[] chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890\".toCharArray();\n final Random random = new Random();\n for (int i = 0; i < length; i++) {\n randomString = randomString + chars[random.nextInt(chars.length)];\n }\n\n return randomString;\n}\n"
},
{
"answer_id": 54907024,
"author": "mike",
"author_id": 1809463,
"author_profile": "https://Stackoverflow.com/users/1809463",
"pm_score": 0,
"selected": false,
"text": " public String generateString(String alphabet, int length) {\n return generateString(alphabet, length, new SecureRandom()::nextInt);\n }\n\n // nextInt = bound -> n in [0, bound)\n public String generateString(String source, int length, IntFunction<Integer> nextInt) {\n StringBuilder sb = new StringBuilder();\n IntStream.generate(source::length)\n .boxed()\n .limit(length)\n .map(nextInt::apply)\n .map(source::charAt)\n .forEach(sb::append);\n\n return sb.toString();\n }\n String alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nint length = 12;\nString generated = generateString(alphabet, length);\nSystem.out.println(generated);\n nextInt bound 0 bound - 1"
},
{
"answer_id": 55376955,
"author": "SoBeRich",
"author_id": 8305572,
"author_profile": "https://Stackoverflow.com/users/8305572",
"pm_score": -1,
"selected": false,
"text": "/**\n * Utility class for generating random Strings.\n */\npublic interface RandomUtil {\n\n int DEF_COUNT = 20;\n Random RANDOM = new SecureRandom();\n\n /**\n * Generate a password.\n *\n * @return the generated password\n */\n static String generatePassword() {\n return generate(true, true);\n }\n\n /**\n * Generate an activation key.\n *\n * @return the generated activation key\n */\n static String generateActivationKey() {\n return generate(false, true);\n }\n\n /**\n * Generate a reset key.\n *\n * @return the generated reset key\n */\n static String generateResetKey() {\n return generate(false, true);\n }\n\n static String generate(boolean letters, boolean numbers) {\n int\n start = ' ',\n end = 'z' + 1,\n count = DEF_COUNT,\n gap = end - start;\n StringBuilder builder = new StringBuilder(count);\n\n while (count-- != 0) {\n int codePoint = RANDOM.nextInt(gap) + start;\n\n switch (getType(codePoint)) {\n case UNASSIGNED:\n case PRIVATE_USE:\n case SURROGATE:\n count++;\n continue;\n }\n\n int numberOfChars = charCount(codePoint);\n\n if (count == 0 && numberOfChars > 1) {\n count++;\n continue;\n }\n\n if (letters && isLetter(codePoint)\n || numbers && isDigit(codePoint)\n || !letters && !numbers) {\n\n builder.appendCodePoint(codePoint);\n if (numberOfChars == 2)\n count--;\n }\n else\n count++;\n }\n return builder.toString();\n }\n}\n"
},
{
"answer_id": 59223550,
"author": "Riley Jones",
"author_id": 12491840,
"author_profile": "https://Stackoverflow.com/users/12491840",
"pm_score": 0,
"selected": false,
"text": "public static String RandomAlphanum(int length)\n{\n String charstring = \"abcdefghijklmnopqrstuvwxyz0123456789\";\n String randalphanum = \"\";\n double randroll;\n String randchar;\n for (double i = 0; i < length; i++)\n {\n randroll = Math.random();\n randchar = \"\";\n for (int j = 1; j <= 35; j++)\n {\n if (randroll <= (1.0 / 36.0 * j))\n {\n randchar = Character.toString(charstring.charAt(j - 1));\n break;\n }\n }\n randalphanum += randchar;\n }\n return randalphanum;\n}\n util.Date"
},
{
"answer_id": 61152198,
"author": "Chuong Tran",
"author_id": 8568835,
"author_profile": "https://Stackoverflow.com/users/8568835",
"pm_score": 3,
"selected": false,
"text": "import org.apache.commons.lang3.RandomStringUtils;\n\nString keyLength = 20;\nRandomStringUtils.randomAlphanumeric(keylength);\n"
},
{
"answer_id": 67010786,
"author": "Mayank",
"author_id": 9297984,
"author_profile": "https://Stackoverflow.com/users/9297984",
"pm_score": -1,
"selected": false,
"text": "...\nimport java.security.SecureRandom;\n...\n\n//Generate a random String of length between 10 to 20.\n//Length is also randomly generated here.\nSecureRandom random = new SecureRandom();\n\nString sampleSet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_\";\n\nint stringLength = random.ints(1, 10, 21).mapToObj(x -> x).reduce((a, b) -> a).get();\n\nString randomString = random.ints(stringLength, 0, sampleSet.length() - 1)\n .mapToObj(x -> sampleSet.charAt(x))\n .collect(Collector\n .of(StringBuilder::new, StringBuilder::append,\n StringBuilder::append, StringBuilder::toString));\n public String generateRandomString() {\n \n String sampleSet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_\";\n String sampleSetNumeric = \"0123456789\";\n \n String randomString = getRandomString(sampleSet, 10, 21);\n String randomStringNumeric = getRandomString(sampleSetNumeric, 10, 21);\n \n randomString = randomString + randomStringNumeric;\n \n //Convert String to List<Character>\n List<Character> list = randomString.chars()\n .mapToObj(x -> (char)x)\n .collect(Collectors.toList());\n \n Collections.shuffle(list);\n \n //This is needed to force a non-numeric character as the first String\n //Skip this for() if you don't need this logic\n\n for(;;) {\n if(Character.isDigit(list.get(0))) Collections.shuffle(list);\n else break;\n }\n \n //Convert List<Character> to String\n randomString = list.stream()\n .map(String::valueOf)\n .collect(Collectors.joining());\n \n return randomString;\n \n}\n\n//Generate a random number between the lower bound (inclusive) and upper bound (exclusive)\nprivate int getRandomLength(int min, int max) {\n SecureRandom random = new SecureRandom();\n return random.ints(1, min, max).mapToObj(x -> x).reduce((a, b) -> a).get();\n}\n\n//Generate a random String from the given sample string, having a random length between the lower bound (inclusive) and upper bound (exclusive)\nprivate String getRandomString(String sampleSet, int min, int max) {\n SecureRandom random = new SecureRandom();\n return random.ints(getRandomLength(min, max), 0, sampleSet.length() - 1)\n .mapToObj(x -> sampleSet.charAt(x))\n .collect(Collector\n .of(StringBuilder::new, StringBuilder::append,\n StringBuilder::append, StringBuilder::toString));\n}\n"
},
{
"answer_id": 67020131,
"author": "Muxammed Gafarov",
"author_id": 13589507,
"author_profile": "https://Stackoverflow.com/users/13589507",
"pm_score": 2,
"selected": false,
"text": "public class Utils {\n private final Random RANDOM = new SecureRandom();\n private final String ALPHABET = \"0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm\";\n\n private String generateRandomString(int length) {\n StringBuffer buffer = new StringBuffer(length);\n for (int i = 0; i < length; i++) {\n buffer.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));\n }\n return new String(buffer);\n } \n}\n"
},
{
"answer_id": 74024384,
"author": "cwtuan",
"author_id": 2822680,
"author_profile": "https://Stackoverflow.com/users/2822680",
"pm_score": 0,
"selected": false,
"text": "AllCharacters public class MyProgram {\n static String getRandomString(int size) {\n String AllCharacters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n StringBuilder sb = new StringBuilder(size);\n int length = AllCharacters.length();\n for (int i = 0; i < size; i++) {\n sb.append(AllCharacters.charAt((int)(length * Math.random())));\n }\n return sb.toString();\n }\n\n public static void main(String[] args) {\n System.out.println(MyProgram.getRandomString(30));\n }\n}\n"
},
{
"answer_id": 74402390,
"author": "F_SO_K",
"author_id": 4985580,
"author_profile": "https://Stackoverflow.com/users/4985580",
"pm_score": 0,
"selected": false,
"text": "int length = 12;\nString randomString = new Random().ints(48, 122).filter(i -> (i < 58 || i > 64) && (i < 91 || i > 96)).limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();\nSystem.out.print(randomString);\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803/"
] |
41,134 |
<p>Here is the deal. </p>
<p>$ gem --version</p>
<blockquote>
<p>1.1.0</p>
</blockquote>
<p>$ sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config</p>
<blockquote>
<p>Bulk updating Gem source index for:
<a href="http://gems.rubyforge.org/" rel="nofollow noreferrer">http://gems.rubyforge.org/</a> ERROR:
could not find mysql locally or in a
repository</p>
</blockquote>
<p>$ sudo gem update</p>
<blockquote>
<p>Updating installed gems Bulk updating
Gem source index for:
<a href="http://gems.rubyforge.org/" rel="nofollow noreferrer">http://gems.rubyforge.org/</a> </p>
<p>Updating
RedCloth ERROR: While executing gem
... (Gem::GemNotFoundException)
could not find RedCloth locally or in a repository</p>
</blockquote>
<p>I've tried <a href="http://www.gregbenedict.com/2008/02/21/mysql-ruby-gem-install-issues-solved/" rel="nofollow noreferrer">this</a>, <a href="http://dev.mysql.com/downloads/ruby.html" rel="nofollow noreferrer">this</a>, <a href="http://installingcats.com/2007/12/13/mysql-ruby-gem-install-problem-on-mac-os-x-leopard/" rel="nofollow noreferrer">this</a>, <a href="http://www.docuverse.com/blog/donpark/2007/06/14/os-x-mysql-ruby-gem-install-problem" rel="nofollow noreferrer">this</a>, and a ton of others. </p>
<p>None of them have worked for me. Is anyone else having this problem? If so what did you do to fix it that is not mentioned above? </p>
|
[
{
"answer_id": 41160,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "gem update --system\n"
},
{
"answer_id": 223708,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "sudo env ARCHFLAGS=\"-arch i386\" gem install mysql -- \\\n --with-mysql-dir=/usr/local/mysql --with-mysql-lib=/usr/local/mysql/lib \\\n --with-mysql-include=/usr/local/mysql/include\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] |
41,155 |
<p>In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. </p>
<p>I've got my interface set up with the ServiceContract and OperationContract:</p>
<pre><code> [OperationContract]
void FileUpload(UploadedFile file);
</code></pre>
<p>Along with the actual method:</p>
<pre><code> public void FileUpload(UploadedFile file) {};
</code></pre>
<p>To access the Service I enter <a href="http://localhost/project/myService.svc/FileUpload" rel="noreferrer">http://localhost/project/myService.svc/FileUpload</a>
but I get the "Method not Allowed" error</p>
<p>Am I missing something?</p>
|
[
{
"answer_id": 41205,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 2,
"selected": false,
"text": "byte int string [DataContract]"
},
{
"answer_id": 41301,
"author": "Ubiguchi",
"author_id": 2562,
"author_profile": "https://Stackoverflow.com/users/2562",
"pm_score": 1,
"selected": false,
"text": "http://localhost/project/myService.svc\n"
},
{
"answer_id": 545754,
"author": "Ries",
"author_id": 64565,
"author_profile": "https://Stackoverflow.com/users/64565",
"pm_score": 7,
"selected": true,
"text": "[ServiceContract]\npublic interface IUploadService\n{\n [WebGet()]\n [OperationContract]\n string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.\n\n [OperationContract]\n void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.\n }\n"
},
{
"answer_id": 2018327,
"author": "darthjit",
"author_id": 121397,
"author_profile": "https://Stackoverflow.com/users/121397",
"pm_score": 6,
"selected": false,
"text": "[WebInvoke(Method=\"GET\")]"
},
{
"answer_id": 12079267,
"author": "sandeep",
"author_id": 1617832,
"author_profile": "https://Stackoverflow.com/users/1617832",
"pm_score": 0,
"selected": false,
"text": "<endpoint address=\"customBinding\" binding=\"customBinding\" bindingConfiguration=\"basicConfig\" contract=\"WcfRest.IService1\"/> \n\n<bindings> \n <customBinding> \n <binding name=\"basicConfig\"> \n <binaryMessageEncoding/> \n <httpTransport transferMode=\"Streamed\" maxReceivedMessageSize=\"67108864\"/> \n </binding> \n </customBinding> \n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/831/"
] |
41,159 |
<p>Given the following:</p>
<pre><code>List<List<Option>> optionLists;
</code></pre>
<p>what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.</p>
<p>So we should end up with <code>List<Option></code> where each item appears only once.</p>
|
[
{
"answer_id": 41175,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "var x = from list in optionLists\n from option in list\n where optionLists.All(l => l.Any(o => o.Value == option.Value))\n orderby option.Value\n select option;\n"
},
{
"answer_id": 41327,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "static SortedDictionary<T,bool>.KeyCollection FindCommon<T> (List<List<T>> items)\n{\n SortedDictionary<T, bool>\n current_common = new SortedDictionary<T, bool> (),\n common = new SortedDictionary<T, bool> ();\n\n foreach (List<T> list in items)\n {\n if (current_common.Count == 0)\n {\n foreach (T item in list)\n {\n common [item] = true;\n }\n }\n else\n {\n foreach (T item in list)\n {\n if (current_common.ContainsKey(item))\n common[item] = true;\n else\n common[item] = false;\n }\n }\n\n if (common.Count == 0)\n {\n current_common.Clear ();\n break;\n }\n\n SortedDictionary<T, bool>\n swap = current_common;\n\n current_common = common;\n common = swap;\n common.Clear ();\n }\n\n return current_common.Keys;\n} \n static void Main (string [] args)\n{\n Random\n random = new Random();\n\n List<List<int>>\n items = new List<List<int>>();\n\n for (int i = 0 ; i < 10 ; ++i)\n {\n List<int>\n list = new List<int> ();\n\n items.Add (list);\n\n for (int j = 0 ; j < 100 ; ++j)\n {\n list.Add (random.Next (70));\n }\n }\n\n SortedDictionary<int, bool>.KeyCollection\n common = FindCommon (items);\n\n foreach (List<int> list in items)\n {\n list.Sort ();\n }\n\n for (int i = 0 ; i < 100 ; ++i)\n {\n for (int j = 0 ; j < 10 ; ++j)\n {\n System.Diagnostics.Trace.Write (String.Format (\"{0,-4:D} \", items [j] [i]));\n }\n\n System.Diagnostics.Trace.WriteLine (\"\");\n }\n\n foreach (int item in common)\n {\n System.Diagnostics.Trace.WriteLine (String.Format (\"{0,-4:D} \", item));\n }\n}\n"
},
{
"answer_id": 42941,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 2,
"selected": false,
"text": "var sharedOptions =\n from option in optionLists.First( ).Distinct( )\n where optionLists.Skip( 1 ).All( l => l.Contains( option ) )\n select option;\n Distinct First Contains"
},
{
"answer_id": 18097168,
"author": "logicnp",
"author_id": 51919,
"author_profile": "https://Stackoverflow.com/users/51919",
"pm_score": 0,
"selected": false,
"text": " static List<T> FindCommon<T>(IEnumerable<List<T>> lists)\n {\n Dictionary<T, int> map = new Dictionary<T, int>();\n int listCount = 0; // number of lists\n\n foreach (IEnumerable<T> list in lists)\n {\n listCount++;\n foreach (T item in list)\n {\n // Item encountered, increment count\n int currCount;\n if (!map.TryGetValue(item, out currCount))\n currCount = 0;\n\n currCount++;\n map[item] = currCount;\n }\n }\n\n List<T> result= new List<T>();\n foreach (KeyValuePair<T,int> kvp in map)\n {\n // Items whose occurrence count is equal to the number of lists are common to all the lists\n if (kvp.Value == listCount)\n result.Add(kvp.Key);\n }\n\n return result;\n }\n"
},
{
"answer_id": 45240713,
"author": "user2102327",
"author_id": 2102327,
"author_profile": "https://Stackoverflow.com/users/2102327",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n /// The method FindCommonItems, returns a list of all the COMMON ITEMS in the lists contained in the listOfLists.\n /// The method expects lists containing NO DUPLICATE ITEMS.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"allSets\"></param>\n /// <returns></returns>\n public static List<T> FindCommonItems<T>(IEnumerable<List<T>> allSets)\n {\n Dictionary<T, int> map = new Dictionary<T, int>();\n int listCount = 0; // Number of lists.\n foreach (IEnumerable<T> currentSet in allSets)\n {\n int itemsCount = currentSet.ToList().Count;\n HashSet<T> uniqueItems = new HashSet<T>();\n bool duplicateItemEncountered = false;\n listCount++;\n foreach (T item in currentSet)\n {\n if (!uniqueItems.Add(item))\n {\n duplicateItemEncountered = true;\n } \n if (map.ContainsKey(item))\n {\n map[item]++;\n } \n else\n {\n map.Add(item, 1);\n }\n }\n if (duplicateItemEncountered)\n {\n uniqueItems.Clear();\n List<T> duplicateItems = new List<T>();\n StringBuilder currentSetItems = new StringBuilder();\n List<T> currentSetAsList = new List<T>(currentSet);\n for (int i = 0; i < itemsCount; i++)\n {\n T currentItem = currentSetAsList[i];\n if (!uniqueItems.Add(currentItem))\n {\n duplicateItems.Add(currentItem);\n }\n currentSetItems.Append(currentItem);\n if (i < itemsCount - 1)\n {\n currentSetItems.Append(\", \");\n }\n }\n StringBuilder duplicateItemsNamesEnumeration = new StringBuilder();\n int j = 0;\n foreach (T item in duplicateItems)\n {\n duplicateItemsNamesEnumeration.Append(item.ToString());\n if (j < uniqueItems.Count - 1)\n {\n duplicateItemsNamesEnumeration.Append(\", \");\n }\n }\n throw new Exception(\"The list \" + currentSetItems.ToString() + \" contains the following duplicate items: \" + duplicateItemsNamesEnumeration.ToString());\n }\n }\n List<T> result= new List<T>();\n foreach (KeyValuePair<T, int> itemAndItsCount in map)\n {\n if (itemAndItsCount.Value == listCount) // Items whose occurrence count is equal to the number of lists are common to all the lists.\n {\n result.Add(itemAndItsCount.Key);\n }\n }\n\n return result;\n }\n"
},
{
"answer_id": 45251772,
"author": "user2102327",
"author_id": 2102327,
"author_profile": "https://Stackoverflow.com/users/2102327",
"pm_score": 0,
"selected": false,
"text": "/// <summary>.\n /// The method FindAllCommonItemsInAllTheLists, returns a HashSet that contains all the common items in the lists contained in the listOfLists,\n /// regardless of the order of the items in the various lists.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"listOfLists\"></param>\n /// <returns></returns>\n public static HashSet<T> FindAllCommonItemsInAllTheLists<T>(List<List<T>> listOfLists)\n {\n if (listOfLists == null || listOfLists.Count == 0)\n {\n return null;\n }\n HashSet<T> currentCommon = new HashSet<T>();\n HashSet<T> common = new HashSet<T>();\n\n foreach (List<T> currentList in listOfLists)\n {\n if (currentCommon.Count == 0)\n {\n foreach (T item in currentList)\n {\n common.Add(item);\n }\n }\n else\n {\n foreach (T item in currentList)\n {\n if (currentCommon.Contains(item))\n {\n common.Add(item);\n }\n }\n }\n if (common.Count == 0)\n {\n currentCommon.Clear();\n break;\n }\n currentCommon.Clear(); // Empty currentCommon for a new iteration.\n foreach (T item in common) /* Copy all the items contained in common to currentCommon. \n * currentCommon = common; \n * does not work because thus currentCommon and common would point at the same object and \n * the next statement: \n * common.Clear();\n * will also clear currentCommon.\n */\n {\n if (!currentCommon.Contains(item))\n {\n currentCommon.Add(item);\n }\n }\n common.Clear();\n }\n\n return currentCommon;\n }\n"
},
{
"answer_id": 46712990,
"author": "birdus",
"author_id": 220899,
"author_profile": "https://Stackoverflow.com/users/220899",
"pm_score": 0,
"selected": false,
"text": "SearchResult Option EmployeeId EmployeeId private List<SearchResult> GetFinalSearchResults(IEnumerable<IEnumerable<SearchResult>> lists)\n{\n Dictionary<int, SearchResult> oldList = new Dictionary<int, SearchResult>();\n Dictionary<int, SearchResult> newList = new Dictionary<int, SearchResult>();\n\n oldList = lists.First().ToDictionary(x => x.EmployeeId, x => x);\n\n foreach (List<SearchResult> list in lists.Skip(1))\n {\n foreach (SearchResult emp in list)\n {\n if (oldList.Keys.Contains(emp.EmployeeId))\n {\n newList.Add(emp.EmployeeId, emp);\n }\n }\n\n oldList = new Dictionary<int, SearchResult>(newList);\n newList.Clear();\n }\n\n return oldList.Values.ToList();\n}\n"
},
{
"answer_id": 57379638,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": "var subset = optionLists.Aggregate((x, y) => x.Intersect(y))\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3615/"
] |
41,179 |
<p>I have a number of users with multi-megabyte files that need to be processed before they can be uploaded. I am trying to find a way to do this without having to install any executable software on their machines. </p>
<p>If every machine shipped with, say, Python it would be easy. I could have a Python script do everything. The only scripting language I can think of that's on every machine is JavaScript. However I know there are security restrictions that prevent reading and writing local files from web browsers. </p>
<p>Is there any way to use this extremely pervasive scripting language for general purpose computing tasks?</p>
<hr>
<p>EDIT: To clarify the requirements, this needs to be a cross platform, cross browser solution. I believe that HTA is an Internet Explorer only technology (or that the Firefox equivalent is broken).</p>
|
[
{
"answer_id": 51186981,
"author": "Isaac",
"author_id": 9816472,
"author_profile": "https://Stackoverflow.com/users/9816472",
"pm_score": 0,
"selected": false,
"text": "fs nodeJS"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4262/"
] |
41,198 |
<p>How can I get an image to stretch the height of a <code>DIV</code> class?</p>
<p>Currently it looks like this:</p>
<p><img src="https://i.stack.imgur.com/DcrXC.png" width="650" /></p>
<p>However, I would like the <code>DIV</code> to be stretched so the <code>image</code> fits properly, but I do not want to resize the `image.</p>
<p>Here is the CSS for the <code>DIV</code> (the grey box):</p>
<pre class="lang-css prettyprint-override"><code>.product1 {
width: 100%;
padding: 5px;
margin: 0px 0px 15px -5px;
background: #ADA19A;
color: #000000;
min-height: 100px;
}
</code></pre>
<p>The CSS being applied on the image:</p>
<pre class="lang-css prettyprint-override"><code>.product{
display: inline;
float: left;
}
</code></pre>
<p>So, how can I fix this?</p>
|
[
{
"answer_id": 41201,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "display:inline \nfloat:left \n"
},
{
"answer_id": 41203,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<div style=\"clear:left\"/>"
},
{
"answer_id": 41232,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 2,
"selected": false,
"text": ".product + * { clear: left; }\n"
},
{
"answer_id": 41235,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 6,
"selected": true,
"text": "overflow:auto; .product1"
},
{
"answer_id": 42090,
"author": "Jeremy",
"author_id": 2076253,
"author_profile": "https://Stackoverflow.com/users/2076253",
"pm_score": 2,
"selected": false,
"text": "<div> .product1 {\n width: 100%;\n padding: 5px;\n margin: 0px 0px 15px -5px;\n background: #ADA19A;\n color: #000000;\n min-height: 100px;\n overflow: hidden;\n}\n"
},
{
"answer_id": 8324360,
"author": "Palanikumar",
"author_id": 1019435,
"author_profile": "https://Stackoverflow.com/users/1019435",
"pm_score": 2,
"selected": false,
"text": ".Strech\n{\n background:url(image.jpg);\n background-size:100% 100%;\n background-repeat:no-repeat;\n\n width:500px;\n height:500px;\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
41,204 |
<p>Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts_as_nested_set without using recursion?</p>
<p>Here's the recursive solution for reference:</p>
<pre><code>class Node < ActiveRecord::Base
has_many :products
def json_hash
if children.size > 0
children.collect { |node| { node.name => node.json_hash }.to_json
else
{ node.name => node.products.find(:all).collect(&:name) }.to_json
end
end
end
</code></pre>
|
[
{
"answer_id": 41275,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "{ node.name => node.products.find(:all).collect(&:name) }.to_json\n { node.name => node.products.find(:all).collect!(&:name) }.to_json\n class Node < ActiveRecord::Base\n has_many :products\n def json_hash\n if children.size > 0\n children.collect { |node| { node.name => node.json_hash }.to_json\n else\n { node.name => node.products.find(:all).collect!(&:name) }.to_json\n end\n end\nend\n class Node < ActiveRecord::Base\n has_many :products\n def json_hash\n to_hash.to_json\n end\n\n def to_hash\n if children.size > 0\n children.collect { |node| { node.name => node.to_hash }\n else\n { node.name => node.products.find(:all).collect!(&:name) }\n end\n end\nend\n"
},
{
"answer_id": 3587874,
"author": "standup75",
"author_id": 433333,
"author_profile": "https://Stackoverflow.com/users/433333",
"pm_score": 1,
"selected": false,
"text": "node.to_json(:include=>{:products=>{:include=>:product_parts}})\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] |
41,207 |
<p>For debugging and testing I'm searching for a JavaScript shell with auto completion and if possible object introspection (like ipython). The online <a href="http://www.squarefree.com/shell/" rel="nofollow noreferrer">JavaScript Shell</a> is really nice, but I'm looking for something local, without the need for an browser.</p>
<p>So far I have tested the standalone JavaScript interpreter rhino, spidermonkey and google V8. But neither of them has completion. At least Rhino with jline and spidermonkey have some kind of command history via key up/down, but nothing more.</p>
<p>Any suggestions?</p>
<p>This question was asked again <a href="https://stackoverflow.com/questions/260787/javascript-shell">here</a>. It might contain an answer that you are looking for.</p>
|
[
{
"answer_id": 1812416,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 3,
"selected": false,
"text": "// shell.js\n// ------------------------------------------------------------------\n//\n// implements an interactive javascript shell.\n//\n// from\n// http://kobyk.wordpress.com/2007/09/14/a-jscript-interactive-interpreter-shell-for-the-windows-script-host/\n//\n// Sat Nov 28 00:09:55 2009\n//\n\nvar GSHELL = (function () {\n\n var numberToHexString = function (n) {\n if (n >= 0) {\n return n.toString(16);\n } else {\n n += 0x100000000;\n return n.toString(16);\n }\n };\n var line, scriptText, previousLine, result;\n\n return function() {\n while(true) {\n WScript.StdOut.Write(\"js> \");\n if (WScript.StdIn.AtEndOfStream) {\n WScript.Echo(\"Bye.\");\n break;\n }\n line = WScript.StdIn.ReadLine();\n scriptText = line + \"\\n\";\n if (line === \"\") {\n WScript.Echo(\n \"Enter two consecutive blank lines to terminate multi-line input.\");\n do {\n if (WScript.StdIn.AtEndOfStream) {\n break;\n }\n previousLine = line;\n line = WScript.StdIn.ReadLine();\n line += \"\\n\";\n scriptText += line;\n } while(previousLine != \"\\n\" || line != \"\\n\");\n }\n try {\n result = eval(scriptText);\n } catch (error) {\n WScript.Echo(\"0x\" + numberToHexString(error.number) + \" \" + error.name + \": \" +\n error.message);\n }\n if (result) {\n try {\n WScript.Echo(result);\n } catch (error) {\n WScript.Echo(\"<<>>\");\n }\n }\n result = null;\n }\n };\n})();\n\nGSHELL();\n <job>\n <reference object=\"Scripting.FileSystemObject\" />\n <script language=\"JavaScript\" src=\"util.js\" />\n <script language=\"JavaScript\" src=\"shell.js\" />\n</job>\n var quit = function(x) { WScript.Quit(x);}\nvar say = function(s) { WScript.Echo(s); };\nvar echo = say;\nvar exit = quit;\nvar sleep = function(n) { WScript.Sleep(n*1000); };\n"
},
{
"answer_id": 4074237,
"author": "intuited",
"author_id": 192812,
"author_profile": "https://Stackoverflow.com/users/192812",
"pm_score": 3,
"selected": false,
"text": "node-repl"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720/"
] |
41,218 |
<p>I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I <strong>could</strong> configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer.</p>
<p>Thanks</p>
|
[
{
"answer_id": 41272,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "/Applications/MAMP/bin/apache2/bin$ ./apachectl stop\n/Applications/MAMP/bin/apache2/bin$ sudo ./apachectl startssl\n"
},
{
"answer_id": 43384,
"author": "Rodney Amato",
"author_id": 4342,
"author_profile": "https://Stackoverflow.com/users/4342",
"pm_score": 4,
"selected": true,
"text": "/Applications/MAMP/startApache.sh\n"
},
{
"answer_id": 1795144,
"author": "Riley",
"author_id": 218358,
"author_profile": "https://Stackoverflow.com/users/218358",
"pm_score": 5,
"selected": false,
"text": "# LoadModule foo_module modules/mod_foo.so LoadModule ssl_module modules/mod_ssl.so <IfDefine SSL> </IfDefine SSL> <IfDefine SSL> </IfDefine SSL> SSLCertificateFile SSLCertificateKeyFile SSLCertificateFile /Applications/MAMP/conf/apache/ssl/server.crt SSLCertificateKeyFile /Applications/MAMP/conf/apache/ssl/server.key cd /Applications/MAMP/conf/apache/ssl openssl genrsa -des3 -out server.key 1024 cp server.key server-pw.key openssl rsa -in server-pw.key -out server.key openssl req -new -key server.key -out server.csr openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt https://localhost/"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4247/"
] |
41,233 |
<p>I'm attracted to the neatness that a single file database provides. What driver/connector library is out there to connect and use SQLite with Java.</p>
<p>I've discovered a wrapper library, <a href="http://www.ch-werner.de/javasqlite/" rel="noreferrer">http://www.ch-werner.de/javasqlite</a>, but are there other more prominent projects available?</p>
|
[
{
"answer_id": 593137,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 8,
"selected": false,
"text": "java -cp .:sqlitejdbc-v056.jar Test package com.rungeek.sqlite;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class Test {\n public static void main(String[] args) throws Exception {\n Class.forName(\"org.sqlite.JDBC\");\n Connection conn = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n Statement stat = conn.createStatement();\n stat.executeUpdate(\"drop table if exists people;\");\n stat.executeUpdate(\"create table people (name, occupation);\");\n PreparedStatement prep = conn.prepareStatement(\n \"insert into people values (?, ?);\");\n\n prep.setString(1, \"Gandhi\");\n prep.setString(2, \"politics\");\n prep.addBatch();\n prep.setString(1, \"Turing\");\n prep.setString(2, \"computers\");\n prep.addBatch();\n prep.setString(1, \"Wittgenstein\");\n prep.setString(2, \"smartypants\");\n prep.addBatch();\n\n conn.setAutoCommit(false);\n prep.executeBatch();\n conn.setAutoCommit(true);\n\n ResultSet rs = stat.executeQuery(\"select * from people;\");\n while (rs.next()) {\n System.out.println(\"name = \" + rs.getString(\"name\"));\n System.out.println(\"job = \" + rs.getString(\"occupation\"));\n }\n rs.close();\n conn.close();\n }\n }\n"
},
{
"answer_id": 8797310,
"author": "snail",
"author_id": 1139901,
"author_profile": "https://Stackoverflow.com/users/1139901",
"pm_score": 2,
"selected": false,
"text": "outofmemory"
},
{
"answer_id": 9046459,
"author": "Eddie",
"author_id": 1175379,
"author_profile": "https://Stackoverflow.com/users/1175379",
"pm_score": 0,
"selected": false,
"text": "java -cp .:sqlitejdbc-v056.jar Test java -cp .:sqlitejdbc-v056.jar; Test"
},
{
"answer_id": 9426806,
"author": "aboutstudy",
"author_id": 1122995,
"author_profile": "https://Stackoverflow.com/users/1122995",
"pm_score": 2,
"selected": false,
"text": "javac -classpath .;sqlitejdbc-v056.jar Text.java\n\njava -classpath .;sqlitejdbc-v056.jar Text\n"
},
{
"answer_id": 13273626,
"author": "Morbo",
"author_id": 1806702,
"author_profile": "https://Stackoverflow.com/users/1806702",
"pm_score": 2,
"selected": false,
"text": "# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc\n...\n# cd sqlitejdbc\n# make\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915/"
] |
41,239 |
<p>I am pretty sure that the settings that I am using are correct, so all possible things can be wrong which I should check out so that I can make authentication with our Active Directory work.</p>
|
[
{
"answer_id": 41247,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 1,
"selected": false,
"text": "<?php\n$ds = ldap_connect('host.ad.lan', 389);\nldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($ds, LDAP_OPT_REFERRALS, 0);\nldap_bind($ds, '[email protected]', 'xxx');\n$sr = ldap_search($ds, 'CN=Cameron Zemek,OU=Users,OU=BRC,DC=ad,DC=lan', '(objectclass=*)', array('cn'));\n$entryID = ldap_first_entry($ds, $sr);\n$data = ldap_get_attributes($ds, $entryID);\nprint_r($data);\nldap_close($ds);\n"
},
{
"answer_id": 45745926,
"author": "incrementor",
"author_id": 1203340,
"author_profile": "https://Stackoverflow.com/users/1203340",
"pm_score": 0,
"selected": false,
"text": "# openssl s_client -showcerts -connect google.com:443 /usr/local/share/ca-certificates # dpkg-reconfigure ca-certificates /etc/ldap/ldap.conf ldapsearch -x -LLL -h ad.mydomain.com -D binduser -W -z 30 -b \"dc=mydomain,dc=com\" searchString"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] |
41,244 |
<p>I found an example in the <a href="http://msdn2.microsoft.com/en-us/bb330936.aspx" rel="noreferrer">VS2008 Examples</a> for Dynamic LINQ that allows you to use a SQL-like string (e.g. <code>OrderBy("Name, Age DESC"))</code> for ordering. Unfortunately, the method included only works on <code>IQueryable<T></code>. Is there any way to get this functionality on <code>IEnumerable<T></code>?</p>
|
[
{
"answer_id": 41262,
"author": "Kjetil Watnedal",
"author_id": 4116,
"author_profile": "https://Stackoverflow.com/users/4116",
"pm_score": 6,
"selected": false,
"text": "IEnumerable<T> myEnumerables\nvar query=from enumerable in myenumerables\n where some criteria\n orderby GetPropertyValue(enumerable,\"SomeProperty\")\n select enumerable\n\nprivate static object GetPropertyValue(object obj, string property)\n{\n System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);\n return propertyInfo.GetValue(obj, null);\n}\n"
},
{
"answer_id": 41427,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {\n //parse the string into property names\n //Use reflection to get and sort by properties\n //something like\n\n foreach( string propname in queryString.Split(','))\n input.OrderBy( x => GetPropertyValue( x, propname ) );\n\n // I used Kjetil Watnedal's reflection example\n}\n GetPropertyValue"
},
{
"answer_id": 233505,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 11,
"selected": true,
"text": "IEnumerable<T> AsQueryable Expression public static IOrderedQueryable<T> OrderBy<T>(\n this IQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"OrderBy\");\n}\n\npublic static IOrderedQueryable<T> OrderByDescending<T>(\n this IQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"OrderByDescending\");\n}\n\npublic static IOrderedQueryable<T> ThenBy<T>(\n this IOrderedQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"ThenBy\");\n}\n\npublic static IOrderedQueryable<T> ThenByDescending<T>(\n this IOrderedQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"ThenByDescending\");\n}\n\nstatic IOrderedQueryable<T> ApplyOrder<T>(\n IQueryable<T> source, \n string property, \n string methodName) \n{\n string[] props = property.Split('.');\n Type type = typeof(T);\n ParameterExpression arg = Expression.Parameter(type, \"x\");\n Expression expr = arg;\n foreach(string prop in props) {\n // use reflection (not ComponentModel) to mirror LINQ\n PropertyInfo pi = type.GetProperty(prop);\n expr = Expression.Property(expr, pi);\n type = pi.PropertyType;\n }\n Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);\n LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);\n\n object result = typeof(Queryable).GetMethods().Single(\n method => method.Name == methodName\n && method.IsGenericMethodDefinition\n && method.GetGenericArguments().Length == 2\n && method.GetParameters().Length == 2)\n .MakeGenericMethod(typeof(T), type)\n .Invoke(null, new object[] {source, lambda});\n return (IOrderedQueryable<T>)result;\n}\n dynamic dynamic dynamic MemberExpression Hashtable using Microsoft.CSharp.RuntimeBinder;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nstatic class Program\n{\n private static class AccessorCache\n {\n private static readonly Hashtable accessors = new Hashtable();\n\n private static readonly Hashtable callSites = new Hashtable();\n\n private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(\n string name) \n {\n var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];\n if(callSite == null)\n {\n callSites[name] = callSite = CallSite<Func<CallSite, object, object>>\n .Create(Binder.GetMember(\n CSharpBinderFlags.None, \n name, \n typeof(AccessorCache),\n new CSharpArgumentInfo[] { \n CSharpArgumentInfo.Create(\n CSharpArgumentInfoFlags.None, \n null) \n }));\n }\n return callSite;\n }\n\n internal static Func<dynamic,object> GetAccessor(string name)\n {\n Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];\n if (accessor == null)\n {\n lock (accessors )\n {\n accessor = (Func<dynamic, object>)accessors[name];\n if (accessor == null)\n {\n if(name.IndexOf('.') >= 0) {\n string[] props = name.Split('.');\n CallSite<Func<CallSite, object, object>>[] arr \n = Array.ConvertAll(props, GetCallSiteLocked);\n accessor = target =>\n {\n object val = (object)target;\n for (int i = 0; i < arr.Length; i++)\n {\n var cs = arr[i];\n val = cs.Target(cs, val);\n }\n return val;\n };\n } else {\n var callSite = GetCallSiteLocked(name);\n accessor = target =>\n {\n return callSite.Target(callSite, (object)target);\n };\n }\n accessors[name] = accessor;\n }\n }\n }\n return accessor;\n }\n }\n\n public static IOrderedEnumerable<dynamic> OrderBy(\n this IEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.OrderBy<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n public static IOrderedEnumerable<dynamic> OrderByDescending(\n this IEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.OrderByDescending<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n public static IOrderedEnumerable<dynamic> ThenBy(\n this IOrderedEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.ThenBy<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n public static IOrderedEnumerable<dynamic> ThenByDescending(\n this IOrderedEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.ThenByDescending<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n static void Main()\n {\n dynamic a = new ExpandoObject(), \n b = new ExpandoObject(), \n c = new ExpandoObject();\n a.X = \"abc\";\n b.X = \"ghi\";\n c.X = \"def\";\n dynamic[] data = new[] { \n new { Y = a },\n new { Y = b }, \n new { Y = c } \n };\n\n var ordered = data.OrderByDescending(\"Y.X\").ToArray();\n foreach (var obj in ordered)\n {\n Console.WriteLine(obj.Y.X);\n }\n }\n}\n"
},
{
"answer_id": 370126,
"author": "InfoStatus",
"author_id": 41385,
"author_profile": "https://Stackoverflow.com/users/41385",
"pm_score": 3,
"selected": false,
"text": "var query = pets.OrderBy(pet => pet.Name).ThenByDescending(pet => pet.Age); \n"
},
{
"answer_id": 649026,
"author": "Mike Christiansen",
"author_id": 29249,
"author_profile": "https://Stackoverflow.com/users/29249",
"pm_score": 2,
"selected": false,
"text": "public interface IID\n{\n int ID\n {\n get; set;\n }\n}\n\npublic static class Utils\n{\n public static int GetID<T>(ObjectQuery<T> items) where T:EntityObject, IID\n {\n if (items.Count() == 0) return 1;\n return items.OrderByDescending(u => u.ID).FirstOrDefault().ID + 1;\n }\n}\n"
},
{
"answer_id": 704341,
"author": "vdhant",
"author_id": 30572,
"author_profile": "https://Stackoverflow.com/users/30572",
"pm_score": 5,
"selected": false,
"text": "public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> input, string queryString)\n{\n if (string.IsNullOrEmpty(queryString))\n return input;\n\n int i = 0;\n foreach (string propname in queryString.Split(','))\n {\n var subContent = propname.Split('|');\n if (Convert.ToInt32(subContent[1].Trim()) == 0)\n {\n if (i == 0)\n input = input.OrderBy(x => GetPropertyValue(x, subContent[0].Trim()));\n else\n input = ((IOrderedEnumerable<T>)input).ThenBy(x => GetPropertyValue(x, subContent[0].Trim()));\n }\n else\n {\n if (i == 0)\n input = input.OrderByDescending(x => GetPropertyValue(x, subContent[0].Trim()));\n else\n input = ((IOrderedEnumerable<T>)input).ThenByDescending(x => GetPropertyValue(x, subContent[0].Trim()));\n }\n i++;\n }\n\n return input;\n}\n"
},
{
"answer_id": 1642942,
"author": "James McCormack",
"author_id": 71906,
"author_profile": "https://Stackoverflow.com/users/71906",
"pm_score": 4,
"selected": false,
"text": "IComparer List<DATA__Security__Team> teams = TeamManager.GetTeams();\nvar query = teams.Where(team => team.ID < 10).AsQueryable();\n string SortField; // Set at run-time to \"Name\"\n query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));\n public static string GetReflectedPropertyValue(this object subject, string field)\n{\n object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);\n return reflectedValue != null ? reflectedValue.ToString() : \"\";\n}\n OrderBy IComparer OrderBy query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());\n NaturalSortComparer()"
},
{
"answer_id": 2058305,
"author": "Sameer Alibhai",
"author_id": 2343,
"author_profile": "https://Stackoverflow.com/users/2343",
"pm_score": 2,
"selected": false,
"text": "DataTable orders = dataSet.Tables[\"SalesOrderHeader\"];\nEnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()\n orderby order.Field<DateTime>(\"OrderDate\")\n select order;\nDataView view = query.AsDataView();\nbindingSource1.DataSource = view;\n DataTable contacts = dataSet.Tables[\"Contact\"]; \nDataView view = contacts.AsDataView(); \nview.Sort = \"LastName desc, FirstName asc\"; \nbindingSource1.DataSource = view;\ndataGridView1.AutoResizeColumns();\n"
},
{
"answer_id": 3508411,
"author": "Adam Anderson",
"author_id": 302998,
"author_profile": "https://Stackoverflow.com/users/302998",
"pm_score": 6,
"selected": false,
"text": "list.OrderBy(\"MyProperty DESC, MyOtherProperty ASC\");\n"
},
{
"answer_id": 8660293,
"author": "Alaa Osta",
"author_id": 456156,
"author_profile": "https://Stackoverflow.com/users/456156",
"pm_score": 8,
"selected": false,
"text": "using System.Linq.Dynamic; vehicles = vehicles.AsQueryable().OrderBy(\"Make ASC, Year DESC\").ToList();"
},
{
"answer_id": 12920204,
"author": "joaopintocruz",
"author_id": 1139347,
"author_profile": "https://Stackoverflow.com/users/1139347",
"pm_score": 2,
"selected": false,
"text": "myList.OrderByDescending(x => myPropertyInfo.GetValue(x, null)).ToList();\n foreach (PropertyInfo column in (new Process()).GetType().GetProperties())\n{\n if (column.Name == dgvProcessList.Columns[e.ColumnIndex].Name)\n {}\n}\n PropertyInfo column = (new Process()).GetType().GetProperties().Where(x => x.Name == dgvProcessList.Columns[e.ColumnIndex].Name).First();\n"
},
{
"answer_id": 16046948,
"author": "Sanchitos",
"author_id": 317832,
"author_profile": "https://Stackoverflow.com/users/317832",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<TEntity> OrderBy<TEntity>(this IEnumerable<TEntity> source, \n string orderByProperty, bool desc)\n{\n string command = desc ? \"OrderByDescending\" : \"OrderBy\";\n var type = typeof(TEntity);\n var property = type.GetProperty(orderByProperty);\n var parameter = Expression.Parameter(type, \"p\");\n var propertyAccess = Expression.MakeMemberAccess(parameter, property);\n var orderByExpression = Expression.Lambda(propertyAccess, parameter);\n var resultExpression = Expression.Call(typeof(Queryable), command, \n new[] { type, property.PropertyType },\n source.AsQueryable().Expression, \n Expression.Quote(orderByExpression));\n return source.AsQueryable().Provider.CreateQuery<TEntity>(resultExpression);\n}\n"
},
{
"answer_id": 25034533,
"author": "Richard YS",
"author_id": 1659637,
"author_profile": "https://Stackoverflow.com/users/1659637",
"pm_score": 2,
"selected": false,
"text": "items = items.AsQueryable().OrderBy(\"Name ASC\");\n"
},
{
"answer_id": 37251268,
"author": "Arindam",
"author_id": 6198269,
"author_profile": "https://Stackoverflow.com/users/6198269",
"pm_score": -1,
"selected": false,
"text": "var result1 = lst.OrderBy(a=>a.Name);// for ascending order. \n var result1 = lst.OrderByDescending(a=>a.Name);// for desc order. \n"
},
{
"answer_id": 47462935,
"author": "M.Hassan",
"author_id": 3142139,
"author_profile": "https://Stackoverflow.com/users/3142139",
"pm_score": 2,
"selected": false,
"text": "public IEnumerable<Order> GetOrders()\n{\n // i use Dapper to return IEnumerable<T> using Query<T>\n //.. do stuff\n\n return orders // IEnumerable<Order>\n}\n public IQueryable<Order> GetOrdersAsQuerable()\n{\n IEnumerable<Order> qry= GetOrders();\n\n // use the built-in extension method AsQueryable in System.Linq namespace\n return qry.AsQueryable(); \n}\n"
},
{
"answer_id": 49212617,
"author": "Aminur Rahman",
"author_id": 5644299,
"author_profile": "https://Stackoverflow.com/users/5644299",
"pm_score": 3,
"selected": false,
"text": "install-package System.Linq.Dynamic\n using System.Linq.Dynamic; OrderBy(\"Name, Age DESC\")"
},
{
"answer_id": 53921180,
"author": "Masoud Darvishian",
"author_id": 1402749,
"author_profile": "https://Stackoverflow.com/users/1402749",
"pm_score": 3,
"selected": false,
"text": "linq using System.Linq.Dynamic; string sortTypeStr = \"ASC\"; // or DESC\nstring SortColumnName = \"Age\"; // Your column name\nquery = query.OrderBy($\"{SortColumnName} {sortTypeStr}\");\n"
},
{
"answer_id": 60711480,
"author": "k1developer",
"author_id": 3607574,
"author_profile": "https://Stackoverflow.com/users/3607574",
"pm_score": 2,
"selected": false,
"text": " public List<Book> Books(string orderField, bool desc, int skip, int take)\n{\n var propertyInfo = typeof(Book).GetProperty(orderField);\n\n return _context.Books\n .Where(...)\n .OrderBy(p => !desc ? propertyInfo.GetValue(p, null) : 0)\n .ThenByDescending(p => desc ? propertyInfo.GetValue(p, null) : 0)\n .Skip(skip)\n .Take(take)\n .ToList();\n}\n"
},
{
"answer_id": 64088037,
"author": "Francis Shaw",
"author_id": 9614021,
"author_profile": "https://Stackoverflow.com/users/9614021",
"pm_score": 1,
"selected": false,
"text": "IOrderedEnumerable<JToken> sort;\n\nif (query.OrderBys[0].IsDESC)\n{\n sort = jarry.OrderByDescending(r => (string)r[query.OrderBys[0].Key]);\n}\nelse\n{\n sort = jarry.OrderBy(r =>\n (string) r[query.OrderBys[0].Key]); \n}\n\nforeach (var item in query.OrderBys.Skip(1))\n{\n if (item.IsDESC)\n {\n sort = sort.ThenByDescending(r => (string)r[item.Key]);\n }\n else\n {\n sort = sort.ThenBy(r => (string)r[item.Key]);\n }\n}\n"
},
{
"answer_id": 70193394,
"author": "BenW",
"author_id": 1833408,
"author_profile": "https://Stackoverflow.com/users/1833408",
"pm_score": -1,
"selected": false,
"text": " protected void sort_array(string field_name, string asc_desc)\n {\n\n objArrayList= Sort(objArrayList, field_name, asc_desc);\n }\n\n protected List<ArrayType> Sort(List<ArrayType> input, string property, string asc_desc)\n {\n if (asc_desc == \"ASC\")\n {\n\n return input.OrderBy(p => p.GetType()\n .GetProperty(property)\n .GetValue(p, null)).ToList();\n }\n else\n {\n return input.OrderByDescending(p => p.GetType()\n .GetProperty(property)\n .GetValue(p, null)).ToList();\n }\n }\n"
},
{
"answer_id": 70411214,
"author": "Sajed",
"author_id": 10336618,
"author_profile": "https://Stackoverflow.com/users/10336618",
"pm_score": 2,
"selected": false,
"text": "Dictionary<string, Func<Item, object>> SortParameters = new Dictionary<string, Func<Item, object>>()\n{\n {\"Rank\", x => x.Rank}\n};\n yourList.OrderBy(SortParameters[\"Rank\"]);\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] |
41,290 |
<p>I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is <em>very</em> static, but just <em>might</em> change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt.</p>
<p>I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file.</p>
<p>This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released?</p>
<p>Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :)</p>
<ul>
<li><strong>Am I missing something?</strong></li>
<li><strong>What is the best file access strategy in a multi-threaded environment?</strong>
<hr></li>
</ul>
<h3>Edit</h3>
<p>Sorry - I should have said this is using <strong>ASP.NET 2.0</strong> :)</p>
|
[
{
"answer_id": 41559,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 4,
"selected": true,
"text": " /// <summary>\n /// Blocks until the file is not locked any more.\n /// </summary>\n /// <param name=\"fullPath\"></param>\n bool WaitForFile(string fullPath)\n {\n int numTries = 0;\n while (true)\n {\n ++numTries;\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite, \n FileShare.None, 100))\n {\n fs.ReadByte();\n\n // If we got this far the file is ready\n break;\n }\n }\n catch (Exception ex)\n {\n Log.LogWarning(\n \"WaitForFile {0} failed to get an exclusive lock: {1}\", \n fullPath, ex.ToString());\n\n if (numTries > 10)\n {\n Log.LogWarning(\n \"WaitForFile {0} giving up after 10 tries\", \n fullPath);\n return false;\n }\n\n // Wait for the lock to be released\n System.Threading.Thread.Sleep(500);\n }\n }\n\n Log.LogTrace(\"WaitForFile {0} returning true after {1} tries\",\n fullPath, numTries);\n return true;\n }\n"
},
{
"answer_id": 113659,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "lock"
},
{
"answer_id": 32701350,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 0,
"selected": false,
"text": "AutoResetEvent createfile main static AutoResetEvent waitHandle = new AutoResetEvent(false);\n static string filePath=@\"C:\\Temp\\test.txt\";\n static string fileCopyPath=@\"C:\\Temp\\test-copy.txt\";\n static void Main(string[] args)\n {\n Console.WriteLine(\"in main method\");\n Console.WriteLine();\n Thread thread = new Thread(createFile);\n thread.Start();\n\n Console.WriteLine(\"waiting for file to be processed \");\n Console.WriteLine();\n waitHandle.WaitOne();\n Console.WriteLine();\n\n File.Copy(filePath, fileCopyPath);\n Console.WriteLine(\"file copied \");\n\n }\n\n\n static void createFile()\n {\n\n FileStream fs= File.Create(filePath); \n Console.WriteLine(\"start processing a file \"+DateTime.Now);\n Console.WriteLine();\n using (StreamWriter sw = new StreamWriter(fs))\n {\n for (long i = 0; i < 300000000; i++)\n {\n sw.WriteLine(\"The value of i is \" + i);\n\n }\n }\n Console.WriteLine(\"file processed \" + DateTime.Now);\n Console.WriteLine();\n\n waitHandle.Set();\n }\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
41,300 |
<p>How do you run Emacs in Windows?</p>
<p>What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the .emacs file located?</p>
|
[
{
"answer_id": 3679058,
"author": "cristobalito",
"author_id": 376700,
"author_profile": "https://Stackoverflow.com/users/376700",
"pm_score": 5,
"selected": false,
"text": "C-h v user-init-file\n (find-file user-init-file)\n"
},
{
"answer_id": 14307654,
"author": "mkasberg",
"author_id": 1263211,
"author_profile": "https://Stackoverflow.com/users/1263211",
"pm_score": 3,
"selected": false,
"text": "emacs-xx.x-bin-i686-pc-mingw32.zip"
},
{
"answer_id": 16260342,
"author": "Jeff",
"author_id": 2320976,
"author_profile": "https://Stackoverflow.com/users/2320976",
"pm_score": 0,
"selected": false,
"text": "Emacs4LS"
},
{
"answer_id": 16415484,
"author": "Adam.at.Epsilon",
"author_id": 2173897,
"author_profile": "https://Stackoverflow.com/users/2173897",
"pm_score": 1,
"selected": false,
"text": "@call drive:\\EMACS_SOMEWHERE\\emacs-23.2\\bin\\emacsclientw.exe --alternate-editor=c:\\programs\\emacs-23.2\\bin\\runemacs.exe -n -c %*\n"
},
{
"answer_id": 17683861,
"author": "Darren Embry",
"author_id": 8621049,
"author_profile": "https://Stackoverflow.com/users/8621049",
"pm_score": 1,
"selected": false,
"text": "c:\\site-lisp\\site-start.el c:\\site-lisp c:\\site-lisp site-start.el"
},
{
"answer_id": 27023911,
"author": "Alain",
"author_id": 475162,
"author_profile": "https://Stackoverflow.com/users/475162",
"pm_score": 1,
"selected": false,
"text": "https://bitbucket.org/Haroogan/emacs-for-windows eww"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473/"
] |
41,304 |
<p>I know in ASP.NET I can get an item from a DropDownList by using</p>
<pre><code>DropDownList1.Items.FindByText
</code></pre>
<p>Is there a similar method I can use in WPF for a ComboBox?</p>
<p>Here's the scenario.</p>
<p>I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.</p>
<p>In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.</p>
<hr>
<p>Here's the scenario.</p>
<p>I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.</p>
<p>In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.</p>
<p>Does this make sense?</p>
|
[
{
"answer_id": 41305,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": " <ComboBox Name=\"combo\">\n <ComboBoxItem Name=\"item1\" >1</ComboBoxItem>\n <ComboBoxItem Name=\"item2\">2</ComboBoxItem>\n <ComboBoxItem Name=\"item3\">3</ComboBoxItem>\n </ComboBox>\n item1.Content = \"New content\"; // Reference combo box item by name\n ComboBoxItem item = (ComboBoxItem)this.combo.FindName(\"item1\"); // Using FindName method\n"
},
{
"answer_id": 662946,
"author": "Rich",
"author_id": 53501,
"author_profile": "https://Stackoverflow.com/users/53501",
"pm_score": 5,
"selected": true,
"text": "ComboBoxItem item = \n (ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject);\n"
},
{
"answer_id": 662950,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "ComboBoxItem item = (ComboBoxItem) control.ItemContainerGenerator.ContainerFromItem(control.SelectedItem);\n ComboBoxItem item = (ComboBoxItem) control.ItemContainerGenerator.ContainerFromIndex(1);\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
41,319 |
<p>What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type <code>IEnumerable<T></code> and doesn't have a Count property.</p>
<p>Right now I'm tossing up between this:</p>
<pre><code>if (myList.Count() == 0) { ... }
</code></pre>
<p>and this:</p>
<pre><code>if (!myList.Any()) { ... }
</code></pre>
<p>My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.</p>
<p>That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?</p>
<p><strong>Edit</strong> @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:</p>
<pre><code>public static bool IsEmpty<T>(this IEnumerable<T> list)
{
if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;
return !list.Any();
}
</code></pre>
|
[
{
"answer_id": 41324,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 8,
"selected": true,
"text": "public static Boolean IsEmpty<T>(this IEnumerable<T> source)\n{\n if (source == null)\n return true; // or throw an exception\n return !source.Any();\n}\n"
},
{
"answer_id": 41325,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 3,
"selected": false,
"text": " IEnumerable<Object> myList = new List<Object>();\n\n Stopwatch watch = new Stopwatch();\n\n int x;\n\n watch.Start();\n for (var i = 0; i <= 1000000; i++)\n {\n if (myList.Count() == 0) x = i; \n }\n watch.Stop();\n\n Stopwatch watch2 = new Stopwatch();\n\n watch2.Start();\n for (var i = 0; i <= 1000000; i++)\n {\n if (!myList.Any()) x = i;\n }\n watch2.Stop();\n\n Console.WriteLine(\"myList.Count() = \" + watch.ElapsedMilliseconds.ToString());\n Console.WriteLine(\"myList.Any() = \" + watch2.ElapsedMilliseconds.ToString());\n Console.ReadLine();\n"
},
{
"answer_id": 41339,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "Any() Count() Any() Count()"
},
{
"answer_id": 41357,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "IList Count Any IEnumerable.GetEnumerator MoveNext ICollection IList"
},
{
"answer_id": 41365,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "IEnumerable<T> IList<T> public static int Count<T>(this IEnumerable<T> list)\n{\n if (list is IList<T>) return ((IList<T>)list).Count;\n\n int i = 0;\n foreach (var t in list) i++;\n return i;\n}\n IList<T> ICollection<T>"
},
{
"answer_id": 1620712,
"author": "Jonny Dee",
"author_id": 196164,
"author_profile": "https://Stackoverflow.com/users/196164",
"pm_score": -1,
"selected": false,
"text": "public static bool IsEmpty<T>(this IEnumerable<T> enumerable)\n{\n try\n {\n enumerable.First();\n return false;\n }\n catch (InvalidOperationException)\n {\n return true;\n }\n}\n"
},
{
"answer_id": 1623097,
"author": "Jonny Dee",
"author_id": 196432,
"author_profile": "https://Stackoverflow.com/users/196432",
"pm_score": 1,
"selected": false,
"text": "public static bool IsEmpty<T>(this IEnumerable<T> enumerable)\n{\n return !enumerable.GetEnumerator().MoveNext();\n}\n"
},
{
"answer_id": 1938747,
"author": "ChulioMartinez",
"author_id": 63865,
"author_profile": "https://Stackoverflow.com/users/63865",
"pm_score": 1,
"selected": false,
"text": "if(enumerable.FirstOrDefault() != null)\n"
},
{
"answer_id": 3495249,
"author": "Dasmowenator",
"author_id": 367544,
"author_profile": "https://Stackoverflow.com/users/367544",
"pm_score": 3,
"selected": false,
"text": "List.Count List.Count == 0 List.Count"
},
{
"answer_id": 3576549,
"author": "Dan Tao",
"author_id": 105570,
"author_profile": "https://Stackoverflow.com/users/105570",
"pm_score": 4,
"selected": false,
"text": "ICollection Queue<T> Stack<T> as is public static bool IsEmpty<T>(this IEnumerable<T> list)\n{\n if (list == null)\n {\n throw new ArgumentNullException(\"list\");\n }\n\n var genericCollection = list as ICollection<T>;\n if (genericCollection != null)\n {\n return genericCollection.Count == 0;\n }\n\n var nonGenericCollection = list as ICollection;\n if (nonGenericCollection != null)\n {\n return nonGenericCollection.Count == 0;\n }\n\n return !list.Any();\n}\n"
},
{
"answer_id": 6958074,
"author": "gandarez",
"author_id": 833531,
"author_profile": "https://Stackoverflow.com/users/833531",
"pm_score": 0,
"selected": false,
"text": "var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()\n\nif (cfop.Count() > 0)\n{\n var itemCfop = cfop.First();\n //....\n}\n var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()\n\nvar itemCfop = cfop.FirstOrDefault();\n\nif (itemCfop != null)\n{\n //....\n}\n"
},
{
"answer_id": 8527081,
"author": "Holt Mansfield",
"author_id": 522598,
"author_profile": "https://Stackoverflow.com/users/522598",
"pm_score": 1,
"selected": false,
"text": "var genericCollection = list as ICollection<T>;\n\nif (genericCollection != null)\n{\n //your code \n}\n"
},
{
"answer_id": 9770656,
"author": "suneelsarraf",
"author_id": 1124234,
"author_profile": "https://Stackoverflow.com/users/1124234",
"pm_score": 0,
"selected": false,
"text": "private bool NullTest<T>(T[] list, string attribute)\n\n {\n bool status = false;\n if (list != null)\n {\n int flag = 0;\n var property = GetProperty(list.FirstOrDefault(), attribute);\n foreach (T obj in list)\n {\n if (property.GetValue(obj, null) == null)\n flag++;\n }\n status = flag == 0 ? true : false;\n }\n return status;\n }\n\n\npublic PropertyInfo GetProperty<T>(T obj, string str)\n\n {\n Expression<Func<T, string, PropertyInfo>> GetProperty = (TypeObj, Column) => TypeObj.GetType().GetProperty(TypeObj\n .GetType().GetProperties().ToList()\n .Find(property => property.Name\n .ToLower() == Column\n .ToLower()).Name.ToString());\n return GetProperty.Compile()(obj, str);\n }\n"
},
{
"answer_id": 10409651,
"author": "Milad Sadeghi",
"author_id": 1369436,
"author_profile": "https://Stackoverflow.com/users/1369436",
"pm_score": -1,
"selected": false,
"text": "List<T> li = new List<T>();\n(li.First().DefaultValue.HasValue) ? string.Format(\"{0:yyyy/MM/dd}\", sender.First().DefaultValue.Value) : string.Empty;\n"
},
{
"answer_id": 12237400,
"author": "devuxer",
"author_id": 129164,
"author_profile": "https://Stackoverflow.com/users/129164",
"pm_score": 0,
"selected": false,
"text": "public static bool IsEmpty<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)\n{\n if (source == null) throw new ArgumentNullException();\n if (IsCollectionAndEmpty(source)) return true;\n return !source.Any(predicate);\n}\n\npublic static bool IsEmpty<TSource>(this IEnumerable<TSource> source)\n{\n if (source == null) throw new ArgumentNullException();\n if (IsCollectionAndEmpty(source)) return true;\n return !source.Any();\n}\n\nprivate static bool IsCollectionAndEmpty<TSource>(IEnumerable<TSource> source)\n{\n var genericCollection = source as ICollection<TSource>;\n if (genericCollection != null) return genericCollection.Count == 0;\n var nonGenericCollection = source as ICollection;\n if (nonGenericCollection != null) return nonGenericCollection.Count == 0;\n return false;\n}\n"
},
{
"answer_id": 30056312,
"author": "user3149517",
"author_id": 3149517,
"author_profile": "https://Stackoverflow.com/users/3149517",
"pm_score": -1,
"selected": false,
"text": "myList.ToList().Count == 0"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] |
41,330 |
<p>How do I detect if the system has a default recording device installed?
I bet this can be done through some calls to the Win32 API, anyone has any experience with this?</p>
<p>I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.</p>
|
[
{
"answer_id": 41385,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 2,
"selected": true,
"text": "#include <tchar.h>\n#include <windows.h>\n#include \"mmsystem.h\"\n\nint _tmain( int argc, wchar_t *argv[] )\n{\n UINT deviceCount = waveInGetNumDevs();\n\n if ( deviceCount > 0 )\n {\n for ( int i = 0; i < deviceCount; i++ )\n {\n WAVEINCAPSW waveInCaps;\n\n waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) );\n\n // do some stuff with waveInCaps...\n }\n }\n\n return 0;\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509946/"
] |
41,355 |
<p>Has anybody got any kind of experience with dynamic programming using WCF. By dynamic programming I mean runtime consumption of WSDL's.
I have found one blog entry/tool:
<a href="http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx</a></p>
<p>Has anybody here found good tools for this?</p>
|
[
{
"answer_id": 169485,
"author": "Cuyler",
"author_id": 25041,
"author_profile": "https://Stackoverflow.com/users/25041",
"pm_score": 3,
"selected": true,
"text": "Execute() ChannelFactory<IFoo>"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189/"
] |
41,397 |
<p>Right, I know I am totally going to look an idiot with this one, but my brain is just <em>not</em> kicking in to gear this morning.</p>
<p>I want to have a method where I can say "if it goes bad, come back with this type of Exception", right?</p>
<p>For example, something like (<strong>and this doesn't work</strong>):</p>
<pre><code> static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
</code></pre>
<p>Now whats confusing me is that we <em>KNOW</em> that the generic type is going to be of an Exception type due to the <em>where</em> clause. However, the code fails because we cannot implicitly cast <em>Exception</em> to <em>ExType</em>. We cannot explicitly convert it either, such as:</p>
<pre><code> static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
</code></pre>
<p>As that fails too.. So <strong>is this kind of thing possible?</strong> I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P</p>
<hr />
<h2>Update</h2>
<p>Thanks for the responses guys, looks like it wasn't me being a <em>complete</em> idiot! ;)</p>
<p>OK, so <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398">Vegard</a> and <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404">Sam</a> got me on to the point where I could instantiate the correct type, but then obviously got stuck because the <em>message</em> param is read-only following instantiation.</p>
<p><a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408">Matt</a> hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code:</p>
<pre><code> static ExType TestException<ExType>(string message) where ExType:Exception, new ()
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
</code></pre>
<p>Sweet! :)</p>
<p>Thanks guys!</p>
|
[
{
"answer_id": 41402,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "static T TestException<Exception>(string message)\n{}\n"
},
{
"answer_id": 41404,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": -1,
"selected": false,
"text": "Message static ExType TestException<ExType>(string message) where ExType:Exception\n{\n ExType ex = new ExType();\n ex.Message = message;\n return ex;\n}\n static ExType TestException<ExType>(string message) where ExType:Exception\n{\n return new ExType(message);\n}\n"
},
{
"answer_id": 41408,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "static void TestException<E>(string message) where E : Exception, new()\n{\n var e = new E();\n e.Message = message;\n throw e;\n}\n static void TestException<E>(string message) where E : Exception\n{\n throw Activator.CreateInstance(typeof(E), message) as E;\n}\n"
},
{
"answer_id": 41450,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 4,
"selected": false,
"text": "static void TestException<E>(string message) where E : Exception, new()\n{\n try \n {\n return Activator.CreateInstance(typeof(E), message) as E;\n } \n catch(MissingMethodException ex) \n {\n return new E();\n }\n}\n"
},
{
"answer_id": 9113952,
"author": "MiloNC",
"author_id": 1185299,
"author_profile": "https://Stackoverflow.com/users/1185299",
"pm_score": 1,
"selected": false,
"text": "if (ItemNameIsValid(ItemName, out errorMessage))\n throw new KeyNotFoundException(\"Invalid name '\" + ItemName + \"': \" + errorMessage);\nif (null == MyArgument)\n throw new ArgumentNullException(\"MyArgument is null\");\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
41,400 |
<p>I am looking to do this in C/C++. I came across <a href="http://www.swig.org/Doc1.3/Varargs.html" rel="nofollow noreferrer"><strong>Variable Length Arguments</strong></a>, but this suggests a solution with Python and C using <a href="http://sourceware.org/libffi/" rel="nofollow noreferrer">libffi</a>.</p>
<p>Now, if I want to wrap the <code>printf</code> function with <code>myprintf</code>.</p>
<p>I do it like below:</p>
<pre><code>void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
</code></pre>
<p>But the results are not as expected!</p>
<pre class="lang-none prettyprint-override"><code>This is a number: 1244780 and
this is a character: h and
another number: 29953463
</code></pre>
<p>What did I miss?</p>
|
[
{
"answer_id": 41414,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "void f(varargs va) {\n BOOST_FOREACH(varargs::iterator i, va)\n cout << *i << \" \";\n}\n\nf(args = 1, 2, 3, \"Hello\");\n varargs operator = operator ,"
},
{
"answer_id": 41422,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 3,
"selected": false,
"text": "#include <cstdarg>\n#include <cstdio>\n\nclass Foo\n{ \n void Write(const char* pMsg, ...);\n};\n\nvoid Foo::Write( const char* pMsg, ...)\n{\n char buffer[4096];\n std::va_list arg;\n va_start(arg, pMsg);\n std::vsnprintf(buffer, 4096, pMsg, arg);\n va_end(arg);\n ...\n}\n"
},
{
"answer_id": 41794,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 7,
"selected": true,
"text": "void myprintf(char* fmt, ...)\n{\n va_list args;\n va_start(args, fmt);\n vprintf(fmt, args);\n va_end(args);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n int a = 9;\n int b = 10;\n char v = 'C';\n myprintf(\"This is a number: %d and \\nthis is a character: %c and \\n another number: %d\\n\", a, v, b);\n return 0;\n}\n"
},
{
"answer_id": 10380279,
"author": "john",
"author_id": 1053621,
"author_profile": "https://Stackoverflow.com/users/1053621",
"pm_score": 0,
"selected": false,
"text": "void myprintf(char* fmt, ...)\n{\n va_ list args;\n va_ start(args, fmt);\n printf(fmt, args); // This is the fault. \"vprintf(fmt, args);\"\n // should have been used.\n va_ end(args);\n}\n"
},
{
"answer_id": 17837382,
"author": "Shafik Yaghmour",
"author_id": 1708801,
"author_profile": "https://Stackoverflow.com/users/1708801",
"pm_score": 4,
"selected": false,
"text": "template<typename... Args>\nvoid myprintf(const char* fmt, Args... args)\n{\n std::printf(fmt, args...);\n}\n"
},
{
"answer_id": 22048209,
"author": "basin",
"author_id": 447503,
"author_profile": "https://Stackoverflow.com/users/447503",
"pm_score": 3,
"selected": false,
"text": "va_list call addr_printf printf() __declspec( thread ) static void* _tls_ret;\n\nstatic void __stdcall saveret(void *retaddr) {\n _tls_ret = retaddr;\n}\n\nstatic void* __stdcall _getret() {\n return _tls_ret;\n}\n\n__declspec(naked)\nstatic void __stdcall restret_and_return_int(int retval) {\n __asm {\n call _getret\n mov [esp], eax ; /* replace current retaddr with saved */\n mov eax, [esp+4] ; /* retval */\n ret 4\n }\n}\n\nstatic void __stdcall _dbg_printf_beg(const char *fmt, va_list args) {\n printf(\"calling printf(\\\"%s\\\")\\n\", fmt);\n}\n\nstatic void __stdcall _dbg_printf_end(int ret) {\n printf(\"printf() returned %d\\n\", ret);\n}\n\n__declspec(naked)\nint dbg_printf(const char *fmt, ...)\n{\n static const void *addr_printf = printf;\n /* prolog */\n __asm {\n push ebp\n mov ebp, esp\n sub esp, __LOCAL_SIZE\n nop\n }\n {\n va_list args;\n va_start(args, fmt);\n _dbg_printf_beg(fmt, args);\n va_end(args);\n }\n /* epilog */\n __asm {\n mov esp, ebp\n pop ebp\n }\n __asm {\n call saveret\n call addr_printf\n push eax\n push eax\n call _dbg_printf_end\n call restret_and_return_int\n }\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] |
41,406 |
<p>I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load.</p>
<p>How could I go about doing this?</p>
|
[
{
"answer_id": 41440,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 3,
"selected": false,
"text": "eval() eval execute() ->execute()"
},
{
"answer_id": 1472666,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "$x // your variable with the data from the DB\n<?php echo eval(\"?>\".$x.\"<?\") ?>\n"
},
{
"answer_id": 18580803,
"author": "Khaptin",
"author_id": 2741070,
"author_profile": "https://Stackoverflow.com/users/2741070",
"pm_score": 0,
"selected": false,
"text": "$lookFor = $row['page'];\n\ninclude(\"resources/\" . $lookFor . \"Codebase.php\");\n"
},
{
"answer_id": 33864063,
"author": "ashkufaraz",
"author_id": 634146,
"author_profile": "https://Stackoverflow.com/users/634146",
"pm_score": 0,
"selected": false,
"text": "$uniqid=\"tmp/\".date(\"d-m-Y h-i-s\").'_'.$Title.\"_\".uniqid().\".php\"; \n$file = fopen($uniqid,\"w\");\nfwrite($file,\"<?php \\r\\n \".$R['Body']);\nfclose($file); \n// eval($R['Body']);\ninclude $uniqid;\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654/"
] |
41,407 |
<p>I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:</p>
<pre><code>(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}):\d{2}:\d{2}),\d{3})\s(?<message>.+)
</code></pre>
<p>The log format (which I use for testing the parser) is this:</p>
<pre><code>07/23/08 14:17:31,321 log
message
spanning
multiple
lines
07/23/08 14:17:31,321 log message on one line
</code></pre>
<p>When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).</p>
<hr>
<p>@samjudson:</p>
<p><em>You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).</em></p>
<p>I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).</p>
<p>The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.</p>
<hr>
<p>I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.</p>
<pre><code>(?<message>(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
</code></pre>
|
[
{
"answer_id": 41412,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "RegexOptions"
},
{
"answer_id": 41428,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": true,
"text": "(?<date>\\d{2}/\\d{2}/\\d{2})\\s(?<time>\\d{2}:\\d{2}:\\d{2},\\d{3})\\s(?<message>(.(?!^\\d{2}/\\d{2}/\n\\d{2}))+)\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] |
41,424 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/307291/how-does-the-google-did-you-mean-algorithm-work">How does the Google “Did you mean?” Algorithm work?</a> </p>
</blockquote>
<p>Suppose you have a search system already in your website. How can you implement the "Did you mean:<code><spell_checked_word></code>" like Google does in some <a href="http://www.google.com/search?hl=en&q=spellling&btnG=Search" rel="noreferrer">search queries</a>?</p>
|
[
{
"answer_id": 302727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " string = \"my haert wil go on\"\n\n string.gsub(/[\\w\\']+/) do |word|\n if !speller.check(word)\n # word is wrong\n puts \"Possible correction for #{word}:\"\n puts speller.suggest(word).first\n end\n end\n"
},
{
"answer_id": 3888537,
"author": "hugo24",
"author_id": 252135,
"author_profile": "https://Stackoverflow.com/users/252135",
"pm_score": 0,
"selected": false,
"text": "import ngram\n\nG2 = ngram.NGram([ \"iis7 configure ftp 7.5\",\n \"ubunto configre 8.5\",\n \"mac configure ftp\"])\n\nprint \"String\", \"\\t\", \"Similarity\"\nfor i in G2.search(\"iis7 configurftp 7.5\", threshold=0.1):\n print i[1], \"\\t\", i[0]\n >>> \nString Similarity\n0.76 \"iis7 configure ftp 7.5\" \n0.24 \"mac configure ftp\"\n0.19 \"ubunto configre 8.5\" \n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
41,449 |
<p>The exact error is as follows</p>
<blockquote>
<p>Could not load file or assembly 'Microsoft.SqlServer.Replication,
Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
or one of its dependencies. An attempt was made to load a program with
an incorrect format.</p>
</blockquote>
<p>I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.</p>
|
[
{
"answer_id": 2926982,
"author": "bboyle1234",
"author_id": 213256,
"author_profile": "https://Stackoverflow.com/users/213256",
"pm_score": 9,
"selected": false,
"text": "ChilkatDotNet2"
},
{
"answer_id": 4023955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "Any CPU"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012/"
] |
41,453 |
<p>I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?</p>
|
[
{
"answer_id": 41865,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 4,
"selected": false,
"text": "namespace {\n static bool b2 = Filter::Filterable<const MyObj>::Register(\"MyObject\");\n} \n\nbool MyObj::BuildMap()\n{\n Filterable<const OutputDisease>::AddAccess(\"time\", &MyObj::time);\n Filterable<const OutputDisease>::AddAccess(\"person\", &MyObj::id);\n return true;\n}\n BuildMap() FILTER-OUTPUT-OBJECT MyObject\nFILTER-OUTPUT-FILENAME file.txt\nFILTER-CLAUSE-1 person == 1773\nFILTER-CLAUSE-2 time > 2000\n boost"
},
{
"answer_id": 314282,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "reflection template-tricks boost::type_traits"
},
{
"answer_id": 324689,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 4,
"selected": false,
"text": "boost::static_pointer_cast boost::dynamic_pointer_cast"
},
{
"answer_id": 1300289,
"author": "Roderick",
"author_id": 134919,
"author_profile": "https://Stackoverflow.com/users/134919",
"pm_score": 5,
"selected": false,
"text": "class __declspec(export) MyClass\n{\npublic:\n void Foo(float x);\n}\n MyClass *instance_ptr=new MyClass;\nGetClass(\"MyClass\")->GetFunction(\"Foo\")->Invoke(instance_ptr,1.331);\n instance_ptr->Foo(1.331);\n"
},
{
"answer_id": 4167176,
"author": "Matthieu M.",
"author_id": 147192,
"author_profile": "https://Stackoverflow.com/users/147192",
"pm_score": 3,
"selected": false,
"text": "BOOST_FUSION_ADAPT_STRUCT"
},
{
"answer_id": 11748131,
"author": "Paul Fultz II",
"author_id": 375343,
"author_profile": "https://Stackoverflow.com/users/375343",
"pm_score": 8,
"selected": false,
"text": "int x (int) x #define REM(...) __VA_ARGS__\n#define EAT(...)\n\n// Retrieve the type\n#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)\n#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)\n#define DETAIL_TYPEOF_HEAD(x, ...) REM x\n#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),\n// Strip off the type\n#define STRIP(x) EAT x\n// Show the type without parenthesis\n#define PAIR(x) REM x\n REFLECTABLE REFLECTABLE\n(\n (const char *) name,\n (int) age\n)\n // A helper metafunction for adding const to a type\ntemplate<class M, class T>\nstruct make_const\n{\n typedef T type;\n};\n\ntemplate<class M, class T>\nstruct make_const<const M, T>\n{\n typedef typename boost::add_const<T>::type type;\n};\n\n\n#define REFLECTABLE(...) \\\nstatic const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \\\nfriend struct reflector; \\\ntemplate<int N, class Self> \\\nstruct field_data {}; \\\nBOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))\n\n#define REFLECT_EACH(r, data, i, x) \\\nPAIR(x); \\\ntemplate<class Self> \\\nstruct field_data<i, Self> \\\n{ \\\n Self & self; \\\n field_data(Self & self) : self(self) {} \\\n \\\n typename make_const<Self, TYPEOF(x)>::type & get() \\\n { \\\n return self.STRIP(x); \\\n }\\\n typename boost::add_const<TYPEOF(x)>::type & get() const \\\n { \\\n return self.STRIP(x); \\\n }\\\n const char * name() const \\\n {\\\n return BOOST_PP_STRINGIZE(STRIP(x)); \\\n } \\\n}; \\\n fields_n field_data reflector struct reflector\n{\n //Get field_data at index N\n template<int N, class T>\n static typename T::template field_data<N, T> get_field_data(T& x)\n {\n return typename T::template field_data<N, T>(x);\n }\n\n // Get the number of fields\n template<class T>\n struct fields\n {\n static const int n = T::fields_n;\n };\n};\n struct field_visitor\n{\n template<class C, class Visitor, class I>\n void operator()(C& c, Visitor v, I)\n {\n v(reflector::get_field_data<I::value>(c));\n }\n};\n\n\ntemplate<class C, class Visitor>\nvoid visit_each(C & c, Visitor v)\n{\n typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range;\n boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1));\n}\n Person struct Person\n{\n Person(const char *name, int age)\n :\n name(name),\n age(age)\n {\n }\nprivate:\n REFLECTABLE\n (\n (const char *) name,\n (int) age\n )\n};\n print_fields struct print_visitor\n{\n template<class FieldData>\n void operator()(FieldData f)\n {\n std::cout << f.name() << \"=\" << f.get() << std::endl;\n }\n};\n\ntemplate<class T>\nvoid print_fields(T & x)\n{\n visit_each(x, print_visitor());\n}\n print_fields Person int main()\n{\n Person p(\"Tom\", 82);\n print_fields(p);\n return 0;\n}\n name=Tom\nage=82\n"
},
{
"answer_id": 40476588,
"author": "jenkas",
"author_id": 2604941,
"author_profile": "https://Stackoverflow.com/users/2604941",
"pm_score": 1,
"selected": false,
"text": "struct S1\n{\n ENUMERATE_MEMBERS(str,i);\n std::string str;\n int i;\n};\nstruct S2\n{\n ENUMERATE_MEMBERS(s1,i2);\n S1 s1;\n int i2;\n};\n void EnumerateWith(BinaryWriter & writer, int val)\n{\n //store integer\n writer.WriteBuffer(&val, sizeof(int));\n}\nvoid EnumerateWith(BinaryWriter & writer, std::string val)\n{\n //store string\n writer.WriteBuffer(val.c_str(), val.size());\n}\n template<typename TWriter, typename T>\nauto EnumerateWith(TWriter && writer, T && val) -> is_enumerable_t<T>\n{\n val.EnumerateWith(write); //method generated by ENUMERATE_MEMBERS macro\n}\n S1 s1;\nS2 s2;\n//....\nBinaryWriter writer(\"serialized.bin\");\n\nEnumerateWith(writer, s1); //this will call EnumerateWith for all members of S1\nEnumerateWith(writer, s2); //this will call EnumerateWith for all members of S2 and S2::s1 (recursively)\n #define ENUMERATE_MEMBERS(...) \\\ntemplate<typename TEnumerator> inline void EnumerateWith(TEnumerator & enumerator) const { EnumerateWithHelper(enumerator, __VA_ARGS__ ); }\\\ntemplate<typename TEnumerator> inline void EnumerateWith(TEnumerator & enumerator) { EnumerateWithHelper(enumerator, __VA_ARGS__); }\n\n// EnumerateWithHelper\ntemplate<typename TEnumerator, typename ...T> inline void EnumerateWithHelper(TEnumerator & enumerator, T &...v) \n{ \n int x[] = { (EnumerateWith(enumerator, v), 1)... }; \n}\n\n// Generic EnumerateWith\ntemplate<typename TEnumerator, typename T>\nauto EnumerateWith(TEnumerator & enumerator, T & val) -> std::void_t<decltype(val.EnumerateWith(enumerator))>\n{\n val.EnumerateWith(enumerator);\n}\n"
},
{
"answer_id": 54973430,
"author": "S.S. Anne",
"author_id": 10795151,
"author_profile": "https://Stackoverflow.com/users/10795151",
"pm_score": 0,
"selected": false,
"text": "int (*func)(int a, int b);\n libdl dlopen #include <dlfcn.h>\n\nint main(void)\n{\n void *handle;\n char *func_name = \"bla_bla_bla\";\n handle = dlopen(\"foo.so\", RTLD_LAZY);\n *(void **)(&func) = dlsym(handle, func_name);\n return func(1,2);\n}\n dlopen argv[0] dlopen() libdl dlfcn.h"
},
{
"answer_id": 55364085,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 2,
"selected": false,
"text": "#include \"CppReflect.h\"\nusing namespace std;\n\n\nclass Person\n{\npublic:\n\n // Repack your code into REFLECTABLE macro, in (<C++ Type>) <Field name>\n // form , like this:\n\n REFLECTABLE( Person,\n (CString) name,\n (int) age,\n...\n )\n};\n\nvoid main(void)\n{\n Person p;\n p.name = L\"Roger\";\n p.age = 37;\n...\n\n // And here you can convert your class contents into xml form:\n\n CStringW xml = ToXML( &p );\n CStringW errors;\n\n People ppl2;\n\n // And here you convert from xml back to class:\n\n FromXml( &ppl2, xml, errors );\n CStringA xml2 = ToXML( &ppl2 );\n printf( xml2 );\n\n}\n REFLECTABLE offsetof TypeInfo FieldInfo <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<People groupName=\"Group1\">\n <people>\n <Person name=\"Roger\" age=\"37\" />\n <Person name=\"Alice\" age=\"27\" />\n <Person name=\"Cindy\" age=\"17\" />\n </people>\n</People>\n c.General.IntDir = LR\"(obj\\$(ProjectName)_$(Configuration)_$(Platform)\\)\";\nc.General.OutDir = LR\"(bin\\$(Configuration)_$(Platform)\\)\";\nc.General.UseDebugLibraries = true;\nc.General.LinkIncremental = true;\nc.CCpp.Optimization = optimization_Disabled;\nc.Linker.System.SubSystem = subsystem_Console;\nc.Linker.Debugging.GenerateDebugInformation = debuginfo_true;\n __declspec(property(get =, put ... ) ReflectCopy ::OnAfterSetProperty"
},
{
"answer_id": 59447720,
"author": "TheNitesWhoSay",
"author_id": 12580603,
"author_profile": "https://Stackoverflow.com/users/12580603",
"pm_score": 3,
"selected": false,
"text": "class FuelTank {\n public:\n float capacity;\n float currentLevel;\n float tickMarks[2];\n\n REFLECT(FuelTank, capacity, currentLevel, tickMarks)\n};\n for ( size_t i=0; i<FuelTank::Class::TotalFields; i++ )\n std::cout << FuelTank::Class::Fields[i].name << std::endl;\n FuelTank::Class::ForEachField(fuelTank, [&](auto & field, auto & value) {\n using Type = typename std::remove_reference<decltype(value)>::type;\n std::cout << TypeToStr<Type>() << \" \" << field.name << \": \" << value << std::endl;\n});\n struct MyOtherObject { int myOtherInt; REFLECT(MyOtherObject, myOtherInt) };\nstruct MyObject\n{\n int myInt;\n std::string myString;\n MyOtherObject myOtherObject;\n std::vector<int> myIntCollection;\n\n REFLECT(MyObject, myInt, myString, myOtherObject, myIntCollection)\n};\n\nint main()\n{\n MyObject myObject = {};\n std::cout << \"Enter MyObject:\" << std::endl;\n std::cin >> Json::in(myObject);\n std::cout << std::endl << std::endl << \"You entered:\" << std::endl;\n std::cout << Json::pretty(myObject);\n}\n Enter MyObject:\n{\n \"myInt\": 1337, \"myString\": \"stringy\", \"myIntCollection\": [2,4,6],\n \"myOtherObject\": {\n \"myOtherInt\": 9001\n }\n}\n\n\nYou entered:\n{\n \"myInt\": 1337,\n \"myString\": \"stringy\",\n \"myOtherObject\": {\n \"myOtherInt\": 9001\n },\n \"myIntCollection\": [ 2, 4, 6 ]\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3233/"
] |
41,469 |
<p>I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality:</p>
<p>The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database.</p>
<p>Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.</p>
|
[
{
"answer_id": 41473,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 3,
"selected": false,
"text": "- Cataloguing home book collections\n- Building and verifying bookstores' inventories\n- Empowering forums and online communities with more useful book references\n- Automated cross-merchant price lookups over messaging devices or phones\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
41,479 |
<p>After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?</p>
<p>For example I rather lazily used var in questionable circumstances, e.g.:-</p>
<pre><code>foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
</code></pre>
<p>More legitimate uses of var are as follows:-</p>
<pre><code>var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
</code></pre>
<p>Interestingly LINQ seems to be a bit of a grey area, e.g.:-</p>
<pre><code>var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
</code></pre>
<p>It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.</p>
<p>It's even worse when it comes to LINQ to objects, e.g.:-</p>
<pre><code>var results = from item in someList
where item != 3
select item;
</code></pre>
<p>This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.</p>
<p>There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.</p>
<p><code>var</code> <em>does</em> maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.</p>
|
[
{
"answer_id": 41486,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "foreach (var c in list) { ... }\n foreach (var customer in list) { ... }\n var x = SaveFoo(foo);\n var saveSucceeded = SaveFoo(foo);\n var f = (float)3;\n"
},
{
"answer_id": 41487,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "IEnumerable<TypeReturnedBySelectObject>\n"
},
{
"answer_id": 41505,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 9,
"selected": true,
"text": "var var orders = cust.Orders;\n IEnumerable<Order> ObservableCollection<Order> BindingList<Order> ObservableCollection<Order> orders = cust.Orders;\n ObservableCollection<Order> IList<Order>"
},
{
"answer_id": 41514,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "var var var var var var var var var MyType"
},
{
"answer_id": 41519,
"author": "Frep D-Oronge",
"author_id": 3024,
"author_profile": "https://Stackoverflow.com/users/3024",
"pm_score": 4,
"selected": false,
"text": "var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!\n List<somethinglongtypename> v = new List<somethinglongtypename>();\n var v = new List<somethinglongtypename>();\n v = List<somethinglongtypename>();\n"
},
{
"answer_id": 41523,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 3,
"selected": false,
"text": "var int"
},
{
"answer_id": 41531,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<int> IEnumerable<double> var Var var anonEnumeration =\n from post in AllPosts()\n where post.Date > oldDate\n let author = GetAuthor( post.AuthorId )\n select new { \n PostName = post.Name, \n post.Date, \n AuthorName = author.Name\n };\n IEnumerable<'a> foreach( var item in anonEnumeration ) \n{\n //VS knows the type\n item.PostName; //you'll get intellisense here\n\n //you still have type safety\n item.ItemId; //will throw a compiler exception\n}\n var //less typing, this is good\nvar myList = new List<UnreasonablyLongClassName>();\n\n//also good - I can't be mistaken on type\nvar anotherList = GetAllOfSomeItem();\n\n//but not here - probably best to leave single value types declared\nvar decimalNum = 123.456m;\n"
},
{
"answer_id": 41532,
"author": "robi-y",
"author_id": 4388,
"author_profile": "https://Stackoverflow.com/users/4388",
"pm_score": 3,
"selected": false,
"text": "int i = 3; var i = 3;"
},
{
"answer_id": 41689,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 1,
"selected": false,
"text": "Employee emp = new Employee() any more obvious?\n var emp = GetEmployee();\n"
},
{
"answer_id": 67083,
"author": "AlanR",
"author_id": 7311,
"author_profile": "https://Stackoverflow.com/users/7311",
"pm_score": 1,
"selected": false,
"text": "foreach( var item in list ) { DoWork( item ); }\n foreach( KeyValuePair<string, double> entry in list ) { DoWork( Item ); }\n"
},
{
"answer_id": 78833,
"author": "Dexter",
"author_id": 10717,
"author_profile": "https://Stackoverflow.com/users/10717",
"pm_score": 5,
"selected": false,
"text": "var something = SomeMethod();\n var list = new List<KeyValuePair<string, double>>();\nFillList( list );\nforeach( var item in list ) {\n DoWork( item ); \n}\n"
},
{
"answer_id": 96490,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 6,
"selected": false,
"text": "var Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>(); var mylists = new Dictionary<string,List<int>>(); var var"
},
{
"answer_id": 105485,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 3,
"selected": false,
"text": "var var List<string> whatever = new List<string>();\n Dim whatever As List(Of String) = New List(Of String)\n Dim whatever As New List(Of String)\n IList<string> List<string> Dim whatever As IList(Of String) = New List(Of String)\n var IList<string> whatever = new List<string>();\n"
},
{
"answer_id": 133732,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 3,
"selected": false,
"text": "var var var"
},
{
"answer_id": 213704,
"author": "TimothyP",
"author_id": 28149,
"author_profile": "https://Stackoverflow.com/users/28149",
"pm_score": 1,
"selected": false,
"text": "var something = 5;\n something = \"hello\";\n LedDeviceController controller = new LedDeviceController(\"172.17.0.1\");\n var controller = new LedDeviceController(\"172.17.0.1\");\n"
},
{
"answer_id": 321277,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 0,
"selected": false,
"text": "var var i = 5;\nint j = 5;\n\nSomeType someType = new SomeType();\nvar someType = new SomeType();\n var"
},
{
"answer_id": 391590,
"author": "Rostov",
"author_id": 2108310,
"author_profile": "https://Stackoverflow.com/users/2108310",
"pm_score": 3,
"selected": false,
"text": "var people = Managers.People\n var fc = Factory.Run();\n"
},
{
"answer_id": 488436,
"author": "Christian Klauser",
"author_id": 55208,
"author_profile": "https://Stackoverflow.com/users/55208",
"pm_score": 2,
"selected": false,
"text": "var"
},
{
"answer_id": 498706,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 0,
"selected": false,
"text": "foreach (var s in stringArray)\n{\n\n}\n"
},
{
"answer_id": 792765,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 971919,
"author": "mqp",
"author_id": 55943,
"author_profile": "https://Stackoverflow.com/users/55943",
"pm_score": 3,
"selected": false,
"text": "var var index = 5; // this is supposed to be bad\n\nvar firstEligibleObject = FetchSomething(); // oh no what type is it\n // i am going to die if i don't know\n"
},
{
"answer_id": 971934,
"author": "Colin Desmond",
"author_id": 93399,
"author_profile": "https://Stackoverflow.com/users/93399",
"pm_score": 4,
"selected": false,
"text": "IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();\n var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();\n"
},
{
"answer_id": 971943,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "var Dictionary<string, Dictionary<string, List<MyNewType>>> collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();\n var collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();\n var var var value= 5;\n 5 double value = 5;\n"
},
{
"answer_id": 971949,
"author": "Richard",
"author_id": 67392,
"author_profile": "https://Stackoverflow.com/users/67392",
"pm_score": 3,
"selected": false,
"text": "var content = new Queue<Pair<Regex, Func<string, bool>>>();\n...\nforeach (var entry in content) { ... }\n var var"
},
{
"answer_id": 971967,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 3,
"selected": false,
"text": "var something = myObject.SomeProperty.SomeOtherThing.CallMethod();\nConsole.WriteLine(something);\n var something = myObject.SomeProperty.SomeOtherThing.CallMethod();\n var something = myObject.SomeProperty.SomeOtherThing;\n"
},
{
"answer_id": 972071,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 2,
"selected": false,
"text": "var var var nullable<> int decimal string decimal? var"
},
{
"answer_id": 1031291,
"author": "Jamie Eisenhart",
"author_id": 19533,
"author_profile": "https://Stackoverflow.com/users/19533",
"pm_score": 0,
"selected": false,
"text": "List<string> list = new List<string> { \"LINQ\", \"query\", \"adventure\" };\nvar query = from string word in list\n where word.Contains(\"r\")\n orderby word ascending\n select word;\n"
},
{
"answer_id": 1298237,
"author": "ShdNx",
"author_id": 128240,
"author_profile": "https://Stackoverflow.com/users/128240",
"pm_score": 3,
"selected": false,
"text": "var sb = new StringBuilder();\n StringBuilder sb = new StringBuilder();\n var stuff = new { Name = \"Me\", Age = 20 };\n"
},
{
"answer_id": 1298268,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();\n var data = new Dictionary<string, List<SomeComplexType<int>>>();\n var static void DoSomething(IFoo foo) {Console.WriteLine(\"working happily\") }\nstatic void DoSomething(Foo foo) {Console.WriteLine(\"formatting hard disk...\");}\n\n// this working code...\nIFoo oldCode = new Foo();\nDoSomething(oldCode);\n// ...is **very** different to this code\nvar newCode = new Foo();\nDoSomething(newCode);\n"
},
{
"answer_id": 1298283,
"author": "MartinStettner",
"author_id": 81424,
"author_profile": "https://Stackoverflow.com/users/81424",
"pm_score": 3,
"selected": false,
"text": "var ...\nList<MyClass> SomeMethod() { ... }\n...\n ...\nIList<MyClass> list = obj.SomeMethod();\nforeach (MyClass c in list)\n System.Console.WriteLine(c.ToString());\n...\n SomeMethod() IEnumerable<MySecondClass> foreach ...\nvar list = obj.SomeMethod();\nforeach (var element in list)\n System.Console.WriteLine(element.ToString());\n...\n"
},
{
"answer_id": 1298706,
"author": "saret",
"author_id": 155438,
"author_profile": "https://Stackoverflow.com/users/155438",
"pm_score": 1,
"selected": false,
"text": "Func<Person, bool> predicate = (i) => i.Id < 10;\nIEnumerable<Person> result = table.Where(predicate);\n var predicate = (Person i) => i.Id < 10;\nvar result = table.Where(predicate);\n"
},
{
"answer_id": 1724070,
"author": "David_001",
"author_id": 209578,
"author_profile": "https://Stackoverflow.com/users/209578",
"pm_score": 2,
"selected": false,
"text": "var customers = new List<Customer>(); var customers = dataAccess.GetCustomers(); IList<Customer> customers = dataAccess.GetCustomers();\n\nvar dummyCustomer = new Customer();\ncustomers.Add(dummyCustomer);\n var customers = dataAccess.GetCustomers();\n\nvar dummyCustomer = new Customer();\ncustomers.Add(dummyCustomer);\n IEnumerable<Customer>"
},
{
"answer_id": 2427596,
"author": "Wray Smallwood",
"author_id": 291765,
"author_profile": "https://Stackoverflow.com/users/291765",
"pm_score": 3,
"selected": false,
"text": "var StringBuilder sb = new StringBuilder();\n var sb = new StringBuilder();\n"
},
{
"answer_id": 2746399,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "var foreach foreach (Derived d in listOfBase)\n{\n Base Derived Derived var"
},
{
"answer_id": 2866052,
"author": "Jeff Sternal",
"author_id": 47886,
"author_profile": "https://Stackoverflow.com/users/47886",
"pm_score": 1,
"selected": false,
"text": "vars // If you change ItemLibrary to use int, you need to update this call\nbyte totalItemCount = ItemLibrary.GetItemCount();\n\n// If GetItemCount changes, I don't have to update this statement.\nvar totalItemCount = ItemLibrary.GetItemCount();\n"
},
{
"answer_id": 2866054,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "CallMe var variable = CallMe();\n Func var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {\n ...\n});\n"
},
{
"answer_id": 2866064,
"author": "Adam Robinson",
"author_id": 82187,
"author_profile": "https://Stackoverflow.com/users/82187",
"pm_score": 7,
"selected": false,
"text": "var var var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating() var"
},
{
"answer_id": 2866065,
"author": "andypaxo",
"author_id": 46575,
"author_profile": "https://Stackoverflow.com/users/46575",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 2866075,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 7,
"selected": false,
"text": "List<T> IEnumerable<T>"
},
{
"answer_id": 2866077,
"author": "Randolpho",
"author_id": 12716,
"author_profile": "https://Stackoverflow.com/users/12716",
"pm_score": 1,
"selected": false,
"text": "var var var var var var var var"
},
{
"answer_id": 2866080,
"author": "Guffa",
"author_id": 69083,
"author_profile": "https://Stackoverflow.com/users/69083",
"pm_score": 4,
"selected": false,
"text": "var var var"
},
{
"answer_id": 2866088,
"author": "Andrey",
"author_id": 283676,
"author_profile": "https://Stackoverflow.com/users/283676",
"pm_score": 0,
"selected": false,
"text": "var dynamic var"
},
{
"answer_id": 2866094,
"author": "kastermester",
"author_id": 40240,
"author_profile": "https://Stackoverflow.com/users/40240",
"pm_score": 2,
"selected": false,
"text": "List<string> var list = new List<string>();\n IList<string>"
},
{
"answer_id": 2866100,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": false,
"text": "int IEnumerable<MyStupidLongNamedGenericClass<int, string>>"
},
{
"answer_id": 2866236,
"author": "Christian Specht",
"author_id": 6884,
"author_profile": "https://Stackoverflow.com/users/6884",
"pm_score": 3,
"selected": false,
"text": "var x = new MyClass();\n var x = MyClass.MyFunction();\n var x = 5;\n"
},
{
"answer_id": 2866354,
"author": "Christopher Barber",
"author_id": 334526,
"author_profile": "https://Stackoverflow.com/users/334526",
"pm_score": 2,
"selected": false,
"text": "var x = getFoo(); // Originally declared to return Object\nx = getNonFoo();\n"
},
{
"answer_id": 2866857,
"author": "Will Marcouiller",
"author_id": 162167,
"author_profile": "https://Stackoverflow.com/users/162167",
"pm_score": 2,
"selected": false,
"text": "var anonymous types var var public object SomeObject { get; set; }\n public object SomeObject {\n get {\n return _someObject;\n } \n set {\n _someObject = value;\n }\n}\nprivate object _someObject;\n var"
},
{
"answer_id": 2867274,
"author": "Jerry Liu",
"author_id": 240951,
"author_profile": "https://Stackoverflow.com/users/240951",
"pm_score": 0,
"selected": false,
"text": "var var city = new City()"
},
{
"answer_id": 3367011,
"author": "Glenn Doten",
"author_id": 277774,
"author_profile": "https://Stackoverflow.com/users/277774",
"pm_score": -1,
"selected": false,
"text": "var iCounter = 0;"
},
{
"answer_id": 3466472,
"author": "user418243",
"author_id": 418243,
"author_profile": "https://Stackoverflow.com/users/418243",
"pm_score": 1,
"selected": false,
"text": "var something = new StringBuilder(); \n StringBuilder something = KEY'TAB'();\n"
},
{
"answer_id": 4013498,
"author": "David Mårtensson",
"author_id": 479137,
"author_profile": "https://Stackoverflow.com/users/479137",
"pm_score": 2,
"selected": false,
"text": "var var var"
},
{
"answer_id": 8294143,
"author": "Muhammad Atif Agha",
"author_id": 727794,
"author_profile": "https://Stackoverflow.com/users/727794",
"pm_score": 0,
"selected": false,
"text": "var z = 100;\n var s = \"Hello\";\n var a = new[] { 0, 1, 2 };\n var expr =\n from c in customers\n where c.City == \"London\"\n select c;\n var anon = new { Name = \"Terry\", Age = 34 };\n var list = new List<int>();\n\nvar can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
41,492 |
<p>Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!</p>
<p><strong>/EDIT:</strong> Without having source to the object itself</p>
|
[
{
"answer_id": 41612,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "Attribute Value.VB_UserMemId = 0\n"
},
{
"answer_id": 54239,
"author": "John T",
"author_id": 5553,
"author_profile": "https://Stackoverflow.com/users/5553",
"pm_score": 1,
"selected": false,
"text": "debug.print \"Value for cmdTest is [\"+format(cmdTest)+\"]\"\n debug.print \"cmdTest's value is of type [\"+TypeName(oObject) +\"]\"\n"
},
{
"answer_id": 2478693,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 2,
"selected": true,
"text": "[id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)]\nvoid Value([in] VARIANT_BOOL rhs);\n[id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)]\nVARIANT_BOOL Value();\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] |
41,498 |
<p>We recently lost a database and I want to recover the data from de Production.log.</p>
<p>Every request is logged like this:</p>
<p>Processing ChamadosController#create (for XXX.XXX.XXX.40 at 2008-07-30 11:07:30) [POST]
Session ID: 74c865cefa0fdd96b4e4422497b828f9
Parameters: {"commit"=>"Gravar", "action"=>"create", "funcionario"=>"6" ... (all other parameters go here).</p>
<p>But some stuff to post on de database were in the session. In the request I have the Session ID, and I also have all the session files from the server.</p>
<p>Is there anyway I can, from this Session ID, open de session file and get it's contents?</p>
|
[
{
"answer_id": 7872075,
"author": "parasew",
"author_id": 298982,
"author_profile": "https://Stackoverflow.com/users/298982",
"pm_score": 2,
"selected": false,
"text": "file = File.open(\"location_of_your_production.log\", \"rb\")\ncontents = file.read\ncontents.scan(/(Started POST \\\"(.*?)\\\" for (.*?) at (.*?)\\n.*?Parameters: \\{(.*?)\\}\\n.*?Completed (.*?) in (.*?)ms)/m).each do |x|\n # now you can collect all the important data.\n # do the same for GET requests as well, if you need it.\nend\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4384/"
] |
41,499 |
<p>In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, <code>static int MYINT = 3;</code> causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, <code>static String MYSTRING = System.getProperty("foo");</code> also causes the serialVersionUID to change.</p>
<p>To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.</p>
|
[
{
"answer_id": 41515,
"author": "Alfred B. Thordarson",
"author_id": 3379,
"author_profile": "https://Stackoverflow.com/users/3379",
"pm_score": 0,
"selected": false,
"text": "serialVersionUID static int MYINT = 3 MYINT = 3 serialVersionUID serialVersionUID private static final long serialVersionUID = 7526472295622776147L;\n"
},
{
"answer_id": 41527,
"author": "David G",
"author_id": 3150,
"author_profile": "https://Stackoverflow.com/users/3150",
"pm_score": 0,
"selected": false,
"text": "serialVersionUID serialVersionUID"
},
{
"answer_id": 42674,
"author": "Damien B",
"author_id": 3069,
"author_profile": "https://Stackoverflow.com/users/3069",
"pm_score": 4,
"selected": true,
"text": "static System.getProperty() static System System serialVersionUID serialVersionUID"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150/"
] |
41,513 |
<p>I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?</p>
|
[
{
"answer_id": 41524,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 4,
"selected": false,
"text": "/project\n /trunk\n /src\n /doc\n /...\n /branches\n /feature1\n /src\n /doc\n /...\n /feature2\n /src\n /doc\n /...\n"
},
{
"answer_id": 41539,
"author": "ryan",
"author_id": 2454,
"author_profile": "https://Stackoverflow.com/users/2454",
"pm_score": 0,
"selected": false,
"text": "WebAppName\\\n \\lib\n \\src\n \\tests\n etc...\n \\svn\\trunk\\WebAppNameProject\n \\WebAppNameSource\n \\lib\n \\src\n \\tests\n etc...\n \\Documentation \n"
},
{
"answer_id": 41571,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "web test src resources"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
41,525 |
<p>If not, what are the significant differences?</p>
<hr>
<p><strong>Edit:</strong> Daren Thomas asks:</p>
<blockquote>
<p>which ones?</p>
<p>I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...</p>
</blockquote>
<p>By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.</p>
|
[
{
"answer_id": 41529,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "gvim MacVim"
},
{
"answer_id": 41545,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "~/vim.rc %HOME%\\vim_rc C:\\Program Files\\vim\\... ~/.vim/..."
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
41,547 |
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p>
<p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p>
<p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
|
[
{
"answer_id": 41555,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "request.user authenticate() login() locals() request request.user"
},
{
"answer_id": 269249,
"author": "zalun",
"author_id": 23457,
"author_profile": "https://Stackoverflow.com/users/23457",
"pm_score": 5,
"selected": false,
"text": "TEMPLATE_CONTEXT_PROCESSORS = (\n 'myapp.processor_file_name.user',\n)\n def user(request):\n if hasattr(request, 'user'):\n return {'user':request.user }\n return {}\n {{ user.get_full_name }}\n"
},
{
"answer_id": 1064621,
"author": "Daniel",
"author_id": 50841,
"author_profile": "https://Stackoverflow.com/users/50841",
"pm_score": 6,
"selected": false,
"text": "\"django.core.context_processors.auth\" TEMPLATE_CONTEXT_PROCESSORS RequestContext django.contrib.auth.context_processors.auth"
},
{
"answer_id": 4815619,
"author": "Anto Binish Kaspar",
"author_id": 592065,
"author_profile": "https://Stackoverflow.com/users/592065",
"pm_score": 1,
"selected": false,
"text": "TEMPLATE_CONTEXT_PROCESSORS = (\n'django.core.context_processors.request',\n'django.contrib.auth.context_processors.auth',\n'django.core.context_processors.auth',)\n {% if user.is_authenticated %}\n<p>Welcome, {{ user.username }}. Thanks for logging in.</p>\n{% else %}\n <p>Welcome, new user. Please log in.</p>\n{% endif %}\n"
},
{
"answer_id": 11878636,
"author": "iutinvg",
"author_id": 444966,
"author_profile": "https://Stackoverflow.com/users/444966",
"pm_score": 2,
"selected": false,
"text": "views.py from django.template import RequestContext\n...\ndef index(request):\n return render_to_response('index.html', \n {'var': 'value'},\n context_instance=RequestContext(request))\n index.html ...\nHi, {{ user.username }}\nvar: {{ value }}\n... \n"
},
{
"answer_id": 58683713,
"author": "synkc",
"author_id": 11078019,
"author_profile": "https://Stackoverflow.com/users/11078019",
"pm_score": 0,
"selected": false,
"text": "'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'myapp.functions.test'\n ],\n},\n def test(request):\n return {'misc': 'misc'}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] |
41,561 |
<p>I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...</p>
|
[
{
"answer_id": 43226,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 4,
"selected": false,
"text": "<bar xmlns:foo=\"http://www.foo.com/\"\n foo:baz=\"baz\"\n qux=\"qux\"/>\n<bar xmlns=\"http://www.foo.com/\" xmlns:foo=\"http://www.foo.com/\"\n foo:baz=\"baz\"\n qux=\"qux\"/>\n<foo:bar xmlns=\"http://www.foo.com/\" xmlns:foo=\"http://www.foo.com/\"\n foo:baz=\"baz\"\n qux=\"qux\"/>\n <{}bar\n {http://www.foo.com/}baz=\"baz\"\n {}qux=\"qux\"/>\n<{http://www.foo.com/}bar\n {http://www.foo.com/}baz=\"baz\"\n {}qux=\"qux\"/>\n<{http://www.foo.com/}bar\n {http://www.foo.com/}baz=\"baz\"\n {}qux=\"qux\"/>\n"
},
{
"answer_id": 46865,
"author": "Bart Schuller",
"author_id": 4711,
"author_profile": "https://Stackoverflow.com/users/4711",
"pm_score": 6,
"selected": false,
"text": "<schema attributeFormDefault=\"qualified\">"
},
{
"answer_id": 235551,
"author": "Diego Tercero",
"author_id": 2046272,
"author_profile": "https://Stackoverflow.com/users/2046272",
"pm_score": 4,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xs:schema xmlns=\"http://schemas.mycompany.com/Customer/V1\" \ntargetNamespace=\"http://schemas.mycompany.com/Customer/V1\" \nxmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:attribute name=\"Id\" type=\"xs:positiveInteger\"/>\n <xs:element name=\"Customer\">\n <xs:complexType>\n <xs:attribute ref=\"Id\" use=\"required\"/>\n <!-- some elements here -->\n </xs:complexType>\n</xs:element>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Customer Id=\"1\" xmlns=\"http://schemas.mycompany.com/Customer/V1\">\n <!-- ... other elements here -->\n</Customer>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Customer cus:Id=\"1\" xmlns=\"http://schemas.mycompany.com/Customer/V1\"\n xmlns:cus=\"http://schemas.mycompany.com/Customer/V1\">\n <!-- ... other elements here -->\n</Customer>\n <xs:element name=\"Customer\">\n <xs:complexType>\n <xs:attribute name=\"Id\" type=\"xs:positiveInteger\" use=\"required\"/>\n <!-- some elements here -->\n </xs:complexType>\n</xs:element>\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4315/"
] |
41,568 |
<p>this kind of follows on from another <a href="https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app">question</a> of mine.</p>
<p>Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to <strong>test</strong> it?</p>
<p>I am thinking of creating a method which just spawns lots of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a>'s or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc.</p>
<p>Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :)</p>
<h3>Edit</h3>
<p>Following <a href="https://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572">ajmastrean's</a> post:</p>
<p>I am using a console app to test with Debug.Asserts :)</p>
<hr />
<h2>Update</h2>
<p>I originally rolled with using <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a> to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this.</p>
<p>I then followed up on <a href="https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads#41589">ajmastrean</a>'s post and realised I should really be using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread(VS.80).aspx" rel="noreferrer">Thread</a> class for working with concurrent operations. I will now refactor using this method (albeit a different approach).</p>
|
[
{
"answer_id": 41589,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 5,
"selected": true,
"text": "ThreadPool ManualResetEvent AutoResetEvent ThreadStart public static void MultiThreadedTest()\n{\n Thread[] threads = new Thread[count];\n\n for (int i = 0; i < threads.Length; i++)\n {\n threads[i] = new Thread(DoSomeWork());\n }\n\n foreach(Thread thread in threads)\n {\n thread.Start();\n }\n\n foreach(Thread thread in threads)\n {\n thread.Join();\n }\n}\n"
},
{
"answer_id": 41619,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "ThreadPool.QueueUserWorkItem ThreadPool.QueueUserWorkItem(x => { \n File.Open(fileName, FileMode.Open);\n event1.Set(); // Start 2nd tread;\n event2.WaitOne(); // Blocking the file;\n});\nThreadPool.QueueUserWorkItem(x => { \n try\n {\n event1.WaitOne(); // Waiting until 1st thread open file\n File.Delete(fileName); // Simulating conflict\n }\n catch (IOException e)\n {\n Debug.Write(\"File access denied\");\n }\n});\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
41,590 |
<p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p>
<p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p>
|
[
{
"answer_id": 41598,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 8,
"selected": true,
"text": "namespace MyNamespace\n{\n class MyClass\n {\n };\n}\n MyNamespace::MyClass* pClass = new MyNamespace::MyClass();\n using namespace MyNamespace;\n\nMyClass* pClass = new MyClass();\n"
},
{
"answer_id": 41620,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 3,
"selected": false,
"text": "using namespace boost; \nusing namespace std; \n\nshared_ptr<int> p(new int(1)); // shared_ptr belongs to boost \ncout << \"cout belongs to std::\" << endl; // cout and endl are in std\n"
},
{
"answer_id": 41622,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 4,
"selected": false,
"text": "package somepackage;\nclass SomeClass {}\n namespace somenamespace {\n class SomeClass {}\n}\n import somepackage;\n using namespace somenamespace;\n"
},
{
"answer_id": 41624,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 7,
"selected": false,
"text": "using std::cout; \nusing std::endl;\n"
},
{
"answer_id": 41637,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 4,
"selected": false,
"text": "namespace MyNamespace\n{\n double square(double x) { return x * x; }\n}\n square.h namespace MyNamespace\n{\n double cube(double x) { return x * x * x; }\n}\n cube.h MyNamespace"
},
{
"answer_id": 41823,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 2,
"selected": false,
"text": "#include \"lib/module1.h\"\n#include \"lib/module2.h\"\n\nlib::class1 *v = new lib::class1();\n"
},
{
"answer_id": 41860,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "void test(const std::string& s) {\n using namespace std;\n cout << s;\n}\n"
},
{
"answer_id": 47976,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "namespace {\n const int CONSTANT = 42;\n}\n static const int CONSTANT = 42;\n"
},
{
"answer_id": 48008,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 6,
"selected": false,
"text": "namespace ns {\n\nclass A\n{\n};\n\nvoid print(A a)\n{\n}\n\n}\n ns::A a;\nprint(a);\n namespace ns {\n\nclass A\n{\n};\n\n}\n\nvoid print(A a)\n{\n}\n"
},
{
"answer_id": 81602,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 6,
"selected": false,
"text": "void doSomething()\n{\n using std::string ; // string is now \"imported\", at least,\n // until the end of the function\n string a(\"Hello World!\") ;\n std::cout << a << std::endl ;\n}\n\nvoid doSomethingElse()\n{\n using namespace std ; // everything from std is now \"imported\", at least,\n // until the end of the function\n string a(\"Hello World!\") ;\n cout << a << endl ;\n}\n namespace AAA\n{\n void doSomething() ;\n}\n\nnamespace BBB\n{\n void doSomethingElse() ;\n}\n\nnamespace CCC\n{\n using namespace AAA ;\n using namespace BBB ;\n}\n\nvoid doSomethingAgain()\n{\n CCC::doSomething() ;\n CCC::doSomethingElse() ;\n}\n"
},
{
"answer_id": 1600792,
"author": "Éric Malenfant",
"author_id": 59781,
"author_profile": "https://Stackoverflow.com/users/59781",
"pm_score": 6,
"selected": false,
"text": "Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;\nSome::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;\n namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;\nShorter::TheClassName foo;\nShorter::AnotherClassName bar;\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] |
41,594 |
<p>I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on <a href="http://www.plus2net.com/sql_tutorial/access_to_mysql.php" rel="nofollow noreferrer">this site</a>
and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt.</p>
<p>The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field.</p>
<p>Has anyone had this issue before and how did they resolve it ?</p>
|
[
{
"answer_id": 41985,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 3,
"selected": true,
"text": " Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap\n Dim oImage As Bitmap = New Bitmap(\"c:\\default.jpg\")\n Try\n If Not IsDBNull(row(columnName)) Then\n If row(columnName) IsNot Nothing Then\n Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte()))\n If mStream.Length > 0 Then\n\n Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte\n mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1))\n\n Dim position As Integer = 0\n\n For index As Integer = 0 To b.Length - 3\n If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then\n position = index\n Exit For\n End If\n Next\n\n If position > 0 Then\n Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position)\n oImage = New Bitmap(jpgStream)\n End If\n End If\n End If\n End If\n Catch ex As Exception\n Throw New ApplicationException(ex.Message, ex)\n End Try\n Return oImage\nEnd Function\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2720/"
] |
41,630 |
<p>I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.</p>
<p>I know that's possible by using keyword <em>system</em> like that :</p>
<pre><code>#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory
</code></pre>
<p>but is that possible by using the "backquotes or backticks syntax" ?
(I mean by using that syntax : <code>ls</code>)</p>
|
[
{
"answer_id": 41635,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": true,
"text": "ls directory #!/usr/bin/env ruby\ndirectory = '/home/paulgreg/'\n`ls #{directory}`\n"
},
{
"answer_id": 41892,
"author": "Nick Brosnahan",
"author_id": 528,
"author_profile": "https://Stackoverflow.com/users/528",
"pm_score": 3,
"selected": false,
"text": "`ls #{directory}` \n directory = '/home/paulgreg/'\n\nargs = []\nargs << \"/bin/ls\"\nargs << directory\n\nsystem(*args)\n"
},
{
"answer_id": 71636,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 1,
"selected": false,
"text": "directory = '/Volumes/Omg a space/'\nsystem('/bin/ls', directory)\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] |
41,638 |
<p>The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!</p>
<p>The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!</p>
<p>We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).</p>
<p>Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object <strong>Person</strong> will be mapped to say <strong>PersonDTO</strong>. I do not want to do this manually since it is a waste.</p>
<p>Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that <em>"cooler"</em> will be suggested.</p>
<p>Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.</p>
<hr>
<h2>Example code:</h2>
<p>By @ajmastrean's request I have <a href="http://www.fryhard.com/downloads/stackoverflow/ActiveRecordAsync.zip" rel="noreferrer">linked</a> to an example that I have (badly) mocked together. The example has a <strong>capture form</strong>, capture form <strong>controller</strong>, <strong>domain</strong> objects, activerecord <strong>repository</strong> and an <strong>async</strong> helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called <em>ActiveRecordAsync</em> on your local machine or just change the .config file.</p>
<p>Basic details of example:</p>
<p><strong>The Capture Form</strong></p>
<p>The capture form has a reference to the contoller</p>
<pre><code>private CompanyCaptureController MyController { get; set; }
</code></pre>
<p>On initialise of the form it calls MyController.Load()
private void InitForm ()
{
MyController = new CompanyCaptureController(this);
MyController.Load();
}
This will return back to a method called LoadComplete()</p>
<pre><code>public void LoadCompleted (Company loadCompany)
{
_context.Post(delegate
{
CurrentItem = loadCompany;
bindingSource.DataSource = CurrentItem;
bindingSource.ResetCurrentItem();
//TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone.
grdEmployees.DataSource = loadCompany.Employees;
}, null);
}
}
</code></pre>
<p>this is where the <em>"bad stuff"</em> occurs, since we are using the child list of Company that is set as Lazy load.</p>
<p><strong>The Controller</strong></p>
<p>The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.</p>
<pre><code>public void Load ()
{
new AsyncListLoad<Company>().BeginLoad(LoadCompany, Form.LoadCompleted);
}
</code></pre>
<p>The LoadCompany() method simply makes use of the Repository to find a know company.</p>
<pre><code>public Company LoadCompany()
{
return ActiveRecordRepository<Company>.Find(Setup.company.Identifier);
}
</code></pre>
<p>The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the <strong>ActiveRecordMediator</strong> abilities.</p>
|
[
{
"answer_id": 169708,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 3,
"selected": false,
"text": "public static T ChangeType<S, T>(this S source) where T : class, new()\n public static T ChangeType<S, T>(this S source, Action<S, T> additionalOperations) where T : class, new()\n Person p = new Person( /* set whatever */);\nPersonDTO = p.ChangeType<Person, PersonDTO>();\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] |
41,640 |
<p>I am in need of a way to mute a specific application in Vista.</p>
<p>Example: Mute just Firefox, but not all of the other application. Much similar to muting a specific program from within the volume mixer in vista. </p>
<p>If there is a program that will do this, i would appreciate that. Otherwise if there is a way to do this, I will write a small app(Preferrably something .net).</p>
<p>EDIT: I want to automate this procedure, possibly key-map it.</p>
|
[
{
"answer_id": 29990633,
"author": "Devin",
"author_id": 4854726,
"author_profile": "https://Stackoverflow.com/users/4854726",
"pm_score": 0,
"selected": false,
"text": "#NoEnv ;// Recommended for new scripts\n#Persistent ;// Recommended for new scripts\nSendMode Input ;// Recommended for new scripts\nSetTitleMatchMode 2\n\n;// Set VolumeMute to only silence Media Center\n$f3::\n MuteMediaCenter()\n return\n\nMuteMediaCenter()\n{ \n ;// Open mixer\n Run sndvol \n WinWait Volume Mixer\n ;// Mute Standard Media Center Process\n appName = Chrome\n MuteApp(appName)\n ;// Mute Netflix Media Center Process\n appName = Firefox\n MuteApp(appName)\n WinClose Volume Mixer\n}\n\n;// Volume Mixer must exist\nMuteApp(appName) \n{\n ;// Find X position & width of textblock with text matching our appName\n ControlGetPos, refX, , refW, , % appName, Volume Mixer\n ;// Find button with left side within the width of the textblock\n x = -1\n while ( x != \"\") \n {\n ;// A_Index is current loop iteration→used to find id\n tbIDX := (A_Index * 2) \n ControlGetPos, x, , , , ToolbarWindow32%tbIDX%, Volume Mixer\n diff := x - refX\n if (diff > 0 && diff < refW)\n {\n ;// msgbox diff: %diff% refX: %refX% tbIDX: %tbIDX% x: %x% A_Index: %A_Index%\n ControlClick, ToolbarWindow32%tbIDX%, Volume Mixer\n break\n }\n }\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4394/"
] |
41,647 |
<p>When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. </p>
<p>At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (<strong>link no longer working</strong>) <a href="http://driveefficiently.com/testinclude.php" rel="noreferrer">http://driveefficiently.com/testinclude.php</a> this file consists of only: </p>
<pre><code><? include("include.inc"); ?>
</code></pre>
<p>and include.inc consists of only: </p>
<pre><code><? echo ("hello, world"); ?>
</code></pre>
<p>and yet, the output is: <em>"?hello, world"</em> where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. </p>
<p>Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.</p>
|
[
{
"answer_id": 41655,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 0,
"selected": false,
"text": "hello, world"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] |
41,652 |
<p>We have got a custom <code>MembershipProvider</code> in <code>ASP.NET</code>. Now there are 2 possible scenario the user can be validated:</p>
<ol>
<li><p>User login via <code>login.aspx</code> page by entering his username/password. I have used <strong>Login control</strong> and linked it with the <code>MyMembershipProvider</code>. This is working perfectly fine.</p></li>
<li><p>An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in <code>MembershipProvider.Validate(string authenticationToken)</code>, which is actually validating the user. In this case we cannot use the <strong>Login control</strong>. Now how can I use the same <code>MembershipProvider</code> to validate the user without actually using the <strong>Login control</strong>? I tried to call <code>Validate</code> manually, but this is not signing the user in.</p></li>
</ol>
<p>Here is the code snippet I am using </p>
<pre><code>if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) {
string ticket = Request.QueryString["authenticationToken"];
MyMembershipProvider provider = Membership.Provider as MyMembershipProvider;
if (provider != null) {
if (provider.ValidateUser(ticket))
// Login Success
else
// Login Fail
}
}
</code></pre>
|
[
{
"answer_id": 42151,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 2,
"selected": false,
"text": "FormsAuthenticationTicket if (provider != null) {\n if (provider.ValidateUser(ticket)) {\n // Login Success\n FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(\n 1, //version\n someUserName, //name\n DateTime.Now, //issue date\n DateTime.Now.AddMinutes(lengthOfSession), //expiration\n false, // persistence of login\n FormsAuthentication.FormsCookiePath\n );\n\n //encrypt the ticket\n string hash = FormsAuthentication.Encrypt(authTicket);\n HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);\n\n Response.Cookies.Add(cookie);\n Response.Redirect(url where you want the user to land);\n } else {\n // Login Fail \n } \n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
41,659 |
<p>Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container?</p>
<p>For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, </p>
<ol>
<li>a properties file in the classpath,</li>
<li>a web.xml parameter, </li>
<li>a system property, or </li>
<li>some default logic if nothing else is available. </li>
</ol>
<p>I'd like to be able to do this without injecting any reference to <code>ServletConfig</code> or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container.</p>
<p>This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml.</p>
<p>If I recall correctly, .NET has something like <code>Request.GetCurrentRequest()</code> to get a reference to the currently executing <code>Request</code> - but since this is a Java app I'm looking for something simliar that could be used to gain access to <code>ServletConfig</code>.</p>
|
[
{
"answer_id": 41814,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": true,
"text": "public class FactoryInitialisingServletContextListener implements ServletContextListener {\n\n public void contextDestroyed(ServletContextEvent event) {\n }\n\n public void contextInitialized(ServletContextEvent event) {\n Properties properties = new Properties();\n ServletContext servletContext = event.getServletContext();\n Enumeration<?> keys = servletContext.getInitParameterNames();\n while (keys.hasMoreElements()) {\n String key = (String) keys.nextElement();\n String value = servletContext.getInitParameter(key);\n properties.setProperty(key, value);\n }\n Factory.setServletContextProperties(properties);\n }\n}\n\npublic class Factory {\n\n static Properties _servletContextProperties = new Properties();\n\n public static void setServletContextProperties(Properties servletContextProperties) {\n _servletContextProperties = servletContextProperties;\n }\n}\n <listener>\n <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>\n</listener>\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
41,665 |
<p>Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?</p>
|
[
{
"answer_id": 41672,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;\n Bitmap.CompositingQuality = CompositingQuality.HighQuality;\n"
},
{
"answer_id": 41684,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 7,
"selected": true,
"text": "var qualityEncoder = Encoder.Quality;\nvar quality = (long)<desired quality>;\nvar ratio = new EncoderParameter(qualityEncoder, quality );\nvar codecParams = new EncoderParameters(1);\ncodecParams.Param[0] = ratio;\nvar jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = \"image/jpeg\">;\nbmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG\n"
},
{
"answer_id": 2412375,
"author": "jestro",
"author_id": 417811,
"author_profile": "https://Stackoverflow.com/users/417811",
"pm_score": 5,
"selected": false,
"text": "public static class BitmapExtensions\n{\n public static void SaveJPG100(this Bitmap bmp, string filename)\n { \n EncoderParameters encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);\n bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n public static void SaveJPG100(this Bitmap bmp, Stream stream)\n {\n EncoderParameters encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);\n bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n public static ImageCodecInfo GetEncoder(ImageFormat format)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();\n\n foreach (ImageCodecInfo codec in codecs)\n {\n if (codec.FormatID == format.Guid)\n {\n return codec;\n }\n }\n\n return null;\n }\n}\n"
},
{
"answer_id": 8703634,
"author": "net_prog",
"author_id": 355264,
"author_profile": "https://Stackoverflow.com/users/355264",
"pm_score": 4,
"selected": false,
"text": "public static class ImageExtensions\n{\n public static void SaveJpeg(this Image img, string filePath, long quality)\n {\n var encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);\n img.Save(filePath, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n public static void SaveJpeg(this Image img, Stream stream, long quality)\n {\n var encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);\n img.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n static ImageCodecInfo GetEncoder(ImageFormat format)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();\n return codecs.Single(codec => codec.FormatID == format.Guid);\n }\n}\n"
},
{
"answer_id": 32166157,
"author": "Jeff R",
"author_id": 4161426,
"author_profile": "https://Stackoverflow.com/users/4161426",
"pm_score": 1,
"selected": false,
"text": "Bitmap finalBitmap = ....; //from disk or whatever\nfinalBitmap.Save(xpsFileName + \".final.jpg\", ImageFormat.Jpeg);\nfinalBitmap.Save(xpsFileName + \".final.png\", ImageFormat.Png);\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
41,674 |
<p>In Visual Studio you can create a template XML document from an existing schema. The new <a href="http://msdn.microsoft.com/en-us/library/cc716766.aspx" rel="noreferrer">XML Schema Explorer</a> in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the <a href="http://msdn.microsoft.com/en-us/library/aa302296.aspx" rel="noreferrer">XmlSampleGenerator</a> article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?</p>
|
[
{
"answer_id": 245461,
"author": "Andrew Theken",
"author_id": 32238,
"author_profile": "https://Stackoverflow.com/users/32238",
"pm_score": 3,
"selected": false,
"text": "DataSet ds = new DataSet();\nds.ReadXmlSchema(\"c:/xsdfile.xsd\");\n\nforeach(DataTable t in ds.Tables)\n{\nvar row = t.NewRow();\nt.Rows.Add(row);\n}\n\nds.WriteXml(\"c:/example.xml\");\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3873/"
] |
41,686 |
<p>I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code:</p>
<p>Servlet</p>
<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String customerPath = "\\leetest\\";
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (item.isFormField()) {
// Form field. Ignore for now
} else {
BufferedInputStream stream = new BufferedInputStream(item
.openStream());
if (stream == null) {
LOGGER
.error("Something went wrong with fetching the stream for field "
+ name);
}
byte[] bytes = StreamUtils.getBytes(stream);
FileManager.createFile(customerPath, item.getName(), bytes);
stream.close();
}
}
}
} catch (Exception e) {
throw new UploadException("An error occured during upload: "
+ e.getMessage());
}
}
</code></pre>
<p>StreamUtils.getBytes(stream) looks like:</p>
<pre><code>public static byte[] getBytes(InputStream src, int buffsize)
throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buff = new byte[buffsize];
while (true) {
int nBytesRead = src.read(buff);
if (nBytesRead < 0) {
break;
}
byteStream.write(buff);
}
byte[] result = byteStream.toByteArray();
byteStream.close();
return result;
}
</code></pre>
<p>And finally FileManager.createFile looks like:</p>
<pre><code>public static void createFile(String customerPath, String filename,
byte[] fileData) throws IOException {
customerPath = getFullPath(customerPath + filename);
File newFile = new File(customerPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(fileData);
outputStream.close();
}
</code></pre>
<p>Can anyone spot what I'm doing wrong?</p>
<p>Cheers,
Lee</p>
|
[
{
"answer_id": 41748,
"author": "Ben",
"author_id": 1417,
"author_profile": "https://Stackoverflow.com/users/1417",
"pm_score": 0,
"selected": false,
"text": "getBytes() doPost() byte[] bytes = StreamUtils.getBytes(stream);\n public static byte[] getBytes(InputStream src, int buffsize)\n"
},
{
"answer_id": 42202,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 3,
"selected": true,
"text": " 1 while (true) {\n 2 int nBytesRead = src.read(buff);\n 3 if (nBytesRead < 0) {\n 4 break;\n 5 }\n 6 byteStream.write(buff);\n 7 }\n 1 while (true) {\n 2 int nBytesRead = src.read(buff);\n 3 if (nBytesRead < 0) {\n 4 break;\n 5 } else {\n 6 byteStream.write(buff, 0, nBytesRead);\n 7 }\n 8 }\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1900/"
] |
41,699 |
<p>So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.</p>
|
[
{
"answer_id": 43161,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "SERVICE_TABLE_ENTRY ServiceStartTable[] =\n{\n { \"ServiceName\", ServiceMain },\n { 0, 0 }\n};\n\nif (!StartServiceCtrlDispatcher(ServiceStartTable))\n{\n DWORD err = GetLastError();\n if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)\n return false;\n}\n void WINAPI ServiceMain(DWORD, LPTSTR*)\n{\n hServiceStatus = RegisterServiceCtrlHandlerEx(\"ServiceName\", ServiceHandlerProc, 0);\n DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)\n{\n switch (ControlCode)\n {\n case SERVICE_CONTROL_INTERROGATE :\n // update OS about our status\n case SERVICE_CONTROL_STOP :\n // shut down service\n }\n\n return 0;\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/634/"
] |
41,701 |
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p>
<p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:
(jobId, label, username) = job</p>
<p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p>
<p>Here are my two best guesses:
(jobId, label, username) = (job[0], job[1], job[2])
...but that doesn't scale nicely when you have 15...20 fields</p>
<p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
|
[
{
"answer_id": 41707,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 5,
"selected": true,
"text": "job={}\njob['jobid'], job['label'], job['username']=<querycode>\n"
},
{
"answer_id": 41709,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 0,
"selected": false,
"text": "job job.jobId, job.username = jobId, username\n"
},
{
"answer_id": 41723,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 2,
"selected": false,
"text": "values = <querycode>\nkeys = [\"jobid\", \"label\", \"username\"]\njob = dict([[keys[i], values [i]] for i in xrange(len(values ))])\n"
},
{
"answer_id": 41730,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": -1,
"selected": false,
"text": "class TypedTuple:\n def __init__(self, fieldlist, items):\n self.fieldlist = fieldlist\n self.items = items\n def __getattr__(self, field):\n return self.items[self.fieldlist.index(field)]\n j = TypedTuple([\"jobid\", \"label\", \"username\"], job)\nprint j.jobid\n self.fieldlist.index(field) __init__"
},
{
"answer_id": 41846,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": false,
"text": "job = dict(zip(keys, values))\n"
},
{
"answer_id": 2609123,
"author": "jpkotta",
"author_id": 245173,
"author_profile": "https://Stackoverflow.com/users/245173",
"pm_score": 0,
"selected": false,
"text": "import MySQLdb, MySQLdb.cursors\nconn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)\ncur = conn.cursor() # a DictCursor\ncur2 = conn.cursor(cursorclass=MySQLdb.cursors.Cursor) # a \"normal\" tuple cursor\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397/"
] |
41,715 |
<p>Right now I'm working with an ASP.NET website that automatically generates images and stores them in a temporary folder. When working on my local system these go going into a temporary folder that gets picked up by Visual Source Safe which then wants to check them in. As such, I am wondering if there is a way to just exclude that particular folder from source control?</p>
<p>I've done a bit of reading and found that there are ways to do this for <a href="http://forums.msdn.microsoft.com/en-US/vssourcecontrol/thread/6cc4aab0-e7bc-44e8-baa3-045c9cd82e9a/" rel="nofollow noreferrer">individual files</a>, but I haven't found anything yet about an entire folder.</p>
|
[
{
"answer_id": 778985,
"author": "Min",
"author_id": 14461,
"author_profile": "https://Stackoverflow.com/users/14461",
"pm_score": 0,
"selected": false,
"text": "C:\\tempfiles"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] |
41,717 |
<p>Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.</p>
<p>I'm wondering about how user controls work in ASP.NET MVC. We have tons of <code>.ASCX</code> controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.</p>
<p>What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.</p>
|
[
{
"answer_id": 41722,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": true,
"text": "<% Html.RenderPartial(\"~/Views/Shared/MyControl.ascx\", {data model object}) %>\n <%= Html.RenderUserControl(\"~/Views/Shared/MyControl.ascx\", {data model object}) %>\n"
},
{
"answer_id": 5192101,
"author": "Trevor",
"author_id": 644471,
"author_profile": "https://Stackoverflow.com/users/644471",
"pm_score": 1,
"selected": false,
"text": "Page_Load Index()"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
41,724 |
<p>I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen <a href="http://ayende.com/blog/tags/domain-specific-languages" rel="noreferrer">Ayende's blog posts</a> and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.</p>
<p>If you've got some background using these things, any chance you could put it in real laymans terms:</p>
<ul>
<li>What exactly building DSLs means?</li>
<li>What languages are you using?</li>
<li>Where using a DSL makes sense?</li>
<li>What is the benefit of using DSLs?</li>
</ul>
|
[
{
"answer_id": 41742,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 1,
"selected": false,
"text": "NewsDAO.writtenBy(\"someUser\").before(\"someDate\").updateStatus(\"Deleted\")\n"
},
{
"answer_id": 41743,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 5,
"selected": true,
"text": "DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO();\nfor (int id : documentIDS) {\nDocument myDoc = MyDocumentDAO.loadDoc(id);\nif (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) {\n ReminderService.sendUnreadReminder(myDoc)\n}\n for (document : documents) {\nif (document is unread) {\n document.sendReminder\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] |
41,733 |
<p>Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?</p>
<pre><code>TExample = record
SortOrder : integer;
SomethingElse : string;
end;
var SomeVar : array of TExample;
</code></pre>
|
[
{
"answer_id": 41951,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 6,
"selected": true,
"text": "TList TList.Sort IComparer<TExample> TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct(\n function(const Left, Right: TExample): Integer\n begin\n Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder);\n end));\n"
},
{
"answer_id": 49702,
"author": "ddowns",
"author_id": 5201,
"author_profile": "https://Stackoverflow.com/users/5201",
"pm_score": 1,
"selected": false,
"text": "quicksort heapsort TExample.SortOrder"
},
{
"answer_id": 161661,
"author": "CoolMagic",
"author_id": 22641,
"author_profile": "https://Stackoverflow.com/users/22641",
"pm_score": 2,
"selected": false,
"text": "TStringList TString.AddObject(string, Pointer(int_val)) TObjectList TObjectList.Sort"
},
{
"answer_id": 161880,
"author": "Germán Estévez -Neftalí-",
"author_id": 17487,
"author_profile": "https://Stackoverflow.com/users/17487",
"pm_score": 0,
"selected": false,
"text": "TStringList TStringList Sorted TStringList"
},
{
"answer_id": 1381865,
"author": "Guy Gordon",
"author_id": 652328,
"author_profile": "https://Stackoverflow.com/users/652328",
"pm_score": 4,
"selected": false,
"text": "TExample = record\n SortOrder : integer;\n SomethingElse : string;\nend;\n var MyDA: Array of TExample; \n...\n SetLength(MyDA,NewSize); //allocate memory for the dynamic array\n for i:=0 to NewSize-1 do begin //fill the array with records\n MyDA[i].SortOrder := SomeInteger;\n MyDA[i].SomethingElse := SomeString;\n end;\n var tsExamples: TStringList; //declare it somewhere (global or local)\n...\n tsExamples := tStringList.create; //allocate it somewhere (and free it later!)\n...\n tsExamples.Clear; //now let's use it\n tsExamples.sorted := False; //don't want to sort after every add\n tsExamples.Capacity := High(MyDA)+1; //don't want to increase size with every add\n //an empty dynamic array has High() = -1\n for i:=0 to High(MyDA) do begin\n tsExamples.AddObject(MyDA[i].SomethingElse,TObject(MyDA[i].SortOrder));\n end;\n function CompareObjects(ts:tStringList; Item1,Item2: integer): Integer;\nbegin\n Result := CompareValue(Integer(ts.Objects[Item1]), Integer(ts.Objects[Item2]))\nend;\n tsExamples.CustomSort(@CompareObjects); //Sort the list\n var Mlist: TList; //a list of Pointers\n...\n for i:=0 to High(MyDA) do\n Mlist.add(Pointer(i)); //cast the array index as a Pointer\n Mlist.Sort(@CompareRecords); //using the compare function below\n\nfunction CompareRecords(Item1, Item2: Integer): Integer;\nvar i,j: integer;\nbegin\n i := integer(item1); //recover the index into MyDA\n j := integer(item2); // and use it to access any field\n Result := SomeFunctionOf(MyDA[i].SomeField) - SomeFunctionOf(MyDA[j].SomeField);\nend;\n for i:=0 to Mlist.Count-1 do begin\n Something := MyDA[integer(Mlist[i])].SomeField;\n end;\n"
},
{
"answer_id": 9001207,
"author": "rt15",
"author_id": 1168949,
"author_profile": "https://Stackoverflow.com/users/1168949",
"pm_score": 1,
"selected": false,
"text": "type TComparatorFunction = function(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl;\nprocedure qsort(base: Pointer; num: Cardinal; size: Cardinal; lpComparatorFunction: TComparatorFunction) cdecl; external 'msvcrt.dll';\n"
},
{
"answer_id": 28460112,
"author": "David Miró",
"author_id": 2270217,
"author_profile": "https://Stackoverflow.com/users/2270217",
"pm_score": -1,
"selected": false,
"text": "Type\n THuman = Class\n Public\n Name: String;\n Age: Byte;\n Constructor Create(Name: String; Age: Integer);\n End;\n\nConstructor THuman.Create(Name: String; Age: Integer);\nBegin\n Self.Name:= Name;\n Self.Age:= Age;\nEnd;\n\nProcedure Test();\nVar\n Human: THuman;\n Humans: Array Of THuman;\n List: TStringList;\nBegin\n\n SetLength(Humans, 3);\n Humans[0]:= THuman.Create('David', 41);\n Humans[1]:= THuman.Create('Brian', 50);\n Humans[2]:= THuman.Create('Alex', 20);\n\n List:= TStringList.Create;\n List.AddObject(Humans[0].Name, TObject(Humans[0]));\n List.AddObject(Humans[1].Name, TObject(Humans[1]));\n List.AddObject(Humans[2].Name, TObject(Humans[2]));\n List.Sort;\n\n Human:= THuman(List.Objects[0]);\n Showmessage('The first person on the list is the human ' + Human.name + '!');\n\n List.Free;\nEnd;\n"
},
{
"answer_id": 47884859,
"author": "Jacek Krawczyk",
"author_id": 1960514,
"author_profile": "https://Stackoverflow.com/users/1960514",
"pm_score": 0,
"selected": false,
"text": "var \n someVar: array of TExample;\n list: TList<TExample>;\n sortedVar: array of TExample;\nbegin\n list := TList<TExample>.Create(someVar);\n try\n list.Sort;\n sortedVar := list.ToArray;\n finally\n list.Free;\n end;\nend;\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] |
41,763 |
<p>What is the best way to calculate Age using Flex?</p>
|
[
{
"answer_id": 41845,
"author": "Richard Braxton",
"author_id": 4393,
"author_profile": "https://Stackoverflow.com/users/4393",
"pm_score": 4,
"selected": false,
"text": "private function getYearsOld(dob:Date):uint { \n var now:Date = new Date(); \n var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear); \n if (dob.month > now.month || (dob.month == now.month && dob.date > now.date)) \n {\n yearsOld--;\n }\n return yearsOld; \n}\n"
},
{
"answer_id": 43789,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 1,
"selected": false,
"text": "var age:int = (new Date()).fullYear - bDay.fullYear;\nif ((new Date()) < (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--;\n"
},
{
"answer_id": 542129,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 1,
"selected": false,
"text": "private function calculateAge(dob:Date):String { \n var now:Date = new Date();\n\n var ageDays:int = 0;\n var ageYears:int = 0;\n var ageRmdr:int = 0;\n\n var diff:Number = now.getTime()-dob.getTime();\n ageDays = diff / 86400000;\n ageYears = Math.floor(ageDays / 365.24);\n ageRmdr = Math.floor( (ageDays - (ageYears*365.24)) / 30.4375 );\n\n if ( ageRmdr == 12 ) {\n ageRmdr = 11;\n }\n\n return ageYears + \" years \" + ageRmdr + \" months\";\n}\n"
},
{
"answer_id": 542592,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "var userDOB : Date = new Date(year,month-1,day);\nvar today : Date = new Date();\n\nvar diff : Date = new Date();\ndiff.setTime( today.getTime() - userDOB.getTime() );\n\nvar userAge : int = diff.getFullYear() - 1970;\n"
},
{
"answer_id": 1269238,
"author": "datico",
"author_id": 127105,
"author_profile": "https://Stackoverflow.com/users/127105",
"pm_score": 1,
"selected": false,
"text": "int( now.getFullYear() - dob.getFullYear() + (now.getMonth() - dob.getMonth())*.01 + (now.getDate() - dob.getDate())*.0001 );\n"
},
{
"answer_id": 2791649,
"author": "jowie",
"author_id": 190657,
"author_profile": "https://Stackoverflow.com/users/190657",
"pm_score": 1,
"selected": false,
"text": "private function getYearsOld(dob:Date):uint\n{\n var now:Date = new Date();\n var age:Date = new Date(now.getTime() - dob.getTime());\n var yearsOld:uint = age.getFullYear() - 1970;\n return yearsOld;\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4393/"
] |
41,766 |
<p>I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys <a href="http://www.herdingcode.com/" rel="noreferrer">HerdingCode</a> called <a href="http://code.google.com/p/wittytwitter/" rel="noreferrer">Witty</a>. (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code.</p>
<p>Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code. </p>
<p>On the source page for this project (<a href="http://code.google.com/p/wittytwitter/source/checkout" rel="noreferrer">google code witty source</a>) it gives the following instruction:</p>
<p><strong>Non-members may check out a read-only working copy anonymously over HTTP.</strong> <br>
<strong><em>svn checkout <a href="http://wittytwitter.googlecode.com/svn/trunk/" rel="noreferrer">http://wittytwitter.googlecode.com/svn/trunk/</a> wittytwitter-read-only</em></strong> </p>
<p>I'm confused as to where I am supposed to enter the above command so that I can download the code.</p>
<p>I have installed SVN and Tortoise (which I know almost nothing about). </p>
<p>Thanks for any help or simply pointing me in the right direction.</p>
<p>...Ed (@emcpadden)</p>
|
[
{
"answer_id": 41771,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 4,
"selected": false,
"text": "svn checkout http://wittytwitter.googlecode.com/svn/trunk\n"
},
{
"answer_id": 41774,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 2,
"selected": false,
"text": "tortoise-svn -> repo-browser trunk checkout export"
},
{
"answer_id": 41776,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 8,
"selected": true,
"text": "SVN Checkout"
},
{
"answer_id": 724336,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 1,
"selected": false,
"text": "bin cd"
},
{
"answer_id": 3818917,
"author": "Vicky",
"author_id": 266052,
"author_profile": "https://Stackoverflow.com/users/266052",
"pm_score": 3,
"selected": false,
"text": "Tortoise SVN - > Settings - > NetWork"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2858/"
] |
41,781 |
<p>I've worked with T-SQL for years but I've just moved to an organisation that is going to require writing some Oracle stuff, probably just simple CRUD operations at least until I find my feet. I'm not going to be migrating databases from one to the other simply interacting with existing Oracle databases from an Application Development perspective. Is there are tool or utility available to easily translate T-SQL into Oracle SQL, a keyword mapper is the sort of thing I'm looking for.</p>
<p>P.S. I'm too lazy to RTFM, besides it's not going to be a big part of my role so I just want something to get me up to speed a little faster.</p>
|
[
{
"answer_id": 54420302,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 0,
"selected": false,
"text": "$ java -cp jooq-3.11.9.jar org.jooq.ParserCLI -t ORACLE -s \"SELECT substring('abcde', 2, 3)\"\nselect substr('abcde', 2, 3) from dual;\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403/"
] |
41,792 |
<p>I am re-factoring some code and am wondering about the use of a <code>lock</code> in the instance constructor.</p>
<pre><code>public class MyClass {
private static Int32 counter = 0;
private Int32 myCount;
public MyClass() {
lock(this) {
counter++;
myCount = counter;
}
}
}
</code></pre>
<p>Please confirm</p>
<ol>
<li>Instance constructors are thread-safe.</li>
<li>The lock statement prevents access to that code block, not to the static 'counter' member.</li>
</ol>
<p>If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a <code>MyClass</code> and changing the count before this one sets its count?</p>
<p><em>FYI - This class is not a singleton. Instances must simply be aware of their number.</em></p>
|
[
{
"answer_id": 41801,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "private static int counter = 0;\nprivate static object counterLock = new Object();\n\nlock(counterLock) {\n counter++;\n myCounter = counter;\n}\n"
},
{
"answer_id": 41804,
"author": "hakan",
"author_id": 3993,
"author_profile": "https://Stackoverflow.com/users/3993",
"pm_score": 2,
"selected": false,
"text": "private static Object lockObj = new Object();\n lock(lockObj){}\n .NET"
},
{
"answer_id": 41816,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 0,
"selected": false,
"text": "public MyClass {\n\n private static Int32 counter = 0;\n public static MyClass GetAnInstance() {\n\n lock(MyClass) {\n counter++;\n return new MyClass();\n }\n }\n\n private Int32 myCount;\n private MyClass() {\n myCount = counter;\n }\n}\n"
},
{
"answer_id": 41852,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 4,
"selected": false,
"text": "System.Threading.Interlocked.Increment(myField);\n"
},
{
"answer_id": 41961,
"author": "Andrew",
"author_id": 1948,
"author_profile": "https://Stackoverflow.com/users/1948",
"pm_score": 2,
"selected": false,
"text": "class MyClass {\n\n static int _LastInstanceId = 0;\n private readonly int instanceId; \n\n public MyClass() { \n this.instanceId = Interlocked.Increment(ref _LastInstanceId); \n }\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] |
41,796 |
<p>I'm looking for a quality WinForms component that supports syntax highlighting, code folding and the like. The key criteria are:</p>
<ol>
<li>Stability </li>
<li>Value (price)</li>
<li>Ability to easily customize syntax to highlight</li>
<li>Light weight</li>
</ol>
|
[
{
"answer_id": 16391867,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 2,
"selected": false,
"text": "public Form1()\n{\nInitializeComponent();\nICSharpCode.AvalonEdit.TextEditor te = new ICSharpCode.AvalonEdit.TextEditor();\nElementHost host = new ElementHost();\nhost.Size = new Size(200, 100);\nhost.Location = new Point(100, 100);\nhost.Child = te;\nthis.Controls.Add(host);\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4398/"
] |
41,824 |
<p>I'm using Microsoft AjaxControlToolkit for modal popup window.</p>
<p>And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?</p>
|
[
{
"answer_id": 41910,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 3,
"selected": false,
"text": "Show() MyModalPopoupExtender.Show()\n"
},
{
"answer_id": 42188,
"author": "Jon Erickson",
"author_id": 1950,
"author_profile": "https://Stackoverflow.com/users/1950",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (Page.IsPostBack)\n {\n // reshow\n MyModalPopup.Show()\n }\n}\n"
},
{
"answer_id": 8576317,
"author": "Gregor Primar",
"author_id": 1107945,
"author_profile": "https://Stackoverflow.com/users/1107945",
"pm_score": 4,
"selected": false,
"text": "<asp:Panel ID=\"pnlControls\" runat=\"server\">\n\n <asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\">\n <ContentTemplate>\n <asp:Button ID=\"TestButton\" runat=\"server\" Text=\"Test Button\" onclick=\"TestButton_Click\" />\n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"Label\"></asp:Label> \n </ContentTemplate>\n\n </asp:UpdatePanel>\n"
},
{
"answer_id": 27068727,
"author": "Darrel Lee",
"author_id": 307968,
"author_profile": "https://Stackoverflow.com/users/307968",
"pm_score": 2,
"selected": false,
"text": " Protected Sub Control_Load(sende As Object, e As EventArgs) Handles Me.Load\n If IsPostBack Then\n Dim eventTarget As String = Page.Request.Params.Get(\"__EventTarget\")\n Dim eventArgs As String = Page.Request.Params.Get(\"__EventArgument\")\n\n If Not String.IsNullOrEmpty(eventTarget) AndAlso eventTarget.StartsWith(Me.UniqueID) Then\n If eventTarget.Contains(\"$\" + _credentialBuilder.ID + \"$\") Then\n ' Postback from credential builder modal. Keep it open.\n showCredentialBuilder = True\n End If\n End If\n End If\n End Sub\n Protected Sub Control_PreRender(ByVal sende As Object, ByVal e As EventArgs) Handles Me.PreRender\n If showCredentialBuilder Then\n _mpeCredentialEditor.Show()\n End If\n End Sub\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] |
41,836 |
<p>I have tried both of :</p>
<pre><code>ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes');
</code></pre>
<p>and also :</p>
<pre><code>php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes"
</code></pre>
<p>in the .htaccess file.</p>
<p>Both methods actually <strong>do work</strong> but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site.</p>
<p>I'm not even sure where to begin trying to find out what is going on!</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/41836/setting-include-path-in-php-intermittently-fails-why#41877">cnote</a></p>
<blockquote>
<p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p>
</blockquote>
<p>The in script version was originally </p>
<pre><code>ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
</code></pre>
<p>and thus the .:.: was coming from the existing path:</p>
<pre><code>ini_get('include_path')
</code></pre>
<p>I tried removing it anyway and the problem persists.</p>
|
[
{
"answer_id": 42336,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "PATH_SEPARATOR set_include_path('.' . PATH_SEPARATOR . './app/lib' . PATH_SEPARATOR . get_include_path());\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319/"
] |
41,842 |
<p>When should I include PDB files for a production release? Should I use the <code>Optimize code</code> flag and how would that affect the information I get from an exception?</p>
<p>If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?</p>
|
[
{
"answer_id": 96261,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 4,
"selected": false,
"text": "[.NET Framework Debugging Control]\nGenerateTrackingInfo=0\nAllowOptimize=1\n [.NET Framework Debugging Control]\nGenerateTrackingInfo=1\nAllowOptimize=0 \n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3615/"
] |
41,869 |
<p>If I run the following query in SQL Server 2000 Query Analyzer:</p>
<pre><code>BULK INSERT OurTable
FROM 'c:\OurTable.txt'
WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK)
</code></pre>
<p>On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?</p>
|
[
{
"answer_id": 152695,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 6,
"selected": true,
"text": "BULK INSERT INSERT BEGIN TRANSACTION\nBEGIN TRY\nBULK INSERT OurTable \nFROM 'c:\\OurTable.txt' \nWITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\\t', \n ROWS_PER_BATCH = 10000, TABLOCK)\nCOMMIT TRANSACTION\nEND TRY\nBEGIN CATCH\nROLLBACK TRANSACTION\nEND CATCH\n"
},
{
"answer_id": 9520696,
"author": "Guillermo Garcia",
"author_id": 247684,
"author_profile": "https://Stackoverflow.com/users/247684",
"pm_score": 1,
"selected": false,
"text": "BATCHSIZE"
},
{
"answer_id": 41284802,
"author": "Sai Bhasker Raju",
"author_id": 2431980,
"author_profile": "https://Stackoverflow.com/users/2431980",
"pm_score": 2,
"selected": false,
"text": "BatchSize MAXERRORS MAXERRORS=1 BatchSize=1"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
] |
41,881 |
<p>I am using the <code>ODBC</code> connector to access a MySQL db from Visual Studio 2008 and I'm facing performance problems when dealing with crystal reports and to solve this I need a native connector to visual studio. If someone has had a similar problem and knows a solution or tools (freeware preferable), I would be really grateful.</p>
|
[
{
"answer_id": 2738330,
"author": "Fabio",
"author_id": 329018,
"author_profile": "https://Stackoverflow.com/users/329018",
"pm_score": 1,
"selected": false,
"text": "Mysql.Data.dll dll Bin"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
41,894 |
<p>Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.</p>
|
[
{
"answer_id": 41904,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 7,
"selected": true,
"text": " StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();\n StackTraceElement main = stack[stack.length - 1];\n String mainClass = main.getClassName ();\n"
},
{
"answer_id": 42082,
"author": "polarbear",
"author_id": 3636,
"author_profile": "https://Stackoverflow.com/users/3636",
"pm_score": 2,
"selected": false,
"text": "jps -l \n"
},
{
"answer_id": 42938,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 4,
"selected": false,
"text": "main"
},
{
"answer_id": 2421152,
"author": "Adam",
"author_id": 291006,
"author_profile": "https://Stackoverflow.com/users/291006",
"pm_score": -1,
"selected": false,
"text": "public class Foo\n{\n public static final String PROGNAME = new Foo().getClass().getName();\n}\n String myProgramName = this.getClass().getName();\n"
},
{
"answer_id": 8883260,
"author": "tschodt",
"author_id": 1069589,
"author_profile": "https://Stackoverflow.com/users/1069589",
"pm_score": 2,
"selected": false,
"text": "public final class ClassUtils {\n public static final Class[] getClassContext() {\n return new SecurityManager() { \n protected Class[] getClassContext(){return super.getClassContext();}\n }.getClassContext(); \n };\n private ClassUtils() {};\n public static final Class getMyClass() { return getClassContext()[2];}\n public static final Class getCallingClass() { return getClassContext()[3];}\n public static final Class getMainClass() { \n Class[] c = getClassContext();\n return c[c.length-1];\n }\n public static final void main(final String[] arg) {\n System.out.println(getMyClass());\n System.out.println(getCallingClass());\n System.out.println(getMainClass());\n }\n}\n class ClassUtils\n classcontext[0] is the securitymanager\nclasscontext[1] is the anonymous securitymanager\nclasscontext[2] is the class with this funky getclasscontext method\nclasscontext[3] is the calling class\nclasscontext[last entry] is the root class of this thread.\n"
},
{
"answer_id": 12031392,
"author": "Andrew Taylor",
"author_id": 303442,
"author_profile": "https://Stackoverflow.com/users/303442",
"pm_score": 3,
"selected": false,
"text": "private static Class<?> mainClass;\n\npublic static Class<?> getMainClass() {\n if (mainClass != null)\n return mainClass;\n\n Collection<StackTraceElement[]> stacks = Thread.getAllStackTraces().values();\n for (StackTraceElement[] currStack : stacks) {\n if (currStack.length==0)\n continue;\n StackTraceElement lastElem = currStack[currStack.length - 1];\n if (lastElem.getMethodName().equals(\"main\")) {\n try {\n String mainClassName = lastElem.getClassName();\n mainClass = Class.forName(mainClassName);\n return mainClass;\n } catch (ClassNotFoundException e) {\n // bad class name in line containing main?! \n // shouldn't happen\n e.printStackTrace();\n }\n }\n }\n return null;\n}\n"
},
{
"answer_id": 12989117,
"author": "Nadav Brandes",
"author_id": 1622468,
"author_profile": "https://Stackoverflow.com/users/1622468",
"pm_score": 4,
"selected": false,
"text": "System.getProperty(\"sun.java.command\")\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823/"
] |
41,925 |
<p>What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently.</p>
<p><strong>Edit:</strong> Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like</p>
<pre><code>where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2)
</code></pre>
<p>which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field.</p>
<p><strong>[Edit]</strong></p>
<p>People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.</p>
|
[
{
"answer_id": 41982,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 7,
"selected": true,
"text": "vanity (800) Lucky-Guy"
},
{
"answer_id": 42028,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 3,
"selected": false,
"text": "en_GB de_DE"
},
{
"answer_id": 170898,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 2,
"selected": false,
"text": "function validatePhone(phoneNumber) {\n var valid = true;\n var stripped = phoneNumber.replace(/[\\(\\)\\.\\-\\ \\+\\x]/g, ''); \n\n if(phoneNumber == \"\"){\n valid = false;\n }else if (isNaN(parseInt(stripped))) {\n valid = false;\n }else if (stripped.length > 40) {\n valid = false;\n }\n return valid;\n}\n"
},
{
"answer_id": 51761170,
"author": "Alex Klaus",
"author_id": 968003,
"author_profile": "https://Stackoverflow.com/users/968003",
"pm_score": 3,
"selected": false,
"text": "+1-202-555-0252 +1-202-555-7166;ext=22 0 8 0449053501 04 4905 3501 (04) 4905 3501"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
41,928 |
<p>I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of <code>lightwindow.js</code>, claiming that the <code>object does not support this property or method</code>. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later.</p>
<p>Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow).</p>
<p>These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue:</p>
<ol>
<li>Moved the call to lightwindow.js to the bottom of the page.</li>
<li>Changed line 444 to: <code>if (this._getGalleryInfo(link.rel)) {</code></li>
<li>Changed line 1157 to: <code>if (this._getGalleryInfo(this.element.rel)) {</code></li>
<li>Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a <code>try/catch</code> block, swallowing the exception.</li>
</ol>
<p><strong>EDIT:</strong> </p>
<p>I realised that this broke Firefox. Adding the following as line 445 now makes it work - <code>try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }</code></p>
<p>It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.</p>
|
[
{
"answer_id": 47224,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "if( this && this._getGalleryInfo )\n{\n //use the function\n\n}\n if(this && this.element && this.element.rel) _getGalleryInfo this.element.rel"
},
{
"answer_id": 595214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if(gallery = this._getGalleryInfo(link.rel)) gallery = this._getGalleryInfo(link.rel) if(gallery)"
},
{
"answer_id": 627554,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": true,
"text": "var gallery = this._getGalleryInfo(link.rel)\n if(gallery.length > 0)\n{\n // Rest of code here...\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
41,934 |
<p>When I do a file search on eclipse it includes the <code>.svn</code> directories by default. I tried excluding them from the build path but they still appear on file search results.</p>
|
[
{
"answer_id": 41959,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 3,
"selected": false,
"text": ".svn"
},
{
"answer_id": 354675,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Share Team Share Project..."
},
{
"answer_id": 1627108,
"author": "spaceman",
"author_id": 158341,
"author_profile": "https://Stackoverflow.com/users/158341",
"pm_score": 2,
"selected": false,
"text": ".svn .svn"
},
{
"answer_id": 3693293,
"author": "Brad Whitaker",
"author_id": 330923,
"author_profile": "https://Stackoverflow.com/users/330923",
"pm_score": 8,
"selected": true,
"text": "Project -> Properties -> Resource -> Resource Filters exclude .svn"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823/"
] |
41,937 |
<p>I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection.</p>
<p>The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.</p>
|
[
{
"answer_id": 1143731,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "MapWindow"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1958/"
] |
41,948 |
<p>I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.</p>
|
[
{
"answer_id": 41960,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 7,
"selected": true,
"text": "getTime() var oldBegin = ...\nvar oldEnd = ...\nvar newBegin = ...\n\nvar newEnd = new Date(newBegin + oldEnd - oldBegin);\n oldBegin oldEnd newBegin Date + - valueOf() valueOf() Date getTime() date.getTime() === date.valueOf() === (0 + date) === (+date)"
},
{
"answer_id": 41966,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 0,
"selected": false,
"text": "getTime()"
},
{
"answer_id": 41974,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": ".getDate() .setDate() function GetEndDate(startDate)\n{\n var endDate = new Date(startDate.getTime());\n endDate.setDate(endDate.getDate()+14);\n return endDate;\n}\n function GetDateDiff(startDate, endDate)\n{\n return endDate.getDate() - startDate.getDate();\n}\n function GetEndDate(startDate, days)\n{\n var endDate = new Date(startDate.getTime());\n endDate.setDate(endDate.getDate() + days);\n return endDate;\n}\n"
},
{
"answer_id": 42086,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "newBegin + oldEnd - oldBegin // don't update end date if there's already an end date but not an old start date\n if (!oldEnd || oldBegin) {\n var selectedDateSpan = 1800000; // 30 minutes\n if (oldEnd) {\n selectedDateSpan = oldEnd - oldBegin;\n }\n\n newEnd = new Date(newBegin.getTime() + selectedDateSpan));\n }\n"
},
{
"answer_id": 5056705,
"author": "hiren gamit",
"author_id": 625179,
"author_profile": "https://Stackoverflow.com/users/625179",
"pm_score": -1,
"selected": false,
"text": "function checkdate() {\n var indate = new Date()\n indate.setDate(dat)\n indate.setMonth(mon - 1)\n indate.setFullYear(year)\n\n var one_day = 1000 * 60 * 60 * 24\n var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))\n var str = diff + \" days are remaining..\"\n document.getElementById('print').innerHTML = str.fontcolor('blue')\n}\n"
},
{
"answer_id": 10409160,
"author": "shareef",
"author_id": 944593,
"author_profile": "https://Stackoverflow.com/users/944593",
"pm_score": 0,
"selected": false,
"text": "txtFromQualifDate txtQualifDate txtStudyYears function getStudyYears()\n {\n if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')\n {\n var d1 = document.getElementById('txtFromQualifDate').value;\n\n var d2 = document.getElementById('txtQualifDate').value;\n\n var one_day=1000*60*60*24;\n\n var x = d1.split(\"/\");\n var y = d2.split(\"/\");\n\n var date1=new Date(x[2],(x[1]-1),x[0]);\n\n var date2=new Date(y[2],(y[1]-1),y[0])\n\n var dDays = (date2.getTime()-date1.getTime())/one_day;\n\n if(dDays < 365)\n {\n alert(\"the date between start study and graduate must not be less than a year !\");\n\n document.getElementById('txtQualifDate').value = \"\";\n document.getElementById('txtStudyYears').value = \"\";\n\n return ;\n }\n\n var dMonths = Math.ceil(dDays / 30);\n\n var dYears = Math.floor(dMonths /12) + \".\" + dMonths % 12;\n\n document.getElementById('txtStudyYears').value = dYears;\n }\n }\n"
},
{
"answer_id": 10536394,
"author": "sparkyspider",
"author_id": 578318,
"author_profile": "https://Stackoverflow.com/users/578318",
"pm_score": 2,
"selected": false,
"text": "// This one returns a signed decimal. The sign indicates past or future.\n\nthis.getDateDiff = function(date1, date2) {\n return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);\n}\n\n// This one always returns a positive decimal. (Suggested by Koen below)\n\nthis.getDateDiff = function(date1, date2) {\n return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));\n}\n"
},
{
"answer_id": 15810692,
"author": "Dan",
"author_id": 139361,
"author_profile": "https://Stackoverflow.com/users/139361",
"pm_score": 5,
"selected": false,
"text": "var msMinute = 60*1000, \n msDay = 60*60*24*1000,\n a = new Date(2012, 2, 12, 23, 59, 59),\n b = new Date(\"2013 march 12\");\n\n\nconsole.log(Math.floor((b - a) / msDay) + ' full days between'); // 364\nconsole.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0\n console.log(a - 10); // 1331614798990\nconsole.log(a + 10); // mixed string\n number console.log(a.getTime() - 10); // 1331614798990\nconsole.log(a.getTime() + 10); // 1331614799010\n"
},
{
"answer_id": 20002054,
"author": "dheerendra",
"author_id": 2927163,
"author_profile": "https://Stackoverflow.com/users/2927163",
"pm_score": 1,
"selected": false,
"text": "function compare()\n{\n var end_actual_time = $('#date3').val();\n\n start_actual_time = new Date();\n end_actual_time = new Date(end_actual_time);\n\n var diff = end_actual_time-start_actual_time;\n\n var diffSeconds = diff/1000;\n var HH = Math.floor(diffSeconds/3600);\n var MM = Math.floor(diffSeconds%3600)/60;\n\n var formatted = ((HH < 10)?(\"0\" + HH):HH) + \":\" + ((MM < 10)?(\"0\" + MM):MM)\n getTime(diffSeconds);\n}\nfunction getTime(seconds) {\n var days = Math.floor(leftover / 86400);\n\n //how many seconds are left\n leftover = leftover - (days * 86400);\n\n //how many full hours fits in the amount of leftover seconds\n var hours = Math.floor(leftover / 3600);\n\n //how many seconds are left\n leftover = leftover - (hours * 3600);\n\n //how many minutes fits in the amount of leftover seconds\n var minutes = leftover / 60;\n\n //how many seconds are left\n //leftover = leftover - (minutes * 60);\n alert(days + ':' + hours + ':' + minutes);\n}\n"
},
{
"answer_id": 25042075,
"author": "tika",
"author_id": 2988919,
"author_profile": "https://Stackoverflow.com/users/2988919",
"pm_score": 3,
"selected": false,
"text": " var date1 = new Date(); \n var date2 = new Date(\"2025/07/30 21:59:00\");\n //Customise date2 for your required future time\n\n showDiff();\n\nfunction showDiff(date1, date2){\n\n var diff = (date2 - date1)/1000;\n diff = Math.abs(Math.floor(diff));\n\n var days = Math.floor(diff/(24*60*60));\n var leftSec = diff - days * 24*60*60;\n\n var hrs = Math.floor(leftSec/(60*60));\n var leftSec = leftSec - hrs * 60*60;\n\n var min = Math.floor(leftSec/(60));\n var leftSec = leftSec - min * 60;\n\n document.getElementById(\"showTime\").innerHTML = \"You have \" + days + \" days \" + hrs + \" hours \" + min + \" minutes and \" + leftSec + \" seconds before death.\";\n\nsetTimeout(showDiff,1000);\n}\n <div id=\"showTime\"></div>\n"
},
{
"answer_id": 28616175,
"author": "NovaYear",
"author_id": 556986,
"author_profile": "https://Stackoverflow.com/users/556986",
"pm_score": 1,
"selected": false,
"text": "showDiff();\n\nfunction showDiff(){\nvar date1 = new Date(\"2013/01/18 06:59:00\"); \nvar date2 = new Date();\n//Customise date2 for your required future time\n\nvar diff = (date2 - date1)/1000;\nvar diff = Math.abs(Math.floor(diff));\n\nvar years = Math.floor(diff/(365*24*60*60));\nvar leftSec = diff - years * 365*24*60*60;\n\nvar month = Math.floor(leftSec/((365/12)*24*60*60));\nvar leftSec = leftSec - month * (365/12)*24*60*60; \n\nvar days = Math.floor(leftSec/(24*60*60));\nvar leftSec = leftSec - days * 24*60*60;\n\nvar hrs = Math.floor(leftSec/(60*60));\nvar leftSec = leftSec - hrs * 60*60;\n\nvar min = Math.floor(leftSec/(60));\nvar leftSec = leftSec - min * 60;\n\n\n\n\ndocument.getElementById(\"showTime\").innerHTML = \"You have \" + years + \" years \"+ month + \" month \" + days + \" days \" + hrs + \" hours \" + min + \" minutes and \" + leftSec + \" seconds the life time has passed.\";\n\nsetTimeout(showDiff,1000);\n}\n"
},
{
"answer_id": 34782685,
"author": "Sukanya Suku",
"author_id": 5681934,
"author_profile": "https://Stackoverflow.com/users/5681934",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n<script>\nfunction dayDiff()\n{\n var start = document.getElementById(\"datepicker\").value;\n var end= document.getElementById(\"date_picker\").value;\n var oneDay = 24*60*60*1000; \n var firstDate = new Date(start);\n var secondDate = new Date(end); \n var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));\n document.getElementById(\"leave\").value =diffDays ;\n }\n</script>\n</head>\n<body>\n<input type=\"text\" name=\"datepicker\"value=\"\"/>\n<input type=\"text\" name=\"date_picker\" onclick=\"function dayDiff()\" value=\"\"/>\n<input type=\"text\" name=\"leave\" value=\"\"/>\n</body>\n</html>\n"
},
{
"answer_id": 37532797,
"author": "Miguel Guardo",
"author_id": 5739841,
"author_profile": "https://Stackoverflow.com/users/5739841",
"pm_score": 2,
"selected": false,
"text": "moment(endDate).diff(moment(beginDate), 'days');\n"
},
{
"answer_id": 49576078,
"author": "Vin S",
"author_id": 9573544,
"author_profile": "https://Stackoverflow.com/users/9573544",
"pm_score": 1,
"selected": false,
"text": "var getDaysLeft = function (date) {\n var today = new Date();\n var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));\n var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24); \n return daysLeft;\n};\n\ngetDaysLeft('YYYY-MM-DD');\n"
},
{
"answer_id": 50414819,
"author": "Vin S",
"author_id": 9573544,
"author_profile": "https://Stackoverflow.com/users/9573544",
"pm_score": 0,
"selected": false,
"text": "var getDaysLeft = function (date1, date2) {\n var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));\n var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24); \n return daysLeft;\n};\nvar date1='2018-05-18';\nvar date2='2018-05-25';\nvar dateDiff = getDaysLeft(date1, date2);\nconsole.log(dateDiff);\n"
},
{
"answer_id": 50508313,
"author": "Sean Cortez",
"author_id": 8750004,
"author_profile": "https://Stackoverflow.com/users/8750004",
"pm_score": -1,
"selected": false,
"text": "var startTime=(\"08:00:00\").split(\":\");\nvar endTime=(\"16:00:00\").split(\":\");\nvar HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));\nconsole.log(HoursInMinutes/60);\n"
},
{
"answer_id": 72967699,
"author": "Liam Pillay",
"author_id": 11404295,
"author_profile": "https://Stackoverflow.com/users/11404295",
"pm_score": 0,
"selected": false,
"text": "var diff = Math.abs(date1 - date2);\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688/"
] |
41,969 |
<p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p>
<p>On OSX, I can open a window in the finder with</p>
<pre><code>os.system('open "%s"' % foldername)
</code></pre>
<p>and on Windows with</p>
<pre><code>os.startfile(foldername)
</code></pre>
<p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p>
<p>This looks like something that could be specified by the <a href="http://freedesktop.org" rel="noreferrer">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
|
[
{
"answer_id": 42046,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 5,
"selected": true,
"text": "os.system('xdg-open \"%s\"' % foldername)\n xdg-open"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/41969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002/"
] |
42,017 |
<p>I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this?</p>
|
[
{
"answer_id": 2707506,
"author": "Rowland Shaw",
"author_id": 50447,
"author_profile": "https://Stackoverflow.com/users/50447",
"pm_score": 3,
"selected": false,
"text": "BitmapSource Metadata"
},
{
"answer_id": 31329551,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": false,
"text": "IEnumerable<Directory> directories = ImageMetadataReader.ReadMetadata(path);\n\nforeach (var directory in directories)\nforeach (var tag in directory.Tags)\n Console.WriteLine($\"{directory.Name} - {tag.TagName} = {tag.Description}\");\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] |
42,034 |
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
|
[
{
"answer_id": 42052,
"author": "sphereinabox",
"author_id": 2775,
"author_profile": "https://Stackoverflow.com/users/2775",
"pm_score": 4,
"selected": false,
"text": "a = {}\na[(1,2,\"bob\")] = \"hello!\"\na[(\"Hello\",\"en-US\")] = \"Hi There!\"\n"
},
{
"answer_id": 39638334,
"author": "Mayank Shekhar",
"author_id": 6505489,
"author_profile": "https://Stackoverflow.com/users/6505489",
"pm_score": 2,
"selected": false,
"text": "t = 'p', 'q', 'r', 's', 't'\n t = ('p', 'q', 'r', 's', 't') \n"
},
{
"answer_id": 52500970,
"author": "Lassi",
"author_id": 6272277,
"author_profile": "https://Stackoverflow.com/users/6272277",
"pm_score": 3,
"selected": false,
"text": "person = {\"name\": \"Sam\", \"age\": 42}\nname, age = person[\"name\"], person[\"age\"]\n class Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\nperson = Person(\"Sam\", 42)\nname, age = person.name, person.age\n person = (\"Sam\", 42)\nname, age = person\n type alias Person = (String, Int)\n\nperson : Person\nperson = (\"Sam\", 42)\n (Float, Float, Float) (Person, [String]) [String] Person (String, String) (String, Integer) from collections import namedtuple\n\nPerson = namedtuple(\"Person\", \"name age\")\n\nperson = Person(\"Sam\", 42)\nname, age = person.name, person.age\n"
},
{
"answer_id": 63481233,
"author": "Sanmitha Sadhishkumar",
"author_id": 13827419,
"author_profile": "https://Stackoverflow.com/users/13827419",
"pm_score": 0,
"selected": false,
"text": "a,b=1,2\n def add(*arg) #arg is a tuple\n return sum(arg)\n"
},
{
"answer_id": 72592849,
"author": "hassanzadeh.sd",
"author_id": 9533909,
"author_profile": "https://Stackoverflow.com/users/9533909",
"pm_score": 1,
"selected": false,
"text": "a_tuple = tuple(range(1000))\na_list = list(range(1000))\na_tuple.__sizeof__() # 8024 bytes\na_list.__sizeof__() # 9088 bytes\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] |
42,068 |
<p>I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:</p>
<pre><code>var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
</code></pre>
<p>This gives me an error: </p>
<pre><code>unterminated string literal
</code></pre>
<p>With <code>JSON.parse(data)</code>, I see similar error messages: "<code>Unexpected token ↵</code>" in Chrome, and "<code>unterminated string literal</code>" in Firefox and IE.</p>
<p>When I take out the <code>\n</code> after <code>sometext</code> the error goes away in both cases. I can't seem to figure out why the <code>\n</code> makes <code>eval</code> and <code>JSON.parse</code> fail. </p>
|
[
{
"answer_id": 42073,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 10,
"selected": true,
"text": "var data = '{\"count\" : 1, \"stack\" : \"sometext\\\\n\\\\n\"}';\n \\ \\"
},
{
"answer_id": 1111538,
"author": "Ron",
"author_id": 2293628,
"author_profile": "https://Stackoverflow.com/users/2293628",
"pm_score": 2,
"selected": false,
"text": "public static string Enquote(string s) \n{ \n if (s == null || s.Length == 0) \n { \n return \"\\\"\\\"\"; \n } \n char c; \n int i; \n int len = s.Length; \n StringBuilder sb = new StringBuilder(len + 4); \n string t; \n\n sb.Append('\"'); \n for (i = 0; i < len; i += 1) \n { \n c = s[i]; \n if ((c == '\\\\') || (c == '\"') || (c == '>')) \n { \n sb.Append('\\\\'); \n sb.Append(c); \n } \n else if (c == '\\b') \n sb.Append(\"\\\\b\"); \n else if (c == '\\t') \n sb.Append(\"\\\\t\"); \n else if (c == '\\n') \n sb.Append(\"\\\\n\"); \n else if (c == '\\f') \n sb.Append(\"\\\\f\"); \n else if (c == '\\r') \n sb.Append(\"\\\\r\"); \n else \n { \n if (c < ' ') \n { \n //t = \"000\" + Integer.toHexString(c); \n string t = new string(c,1); \n t = \"000\" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber); \n sb.Append(\"\\\\u\" + t.Substring(t.Length - 4)); \n } \n else \n { \n sb.Append(c); \n } \n } \n } \n sb.Append('\"'); \n return sb.ToString(); \n} \n"
},
{
"answer_id": 5191059,
"author": "Manish Singh",
"author_id": 518493,
"author_profile": "https://Stackoverflow.com/users/518493",
"pm_score": 6,
"selected": false,
"text": "\\n \\\\n data function jsonEscape(str) {\n return str.replace(/\\n/g, \"\\\\\\\\n\").replace(/\\r/g, \"\\\\\\\\r\").replace(/\\t/g, \"\\\\\\\\t\");\n}\n\nvar data = '{\"count\" : 1, \"stack\" : \"sometext\\n\\n\"}';\nvar dataObj = JSON.parse(jsonEscape(data));\n dataObj Object {count: 1, stack: \"sometext\\n\\n\"}\n"
},
{
"answer_id": 6156153,
"author": "GabrielP",
"author_id": 773563,
"author_profile": "https://Stackoverflow.com/users/773563",
"pm_score": -1,
"selected": false,
"text": "class jsonResponse {\n var $response;\n\n function jsonResponse() {\n $this->response = array('isOK'=>'KO', 'msg'=>'Undefined');\n }\n\n function set($isOK, $msg) {\n $this->response['isOK'] = ($isOK) ? 'OK' : 'KO';\n $this->response['msg'] = htmlentities($msg);\n }\n\n function setData($data=null) {\n if(!is_null($data))\n $this->response['data'] = $data;\n elseif(isset($this->response['data']))\n unset($this->response['data']);\n }\n\n function send() {\n header('Content-type: application/json');\n echo '{\"isOK\":\"' . $this->response['isOK'] . '\",\"msg\":' . $this->parseString($this->response['msg']);\n if(isset($this->response['data']))\n echo ',\"data\":' . $this->parseData($this->response['data']);\n echo '}';\n }\n\n function parseData($data) {\n if(is_array($data)) {\n $parsed = array();\n foreach ($data as $key=>$value)\n array_push($parsed, $this->parseString($key) . ':' . $this->parseData($value));\n return '{' . implode(',', $parsed) . '}';\n }\n else\n return $this->parseString($data);\n }\n\n function parseString($string) {\n $string = str_replace(\"\\\\\", \"\\\\\\\\\", $string);\n $string = str_replace('/', \"\\\\/\", $string);\n $string = str_replace('\"', \"\\\\\".'\"', $string);\n $string = str_replace(\"\\b\", \"\\\\b\", $string);\n $string = str_replace(\"\\t\", \"\\\\t\", $string);\n $string = str_replace(\"\\n\", \"\\\\n\", $string);\n $string = str_replace(\"\\f\", \"\\\\f\", $string);\n $string = str_replace(\"\\r\", \"\\\\r\", $string);\n $string = str_replace(\"\\u\", \"\\\\u\", $string);\n return '\"'.$string.'\"';\n }\n}\n"
},
{
"answer_id": 13493212,
"author": "ShivarajRH",
"author_id": 903527,
"author_profile": "https://Stackoverflow.com/users/903527",
"pm_score": 0,
"selected": false,
"text": "function normalize_str($str) {\n\n $invalid = array(\n 'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z',\n 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A',\n 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E',\n 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',\n 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y',\n 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a',\n 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i',\n 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',\n 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',\n 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',\n \"`\" => \"'\", \"´\" => \"'\", '\"' => ',', '`' => \"'\",\n '´' => \"'\", '\"' => '\\\"', '\"' => \"\\\"\", '´' => \"'\",\n \"’\" => \"'\",\n \"{\" => \"\",\n \"~\" => \"\", \"–\" => \"-\", \"'\" => \"'\", \" \" => \" \");\n\n $str = str_replace(array_keys($invalid), array_values($invalid), $str);\n\n $remove = array(\"\\n\", \"\\r\\n\", \"\\r\");\n $str = str_replace($remove, \"\\\\n\", trim($str));\n\n //$str = htmlentities($str, ENT_QUOTES);\n\n return htmlspecialchars($str);\n}\n\necho normalize_str($lst['address']);\n"
},
{
"answer_id": 16700486,
"author": "Victor_Magalhaes",
"author_id": 751147,
"author_profile": "https://Stackoverflow.com/users/751147",
"pm_score": 2,
"selected": false,
"text": "response.write \"{\"\"field1\"\":\"\"\" & escape(RS_Temp(\"textField\")) & \"\"\"}\"\n document.getElementById(\"text1\").value = unescape(jsonObject.field1)\n"
},
{
"answer_id": 42899451,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 4,
"selected": false,
"text": "U+0022 U+0022 U+005C U+0000 U+001F 0x0A 0x0C U+0000 U+001F \\f U+000C \\n U+000A \\ jsonStr = \"{ \\\"name\\\": \\\"Multi\\\\nline.\\\" }\";\n"
},
{
"answer_id": 55850752,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": -1,
"selected": false,
"text": "dataObj eval==evil var dataObj = {\"count\" : 1, \"stack\" : \"sometext\\n\\n\"};\n\nconsole.log(dataObj);"
},
{
"answer_id": 63137400,
"author": "jerryurenaa",
"author_id": 11611288,
"author_profile": "https://Stackoverflow.com/users/11611288",
"pm_score": 2,
"selected": false,
"text": " <p style={{whiteSpace: 'pre-line'}}>my json text goes here \\n\\n</p>\n"
},
{
"answer_id": 66531090,
"author": "Marinos An",
"author_id": 1555615,
"author_profile": "https://Stackoverflow.com/users/1555615",
"pm_score": 5,
"selected": false,
"text": "String.raw var data = String.raw`{\"count\" : 1, \"stack\" : \"sometext\\n\\n\"}`;\n node \nlet obj = JSON.parse(fs.readFileSync('file.json'));\nconsole.log(obj.mykey)\n file.json {\n \"mykey\": \"my multiline\n value\"\n}\n SyntaxError: Unexpected token\n {\n \"mykey\": \"my multiline\\nvalue\"\n}\n my multiline\nvalue\n {\n \"mykey\": \"my multiline\\\\nvalue\"\n}\n my multiline\\nvalue\n json \\n \\n \\\\n \\n String.raw let input1 = '{\"mykey\": \"my multiline\\nvalue\"}'\n\n//OR\nlet input1 = `{\n \"mykey\": \"my multiline\n value\"\n}`;\n//(or even)\nlet input1 = `{\n \"mykey\": \"my multiline\\nvalue\"\n}`;\n\n//OR\nlet input1 = String.raw`{\n \"mykey\": \"my multiline\n value\"\n}`;\n\nconsole.log(JSON.parse(input1).mykey);\n\n//SyntaxError: Unexpected token\n//in JSON at position [..]\n let input2 = '{\"mykey\": \"my multiline\\\\nvalue\"}'\n\n//OR\nlet input2 = `{\n \"mykey\": \"my multiline\\\\nvalue\"\n}`;\n\n//OR (Notice the difference from default literal)\nlet input2 = String.raw`{\n \"mykey\": \"my multiline\\nvalue\"\n}`;\n\nconsole.log(JSON.parse(input2).mykey);\n\n//my multiline\n//value\n\n let input3 = '{\"mykey\": \"my multiline\\\\\\\\nvalue\"}'\n\n//OR\nlet input3 = `{\n \"mykey\": \"my multiline\\\\\\\\nvalue\"\n}`;\n\n//OR (Notice the difference from default literal)\nlet input3 = String.raw`{\n \"mykey\": \"my multiline\\\\nvalue\"\n}`;\n\nconsole.log(JSON.parse(input3).mykey);\n\n//my multiline\\nvalue\n json String.raw String.raw`abc${\"`\"}def` json JSON.stringify"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636/"
] |
42,070 |
<p>What's going on here?</p>
<p>printf.sh:</p>
<pre><code>#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" $NAME
</code></pre>
<p>Command line session:</p>
<pre><code>$ ./printf.sh
Hello, George
Hello, W.
Hello, Bush
</code></pre>
<p>UPDATE: <code>printf "Hello, %s\n" "$NAME"</code> works. For why I'm not using <code>echo</code>, consider</p>
<p>echo.sh:</p>
<pre><code>#! /bin/sh
FILE="C:\tmp"
echo "Filename: $FILE"
</code></pre>
<p>Command-line:</p>
<pre><code>$ ./echo.sh
Filename: C: mp
</code></pre>
<p>The <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="noreferrer">POSIX spec for <code>echo</code></a> says, "New applications are encouraged to use <code>printf</code> instead of <code>echo</code>" (for this and other reasons). </p>
|
[
{
"answer_id": 42089,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": 1,
"selected": false,
"text": "NAME=\"George W. Bush\"\necho \"Hello, \"$NAME\n Hello, George W. Bush\n printf \"Hello, %s\\n\" \"$NAME\"\n"
},
{
"answer_id": 42092,
"author": "ColinYounger",
"author_id": 1223,
"author_profile": "https://Stackoverflow.com/users/1223",
"pm_score": 4,
"selected": true,
"text": "printf \"Hello, %s\\n\" George W. Bush\n #! /bin/sh\nNAME=\"George W. Bush\"\nprintf \"Hello, %s\\n\" \"$NAME\"\n"
},
{
"answer_id": 42103,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 1,
"selected": false,
"text": "printf \"Hello, $NAME.\"\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
42,076 |
<p><strong>What mechanisms do you know that prevent your site from being abused by anonymous spammers.</strong></p>
<p>For example, let's say that I have a site where people can vote something. But I <em>don't</em> want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work?</p>
|
[
{
"answer_id": 895737,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 2,
"selected": false,
"text": "style=\"display:none\""
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
42,102 |
<p>I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class.</p>
<p>Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader. </p>
<p>Is there any way with JUnit (or with another unit testing package) to do this?</p>
<p>edit: here is some of the Factory code that is in use:</p>
<pre><code>private static MyClass myClassImpl = instantiateMyClass();
private static MyClass instantiateMyClass() {
MyClass newMyClass = null;
String className = null;
try {
Properties props = getProperties();
className = props.getProperty(PROPERTY_CLASSNAME_KEY);
if (className == null) {
log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY
+ "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]");
className = DEFAULT_CLASSNAME;
}
Class MyClassClass = Class.forName(className);
Object MyClassObj = MyClassClass.newInstance();
if (MyClassObj instanceof MyClass) {
newMyClass = (MyClass) MyClassObj;
}
}
catch (...) {
...
}
return newMyClass;
}
private static Properties getProperties() throws IOException {
Properties props = new Properties();
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
if (stream != null) {
props.load(stream);
}
else {
log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found");
}
return props;
}
</code></pre>
|
[
{
"answer_id": 42130,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 2,
"selected": false,
"text": "myClassImpl instantiateMyClass()"
},
{
"answer_id": 9192126,
"author": "AutomatedMike",
"author_id": 352035,
"author_profile": "https://Stackoverflow.com/users/352035",
"pm_score": 5,
"selected": false,
"text": "@RunWith(SeparateClassloaderTestRunner.class) SeparateClassloaderTestRunner public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {\n\n public SeparateClassloaderTestRunner(Class<?> clazz) throws InitializationError {\n super(getFromTestClassloader(clazz));\n }\n\n private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError {\n try {\n ClassLoader testClassLoader = new TestClassLoader();\n return Class.forName(clazz.getName(), true, testClassLoader);\n } catch (ClassNotFoundException e) {\n throw new InitializationError(e);\n }\n }\n\n public static class TestClassLoader extends URLClassLoader {\n public TestClassLoader() {\n super(((URLClassLoader)getSystemClassLoader()).getURLs());\n }\n\n @Override\n public Class<?> loadClass(String name) throws ClassNotFoundException {\n if (name.startsWith(\"org.mypackages.\")) {\n return super.findClass(name);\n }\n return super.loadClass(name);\n }\n }\n}\n"
},
{
"answer_id": 17805809,
"author": "barclar",
"author_id": 329736,
"author_profile": "https://Stackoverflow.com/users/329736",
"pm_score": 2,
"selected": false,
"text": "fork=true MyClass"
},
{
"answer_id": 34154189,
"author": "Neeme Praks",
"author_id": 74694,
"author_profile": "https://Stackoverflow.com/users/74694",
"pm_score": 1,
"selected": false,
"text": "package com.mycompany.app;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\n\nimport java.net.URLClassLoader;\n\nimport org.junit.Test;\n\npublic class ApplicationInSeparateClassLoaderTest {\n\n @Test\n public void testApplicationInSeparateClassLoader1() throws Exception {\n testApplicationInSeparateClassLoader();\n }\n\n @Test\n public void testApplicationInSeparateClassLoader2() throws Exception {\n testApplicationInSeparateClassLoader();\n }\n\n private void testApplicationInSeparateClassLoader() throws Exception {\n //run application code in separate class loader in order to isolate static state between test runs\n Runnable runnable = mock(Runnable.class);\n //set up your mock object expectations here, if needed\n InterfaceToApplicationDependentCode tester = makeCodeToRunInSeparateClassLoader(\n \"com.mycompany.app\", InterfaceToApplicationDependentCode.class, CodeToRunInApplicationClassLoader.class);\n //if you want to try the code without class loader isolation, comment out above line and comment in the line below\n //CodeToRunInApplicationClassLoader tester = new CodeToRunInApplicationClassLoaderImpl();\n tester.testTheCode(runnable);\n verify(runnable).run();\n assertEquals(\"should be one invocation!\", 1, tester.getNumOfInvocations());\n }\n\n /**\n * Create a new class loader for loading application-dependent code and return an instance of that.\n */\n @SuppressWarnings(\"unchecked\")\n private <I, T> I makeCodeToRunInSeparateClassLoader(\n String packageName, Class<I> testCodeInterfaceClass, Class<T> testCodeImplClass) throws Exception {\n TestApplicationClassLoader cl = new TestApplicationClassLoader(\n packageName, getClass(), testCodeInterfaceClass);\n Class<?> testerClass = cl.loadClass(testCodeImplClass.getName());\n return (I) testerClass.newInstance();\n }\n\n /**\n * Bridge interface, implemented by code that should be run in application class loader.\n * This interface is loaded by the same class loader as the unit test class, so\n * we can call the application-dependent code without need for reflection.\n */\n public static interface InterfaceToApplicationDependentCode {\n void testTheCode(Runnable run);\n int getNumOfInvocations();\n }\n\n /**\n * Test-specific code to call application-dependent code. This class is loaded by \n * the same class loader as the application code.\n */\n public static class CodeToRunInApplicationClassLoader implements InterfaceToApplicationDependentCode {\n private static int numOfInvocations = 0;\n\n @Override\n public void testTheCode(Runnable runnable) {\n numOfInvocations++;\n runnable.run();\n }\n\n @Override\n public int getNumOfInvocations() {\n return numOfInvocations;\n }\n }\n\n /**\n * Loads application classes in separate class loader from test classes.\n */\n private static class TestApplicationClassLoader extends URLClassLoader {\n\n private final String appPackage;\n private final String mainTestClassName;\n private final String[] testSupportClassNames;\n\n public TestApplicationClassLoader(String appPackage, Class<?> mainTestClass, Class<?>... testSupportClasses) {\n super(((URLClassLoader) getSystemClassLoader()).getURLs());\n this.appPackage = appPackage;\n this.mainTestClassName = mainTestClass.getName();\n this.testSupportClassNames = convertClassesToStrings(testSupportClasses);\n }\n\n private String[] convertClassesToStrings(Class<?>[] classes) {\n String[] results = new String[classes.length];\n for (int i = 0; i < classes.length; i++) {\n results[i] = classes[i].getName();\n }\n return results;\n }\n\n @Override\n public Class<?> loadClass(String className) throws ClassNotFoundException {\n if (isApplicationClass(className)) {\n //look for class only in local class loader\n return super.findClass(className);\n }\n //look for class in parent class loader first and only then in local class loader\n return super.loadClass(className);\n }\n\n private boolean isApplicationClass(String className) {\n if (mainTestClassName.equals(className)) {\n return false;\n }\n for (int i = 0; i < testSupportClassNames.length; i++) {\n if (testSupportClassNames[i].equals(className)) {\n return false;\n }\n }\n return className.startsWith(appPackage);\n }\n\n }\n\n}\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
42,115 |
<p>I am running into an issue I had before; can't find my reference on how to solve it.</p>
<p>Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below:</p>
<pre><code> config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
If config.ConnectionStrings.SectionInformation.IsProtected = False Then
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing)
' We must save the changes to the configuration file.'
config.Save(ConfigurationSaveMode.Modified, True)
End If
</code></pre>
<p>The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is:</p>
<pre><code>Unhandled Exception: System.Configuration.ConfigurationErrorsException:
An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'.
Error message from the provider: Object already exists.
---> System.Security.Cryptography.CryptographicException: Object already exists
</code></pre>
|
[
{
"answer_id": 373205,
"author": "MikeScott8",
"author_id": 1889,
"author_profile": "https://Stackoverflow.com/users/1889",
"pm_score": 2,
"selected": true,
"text": "aspnet_regiis -pa \"NetFrameworkConfigurationKey\" \"{domain}\\{user}\"\n"
},
{
"answer_id": 2702297,
"author": "luisfbn",
"author_id": 324647,
"author_profile": "https://Stackoverflow.com/users/324647",
"pm_score": 2,
"selected": false,
"text": "aspnet_regiis -pc \"DataProtectionConfigurationProviderKeys\" -exp\n <add name=\"DataProtectionConfigurationProvider\"\n\n type=\"System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0,\n\n Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,\n\n processorArchitecture=MSIL\"\n\n keyContainerName=\"DataProtectionConfigurationProviderKeys\"\n\n useMachineContainer=\"true\" />\n <clear /> <configuration xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\">\n aspnet_regiis -pdf \"connectionStrings\" \"c:\\Bla\\Bla\\Bla\"\n\naspnet_regiis -pdf \"system.web/membership\" \"c:\\Bla\\Bla\\Bla\"\n aspnet_regiis -pz \"DataProtectionConfigurationProviderKeys\"\n aspnet_regiis -px \"DataProtectionConfigurationProviderKeys\" \\temp\\mykeyfile.xml -pri\n aspnet_regiis -pi \"DataProtectionConfigurationProviderKeys\" \\temp\\mykeyfile.xml\n aspnet_regiis -pa \"DataProtectionConfigurationProviderKeys\" \"DOMAIN\\User\"\n Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name\n aspnet_regiis -pr \"DataProtectionConfigurationProviderKeys\" \"Domain\\User\"\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889/"
] |
42,125 |
<p>I have a library I created,</p>
<h3>File <em>mylib.c:</em></h3>
<pre><code>#include <mylib.h>
int
testlib() {
printf("Hello, World!\n");
return (0);
}
</code></pre>
<h3>File <em>mylib.h:</em></h3>
<pre><code>#include <stdio.h>
extern int testlib();
</code></pre>
<p>In my program, I've attempted to call this library function:</p>
<h3>File <em>myprogram.c</em>:</h3>
<pre><code>#include <mylib.h>
int
main (int argc, char *argv[]) {
testlib();
return (0);
}
</code></pre>
<p>When I attempt to compile this program I get the following error:</p>
<pre>In file included from myprogram.c:1
mylib.h:2 warning: function declaration isn't a prototype</pre>
<p>I'm using: <code>gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)</code></p>
<p>What is the proper way to declare a function prototype?</p>
|
[
{
"answer_id": 42133,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "extern int testlib(void);\n"
},
{
"answer_id": 47693,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 10,
"selected": true,
"text": "int foo() int foo(void) int foo() int foo(void) void a extern int a; a extern static extern extern extern"
},
{
"answer_id": 20843829,
"author": "Keith Thompson",
"author_id": 827263,
"author_profile": "https://Stackoverflow.com/users/827263",
"pm_score": 6,
"selected": false,
"text": "int testlib() int testlib(void) int foo();\n int bar(int x, double y);\n void int foo(void); /* foo takes no arguments */\n int testlib()\n{\n /* code that implements testlib */\n}\n testlib testlib testlib () (void) testlib (void) () (void)"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3807/"
] |
42,126 |
<p>I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS.</p>
<blockquote>
<p>C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430) :
error C2371: 'WCHAR' : redefinition; different basic types 1><br>
C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winnt.h(289) :
see declaration of 'WCHAR'</p>
</blockquote>
<p>I don't see any defines in odbcss.h that I could set to avoid this. Has anyone else seen this? </p>
|
[
{
"answer_id": 42207,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "#define WIN16 #include \"wab.h\" #undef WIN16"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] |
42,146 |
<p>This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field.</p>
<p>Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications.</p>
|
[
{
"answer_id": 42152,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "netstat -b\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] |
42,150 |
<p>.NET Framework: 2.0
Preferred Language: C#</p>
<p>I am new to TDD (Test Driven Development).</p>
<p>First of all, is it even possible to unit test Windows Service?</p>
<p>Windows service class is derived from ServiceBase, which has overridable methods, </p>
<ol>
<li>OnStart </li>
<li>OnStop</li>
</ol>
<p>How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?</p>
<p>At this point, am I even doing a Unit testing? or an Integration test?</p>
<p>I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.</p>
|
[
{
"answer_id": 42155,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 3,
"selected": false,
"text": "public static void StartService(string serviceName, int timeoutMilliseconds)\n{\n ServiceController service = new ServiceController(serviceName);\n try\n {\n TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);\n\n service.Start();\n service.WaitForStatus(ServiceControllerStatus.Running, timeout);\n }\n catch\n {\n // ...\n }\n}\n"
},
{
"answer_id": 33901272,
"author": "BitMask777",
"author_id": 509891,
"author_profile": "https://Stackoverflow.com/users/509891",
"pm_score": 2,
"selected": false,
"text": "OnStart OnStop OnStart serviceInstance.GetType().InvokeMember(\"OnStart\", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, serviceInstance, new object[] {new string[] {}});\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4035/"
] |
42,153 |
<p>I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead.</p>
<p>How do you embed a <code>JApplet</code> in HTML on a webpage?</p>
|
[
{
"answer_id": 42163,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<applet code=\"TumbleItem.class\" \n codebase=\"examples/\"\n archive=\"tumbleClasses.jar, tumbleImages.jar\"\n width=\"600\" height=\"95\">\n <param name=\"maxwidth\" value=\"120\">\n <param name=\"nimgs\" value=\"17\">\n <param name=\"offset\" value=\"-57\">\n <param name=\"img\" value=\"images/tumble\">\n\nYour browser is completely ignoring the <APPLET> tag!\n</applet>\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] |
42,169 |
<p>I converted my company's calendar to XSL and changed all the tables to divs. It worked pretty well, but I had a lot of 8 day week bugs to work out initially owing to precarious cross-browser spacing issues. But I was reading another post regarding when to use tables v. divs and the consensus seemed to be that you should only use divs for true divisions between parts of the webpage, and only use tables for tabular data. </p>
<p>I'm not sure I could even have used tables with XSL but I wanted to follow up that discussion of Divs and Tables with a discussion of the ideal way to make a web calendars and maybe a union of the two. </p>
|
[
{
"answer_id": 42183,
"author": "automatic",
"author_id": 3854,
"author_profile": "https://Stackoverflow.com/users/3854",
"pm_score": 1,
"selected": false,
"text": "<table>"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
42,182 |
<p>I'm trying to write a blog post which includes a code segment inside a <code><pre></code> tag. The code segment includes a generic type and uses <code><></code> to define that type. This is what the segment looks like:</p>
<pre><code><pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
</code></pre>
<p>The resulting HTML removes the <code><></code> and ends up like this:</p>
<pre><code>PrimeCalc calc = new PrimeCalc();
Func del = calc.GetNextPrime;
</code></pre>
<p>How do I escape the <code><></code> so they show up in the HTML?</p>
|
[
{
"answer_id": 42191,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": false,
"text": "< and >\n"
},
{
"answer_id": 42192,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 3,
"selected": false,
"text": "< >"
},
{
"answer_id": 42193,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 4,
"selected": false,
"text": "< > < >"
},
{
"answer_id": 42194,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": false,
"text": "<pre>></pre>\n <pre>\n PrimeCalc calc = new PrimeCalc();\n Func<int, int> del = calc.GetNextPrime;\n</pre>\n"
},
{
"answer_id": 42195,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 8,
"selected": true,
"text": "<pre>\n PrimeCalc calc = new PrimeCalc();\n Func<int, int> del = calc.GetNextPrime;\n</pre>\n"
},
{
"answer_id": 42201,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 2,
"selected": false,
"text": "<pre>\n PrimeCalc calc = new PrimeCalc();\n Func<int, int> del = calc.GetNextPrime;\n</pre>\n"
},
{
"answer_id": 27536517,
"author": "PanicBus",
"author_id": 2526710,
"author_profile": "https://Stackoverflow.com/users/2526710",
"pm_score": -1,
"selected": false,
"text": "<pre> <pre>\n${fn:escapeXml('\n <!-- all your code -->\n')};\n</pre>\n"
}
] |
2008/09/03
|
[
"https://Stackoverflow.com/questions/42182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.