qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
251,271
<p>Sometimes you need to upgrade the database with many rows that you have in a datatable or you have an array full of data, instead of putting all this data together in a string and then splitting in SQL SERVER, or instead of iterating the datatable in the code row by row and updating database, is there any other way? Is there other type of variables besides the traditional ones in SQL SERVER 2005?</p>
[ { "answer_id": 251285, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 3, "selected": true, "text": "SqlBulkCopy copier = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default);\ncopier.BatchSize = 500; //# of rows to insert at a time\ncopier.DestinationTableName = \"dbo.MyTable\";\ncopier.WriteToServer(myDataTable);\n" }, { "answer_id": 251545, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "SqlBulkCopy SqlBulkCopy DataTable IDataReader SimpleDataReader SqlBulkCopy IDataReader" }, { "answer_id": 251574, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE MySproc ( @Accounts XML )\nAS\n\nSELECT\n Accounts.AccountID.query('.')\nFROM\n @Accounts.nodes('//ID/text()') AS Accounts(AccountID)\n\nGO\nEXEC MySproc '<Accounts><ID>123</ID><ID>456</ID></Accounts>'\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31791/" ]
251,275
<p>I have a User object that has a Country object on it. I map this with a many-to-one tag in the User mapping file:</p> <pre><code>&lt;many-to-one name="Country" column="CountryID" cascade="none"/&gt; </code></pre> <p>How do I update a User's country?</p> <p>At the moment my UI has a dropdown of countries and the ID of the new country is passed to the controller. The controller then sets the ID of the User's country from that value. So:</p> <pre><code>var user = session.Get&lt;User&gt;(userID); user.Country.ID = Convert.ToInt32(Request.Form["Country_ID"]); </code></pre> <p>But when I call:</p> <pre><code>session.SaveOrUpdate(user); </code></pre> <p>I get an error saying that "identifier of an instance of Country was altered from 7 to 8". Presumably this is because the Country object is marked as dirty by NHibernate? I don't want to update the country object though, just the ID reference in the User. Is it possible to do it this way?</p> <p>Thanks, Jon</p>
[ { "answer_id": 251324, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 0, "selected": false, "text": "var user = session.Get<User>(userID);\nuser.Country = session.Get<Country>(Convert.ToInt32(Request.Form[\"Country_ID\"]));\n" }, { "answer_id": 253209, "author": "JontyMC", "author_id": 32855, "author_profile": "https://Stackoverflow.com/users/32855", "pm_score": 0, "selected": false, "text": "var user = session.Get<User>(userID);\nuser.Country = session.Get<Country>(Convert.ToInt32(Request.Form[\"Country_ID\"]));\nuser.Manager = session.Get<User>(Convert.ToInt32(Request.Form[\"Manager_ID\"]));\nuser.State = session.Get<State>(Convert.ToInt32(Request.Form[\"State _ID\"]));\nuser.Region = session.Get<Region>(Convert.ToInt32(Request.Form[\"State _ID\"]));\n var ds = new NameValueDeserializer();\nvar entity = session.Get<TEntity>(entityID);\nds.Deserialize(entity, form);\nsession.Update(entity);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32855/" ]
251,276
<p>I am writing a searching function, and have thought up of this query using parameters to prevent, or at least limit, SQL injection attacks. However, when I run it through my program it does not return anything:</p> <p><code>SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')</code></p> <p>Can parameters be used like this? or are they only valid in an instance such as:</p> <p><code>SELECT * FROM compliance_corner WHERE body LIKE '%&lt;string&gt;%'</code> (where <code>&lt;string&gt;</code> is the search object).</p> <p>EDIT: I am constructing this function with VB.NET, does that have impact on the syntax you guys have contributed?</p> <p>Also, I ran this statement in SQL Server: <code>SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE</code>%max%')` and that returns results.</p>
[ { "answer_id": 251288, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 5, "selected": false, "text": "LIKE '%' + @param + '%'" }, { "answer_id": 251311, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 7, "selected": true, "text": "Dim cmd as New SqlCommand(\"SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')\")\n\ncmd.Parameters.Add(\"@query\", searchString)\n" }, { "answer_id": 251380, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 7, "selected": false, "text": " Dim cmd as New SqlCommand(\n \"SELECT * FROM compliance_corner\"_\n + \" WHERE (body LIKE @query )\"_ \n + \" OR (title LIKE @query)\")\n\n cmd.Parameters.Add(\"@query\", \"%\" +searchString +\"%\")\n" }, { "answer_id": 4433177, "author": "Lalie", "author_id": 541042, "author_profile": "https://Stackoverflow.com/users/541042", "pm_score": 1, "selected": false, "text": "% % * %" }, { "answer_id": 45429309, "author": "Ramgy Borja", "author_id": 7978302, "author_profile": "https://Stackoverflow.com/users/7978302", "pm_score": 1, "selected": false, "text": "Dim cmd as New SqlCommand(\"SELECT * FROM compliance_corner WHERE (body LIKE CONCAT('%',@query,'%') OR title LIKE CONCAT('%',@query,'%') )\")\ncmd.Parameters.Add(\"@query\", searchString)\ncmd.ExecuteNonQuery()\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
251,277
<p>Is there a simple way to sort an iterator in PHP (without just pulling it all into an array and sorting that).</p> <p>The specific example I have is a <a href="http://www.php.net/directoryiterator" rel="noreferrer">DirectoryIterator</a> but it would be nice to have a solution general to any iterator.</p> <pre><code>$dir = new DirectoryIterator('.'); foreach ($dir as $file) echo $file-&gt;getFilename(); </code></pre> <p>I'd like to be able to sort these by various criteria (filename, size, etc)</p>
[ { "answer_id": 3832409, "author": "bishop", "author_id": 463000, "author_profile": "https://Stackoverflow.com/users/463000", "pm_score": 3, "selected": false, "text": "// get (recursively) files matching a pattern, each file as SplFileInfo object\n$matches = new RegexIterator(\n new RecursiveIteratorIterator(\n new RecursiveDirectoryIterator('/path/to/files/')\n ),\n '/(\\.php|\\.ini|\\.xml)$/i'\n );\n $files = iterator_to_array($matches);\n\n// sort them by name\nuasort($files, create_function('$a,$b', 'return strnatcasecmp($a->getFilename(), $b->getFilename());'));\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24181/" ]
251,278
<p>Added: Working with SQL Server 2000 and 2005, so has to work on both. Also, value_rk is not a number/integer (Error: Operand data type uniqueidentifier is invalid for min operator)</p> <p>Is there a way to do a single column "DISTINCT" match when I don't care about the other columns returned? Example:</p> <pre><code>**Table** Value A, Value L, Value P Value A, Value Q, Value Z </code></pre> <p>I need to return only one of these rows based on what is in the first one (Value A). I still need results from the second and third columns (the second should actually match all across the board anyway, but the third is a unique key, which I need at least one of).</p> <p>Here's what I've got so far, although it doesn't work obviously:</p> <pre><code>SELECT value, attribute_definition_id, value_rk FROM attribute_values WHERE value IN ( SELECT value, max(value_rk) FROM attribute_values ) ORDER BY attribute_definition_id </code></pre> <p>I'm working in ColdFusion so if there's a simple workaround in that I'm open to that as well. I'm trying to limit or "group by" the first column "value". value_rk is my big problem since every value is unique but I only need one.</p> <p>NOTE: value_rk is not a number, hence this DOES NOT WORK</p> <p>UPDATE: I've got a working version, it's probably quite a bit slower than a pure SQL version, but honestly anything working at this point is better than nothing. It takes the results from the first query, does a second query except limiting it's results to one, and grabs a matching value_rk for the value that matches. Like so:</p> <pre><code>&lt;cfquery name="queryBaseValues" datasource="XXX" timeout="999"&gt; SELECT DISTINCT value, attribute_definition_id FROM attribute_values ORDER BY attribute_definition_id &lt;/cfquery&gt; &lt;cfoutput query="queryBaseValues"&gt; &lt;cfquery name="queryRKValue" datasource="XXX"&gt; SELECT TOP 1 value_rk FROM attribute_values WHERE value = '#queryBaseValues.value#' &lt;/cfquery&gt; &lt;cfset resourceKey = queryRKValue.value_rk&gt; ... </code></pre> <p>So there you have it, selecting a single column distinctly in ColdFusion. Any pure SQL Server 2000/2005 suggestions are still very welcome :)</p>
[ { "answer_id": 251290, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 1, "selected": false, "text": "SELECT value, attribute_definition_id, value_rk\nFROM attribute_values\nWHERE value, value_rk IN (\n SELECT value, max(value_rk)\n FROM attribute_values\n GROUP BY value\n)\nORDER BY attribute_definition_id\n" }, { "answer_id": 251293, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 2, "selected": false, "text": "SELECT value, attribute_definition_id, value_rk\nFROM attribute_values av1\nWHERE value_rk IN (\n SELECT max(value_rk)\n FROM attribute_values av2\n WHERE av2.value = av1.value\n)\nORDER BY attribute_definition_id\n" }, { "answer_id": 251301, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "SELECT a1.value, a1.attribute_definition_id, a1.value_rk\nFROM attribute_values AS a1\n LEFT OUTER JOIN attribute_values AS a2\n ON (a1.value = a2.value AND a1.value_rk < a2.value_rk)\nWHERE a2.value IS NULL\nORDER BY a1.attribute_definition_id;\n a1 a2 value value_rk" }, { "answer_id": 251316, "author": "Adam", "author_id": 30084, "author_profile": "https://Stackoverflow.com/users/30084", "pm_score": 1, "selected": false, "text": "SELECT value, attribute_definition_id, value_rk\nFROM attribute_values\nGROUP BY value\nORDER BY attribute_definition_id;\n" }, { "answer_id": 251319, "author": "Patryk Kordylewski", "author_id": 30927, "author_profile": "https://Stackoverflow.com/users/30927", "pm_score": 3, "selected": false, "text": "SELECT DISTINCT ON (value)\n value, \n attribute_definition_id, \n value_rk\nFROM \n attribute_values\nORDER BY\n value, \n attribute_definition_id\n" }, { "answer_id": 251370, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 2, "selected": false, "text": "SELECT value_rk, MIN(value) as value, MIN(attribute_definition_id) as attribute_definition_id\nFROM attribute_values\nGROUP BY value_rk\nORDER BY MIN(attribute_definition_id)\n" }, { "answer_id": 251856, "author": "walming", "author_id": 24595, "author_profile": "https://Stackoverflow.com/users/24595", "pm_score": 5, "selected": true, "text": "SELECT DISTINCT a.value, a.attribute_definition_id, \n (SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk\nFROM attribute_values as a\nORDER BY attribute_definition_id\n" }, { "answer_id": 266933, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 2, "selected": false, "text": "DECLARE @attribute_values TABLE (value int, attribute_definition_id int, value_rk uniqueidentifier)\n\nINSERT INTO @attribute_values (value)\nSELECT DISTINCT value FROM attribute_values\n\nUPDATE @attribute_values\nSET attribute_definition_id = av2.attribute_definition_id,\n value_rk = av2.value_rk\nFROM @attribute_values av1\nINNER JOIN attribute_values av2 ON av1.value = av2.value\n\nSELECT value, attribute_definition_id, value_rk FROM @attribute_values\n" }, { "answer_id": 8756710, "author": "user1133937", "author_id": 1133937, "author_profile": "https://Stackoverflow.com/users/1133937", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT a.value, a.attribute_definition_id, \n(SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk\nFROM attribute_values as a\nORDER BY attribute_definition_id\n" }, { "answer_id": 12221134, "author": "Corwin Joy", "author_id": 150709, "author_profile": "https://Stackoverflow.com/users/150709", "pm_score": 0, "selected": false, "text": "SELECT value_rk, MIN(value) as value, \nMIN(attribute_definition_id) as attribute_definition_id\nFROM attribute_values\nGROUP BY value_rk\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631/" ]
251,298
<p>I noticed the specificaition for Collections.sort:</p> <pre><code>public static &lt;T&gt; void sort(List&lt;T&gt; list, Comparator&lt;? super T&gt; c) </code></pre> <p>Why is the "<code>? super</code>" necessary here? If <code>ClassB</code> extends <code>ClassA</code>, then wouldn't we have a guarantee that a <code>Comparator&lt;ClassA&gt;</code> would be able to compare two <code>ClassB</code> objects anyway, without the "<code>? super</code>" part?</p> <p>In other words, given this code:</p> <pre><code>List&lt;ClassB&gt; list = . . . ; Comparator&lt;ClassA&gt; comp = . . . ; Collections.sort(list, comp); </code></pre> <p>why isn't the compiler smart enough to know that this is OK even without specifying "<code>? super</code>" for the declaration of Collections.sort()?</p>
[ { "answer_id": 251328, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "extends super ? extends T ? super T" }, { "answer_id": 251342, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "Comparator T Comparator <T> <? super T> Comparator <? super T>" }, { "answer_id": 251355, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "Dog extends Animal Blah<Dog> Blah<Animal> Dog Animal Blah<T> T Clone(); \n Blah<Dog> Dog Clone(); Blah<Animal> Animal Clone(); Blah<Dog> Blah<Animal> <? super T> Blah<? super T> Blah<out T>" }, { "answer_id": 251714, "author": "Kris Nuttycombe", "author_id": 390636, "author_profile": "https://Stackoverflow.com/users/390636", "pm_score": 0, "selected": false, "text": "List<Integer> ints = Arrays.asList(1,2,3);\nComparator<Number> numberComparator = ...;\n\nCollections.sort(ints, numberComparator);\n Comparator<Integer>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
251,307
<p>I have a resource handler that is Response.WriteFile(fileName) based on a parameter passed through the querystring. I am handling the mimetype correctly, but the issue is in some browsers, the filename comes up as Res.ashx (The name of the handler) instead of MyPdf.pdf (the file I am outputting). Can someone inform me how to change the name of the file when it is sent back to the server? Here is my code:</p> <pre><code>// Get the name of the application string application = context.Request.QueryString["a"]; string resource = context.Request.QueryString["r"]; // Parse the file extension string[] extensionArray = resource.Split(".".ToCharArray()); // Set the content type if (extensionArray.Length &gt; 0) context.Response.ContentType = MimeHandler.GetContentType( extensionArray[extensionArray.Length - 1].ToLower()); // clean the information application = (string.IsNullOrEmpty(application)) ? "../App_Data/" : application.Replace("..", ""); // clean the resource resource = (string.IsNullOrEmpty(resource)) ? "" : resource.Replace("..", ""); string url = "./App_Data/" + application + "/" + resource; context.Response.WriteFile(url); </code></pre>
[ { "answer_id": 251364, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 3, "selected": true, "text": "context.Response.AddHeader(\"content-disposition\", \"attachment; filename=\" + resource);\n" }, { "answer_id": 251388, "author": "Matthew Kruskamp", "author_id": 22521, "author_profile": "https://Stackoverflow.com/users/22521", "pm_score": 0, "selected": false, "text": "if (extensionArray[extensionArray.Length - 1].ToLower() == \"pdf\")\n context.Response.AddHeader(\"content-disposition\", \n \"Attachment; filename=\" + resource);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22521/" ]
251,313
<p>Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript?</p> <pre><code>function getSomethingAsync(someState, callback) { var req = abc.createRequestObject(someParams); req.invoke(makeCallback(someState, callback)); } function makeCallback(someState, callback) { return function getSomethingCallback(data) { var result = processDataUsingState(data, someState); callback(result); // alternately/optionally pass someState along to result } } </code></pre> <p>If not, is there a better or more idiomatic way?</p>
[ { "answer_id": 251347, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "function getSomethingAsync (someState, callback) {\n req.invoke (function (data) {\n var result = processDataUsingState (data, someState);\n callback (result);\n });\n}\n" }, { "answer_id": 8930571, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 1, "selected": false, "text": "Function.bind /**\n * Retrieves the content of a url asyunchronously\n * The callback will be called with one parameter: the html retrieved\n */\nfunction getUrl(url, callback) {\n $.ajax({url: url, success: function(data) {\n callback(data);\n }}) \n}\n\n// Now lets' call getUrl twice, specifying the same \n// callback but a different id will be passed to each\nfunction updateHtml(id, html) {\n $('#' + id).html(html);\n}\n\n\n// By calling bind on the callback, updateHTML will be called with \n// the parameters you passed to it, plus the parameters that are used\n// when the callback is actually called (inside )\n// The first parameter is the context (this) to use, since we don't care,\n// I'm passing in window since it's the default context\ngetUrl('/get/something.html', updateHTML.bind(window, 'node1'));\n// results in updateHTML('node1', 'response HTML here') being called\ngetUrl('/get/something-else.html', updateHTML.bind(window, 'node2'));\n// results in updateHTML('node2', 'response HTML here') being called\n Function.bind Function.bind" }, { "answer_id": 8965087, "author": "pete otaqui", "author_id": 484190, "author_profile": "https://Stackoverflow.com/users/484190", "pm_score": 0, "selected": false, "text": "function getSomethingAsync(callback, scope) {\n var req = abc.createRequestObject(someParams);\n req.invoke(function(rsp) {\n callback.apply(scope, [rsp]);\n });\n}\n\n// usage:\ngetSomethingAsync(function() {console.log(this.someState)}, {someState:'value'});\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
251,317
<p>When I try to use <code>curl</code> or <code>file_get_contents</code> to read something like <a href="http://example.com/python/json/" rel="nofollow noreferrer">http://example.com/python/json/</a> from <a href="http://example.com/" rel="nofollow noreferrer">http://example.com/</a> I should be getting a JSON response, but instead I get a 404 error. Using curl or any other method outside my own domain works perfectly well.</p> <pre><code>echo file_get_contents('http://example.com/python/json/'); =&gt; 404 echo file_get_contents('http://google.com'); =&gt; OK </code></pre> <p>The same script works on my laptop, but I can't figure out what the difference is.</p>
[ { "answer_id": 251327, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 3, "selected": true, "text": "$curl = curl_init();\ncurl_setopt($curl, CURLOPT_URL, 'http://example.com/');\ncurl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);\n$result = curl_exec($curl);\ncurl_close($curl);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ]
251,325
<p>So let's say I have two different functions. One is a part of the BST class, one is just a helper function that will call on that Class function. I will list them out here.</p> <pre><code>sieve(BST&lt;T&gt;* t, int n); </code></pre> <p>this function is called like this: sieve(t,n) the object is called BST t; </p> <p>I'm going to be using the class remove function within the sieve function to remove specific objects. I'm not sure what my prototype for this basic function should look like? Doing this:</p> <pre><code>sieve(BST&lt;int&gt; t, int n) </code></pre> <p>What happens here is everything compiles just fine, but when t.remove function is called I see no actual results. I'm assuming because it's just creating a copy or a whole other t object instead of passing the one from my main() function.</p> <p>If I call the remove function (t.remove(value)) in my main function where the original object was created it removes everything properly. Once I start doing it through my sieve function I see no change when I re print it out from my main function. So my main function looks something like this:</p> <pre><code>int main () { int n, i, len; BST&lt;int&gt; t; cin &gt;&gt; n; vector&lt;int&gt; v(n); srand(1); for (i = 0; i &lt; n; i++) v[i] = rand() % n; for (i = 0; i &lt; n; i++) t.insert(v[i]); print_stat(t); t.inOrder(print_data); sieve(v,t,n); print_stat(t); t.inOrder(print_data); return 0; } </code></pre> <p>So my results end up being the same, even though my debug statements within the functions show it's actually deleting something. I'm guessing where I'm going wrong is how I am passing the t object onto the function.</p>
[ { "answer_id": 251335, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "sieve(BST<int>& t, int n)\n &" }, { "answer_id": 251350, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "/* missing return type */ sieve<BST<int> t, int n);\n BST<int> sieve() void sieve<BST<int> & t, int n);\n t sieve() BST<>" }, { "answer_id": 251352, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 2, "selected": false, "text": "BST t; \nsieve(BST<T> *t, int n);\n sieve(&t,n)\n t BST t; \nsieve(BST<T> &t, int n);\n sieve(t,n)\n t" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
251,336
<p>How do I discover classes at runtime in the classpath which implements a defined interface?</p> <p>ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.</p>
[ { "answer_id": 251691, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "ServiceLoader public <S> Iterable<S> load(Class<S> ifc) throws Exception {\n ClassLoader ldr = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> e = ldr.getResources(\"META-INF/services/\" + ifc.getName());\n Collection<S> services = new ArrayList<S>();\n while (e.hasMoreElements()) {\n URL url = e.nextElement();\n InputStream is = url.openStream();\n try {\n BufferedReader r = new BufferedReader(new InputStreamReader(is, \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null)\n break;\n int comment = line.indexOf('#');\n if (comment >= 0)\n line = line.substring(0, comment);\n String name = line.trim();\n if (name.length() == 0)\n continue;\n Class<?> clz = Class.forName(name, true, ldr);\n Class<? extends S> impl = clz.asSubclass(ifc);\n Constructor<? extends S> ctor = impl.getConstructor();\n S svc = ctor.newInstance();\n services.add(svc);\n }\n }\n finally {\n is.close();\n }\n }\n return services;\n}\n" }, { "answer_id": 5246753, "author": "Marco Hunsicker", "author_id": 651652, "author_profile": "https://Stackoverflow.com/users/651652", "pm_score": 3, "selected": false, "text": "javax.imageio.spi.ServiceRegistry ServiceLoader" }, { "answer_id": 6534230, "author": "Petrychenko", "author_id": 730929, "author_profile": "https://Stackoverflow.com/users/730929", "pm_score": 1, "selected": false, "text": "sun.misc.Service JRockit" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
251,338
<p>I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path). This doesn't need to work cross platform; only in Windows.</p> <p>I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.</p> <p>I can get the free space available by doing:</p> <blockquote> <p>cmd.exe /c Z:\ /-c</p> <p>or</p> <p>cmd.exe /c \\server\share /-c</p> </blockquote> <p>and just parsing out the resulting bytes free. However I can't seem to find a way to get the total drive size.</p> <p>Any suggestions?</p>
[ { "answer_id": 251447, "author": "DMKing", "author_id": 10887, "author_profile": "https://Stackoverflow.com/users/10887", "pm_score": 3, "selected": true, "text": "D:\\>fsutil fsinfo ntfsinfo c:\nNTFS Volume Serial Number : 0xd49cf9cf9cf9ac5c\nVersion : 3.1\nNumber Sectors : 0x0000000004a813ff\nTotal Clusters : 0x000000000095027f\nFree Clusters : 0x00000000002392f5\nTotal Reserved : 0x0000000000000490\nBytes Per Sector : 512\nBytes Per Cluster : 4096\nBytes Per FileRecord Segment : 1024\nClusters Per FileRecord Segment : 0\nMft Valid Data Length : 0x000000000e70c000\nMft Start Lcn : 0x00000000000c0000\nMft2 Start Lcn : 0x0000000000000010\nMft Zone Start : 0x0000000000624ea0\nMft Zone End : 0x0000000000643da0\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14007/" ]
251,343
<p>I am investigating GDI leaks issue in one of our smart-client application. I am looking for a tool (like <strong>tasklist</strong>) to get the GDI objects associated to a process. I can see the GDI objects in taskmanager, But my requirement to capture it periodically somewhere. For example in a text file.</p>
[ { "answer_id": 400630, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "GDI Objects GDI Objects Process Memory Select Columns" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31001/" ]
251,345
<p>Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it.</p> <p>Is there a 'proper' Rails way?</p>
[ { "answer_id": 251518, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 7, "selected": false, "text": "MyModel.find(:all, :conditions => [\"field LIKE ?\", \"#{prefix}%\"])\n prefix MyModel.where(\"field LIKE :prefix\", prefix: \"#{prefix}%\")\n" }, { "answer_id": 251556, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 4, "selected": true, "text": "@search = Model.new_search(params[:search])\n@search.condition.field_starts_with = \"prefix\"\n@models = @search.all\n starts_with" }, { "answer_id": 898345, "author": "narsk", "author_id": 110123, "author_profile": "https://Stackoverflow.com/users/110123", "pm_score": 3, "selected": false, "text": "class User\n named_scope :with_name_like, lambda {|str|\n :conditions => ['lower(name) like ?', %(%#{str.downcase}%)]\n }\nend\n User.with_name_like(\"Samson\")\n some_association.users.with_name_like(\"Samson\")\n" }, { "answer_id": 6959671, "author": "Larry", "author_id": 838196, "author_profile": "https://Stackoverflow.com/users/838196", "pm_score": 3, "selected": false, "text": "# name_searchable.rb\n# mix this into your class using\n# extend NameSearchable\nmodule NameSearchable\n def search_by_prefix (prefix)\n self.where(\"lower(name) LIKE '#{prefix.downcase}%'\")\n end\nend\n class User < ActiveRecord::Base\n extend NameSearchable\n ...\nend\n User.search_by_prefix('John') #or\nUser.search_by_prefix(\"#{name_str}\")\n" }, { "answer_id": 12223406, "author": "Dave Sag", "author_id": 917187, "author_profile": "https://Stackoverflow.com/users/917187", "pm_score": 2, "selected": false, "text": "named_scope scope class User\n scope :name_starts_with, lambda {|str|\n :conditions => ['lower(name) like ?', \"#{str.downcase}%\"]\n }\nend\n % User.name_starts_with(\"b\").each do {|bs| puts bs.inspect}\nbob = User.name_starts_with(\"bob\").first\n\n… etc\n" }, { "answer_id": 14882525, "author": "Oriettaxx", "author_id": 1761229, "author_profile": "https://Stackoverflow.com/users/1761229", "pm_score": 1, "selected": false, "text": "class User\n scope :name_starts_with, (lambda do |str|\n {:conditions => ['lower(name) like ?', \"#{str.downcase}%\"]}\n end )\nend\n" }, { "answer_id": 24322687, "author": "bert bruynooghe", "author_id": 306730, "author_profile": "https://Stackoverflow.com/users/306730", "pm_score": 1, "selected": false, "text": "Model.where(field: ('prefix'...'prefiy'))\n WHERE ( field >= 'prefix' AND field < 'prefiy')\n" }, { "answer_id": 26679117, "author": "Abdo", "author_id": 226255, "author_profile": "https://Stackoverflow.com/users/226255", "pm_score": 3, "selected": false, "text": "# initializers/active_record_initializers.rb\nclass ActiveRecord::Base\n # do not accept a column_name from the outside without sanitizing it\n # as this can be prone to sql injection\n def self.starts_with(column_name, prefix)\n where(\"lower(#{column_name}) like ?\", \"#{prefix.downcase}%\")\n end\nend\n User.starts_with('name', 'ab').limit(1)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
251,346
<p>What would be the best hashing algorithm if we had the following priorities (in that order):</p> <ol> <li>Minimal hash collisions</li> <li>Performance</li> </ol> <p>It doesn't have to be secure. Basically I'm trying to create an index based on a combination of properties of some objects. <strong>All the properties are strings</strong>.</p> <p>Any references to c# implementations would be appreciated.</p>
[ { "answer_id": 251394, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": " /**\n * Computes the hashcode for this String. This is done with int arithmetic,\n * where ** represents exponentiation, by this formula:<br>\n * <code>s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]</code>.\n *\n * @return hashcode value of this String\n */\n public int hashCode()\n {\n if (cachedHashCode != 0)\n return cachedHashCode;\n\n // Compute the hash code using a local variable to be reentrant.\n int hashCode = 0;\n int limit = count + offset;\n for (int i = offset; i < limit; i++)\n hashCode = hashCode * 31 + value[i];\n return cachedHashCode = hashCode;\n }\n" }, { "answer_id": 251404, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "int hashCode = 0;\n\nforeach (string s in propertiesToHash) {\n hashCode = 31*hashCode + s.GetHashCode();\n}\n combinedHash = ((combinedHash << 5) + combinedHash) ^ nextObj.GetHashCode();\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8911/" ]
251,351
<p>Is there a way of ordering a list of objects by a count of a property which is a collection? </p> <p>For arguments sake let's say I have a question object with a question name property, a property that is a collection of answer objects and another property that is a collection of user objects. The users join the question table via foreign key on question table and answers are joined with middle joining table. </p> <p>If I want nhibernate to get a list of "question" objects could I order it by Question.Answers.Count?</p> <p>i've tried the documentation's example using HQL:</p> <pre><code> List&lt;Question&gt; list = nhelper.NHibernateSession .CreateQuery("Select q from Question q left join q.Answers a group by q,a order by count(a)") .List&lt;Question&gt;(); </code></pre> <p>but i get </p> <pre><code>"column Question.Name is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" </code></pre> <p>I've tried adding all the properties to the group by list but it doesn't work. What happens then is that foreign key userId causes the same error as above but i can't include it in the group by as nhibernate lists it as </p> <pre><code>Question.Users.UserId </code></pre> <p>which doesn't solve it if included. </p> <p>any ideas?</p>
[ { "answer_id": 251394, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": " /**\n * Computes the hashcode for this String. This is done with int arithmetic,\n * where ** represents exponentiation, by this formula:<br>\n * <code>s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]</code>.\n *\n * @return hashcode value of this String\n */\n public int hashCode()\n {\n if (cachedHashCode != 0)\n return cachedHashCode;\n\n // Compute the hash code using a local variable to be reentrant.\n int hashCode = 0;\n int limit = count + offset;\n for (int i = offset; i < limit; i++)\n hashCode = hashCode * 31 + value[i];\n return cachedHashCode = hashCode;\n }\n" }, { "answer_id": 251404, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "int hashCode = 0;\n\nforeach (string s in propertiesToHash) {\n hashCode = 31*hashCode + s.GetHashCode();\n}\n combinedHash = ((combinedHash << 5) + combinedHash) ^ nextObj.GetHashCode();\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32835/" ]
251,356
<p>I'm new to ASP.NET MVC so this may be a stupid question.</p> <p>I have an account object that has many parameters. I've figured out a strategy to break this down into a "wizard"-like interface that will walk a user through collecting the required fields to create the initial business objects. It will then step through pages to collect other, optional, parameters. This way the user isn't faced with a single page on which they have to enter 30 things (I'm probably exaggerating the number, but you get the idea).</p> <p>Still, the first page is going to have 10-12 items that the user needs to fill out before I can fill in all the required fields on the 2-3 business objects that accompany a successful registration. Basically, a new user needs to both get an account AND register for an event at the same time, thus the number of items.</p> <p>In ASP.NET MVC it appears that all of my form parameters map onto method parameters in the controller method. Knowing that methods with lots of parameters are considered a <em>code smell</em> that ought to be refactored out, I'm wondering if there is a different way to accomplish this or if I'm stuck with a controller method that has a one-to-one mapping between form parameters and method parameters.</p> <p>Is there a good known pattern that I've missed in my Google searches to solve this problem?</p>
[ { "answer_id": 251916, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 0, "selected": false, "text": "Request.Form(\"key\");\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12950/" ]
251,359
<p>Lets say I have an EJB application which defines some entities and relations among them. I figured the DB schema can easily be created from the entities. So now the app works but after a while a need to change some relations, e.g. a one-to-one needs to become a one-to-many, can I upgrade my DB to do so WITHOUT losing the old data?</p>
[ { "answer_id": 251916, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 0, "selected": false, "text": "Request.Form(\"key\");\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
251,379
<p>I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this:</p> <p>What is the benefit to use databinding from sql queries directly to a control over querying and manually adding items to the control? Is this approach generally considered cleaner, and simpler in terms of deploying? Will there still be cases where manually adding would give more fine grained control over the display / value of the data?</p> <p>I'm asking because I've been assigned some bugs that deal with some controls that populate themselves based off query results, and would love to clean up unnecessary logic and push that off to the libraries to handle instead of me.</p> <p>Note: We are using .NET 2.0</p>
[ { "answer_id": 251452, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 4, "selected": true, "text": "control.DataSource = YourSource;\ncontrol.DataBind();\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
251,391
<p>The <a href="https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/c5kehkcz(v=vs.110)" rel="noreferrer">MSDN documentation</a> says that</p> <pre><code>public class SomeObject { public void SomeOperation() { lock(this) { //Access instance variables } } } </code></pre> <p>is &quot;a problem if the instance can be accessed publicly&quot;. I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?</p>
[ { "answer_id": 251399, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": false, "text": "this this List<int>" }, { "answer_id": 251412, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 5, "selected": false, "text": "lock(typeof(SomeObject))\n" }, { "answer_id": 251668, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 10, "selected": true, "text": "this this this lock(this) lock lock Object public class Person\n{\n public int Age { get; set; }\n public string Name { get; set; }\n\n public void LockThis()\n {\n lock (this)\n {\n System.Threading.Thread.Sleep(10000);\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var nancy = new Person {Name = \"Nancy Drew\", Age = 15};\n var a = new Thread(nancy.LockThis);\n a.Start();\n var b = new Thread(Timewarp);\n b.Start(nancy);\n Thread.Sleep(10);\n var anotherNancy = new Person { Name = \"Nancy Drew\", Age = 50 };\n var c = new Thread(NameChange);\n c.Start(anotherNancy);\n a.Join();\n Console.ReadLine();\n }\n\n static void Timewarp(object subject)\n {\n var person = subject as Person;\n if (person == null) throw new ArgumentNullException(\"subject\");\n // A lock does not make the object read-only.\n lock (person.Name)\n {\n while (person.Age <= 23)\n {\n // There will be a lock on 'person' due to the LockThis method running in another thread\n if (Monitor.TryEnter(person, 10) == false)\n {\n Console.WriteLine(\"'this' person is locked!\");\n }\n else Monitor.Exit(person);\n person.Age++;\n if(person.Age == 18)\n {\n // Changing the 'person.Name' value doesn't change the lock...\n person.Name = \"Nancy Smith\";\n }\n Console.WriteLine(\"{0} is {1} years old.\", person.Name, person.Age);\n }\n }\n }\n\n static void NameChange(object subject)\n {\n var person = subject as Person;\n if (person == null) throw new ArgumentNullException(\"subject\");\n // You should avoid locking on strings, since they are immutable.\n if (Monitor.TryEnter(person.Name, 30) == false)\n {\n Console.WriteLine(\"Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \\\"Nancy Drew\\\".\");\n }\n else Monitor.Exit(person.Name);\n\n if (Monitor.TryEnter(\"Nancy Drew\", 30) == false)\n {\n Console.WriteLine(\"Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!\");\n }\n else Monitor.Exit(\"Nancy Drew\");\n if (Monitor.TryEnter(person.Name, 10000))\n {\n string oldName = person.Name;\n person.Name = \"Nancy Callahan\";\n Console.WriteLine(\"Name changed from '{0}' to '{1}'.\", oldName, person.Name);\n }\n else Monitor.Exit(person.Name);\n }\n}\n 'this' person is locked!\nNancy Drew is 16 years old.\n'this' person is locked!\nNancy Drew is 17 years old.\nFailed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\".\n'this' person is locked!\nNancy Smith is 18 years old.\n'this' person is locked!\nNancy Smith is 19 years old.\n'this' person is locked!\nNancy Smith is 20 years old.\nFailed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!\n'this' person is locked!\nNancy Smith is 21 years old.\n'this' person is locked!\nNancy Smith is 22 years old.\n'this' person is locked!\nNancy Smith is 23 years old.\n'this' person is locked!\nNancy Smith is 24 years old.\nName changed from 'Nancy Drew' to 'Nancy Callahan'.\n" }, { "answer_id": 9870883, "author": "SOReader", "author_id": 190281, "author_profile": "https://Stackoverflow.com/users/190281", "pm_score": 0, "selected": false, "text": "lock(this) lock(this)" }, { "answer_id": 10510647, "author": "Craig Tullis", "author_id": 618649, "author_profile": "https://Stackoverflow.com/users/618649", "pm_score": 5, "selected": false, "text": "lock(typeof(SomeObject)) lock(this) lock(typeof(SomeObject)) System.Type lock(this) lock(typeof(SomeObject))" }, { "answer_id": 17031960, "author": "Raj Rao", "author_id": 44815, "author_profile": "https://Stackoverflow.com/users/44815", "pm_score": 1, "selected": false, "text": "void Main()\n{\n //demonstrates why locking on THIS is BADD! (you should never lock on something that is publicly accessible)\n ClassTest test = new ClassTest();\n lock(test) //locking on the instance of ClassTest\n {\n Console.WriteLine($\"CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Parallel.Invoke(new Action[]\n {\n () => {\n //this is there to just use up the current main thread. \n Console.WriteLine($\"CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n },\n //none of these will enter the lock section.\n () => test.DoWorkUsingThisLock(1),//this will dead lock as lock(x) uses Monitor.Enter\n () => test.DoWorkUsingMonitor(2), //this will not dead lock as it uses Montory.TryEnter\n });\n }\n}\n\npublic class ClassTest\n{\n public void DoWorkUsingThisLock(int i)\n {\n Console.WriteLine($\"Start ClassTest.DoWorkUsingThisLock {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n lock(this) //this can be bad if someone has locked on this already, as it will cause it to be deadlocked!\n {\n Console.WriteLine($\"Running: ClassTest.DoWorkUsingThisLock {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Thread.Sleep(1000);\n }\n Console.WriteLine($\"End ClassTest.DoWorkUsingThisLock Done {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n }\n\n public void DoWorkUsingMonitor(int i)\n {\n Console.WriteLine($\"Start ClassTest.DoWorkUsingMonitor {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n if (Monitor.TryEnter(this))\n {\n Console.WriteLine($\"Running: ClassTest.DoWorkUsingMonitor {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Thread.Sleep(1000);\n Monitor.Exit(this);\n }\n else\n {\n Console.WriteLine($\"Skipped lock section! {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n }\n\n Console.WriteLine($\"End ClassTest.DoWorkUsingMonitor Done {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Console.WriteLine();\n }\n}\n CurrentThread 15\nCurrentThread 15\nStart ClassTest.DoWorkUsingMonitor 2 CurrentThread 13\nStart ClassTest.DoWorkUsingThisLock 1 CurrentThread 12\nSkipped lock section! 2 CurrentThread 13\nEnd ClassTest.DoWorkUsingMonitor Done 2 CurrentThread 13\n" }, { "answer_id": 17062160, "author": "atlaste", "author_id": 1031591, "author_profile": "https://Stackoverflow.com/users/1031591", "pm_score": 3, "selected": false, "text": "lock(this) private protected internal public private [static] object myLock = new object();" }, { "answer_id": 22585601, "author": "ItsAllABadJoke", "author_id": 1070409, "author_profile": "https://Stackoverflow.com/users/1070409", "pm_score": 2, "selected": false, "text": " static void Main(string[] args)\n {\n TestThreading();\n Console.ReadLine();\n }\n\n public static void TestThreading()\n {\n Random rand = new Random();\n Thread[] threads = new Thread[10];\n TestLock.balance = 100000;\n for (int i = 0; i < 10; i++)\n {\n TestLock tl = new TestLock();\n Thread t = new Thread(new ThreadStart(tl.WithdrawAmount));\n threads[i] = t;\n }\n for (int i = 0; i < 10; i++)\n {\n threads[i].Start();\n }\n Console.Read();\n }\n class TestLock\n{\n public static int balance { get; set; }\n public static readonly Object myLock = new Object();\n\n public void Withdraw(int amount)\n {\n // Try both locks to see what I mean\n // lock (this)\n lock (myLock)\n {\n Random rand = new Random();\n if (balance >= amount)\n {\n Console.WriteLine(\"Balance before Withdrawal : \" + balance);\n Console.WriteLine(\"Withdraw : -\" + amount);\n balance = balance - amount;\n Console.WriteLine(\"Balance after Withdrawal : \" + balance);\n }\n else\n {\n Console.WriteLine(\"Can't process your transaction, current balance is : \" + balance + \" and you tried to withdraw \" + amount);\n }\n }\n\n }\n public void WithdrawAmount()\n {\n Random rand = new Random();\n Withdraw(rand.Next(1, 100) * 100);\n }\n}\n Balance before Withdrawal : 100000\n Withdraw : -5600\n Balance after Withdrawal : 94400\n Balance before Withdrawal : 100000\n Balance before Withdrawal : 100000\n Withdraw : -5600\n Balance after Withdrawal : 88800\n Withdraw : -5600\n Balance after Withdrawal : 83200\n Balance before Withdrawal : 83200\n Withdraw : -9100\n Balance after Withdrawal : 74100\n Balance before Withdrawal : 74100\n Withdraw : -9100\n Balance before Withdrawal : 74100\n Withdraw : -9100\n Balance after Withdrawal : 55900\n Balance after Withdrawal : 65000\n Balance before Withdrawal : 55900\n Withdraw : -9100\n Balance after Withdrawal : 46800\n Balance before Withdrawal : 46800\n Withdraw : -2800\n Balance after Withdrawal : 44000\n Balance before Withdrawal : 44000\n Withdraw : -2800\n Balance after Withdrawal : 41200\n Balance before Withdrawal : 44000\n Withdraw : -2800\n Balance after Withdrawal : 38400\n Balance before Withdrawal : 100000\nWithdraw : -6600\nBalance after Withdrawal : 93400\nBalance before Withdrawal : 93400\nWithdraw : -6600\nBalance after Withdrawal : 86800\nBalance before Withdrawal : 86800\nWithdraw : -200\nBalance after Withdrawal : 86600\nBalance before Withdrawal : 86600\nWithdraw : -8500\nBalance after Withdrawal : 78100\nBalance before Withdrawal : 78100\nWithdraw : -8500\nBalance after Withdrawal : 69600\nBalance before Withdrawal : 69600\nWithdraw : -8500\nBalance after Withdrawal : 61100\nBalance before Withdrawal : 61100\nWithdraw : -2200\nBalance after Withdrawal : 58900\nBalance before Withdrawal : 58900\nWithdraw : -2200\nBalance after Withdrawal : 56700\nBalance before Withdrawal : 56700\nWithdraw : -2200\nBalance after Withdrawal : 54500\nBalance before Withdrawal : 54500\nWithdraw : -500\nBalance after Withdrawal : 54000\n" }, { "answer_id": 27279352, "author": "Dhruv Rangunwala", "author_id": 2174507, "author_profile": "https://Stackoverflow.com/users/2174507", "pm_score": 1, "selected": false, "text": "lock (lockObject)\n{\n...\n}\n" }, { "answer_id": 51567344, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "class SomeClass\n{\n public void SomeMethod(int id)\n {\n **lock(this)**\n {\n while(true)\n {\n Console.WriteLine(\"SomeClass.SomeMethod #\" + id);\n }\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n SomeClass o = new SomeClass();\n\n lock(o)\n {\n for (int threadId = 0; threadId < 3; threadId++)\n {\n Thread t = new Thread(() => {\n o.SomeMethod(threadId);\n });\n t.Start();\n }\n\n Console.WriteLine();\n }\n Monitor.TryEnter(temp, millisecondsTimeout, ref lockWasTaken);\n if (lockWasTaken)\n {\n doAction();\n }\n else\n {\n throw new Exception(\"Could not get lock\");\n }\n" }, { "answer_id": 71479913, "author": "Rzassar", "author_id": 862795, "author_profile": "https://Stackoverflow.com/users/862795", "pm_score": -1, "selected": false, "text": "object foo = new Object(); \nobject bar = foo; \n\nlock(foo)\n{\n lock(bar){}\n} \n SomeClass someObject someObject SomeMethod() .Wait() SomeClass this using System;\n using System.Threading;\n using System.Threading.Tasks;\n\n class SomeClass\n {\n public void SomeMethod()\n {\n //NOTE: Locks over an object that is already locked by the caller.\n // Hence, the following code-block never executes.\n lock (this)\n {\n Console.WriteLine(\"Hi\");\n }\n }\n }\n\n public class Program\n {\n public static void Main()\n {\n SomeClass o = new SomeClass();\n\n lock (o)\n {\n Task.Run(() => o.SomeMethod()).Wait();\n }\n\n Console.WriteLine(\"Finish\");\n }\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341413/" ]
251,395
<p>Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings?</p> <p>Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc</p> <p>Thanks</p>
[ { "answer_id": 251410, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 4, "selected": true, "text": "if (!String.IsNullOrEmpty(Request.Querystring[\"foo\"]))\n{\n // check further\n}\nelse\n{\n // not there, do something else\n}\n public static Boolean IsValid(String s)\n{\n const String sRegEx = @\"regex here\";\n\n Regex oRegEx = new Regex(sRegEx , RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n MatchCollection oMatches = oRegEx.Matches(s);\n\n return (oMatches.Count > 0) ? true : false;\n}\n" }, { "answer_id": 251575, "author": "denny", "author_id": 27, "author_profile": "https://Stackoverflow.com/users/27", "pm_score": 2, "selected": false, "text": " if (!string.IsNullOrEmpty(Request.QueryString[\"Variable\"]))\n {\n string s = Request.QueryString[\"Variable\"];\n\n Regex regularExpression = new Regex(\"Put your regex here\");\n\n if (regularExpression.IsMatch(s))\n {\n // Do what you want.\n }\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
251,396
<p>I am currently developing a Java app which handles a SOAP webservice. </p> <p>The problem lies after I parse the WSDL [the <strong>Parser</strong> object from Apache Axis does it for me], and I create the call. </p> <p>When I try to invoke it, I have to pass a Object[] to assign the parameters [taken from the Action of the WSDL]. A normal action is easy, but when I have custom datatypes, I can't get it to fill it out for me. I try to pass Object[]{ new Object { }}, but it assigns the first field instead. I can't pass it already processed, because it changes the '&lt; >' to '--lt --gt', and the server doesn't recognize it'.</p> <p>This is a fragment of the WSDL.</p> <blockquote> <pre><code> &lt;s:element name="FERecuperaQTYRequest"&gt; &lt;s:complexType&gt; &lt;s:sequence&gt; &lt;s:element minOccurs="0" maxOccurs="1" name="argAuth" type="tns:FEAuthRequest" /&gt; &lt;/s:sequence&gt; &lt;/s:complexType&gt; &lt;/s:element&gt; &lt;s:complexType name="FEAuthRequest"&gt; &lt;s:sequence&gt; &lt;s:element minOccurs="0" maxOccurs="1" name="Token" type="s:string" /&gt; &lt;s:element minOccurs="0" maxOccurs="1" name="Sign" type="s:string" /&gt; &lt;s:element minOccurs="1" maxOccurs="1" name="cuit" type="s:long" /&gt; &lt;/s:sequence&gt; &lt;/s:complexType&gt; </code></pre> </blockquote> <p>And this is the troublesome Java Fragment</p> <pre><code> QTY = (String) call.invoke ( new Object[]{ new Object[]{ tokenConexion.getToken (), tokenConexion.getSign (), tokenConexion.getCUIT () } }); </code></pre>
[ { "answer_id": 251443, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<bean id=\"myService\" class=\"org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean\">\n <property name=\"serviceFactoryClass\" value=\"org.apache.axis.client.ServiceFactory\"/>\n <property name=\"wsdlDocumentUrl\" value=\"classpath://META-INF/myService.wsdl\"/>\n <property name=\"namespaceUri\" value=\"http://com/myService\"/>\n <property name=\"endpointAddress\" value=\"http://server/MyService\"/>\n <property name=\"serviceName\" value=\"MyService\"/>\n <property name=\"portName\" value=\"MyService\"/>\n <property name=\"serviceInterface\" value=\"com.IMyService\"/>\n <property name=\"lookupServiceOnStartup\" value=\"false\"/>\n</bean>\n<bean id=\"myClient\" class=\"com.MyServiceClient\">\n <property name=\"myService\" ref=\"myService\"/>\n</bean>\n public interface IMyService {\n Foo getFoo();\n}\n\npublic class MyServiceClient {\n private IMyService myService;\n public void setMyService(IMyService myService) {\n this.myService = myService;\n }\n\n public void DoStuff() {\n Foo foo = myService.getFoo();\n ...\n }\n}\n public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean {\nprotected void postProcessJaxRpcService(Service service) {\n TypeMappingRegistry registry = service.getTypeMappingRegistry();\n TypeMapping mapping = registry.createTypeMapping();\n QName qName = new QName(\"http://com/myService\", \"Foo\");\n mapping.register(Foo.class, qName,\n new BeanSerializerFactory(Foo.class, qName),\n new BeanDeserializerFactory(Foo.class, qName));\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4749/" ]
251,401
<p>Does anyone know of any DLLs (preferably .net) that encapsulate the lua 5.1 compiler? I'm working on a .net project where part of it needs to compile lua scripts, and i would rather have a DLL that i could send script code to instead of sending the script to a temporary file and running luac.exe.</p> <p>Edit: I'd need a .NET library that implements luac in such a way that it outputs standard lua bytecode (not a lua library that compiles to the CLR). Compiling the lua c source code didn't work, as when i went to include a reference to the dll in a c# project, visual studio complained that it wasnt a valid assembly. My searches so far haven't found anything.</p>
[ { "answer_id": 251443, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<bean id=\"myService\" class=\"org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean\">\n <property name=\"serviceFactoryClass\" value=\"org.apache.axis.client.ServiceFactory\"/>\n <property name=\"wsdlDocumentUrl\" value=\"classpath://META-INF/myService.wsdl\"/>\n <property name=\"namespaceUri\" value=\"http://com/myService\"/>\n <property name=\"endpointAddress\" value=\"http://server/MyService\"/>\n <property name=\"serviceName\" value=\"MyService\"/>\n <property name=\"portName\" value=\"MyService\"/>\n <property name=\"serviceInterface\" value=\"com.IMyService\"/>\n <property name=\"lookupServiceOnStartup\" value=\"false\"/>\n</bean>\n<bean id=\"myClient\" class=\"com.MyServiceClient\">\n <property name=\"myService\" ref=\"myService\"/>\n</bean>\n public interface IMyService {\n Foo getFoo();\n}\n\npublic class MyServiceClient {\n private IMyService myService;\n public void setMyService(IMyService myService) {\n this.myService = myService;\n }\n\n public void DoStuff() {\n Foo foo = myService.getFoo();\n ...\n }\n}\n public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean {\nprotected void postProcessJaxRpcService(Service service) {\n TypeMappingRegistry registry = service.getTypeMappingRegistry();\n TypeMapping mapping = registry.createTypeMapping();\n QName qName = new QName(\"http://com/myService\", \"Foo\");\n mapping.register(Foo.class, qName,\n new BeanSerializerFactory(Foo.class, qName),\n new BeanDeserializerFactory(Foo.class, qName));\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19252/" ]
251,402
<p>There are <strong>two different</strong> ways to create an empty object in JavaScript:</p> <pre><code>var objectA = {} var objectB = new Object() </code></pre> <p>Is there any difference in how the script engine handles them? Is there any reason to use one over the other?</p> <p>Similarly it is also possible to create an empty array using different syntax:</p> <pre><code>var arrayA = [] var arrayB = new Array() </code></pre>
[ { "answer_id": 251440, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 4, "selected": false, "text": "new" }, { "answer_id": 251497, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 3, "selected": false, "text": "var objectA = {}\n" }, { "answer_id": 251743, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 3, "selected": false, "text": "{} new var obj = {}; new var Mammal = function (name) {\n this.name = name;\n};\n\nMammal.prototype.get_name = function () {\n return this.name;\n}\n\nMammal.prototype.says = function() {\n return this.saying || '';\n}\n var aMammal = new Mammal('Me warm-blooded');\nvar name = aMammal.get_name();\n {} new Object" }, { "answer_id": 252110, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 10, "selected": true, "text": "new Object(); {}; {} var myObject = {\n title: 'Frog',\n url: '/img/picture.jpg',\n width: 300,\n height: 200\n };\n new Array(); []; var emptyArray = new Array(100);\n undefined (new Array(9)).join('Na-Na ') + 'Batman!' new Object(); {}; [];" }, { "answer_id": 5665204, "author": "Guillermo Snipe", "author_id": 708191, "author_profile": "https://Stackoverflow.com/users/708191", "pm_score": 7, "selected": false, "text": "var objectA = {} //This is an object literal\n\nvar objectB = new Object() //This is the object constructor\n new Object(1) new Object(\"hello\")" }, { "answer_id": 38799700, "author": "basickarl", "author_id": 1137669, "author_profile": "https://Stackoverflow.com/users/1137669", "pm_score": 3, "selected": false, "text": "var arr = []; var arr = new Array(); var arr = new Array(x); var arr = []; arr[x-1] = undefined new Array()" }, { "answer_id": 44992859, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": "object literal constructor {} Object Object(params) {} {} var n = new Object(1); //Number {[[PrimitiveValue]]: 1}\n var a = new Object([1,2,3]); //[1, 2, 3]\n var s = new Object('alireza'); //String {0: \"a\", 1: \"l\", 2: \"i\", 3: \"r\", 4: \"e\", 5: \"z\", 6: \"a\", length: 7, [[PrimitiveValue]]: \"alireza\"}\n String {}" }, { "answer_id": 65141555, "author": "Amit Singh", "author_id": 10561570, "author_profile": "https://Stackoverflow.com/users/10561570", "pm_score": 2, "selected": false, "text": "Var Obj = {};\n var Obj = new Obj() \n new Object()" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918/" ]
251,403
<p>I want to have a map that has a homogeneous key type but heterogeneous data types.</p> <p>I want to be able to do something like (pseudo-code):</p> <pre><code>boost::map&lt;std::string, magic_goes_here&gt; m; m.add&lt;int&gt;("a", 2); m.add&lt;std::string&gt;("b", "black sheep"); int i = m.get&lt;int&gt;("a"); int j = m.get&lt;int&gt;("b"); // error! </code></pre> <p>I could have a pointer to a base class as the data type but would rather not.</p> <p>I've never used boost before but have looked at the fusion library but can't figure out what I need to do.</p> <p>Thanks for your help.</p>
[ { "answer_id": 252106, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": true, "text": "#include <map>\n#include <string>\n#include <iostream>\n#include <boost/any.hpp>\n\nint main()\n{\n try\n {\n std::map<std::string, boost::any> m;\n m[\"a\"] = 2;\n m[\"b\"] = static_cast<char const *>(\"black sheep\");\n\n int i = boost::any_cast<int>(m[\"a\"]);\n std::cout << \"I(\" << i << \")\\n\";\n\n int j = boost::any_cast<int>(m[\"b\"]); // throws exception\n std::cout << \"J(\" << j << \")\\n\";\n }\n catch(...)\n {\n std::cout << \"Exception\\n\";\n }\n\n}\n" }, { "answer_id": 252196, "author": "Kurt", "author_id": 32794, "author_profile": "https://Stackoverflow.com/users/32794", "pm_score": 3, "selected": false, "text": "#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <map>\n#include <boost/any.hpp>\n\nusing boost::any_cast;\ntypedef std::map<std::string, boost::any> t_map;\n\n\nint main(int argc, char **argv)\n{\n\n t_map map;\n char *pc = \"boo yeah!\";\n\n map[\"a\"] = 2.1;\n map[\"b\"] = pc;\n\n cout << \"map contents\" << endl;\n cout << any_cast<double>(map[\"a\"]) << endl;\n cout << any_cast<char*>(map[\"b\"]) << endl;\n\n return 0;\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32794/" ]
251,409
<p>In MS SQL 2005 or T-SQL, you can do something like:</p> <pre><code>SELECT T.NAME, T.DATE FROM (SELECT * FROM MyTable WHERE ....) AS T </code></pre> <p>I failed to try the similar SQL on Oracle 9i DB. In MS SQL, the nested SQL is treated as a temporary/dynamic view created on fly and destroyed afterward. How can I do the similar thing in Oracle? I really don't want to create a view to do it.</p>
[ { "answer_id": 251414, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "SELECT T.NAME, T.DATE \n FROM (SELECT * FROM MyTable WHERE ....) T\n" }, { "answer_id": 251843, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "with t as\n(SELECT /*+ materliaze */ \n *\n FROM MyTable\n WHERE ....)\nSELECT T.NAME, T.DATE \nFROM T\n/\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
251,420
<p>Basically, I have an <code>iframe</code> embedded in a page and the <code>iframe</code> has some <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> routines I need to invoke from the parent page.</p> <p>Now the opposite is quite simple as you only need to call <code>parent.functionName()</code>, but unfortunately, I need exactly the opposite of that.</p> <p>Please note that my problem is not changing the source <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer">URL</a> of the <code>iframe</code>, but invoking a function defined in the <code>iframe</code>.</p>
[ { "answer_id": 251437, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 3, "selected": false, "text": "top.frames[1].frames[2] document.getElementById('theiframe')) name id <iframe src=\"iframe_page1.html\"\n id=\"testiframe\"\n name=\"testiframe\"></iframe>\n name id name id src location.href frames['testiframe'].location.href\n name frames['testiframe'].document.links.length frames frames['testiframe'].location.href document.getElementById('testiframe').src target name id target" }, { "answer_id": 251453, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 10, "selected": true, "text": "targetFunction() document.getElementById('targetFrame').contentWindow.targetFunction();\n window.frames document.getElementById // this option does not work in most of latest versions of chrome and Firefox\nwindow.frames[0].frameElement.contentWindow.targetFunction(); \n" }, { "answer_id": 251457, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 3, "selected": false, "text": "frames[] frames['iframeid'].method();\n" }, { "answer_id": 251468, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": false, "text": "window.myFunction = function(args) {\n doStuff();\n}\n var iframe = document.getElementById(\"iframeId\");\niframe.contentWindow.myFunction(args);\n" }, { "answer_id": 251645, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 7, "selected": false, "text": "HTMLIFrameElement.contentWindow window HTMLIFrameElement.contentDocument.defaultView window window.frames['name'] name=\"...\" id=\"...\" window.frames[number] window.parent" }, { "answer_id": 310014, "author": "GeverGever", "author_id": 31460, "author_profile": "https://Stackoverflow.com/users/31460", "pm_score": 2, "selected": false, "text": " $(\"#myframe\").load(function() {\n alert(\"loaded\");\n });\n" }, { "answer_id": 1063483, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 3, "selected": false, "text": "document\n .getElementById('targetFrame')\n .contentDocument\n .defaultView\n .targetFunction();\n" }, { "answer_id": 2663118, "author": "Vivek Singh CHAUHAN", "author_id": 222168, "author_profile": "https://Stackoverflow.com/users/222168", "pm_score": 6, "selected": false, "text": "iframe iframe example.com http:// https:// superwinningcontest.example iframe" }, { "answer_id": 7239578, "author": "sangam", "author_id": 47043, "author_profile": "https://Stackoverflow.com/users/47043", "pm_score": 2, "selected": false, "text": "window.location.reload();\n window.parent.location.reload();\n" }, { "answer_id": 7757848, "author": "Nitin Bansal", "author_id": 967062, "author_profile": "https://Stackoverflow.com/users/967062", "pm_score": 2, "selected": false, "text": "var el = document.getElementById('targetFrame');\n\nif(el.contentWindow)\n{\n el.contentWindow.targetFunction();\n}\nelse if(el.contentDocument)\n{\n el.contentDocument.targetFunction();\n}\n" }, { "answer_id": 7938270, "author": "19greg96", "author_id": 1018376, "author_profile": "https://Stackoverflow.com/users/1018376", "pm_score": 5, "selected": false, "text": "var o = document.getElementsByTagName('iframe')[0];\no.contentWindow.postMessage('Hello world', 'http://b.example.org/');\n window.addEventListener('message', receiver, false);\nfunction receiver(e) {\n if (e.origin == 'http://example.com') {\n if (e.data == 'Hello world') {\n e.source.postMessage('Hello', e.origin);\n } else {\n alert(e.data);\n }\n }\n}\n" }, { "answer_id": 8381436, "author": "Santhanakumar", "author_id": 826232, "author_profile": "https://Stackoverflow.com/users/826232", "pm_score": 2, "selected": false, "text": "window window.parent.targetFunction();\n" }, { "answer_id": 8503787, "author": "Saeid", "author_id": 884152, "author_profile": "https://Stackoverflow.com/users/884152", "pm_score": 1, "selected": false, "text": "parent.myfunction()" }, { "answer_id": 11795928, "author": "Dominique Fortin", "author_id": 1571709, "author_profile": "https://Stackoverflow.com/users/1571709", "pm_score": 2, "selected": false, "text": "function getIframeWindow(iframe_object) {\n var doc;\n\n if (iframe_object.contentWindow) {\n return iframe_object.contentWindow;\n }\n\n if (iframe_object.window) {\n return iframe_object.window;\n } \n\n if (!doc && iframe_object.contentDocument) {\n doc = iframe_object.contentDocument;\n } \n\n if (!doc && iframe_object.document) {\n doc = iframe_object.document;\n }\n\n if (doc && doc.defaultView) {\n return doc.defaultView;\n }\n\n if (doc && doc.parentWindow) {\n return doc.parentWindow;\n }\n\n return undefined;\n}\n ...\nvar el = document.getElementById('targetFrame');\n\nvar frame_win = getIframeWindow(el);\n\nif (frame_win) {\n frame_win.targetFunction();\n ...\n}\n...\n" }, { "answer_id": 21649520, "author": "Julien L", "author_id": 690236, "author_profile": "https://Stackoverflow.com/users/690236", "pm_score": 3, "selected": false, "text": "function tunnel(fn) {\n fn();\n}\n var myFunction = function() {\n alert(\"This work!\");\n}\n\nparent.tunnel(myFunction);\n" }, { "answer_id": 25138489, "author": "Sandy", "author_id": 846169, "author_profile": "https://Stackoverflow.com/users/846169", "pm_score": -1, "selected": false, "text": "parent.document.getElementById('frameid').contentWindow.somefunction()\n" }, { "answer_id": 46622668, "author": "Cybernetic", "author_id": 1639594, "author_profile": "https://Stackoverflow.com/users/1639594", "pm_score": 4, "selected": false, "text": "<button id='parent_page_button' onclick='call_button_inside_frame()'></button>\n\nfunction call_button_inside_frame() {\n document.getElementById('my_iframe').contentWindow.postMessage('foo','*');\n}\n window.addEventListener(\"message\", receiveMessage, false);\n\nfunction receiveMessage(event)\n {\n if(event) {\n click_button_inside_frame();\n }\n}\n\nfunction click_button_inside_frame() {\n document.getElementById('frame_button').click();\n}\n document.getElementById('my_iframe').contentWindow.postMessage('foo','*');\n window.parent.postMessage('foo','*')\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
251,432
<p>Is it possible to <code>typedef</code> long types that use templates? For example:</p> <pre><code>template &lt;typename myfloat_t&gt; class LongClassName { // ... }; template &lt;typename myfloat_t&gt; typedef std::vector&lt; boost::shared_ptr&lt; LongClassName&lt;myfloat_t&gt; &gt; &gt; LongCollection; LongCollection&lt;float&gt; m_foo; </code></pre> <p>This doesn't work, but is there a way to achieve a similar effect? I just want to avoid having to type and read a type definition that covers almost the full width of my editor window. </p>
[ { "answer_id": 251446, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": true, "text": "template<typename T> struct LongCollection {\n typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;\n};\n\nLongCollection<float>::type m_foo;\n" }, { "answer_id": 251455, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": "typedef std::vector< boost::shared_ptr< LongClassName<float> > > FloatCollection;\ntypedef std::vector< boost::shared_ptr< LongClassName<double> > > DoubleCollection;\n" }, { "answer_id": 251474, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "template <typename myfloat_t>\nclass LongClassName\n{\n // ...\n};\n\ntemplate <typename myfloat_t>\nclass LongCollection : public std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > \n{\n};\n" }, { "answer_id": 251484, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "// Normal function\nresult = f(args);\n\n// Metafunction\ntypedef f<args>::type result;\n allocator_type::rebind<U>::other type other" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32515/" ]
251,433
<p>Looking up LINQ and Or in google is proving somewhat difficult so here I am.</p> <p>I want to so the following:</p> <pre><code>(from creditCard in AvailableCreditCards where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant()) **or creditCard.CardNumber.().Contains(txtFilter.Text)** orderby creditCard.BillToName select creditCard) </code></pre>
[ { "answer_id": 251449, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());\n" }, { "answer_id": 251450, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "where if || (from creditCard in AvailableCreditCards \n where creditCard.BillToName.ToLowerInvariant().Contains(\n txtFilter.Text.ToLowerInvariant()) \n || creditCard.CardNumber.().Contains(txtFilter.Text) \norderby creditCard.BillToName \nselect creditCard)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32772/" ]
251,438
<p>I need to store my class A objects in some data structure. In addition, i would like them to be automatically sorted according to a key, which is in my case an embedded object of another class B. </p> <p>Thus I decided to use a STL priority queue.</p> <p>However it is possible that the 2 or more objects B to have the same key value.</p> <p>My questions:</p> <p><strong>Does the STL priority queue allow duplicate keys??</strong></p> <p><strong>If it does what should I consider and which predicate should I use?</strong></p> <p><strong>I know I could use a multiset but its Big O notation performance is worse, that why I want to use the priority queue.</strong></p>
[ { "answer_id": 251461, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 3, "selected": false, "text": "void push(const value_type& x) Inserts x into the priority_queue.\n Postcondition: size() will be incremented by 1. \n int main() {\n priority_queue<int> q;\n q.push(5);\n q.push(5);\n cout << q.top() << endl;\n q.pop();\n cout << q.top() << endl;\n q.pop();\n}\n 5\n5\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
251,439
<p>I want to pass an int list (List) as a declarative property to a web user control like this:</p> <pre><code>&lt;UC:MyControl runat="server" ModuleIds="1,2,3" /&gt; </code></pre> <p>I created a TypeConverter to do this:</p> <pre><code>public class IntListConverter : System.ComponentModel.TypeConverter { public override bool CanConvertFrom( System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { string[] v = ((string)value).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List&lt;int&gt; list = new List&lt;int&gt;(); foreach (string s in vals) { list.Add(Convert.ToInt32(s)); } return list } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor) &amp;&amp; value is List&lt;int&gt;) { List&lt;int&gt; list = (List&lt;int&gt;)value; ConstructorInfo construcor = typeof(List&lt;int&gt;).GetConstructor(new Type[] { typeof(IEnumerable&lt;int&gt;) }); InstanceDescriptor id = new InstanceDescriptor(construcor, new object[] { list.ToArray() }); return id; } return base.ConvertTo(context, culture, value, destinationType); } } </code></pre> <p>And then added the attribute to my property:</p> <pre><code>[TypeConverter(typeof(IntListConverter))] public List&lt;int&gt; ModuleIds { get { ... }; set { ... }; } </code></pre> <p>But I get this error at runtime:</p> <p><code>Unable to generate code for a value of type 'System.Collections.Generic.List'1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. This error occurred while trying to generate the property value for ModuleIds.</code></p> <p>My question is similar to one found <a href="https://stackoverflow.com/questions/116797/passing-int-array-as-parameter-in-web-user-control">here</a>, but the solution does not solve my problem:</p> <p><strong>Update:</strong> I found a page which solved the first problem. I updated the code above to show my fixes. The added code is the <code>CanConvertTo</code> and <code>ConvertTo</code> methods. Now I get a different error.:</p> <p><code>Object reference not set to an instance of an object.</code></p> <p>This error seems to be indirectly caused by something in the <code>ConvertTo</code> method.</p>
[ { "answer_id": 251600, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "<UC:MyControl id=\"uc\" runat=\"server\" />\n List<int> list = new List<int>();\nlist.add(1);\nlist.add(2);\nlist.add(3);\n\nuc.ModuleIds = list;\n" }, { "answer_id": 251611, "author": "Simon Johnson", "author_id": 854, "author_profile": "https://Stackoverflow.com/users/854", "pm_score": 0, "selected": false, "text": "public IList<int> ModuleIds\n{\n get\n {\n string moduleIds = Convert.ToString(ViewState[\"ModuleIds\"])\n\n IList<int> list = new Collection<int>();\n\n foreach(string moduleId in moduleIds.split(\",\"))\n {\n list.Add(Convert.ToInt32(moduleId));\n }\n\n return list;\n }\n}\n" }, { "answer_id": 251706, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "List<int> CanConvertFrom() List<int>" }, { "answer_id": 251728, "author": "jkind", "author_id": 32893, "author_profile": "https://Stackoverflow.com/users/32893", "pm_score": 0, "selected": false, "text": "private List<int> modules;\npublic string ModuleIds\n{\n set{\n if (!string.IsNullOrEmpty(value))\n {\n if (modules == null) modules = new List<int>();\n var ids = value.Split(new []{','});\n if (ids.Length>0)\n foreach (var id in ids)\n modules.Add((int.Parse(id)));\n }\n}\n" }, { "answer_id": 251994, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "class IntListConverter : TypeConverter {\n public static List<int> FromString(string value) {\n return new List<int>(\n value\n .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(s => Convert.ToInt32(s))\n );\n }\n\n public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {\n if (destinationType == typeof(InstanceDescriptor)) {\n List<int> list = (List<int>)value;\n return new InstanceDescriptor(this.GetType().GetMethod(\"FromString\"),\n new object[] { string.Join(\",\", list.Select(i => i.ToString()).ToArray()) }\n );\n }\n return base.ConvertTo(context, culture, value, destinationType);\n }\n}\n" }, { "answer_id": 252855, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 1, "selected": false, "text": "public List<int> ModuleIDs { get .... set ... }\npublic string ModuleIDstring { get ... set ... }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
251,444
<p>I have a command line Ruby app I'm developing and I want to allow a user of it to provide code that will run as a filter on part of the process. Basically, the application does this:</p> <ol> <li>read in some data</li> <li>If a filter is specified, use it to filter data</li> <li>process the data</li> </ol> <p>I want the filtering process (step 2) to be as flexible as possible.</p> <p>My thinking was that the user could provide a Ruby file that set a known constant to point to an object implementing an interface I define, e.g.:</p> <pre><code># user's filter class MyFilter def do_filter(array_to_filter) filtered_array = Array.new # do my filtering on array_to_filter filtered_array end FILTER = MyFilter.new </code></pre> <p>My app's code would then do something like this:</p> <pre><code>array_that_might_get_filtered = get_my_array() if (options.filter_file) require options.filter_file array_that_might_get_filtered = FILTER.do_filter(array_that_might_get_filtered) end </code></pre> <p>While this would work, it feels cheesy and it seems like there should be a better way to do it. I also considered having the filter be in the form of adding a method of a known name to a known class, but that didn't seem quite right, either.</p> <p>Is there a better idiom in Ruby for this?</p>
[ { "answer_id": 251608, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": true, "text": "ruby dataprocessor.rb custom_filter\n CustomFilter defined? custom_filter.rb do_filter SomeModel require app/models/some_model" }, { "answer_id": 251650, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 0, "selected": false, "text": "# user code\nUSER_FILTER = lambda { |value| value != 0xDEADBEEF }\n\n# script code\nload( user_code );\nFILTER = ( const_defined?(:USER_FILTER) ? USER_FILTER : lambda { true } )\n\noutput_array = input_array.filter(&FILTER)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029/" ]
251,464
<p>How do I get a function's name as a string?</p> <pre><code>def foo(): pass &gt;&gt;&gt; name_of(foo) &quot;foo&quot; </code></pre>
[ { "answer_id": 251469, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 6, "selected": false, "text": "my_function.func_name\n dir(func_name) func_name.func_code.co_code import dis\ndis.dis(my_function)\n" }, { "answer_id": 255297, "author": "user28409", "author_id": 28409, "author_profile": "https://Stackoverflow.com/users/28409", "pm_score": 11, "selected": true, "text": "my_function.__name__\n __name__ func_name >>> import time\n>>> time.time.func_name\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nAttributeError: 'builtin_function_or_method' object has no attribute 'func_name'\n>>> time.time.__name__ \n'time'\n __name__" }, { "answer_id": 13514318, "author": "Albert Vonpupp", "author_id": 1332764, "author_profile": "https://Stackoverflow.com/users/1332764", "pm_score": 9, "selected": false, "text": "import inspect\n\nthis_function_name = inspect.currentframe().f_code.co_name\n sys._getframe inspect.currentframe f_back inspect.currentframe().f_back.f_code.co_name mypy import inspect\nimport types\nfrom typing import cast\n\nthis_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name\n" }, { "answer_id": 18543271, "author": "sandyc", "author_id": 2734604, "author_profile": "https://Stackoverflow.com/users/2734604", "pm_score": 4, "selected": false, "text": "sys._getframe() traceback import traceback\ndef who_am_i():\n stack = traceback.extract_stack()\n filename, codeline, funcName, text = stack[-2]\n\n return funcName\n stack[-1]" }, { "answer_id": 20714270, "author": "Demyn", "author_id": 937597, "author_profile": "https://Stackoverflow.com/users/937597", "pm_score": 5, "selected": false, "text": "def func_name():\n import traceback\n return traceback.extract_stack(None, 2)[0][2]\n" }, { "answer_id": 36228241, "author": "Jim G.", "author_id": 109941, "author_profile": "https://Stackoverflow.com/users/109941", "pm_score": 4, "selected": false, "text": "import inspect\nimport logging\nimport traceback\n\ndef get_function_name():\n return traceback.extract_stack(None, 2)[0][2]\n\ndef get_function_parameters_and_values():\n frame = inspect.currentframe().f_back\n args, _, _, values = inspect.getargvalues(frame)\n return ([(i, values[i]) for i in args])\n\ndef my_func(a, b, c=None):\n logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')\n pass\n\nlogger = logging.getLogger()\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\n '%(asctime)s [%(levelname)s] -> %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n\nmy_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])\n" }, { "answer_id": 38453402, "author": "radato", "author_id": 797396, "author_profile": "https://Stackoverflow.com/users/797396", "pm_score": 5, "selected": false, "text": "class EnterExitLog():\n def __init__(self, funcName):\n self.funcName = funcName\n\n def __enter__(self):\n gLog.debug('Started: %s' % self.funcName)\n self.init_time = datetime.datetime.now()\n return self\n\n def __exit__(self, type, value, tb):\n gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))\n\ndef func_timer_decorator(func):\n def func_wrapper(*args, **kwargs):\n with EnterExitLog(func.__name__):\n return func(*args, **kwargs)\n\n return func_wrapper\n @func_timer_decorator\ndef my_func():\n" }, { "answer_id": 47155992, "author": "lapis", "author_id": 675674, "author_profile": "https://Stackoverflow.com/users/675674", "pm_score": 6, "selected": false, "text": "__qualname__ __name__ def my_function():\n pass\n\nclass MyClass(object):\n def method(self):\n pass\n\nprint(my_function.__name__) # gives \"my_function\"\nprint(MyClass.method.__name__) # gives \"method\"\n\nprint(my_function.__qualname__) # gives \"my_function\"\nprint(MyClass.method.__qualname__) # gives \"MyClass.method\"\n" }, { "answer_id": 49322993, "author": "Mohsin Ashraf", "author_id": 5566361, "author_profile": "https://Stackoverflow.com/users/5566361", "pm_score": 4, "selected": false, "text": "def function1():\n print \"function1\"\n\ndef function2():\n print \"function2\"\n\ndef function3():\n print \"function3\"\nprint function1.__name__\n a = [function1 , function2 , funciton3]\n for i in a:\n print i.__name__\n" }, { "answer_id": 55253296, "author": "Ma Guowei", "author_id": 2330690, "author_profile": "https://Stackoverflow.com/users/2330690", "pm_score": 5, "selected": false, "text": "import inspect\n\ndef foo():\n print(inspect.stack()[0][3])\n stack()[0] stack()[3]" }, { "answer_id": 58548220, "author": "NL23codes", "author_id": 9431874, "author_profile": "https://Stackoverflow.com/users/9431874", "pm_score": 4, "selected": false, "text": "def debug(func=None):\n def wrapper(*args, **kwargs):\n try:\n function_name = func.__func__.__qualname__\n except:\n function_name = func.__qualname__\n return func(*args, **kwargs, function_name=function_name)\n return wrapper\n\n@debug\ndef my_function(**kwargs):\n print(kwargs)\n\nmy_function()\n {'function_name': 'my_function'}\n" }, { "answer_id": 63857383, "author": "Ahmed Shehab", "author_id": 8404743, "author_profile": "https://Stackoverflow.com/users/8404743", "pm_score": 3, "selected": false, "text": "import sys\nfn_name = sys._getframe().f_code.co_name\n" }, { "answer_id": 65110612, "author": "Szczerski", "author_id": 10646189, "author_profile": "https://Stackoverflow.com/users/10646189", "pm_score": 3, "selected": false, "text": "import inspect\n\ndef my_first_function():\n func_name = inspect.stack()[0][3]\n print(func_name) # my_first_function\n import sys\n\ndef my_second_function():\n func_name = sys._getframe().f_code.co_name\n print(func_name) # my_second_function\n" }, { "answer_id": 71002981, "author": "Gustin", "author_id": 10141500, "author_profile": "https://Stackoverflow.com/users/10141500", "pm_score": 2, "selected": false, "text": "__name__ def my_function():\n pass\n\nprint(my_function.__name__) # prints \"my_function\"\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11452/" ]
251,466
<p>An easy jQuery question.</p> <p>I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and then the input name. ( the input names are not unique in my page )</p> <p>So for instance: </p> <pre><code>var xAmt = $('#xForm'+num).('#xAmt'); </code></pre> <p>I really want to supply these values to an AJAX POST</p> <pre><code> $.ajax({ url: "X.asp", cache: false, type: "POST", data: "XID=xID&amp;xNumber=xNum&amp;xAmt=xAmt", </code></pre> <p>...</p> <p>If I can get the values in the AJAX call even better.</p>
[ { "answer_id": 251520, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "formSerialize() ajaxSubmit()" }, { "answer_id": 251591, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 0, "selected": false, "text": "$('form input[name*='xAmt'] ').each(function(){ alert( $(this).val() ); alert( $(this).parent().attr('name') + $(this).parent().attr('id') ); });\n" }, { "answer_id": 251627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "function queryX( args ) {\n var queryString = [ \"XID=\", args.XID, \"&xNumber=\", args.xNumber, \"&xAmt=\", args.xAmt ].join(\"\");\n $.ajax({\n url: \"X.asp\",\n cache: false,\n type: \"POST\",\n data: queryString,\n success : function( data ) {\n return data;\n }\n });\n}\nvar myReturnData = queryX({\n XID : $(\"input[name='XID']\").val(),\n xNumber : $(\"input[name='xNumber']\").val(),\n xAmt : $(\"input[name='xAmt']\").val()\n});\n" }, { "answer_id": 252471, "author": "ack", "author_id": 32840, "author_profile": "https://Stackoverflow.com/users/32840", "pm_score": 1, "selected": false, "text": "var xAmt = $('#xForm'+num+ ' #xAmt').val();\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
251,467
<p>I have a directory of bitmaps that are all of the same dimension. I would like to convert these bitmaps into a video file. I don't care if the video file (codec) is wmv or avi. My only requirement is that I specify the frame rate. This does not need to be cross platform, Windows (Vista and XP) only. I have read a few things about using the Windows Media SDK or DirectShow, but none of them are that explicit about providing code samples.</p> <p>Could anyone provide some insight, or some valuable resources that might help me to do this in C#?</p>
[ { "answer_id": 251853, "author": "crftr", "author_id": 18213, "author_profile": "https://Stackoverflow.com/users/18213", "pm_score": 5, "selected": true, "text": "double framesPerSecond;\nBitmap[] imagesToDisplay; // add the desired bitmaps to this array\nTimer playbackTimer;\n\nint currentImageIndex;\nPictureBox displayArea;\n\n(...)\n\ncurrentImageIndex = 0;\nplaybackTimer.Interval = 1000 / framesPerSecond;\nplaybackTimer.AutoReset = true;\nplaybackTimer.Elapsed += new ElapsedEventHandler(playbackNextFrame);\nplaybackTimer.Start();\n\n(...)\n\nvoid playbackNextFrame(object sender, ElapsedEventArgs e)\n{\n if (currentImageIndex + 1 >= imagesToDisplay.Length)\n {\n playbackTimer.Stop();\n\n return;\n }\n\n displayArea.Image = imagesToDisplay[currentImageIndex++];\n}\n" }, { "answer_id": 289913, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 3, "selected": false, "text": "using (ITimeline timeline = new DefaultTimeline(25))\n{\n IGroup group = timeline.AddVideoGroup(32, 160, 100);\n\n ITrack videoTrack = group.AddTrack();\n IClip clip1 = videoTrack.AddImage(\"image1.jpg\", 0, 2);\n IClip clip2 = videoTrack.AddImage(\"image2.jpg\", 0, 2);\n IClip clip3 = videoTrack.AddImage(\"image3.jpg\", 0, 2);\n IClip clip4 = videoTrack.AddImage(\"image4.jpg\", 0, 2);\n\n double halfDuration = 0.5;\n\n group.AddTransition(clip2.Offset - halfDuration, halfDuration, StandardTransitions.CreateFade(), true);\n group.AddTransition(clip2.Offset, halfDuration, StandardTransitions.CreateFade(), false);\n\n group.AddTransition(clip3.Offset - halfDuration, halfDuration, StandardTransitions.CreateFade(), true);\n group.AddTransition(clip3.Offset, halfDuration, StandardTransitions.CreateFade(), false);\n\n group.AddTransition(clip4.Offset - halfDuration, halfDuration, StandardTransitions.CreateFade(), true);\n group.AddTransition(clip4.Offset, halfDuration, StandardTransitions.CreateFade(), false);\n\n ITrack audioTrack = timeline.AddAudioGroup().AddTrack();\n\n IClip audio =\n audioTrack.AddAudio(\"soundtrack.wav\", 0, videoTrack.Duration);\n\n audioTrack.AddEffect(0, audio.Duration,\n StandardEffects.CreateAudioEnvelope(1.0, 1.0, 1.0, audio.Duration));\n\n using (\n WindowsMediaRenderer renderer =\n new WindowsMediaRenderer(timeline, \"output.wmv\", WindowsMediaProfiles.HighQualityVideo))\n {\n renderer.Render();\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
251,479
<p>I acquired a database from another developer. He didn't use auto_incrementers on any tables. They all have primary key ID's, but he did all the incrementing manually, in code.</p> <p>Can I turn those into Auto_incrementers now?</p> <hr> <p>Wow, very nice, thanks a ton. It worked without a hitch on one of my tables. But a second table, i'm getting this error...Error on rename of '.\DBNAME#sql-6c8_62259c' to '.\DBNAME\dealer_master_events'</p>
[ { "answer_id": 251576, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 3, "selected": false, "text": "ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT \n ALTER TABLE `content` auto_increment = MAX(`id`) + 1\n" }, { "answer_id": 251630, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 8, "selected": true, "text": "AUTO_INCREMENT mysql> CREATE TABLE foo (\n id INT NOT NULL,\n PRIMARY KEY (id)\n);\nmysql> INSERT INTO foo VALUES (1), (2), (5);\n MODIFY AUTO_INCREMENT mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;\n mysql> SHOW CREATE TABLE foo;\n CREATE TABLE foo (\n `id` INT(11) NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1\n PRIMARY KEY ALTER TABLE mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax\nmysql> SELECT * FROM foo;\n +----+\n| id |\n+----+\n| 1 | \n| 2 | \n| 5 | \n| 6 | \n+----+\n4 rows in set (0.00 sec)\n ENGINE=InnoDB id" }, { "answer_id": 2051739, "author": "Michael A. Griffey", "author_id": 249181, "author_profile": "https://Stackoverflow.com/users/249181", "pm_score": 3, "selected": false, "text": "AUTO_INCREMENT MODIFY COLUMN INTEGER UNSIGNED NOT NULL AUTO_INCREMENT AUTO_INCREMENT = 31544 ALTER TABLE `'TableName'` MODIFY COLUMN `'id'` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 31544;\n" }, { "answer_id": 21945624, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "table_name id id" }, { "answer_id": 55655455, "author": "Dima Dz", "author_id": 4685379, "author_profile": "https://Stackoverflow.com/users/4685379", "pm_score": 2, "selected": false, "text": "ALTER TABLE `foo` MODIFY COLUMN `bar_id` INT NOT NULL AUTO_INCREMENT;\n ALTER TABLE `foo` CHANGE `bar_id` `bar_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;\n bar_id an error 1068: Multiple primary key defined\n set foreign_key_checks = 0;\n set foreign_key_checks = 1;\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
251,480
<p>I have several databases for my applications that use SQL Server 2005 mirroring to keep a nice copy of the data somewhere else. Works like a charm, however, the log file just seems to be growing and growing, one is at 15GB for a 3GB database. </p> <p>Normally, I can just shrink it - however an error pops up that this specifically cannot be done. But, it seems eventually if unchecked would just expand to use all the space on the drive.</p> <p>I see that I can set a maximum file size for the log file, is that the answer here? Will the log just roll when it hits the max, or will the DB just stop functioning?</p> <p>Thanks</p>
[ { "answer_id": 11793553, "author": "masoud Cheragee", "author_id": 720242, "author_profile": "https://Stackoverflow.com/users/720242", "pm_score": 1, "selected": false, "text": " use master\n go\n if object_id ('sp_shrink_mirrored_database', 'P') is not null \n drop proc sp_shrink_mirrored_database \n go\n create procedure sp_shrink_mirrored_database @dbname sysname, @target_percent int = null\n as\n begin\n declare @filename sysname\n declare @filesize int\n declare @sql nvarchar(4000)\n\n if @target_percent is null\n dbcc shrinkdatabase (@dbname)\n else \n dbcc shrinkdatabase (@dbname, @target_percent)\n declare c cursor for \n select [name], [size] from sys.master_files where type=0 and database_id = db_id (@dbname)\n open c\n fetch next from c into @filename, @filesize\n while @@fetch_status=0\n begin\n set @filesize=(@filesize+1)*8\n set @sql='alter database [' + @dbname + '] modify file ( name=' \n + @filename + ', size=' + cast(@filesize as nvarchar) + 'kb )'\n execute sp_executesql @sql\n fetch next from c into @filename, @filesize\n end\n close c\n deallocate c\n end\n go\n EXEC sp_shrink_mirrored_database 'mydb'\n" }, { "answer_id": 14624712, "author": "Ahmad Hindash", "author_id": 1818205, "author_profile": "https://Stackoverflow.com/users/1818205", "pm_score": 0, "selected": false, "text": "USE DBNAME\nGO\nDBCC SHRINKFILE(DBNAME_log, 1)\nBACKUP LOG DBNAME WITH TRUNCATE_ONLY\nDBCC SHRINKFILE(DBNAME_log, 1)\nGO\n" }, { "answer_id": 69951559, "author": "Yousaf Khan", "author_id": 17400852, "author_profile": "https://Stackoverflow.com/users/17400852", "pm_score": 0, "selected": false, "text": "use DatabaseName\nGO\nDBCC SHRINKFILE (LogicalFileName_log, 1);\nGO\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29466/" ]
251,482
<p>I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:</p> <pre><code>myvalue = CType(value, "String, Integer or Boolean") </code></pre> <p>The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.</p> <p>Is this possible?</p>
[ { "answer_id": 251508, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "myvalue Object" }, { "answer_id": 251558, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 2, "selected": false, "text": "Dim t As Type = testObject.GetType()\nDim prop As PropertyInfo = t.GetProperty(\"propertyName\")\nDim gmi As MethodInfo = prop.GetGetMethod()\ngmi.Invoke(testObject, Nothing)\n" }, { "answer_id": 251571, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 3, "selected": false, "text": "Sub DoCast(ByVal something As Object)\n\n Dim newSomething = Convert.ChangeType(something, something.GetType())\n\nEnd Sub\n" }, { "answer_id": 251587, "author": "tom.dietrich", "author_id": 15769, "author_profile": "https://Stackoverflow.com/users/15769", "pm_score": 3, "selected": false, "text": " Dim bMyValue As Boolean\n Dim iMyValue As Integer\n Dim sMyValue As String \n Dim t As Type = myValue.GetType\n\n\n Select Case t.Name\n Case \"String\"\n sMyValue = ctype(myValue, string)\n Case \"Boolean\"\n bMyValue = ctype(myValue, boolean)\n Case \"Integer\"\n iMyValue = ctype(myValue, Integer)\n End Select\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968/" ]
251,485
<p>Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this:</p> <pre><code>$this-&gt;{$methodName}($arg1, $arg2, $arg3); </code></pre>
[ { "answer_id": 251499, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "$this->$methodName($arg1, $arg2, $arg3);\n" }, { "answer_id": 251512, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 9, "selected": true, "text": "$this->{$methodName}($arg1, $arg2, $arg3);\n$this->$methodName($arg1, $arg2, $arg3);\ncall_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));\n" }, { "answer_id": 251514, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "call_user_func() call_user_func_array()" }, { "answer_id": 371090, "author": "user46637", "author_id": 46637, "author_profile": "https://Stackoverflow.com/users/46637", "pm_score": 2, "selected": false, "text": "$response = $client->{$this->requestFunc}($this->requestMsg);\n" }, { "answer_id": 27148640, "author": "David", "author_id": 428640, "author_profile": "https://Stackoverflow.com/users/428640", "pm_score": 2, "selected": false, "text": "class test{ \n\n function echo_this($text){\n echo $text;\n }\n\n function get_method($method){\n $object = $this;\n return function() use($object, $method){\n $args = func_get_args();\n return call_user_func_array(array($object, $method), $args); \n };\n }\n}\n\n$test = new test();\n$echo = $test->get_method('echo_this');\n$echo('Hello'); //Output is \"Hello\"\n" }, { "answer_id": 41514419, "author": "RodolfoNeto", "author_id": 2938768, "author_profile": "https://Stackoverflow.com/users/2938768", "pm_score": 4, "selected": false, "text": "class Test {\n\n private $name;\n\n public function __call($name, $arguments) {\n echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);\n //do a get\n if (preg_match('/^get_(.+)/', $name, $matches)) {\n $var_name = $matches[1];\n return $this->$var_name ? $this->$var_name : $arguments[0];\n }\n //do a set\n if (preg_match('/^set_(.+)/', $name, $matches)) {\n $var_name = $matches[1];\n $this->$var_name = $arguments[0];\n }\n }\n}\n\n$obj = new Test();\n$obj->set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String\necho $obj->get_name();//Echo:Method Name: get_name Arguments:\n //return: Any String\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
251,532
<p>If I have a URL (eg. <a href="http://www.foo.com/alink.pl?page=2" rel="noreferrer">http://www.foo.com/alink.pl?page=2</a>), I want to determine if I am being redirected to another link. I'd also like to know the final URL (eg. <a href="http://www.foo.com/other_link.pl" rel="noreferrer">http://www.foo.com/other_link.pl</a>). Finally, I want to be able to do this in Perl and Groovy.</p>
[ { "answer_id": 251559, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "response_redirect add_handler" }, { "answer_id": 251569, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "$ telnet www.google.com 80\nHEAD / HTTP/1.1\nHOST: www.google.com\n\n\nHTTP/1.1 302 Found\nLocation: http://www.google.it/\nCache-Control: private\nContent-Type: text/html; charset=UTF-8\nSet-Cookie: ##############################\nDate: Thu, 30 Oct 2008 20:03:36 GMT\nServer: ####\nContent-Length: 218\n" }, { "answer_id": 251676, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 5, "selected": true, "text": "use LWP::UserAgent;\nmy $ua = LWP::UserAgent->new;\n\nmy $request = HTTP::Request->new( GET => 'http://google.com/' );\nmy $response = $ua->request($request);\nif ( $response->is_success and $response->previous ) {\n print $request->url, ' redirected to ', $response->request->uri, \"\\n\";\n}\n" }, { "answer_id": 252024, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "setFollowRedirects(false) responseCode URL url = new URL ('http://google.com')\nHttpURLConnection conn = url.openConnection()\nconn.followRedirects = false\nconn.requestMethod = 'HEAD'\nprintln conn.responseCode\n// Not ideal - should check response code too\nif (conn.headerFields.'Location') {\n println conn.headerFields.'Location'\n}\n\n301\n[\"http://www.google.com/\"]\n" }, { "answer_id": 6325129, "author": "Rusty Hodge", "author_id": 795147, "author_profile": "https://Stackoverflow.com/users/795147", "pm_score": 1, "selected": false, "text": "use LWP::UserAgent;\nmy $ua = LWP::UserAgent->new;\n\nmy $request = HTTP::Request->new( GET => 'http://google.com/' );\nmy $response = $ua->request($request);\nif ( $response->is_redirect ) {\n print $request->url . \" redirected to location \" . $response->header('Location') . \"\\n\";\n} \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
251,535
<p>One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century if the 2 digit year is after the current year, but work for the current century if the 2 digit year is equal to or less than the current year.</p> <p>as of today 10/30/2008</p> <p>01/01/01 = 01/01/2001</p> <p>01/01/09 = 01/01/1909</p> <p>This is a strange requirement, and I solved the problem, I just don't like my solution. It feels like there is a better way to do this.</p> <p>Thanks for the help.</p> <pre><code>public static String stupidDate(String dateString) { String twoDigitYear = StringUtils.right(dateString, 2); String newDate = StringUtils.left(dateString, dateString.length() - 2); int year = NumberUtils.toInt(twoDigitYear); Calendar c = GregorianCalendar.getInstance(); int centuryInt = c.get(Calendar.YEAR) - year; newDate = newDate + StringUtils.left(Integer.toString(centuryInt), 2) + twoDigitYear; return newDate; } </code></pre>
[ { "answer_id": 251570, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "public static String anEasierStupidDateWithNoStringParsing(String dateString) {\n DateFormat df = new SimpleDateFormat(\"MM/dd/yyyy\");\n\n //handling ParseExceptions is an exercise left to the reader!\n Date date = df.parse(dateString);\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n\n Calendar now = Calendar.getInstance();\n if (cal.after(now)) {\n cal.add(Calendar.YEAR, -100);\n }\n\n return cal;\n}\n MM/dd/yyyy" }, { "answer_id": 251719, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 3, "selected": false, "text": "String inputDate = \"01/01/08\";\n// assuming U.S. style date, since it's not clear from your original question\nDateTimeFormatter parser = DateTimeFormat.forPattern(\"MM/dd/yy\");\nDateTime dateTime = parser.parseDateTime(inputDate);\n// if after current time\nif (dateTime.isAfter(new DateTime())) {\n dateTime = dateTime.minus(Years.ONE);\n}\n\nreturn dateTime.toString(\"MM/dd/yyyy\");\n" }, { "answer_id": 251720, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "DateFormat informat= new SimpleDateFormat(\"MM/dd/yy\");\nDateFormat outformat= new SimpleDateFormat(\"MM/dd/yyyy\");\nreturn outformat.format(informat.parse(dateString));\n" }, { "answer_id": 251836, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 5, "selected": true, "text": "import java.text.SimpleDateFormat\n\nSimpleDateFormat sdf = new SimpleDateFormat('MM/dd/yy')\nSimpleDateFormat fmt = new SimpleDateFormat('yyyy-MM-dd')\n\nCalendar cal = Calendar.getInstance()\ncal.add(Calendar.YEAR, -100)\nsdf.set2DigitYearStart(cal.getTime())\n\ndates = ['01/01/01', '10/30/08','01/01/09']\ndates.each {String d ->\n println fmt.format(sdf.parse(d))\n}\n 2001-01-01\n2008-10-30\n1909-01-01\n" }, { "answer_id": 26647748, "author": "chetan singhal", "author_id": 760935, "author_profile": "https://Stackoverflow.com/users/760935", "pm_score": 0, "selected": false, "text": "Date deliverDate = new SimpleDateFormat(\"MM/dd/yy\").parse(deliverDateString);\nString dateString2 = new SimpleDateFormat(\"yyyy-MM-dd\").format(deliverDate);\n" }, { "answer_id": 74511905, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": false, "text": "java.time DateTimeFormatterBuilder#optionalStart DateTimeFormatterBuilder#optionalEnd DateTimeFormatterBuilder#appendValueReduced import java.time.LocalDate;\nimport java.time.Year;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.temporal.ChronoField;\nimport java.util.Locale;\nimport java.util.stream.Stream;\n\npublic class Main {\n public static void main(String[] args) {\n DateTimeFormatter parser = new DateTimeFormatterBuilder()\n .appendPattern(\"M/d/\")\n .optionalStart()\n .appendPattern(\"uuuu\")\n .optionalEnd()\n .optionalStart()\n .appendValueReduced(ChronoField.YEAR, 2, 2, Year.now().minusYears(100).getValue())\n .optionalEnd()\n .toFormatter(Locale.ENGLISH);\n\n // Test\n Stream.of(\n \"1/2/2022\",\n \"01/2/2022\",\n \"1/02/2022\",\n \"01/02/2022\",\n \"1/2/22\",\n \"1/2/21\",\n \"1/2/20\",\n \"1/2/23\",\n \"1/2/24\"\n )\n .map(s -> LocalDate.parse(s, parser))\n .forEach(System.out::println);\n }\n}\n 2022-01-02\n2022-01-02\n2022-01-02\n2022-01-02\n1922-01-02\n2021-01-02\n2020-01-02\n1923-01-02\n1924-01-02\n LocalDate Date#toInstant Instant java.time Instant Z ZoneOffset +00:00 public class Main {\n public static void main(String[] args) {\n Date date = new Date();\n Instant instant = date.toInstant();\n System.out.println(instant);\n\n ZonedDateTime zdt = instant.atZone(ZoneId.of(\"Asia/Kolkata\"));\n System.out.println(zdt);\n\n OffsetDateTime odt = instant.atOffset(ZoneOffset.of(\"+05:30\"));\n System.out.println(odt);\n // Alternatively, using time-zone\n odt = instant.atZone(ZoneId.of(\"Asia/Kolkata\")).toOffsetDateTime();\n System.out.println(odt);\n\n LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of(\"Asia/Kolkata\"));\n System.out.println(ldt);\n // Alternatively,\n ldt = instant.atZone(ZoneId.of(\"Asia/Kolkata\")).toLocalDateTime();\n System.out.println(ldt);\n }\n}\n 2022-11-20T20:32:42.823Z\n2022-11-21T02:02:42.823+05:30[Asia/Kolkata]\n2022-11-21T02:02:42.823+05:30\n2022-11-21T02:02:42.823+05:30\n2022-11-21T02:02:42.823\n2022-11-21T02:02:42.823\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
251,541
<pre><code>public void Getrecords(ref IList iList,T dataItem) { iList = Populate.GetList&lt;dataItem&gt;() // GetListis defined as GetList&lt;T&gt; } </code></pre> <p>dataItem can be my order object or user object which will be decided at run time.The above does not work as it gives me this error The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type</p>
[ { "answer_id": 251552, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": -1, "selected": false, "text": "Getrecords<T> ...\n" }, { "answer_id": 251555, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "public void GetRecords<T>(ref IList<T> iList, T dataitem)\n{\n}\n iList = Populate.GetList<dataItem>() \n iList = Populate.GetList<T>() \n IList<T> GetList<T>() where T: new() \n{...}\n public void GetRecords<T>(ref IList<T> iList, T dataitem) where T: new() \n{\n iList = Populate.GetList<T>();\n}\n" }, { "answer_id": 251561, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 2, "selected": false, "text": "public IList<T> GetRecords<T>() {\n return Populate.GetList<T>();\n}\n IList<int> result = GetRecords<int>();\n" }, { "answer_id": 251605, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "ref out public IList<T> GetRecords<T>(T dataItem) where T : new()\n{ // MG: what does dataItem do here???\n return Populate.GetList<T>();\n}\n Populate.GetList MakeGenericMethod public static IList GetRecords(object dataItem) \n{\n Type type = dataItem.GetType();\n return (IList) typeof(Populate).GetMethod(\"GetList\")\n .MakeGenericMethod(type).Invoke(null,null);\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
251,557
<p>I need to echo a string containing angle brackets (&lt; and >) to a file on a Windows machine. Basically what I want to do is the following:<br> <code>echo some string &lt; with angle &gt; brackets &gt;&gt;myfile.txt</code></p> <p>This doesn't work since the command interpreter gets confused with the angle brackets. I could quote the whole string like this:<br> <code>echo "some string &lt; with angle &gt; brackets" &gt;&gt;myfile.txt</code></p> <p>But then I have double quotes in my file that I don't want. </p> <p>Escaping the brackets ala unix doesn't work either:<br> <code>echo some string \&lt; with angle \&gt; brackets &gt;&gt;myfile.txt</code></p> <p>Ideas?</p>
[ { "answer_id": 251573, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 9, "selected": true, "text": "echo some string ^< with angle ^> brackets >>myfile.txt\n" }, { "answer_id": 5455611, "author": "aalaap", "author_id": 44257, "author_profile": "https://Stackoverflow.com/users/44257", "pm_score": -1, "selected": false, "text": "echo some string \"<\" with angle \">\" brackets >>myfile.txt\n" }, { "answer_id": 11594161, "author": "sin3.14", "author_id": 1419252, "author_profile": "https://Stackoverflow.com/users/1419252", "pm_score": 5, "selected": false, "text": "^ ^ C:\\WINDOWS> echo ^<html^>\n<html>\n\nC:\\WINDOWS> echo ^<html^> | sort\nThe syntax of the command is incorrect.\n\nC:\\WINDOWS> echo ^^^<html^^^> | sort\n<html>\n\nC:\\WINDOWS> echo ^^^<html^^^>\n^<html^>\n echo C:\\WINDOWS> set/p _=\"<html>\" <nul\n<html>\nC:\\WINDOWS> set/p _=\"<html>\" <nul | sort\n<html>\n" }, { "answer_id": 26041395, "author": "dbenham", "author_id": 1012053, "author_profile": "https://Stackoverflow.com/users/1012053", "pm_score": 3, "selected": false, "text": "^ @echo off\nsetlocal enableDelayedExpansion\nset \"line=<html>\"\necho !line!\n for /f \"delims=\" %A in (\"<html>\") do @echo %~A\n @echo off\nfor /f \"delims=\" %%A in (\"<html>\") do echo %%~A\n < > & | && || echo ^^^<html^^^>|findstr .\n cmd /c \"echo ^<html^>\"|findstr .\n @echo off\nsetlocal disableDelayedExpansion\nset \"line=<html>\"\ncmd /v:on /c echo !test!|findstr .\n @echo off\nsetlocal enableDelayedExpansion\nset \"line=<html>\"\nREM - the following command fails\ncmd /v:on /c echo !test!|findstr .\n !test! < > ! ! @echo off\nsetlocal enableDelayedExpansion\nset \"line=<html>\"\ncmd /v:on /c echo ^^!test^^!|findstr .\n @echo off\nsetlocal enableDelayedExpansion\nset \"line=<html>\"\ncmd /v:on /c \"echo ^!test^!\"|findstr .\n !test! @echo off\nsetlocal enableDelayedExpansion\nset \"line=<html>\"\n(cmd /v:on /c echo !test!)|findstr .\n" }, { "answer_id": 33872568, "author": "orbitcowboy", "author_id": 4070000, "author_profile": "https://Stackoverflow.com/users/4070000", "pm_score": 2, "selected": false, "text": "echo A->B\n echo A-^>B\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26302/" ]
251,560
<p>Our app (already deployed) is using an Access/Jet database. The upcoming version of our software requires some additional columns in one of the tables. I need to first check if these columns exist, and then add them if they don't.</p> <p>Can someone provide a quick code sample, link, or nudge in the right direction?</p> <p>(I'm using c#, but a VB.NET sample would be fine, too).</p>
[ { "answer_id": 251596, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 4, "selected": true, "text": "Dim conn as New AdoConnection(someConnStr)\nDim cmd as New AdoCommand\ncmd.Connection = conn\ncmd.CommandText = \"ALTER TABLE X ADD COLUMN y COLUMNTYPE\"\ncmd.ComandType = CommandType.Text\ncmd.ExecuteNonQuery()\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27414/" ]
251,592
<p>PHP (among others) will execute the deepest function first, working its way out. For example,</p> <pre><code>$text = strtoupper(str_replace('_', ' ', file_get_contents('file.txt'))); </code></pre> <p>I'm doing something very similar to the above example for a template parser. It looks for the tags</p> <pre><code>{@tag_name} </code></pre> <p>and replaces it with a variable of the name <strong>$tag_name</strong>. One more example:</p> <pre><code>$a = 'hello'; $b = ' world'; INPUT = 'This is my test {@a{@b}} string.'; OUTPUT (step 1) = 'This is my test {@a} world string.'; OUTPUT output = 'This is my test hello world string.'; </code></pre> <p>How can I go about doing this? Does this make sense? If not, I can try explaining better.</p>
[ { "answer_id": 251610, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 0, "selected": false, "text": "$a = \"b\";\n$b = \"Hello World!\";\n\nprint $$a;\n" }, { "answer_id": 251655, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 1, "selected": false, "text": "array_push array_pop" }, { "answer_id": 251869, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": true, "text": "'This is my test {@a} {@b} string.'\n $aVars = array('{@a}' => 'hello', '{@b}' => 'world');\n$sString = 'This is my test {@a} {@b} string.';\n\necho str_replace(array_keys($aVars), array_values($aVars), $sString);\n function template($sText, $aVars) {\n if (preg_match_all('/({@([^{}]+)})/',\n $sText, $aMatches, PREG_SET_ORDER)) {\n foreach($aMatches as $aMatch) {\n echo '<pre>' . print_r($aMatches, 1) . '</pre>';\n\n if (array_key_exists($aMatch[2], $aVars)) {\n // replace the guy inside\n $sText = str_replace($aMatch[1], $aVars[$aMatch[2]], $sText);\n\n // now run through the text again since we have new variables\n $sText = template($sText, $aVars);\n }\n }\n }\n\n return $sText;\n}\n $aVars = array('a' => 'hello', 'b' => 'world');\n$sStringOne = 'This is my test {@a} {@b} string.';\n$sStringTwo = 'This is my test {@a{@b}} string.';\n\necho template($sStringOne, $aVars) . '<br />';\n echo template($sStringTwo, $aVars) . '<br />';\n aworld $aVars = array('a' => '', 'b' => '2', 'a2' => 'hello world');\n\necho template($sStringTwo, $aVars) . '<br />';\n $aVars = array('a3' => 'hello world', 'b2' => '3', 'c1' => '2', 'd' => '1');\n$sStringTre = 'This is my test {@a{@b{@c{@d}}}} string.';\n\necho template($sStringTre, $aVars) . '<br />';\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32881/" ]
251,603
<p>Was wondering if it is recomended to pass a database connection object around(to other modules) or let the method (in the other module) take care of setting it up. I am leaning toward letting the method set it up as to not have to check the state of the connection before using it, and just having the caller pass any needed data to the calling method that would be needed to setup the connection. </p>
[ { "answer_id": 251614, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "<configuration>\n <connectionStrings>\n <add name=\"conn1\" providerName=\"System.Data.SqlClient\" connectionString=\"string here\" />\n <add name=\"conn2\" providerName=\"System.Data.SqlClient\" connectionString=\"string here\" />\n </connectionStrings>\n</configuration>\n" }, { "answer_id": 251663, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "TransactionScope" }, { "answer_id": 251726, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "class DatabaseContext : IDisposable {\n\n List<DatabaseContext> currentContexts;\n SqlConnection connection;\n bool first = false; \n\n DatabaseContext (List<DatabaseContext> contexts)\n {\n currentContexts = contexts;\n if (contexts.Count == 0)\n {\n connection = new SqlConnection(); // fill in info \n connection.Open();\n first = true;\n }\n else\n {\n connection = contexts.First().connection;\n }\n\n contexts.Add(this);\n }\n\n static List<DatabaseContext> DatabaseContexts {\n get\n {\n var contexts = CallContext.GetData(\"contexts\") as List<DatabaseContext>;\n if (contexts == null)\n {\n contexts = new List<DatabaseContext>();\n CallContext.SetData(\"contexts\", contexts);\n }\n return contexts;\n }\n }\n\n public static DatabaseContext GetOpenConnection() \n {\n return new DatabaseContext(DatabaseContexts);\n }\n\n\n public SqlCommand CreateCommand(string sql)\n {\n var cmd = new SqlCommand(sql);\n cmd.Connection = connection;\n return cmd;\n }\n\n public void Dispose()\n {\n if (first)\n {\n connection.Close();\n }\n currentContexts.Remove(this);\n }\n}\n\n\n\nvoid Test()\n{\n // connection is opened here\n using (var ctx = DatabaseContext.GetOpenConnection())\n {\n using (var cmd = ctx.CreateCommand(\"select 1\"))\n {\n cmd.ExecuteNonQuery(); \n }\n\n Test2(); \n }\n // closed after dispose\n}\n\nvoid Test2()\n{\n // reuse existing connection \n using (var ctx = DatabaseContext.GetOpenConnection())\n {\n using (var cmd = ctx.CreateCommand(\"select 2\"))\n {\n cmd.ExecuteNonQuery();\n }\n }\n // leaves connection open\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11907/" ]
251,622
<p>I'm looking for a tool that can pretty-print (AKA tidy or beautify) source code in as many languages as possible. Those I'm particularly keen on include:</p> <ul> <li>Java </li> <li>JSP </li> <li>HTML </li> <li>JavaScript </li> <li>SQL</li> <li>JSON</li> <li>XML</li> </ul> <p>Ideally, the tool should be able to update source files in-place and be able to format more than a single file at-a-time. It would be great if it could format files containing multiple languages (e.g. a JSP containing HTML, Java, and JavaScript source code), but that's probably asking for a bit much.</p> <p>I've already found a <a href="http://www.polystyle.com/" rel="noreferrer">commercial tool</a> that seems to cover a lot of languages, but a free one would be even better :)</p> <p>BTW, I know there is a pretty printer available for most languages, but what I'm looking for is a "one-stop shop".</p> <p>Cheers, Don</p>
[ { "answer_id": 251835, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "~/bin/pp.hs #!/usr/bin/env runhaskell\nmodule Main (main) where\nimport Language.Haskell.Parser\nimport Language.Haskell.Pretty\nimport System.Environment\npp f = case parseModule f\n of ParseOk m -> prettyPrint m\n a -> show a\nmain = do args <- getArgs\n mapM_ (>>= putStrLn . pp) $\n if null args then [getContents] else map readFile args\n :set equalprg=~/bin/pp.hs =" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
251,636
<p>ExtJS has Ext.each() function, but is there a map() also hidden somewhere?</p> <p>I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.</p> <p>Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write:</p> <pre><code>Ext.map = function(arr, f) { ... }; </code></pre> <p>But is this really the correct way to do this?</p>
[ { "answer_id": 251689, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "map if(Ext && typeof(Ext.map) == \"undefined\") { // only if Ext exists & map isn't already defined\n Ext.map = function(arr, f) { ... };\n}\n" }, { "answer_id": 252049, "author": "Rene Saarsoo", "author_id": 15982, "author_profile": "https://Stackoverflow.com/users/15982", "pm_score": 3, "selected": true, "text": "[1, 2, 3].map( function(){ ... } );\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15982/" ]
251,637
<p>Anyone know where to find a reference that describes how to output color on the Windows CLI interfaces using API and/or stdout?</p>
[ { "answer_id": 251697, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "color bg fg\n 0: Black\n1: Blue\n2: Green\n3: Cyan\n4: Red\n5: Purple\n6: Yellow\n7: Gray\n8: Silver\n9: Light blue\nA: Lime\nB: Light cyan\nC: Light red\nD: Light purple\nE: Light yellow\nF: White\n color 80\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26227/" ]
251,651
<p>I have a table of about a million rows and I need to update every row in the table with the result of a lengthy calculation (the calculation gets a potentially different result for each row). Because it is time consuming, the DBA must be able to control execution. This particular calculation needs to be run once a year (it does a year-end summary). I wanted to create a job using DBMS_SCHEDULER.CREATE_JOB that would grab 100 rows from the table, update them and then stop; the next execution of the job would then pick up where the prior execution left off.</p> <p>My first thought was to include this code at the end of my stored procedure:</p> <pre><code>-- update 100 rows, storing the primary key of the last -- updated row in last_id -- make a new job that will run in about a minute and will -- start from the primary key value just after last_id dbms_scheduler.create_job ( job_name=&gt;'yearly_summary' , job_type=&gt;'STORED_PROCEDURE' , job_action=&gt;'yearly_summary_proc(' || last_id || ')' , start_date=&gt;CURRENT_TIMESTAMP + 1/24/60 , enabled=&gt;TRUE ); </code></pre> <p>But I get this error when the stored procedure runs:</p> <pre><code>ORA-27486: insufficient privileges ORA-06512: at "SYS.DBMS_ISCHED", line 99 ORA-06512: at "SYS.DBMS_SCHEDULER", line 262 ORA-06512: at "JBUI.YEARLY_SUMMARY_PROC", line 37 ORA-06512: at line 1 </code></pre> <p>Suggestions for other ways to do this are welcome. I'd prefer to use DBMS_SCHEDULER and I'd prefer not to have to create any tables; that's why I'm passing in the last_id to the stored procedure.</p>
[ { "answer_id": 251725, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": "DBMS_ALERT.WAITONE PAUSE_YEAREND_JOB RESUME_YEAREND_JOB PAUSE_YEAREND_JOB" }, { "answer_id": 252696, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "DBMS_ALERT DBMS_APPLICATION_INFO.SET_SESSION_LONGOPS" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3275/" ]
251,659
<p>I have created a json object from ruby with cobravsmongoose, however the attributes have the <strong><code>@</code></strong> symbol in front of them. Whenever I try to access them with standard object notation in JavaScript, such as <code>object.object.object.@attribute</code> I get a <em>parse error</em>. Is there another way to access these objects?</p>
[ { "answer_id": 251725, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": "DBMS_ALERT.WAITONE PAUSE_YEAREND_JOB RESUME_YEAREND_JOB PAUSE_YEAREND_JOB" }, { "answer_id": 252696, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "DBMS_ALERT DBMS_APPLICATION_INFO.SET_SESSION_LONGOPS" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3484/" ]
251,675
<p>I have a requirement to produce a Web User Control (in C#) which will exhibit different behaviour when clicked depending on whether the shift (or control) key is pressed at the time. The control itself will contain an ImageButton and/or Hyperlink.</p> <p>Is this possible?</p> <p>Basically, if the logged in user is an Admin then I need to allow them access to update the associated URL. I don't want to have a separate page for this admin as it will cause confusion.</p> <p>Thanks in advance</p>
[ { "answer_id": 251681, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "event.ctrlKey event.altKey event.shiftKey event.modifiers" }, { "answer_id": 251687, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "window" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31580/" ]
251,688
<p>Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?</p> <pre><code>$ar = array(array(1, 10, 9.0, 'HELLO'), array(1, 11, 12.9, 'HELLO'), array(3, 12, 10.9, 'HELLO')); </code></pre> <p>Output should be like:</p> <p>max(12.9) min(10)</p>
[ { "answer_id": 251721, "author": "belunch", "author_id": 32867, "author_profile": "https://Stackoverflow.com/users/32867", "pm_score": 2, "selected": true, "text": "<?php\n$ar = array(array(1, 10, 9.0, 'HELLO'),\n array(1, 11, 12.9, 'HELLO'),\n array(3, 12, 10.9, 'HELLO'));\nfunction col($tbl,$col){\n $ret = array();\n foreach ($tbl as $row){\n $ret[count($ret)+1] = $row[$col];\n }\n return $ret;\n}\nprint (max(col($ar,2)).\"\\n\");\nprint (min(col($ar,1)).\"\\n\");\n?>\n" }, { "answer_id": 251754, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "<?php\n\nfunction array_rotate( $array )\n{\n $rotated = array();\n foreach ( $array as $rowIndex => $col )\n {\n foreach ( $col as $colIndex => $value )\n {\n $rotated[$colIndex][$rowIndex] = $value;\n }\n }\n return $rotated;\n}\n\n$ar = array(array(1, 10, 9.0, 'HELLO'),\n array(1, 11, 12.9, 'HELLO'),\n array(3, 12, 10.9, 'HELLO'));\n\n$ar = array_rotate( $ar );\n\necho max( $ar[2] ), \"\\n\", min( $ar[1] );\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
251,694
<p>I have Perl code which relies on <code>Term::ReadKey</code> to get the terminal width. My installation is missing this module, so I want to provide a default if the module isn't present rather than throw an exception.</p> <p>How can I conditionally use an optional module, without knowing ahead of time whether it is available.</p> <pre><code># but only if the module is installed and exists use Term::ReadKey; ... </code></pre> <p>How can I accomplish this?</p>
[ { "answer_id": 251786, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 8, "selected": true, "text": "my $rc = eval\n{\n require Term::ReadKey;\n Term::ReadKey->import();\n 1;\n};\n\nif($rc)\n{\n # Term::ReadKey loaded and imported successfully\n ...\n}\n eval { use SomeModule } use SomeModule use eval 'use SomeModule'; require import eval { ... } $@" }, { "answer_id": 261474, "author": "Hinrik", "author_id": 10689, "author_profile": "https://Stackoverflow.com/users/10689", "pm_score": 2, "selected": false, "text": "my $GOT_READKEY;\nBEGIN {\n eval {\n require Term::ReadKey;\n Term::ReadKey->import();\n $GOT_READKEY = 1 if $Term::ReadKey::VERSION >= 2.30;\n };\n}\n\n\n# elsewhere in the code\nif ($GOT_READKEY) {\n # ...\n}\n" }, { "answer_id": 823638, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "if (eval {require Term::ReadKey;1;} ne 1) {\n# if module can't load\n} else {\nTerm::ReadKey->import();\n}\n if (eval {require Term::ReadKey;1;}) {\n#module loaded\nTerm::ReadKey->import();\n}\n 1; require Term::..." }, { "answer_id": 26519509, "author": "Utkarsh Kumar", "author_id": 1566968, "author_profile": "https://Stackoverflow.com/users/1566968", "pm_score": -1, "selected": false, "text": "$class = 'Foo::Bar';\n require $class; # $class is not a bareword\n #or\n require \"Foo::Bar\"; # not a bareword because of the \"\"\n eval \"require $class\";\n" }, { "answer_id": 64922599, "author": "Evan Carroll", "author_id": 124486, "author_profile": "https://Stackoverflow.com/users/124486", "pm_score": 0, "selected": false, "text": "use constant HAS_MODULE => defined eval { require Module };\n use constant HAS_READLINE => defined eval { require Term::ReadKey };\n\nmy $width = 80;\nif ( HAS_READLINE ) {\n $width = # ... code, override default.\n}\n use constant HAS_READLINE => defined eval { require Term::ReadKey };\nTerm::ReadKey->import if HAS_READLINE;\n" }, { "answer_id": 65610898, "author": "Elvin", "author_id": 13762488, "author_profile": "https://Stackoverflow.com/users/13762488", "pm_score": 2, "selected": false, "text": "use Module::Load::Conditional qw(check_install);\n\nuse if check_install(module => 'Clipboard') != undef, 'Clipboard'; # class methods: paste, copy\n undef" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
251,696
<p>What is the best way to read and/or set Internet Explorer options from a web page in Javascript? I know that these are in registry settings.</p> <p>For example, I'm using the <a href="http://www.lutanho.net/diagram/" rel="nofollow noreferrer">JavaScript Diagram Builder</a> to dynamically generate bar charts within a web page. This uses the background color in floating DIVs to generate the bars. I would like to be able to read the browser setting for printing background colors, and if not checked, either warn the user that the colors won't print, or programatically select this option.</p> <p>EDIT: As I think about the products that do something similar, I think they mostly just test whether Java or JavaScript or Cookies are disabled, which can be done without reading the registry.</p> <p>So I guess the consensus is that what I want to do shouldn't be attempted.</p>
[ { "answer_id": 251837, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 1, "selected": false, "text": "<style>\n div.bar\n {\n width:1px;\n border-left:10px solid red;\n }\n</style>\n<div class=\"bar\" style=\"height:100px\"></div>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26671/" ]
251,705
<p>Here is my situation: I know almost nothing about Perl but it is the only language available on a porting machine. I only have permissions to write in my local work area and not the Perl install location. I need to use the <a href="http://search.cpan.org/dist/Parallel-ForkManager" rel="noreferrer">Parallel::ForkManager</a> Perl module from CPAN </p> <p>How do I use this Parallel::ForkManager without doing a central install? Is there an environment variable that I can set so it is located?</p> <p>Thanks</p> <p>JD</p>
[ { "answer_id": 251766, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 6, "selected": true, "text": "perl Makefile.PL INSTALL_BASE=/mydir/perl\n % cpan\ncpan> o conf makepl_arg INSTALL_BASE=/mydir/perl\ncpan> o conf commit\n perl Build.PL --install_base /mydir/perl\n % cpan\ncpan> o conf mbuild_arg --install_base /mydir/perl\ncpan> o conf commit\n" }, { "answer_id": 251774, "author": "Alex", "author_id": 12204, "author_profile": "https://Stackoverflow.com/users/12204", "pm_score": 2, "selected": false, "text": "-I" }, { "answer_id": 251808, "author": "dexedrine", "author_id": 20266, "author_profile": "https://Stackoverflow.com/users/20266", "pm_score": 2, "selected": false, "text": "use lib 'directory';\nuse Parallel::ForkManager;\n" }, { "answer_id": 251820, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "-I" }, { "answer_id": 12144409, "author": "Viraj", "author_id": 1628007, "author_profile": "https://Stackoverflow.com/users/1628007", "pm_score": 2, "selected": false, "text": "perl Makefile.PL LIB=/my/perl_modules/lib/\nmake\nmake install\nPERL5LIB=$PERL5LIB:/my/perl_modules/lib/\nperl myperlcode.pl\n" }, { "answer_id": 21911478, "author": "ChathuraG", "author_id": 2437599, "author_profile": "https://Stackoverflow.com/users/2437599", "pm_score": 3, "selected": false, "text": "wget http://search.cpan.org/CPAN/authors/id/S/SZ/SZABGAB/Parallel-ForkManager-1.06.tar.gz\ngunzip Parallel-ForkManager-1.06.tar.gz\ntar -xvf Parallel-ForkManager-1.06.tar\n perl Makefile.PL PREFIX=/home/username/myModules\nmake\nmake test\nmake install\n use lib '/home/username/myModules/bin.../Parallel';\nuse parallel::ForkManager;\n" }, { "answer_id": 26688145, "author": "Ron Abraham", "author_id": 2742748, "author_profile": "https://Stackoverflow.com/users/2742748", "pm_score": 2, "selected": false, "text": "cpanm -l $DIR_NAME" }, { "answer_id": 57907772, "author": "serv-inc", "author_id": 1587329, "author_profile": "https://Stackoverflow.com/users/1587329", "pm_score": 1, "selected": false, "text": "perlbrew \\curl -L https://install.perlbrew.pl | bash\n\nperlbrew init # put this in .bash_profile etc\n\nperlbrew install 5.27.11\n\nperlbrew switch 5.27.11\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7743/" ]
251,711
<p>I have a SQL database (SQL Server 2008) which contains the following design</p> <h2>ITEM</h2> <ul> <li>ID (Int, Identity)</li> <li>Name (NVarChar(50))</li> <li>Description (NVarChar(200))</li> </ul> <h2>META</h2> <ul> <li>ID (Int, Identity)</li> <li>Name (NVarChar(50))</li> </ul> <p>There exists a N-N relationship between these two, i.e an Item can contain zero or more meta references and a meta can be associated with more than one item. Each meta can only be assocated with the same item once. This means I have the classic table in the middle</p> <h2>ITEMMETA</h2> <ul> <li>ItemID (Int)</li> <li>MetaID (Int)</li> </ul> <p>I would like to to execute a LinqToSql query to extract all of the item entities which contains a specific set of meta links. For example, give me all the Items which have the following meta items associated with it</p> <ul> <li>Car</li> <li>Ford</li> <li>Offroad</li> </ul> <p>Is it possible to write such a query with the help of LinqToSql? Let me provide some more requirements</p> <ul> <li>I will have a list of Meta tags I want to use to filter the items which will be returned (for example in the example above I had Car, Ford and Offroad)</li> <li>An item can have MORE meta items associated with it than what I provide in the match, i.e if an item had Car, Ford, Offroad and Red assocated to it then providing any combination of them in the filter should result in a match</li> <li>However ALL of the meta names which are provided in the filter MUST be assocated with an item for it to be returned in the resultset. So sending in Car, Ford, Offroad and Red SHOULD NOT be a match for an item which has Car, Ford and Offroad (no Red) associated with itself</li> </ul> <p>I hope its clear what I'm trying to achieve, I feel Im not being quite as clear as I'd hoped =/ Let's hope its enough :)</p> <p>Thank you!</p>
[ { "answer_id": 252011, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 1, "selected": false, "text": "var db = new YourDataContext();\nvar possibleItems = (from m in db.Metas where <meta criteria> select m.ItemMetas.Item);\n\nvar items = possibleItems.GroupBy(y=>y).Where(x=>x.Count() == criteriaCount).Select(x=>x.Key);\n" }, { "answer_id": 252152, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "List<string> metaList = new List<string>() { \"Car\", \"Ford\", \"Offroad\" };\nint metaListCount = metaList.Count;\nList<Item> result =\n db.Items\n .Where(i => metaListCount ==\n i.ItemMeta.Meta\n .Where(m => metaList.Contains(m.Name))\n .Count()\n )\n .ToList();\n" }, { "answer_id": 252647, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 3, "selected": true, "text": "string[] criteria = new[] { \"Car\", \"Ford\", \"Offroad\" };\n\nvar items = \n from i in db.Item\n let wantedMetas = db.Meta.Where(m => criteria.Contains(m.Name))\n let metas = i.ItemMeta.Select(im => im.Meta)\n where wantedMetas.All(m => metas.Contains(m))\n select i;\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25319/" ]
251,727
<p>I've set hibernate.generate_statistics=true and now need to register the mbeans so I can see the statistics in the jmx console. I can't seem to get anywhere and this doesn't seem like it should be such a difficult problem. Maybe I'm making things overcomplicated, but in any case so far I've tried:</p> <ul> <li>I copied EhCacheProvider and had it instantiate an extended version of CacheManager which overloaded init() and called ManagementService.registerMBeans(...) after initialization. The code all ran fine until the actual call to registerMBeans(...) which would cause the provider initialization to fail with a generic error (unfortunately I didn't write it down.) This approach was motivated by the methods used in <a href="http://www.kanonbra.com/index.php/projects/performance-testing/18-using-visualvm-on-liferay" rel="nofollow noreferrer">this liferay performance walkthrough.</a></li> <li>I created my own MBean with a start method that ran similar code to <a href="http://weblogs.java.net/blog/maxpoon/archive/2007/06/extending_the_n_2.html" rel="nofollow noreferrer">this example of registering ehcache's jmx mbeans</a>. Everything appeared to work correctly and my mbean shows up in the jmx console but nothing for net.sf.ehcache.</li> <li>I've since upgraded ehcache to 1.5 (we were using 1.3, not sure if that's specific to jboss 4.2.1 or just something we chose ourselves) and changed to using the SingletonEhCacheProvider and trying to just manually grab the statistics instead of dealing with the mbean registration. It hasn't really gone any better though; if I call getInstance() the CacheManager that's returned only has a copy of StandardQueryCache, but jboss logs show that many other caches have been initialized (one for each of the cached entities in our application.)</li> </ul> <p>EDIT: Well I have figured out one thing...connecting via JConsole does reveal the statistics mbeans. I guess ManagementFactory.getPlatformMBeanServer() doesn't give you the same mbean server as jboss is using. Anyway it looks like I'm encountering a similar problem as when I tried collecting the statistics manually, because I'm getting all zeros even after clicking through my app for a bit.</p>
[ { "answer_id": 251822, "author": "Matt S.", "author_id": 1458, "author_profile": "https://Stackoverflow.com/users/1458", "pm_score": 1, "selected": true, "text": "SessionFactory sf = (new Configuration()).configure().buildSessionFactory();\n EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"myPersistenceUnit\");\nreturn ((EntityManagerFactoryImpl)emf).getSessionFactory();\n import javax.ejb.Stateless;\nimport javax.persistence.PersistenceUnit;\nimport net.sf.ehcache.CacheManager;\nimport org.hibernate.SessionFactory;\n\n@Stateless\npublic class UtilMgrBean implements UtilMgr {\n // NOTE: rename as necessary\n @PersistenceUnit(unitName = \"myPersistenceCtx\")\n private SessionFactory sessionFactory;\n\n public SessionFactory getSessionFactory() {\n return this.sessionFactory;\n }\n\n public CacheManager getCacheManager() {\n return CacheManager.getInstance(); // NOTE: assumes SingletonEhCacheProvider\n }\n}\n try {\n // NOTE: lookupBean is a utility method in our app we use for jndi lookups.\n // replace as necessary for your application.\n UtilMgr utilMgr = (UtilMgr)Manager.lookupBean(\"UtilMgrBean\", UtilMgr.class);\n SessionFactory sf = utilMgr.getSessionFactory();\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n\n // NOTE: replace myAppName as necessary\n ObjectName on = new ObjectName(\"Hibernate:type=statistics,application=myAppName\");\n\n // Enable Hibernate JMX Statistics\n StatisticsService statsMBean = new StatisticsService();\n statsMBean.setSessionFactory(sf);\n statsMBean.setStatisticsEnabled(true);\n mbs.registerMBean(statsMBean, on);\n\n CacheManager cacheMgr = utilMgr.getCacheManager();\n ManagementService.registerMBeans(cacheMgr, mbs, true, true, true, true);\n} catch(Throwable t) {\n throw new RuntimeException(t);\n}\n" }, { "answer_id": 2591306, "author": "sans_sense", "author_id": 310818, "author_profile": "https://Stackoverflow.com/users/310818", "pm_score": 1, "selected": false, "text": "@Name(\"hibernateStatistics\")\n@Scope(ScopeType.APPLICATION)\n@Startup\npublic class HibernateUtils {\n@In\nprivate EntityManager entityManager;\n\n@Create\npublic void onStartup() {\n if (entityManager != null) {\n try {\n //lookup the jboss mbean server\n MBeanServer beanServer = org.jboss.mx.util.MBeanServerLocator.locateJBoss();\n StatisticsService mBean = new StatisticsService();\n ObjectName objectName = new ObjectName(\"Hibernate:type=statistics,application=<application-name>\");\n try{\n beanServer.unregisterMBean(objectName);\n }catch(Exception exc) {\n //no problems, as unregister is not important\n }\n SessionFactory sessionFactory = ((HibernateSessionProxy) entityManager.getDelegate()).getSessionFactory();\n mBean.setSessionFactory(sessionFactory);\n beanServer.registerMBean(mBean, objectName);\n\n if (sessionFactory instanceof SessionFactoryImplementor ){\n CacheProvider cacheProvider = ((SessionFactoryImplementor)sessionFactory).getSettings().getCacheProvider();\n if (cacheProvider instanceof EhCacheProvider) {\n try{\n Field field = EhCacheProvider.class.getDeclaredField(\"manager\");\n field.setAccessible(true);\n CacheManager cacheMgr = (CacheManager) field.get(cacheProvider);\n ManagementService.registerMBeans(cacheMgr, beanServer, true, true, true, true);\n }catch(Exception exc) {\n //do nothing\n exc.printStackTrace();\n }\n }\n }\n\n } catch (Exception e) {\n throw new RuntimeException(\"The persistence context \" + entityManager.toString() + \"is not properly configured.\", e);\n }\n }\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458/" ]
251,730
<p>We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation.</p> <p>Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build.</p> <p>Of course we can use the surefire plugin's exclusion mechanism and just punt them from the build, but ideally we'd love something that would allow the developer to run them at will through Maven 2.</p>
[ { "answer_id": 251760, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 5, "selected": true, "text": " <profile>\n <id>integrationtest</id>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <configuration>\n <argLine>-client -Xmx896m -XX:MaxPermSize=192m</argLine>\n <forkMode>once</forkMode>\n <includes>\n <include>**/**/*Test.java</include>\n <include>**/**/*IntTest.java</include>\n </includes>\n <excludes>\n <exclude>**/**/*SeleniumTest.java</exclude>\n </excludes>\n </configuration>\n </plugin>\n </plugins>\n </build>\n <activation>\n <property>\n <name>integrationtest</name>\n </property>\n </activation>\n </profile>\n" }, { "answer_id": 549838, "author": "Matthew McCullough", "author_id": 56039, "author_profile": "https://Stackoverflow.com/users/56039", "pm_score": 1, "selected": false, "text": "mvn shitty:clean shitty:install shitty:test <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>shitty-maven-plugin</artifactId>\n </plugin>\n</plugins>\n" }, { "answer_id": 7325398, "author": "Joel Westberg", "author_id": 840333, "author_profile": "https://Stackoverflow.com/users/840333", "pm_score": 2, "selected": false, "text": "<profile>\n <id>normal</id>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <configuration>\n <excludes>\n <exclude>**/**/*IntTest.java</exclude>\n </excludes>\n </configuration>\n </plugin>\n </plugins>\n </build>\n <activation>\n <activeByDefault>true</activeByDefault>\n </activation>\n</profile>\n mvn -P integrationtest clean install\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32514/" ]
251,746
<p>I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works.</p> <pre><code>import scalax.data._ import scalax.io.CommandLineParser class TestCLI(arguments: Array[String]) extends CommandLineParser { private val opt1Option = new Flag("p", "print") with AllowAll private val opt2Option = new Flag("o", "out") with AllowAll private val strOption = new StringOption("v", "value") with AllowAll private val result = parse(arguments) // true or false val opt1 = result(opt1Option) val opt2 = result(opt2Option) val str = result(strOption) } </code></pre>
[ { "answer_id": 252007, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "Bistate Either Bistate Either Option None Either def div(a: Int, b: Int) = if (b != 0) Left(a / b) else Right(\"Divide by zero\")\n\ndiv(4, 2) match {\n case Left(x) => println(\"Result: \" + x)\n case Right(e) => Println(\"Error: \" + e)\n}\n Result: 2 Either Left Right" }, { "answer_id": 256638, "author": "JtR", "author_id": 30958, "author_profile": "https://Stackoverflow.com/users/30958", "pm_score": 0, "selected": false, "text": "val opt1 = result(opt1Option) match {\n case Positive(_) => true\n case Negative(_) => false\n}\n" }, { "answer_id": 260444, "author": "Germán", "author_id": 17138, "author_profile": "https://Stackoverflow.com/users/17138", "pm_score": 3, "selected": true, "text": "val opt1 = result(opt1Option).isInstanceOf[Positive[_]]\nval opt2 = result(opt2Option).posValue.isDefined\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30958/" ]
251,753
<p>Using VB.net (.net 2.0) I have a string in this format:</p> <pre><code>record1_field1,record1_field2,record2_field3,record2_field1,record2_field2, </code></pre> <p>etc...</p> <p>I wonder what the best (easiest) way is to get this into an xml?</p> <p>I can think of 2 ways:</p> <p>Method 1: - use split to get the items in an array - loop through array and build an xml string using concatenation</p> <p>Method 2: - use split to get the items in an array - loops through array to build a datatable - use writexml to output xml from the datatable</p> <p>The first sounds pretty simple but would require more logic to build the string.</p> <p>The second seems slicker and easier to understand.</p> <p>Are there other ways to do this?</p>
[ { "answer_id": 251770, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 3, "selected": true, "text": "\nXmlDocument doc = new XmlDocuent();\n\nstring[] data = csv.split(',');\n\nXmlNode = doc.CreateElement(\"root\");\nforeach(string str in data)\n{\n XmlNode node = doc.CreateElement(\"data\");\n node.innerText = str;\n root.AppendChild(node);\n}\nConsole.WriteLine(doc.InnerXML);\n \n<root>\n <data>field 1</data>\n <data>field 2</data>\n <data>field 3</data>\n</root>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32892/" ]
251,759
<p>I'm writing an application that uses renaming rules to rename a list of files based on information given by the user. The files may be inconsistently named to begin with, or the filenames may be consistent. The user selects a list of files, and inputs information about the files (for MP3s, they would be Artist, Title, Album, etc). Using a rename rule (example below), the program uses the user-inputted information to rename the files accordingly.</p> <p>However, if all or some the files are named consistently, I would like to allow the program to 'guess' the file information. That is the problem I'm having. What is the best way to do this?</p> <p>Sample filenames:</p> <pre><code>Kraftwerk-Kraftwerk-01-RuckZuck.mp3 Kraftwerk-Autobahn-01-Autobahn.mp3 Kraftwerk-Computer World-03-Numbers.mp3 </code></pre> <p>Rename Rule:</p> <pre><code>%Artist%-%Album%-%Track%-%Title%.mp3 </code></pre> <p>The program should properly deduce the Artist, Track number, Title, and Album name.</p> <p>Again, what's the best way to do this? I was thinking regular expressions, but I'm a bit confused.</p>
[ { "answer_id": 251897, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": true, "text": "%Label% (?<Label>.*?) %Artist%-%Album%-%Track%-%Title%.mp3\n (?<Artist>.*?)-(?<Album>.*?)-(?<Track>.*?)-(?<Title>.*?)\\.mp3\n Dictinary<string,string> match_filename(string rule, string filename) {\n Regex tag_re = new Regex(@'%(\\w+)%');\n string pattern = tag_re.Replace(Regex.escape(rule), @'(?<$1>.*?)');\n Regex filename_re = new Regex(pattern);\n Match match = filename_re.Match(filename);\n\n Dictionary<string,string> tokens =\n new Dictionary<string,string>();\n for (int counter = 1; counter < match.Groups.Count; counter++)\n {\n string group_name = filename_re.GroupNameFromNumber(counter);\n tokens.Add(group_name, m.Groups[counter].Value);\n }\n return tokens;\n}\n %Artist%%Album% (?<Artist>.*?)(?<Album>.*?) .*?.*? %Track% (?<Track>\\d+) Track" }, { "answer_id": 256740, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": 0, "selected": false, "text": "<artist>-<album>-<track>-<title>.mp3\n <title.upper>-<3|track+10>-<album.lower>-<artist>.mp3\n Kraftwerk-Computer World-03-Numbers.mp3\n NUMBERS-013-computer world-Kraftwerk.mp3\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29249/" ]
251,778
<p>Are there, in the canonical Gang of Four list, any design patterns that you often find misused, misunderstood or overused (other than the highly debated Singleton)? In other words, is there a design pattern you would advise to think twice before using? (And why?)</p>
[ { "answer_id": 251810, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 4, "selected": false, "text": "MyObject MyObjectFactory" }, { "answer_id": 251995, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "if (account1.balance > 1000)\n{\n account1.balance = account1.balance - 1000;\n account2.balance = account2.balance + 1000;\n}; = BAD CODE. \n\naccount2.deposit(account1.withdraw(1000)); = GOOD CODE. \n" }, { "answer_id": 38773369, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 0, "selected": false, "text": "Visitor Visitor" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
251,781
<p>I believe there's a way to find the kth largest element in an unsorted array of length n in O(n). Or perhaps it's "expected" O(n) or something. How can we do this?</p>
[ { "answer_id": 251797, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 4, "selected": false, "text": "\"Make one pass through tracking the three largest values so far.\" \n Build a heap/priority queue. O(n)\nPop top element. O(log n)\nPop top element. O(log n)\nPop top element. O(log n)\n\nTotal = O(n) + 3 O(log n) = O(n)\n" }, { "answer_id": 251818, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": -1, "selected": false, "text": "initialize empty doubly linked list l\nfor each element e in array\n if e larger than head(l)\n make e the new head of l\n if size(l) > k\n remove last element from l\n\nthe last element of l should now be the kth largest element\n initialize empty sorted tree l\nfor each element e in array\n if e between head(l) and tail(l)\n insert e into l // O(log k)\n if size(l) > k\n remove last element from l\n\nthe last element of l should now be the kth largest element\n" }, { "answer_id": 251884, "author": "eladv", "author_id": 7314, "author_profile": "https://Stackoverflow.com/users/7314", "pm_score": 8, "selected": true, "text": "O(n) O(n^2) O(n) O(n) Select(A,n,i):\n Divide input into ⌈n/5⌉ groups of size 5.\n\n /* Partition on median-of-medians */\n medians = array of each group’s median.\n pivot = Select(medians, ⌈n/5⌉, ⌈n/10⌉)\n Left Array L and Right Array G = partition(A, pivot)\n\n /* Find ith element in L, pivot, or G */\n k = |L| + 1\n If i = k, return pivot\n If i < k, return Select(L, k-1, i)\n If i > k, return Select(G, n-k, i-k)\n" }, { "answer_id": 252047, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "nth_element const int N = ...;\ndouble a[N];\n// ... \nconst int m = ...; // m < N\nnth_element (a, a + m, a + N);\n// a[m] contains the mth element in a\n" }, { "answer_id": 255128, "author": "Ying Xiao", "author_id": 30202, "author_profile": "https://Stackoverflow.com/users/30202", "pm_score": 7, "selected": false, "text": "O(n) O(kn) n QuickSelect(A, k)\n let r be chosen uniformly at random in the range 1 to length(A)\n let pivot = A[r]\n let A1, A2 be new arrays\n # split into a pile A1 of small elements and A2 of big elements\n for i = 1 to n\n if A[i] < pivot then\n append A[i] to A1\n else if A[i] > pivot then\n append A[i] to A2\n else\n # do nothing\n end for\n if k <= length(A1):\n # it's in the pile of small elements\n return QuickSelect(A1, k)\n else if k > length(A) - length(A2)\n # it's in the pile of big elements\n return QuickSelect(A2, k - (length(A) - length(A2))\n else\n # it's equal to the pivot\n return pivot\n k T(n) = Theta(n) + T(n-1) = Theta(n2) T(n) <= Theta(n) + (1/n) ∑i=1 to nT(max(i, n-i-1)) A1 A2 T(n) <= an a T(n) \n <= cn + (1/n) ∑i=1 to nT(max(i-1, n-i))\n = cn + (1/n) ∑i=1 to floor(n/2) T(n-i) + (1/n) ∑i=floor(n/2)+1 to n T(i)\n <= cn + 2 (1/n) ∑i=floor(n/2) to n T(i)\n <= cn + 2 (1/n) ∑i=floor(n/2) to n ai cn 2(1/n) ∑i=n/2 to n an 2(1/n)(n/2)an = an cn ∑i=floor(n/2) to n i \n = ∑i=1 to n i - ∑i=1 to floor(n/2) i \n = n(n+1)/2 - floor(n/2)(floor(n/2)+1)/2 \n <= n2/2 - (n/4)2/2 \n = (15/32)n2 floor(n/2) n/4 cn + 2 (1/n) ∑i=floor(n/2) to n ai,\n <= cn + (2a/n) (15/32) n2\n = n (c + (15/16)a)\n <= an a > 16c T(n) = O(n) Omega(n) T(n) = Theta(n)" }, { "answer_id": 7103794, "author": "prithvi zankat", "author_id": 606270, "author_profile": "https://Stackoverflow.com/users/606270", "pm_score": 2, "selected": false, "text": "public int quickSelect(ArrayList<Integer>list, int nthSmallest){\n //Choose random number in range of 0 to array length\n Random random = new Random();\n //This will give random number which is not greater than length - 1\n int pivotIndex = random.nextInt(list.size() - 1); \n\n int pivot = list.get(pivotIndex);\n\n ArrayList<Integer> smallerNumberList = new ArrayList<Integer>();\n ArrayList<Integer> greaterNumberList = new ArrayList<Integer>();\n\n //Split list into two. \n //Value smaller than pivot should go to smallerNumberList\n //Value greater than pivot should go to greaterNumberList\n //Do nothing for value which is equal to pivot\n for(int i=0; i<list.size(); i++){\n if(list.get(i)<pivot){\n smallerNumberList.add(list.get(i));\n }\n else if(list.get(i)>pivot){\n greaterNumberList.add(list.get(i));\n }\n else{\n //Do nothing\n }\n }\n\n //If smallerNumberList size is greater than nthSmallest value, nthSmallest number must be in this list \n if(nthSmallest < smallerNumberList.size()){\n return quickSelect(smallerNumberList, nthSmallest);\n }\n //If nthSmallest is greater than [ list.size() - greaterNumberList.size() ], nthSmallest number must be in this list\n //The step is bit tricky. If confusing, please see the above loop once again for clarification.\n else if(nthSmallest > (list.size() - greaterNumberList.size())){\n //nthSmallest will have to be changed here. [ list.size() - greaterNumberList.size() ] elements are already in \n //smallerNumberList\n nthSmallest = nthSmallest - (list.size() - greaterNumberList.size());\n return quickSelect(greaterNumberList,nthSmallest);\n }\n else{\n return pivot;\n }\n}\n" }, { "answer_id": 15144377, "author": "totjammykd", "author_id": 2056223, "author_profile": "https://Stackoverflow.com/users/2056223", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint findMedian(vector<int> vec){\n// Find median of a vector\n int median;\n size_t size = vec.size();\n median = vec[(size/2)];\n return median;\n}\n\nint findMedianOfMedians(vector<vector<int> > values){\n vector<int> medians;\n\n for (int i = 0; i < values.size(); i++) {\n int m = findMedian(values[i]);\n medians.push_back(m);\n }\n\n return findMedian(medians);\n}\n\nvoid selectionByMedianOfMedians(const vector<int> values, int k){\n// Divide the list into n/5 lists of 5 elements each\n vector<vector<int> > vec2D;\n\n int count = 0;\n while (count != values.size()) {\n int countRow = 0;\n vector<int> row;\n\n while ((countRow < 5) && (count < values.size())) {\n row.push_back(values[count]);\n count++;\n countRow++;\n }\n vec2D.push_back(row);\n }\n\n cout<<endl<<endl<<\"Printing 2D vector : \"<<endl;\n for (int i = 0; i < vec2D.size(); i++) {\n for (int j = 0; j < vec2D[i].size(); j++) {\n cout<<vec2D[i][j]<<\" \";\n }\n cout<<endl;\n }\n cout<<endl;\n\n// Calculating a new pivot for making splits\n int m = findMedianOfMedians(vec2D);\n cout<<\"Median of medians is : \"<<m<<endl;\n\n// Partition the list into unique elements larger than 'm' (call this sublist L1) and\n// those smaller them 'm' (call this sublist L2)\n vector<int> L1, L2;\n\n for (int i = 0; i < vec2D.size(); i++) {\n for (int j = 0; j < vec2D[i].size(); j++) {\n if (vec2D[i][j] > m) {\n L1.push_back(vec2D[i][j]);\n }else if (vec2D[i][j] < m){\n L2.push_back(vec2D[i][j]);\n }\n }\n }\n\n// Checking the splits as per the new pivot 'm'\n cout<<endl<<\"Printing L1 : \"<<endl;\n for (int i = 0; i < L1.size(); i++) {\n cout<<L1[i]<<\" \";\n }\n\n cout<<endl<<endl<<\"Printing L2 : \"<<endl;\n for (int i = 0; i < L2.size(); i++) {\n cout<<L2[i]<<\" \";\n }\n\n// Recursive calls\n if ((k - 1) == L1.size()) {\n cout<<endl<<endl<<\"Answer :\"<<m;\n }else if (k <= L1.size()) {\n return selectionByMedianOfMedians(L1, k);\n }else if (k > (L1.size() + 1)){\n return selectionByMedianOfMedians(L2, k-((int)L1.size())-1);\n }\n\n}\n\nint main()\n{\n int values[] = {2, 3, 5, 4, 1, 12, 11, 13, 16, 7, 8, 6, 10, 9, 17, 15, 19, 20, 18, 23, 21, 22, 25, 24, 14};\n\n vector<int> vec(values, values + 25);\n\n cout<<\"The given array is : \"<<endl;\n for (int i = 0; i < vec.size(); i++) {\n cout<<vec[i]<<\" \";\n }\n\n selectionByMedianOfMedians(vec, 8);\n\n return 0;\n}\n" }, { "answer_id": 19089380, "author": "Chris Cinelli", "author_id": 407245, "author_profile": "https://Stackoverflow.com/users/407245", "pm_score": 0, "selected": false, "text": "function kthMax(a, k){\n var size = a.length;\n\n var pivot = a[ parseInt(Math.random()*size) ]; //Another choice could have been (size / 2) \n\n //Create an array with all element lower than the pivot and an array with all element higher than the pivot\n var i, lowerArray = [], upperArray = [];\n for (i = 0; i < size; i++){\n var current = a[i];\n\n if (current < pivot) {\n lowerArray.push(current);\n } else if (current > pivot) {\n upperArray.push(current);\n }\n }\n\n //Which one should I continue with?\n if(k <= upperArray.length) {\n //Upper\n return kthMax(upperArray, k);\n } else {\n var newK = k - (size - lowerArray.length);\n\n if (newK > 0) {\n ///Lower\n return kthMax(lowerArray, newK);\n } else {\n //None ... it's the current pivot!\n return pivot;\n } \n }\n} \n function kthMax (a, k, logging) {\n var comparisonCount = 0; //Number of comparison that the algorithm uses\n var memoryCount = 0; //Number of integers in memory that the algorithm uses\n var _log = logging;\n\n if(k < 0 || k >= a.length) {\n if (_log) console.log (\"k is out of range\"); \n return false;\n } \n\n function _kthmax(a, k){\n var size = a.length;\n var pivot = a[parseInt(Math.random()*size)];\n if(_log) console.log(\"Inputs:\", a, \"size=\"+size, \"k=\"+k, \"pivot=\"+pivot);\n\n // This should never happen. Just a nice check in this exercise\n // if you are playing with the code to avoid never ending recursion \n if(typeof pivot === \"undefined\") {\n if (_log) console.log (\"Ops...\"); \n return false;\n }\n\n var i, lowerArray = [], upperArray = [];\n for (i = 0; i < size; i++){\n var current = a[i];\n if (current < pivot) {\n comparisonCount += 1;\n memoryCount++;\n lowerArray.push(current);\n } else if (current > pivot) {\n comparisonCount += 2;\n memoryCount++;\n upperArray.push(current);\n }\n }\n if(_log) console.log(\"Pivoting:\",lowerArray, \"*\"+pivot+\"*\", upperArray);\n\n if(k <= upperArray.length) {\n comparisonCount += 1;\n return _kthmax(upperArray, k);\n } else if (k > size - lowerArray.length) {\n comparisonCount += 2;\n return _kthmax(lowerArray, k - (size - lowerArray.length));\n } else {\n comparisonCount += 2;\n return pivot;\n }\n /* \n * BTW, this is the logic for kthMin if we want to implement that... ;-)\n * \n\n if(k <= lowerArray.length) {\n return kthMin(lowerArray, k);\n } else if (k > size - upperArray.length) {\n return kthMin(upperArray, k - (size - upperArray.length));\n } else \n return pivot;\n */ \n }\n\n var result = _kthmax(a, k);\n return {result: result, iterations: comparisonCount, memory: memoryCount};\n }\n function getRandomArray (n){\n var ar = [];\n for (var i = 0, l = n; i < l; i++) {\n ar.push(Math.round(Math.random() * l))\n }\n\n return ar;\n }\n\n //Create a random array of 50 numbers\n var ar = getRandomArray (50); \n kthMax(ar, 2, true);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 34, true);\n kthMax(ar, 34);\n kthMax(ar, 34);\n kthMax(ar, 34);\n kthMax(ar, 34);\n kthMax(ar, 34);\n" }, { "answer_id": 24893260, "author": "hoder", "author_id": 2525478, "author_profile": "https://Stackoverflow.com/users/2525478", "pm_score": 2, "selected": false, "text": "def quickselect(arr, k):\n '''\n k = 1 returns first element in ascending order.\n can be easily modified to return first element in descending order\n '''\n\n r = random.randrange(0, len(arr))\n\n a1 = [i for i in arr if i < arr[r]] '''partition'''\n a2 = [i for i in arr if i > arr[r]]\n\n if k <= len(a1):\n return quickselect(a1, k)\n elif k > len(arr)-len(a2):\n return quickselect(a2, k - (len(arr) - len(a2)))\n else:\n return arr[r]\n" }, { "answer_id": 26725019, "author": "estama", "author_id": 4212243, "author_profile": "https://Stackoverflow.com/users/4212243", "pm_score": 1, "selected": false, "text": "#define F_SWAP(a,b) { float temp=(a);(a)=(b);(b)=temp; }\n\n# Note: The code needs more than 2 elements to work\nfloat lefselect(float a[], const int n, const int k) {\n int l=0, m = n-1, i=l, j=m;\n float x;\n\n while (l<m) {\n if( a[k] < a[i] ) F_SWAP(a[i],a[k]);\n if( a[j] < a[i] ) F_SWAP(a[i],a[j]);\n if( a[j] < a[k] ) F_SWAP(a[k],a[j]);\n\n x=a[k];\n while (j>k & i<k) {\n do i++; while (a[i]<x);\n do j--; while (a[j]>x);\n\n F_SWAP(a[i],a[j]);\n }\n i++; j--;\n\n if (j<k) {\n while (a[i]<x) i++;\n l=i; j=m;\n }\n if (k<i) {\n while (x<a[j]) j--;\n m=j; i=l;\n }\n }\n return a[k];\n}\n" }, { "answer_id": 28120511, "author": "user3585010", "author_id": 3585010, "author_profile": "https://Stackoverflow.com/users/3585010", "pm_score": 1, "selected": false, "text": "kthElem index list = sort list !! index\n\nwithShape ~[] [] = []\nwithShape ~(x:xs) (y:ys) = x : withShape xs ys\n\nsort [] = []\nsort (x:xs) = (sort ls `withShape` ls) ++ [x] ++ (sort rs `withShape` rs)\n where\n ls = filter (< x)\n rs = filter (>= x)\n" }, { "answer_id": 29729453, "author": "learner", "author_id": 1672427, "author_profile": "https://Stackoverflow.com/users/1672427", "pm_score": 1, "selected": false, "text": "#include<iostream>\n#include<climits>\n#include<cstdlib>\nusing namespace std;\n\nint randomPartition(int arr[], int l, int r);\n\n// This function returns k'th smallest element in arr[l..r] using\n// QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT\nint kthSmallest(int arr[], int l, int r, int k)\n{\n // If k is smaller than number of elements in array\n if (k > 0 && k <= r - l + 1)\n {\n // Partition the array around a random element and\n // get position of pivot element in sorted array\n int pos = randomPartition(arr, l, r);\n\n // If position is same as k\n if (pos-l == k-1)\n return arr[pos];\n if (pos-l > k-1) // If position is more, recur for left subarray\n return kthSmallest(arr, l, pos-1, k);\n\n // Else recur for right subarray\n return kthSmallest(arr, pos+1, r, k-pos+l-1);\n }\n\n // If k is more than number of elements in array\n return INT_MAX;\n}\n\nvoid swap(int *a, int *b)\n{\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\n// Standard partition process of QuickSort(). It considers the last\n// element as pivot and moves all smaller element to left of it and\n// greater elements to right. This function is used by randomPartition()\nint partition(int arr[], int l, int r)\n{\n int x = arr[r], i = l;\n for (int j = l; j <= r - 1; j++)\n {\n if (arr[j] <= x) //arr[i] is bigger than arr[j] so swap them\n {\n swap(&arr[i], &arr[j]);\n i++;\n }\n }\n swap(&arr[i], &arr[r]); // swap the pivot\n return i;\n}\n\n// Picks a random pivot element between l and r and partitions\n// arr[l..r] around the randomly picked element using partition()\nint randomPartition(int arr[], int l, int r)\n{\n int n = r-l+1;\n int pivot = rand() % n;\n swap(&arr[l + pivot], &arr[r]);\n return partition(arr, l, r);\n}\n\n// Driver program to test above methods\nint main()\n{\n int arr[] = {12, 3, 5, 7, 4, 19, 26};\n int n = sizeof(arr)/sizeof(arr[0]), k = 3;\n cout << \"K'th smallest element is \" << kthSmallest(arr, 0, n-1, k);\n return 0;\n}\n" }, { "answer_id": 31862041, "author": "advncd", "author_id": 996926, "author_profile": "https://Stackoverflow.com/users/996926", "pm_score": 0, "selected": false, "text": "define variables a=0, b=0, c=0\niterate through the array items\n find minimum a,b,c\n if item > min then replace the min variable with item value\n continue until end of array\nthe minimum of a,b,c is our answer\n [1,2,4,1,7,3,9,5,6,2,9,8]\n\nFinal variable values:\n\na=7 (answer)\nb=8\nc=9\n" }, { "answer_id": 32394237, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 2, "selected": false, "text": "O(n) k <= n/2 cn c cn/2 cn/4 cn + cn/2 + cn/4 +\n .... = 2cn = o(n) 3n/10 T(n) = T(n/5)+T(7n/10)+O(n). Since n/5+7n/10 < 1 O(n) public static int findKthLargestUsingMedian(Integer[] array, int k) {\n // Step 1: Divide the list into n/5 lists of 5 element each.\n int noOfRequiredLists = (int) Math.ceil(array.length / 5.0);\n // Step 2: Find pivotal element aka median of medians.\n int medianOfMedian = findMedianOfMedians(array, noOfRequiredLists);\n //Now we need two lists split using medianOfMedian as pivot. All elements in list listOne will be grater than medianOfMedian and listTwo will have elements lesser than medianOfMedian.\n List<Integer> listWithGreaterNumbers = new ArrayList<>(); // elements greater than medianOfMedian\n List<Integer> listWithSmallerNumbers = new ArrayList<>(); // elements less than medianOfMedian\n for (Integer element : array) {\n if (element < medianOfMedian) {\n listWithSmallerNumbers.add(element);\n } else if (element > medianOfMedian) {\n listWithGreaterNumbers.add(element);\n }\n }\n // Next step.\n if (k <= listWithGreaterNumbers.size()) return findKthLargestUsingMedian((Integer[]) listWithGreaterNumbers.toArray(new Integer[listWithGreaterNumbers.size()]), k);\n else if ((k - 1) == listWithGreaterNumbers.size()) return medianOfMedian;\n else if (k > (listWithGreaterNumbers.size() + 1)) return findKthLargestUsingMedian((Integer[]) listWithSmallerNumbers.toArray(new Integer[listWithSmallerNumbers.size()]), k-listWithGreaterNumbers.size()-1);\n return -1;\n }\n\n public static int findMedianOfMedians(Integer[] mainList, int noOfRequiredLists) {\n int[] medians = new int[noOfRequiredLists];\n for (int count = 0; count < noOfRequiredLists; count++) {\n int startOfPartialArray = 5 * count;\n int endOfPartialArray = startOfPartialArray + 5;\n Integer[] partialArray = Arrays.copyOfRange((Integer[]) mainList, startOfPartialArray, endOfPartialArray);\n // Step 2: Find median of each of these sublists.\n int medianIndex = partialArray.length/2;\n medians[count] = partialArray[medianIndex];\n }\n // Step 3: Find median of the medians.\n return medians[medians.length / 2];\n }\n O(nlogn) public static int findKthLargestUsingPriorityQueue(Integer[] nums, int k) {\n int p = 0;\n int numElements = nums.length;\n // create priority queue where all the elements of nums will be stored\n PriorityQueue<Integer> pq = new PriorityQueue<Integer>();\n\n // place all the elements of the array to this priority queue\n for (int n : nums) {\n pq.add(n);\n }\n\n // extract the kth largest element\n while (numElements - k + 1 > 0) {\n p = pq.poll();\n k++;\n }\n\n return p;\n }\n public static void main(String[] args) throws IOException {\n Integer[] numbers = new Integer[]{2, 3, 5, 4, 1, 12, 11, 13, 16, 7, 8, 6, 10, 9, 17, 15, 19, 20, 18, 23, 21, 22, 25, 24, 14};\n System.out.println(findKthLargestUsingMedian(numbers, 8));\n System.out.println(findKthLargestUsingPriorityQueue(numbers, 8));\n }\n 18\n18" }, { "answer_id": 37587307, "author": "TheLogicGuy", "author_id": 2671102, "author_profile": "https://Stackoverflow.com/users/2671102", "pm_score": 0, "selected": false, "text": "public class Median {\n\n public static void main(String[] s) {\n\n int[] test = {4,18,20,3,7,13,5,8,2,1,15,17,25,30,16};\n System.out.println(selectK(test,8));\n\n /*\n int n = 100000000;\n int[] test = new int[n];\n for(int i=0; i<test.length; i++)\n test[i] = (int)(Math.random()*test.length);\n\n long start = System.currentTimeMillis();\n random_selectK(test, test.length/2);\n long end = System.currentTimeMillis();\n System.out.println(end - start);\n */\n }\n\n public static int random_selectK(int[] a, int k) {\n if(a.length <= 1)\n return a[0];\n\n int r = (int)(Math.random() * a.length);\n int p = a[r];\n\n int small = 0, equal = 0, big = 0;\n for(int i=0; i<a.length; i++) {\n if(a[i] < p) small++;\n else if(a[i] == p) equal++;\n else if(a[i] > p) big++;\n }\n\n if(k <= small) {\n int[] temp = new int[small];\n for(int i=0, j=0; i<a.length; i++)\n if(a[i] < p)\n temp[j++] = a[i];\n return random_selectK(temp, k);\n }\n\n else if (k <= small+equal)\n return p;\n\n else {\n int[] temp = new int[big];\n for(int i=0, j=0; i<a.length; i++)\n if(a[i] > p)\n temp[j++] = a[i];\n return random_selectK(temp,k-small-equal);\n }\n }\n\n public static int selectK(int[] a, int k) {\n if(a.length <= 5) {\n Arrays.sort(a);\n return a[k-1];\n }\n\n int p = median_of_medians(a);\n\n int small = 0, equal = 0, big = 0;\n for(int i=0; i<a.length; i++) {\n if(a[i] < p) small++;\n else if(a[i] == p) equal++;\n else if(a[i] > p) big++;\n }\n\n if(k <= small) {\n int[] temp = new int[small];\n for(int i=0, j=0; i<a.length; i++)\n if(a[i] < p)\n temp[j++] = a[i];\n return selectK(temp, k);\n }\n\n else if (k <= small+equal)\n return p;\n\n else {\n int[] temp = new int[big];\n for(int i=0, j=0; i<a.length; i++)\n if(a[i] > p)\n temp[j++] = a[i];\n return selectK(temp,k-small-equal);\n }\n }\n\n private static int median_of_medians(int[] a) {\n int[] b = new int[a.length/5];\n int[] temp = new int[5];\n for(int i=0; i<b.length; i++) {\n for(int j=0; j<5; j++)\n temp[j] = a[5*i + j];\n Arrays.sort(temp);\n b[i] = temp[2];\n }\n\n return selectK(b, b.length/2 + 1);\n }\n}\n" }, { "answer_id": 37855810, "author": "Aishwat Singh", "author_id": 5227718, "author_profile": "https://Stackoverflow.com/users/5227718", "pm_score": 2, "selected": false, "text": "buffer of length k tmp_max O(kn)" }, { "answer_id": 38143116, "author": "Lee.O.", "author_id": 5976676, "author_profile": "https://Stackoverflow.com/users/5976676", "pm_score": 0, "selected": false, "text": " public static int kthElInUnsortedList(List<int> list, int k)\n {\n if (list.Count == 1)\n return list[0];\n\n List<int> left = new List<int>();\n List<int> right = new List<int>();\n\n int pivotIndex = list.Count / 2;\n int pivot = list[pivotIndex]; //arbitrary\n\n for (int i = 0; i < list.Count && i != pivotIndex; i++)\n {\n int currentEl = list[i];\n if (currentEl < pivot)\n left.Add(currentEl);\n else\n right.Add(currentEl);\n }\n\n if (k == left.Count + 1)\n return pivot;\n\n if (left.Count < k)\n return kthElInUnsortedList(right, k - left.Count - 1);\n else\n return kthElInUnsortedList(left, k);\n }\n" }, { "answer_id": 40210625, "author": "Bhagwati Malav", "author_id": 3572733, "author_profile": "https://Stackoverflow.com/users/3572733", "pm_score": 1, "selected": false, "text": "public static int getKthLargestElements(int[] arr)\n{\n PriorityQueue<Integer> pq = new PriorityQueue<>((x , y) -> (y-x));\n //insert all the elements into heap\n for(int ele : arr)\n pq.offer(ele);\n // call poll() k times\n int i=0;\n while(i&lt;k)\n {\n int result = pq.poll();\n } \n return result; \n}\n" }, { "answer_id": 47044986, "author": "Anubhav Agarwal", "author_id": 1032610, "author_profile": "https://Stackoverflow.com/users/1032610", "pm_score": 0, "selected": false, "text": "def _iskthsmallest(self, A, val, k):\n less_count, equal_count = 0, 0\n for i in range(len(A)):\n if A[i] == val: equal_count += 1\n if A[i] < val: less_count += 1\n\n if less_count >= k: return 1\n if less_count + equal_count < k: return -1\n return 0\n\ndef kthsmallest_binary(self, A, min_val, max_val, k):\n if min_val == max_val:\n return min_val\n mid = (min_val + max_val)/2\n iskthsmallest = self._iskthsmallest(A, mid, k)\n if iskthsmallest == 0: return mid\n if iskthsmallest > 0: return self.kthsmallest_binary(A, min_val, mid, k)\n return self.kthsmallest_binary(A, mid+1, max_val, k)\n\n# @param A : tuple of integers\n# @param B : integer\n# @return an integer\ndef kthsmallest(self, A, k):\n if not A: return 0\n if k > len(A): return 0\n min_val, max_val = min(A), max(A)\n return self.kthsmallest_binary(A, min_val, max_val, k)\n" }, { "answer_id": 48825994, "author": "L'ahim", "author_id": 4145053, "author_profile": "https://Stackoverflow.com/users/4145053", "pm_score": 2, "selected": false, "text": "template <typename T>\nT FRselect(std::vector<T>& data, const size_t& n)\n{\n if (n == 0)\n return *(std::min_element(data.begin(), data.end()));\n else if (n == data.size() - 1)\n return *(std::max_element(data.begin(), data.end()));\n else\n return _FRselect(data, 0, data.size() - 1, n);\n}\n\ntemplate <typename T>\nT _FRselect(std::vector<T>& data, const size_t& left, const size_t& right, const size_t& n)\n{\n size_t leftIdx = left;\n size_t rightIdx = right;\n\n while (rightIdx > leftIdx)\n {\n if (rightIdx - leftIdx > 600)\n {\n size_t range = rightIdx - leftIdx + 1;\n long long i = n - (long long)leftIdx + 1;\n long long z = log(range);\n long long s = 0.5 * exp(2 * z / 3);\n long long sd = 0.5 * sqrt(z * s * (range - s) / range) * sgn(i - (long long)range / 2);\n\n size_t newLeft = fmax(leftIdx, n - i * s / range + sd);\n size_t newRight = fmin(rightIdx, n + (range - i) * s / range + sd);\n\n _FRselect(data, newLeft, newRight, n);\n }\n T t = data[n];\n size_t i = leftIdx;\n size_t j = rightIdx;\n // arrange pivot and right index\n std::swap(data[leftIdx], data[n]);\n if (data[rightIdx] > t)\n std::swap(data[rightIdx], data[leftIdx]);\n\n while (i < j)\n {\n std::swap(data[i], data[j]);\n ++i; --j;\n while (data[i] < t) ++i;\n while (data[j] > t) --j;\n }\n\n if (data[leftIdx] == t)\n std::swap(data[leftIdx], data[j]);\n else\n {\n ++j;\n std::swap(data[j], data[rightIdx]);\n }\n // adjust left and right towards the boundaries of the subset\n // containing the (k - left + 1)th smallest element\n if (j <= n)\n leftIdx = j + 1;\n if (n <= j)\n rightIdx = j - 1;\n }\n\n return data[leftIdx];\n}\n\ntemplate <typename T>\nint sgn(T val) {\n return (T(0) < val) - (val < T(0));\n}\n" }, { "answer_id": 69081325, "author": "Chandrakesha Rao", "author_id": 12041867, "author_profile": "https://Stackoverflow.com/users/12041867", "pm_score": -1, "selected": false, "text": "\n\n function nthMax(arr, nth = 1, maxNumber = Infinity) {\n let large = -Infinity;\n for(e of arr) {\n if(e > large && e < maxNumber ) {\n large = e;\n } else if (maxNumber == large) {\n nth++;\n }\n }\n return nth==0 ? maxNumber: nthMax(arr, nth-1, large);\n }\n\n let array = [11,12,12,34,23,34];\n\n let secondlargest = nthMax(array, 1);\n\n console.log(\"Number:\", secondlargest);\n\n\n\n\n \n function nthMax(arr, nth = 1, maxNumber = Infinity) {\n let large = -Infinity;\n for(e of arr) {\n if(e > large && e < maxNumber ) {\n large = e;\n } else if (maxNumber == large) {\n nth++;\n }\n }\n return nth==0 ? maxNumber: nthMax(arr, nth-1, large);\n }\n\n let array = [11,12,12,34,23,34];\n\n let secondlargest = nthMax(array, 1);\n\n console.log(\"Number:\", secondlargest);" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
251,791
<p>I need to use JUnit 4.4 (or newer) in a set of eclipse plugin tests, but I've run into the following problem:</p> <p>Tests are not detected when running with the junit 4.4 or 4.5 bundles from springsource (<a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&amp;version=4.4.0" rel="nofollow noreferrer">junit44</a> and <a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&amp;version=4.5.0&amp;searchType=bundlesByName&amp;searchQuery=junit" rel="nofollow noreferrer">junit45</a>). The org.junit4 bundle that can be obtained with eclipse supplies junit 4.3 (as of Ganymead / Eclipse 3.4). The org.junit4 bundle <em>does</em> work in that it identifies and runs the tests, but it is not compatible with the latest versions of JMock, and I need to use a mocking library.</p> <p>Here is a sample test:</p> <pre><code>package testingplugin; import static org.junit.Assert.*; import org.junit.Test; public class ActivatorTest { @Test public final void testDoaddTest() { fail("Not yet implemented"); } } </code></pre> <p>When running this test, I receive the following exception:</p> <pre><code>java.lang.Exception: No runnable methods at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:33) at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.pde.internal.junit.runtime.RemotePluginTestRunner.main(RemotePluginTestRunner.java:62) at org.eclipse.pde.internal.junit.runtime.CoreTestApplication.run(CoreTestApplication.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:574) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:195) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504) at org.eclipse.equinox.launcher.Main.run(Main.java:1236) at org.eclipse.equinox.launcher.Main.main(Main.java:1212) </code></pre> <p>However, if I switch the project dependencies from com.springsource.org.junit to org.junit4, then the test runs and fails (as expected).</p> <p>I am running the test as a JUnit Plug-in Test in Eclipse, with the following program arguments:</p> <p>-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}</p> <p>The following plug-ins selected during launch (selected by me, then I used "add required plugins" to get the rest of the dependencies.):</p> <pre><code>Workspace: testingPlugin Target Platform: com.springsource.org.hamcrest.core (1.1.0) com.springsource.org.junit (4.5.0) ....and a bunch of others... (nothing related to testing was auto-selected) </code></pre> <p>Here is my MANIFEST.MF:</p> <pre><code>Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: TestingPlugin Plug-in Bundle-SymbolicName: testingPlugin Bundle-Version: 1.0.0 Bundle-Activator: testingplugin.Activator Import-Package: org.osgi.framework;version="1.3.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: com.springsource.org.junit;bundle-version="4.5.0" </code></pre> <p>Switching the last line to:</p> <pre><code>Require-Bundle: org.junit4;bundle-version="4.3.1" </code></pre> <p>And updating the selected plugins at launch to:</p> <pre><code>Workspace: testingPlugin Target Platform: org.junit4 (4.3.1) ...bunches of auto-selected bundles... (again, nothing else test related) </code></pre> <p>Causes the test to run properly (but with the wrong version of junit).</p>
[ { "answer_id": 261242, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 0, "selected": false, "text": "import static junit.framework.Assert.*;\n...\n@Test\n public void testDummy() throws Exception\n" }, { "answer_id": 358705, "author": "Thomas Dufour", "author_id": 371593, "author_profile": "https://Stackoverflow.com/users/371593", "pm_score": 2, "selected": false, "text": "import org.junit.runners.JUnit4;\n\n@RunWith(JUnit4.class)\npublic class ActivatorTest {\n //...\n}\n org.junit.runners.BlockJUnit4ClassRunner org.junit.internal.runners.JUnit4ClassRunner com.springsource. com.springsource.org.junit org.junit" }, { "answer_id": 522640, "author": "James Mead", "author_id": 2025138, "author_profile": "https://Stackoverflow.com/users/2025138", "pm_score": 1, "selected": false, "text": " import org.junit.Test;\n import org.junit.runner.RunWith;\n\n import org.jmock.Mockery;\n import org.jmock.Expectations;\n import org.jmock.integration.junit4.JUnit4Mockery;\n import org.jmock.integration.junit4.JMock;\n\n @RunWith(JMock.class)\n public class PublisherTest {\n\n Mockery context = new JUnit4Mockery();\n\n @Test \n public void oneSubscriberReceivesAMessage() {\n" }, { "answer_id": 892198, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " return new JUnit4TestAdapter(AllTestSuite .class);\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ]
251,806
<p>I have a interface that defines some methods with attributes. These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface. What am I missing?</p> <pre><code>public class SomeClass: ISomeInterface { MyAttribute GetAttribute() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true); if (attributes.Count() == 0) throw new Exception("could not find MyAttribute defined for " + methodBase.Name); return attributes[0] as MyAttribute; } void DoSomething() { MyAttribute ma = GetAttribute(); string s = ma.SomeProperty; } } </code></pre>
[ { "answer_id": 251827, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\ninterface IFoo\n{\n void AAA(); // just to push Bar to index 1\n [Description(\"abc\")]\n void Bar();\n}\nclass Foo : IFoo\n{\n public void AAA() { } // just to satisfy interface\n static void Main()\n {\n IFoo foo = new Foo();\n foo.Bar();\n }\n void IFoo.Bar()\n {\n GetAttribute();\n }\n\n void GetAttribute()\n { // simplified just to obtain the [Description]\n\n StackTrace stackTrace = new StackTrace();\n StackFrame stackFrame = stackTrace.GetFrame(1);\n MethodBase classMethod = stackFrame.GetMethod();\n InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));\n int index = Array.IndexOf(map.TargetMethods, classMethod);\n MethodBase iMethod = map.InterfaceMethods[index];\n string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;\n }\n}\n" }, { "answer_id": 251857, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 0, "selected": false, "text": "public abstract class SomeBaseClass: ISomeInterface\n{\n [MyAttribute]\n abstract void MyTestMethod();\n\n\n}\n\npublic SomeClass : SomeBaseClass{\n\n MyAttribute GetAttribute(){\n Type t = GetType();\n object[] attibutes = t.GetCustomAttributes(typeof(MyAttribute), false);\n\n if (attributes.Count() == 0)\n throw new Exception(\"could not find MyAttribute defined for \" + methodBase.Name);\n return attributes[0] as MyAttribute;\n }\n\n\n ....\n}\n" }, { "answer_id": 253602, "author": "Thad", "author_id": 24500, "author_profile": "https://Stackoverflow.com/users/24500", "pm_score": 2, "selected": false, "text": "interface IFoo<T> {}\nclass Foo<T>: IFoo<T>\n{\n T Bar()\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24500/" ]
251,807
<p>I use eclipse to work on an application which was originally created independently of eclipse. As such, the application's directory structure is decidedly not eclipse-friendly.</p> <p>I want to programmatically generate a project for the application. The <code>.project</code> and <code>.classpath</code> files are easy enough to figure out, and I've learned that projects are stored in the workspace under <code>&lt;workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects</code></p> <p>Unfortunately, some of the files under here (particularly <code>.location</code>) seem to be encoded in some kind of binary format. On a hunch I tried to deserialize it using <code>ObjectInputStream</code> - no dice. So it doesn't appear to be a serialized java object.</p> <p>My question is: is there a way to generate these files automatically?</p> <p>For the curious, the error I get trying to deserialize the <code>.location</code> file is the following:</p> <p><code>java.io.StreamCorruptedException: java.io.StreamCorruptedException: invalid stream header: 40B18B81</code></p> <p><strong>Update:</strong> My goal here is to be able to replace the New Java Project wizard with a command-line script or program. The reason is the application in question is actually a very large J2EE/weblogic application, which I like to break down into a largish (nearly 20) collection of subprojects. Complicating matters, we use clearcase for SCM and create a new branch for every release. This means I need to recreate these projects for every development view (branch) I create. This happens often enough to automate.</p>
[ { "answer_id": 252168, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 5, "selected": true, "text": "IProgressMonitor progressMonitor = new NullProgressMonitor();\nIWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();\nIProject project = root.getProject(\"DesiredProjectName\");\nproject.create(progressMonitor);\nproject.open(progressMonitor);\n" }, { "answer_id": 63685295, "author": "mikolayek", "author_id": 3115384, "author_profile": "https://Stackoverflow.com/users/3115384", "pm_score": 0, "selected": false, "text": "org.eclipse.jdt.core.JavaCore sourceProject IJavaProject javaSourceProject = JavaCore.create(sourceProject);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
251,814
<p>I've been struggling lately with understanding the best way to organize jQuery code. I asked another question earlier and I don't think I was specific enough (<a href="https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess">found in this question here</a>).</p> <p>My problem is that the richer you make an application, the quicker your client side gets out of control. Consider this situation...</p> <pre><code>//Let's start some jQuery $(function() { var container = $("#inputContainer"); //Okay let's list text fields that can be updated for(var i=0; i &lt; 5; i++) { //okay let's add an event for when a field changes $("&lt;input/&gt;").change(function() { //okay something changed, let's update the server $.ajax({ success:function(data) { //Okay - no problem from the server... let's update //the bindings on our input fields $.each(container.children(), function(j,w) { //YIKES!! We're deep in here now!! $(w).unbind().change(function() { //Then insanity starts... }); // end some function }); //end some loop } // what was this again? }); //ending something... not sure anymore }).appendTo(container); //input added to the page... logic WAY split apart }; //the first loop - whew! almost out! }); //The start of the code!! </code></pre> <p>Now this situation isn't too far from impossible. I'm not saying this is the right way to do it, but it's not uncommon to find yourself several levels down into a jQuery command and starting to wonder how much more logic can add before the screen begins to melt.</p> <p><strong>My question is how are people managing this or organizing to limit the complexity of their code?</strong></p> <p><em><a href="https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess#247382">I listed how I'm doing it in my other post</a>...</em></p>
[ { "answer_id": 251854, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "var aCustomObject = {\n container: $(\"#inputContainer\"),\n initialize: function()\n {\n for(var i=0; i < 5; i++)\n {\n $(\"<input/>\").changed( aCustomObject.changeHandler );\n }\n },\n changeHandler: function( event )\n {\n $.ajax( {success: aCustomObject.ajaxSuccessHandler} );\n },\n ajaxSuccessHandler: function( data )\n {\n $.each( aCustomObject.container.children(), aCustomObject.updateBindings )\n },\n updateBindings: function( j, w )\n {\n $(w).unbind().changed( function(){} );\n }\n}\naCustomObject.initialize();\n" }, { "answer_id": 251864, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 4, "selected": false, "text": "// initial description of this code block\n$(function() { \n var container = $(\"#inputContainer\");\n\n for(var i=0; i < 5; i++) {\n $(\"<input/>\").changed(inputChanged).appendTo(container);\n }; \n\n function inputChanged() {\n $.ajax({\n success: inputChanged_onSuccess\n });\n } \n\n function inputChanged_onSuccess(data) {\n $.each(container.children(), function(j,w) {\n $(w).unbind().changed(function() {\n //replace the insanity with another refactored function\n });\n });\n }\n});\n" }, { "answer_id": 252060, "author": "user32924", "author_id": 32924, "author_profile": "https://Stackoverflow.com/users/32924", "pm_score": 2, "selected": false, "text": "// Page specific code\njQuery(function() {\n for(var i = 0; i < 5; i++) {\n $(\"<input/>\").bindWithServer(\"#inputContainer\");\n }\n});\n\n// Nicely abstracted code\njQuery.fn.bindWithServer = function(container) {\n this.change(function() {\n jQuery.ajax({\n url: 'http://example.com/',\n success: function() { jQuery(container).unbindChildren(); }\n });\n });\n}\njQuery.fn.unbindChildren = function() {\n this.children().each(function() {\n jQuery(this).unbind().change(function() {});\n });\n}\n" }, { "answer_id": 255222, "author": "John Resig", "author_id": 6524, "author_profile": "https://Stackoverflow.com/users/6524", "pm_score": 6, "selected": false, "text": "$.each(container.children(), function(j,w) {\n $(w).unbind().change(function() { ... });\n});\n container.children().unbind().change(function() { ... });\n" }, { "answer_id": 2185057, "author": "Irfan", "author_id": 236324, "author_profile": "https://Stackoverflow.com/users/236324", "pm_score": 2, "selected": false, "text": "$(document).ready(DocReady);\n\nfunction DocReady()\n{ \n AssignClickToToggleButtons();\n ColorCodeTextBoxes();\n}\n function ColorCodeTextBoxes()\n{\n var TextBoxes = $(\":text.DataEntry\");\n\n TextBoxes.each(function()\n {\n if (this.value == \"\")\n this.style.backgroundColor = \"yellow\";\n else\n this.style.backgroundColor = \"White\";\n });\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
251,834
<p>Given a Generic List of objects that contain a member variable that is a string, what is the best way to get the object that contains the string with the longest length?</p> <p>ie. assuming val1 is the string I'm comparing:</p> <pre><code>0 : { val1 = "a" } 1 : { val1 = "aa" } 2 : { val1 = "aba" } 3 : { val1 = "c" } </code></pre> <p>what needs to be returned is object 2 because "aba" has the greatest length.</p>
[ { "answer_id": 251858, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "Dim result = elements.Aggregate(Function(a, b) If(a.val1.Length > b.val1.Length, a, b))\n" }, { "answer_id": 251860, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 0, "selected": false, "text": "var x = myStringArray.OrderBy(s => s.Length).Last();\n" }, { "answer_id": 1054690, "author": "Joe Chung", "author_id": 86483, "author_profile": "https://Stackoverflow.com/users/86483", "pm_score": 0, "selected": false, "text": "Dim longestLength = elements.Max(Function(el) el.val1.Length)\nDim longest = elements.First(Function(el) el.val1.Length = longestLength)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847/" ]
251,842
<p>I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem? </p> <p>[Update] Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.</p>
[ { "answer_id": 251873, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "^(1\\d{2}|200|5\\d{2}|600)$\n" }, { "answer_id": 251881, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "void ValidateRange(object sender, ServerValidateEventArgs e)\n{\n int input;\n bool parseOk = int.TryParse(e.Value, out input);\n e.IsValid = parseOk &&\n ((input >= 100 || input <= 200) ||\n (input >= 500 || input <= 600));\n}\n" }, { "answer_id": 252556, "author": "HashName", "author_id": 28773, "author_profile": "https://Stackoverflow.com/users/28773", "pm_score": 1, "selected": true, "text": " public class RangeValidatorEx : BaseValidator\n{\n\n protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)\n {\n base.AddAttributesToRender(writer);\n\n if (base.RenderUplevel)\n {\n string clientId = this.ClientID;\n\n // The attribute evaluation funciton holds the name of client-side js function.\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"evaluationfunction\", \"RangeValidatorEx\");\n\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range1High\", this.Range1High.ToString());\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range2High\", this.Range2High.ToString());\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range1Low\", this.Range1Low.ToString());\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range2Low\", this.Range2Low.ToString());\n\n }\n }\n\n // Will be invoked to validate the parameters \n protected override bool ControlPropertiesValid()\n {\n if ((Range1High <= 0) || (this.Range1Low <= 0) || (this.Range2High <= 0) || (this.Range2Low <= 0))\n throw new HttpException(\"The range values cannot be less than zero\");\n\n return base.ControlPropertiesValid();\n }\n\n // used to validation on server-side\n protected override bool EvaluateIsValid()\n {\n int code;\n if (!Int32.TryParse(base.GetControlValidationValue(ControlToValidate), out code))\n return false;\n\n if ((code < this.Range1High && code > this.Range1Low) || (code < this.Range2High && code > this.Range2Low))\n return true;\n else\n return false;\n }\n\n // inject the client-side script to page\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n\n if (base.RenderUplevel)\n {\n this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), \"RangeValidatorEx\", RangeValidatorExJs(),true);\n }\n }\n\n\n string RangeValidatorExJs()\n {\n string js;\n // the validator will be rendered as a SPAN tag on the client-side and it will passed to the validation function.\n js = \"function RangeValidatorEx(val){ \"\n + \" var code=document.getElementById(val.controltovalidate).value; \"\n + \" if ((code < rangeValidatorCtrl.Range1High && code > rangeValidatorCtrl.Range1Low ) || (code < rangeValidatorCtrl.Range2High && code > rangeValidatorCtrl.Range2Low)) return true; else return false;}\";\n return js;\n }\n\n\n public int Range1Low\n {\n get {\n object obj2 = this.ViewState[\"Range1Low\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range1Low\"] = value; }\n }\n\n public int Range1High\n {\n get\n {\n object obj2 = this.ViewState[\"Range1High\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range1High\"] = value; }\n }\n public int Range2Low\n {\n get\n {\n object obj2 = this.ViewState[\"Range2Low\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range2Low\"] = value; }\n }\n public int Range2High\n {\n get\n {\n object obj2 = this.ViewState[\"Range2High\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range2High\"] = value; }\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28773/" ]
251,850
<p>I'm using symfony and propel, and I'm trying to invoke a specific culture on an object and output some fields of that object to the screen in that specific culture. However, if the object's mapped database record doesn't have those fields in that specific culture, I would like it to default to the base culture (in this case, en_US)</p> <p>I'm doing it like this:</p> <pre><code>$currentLesson = $currentLesson-&gt;getCurrentLessonsI18n($lessonCulture); </code></pre> <p>But when I output such as this</p> <pre><code>$currentLesson-&gt;getTitle(); </code></pre> <p>It outputs an empty string if there is no culture record for it. My question is, is there a way to make an object default to a specific culuture if the one I specify isn't available, or is there a method to see if a specific object has a culture i18n record?</p> <p>something like this:</p> <pre><code>if($currentLesson-&gt;cultureExists($lessonCulture) $currentLesson = $currentLesson-&gt;getCurrentLessonsI18n($lessonCulture); </code></pre> <p>or</p> <pre><code>sfConfig::setPropelDefaultCulture("en_US"); </code></pre>
[ { "answer_id": 8790184, "author": "Bert-Jan de Lange", "author_id": 1138912, "author_profile": "https://Stackoverflow.com/users/1138912", "pm_score": 0, "selected": false, "text": "i18n getTranslation($language) isNew() (true) (false)" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53001/" ]
251,851
<p>I have a directory of files that I'd like to append file extension to as long as they don't have an existing, specified extension. So add .txt to all file names that don't end in .xyz. PowerShell seems like a good candidate for this, but I don't know anything about it. How would I go about it?</p>
[ { "answer_id": 251855, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "C:\\Documents and Settings\\Kenny>help for\nRuns a specified command for each file in a set of files.\n\nFOR %variable IN (set) DO command [command-parameters]\n\n %variable Specifies a single letter replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\n...\n\nIn addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n" }, { "answer_id": 251875, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "gci -ex \"*.xyz\" | ?{!$_.PsIsContainer} | ren -new {$_.name + \".txt\"}\n Get-ChildItem -exclude \"*.xyz\" \n | WHere-Object{!$_.PsIsContainer} \n | Rename-Item -newname {$_.name + \".txt\"}\n" }, { "answer_id": 251886, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "gci \n | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(\".xyz\") } \n | %{ ren -new ($_.Name + \".txt\") }\n" }, { "answer_id": 30281035, "author": "Coding101", "author_id": 1277533, "author_profile": "https://Stackoverflow.com/users/1277533", "pm_score": 2, "selected": false, "text": "Get-ChildItem -Path \"C:\\temp\" -Filter \"*.config\" -File | \n Rename-Item -NewName { $PSItem.Name + \".disabled\" }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
251,861
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/174796/watermarked-textbox-for-compact-framework">Watermarked Textbox for Compact Framework</a> </p> </blockquote> <p>Using Visual Studio 2008 SP1, the latest Compact framework and Windows Mobile 5.</p> <p>I need to use DrawString to put a string over a TextBox. But as soon as I draw the string the TextBox Control just over writes it. (I Know because I drew slightly off the edge of the control and my text is half visible (where is is off the control) and half gone (where it is on the control.)</p> <p>Is there anyway I can get the TextBox to not refresh so I can keep my text there?</p> <p>NOTE: I have looked into subclassing TextBox and just having it paint my text. However, Paint events for the TextBox class are not catchable in the CompactFramework. If you know a way to be able to paint on the TextBox without the Paint events then I would love to subclass the TextBox class.</p> <p>--End of Question--</p> <p>Just in case you are wondering why I need to do this, here is what I am working on: I need to have a text box where a numeric value must be entered twice. I need some sort of clear clue that they have to enter the number again. I would like to have a slightly grayed out text appear over the text box telling the user to re-enter.</p> <p>I have tried using a label, a hyperlink label and another text box, but they obscure the text below (which has a default value that has to be partially visible).</p> <p>If anyone knows a different way cue for re-entry that would be great too!</p> <p>Vacano</p>
[ { "answer_id": 251855, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "C:\\Documents and Settings\\Kenny>help for\nRuns a specified command for each file in a set of files.\n\nFOR %variable IN (set) DO command [command-parameters]\n\n %variable Specifies a single letter replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\n...\n\nIn addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n" }, { "answer_id": 251875, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "gci -ex \"*.xyz\" | ?{!$_.PsIsContainer} | ren -new {$_.name + \".txt\"}\n Get-ChildItem -exclude \"*.xyz\" \n | WHere-Object{!$_.PsIsContainer} \n | Rename-Item -newname {$_.name + \".txt\"}\n" }, { "answer_id": 251886, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "gci \n | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(\".xyz\") } \n | %{ ren -new ($_.Name + \".txt\") }\n" }, { "answer_id": 30281035, "author": "Coding101", "author_id": 1277533, "author_profile": "https://Stackoverflow.com/users/1277533", "pm_score": 2, "selected": false, "text": "Get-ChildItem -Path \"C:\\temp\" -Filter \"*.config\" -File | \n Rename-Item -NewName { $PSItem.Name + \".disabled\" }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16241/" ]
251,865
<p>For a very simple ajax name lookup, I'm sending an id from the client webpage to the server (Tomcat 5.5, Java 5), looking it up in a database and returning a string, which is assigned to a javascript variable back in the client (and then displayed).</p> <p>The javascript code that receives the value is pretty standard:</p> <pre><code>//client code - javascript xmlHttp.onreadystatechange=function() { if (xmlHttp.readyState==4) { var result = xmlHttp.responseText; alert(result); ... } ... } </code></pre> <p>To return the string, I originally had this in the server:</p> <pre><code>//server code - java myString = "..."; out.write(myString.getBytes("UTF-8")); </code></pre> <p>Which worked perfectly, if unsafe. Later, I replaced it with:</p> <pre><code>import org.apache.commons.lang.StringEscapeUtils; ... myString = "..."; out.write(StringEscapeUtils.escapeJavaScript(myString).getBytes("UTF-8")); </code></pre> <p>But while safer, the resulting string can't be properly displayed if it contains special chars like "ñ".</p> <p>For instance, using:</p> <pre><code>escapeJavaScript("años").getBytes("UTF-8"); </code></pre> <p>sends:</p> <pre><code>an\u00F1os </code></pre> <p>to the client.</p> <p>The question: is there a simple way to parse the resulting string in Javascript or is there an alternate escape function I can use in java that would prevent this issue?</p>
[ { "answer_id": 251855, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "C:\\Documents and Settings\\Kenny>help for\nRuns a specified command for each file in a set of files.\n\nFOR %variable IN (set) DO command [command-parameters]\n\n %variable Specifies a single letter replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\n...\n\nIn addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n" }, { "answer_id": 251875, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "gci -ex \"*.xyz\" | ?{!$_.PsIsContainer} | ren -new {$_.name + \".txt\"}\n Get-ChildItem -exclude \"*.xyz\" \n | WHere-Object{!$_.PsIsContainer} \n | Rename-Item -newname {$_.name + \".txt\"}\n" }, { "answer_id": 251886, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "gci \n | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(\".xyz\") } \n | %{ ren -new ($_.Name + \".txt\") }\n" }, { "answer_id": 30281035, "author": "Coding101", "author_id": 1277533, "author_profile": "https://Stackoverflow.com/users/1277533", "pm_score": 2, "selected": false, "text": "Get-ChildItem -Path \"C:\\temp\" -Filter \"*.config\" -File | \n Rename-Item -NewName { $PSItem.Name + \".disabled\" }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
251,868
<p>I was watching <a href="http://channel9.msdn.com/pdc2008/TL16/" rel="noreferrer">Anders' talk about C# 4.0 and sneak preview of C# 5.0</a>, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?</p> <p>For example something like the <code>FileStream</code> class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an <code>IntPtr</code> and the ones from a <code>SafeFileHandle</code>.</p> <pre><code>FileStream(string,FileMode); FileStream(string,FileMode,FileAccess); FileStream(string,FileMode,FileAccess,FileShare); FileStream(string,FileMode,FileAccess,FileShare,int); FileStream(string,FileMode,FileAccess,FileShare,int,bool); </code></pre> <p>It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].</p> <p>What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?</p>
[ { "answer_id": 251893, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 2, "selected": false, "text": "public Rectangle (Point start = Point.Zero, int width, int height)\n{\n Start = start;\n Width = width;\n Height = height;\n}\n public Rectangle (Point start, int width, int height)\n{\n Start = start;\n Width = width;\n Height = height;\n}\n\npublic Rectangle (int width, int height) :\n this (Point.Zero, width, height)\n{\n}\n" }, { "answer_id": 251904, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "const" }, { "answer_id": 1039599, "author": "JP Alioto", "author_id": 86473, "author_profile": "https://Stackoverflow.com/users/86473", "pm_score": 3, "selected": false, "text": "public void M1( string foo, string bar )\n{\n // do that thang\n}\n\npublic void M1( string foo )\n{\n M1( foo, \"bar default\" ); // I have always hated this line of code specifically\n}\n public void M1( string foo, string bar = \"bar default\" )\n{\n // do that thang\n}\n public void M1( string foo )\n{\n M2( foo, \"bar default\" ); // oops! I meant M1!\n}\n" }, { "answer_id": 14431423, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "Foo Boo(int) Bar Foo.Boo() Foo.Boo(5) Foo Bar Foo.Boo(5) Foo" }, { "answer_id": 30751678, "author": "Zoran Horvat", "author_id": 2279448, "author_profile": "https://Stackoverflow.com/users/2279448", "pm_score": 2, "selected": false, "text": "decimal GetPrice(string productName, decimal discountPercentage = 0)\n{\n\n decimal basePrice = CalculateBasePrice(productName);\n\n if (discountPercentage > 0)\n return basePrice * (1 - discountPercentage / 100);\n else\n return basePrice;\n}\n decimal GetPrice(string productName)\n{\n decimal basePrice = CalculateBasePrice(productName);\n return basePrice;\n}\n\ndecimal GetPrice(string productName, decimal discountPercentage)\n{\n\n if (discountPercentage <= 0)\n throw new ArgumentException();\n\n decimal basePrice = GetPrice(productName);\n\n decimal discountedPrice = basePrice * (1 - discountPercentage / 100);\n\n return discountedPrice;\n\n}\n if (x == null)" }, { "answer_id": 47715752, "author": "Sebastian Mach", "author_id": 76722, "author_profile": "https://Stackoverflow.com/users/76722", "pm_score": 1, "selected": false, "text": "enum Match {\n Regex,\n Wildcard,\n ContainsString,\n}\n\n// Don't: This way, Enumerate() can be called in a way\n// which does not make sense:\nIEnumerable<string> Enumerate(string searchPattern = null,\n Match match = Match.Regex,\n SearchOption searchOption = SearchOption.TopDirectoryOnly);\n\n// Better: Provide only overloads which cannot be mis-used:\nIEnumerable<string> Enumerate(SearchOption searchOption = SearchOption.TopDirectoryOnly);\nIEnumerable<string> Enumerate(string searchPattern, Match match,\n SearchOption searchOption = SearchOption.TopDirectoryOnly);\n" }, { "answer_id": 49162660, "author": "Zach", "author_id": 5478219, "author_profile": "https://Stackoverflow.com/users/5478219", "pm_score": 2, "selected": false, "text": "public string HandleError(string message, bool silent=true, bool isCritical=true)\n{\n ...\n}\n HandleError(\"Disk is full\", false);\n public string HandleError(string message, /*bool silent=true,*/ bool isCritical=true)\n{\n ...\n}\n\n...\n\n// Some other distant code file:\nHandleError(\"Disk is full\", false);\n false HandleError(\"Disk is full\", silent:false)" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13552/" ]
251,885
<p>Or does it?</p> <p>Should an object-oriented design use a language construct that exposes member data by default, if there is an equally useful construct that properly hides data members?</p> <p>EDIT: One of the responders mentioned that if there's no invariant one can use a struct. That's an interesting observation: a struct is a data structure, i.e. it contains related data. If the data members in a struct are related isn't there's always an invariant? </p>
[ { "answer_id": 251906, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "public struct Point\n{\n int X;\n int Y;\n}\n" }, { "answer_id": 251942, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 1, "selected": false, "text": "public struct Point {\n int x;\n int y;\n}\n public class Point {\n private int x;\n private int y;\n public void setX(int x) { this.x=x; }\n public int getX(); { return x; }\n public void setY(int y) { this.y=y; }\n public int getY(); { return y; }\n}\n" }, { "answer_id": 252238, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "struct CPoint\n{\n int x ;\n int y ;\n\n CPoint() : x(0), y(0) {}\n\n int getDistanceFromOrigin() const\n {\n return std::sqrt(x * x + y * y) ;\n }\n} ;\n\ninline CPoint operator + (const CPoint & lhs, const CPoint & rhs)\n{\n CPoint r(lhs) ;\n r.x += rhs.x ;\n r.y += rhs.y ;\n return r ;\n}\n class CString\n{\n public :\n CString(const char * p) { /* etc. */ } ;\n CString(const CString & p) { /* etc. */ } ;\n\n const char * getString() const { return this->m_pString ; }\n size_t getSize() const { return this->m_iSize ; }\n\n void copy { /* code for string copy */ }\n void concat { /* code for string concatenation */ }\n\n private :\n size_t m_iSize ;\n char * m_pString ;\n} ;\n\ninline CString operator + (const CString & lhs, const CString & rhs)\n{\n CString r(lhs) ;\n r.concat(rhs) ;\n return r ;\n}\n" }, { "answer_id": 263622, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 0, "selected": false, "text": "struct" }, { "answer_id": 277091, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 0, "selected": false, "text": "Point foo;\n//...\nfoo.x = bar;\n #define X 0\n#define Y 1\n//...\nfoo[X] = bar;\n foo.x = 1023 x < 1.0 foo.setX(1023) foo.x = 1023" }, { "answer_id": 277113, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "class struct public std::pair<T, U> Point x and y >= 0" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
251,888
<p>I am calling <code>SPWeb.GetSiteData(anSpCrossListQuery)</code>.</p> <p>It fails to bring back any results or any errors when I call it with an accidental space at the end of the CAML query <code>&lt;Where&gt;&lt;/Where&gt;</code> clause.</p> <p>Anyone have an idea why?</p>
[ { "answer_id": 251906, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "public struct Point\n{\n int X;\n int Y;\n}\n" }, { "answer_id": 251942, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 1, "selected": false, "text": "public struct Point {\n int x;\n int y;\n}\n public class Point {\n private int x;\n private int y;\n public void setX(int x) { this.x=x; }\n public int getX(); { return x; }\n public void setY(int y) { this.y=y; }\n public int getY(); { return y; }\n}\n" }, { "answer_id": 252238, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "struct CPoint\n{\n int x ;\n int y ;\n\n CPoint() : x(0), y(0) {}\n\n int getDistanceFromOrigin() const\n {\n return std::sqrt(x * x + y * y) ;\n }\n} ;\n\ninline CPoint operator + (const CPoint & lhs, const CPoint & rhs)\n{\n CPoint r(lhs) ;\n r.x += rhs.x ;\n r.y += rhs.y ;\n return r ;\n}\n class CString\n{\n public :\n CString(const char * p) { /* etc. */ } ;\n CString(const CString & p) { /* etc. */ } ;\n\n const char * getString() const { return this->m_pString ; }\n size_t getSize() const { return this->m_iSize ; }\n\n void copy { /* code for string copy */ }\n void concat { /* code for string concatenation */ }\n\n private :\n size_t m_iSize ;\n char * m_pString ;\n} ;\n\ninline CString operator + (const CString & lhs, const CString & rhs)\n{\n CString r(lhs) ;\n r.concat(rhs) ;\n return r ;\n}\n" }, { "answer_id": 263622, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 0, "selected": false, "text": "struct" }, { "answer_id": 277091, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 0, "selected": false, "text": "Point foo;\n//...\nfoo.x = bar;\n #define X 0\n#define Y 1\n//...\nfoo[X] = bar;\n foo.x = 1023 x < 1.0 foo.setX(1023) foo.x = 1023" }, { "answer_id": 277113, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "class struct public std::pair<T, U> Point x and y >= 0" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13813/" ]
251,890
<p>I am a rookie was using the Visual Studio 2008 built-in Unit Testing components, what would be the best way to record or display your results in a unit test?</p> <p>I want to test my service method when it returns a System.GUID and an empty System.GUID</p> <pre><code>[TestMethod] public void GetGUID() { MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient(); string name = "HasGuid"; System.GUID guid = proxy.GetGUID(name); } [TestMethod] public void GetEmptyGUID() { MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient(); string name = "HasEmptyGuid"; System.GUID guid = proxy.GetGUID(name); } </code></pre>
[ { "answer_id": 251895, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "Assert Assert.IsTrue(...)" }, { "answer_id": 251991, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 4, "selected": true, "text": "Assert.IsFalse(guid == Guid.Empty);\n Assert.IsTrue(guid == Guid.Empty);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
251,902
<p>I would like to search through all of my procedures packages and functions for a certain phrase.</p> <p>Since it is possible to retrieve the code for compiled procedures using toad I assume that the full text is stored in some data dictionary table. Does anyone know where that would be?</p> <p>Thanks a lot</p>
[ { "answer_id": 251914, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 8, "selected": true, "text": "SELECT name, line, text\n FROM dba_source\n WHERE upper(text) like upper('%<<your_phrase>>%') escape '\\' \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
251,908
<p>What commands in Emacs can I use to insert into the text buffer of a file the current date and time?</p> <p><em>(For example, the equivalent in Notepad is simply pressing F5 which is about the only useful feature for Notepad!)</em></p>
[ { "answer_id": 251922, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": ";; ====================\n;; insert date and time\n\n(defvar current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"\n \"Format of date to insert with `insert-current-date-time' func\nSee help of `format-time-string' for possible replacements\")\n\n(defvar current-time-format \"%a %H:%M:%S\"\n \"Format of date to insert with `insert-current-time' func.\nNote the weekly scope of the command's precision.\")\n\n(defun insert-current-date-time ()\n \"insert the current date and time into current buffer.\nUses `current-date-time-format' for the formatting the date/time.\"\n (interactive)\n (insert \"==========\\n\")\n; (insert (let () (comment-start)))\n (insert (format-time-string current-date-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(defun insert-current-time ()\n \"insert the current time (1-week scope) into the current buffer.\"\n (interactive)\n (insert (format-time-string current-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(global-set-key \"\\C-c\\C-d\" 'insert-current-date-time)\n(global-set-key \"\\C-c\\C-t\" 'insert-current-time)\n" }, { "answer_id": 251935, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "(require 'insert-time)\n(define-key global-map [(control c)(d)] 'insert-date-time)\n(define-key global-map [(control c)(control v)(d)] 'insert-personal-time-stamp)\n" }, { "answer_id": 252088, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 4, "selected": false, "text": "current-time-string format-time-string" }, { "answer_id": 275849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "C-u M-! date\n" }, { "answer_id": 619525, "author": "Michael Paulukonis", "author_id": 41153, "author_profile": "https://Stackoverflow.com/users/41153", "pm_score": 5, "selected": false, "text": "(defun now ()\n \"Insert string for the current time formatted like '2:34 PM'.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%D %-I:%M %p\")))\n\n(defun today ()\n \"Insert string for today's date nicely formatted in American style,\ne.g. Sunday, September 17, 2000.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%A, %B %e, %Y\")))\n" }, { "answer_id": 3509321, "author": "bjkeefe", "author_id": 165727, "author_profile": "https://Stackoverflow.com/users/165727", "pm_score": 2, "selected": false, "text": "(defvar bjk-timestamp-format \"%Y-%m-%d %H:%M\"\n \"Format of date to insert with `bjk-timestamp' function\n%Y-%m-%d %H:%M will produce something of the form YYYY-MM-DD HH:MM\nDo C-h f on `format-time-string' for more info\")\n\n\n(defun bjk-timestamp ()\n \"Insert a timestamp at the current point.\nNote no attempt to go to beginning of line and no added carriage return.\nUses `bjk-timestamp-format' for formatting the date/time.\"\n (interactive)\n (insert (format-time-string bjk-timestamp-format (current-time)))\n )\n (load \"c:/bjk/elisp/bjk-timestamp.el\")\n" }, { "answer_id": 17078689, "author": "tangxinfa", "author_id": 802708, "author_profile": "https://Stackoverflow.com/users/802708", "pm_score": 5, "selected": false, "text": "M-x org-time-stamp\n C-u M-x org-time-stamp\n org-mode" }, { "answer_id": 29374896, "author": "Kaushal Modi", "author_id": 1219634, "author_profile": "https://Stackoverflow.com/users/1219634", "pm_score": 0, "selected": false, "text": "(defun modi/insert-time-stamp (option)\n \"Insert date, time, user name - DWIM.\n\nIf the point is NOT in a comment/string, the time stamp is inserted prefixed\nwith `comment-start' characters.\n\nIf the point is IN a comment/string, the time stamp is inserted without the\n`comment-start' characters. If the time stamp is not being inserted immediately\nafter the `comment-start' characters (followed by optional space),\nthe time stamp is inserted with “--” prefix.\n\nIf the buffer is in a major mode where `comment-start' var is nil, no prefix is\nadded regardless.\n\nAdditional control:\n\n C-u -> Only `comment-start'/`--' prefixes are NOT inserted\n C-u C-u -> Only user name is NOT inserted\nC-u C-u C-u -> Both prefix and user name are not inserted.\"\n (interactive \"P\")\n (let ((current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n ;; Insert prefix only if `comment-start' is defined for the major mode\n (when (stringp comment-start)\n (if (or (nth 3 (syntax-ppss)) ; string\n (nth 4 (syntax-ppss))) ; comment\n ;; If the point is already in a comment/string\n (progn\n ;; If the point is not immediately after `comment-start' chars\n ;; (followed by optional space)\n (when (and (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (not (looking-back (concat comment-start \" *\")))\n (not (looking-back \"^ *\")))\n (insert \"--\")))\n ;; If the point is NOT in a comment\n (progn\n (when (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (insert comment-start)))))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n (insert (format-time-string current-date-time-format (current-time)))\n (when (not (equal option '(16))) ; C-u C-u\n (insert (concat \" - \" (getenv \"USER\"))))\n ;; Insert a space after the time stamp if not at the end of the line\n (when (not (looking-at \" *$\"))\n (insert \" \"))))\n C-c d" }, { "answer_id": 68185786, "author": "Misho M. Petkovic", "author_id": 3358597, "author_profile": "https://Stackoverflow.com/users/3358597", "pm_score": 1, "selected": false, "text": "C-c . RET \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
251,909
<p>I'm using <code>Microsoft's DSOFramer</code> control to allow me to embed an Excel file in my dialog so the user can choose his sheet, then select his range of cells; it's used with an import button on my dialog.</p> <p>The problem is that when I call the <code>DSOFramer's OPEN</code> function, if I have Excel open in another window, it closes the Excel document (but leaves Excel running). If the document it tries to close has unsaved data, I get a dialog boxclosing Excel doc in another window. If unsaved data in file, <code>dsoframer</code> fails to open with a messagebox: <code>Attempt to access invalid address</code>. </p> <p>I built the source, and stepped through, and its making a call in its <code>CDsoDocObject::CreateFromFile</code> function, calling <code>BindToObject</code> on an object of class IMoniker. The <code>HR</code> is <code>0x8001010a</code> <code>The message filter indicated that the application is busy</code>. On that failure, it tries to <code>InstantiateDocObjectServer</code> by <code>classid</code> of <code>CLSID</code> Microsoft Excel Worksheet... this fails with an <code>HRESULT</code> of <code>0x80040154</code> <code>Class not registered</code>. The <code>InstantiateDocObjectServer</code> just calls <code>CoCreateInstance</code> on the <code>classid</code>, first with <code>CLSCTX_LOCAL_SERVER</code>, then (if that fails) with <code>CLSCTX_INPROC_SERVER</code>.</p> <p>I know <code>DSOFramer</code> is a popular sample project for embedding Office apps in various dialog and forms. I'm hoping someone else has had this problem and might have some insight on how I can solve this. I really don't want it to close any other open Excel documents, and I really don't want it to error-out if it can't close the document due to unsaved data.</p> <p>Update 1: I've tried changing the <code>classid</code> that's passed in to <code>Excel.Application</code> (I know that class will resolve), but that didn't work. In <code>CDsoDocObject</code>, it tries to open key <code>HKEY_CLASSES_ROOT\CLSID\{00024500-0000-0000-C000-000000000046}\DocObject</code>, but fails. I've visually confirmed that the key is not present in my registry; The key is present for the guide, but there's no <code>DocObject</code> subkey. It then produces an error message box: <code>The associated COM server does not support ActiveX document embedding</code>. I get similar (different key, of course) results when I try to use the <code>Excel.Workbook programid</code>.</p> <p><strong>Update 2: I tried starting a 2nd instance of Excel, hoping that my automation would bind to it (being the most recently invoked) instead of the problem Excel instance, but it didn't seem to do that. Results were the same. My problem seems to have boiled down to this: I'm calling the <code>BindToObject</code> on an object of class <code>IMoniker</code>, and receiving <code>0x8001010A (RPC_E_SERVERCALL_RETRYLATER)</code> <code>The message filter indicated that the application is busy</code>. I've tried playing with the flags passed to the <code>BindToObject</code> (via the <code>SetBindOptions</code>), but nothing seems to make any difference.</strong></p> <p><strong>Update 3: It first tries to bind using an IMoniker class. If that fails, it calls <code>CoCreateInstance</code> for the <code>clsid</code> as a <code>fallback</code> method. This may work for other MS Office objects, but when it's Excel, the class is for the Worksheet. I modified the sample to <code>CoCreateInstance _Application</code>, then got the workbooks, then called the <code>Workbooks::Open</code> for the target file, which returns a Worksheet object. I then returned that pointer and merged back with the original sample code path. All working now.</strong></p>
[ { "answer_id": 251922, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": ";; ====================\n;; insert date and time\n\n(defvar current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"\n \"Format of date to insert with `insert-current-date-time' func\nSee help of `format-time-string' for possible replacements\")\n\n(defvar current-time-format \"%a %H:%M:%S\"\n \"Format of date to insert with `insert-current-time' func.\nNote the weekly scope of the command's precision.\")\n\n(defun insert-current-date-time ()\n \"insert the current date and time into current buffer.\nUses `current-date-time-format' for the formatting the date/time.\"\n (interactive)\n (insert \"==========\\n\")\n; (insert (let () (comment-start)))\n (insert (format-time-string current-date-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(defun insert-current-time ()\n \"insert the current time (1-week scope) into the current buffer.\"\n (interactive)\n (insert (format-time-string current-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(global-set-key \"\\C-c\\C-d\" 'insert-current-date-time)\n(global-set-key \"\\C-c\\C-t\" 'insert-current-time)\n" }, { "answer_id": 251935, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "(require 'insert-time)\n(define-key global-map [(control c)(d)] 'insert-date-time)\n(define-key global-map [(control c)(control v)(d)] 'insert-personal-time-stamp)\n" }, { "answer_id": 252088, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 4, "selected": false, "text": "current-time-string format-time-string" }, { "answer_id": 275849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "C-u M-! date\n" }, { "answer_id": 619525, "author": "Michael Paulukonis", "author_id": 41153, "author_profile": "https://Stackoverflow.com/users/41153", "pm_score": 5, "selected": false, "text": "(defun now ()\n \"Insert string for the current time formatted like '2:34 PM'.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%D %-I:%M %p\")))\n\n(defun today ()\n \"Insert string for today's date nicely formatted in American style,\ne.g. Sunday, September 17, 2000.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%A, %B %e, %Y\")))\n" }, { "answer_id": 3509321, "author": "bjkeefe", "author_id": 165727, "author_profile": "https://Stackoverflow.com/users/165727", "pm_score": 2, "selected": false, "text": "(defvar bjk-timestamp-format \"%Y-%m-%d %H:%M\"\n \"Format of date to insert with `bjk-timestamp' function\n%Y-%m-%d %H:%M will produce something of the form YYYY-MM-DD HH:MM\nDo C-h f on `format-time-string' for more info\")\n\n\n(defun bjk-timestamp ()\n \"Insert a timestamp at the current point.\nNote no attempt to go to beginning of line and no added carriage return.\nUses `bjk-timestamp-format' for formatting the date/time.\"\n (interactive)\n (insert (format-time-string bjk-timestamp-format (current-time)))\n )\n (load \"c:/bjk/elisp/bjk-timestamp.el\")\n" }, { "answer_id": 17078689, "author": "tangxinfa", "author_id": 802708, "author_profile": "https://Stackoverflow.com/users/802708", "pm_score": 5, "selected": false, "text": "M-x org-time-stamp\n C-u M-x org-time-stamp\n org-mode" }, { "answer_id": 29374896, "author": "Kaushal Modi", "author_id": 1219634, "author_profile": "https://Stackoverflow.com/users/1219634", "pm_score": 0, "selected": false, "text": "(defun modi/insert-time-stamp (option)\n \"Insert date, time, user name - DWIM.\n\nIf the point is NOT in a comment/string, the time stamp is inserted prefixed\nwith `comment-start' characters.\n\nIf the point is IN a comment/string, the time stamp is inserted without the\n`comment-start' characters. If the time stamp is not being inserted immediately\nafter the `comment-start' characters (followed by optional space),\nthe time stamp is inserted with “--” prefix.\n\nIf the buffer is in a major mode where `comment-start' var is nil, no prefix is\nadded regardless.\n\nAdditional control:\n\n C-u -> Only `comment-start'/`--' prefixes are NOT inserted\n C-u C-u -> Only user name is NOT inserted\nC-u C-u C-u -> Both prefix and user name are not inserted.\"\n (interactive \"P\")\n (let ((current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n ;; Insert prefix only if `comment-start' is defined for the major mode\n (when (stringp comment-start)\n (if (or (nth 3 (syntax-ppss)) ; string\n (nth 4 (syntax-ppss))) ; comment\n ;; If the point is already in a comment/string\n (progn\n ;; If the point is not immediately after `comment-start' chars\n ;; (followed by optional space)\n (when (and (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (not (looking-back (concat comment-start \" *\")))\n (not (looking-back \"^ *\")))\n (insert \"--\")))\n ;; If the point is NOT in a comment\n (progn\n (when (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (insert comment-start)))))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n (insert (format-time-string current-date-time-format (current-time)))\n (when (not (equal option '(16))) ; C-u C-u\n (insert (concat \" - \" (getenv \"USER\"))))\n ;; Insert a space after the time stamp if not at the end of the line\n (when (not (looking-at \" *$\"))\n (insert \" \"))))\n C-c d" }, { "answer_id": 68185786, "author": "Misho M. Petkovic", "author_id": 3358597, "author_profile": "https://Stackoverflow.com/users/3358597", "pm_score": 1, "selected": false, "text": "C-c . RET \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
251,924
<p>Lists in C# have the <code>.ToArray()</code> method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.</p> <p>I am using the <code>String.Split</code> method in the .NET 2.0 environment, so LINQ, etc. is not available to me.</p>
[ { "answer_id": 251928, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 3, "selected": false, "text": "return new List<string>(stringArray);\n" }, { "answer_id": 251929, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 7, "selected": true, "text": "string s = ...\nnew List<string>(s.Split(....));\n" }, { "answer_id": 251979, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 4, "selected": false, "text": "System.Linq ToList<>()" }, { "answer_id": 252795, "author": "heijp06", "author_id": 1793417, "author_profile": "https://Stackoverflow.com/users/1793417", "pm_score": 2, "selected": false, "text": "IList<string> list = myString.Split(' ');\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
251,937
<p>What do you keep on mind to avoid memory leaks when you write thousands lines of .NET code? I'm a big fan of prevention over inspection , there is a famous example regarding this point which is using a "StringBuilder" to combine strings instead of "String1+String2", so what is else out there from your coding experience?</p> <p>thanks in advance for sharing your thoughts.</p>
[ { "answer_id": 251968, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 1, "selected": false, "text": "something.someEvent += new EventHandler(memoryhog.someMethod);\n[...]\nsomething.someEvent += new EventHandler(memoryhog.someMethod);\n[...]\nsomething.someEvent -= new EventHandler(memoryhog.someMethod);\n" }, { "answer_id": 252114, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "string name = myBigComObject.GetFirstChild().Name;\n ChildComObject firstChild = myBigComObject.GetFirstChild()\nstring name = firstChild.Name;\nMarshal.ReleaseComObject(firstChild);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20006/" ]
251,941
<p>I'm in javascript, running this in the console </p> <pre><code>d = new Date(); d.setMonth(1); d.setFullYear(2009); d.setDate(15); d.toString(); </code></pre> <p>outputs this:</p> <pre><code>"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)" </code></pre> <p>Why would this be happening? It seems like a browser bug.</p>
[ { "answer_id": 251962, "author": "Issac Kelly", "author_id": 144, "author_profile": "https://Stackoverflow.com/users/144", "pm_score": 1, "selected": false, "text": "d = new Date();\nd.setDate(15); \nd.setMonth(1);\nd.setFullYear(2009); \nd.toString();\n" }, { "answer_id": 251975, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "d = new Date();\nd.setDate(15); \nd.setMonth(1);\nd.setFullYear(2009); \n new Date(year, month, date [, hour, minute, second, millisecond ]);\n" }, { "answer_id": 251976, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 5, "selected": false, "text": "d = new Date(2009, 1, 15);\n" }, { "answer_id": 9113409, "author": "Alexander Klimetschek", "author_id": 2709, "author_profile": "https://Stackoverflow.com/users/2709", "pm_score": 0, "selected": false, "text": "d.setDate(1);\nd.setFullYear(year);\nd.setMonth(month);\nd.setDate(day);\n setDate(1) setMonth(month) setDate(day) setDate(1)" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
251,945
<p>I have a site that creates images for some bit of content after the content is created. I'm trying to figure out what to do in between the time the content is created and the image is created. My thought is that I might be able to set a custom image to display on a 404 error on the original image. However, I'm not sure how to do this with lighttpd. Any ideas or alternatives?</p> <p>EDIT: The issue is the user isn't the one creating the content, it's being created by a process. Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider. However, I don't want a slow server on the provider end to slow down the addition of new products. So a separate process goes through and creates the image later, where available. I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.</p>
[ { "answer_id": 251977, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "<object> <P> <!-- First, try the Python applet -->\n<OBJECT title=\"The Earth as seen from space\" \n classid=\"http://www.observer.mars/TheEarth.py\">\n <!-- Else, try the MPEG video -->\n <OBJECT data=\"TheEarth.mpeg\" type=\"application/mpeg\">\n <!-- Else, try the GIF image -->\n <OBJECT data=\"TheEarth.gif\" type=\"image/gif\">\n <!-- Else render the text -->\n The <STRONG>Earth</STRONG> as seen from space.\n </OBJECT>\n </OBJECT>\n</OBJECT>\n</P>\n" }, { "answer_id": 305420, "author": "EoghanM", "author_id": 6691, "author_profile": "https://Stackoverflow.com/users/6691", "pm_score": 0, "selected": false, "text": "<OBJECT data=\"/images/generated_image_xyz.png\" type=\"image/png\">\n Loading..<blink>.</blink>\n</OBJECT>\n <style type=\"text/css\">\n .content_image { width:100px; height: 100px; \n background: transparent url('/images/default_image.png') no-repeat }\n .content_image div { width:100px; height: 100px; }\n</style>\n\n<div class=\"content_image\">\n <div style=\"background: \n transparent url('/images/generated_image_xyz.png') no-repeat\" />\n</div>\n" }, { "answer_id": 333768, "author": "EoghanM", "author_id": 6691, "author_profile": "https://Stackoverflow.com/users/6691", "pm_score": 2, "selected": false, "text": "<img src=\"/images/generated_image_xyz.png\" \n onerror=\"this.src='/images/default_image.png'; this.title='Loading...';\" />\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31240/" ]
251,946
<p>I am currently using Subversion as my Source Control system, mainly because I found ANkhSVN to be a quite nicely integrated into Visual Studio.</p> <p>But many people seem to be using Git or Mercurial and others with great success.</p> <p>Now, I am wondering how to use a system like Git without some sort of IDE integration.</p> <p>Going to the command line to do source control seems very awkward to me, too much hassle.</p> <p><strong>Update:</strong> this has caused quite some discussion.</p> <p>I just wanted to know what your workflow is like, I know how to learn and use the command line tools. They just didn't feel that comfortable due to things like renaming/adding files. I'll stick to AnkhSVN as my svn client of choice within Visual Studio and use TortoiseSVN for files outside of VS. Anyway, thanks for your answers!</p>
[ { "answer_id": 251965, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "svn add <filename> svn commit --message <foo>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
251,957
<p>I have a simple table in SQL Server 2005, I wish to convert this to XML (using the "FOR XML" clause). I'm having trouble getting my XML to look like the required output.</p> <p>I've tried looking through various tutorials on the web, but I am struggling. Can someone help?</p> <p>The table I have looks like this</p> <pre><code>TYPE,GROUP,VALUE Books,Hardback,56 Books,Softcover,34 CDs,Singles,45 CDS,Multis,78 </code></pre> <p>The output style I need is:</p> <pre><code>&lt;data&gt; &lt;variable name="TYPE"&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;/variable&gt; &lt;variable name="TYPE"&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;/variable&gt; &lt;/data&gt; </code></pre> <p><strong>Edit:</strong> As far as I can tell I require the multiple values. I'm generating XML for use with Xcelsius (<a href="http://xcelsius.files.wordpress.com/2008/05/xml_data_button.pdf" rel="nofollow noreferrer">Linking XML and Xcelsius</a>) so have no control over in the formatting of the XML. I can generate the XML using ASP as per the linked tutorial, but I was hoping to get it straight from SQL Server.</p> <p><strong>Edit 2:</strong> I was hoping for something elegant and tidy... but Godeke's example got the closest. Some fiddling with the SQL and I've come up with:</p> <pre><code>select "type" as '@name', "group" as 'row/column', null as 'row/tmp', "value" as 'row/column' from tableName for xml path('variable'), root('data') </code></pre> <p>Outputs almost in the exact way I wanted. The null/tmp line doesn't even output; it is just preventing the concatenation. Still the tag <code>&lt;variable name="TYPE"&gt;</code> repeats for each row, which I can't have.</p>
[ { "answer_id": 252021, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 1, "selected": false, "text": " /*\ncreate table #tablename\n(\n[type] varchar(20),\n[group] varchar(20),\n[value] varchar(20)\n)\n\ninsert into #tablename select 'type1','group11','value111'\ninsert into #tablename select 'type1','group11','value112'\ninsert into #tablename select 'type1','group12','value121'\ninsert into #tablename select 'type1','group12','value122'\ninsert into #tablename select 'type2','group21','value211'\ninsert into #tablename select 'type2','group21','value212'\ninsert into #tablename select 'type2','group22','value221'\ninsert into #tablename select 'type2','group22','value222'\n\nalter table #tablename add id uniqueidentifier\n\nupdate #tablename set id = newid()\n*/\n\nselect [type] as '@name',\n (select \n (select [column] from\n (\n select [group] as 'column', tbn1.type, tbn2.[group]\n from #tablename tbn3 WHERE tbn3.type = tbn1.type and tbn2.[group] = tbn3.[group]\n union\n select [value], tbn1.type, tbn2.[group]\n from #tablename tbn3 WHERE tbn3.type = tbn1.type and tbn2.[group] = tbn3.[group]\n ) as s\n for xml path(''),type \n )\n from #tablename tbn2 \n where tbn2.type = tbn1.type\n for xml path('row3'), type\n)\n\nfrom #tableName tbn1 \nGROUP BY [type]\nfor xml path('variable'), root('data') \n" }, { "answer_id": 252061, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 2, "selected": false, "text": "select \"type\" as '@name', \"group\" as 'row/column1', \"value\" as 'row/column2'\nfrom tableName\nfor xml path('variable'), root('data')\n select distinct \"type\" as '@name'\nfrom Agent\nfor xml path('variable'), root('data')\n" }, { "answer_id": 252378, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 0, "selected": false, "text": "\nDECLARE @tblItems table (\n    [TYPE] varchar(50)\n    ,[GROUP] varchar(50)\n    ,[VALUE] int\n)\n\nDECLARE @tblShredded table (\n    [TYPE] varchar(50)\n    ,[XmlItem] xml\n)\n\nDECLARE @xmlGroupValueTuples xml\n\ninsert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'Books','Hardback',56)\ninsert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'Books','Softcover',34)\ninsert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'CDs','Singles',45)\ninsert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'CDS','Multis',78)\n\nSET @xmlGroupValueTuples =\n  (\n    SELECT\n      \"@TYPE\" = [TYPE]\n      ,[GROUP]\n      ,[VALUE]\n    FROM @tblItems\n    FOR XML PATH('row'), root('Root')\n  )\n\nINSERT @tblShredded([TYPE], XmlItem)\nSELECT\n    [TYPE] = XmlItem.value('./row[1]/@TYPE', 'varchar(50)')\n    ,XmlItem\nFROM dbo.tvfShredGetOneColumnedTableOfXmlItems(@xmlGroupValueTuples)\n\n\nSELECT \n  (\n    SELECT\n      VARIABLE =\n        (\n          SELECT\n            \"@TYPE\" = t.[TYPE]\n \n            ,(\n              SELECT\n                tInner.XmlItem.query('./child::*')\n              FROM @tblShredded tInner\n              WHERE tInner.[TYPE] = t.[TYPE]\n              FOR XML PATH(''), ELEMENTS, type\n            )\n          FOR XML PATH('VARIABLE'),type\n        )\n  )\nFROM @tblShredded t\nGROUP BY \n    t.[TYPE]\nFOR XML PATH(''), ROOT('DATA')\n\n \n-- Example Inputs \n/*\nDECLARE @xmlListFormat xml\nSET @xmlListFormat =\n    '\n        <XmlListRoot>\n            <Item>004421UB7</Item>\n            <Item>59020UH24</Item>\n            <Item>542514NA8</Item>\n        </XmlListRoot>\n    '\n*/\n\n-- =============================================\n-- Author: 6eorge Jetson\n-- Create date: 01/22/3003\n-- Description: Shreds an input XML list conforming to the expected list schema \n-- =============================================\nCREATE FUNCTION [dbo].[tvfShredGetOneColumnedTableOfXmlItems] (@xmlListFormat xml)\nRETURNS \n@tblResults TABLE (XmlItem xml)\nAS\nBEGIN\n\n    INSERT @tblResults\n    SELECT\n        tblShredded.colXmlItem.query('.') as XmlItem\n    FROM\n        @xmlListFormat.nodes('/child::*/child::*') as tblShredded(colXmlItem)\n\n    RETURN \nEND\n\n\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15144/" ]
251,960
<p>I have a long running insert transaction that inserts data into several related tables. </p> <p>When this insert is running, I cannot perform a select * from MainTable. The select just spins its wheels until the insert is done. </p> <p>I will be performing several of these inserts at the same/overlapping time. To check that the information is not inserted twice, I query the MainTable first to see if an entry is there and that its processed bit is not set. </p> <p>During the insert transaction, it flips the MainTable processed bit for that row.</p> <p>So I need to be able to read the table and also be able to tell if the specific row is currently being updated.</p> <p>Any ideas on how to set this up in Microsoft SQL 2005? I am looking through the <a href="http://msdn.microsoft.com/en-us/library/ms173763.aspx" rel="nofollow noreferrer">SET TRANSACTION ISOLATION LEVEL</a> documentation.</p> <p>Thank you,<br> Keith</p> <p><b>EDIT:</b> I do not think that the same insert batch will happen at the same time. These are binary files that are being processed and their data inserted into the database. I check that the file has not been processed before I parse and insert the data. When I do the check, if the file has not been seen before I do a quick insert into the MainTable with the processed bit set false. </p> <p>Is there a way to lock the row being updated instead of the entire table? </p>
[ { "answer_id": 252005, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\n" }, { "answer_id": 252025, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": true, "text": "BEGIN TRANSACTION\n\nSELECT @ProcessedBit = ProcessedBit FROM MainTable WHERE ID = XXX\n\nIF @ProcessedBit = False\n UPDATE MainTable SET ProcessedBit = True WHERE ID = XXX\n\nCOMMIT TRANSACTION\n\nIF @ProcessedBit = False\nBEGIN\n BEGIN TRANSACTION\n -- start long running process\n ...\n COMMIT TRANSACTION\nEND\n BEGIN TRANSACTION\n\nSELECT @ProcessedStatus = ProcessedStatus FROM MainTable WHERE ID = XXX\n\nIF @ProcessedStatus = 'Not Processed'\n UPDATE MainTable SET ProcessedBit = 'Processing' WHERE ID = XXX\n\nCOMMIT TRANSACTION\n\nIF @ProcessedStatus = 'Not Processed'\nBEGIN\n BEGIN TRANSACTION\n -- start long running process\n ...\n\n IF No Errors\n BEGIN\n UPDATE MainTable SET ProcessedStatus = 'Processed' WHERE ID = XXX\n COMMIT TRANSACTION\n ELSE\n ROLLBACK TRANSACTION\n\nEND\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
251,964
<p>I often accidentally create a branch that contains more code than it needs to. When that happens, I delete the branch files, the branch tag, and then start over. The thing that stinks is having to sync the huge pile of data just so I can delete it.</p> <p>Is there a way to delete server-side?</p>
[ { "answer_id": 252038, "author": "pd.", "author_id": 19066, "author_profile": "https://Stackoverflow.com/users/19066", "pm_score": 4, "selected": false, "text": "//depot/oops/... //your-client/oops/...\n p4 sync -k oops/...\n p4 delete oops/...\np4 submit oops/...\n" }, { "answer_id": 2974331, "author": "din", "author_id": 358463, "author_profile": "https://Stackoverflow.com/users/358463", "pm_score": 3, "selected": false, "text": "p4 delete -v oops/...\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116/" ]
251,985
<p>I am binding the dropdown with db entity. </p> <pre><code>ddlCustomer.DataSource = Customer.GetAll(); ddlCustomer.DataTextField = "CustomerName"; ddlCustomer.DataBind(); </code></pre> <p>I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this?</p>
[ { "answer_id": 251998, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 3, "selected": true, "text": "ddlCustomer.Items.Insert(0, \"SELECT\");\n" }, { "answer_id": 255711, "author": "Stefan", "author_id": 30604, "author_profile": "https://Stackoverflow.com/users/30604", "pm_score": 0, "selected": false, "text": "<asp:DropDownList AppendDataBoundItems=\"true\" ID=\"ddlCustomer\" runat=\"server\">\n <asp:ListItem Value=\"0\" Text=\"Select\"/>\n</asp:DropDownList>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
251,987
<p>Imagine I have a property defined in global.asax. </p> <pre><code>public List&lt;string&gt; Roles { get { ... } set { ... } } </code></pre> <p>I want to use the value in another page. how to I refer to it?</p>
[ { "answer_id": 252013, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "public partial class _Default : System.Web.UI.Page \n{\n}\n public class BasePage : System.Web.UI.Page \n{\n public List<string> Roles\n {\n get { ... }\n set { ... }\n }\n}\n public partial class _Default : BasePage\n{\n}\n" }, { "answer_id": 252015, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 5, "selected": true, "text": "((Global)this.Context.ApplicationInstance).Roles\n" }, { "answer_id": 252032, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 0, "selected": false, "text": "Dim someValue As Integer = 5\nContext.Items.Add(\"dataKey\", someValue)\n Dim someValue As Integer = CType(HttpContext.Current.Items(\"dataKey\"), Integer)\n" }, { "answer_id": 4460925, "author": "B Faley", "author_id": 69537, "author_profile": "https://Stackoverflow.com/users/69537", "pm_score": 1, "selected": false, "text": "((Global)HttpContext.Current.ApplicationInstance).Roles\n" }, { "answer_id": 17617651, "author": "Daniel B", "author_id": 336511, "author_profile": "https://Stackoverflow.com/users/336511", "pm_score": 0, "selected": false, "text": "dynamic roles= ((dynamic)System.Web.HttpContext.Current.ApplicationInstance).Roles;\nif (roles!= null){\n // my codes\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
252,014
<p>Sometimes it's difficult to describe some of the things that "us programmers" may think are simple to non-programmers and management types.</p> <p>So...</p> <p>How would you describe the difference between Managed Code (or Java Byte Code) and Unmanaged/Native Code to a Non-Programmer?</p>
[ { "answer_id": 252034, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "malloc free" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
252,028
<p>I have a very strange bug cropping up right now in a fairly massive C++ application at work (massive in terms of CPU and RAM usage as well as code length - in excess of 100,000 lines). This is running on a dual-core Sun Solaris 10 machine. The program subscribes to stock price feeds and displays them on "pages" configured by the user (a page is a window construct customized by the user - the program allows the user to configure such pages). This program used to work without issue until one of the underlying libraries became multi-threaded. The parts of the program affected by this have been changed accordingly. On to my problem. </p> <p>Roughly once in every three executions the program will segfault on startup. This is not necessarily a hard rule - sometimes it'll crash three times in a row then work five times in a row. It's the segfault that's interesting (read: painful). It may manifest itself in a number of ways, but most commonly what will happen is function A calls function B and upon entering function B the frame pointer will suddenly be set to 0x000002. Function A:</p> <pre><code> result_type emit(typename type_trait&lt;T_arg1&gt;::take _A_a1) const { return emitter_type::emit(impl_, _A_a1); } </code></pre> <p>This is a simple signal implementation. impl_ and _A_a1 are well-defined within their frame at the crash. On actual execution of that instruction, we end up at program counter 0x000002. </p> <p>This doesn't always happen on that function. In fact it happens in quite a few places, but this is one of the simpler cases that doesn't leave that much room for error. Sometimes what will happen is a stack-allocated variable will suddenly be sitting on junk memory (always on 0x000002) for no reason whatsoever. Other times, that same code will run just fine. So, my question is, what can mangle the stack so badly? What can actually change the value of the frame pointer? I've certainly never heard of such a thing. About the only thing I can think of is writing out of bounds on an array, but I've built it with a stack protector which should come up with any instances of that happening. I'm also well within the bounds of my stack here. I also don't see how another thread could overwrite the variable on the stack of the first thread since each thread has it's own stack (this is all pthreads). I've tried building this on a linux machine and while I don't get segfaults there, roughly one out of three times it will freeze up on me. </p>
[ { "answer_id": 252070, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "gdb vector" }, { "answer_id": 254262, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "void foo()\n{\n foo(); // endless recursion - whoops!\n}\n\nvoid foo2()\n{\n char myBuffer[A_VERY_BIG_NUMBER]; // The stack can't hold that much.\n}\n\nclass bigObj\n{\n char myBuffer[A_VERY_BIG_NUMBER]; \n}\n\nvoid foo2( bigObj big1) // pass by value of a big object - whoops!\n{\n}\n void foo()\n{ \n char message[10];\n\n message[10] = '!'; // whoops! beyond end of array\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,035
<p>I am building a relatively simple <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow noreferrer">Django</a> application and apart from the main page where most of the dynamic parts of the application are, there are a few pages that I will need that will not be dynamic at all (<em>About</em>, <em>FAQ</em>, etc.). What is the best way to integrate these into Django, idealing still using the Django template engine? Should I just create a template for each and then have a view that simply renders that template?</p>
[ { "answer_id": 252057, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "direct_to_template django.contrib.flatpages" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
252,050
<p>We are developing a small in-house application that will run on monitor having multi resolutions. Now we want that the application should adjust itself and remain consistent over all monitors.</p> <p>I came from a Java background too where we used different layouts to accomplish the task. I experimented in .NET with different layouts like UniGrid (which provide the consistency but very restrictive), Grid, etc. but failed in the required task. </p> <p>What are some possible layout model or some other solution?</p> <p><strong>I think if we can specify percentage width or height as we do in CSS/HTML then we can adopt this cross-resolution policy. I found Infergistics have such controls, but can this can be achieved via default controls?</strong></p> <p>P.S.: I am actually trying in WPF (preferably WPF native application).</p>
[ { "answer_id": 252131, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "Anchor Resize SizeChanged" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17519/" ]
252,055
<p>I have a couple of questions about generic wildcards in Java:</p> <ol> <li><p>What is the difference between <code>List&lt;? extends T&gt;</code> and <code>List&lt;? super T&gt;</code>?</p></li> <li><p>What is a bounded wildcard and what is an unbounded wildcard?</p></li> </ol>
[ { "answer_id": 252099, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": true, "text": "<? extends T> <? super T> <?> <? extends Object> <? extends T> <? super T> <? extends T> <? super T>" }, { "answer_id": 252109, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 6, "selected": false, "text": "A B A C D B class A {}\nclass B extends A {}\nclass C extends B {}\nclass D extends B {}\n List<? extends A> la;\nla = new ArrayList<B>();\nla = new ArrayList<C>();\nla = new ArrayList<D>();\n\nList<? super B> lb;\nlb = new ArrayList<A>(); //fine\nlb = new ArrayList<C>(); //will not compile\n\npublic void someMethod(List<? extends B> lb) {\n B b = lb.get(0); // is fine\n lb.add(new C()); //will not compile as we do not know the type of the list, only that it is bounded above by B\n}\n\npublic void otherMethod(List<? super B> lb) {\n B b = lb.get(0); // will not compile as we do not know whether the list is of type B, it may be a List<A> and only contain instances of A\n lb.add(new B()); // is fine, as we know that it will be a super type of A \n}\n ? extends B B" }, { "answer_id": 252860, "author": "blank", "author_id": 1348, "author_profile": "https://Stackoverflow.com/users/1348", "pm_score": 5, "selected": false, "text": "super extends extends super Stack<E> void pushAll(Collection<? extends E> src); void popAll(Collection<? super E> dst);" }, { "answer_id": 27837085, "author": "Sandeep Kumar", "author_id": 2786474, "author_profile": "https://Stackoverflow.com/users/2786474", "pm_score": 2, "selected": false, "text": "Collection<? extends MyObject> \n class MyObject {}\n\nclass YourObject extends MyObject{}\n\nclass OurObject extends MyObject{}\n Collection<? extends MyObject> myObject; \n" }, { "answer_id": 30956395, "author": "Prateek Joshi", "author_id": 4281711, "author_profile": "https://Stackoverflow.com/users/4281711", "pm_score": 1, "selected": false, "text": "? extends E List<Integer> ints = new ArrayList<Integer>();\nints.add(1);\nints.add(2);\nList<? extends Number> nums = ints;\nnums.add(3.14); // compile-time error\nassert ints.toString().equals(\"[1, 2, 3.14]\"); \n Wildcards with super List<Object> objs = Arrays.<Object>asList(2, 3.14, \"four\");\n List<Integer> ints = Arrays.asList(5, 6);\n Collections.copy(objs, ints);\n assert objs.toString().equals(\"[5, 6, four]\");\n\n public static <T> void copy(List<? super T> dst, List<? extends T> src) {\n for (int i = 0; i < src.size(); i++) {\n dst.set(i, src.get(i));\n }\n }\n" }, { "answer_id": 41013693, "author": "taoxiaopang", "author_id": 3675231, "author_profile": "https://Stackoverflow.com/users/3675231", "pm_score": 1, "selected": false, "text": "List<A> List<A> List<A> List<A-sub> List<A> List<A-super>" }, { "answer_id": 72160674, "author": "mhrsalehi", "author_id": 11762199, "author_profile": "https://Stackoverflow.com/users/11762199", "pm_score": 0, "selected": false, "text": "sort() Collections extends super public static <T extends Comparable<? super T>> void sort(List<T> list){...}\n <T extends Comparable<...>> T Comparable Comparable<? super T> Comparable interface Comparable<T>{\n public int compareTo(T o);\n}\n\npublic static <T extends Comparable<? super T>> void sort(List<T> list){...}\n\n\npublic static <T extends Comparable<T>> void sort2(List<T> list){...}\n\n\nclass A implements Comparable<A>{\n @Override\n public int compareTo(A o) {\n ...\n }\n}\n\nclass B extends A {\n}\n\n List<A> listA = new ArrayList<>();\n List<B> listB = new ArrayList<>();\n\n sort(listA); //ok\n sort(listB); //ok\n \n sort2(listA); //ok\n sort2(listB); //Error\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
252,066
<p>Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?</p>
[ { "answer_id": 252075, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 2, "selected": false, "text": " Array.Sort(array,delegate(string a, string b)\n {\n return b.CompareTo(a);\n });\n" }, { "answer_id": 252080, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "Array.Sort(myarray, (a, b) => b.CompareTo(a));\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,082
<p>I have a J2ee application where I basically want two objects, created by two separate servlets to communicate directly and I need these intances to be stable, i.e. to "know" each other during the session.</p> <p>The sequence is roughly: <br></p> <ol> <li>Client sends a request to Servlet #1, which creates object A</li> <li>Client sends a second request (after the first returns) to servlet #2 which creates object B.</li> <li>Object B finds A, using JNDI, and the two objects interact.</li> <li>The client now continues to send requests to object A which needs to find B again.</li> </ol> <p>How do I make sure that these two instances know each throughout the session? Binding them to JNDI doesn't entirely solve the problem, since object B needs to communicate with its original servlet (servlet #2), which is not kept stable across requests.</p> <p>Any ideas?</p> <p>Thanks in advance.</p> <hr> <p>Yes, I admit the problem description is a bit vague. But it's not a very simple application. Still, I will try to ask it better:</p> <p>My end goal is to create a sort of a "semantic debugger" for my application that, as opposed to a java debugger which simply debugs the java statements.</p> <p>The application debugged is basically a servlet. which my tool connects to. The tool maintains a connection to the application through another servlet which controls the debugging process. These two servlets need to communicate with each other constantly and directly.</p> <p>My current thought is to set up a stateful session bean that will facilitate this communication (never done it, still struggling with setting it up).</p> <p>But I would appreciate any thoughts on how to achieve this better.</p>
[ { "answer_id": 252987, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 0, "selected": false, "text": "public class BusinessServlet {\n\nprotected void doGet(HttpServletRequest req, HttpServletResponse res) {\n HttpSession session = req.getSession(true);\n BusinessCode business = session.getAttribute(\"A\");\n if (business == null) { \n business = new BusinessCode();\n session.setAttribute(\"A\", business);\n }\n\n DebugObject debug = session.getAttribute(\"B\");\n if (debug == null) { \n debug = new DebugObject();\n session.setAttribute(\"B\", debug);\n }\n\n business.doSomeWork(debug); \n }\n} \n\npublic class DebugServlet {\n protected void doGet(HttpServletRequest req, HttpServletResponse res) {\n HttpSession session = req.getSession(true);\n DebugObject debug = session.getAttribute(\"B\");\n if (debug != null) {\n debug.printDebugMessages(res);\n }\n }\n} \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13321/" ]
252,149
<p>The following is code I've used to create a <code>memory mapped file</code>:</p> <pre><code>fid = open(filename, O_CREAT | O_RDWR, 0660); if ( 0 &gt; fid ) { throw error; } /* mapped offset pointer to data file */ offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP); /* Initialize table */ memset(offset_table_p, 0x00, (table_size + 1) * 2); </code></pre> <p>say table_size is around 2XXXXXXXX bytes.</p> <p>During debug, I've noticed it fails while attempt to initializing the 'offset table pointer',</p> <p>Can anyone provide me some inputs on why it's failing during intilalization? is there any possibilities that my memory map file was not created with required table size?</p>
[ { "answer_id": 252261, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "char paxbuff[1000]; // at start of function\nsprintf (paxbuff,\"ls -al %s\",filename);\nsystem (paxbuff);\nfid = open(filename, O_CREAT | O_RDWR, 0660); // this line already exists.\nsystem (paxbuff);\n offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP); // already exists.\nprintf (\"ret = %p, errno = %d\\n\",offset_table_p,errno);\nprintf (\"sz = %d\\n\",table_size);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,151
<p>Is there any way to insert a text (string, may or may not have html tags) to a <code>div</code>?</p> <p>It has to be a <code>div</code> and not a <code>textarea</code>.</p> <p>First of all, I need to get the cursor position, then insert the text in that position. It's similar to function <code>insertAdjacentText</code>, but it can only insert before or after a tag, and only works in IE.</p> <p>Refer to this URL: <a href="http://yart.com.au/test/iframe.aspx" rel="nofollow noreferrer">http://yart.com.au/test/iframe.aspx</a>. Note how you can position the cursor in the div, we need to add text at the cursor location.</p>
[ { "answer_id": 253736, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "document.selection.createRange().pasteHTML(theNewHTML) document.execCommand(\"InsertHTML\", ...)" }, { "answer_id": 19724516, "author": "SyntaxLAMP", "author_id": 2944555, "author_profile": "https://Stackoverflow.com/users/2944555", "pm_score": 0, "selected": false, "text": "iFrame.focus()\niFrame.document.execCommand(\"insertImage\", \"\", \"fakeimage.jpg\")\niFrame.document.body.innerHTML=iFrame.document.body.innerHTML.replace(\"<img src=\\\"fakeimage.jpg\\\">\", \"MY CUSTOM <b>HTML</b> HERE!\")\n" }, { "answer_id": 19725729, "author": "Tim Down", "author_id": 96100, "author_profile": "https://Stackoverflow.com/users/96100", "pm_score": 1, "selected": false, "text": "function pasteHtmlAtCaret(html, selectPastedContent, iframe) {\n var sel, range;\n var win = iframe ? iframe.contentWindow : window;\n var doc = win.document;\n if (win.getSelection) {\n // IE9 and non-IE\n sel = win.getSelection();\n if (sel.getRangeAt && sel.rangeCount) {\n range = sel.getRangeAt(0);\n range.deleteContents();\n\n // Range.createContextualFragment() would be useful here but is\n // only relatively recently standardized and is not supported in\n // some browsers (IE9, for one)\n var el = doc.createElement(\"div\");\n el.innerHTML = html;\n var frag = doc.createDocumentFragment(), node, lastNode;\n while ( (node = el.firstChild) ) {\n lastNode = frag.appendChild(node);\n }\n var firstNode = frag.firstChild;\n range.insertNode(frag);\n\n // Preserve the selection\n if (lastNode) {\n range = range.cloneRange();\n range.setStartAfter(lastNode);\n if (selectPastedContent) {\n range.setStartBefore(firstNode);\n } else {\n range.collapse(true);\n }\n sel.removeAllRanges();\n sel.addRange(range);\n }\n }\n } else if ( (sel = doc.selection) && sel.type != \"Control\") {\n // IE < 9\n var originalRange = sel.createRange();\n originalRange.collapse(true);\n sel.createRange().pasteHTML(html);\n if (selectPastedContent) {\n range = sel.createRange();\n range.setEndPoint(\"StartToStart\", originalRange);\n range.select();\n }\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32941/" ]