qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
141,169
<p>So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.</p> <p>The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.</p> <p>I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?</p> <p>Thanks!</p>
[ { "answer_id": 201301, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 2, "selected": false, "text": "LoadViewState() LoadViewState() SaveViewState() private string searchQuery = null;\n\nprivate void SearchButton(object sender, EventArgs e)\n{\n searchQuery = searchBox.Text;\n var results = DataLayer.PerformSearch(searchQuery);\n CreateLinkButtonControls(results);\n}\n\n// We save both the base state object, plus our query string. Everything here must be serializable.\nprotected override object SaveViewState()\n{\n object baseState = base.SaveViewState();\n return new object[] { baseState, searchQuery };\n}\n\n// The parameter to this method is the exact object we returned from SaveViewState().\nprotected override void LoadViewState(object savedState)\n{\n object[] stateArray = (object[])savedState;\n\n searchQuery = stateArray[1] as string;\n\n // Re-run the query\n var results = DataLayer.PerformSearch(searchQuery);\n\n // Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break.\n CreateLinkButtonControls(results);\n\n // Very important - load the rest of the ViewState, including our controls above.\n base.LoadViewState(stateArray[0]);\n}\n" }, { "answer_id": 2559375, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": -1, "selected": false, "text": " var link = new LinkButton();\n link.ID = \"foo\";\n link.Click += fooEventHandler;\n dummyButtons.Controls.Add(link);\n" }, { "answer_id": 41589644, "author": "M.Rahmani", "author_id": 5467185, "author_profile": "https://Stackoverflow.com/users/5467185", "pm_score": 0, "selected": false, "text": " LinkButton link= new LinkButton();\n link.Command +=new CommandEventHandler(LinkButton1_Command);\n\n protected void LinkButton1_Command(object sender, CommandEventArgs e)\n{\n try\n {\n System.Threading.Thread.Sleep(300);\n if (e.CommandName == \"link\")\n {\n //////////\n }\n }\n catch\n {\n\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19086/" ]
141,201
<p>I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well.</p> <p>I understand that establish_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work:</p> <pre><code>class Foo &lt; ActiveRecord::Base establish_connection(('foo_' + ENV['RAILS_ENV']).intern) end </code></pre>
[ { "answer_id": 141314, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 3, "selected": false, "text": "class Foo < ActiveRecord::Base\n establish_connection \"foo_#{ENV['RAILS_ENV']}\"\nend\n" }, { "answer_id": 143357, "author": "Priit", "author_id": 22964, "author_profile": "https://Stackoverflow.com/users/22964", "pm_score": 5, "selected": true, "text": "class AnotherBase < ActiveRecord::Base\n self.abstract_class = true\n establish_connection \"anotherbase_#{RAILS_ENV}\"\nend\n class Foo < AnotherBase\nend\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809/" ]
141,203
<p>I'm trying to grok the purpose of .NET's SecureString. From MSDN:</p> <blockquote> <p>An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.</p> <p>A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.</p> <p>The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.</p> </blockquote> <p>Is the automatic encryption the big payoff?</p> <p>And why can't I just say:</p> <pre><code>SecureString password = new SecureString(&quot;password&quot;); </code></pre> <p>instead of</p> <pre><code>SecureString pass = new SecureString(); foreach (char c in &quot;password&quot;.ToCharArray()) pass.AppendChar(c); </code></pre> <p>What aspect of SecureString am I missing?</p>
[ { "answer_id": 141393, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 7, "selected": false, "text": "SecureString System.Windows.Controls.PasswordBox PasswordBox::SecurePassword System.Diagnostics.ProcessStartInfo::Password SecureString X509Certificate2 SecureString SecureStrings SecureString SecureString" }, { "answer_id": 143475, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 5, "selected": false, "text": "SecureString SecureString System.String SecureString" }, { "answer_id": 41192547, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "SecureString password = new SecureString(\"password\");\n password SecureZeroMemory ZeroMemory ZeroMemory SecureZeroMemory //Wipe out the password\nfor (int i=0; i<password.Length; i++)\n password[i] = \\0;\n ZeroMemory Dispose SecureString password = new SecureString(\"password\");\n password String connectionString = secureConnectionString.ToString()\n SqlCredential cred = new SqlCredential(userid, password); //password is SecureString\nSqlConnection conn = new SqlConnection(connectionString);\nconn.Credential = cred;\nconn.Open();\n SqlConnection.ChangePassword(connectionString, cred, newPassword);\n private static string CreateString(SecureString secureString)\n{\n IntPtr intPtr = IntPtr.Zero;\n if (secureString == null || secureString.Length == 0)\n {\n return string.Empty;\n }\n string result;\n try\n {\n intPtr = Marshal.SecureStringToBSTR(secureString);\n result = Marshal.PtrToStringBSTR(intPtr);\n }\n finally\n {\n if (intPtr != IntPtr.Zero)\n {\n Marshal.ZeroFreeBSTR(intPtr);\n }\n }\n return result;\n}\n Char[] for (int i=0; i < PasswordArray.Length; i++)\n{\n password.AppendChar(PasswordArray[i]);\n PasswordArray[i] = (Char)0;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2258/" ]
141,204
<p>I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.</p> <p>Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?</p> <pre><code>public class SomeDataClass : IDisposable { private SqlConnection _conn; //constructors and methods private DoSomethingWithTheSqlConnection() { //some code excluded for brevity try { using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection)) { _SqlConnection.Open(); countOfSomething = Convert.ToInt32(cmd.ExecuteScalar()); } } finally { //is this the best way? if (_SqlConnection.State == ConnectionState.Closed) _SqlConnection.Close(); } //some code excluded for brevity } public Dispose() { _conn.Dispose(); } } </code></pre>
[ { "answer_id": 141215, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 7, "selected": true, "text": "using (SqlConnection conn = new SqlConnection (...))\n{\n // Whatever happens in here, the connection is \n // disposed of (closed) at the end.\n}\n" }, { "answer_id": 141228, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "_SqlConnection.State == ConnectionState.Closed != Dispose()" }, { "answer_id": 141235, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": -1, "selected": false, "text": "\n class SqlOpener : IDisposable\n {\n SqlConnection _connection;\n\n public SqlOpener(SqlConnection connection)\n {\n _connection = connection;\n _connection.Open();\n\n }\n\n void IDisposable.Dispose()\n {\n _connection.Close();\n }\n }\n\n public class SomeDataClass : IDisposable\n {\n private SqlConnection _conn;\n\n //constructors and methods\n\n private void DoSomethingWithTheSqlConnection()\n {\n //some code excluded for brevity\n using (SqlCommand cmd = new SqlCommand(\"some sql query\", _conn))\n using(new SqlOpener(_conn))\n {\n int countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());\n }\n //some code excluded for brevity\n }\n\n public void Dispose()\n {\n _conn.Dispose();\n }\n }\n" }, { "answer_id": 141298, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 1, "selected": false, "text": "using try/finally Dispose IDisposable Dispose" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
141,212
<p>I'm working on a form that will display links to open different types of reports. This system has different types of users, so the users should only be able to see the links to the types of reports they can access.</p> <p>Currently, the way I have this set up is that I have an ArrayList of LinkLabels, but the problem I'm having is how to have a LinkClicked event for each LinkLabel in the ArrayList so that it will bring up a form specific to each report.</p>
[ { "answer_id": 141286, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 0, "selected": false, "text": "Report r = m_TheTable[sender] as Report;\nif( r != null ) r.DoSomething();\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4827/" ]
141,232
<p>I'm working on a project with a rather large Oracle database (although my question applies equally well to other databases). We have a web interface which allows users to search on almost any possible combination of fields.</p> <p>To make these searches go fast, we're adding indexes to the fields and combinations of fields on which we believe users will commonly search. However, since we don't really know how our customers will use this software, it's hard to tell which indexes to create.</p> <p>Space isn't a concern; we have a 4 terabyte RAID drive of which we are using only a small fraction. However, I'm worried about the possible performance penalties of having too many indexes. Because those indexes need to be updated every time a row is added, deleted, or modified, I imagine it'd be a bad idea to have dozens of indexes on a single table.</p> <p>So how many indexes is considered too many? 10? 25? 50? Or should I just cover the really, really common and obvious cases and ignore everything else?</p>
[ { "answer_id": 142156, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 5, "selected": false, "text": "alter index my_index_name monitoring usage;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
141,241
<p>I've seen reference in some C# posted questions to a "using" clause. Does java have the equivalent?</p>
[ { "answer_id": 141267, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 6, "selected": true, "text": "try(InputStream is1 = new FileInputStream(\"/tmp/foo\");\n InputStream is2 = new FileInputStream(\"/tmp/bar\")) {\n /* do stuff with is1 and is2 */\n}\n using InputStream is1 = new FileInputStream(\"/tmp/foo\");\ntry{\n\n InputStream is2 = new FileInputStream(\"/tmp/bar\");\n try{\n /* do stuff with is1 and is 2 */\n\n } finally {\n is2.close();\n }\n} finally {\n is1.close();\n}\n" }, { "answer_id": 141279, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": -1, "selected": false, "text": "public void func(){\n\n {\n ArrayList l = new ArrayList();\n }\n System.out.println(\"Hello\");\n\n}\n" }, { "answer_id": 141506, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "public class X : System.IDisposable {\n\n public void Dispose() {\n System.Console.WriteLine(\"dispose\");\n }\n\n private static void Demo() {\n X x = new X();\n using(x) {\n int i = 1;\n i = i/0;\n }\n }\n\n public static void Main(System.String[] args) {\n try {\n Demo();\n } catch (System.DivideByZeroException) {}\n }\n\n}\n public class X {\n\n public void dispose() {\n System.out.println(\"dispose\");\n }\n\n private static void demo() {\n X x = new X();\n try {\n int i = 1 / 0;\n } finally {\n x.dispose();\n } \n }\n\n public static void main(String[] args) {\n try {\n demo();\n } catch(ArithmeticException e) {}\n }\n\n}\n public class X : System.IDisposable {\n\n public void Dispose() {\n System.Console.WriteLine(\"dispose\");\n }\n\n private static void Demo() {\n using(X x = new X()) {\n int i = 1;\n i = i/0;\n }\n }\n\n public static void Main(System.String[] args) {\n try {\n Demo();\n } catch (System.DivideByZeroException) {}\n }\n\n}\n public class X {\n\n public void dispose() {\n System.out.println(\"dispose\");\n }\n\n private static void demo() {\n {\n X x = new X();\n try {\n int i = 1 / 0;\n } finally {\n x.dispose();\n }\n }\n }\n\n public static void main(String[] args) {\n try {\n demo();\n } catch(ArithmeticException e) {}\n }\n\n}\n" }, { "answer_id": 143690, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "using (InputStream in as FileInputStream(\"myfile\")) {\n ... use in ...\n}\n final InputStream in = FileInputStream(\"myfile\");\ntry {\n ... use in ...\n} finally {\n in.close();\n}\n acquire;\ntry {\n use;\n} finally {\n release;\n}\n fileInput(\"myfile\", new FileInput<Void>() {\n public Void read(InputStream in) throws IOException {\n ... use in ...\n return null;\n }\n});\n public static <T> T fileInput(FileInput<T> handler) throws IOException {\n final InputStream in = FileInputStream(\"myfile\");\n try {\n handler.read(in);\n } finally {\n in.close();\n }\n}\n" }, { "answer_id": 178359, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 0, "selected": false, "text": "withLock(lock) { //closure }\n" }, { "answer_id": 500004, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "InputStream is1 = null;\nInputStream is2 = null;\ntry{\n is1 = new FileInputStream(\"/tmp/bar\");\n is2 = new FileInputStream(\"/tmp/foo\");\n\n /* do stuff with is1 and is 2 */\n\n} finally {\n if (is1 != null) {\n is1.close();\n }\n if (is2 != null) {\n is2.close();\n }\n}\n" }, { "answer_id": 18931324, "author": "Lodewijk Bogaards", "author_id": 1860591, "author_profile": "https://Stackoverflow.com/users/1860591", "pm_score": 3, "selected": false, "text": "InputStream is1 = new FileInputStream(\"/tmp/foo\");\ntry{\n\n InputStream is2 = new FileInputStream(\"/tmp/bar\");\n try{\n /* do stuff with is1 and is2 */\n\n } finally {\n is2.close();\n }\n} finally {\n is1.close();\n}\n try(InputStream is1 = new FileInputStream(\"/tmp/foo\");\n InputStream is2 = new FileInputStream(\"/tmp/bar\")) {\n /* do stuff with is1 and is2 */\n}\n java.lang.AutoCloseable" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
141,247
<p>How have you tweaked the MATLAB environment to better suit your needs? One tweak per answer.</p>
[ { "answer_id": 218481, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 3, "selected": false, "text": "-nodesktop -nojvm" }, { "answer_id": 1329626, "author": "Andrew Janke", "author_id": 105904, "author_profile": "https://Stackoverflow.com/users/105904", "pm_score": 3, "selected": false, "text": "function idetitle(Title)\n%IDETITLE Set Window title of the Matlab IDE\n%\n% Examples:\n% idetitle('Matlab - Foo model')\n% idetitle(sprintf('Matlab - some big model - #%d', feature('getpid')))\n\nwin = appwin();\nif ~isempty(win)\n win.setTitle(Title);\nend\n\nfunction out = appwin()\n%APPWIN Get main application window\n\nwins = java.awt.Window.getOwnerlessWindows();\nfor i = 1:numel(wins)\n if isa(wins(i), 'com.mathworks.mde.desk.MLMainFrame')\n out = wins(i);\n return\n end\nend\n\nout = [];\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6688/" ]
141,251
<p>This is really annoying, we've switched our client downloads page to a different site and want to send a link out with our installer. When the link is created and overwrites the existing file, the metadata in windows XP still points to the same place even though the contents of the .url shows the correct address. I can change that URL property to google.com and it points to the same place when I copy over the file. </p> <pre> [InternetShortcut] URL=https://www.xxxx.com/?goto=clientlogon.php IDList= HotKey=0 </pre> <p>It works if we rename our link .url file. But we expect that the directory will be reused and that would result in one bad link and one good link which is more confusing than it is cool. </p>
[ { "answer_id": 144213, "author": "DougN", "author_id": 7442, "author_profile": "https://Stackoverflow.com/users/7442", "pm_score": 1, "selected": false, "text": "[DEFAULT]\nBASEURL=http://www.xxxx.com/Help\n[InternetShortcut]\nURL=http://www.xxxx.com/Help\nModified=60D0EDADF1CAC5014B\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
141,262
<p>I downloaded Hex Workshop, and I was told to read a .dbc file.</p> <blockquote> <p>It should contain 28,315 if you read offset 0x04 and 0x05</p> </blockquote> <p>I am unsure how to do this? What does 0x04 mean?</p>
[ { "answer_id": 141275, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "calc.exe" }, { "answer_id": 141287, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "int value = (ByteArray[4] >> 8) | ByteArray[5]);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20256/" ]
141,280
<p>What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that. </p> <p>Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.</p>
[ { "answer_id": 141323, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "wordArray var keywordRegistry = {};\n\nfor(var i = 0; i < wordArray.length; i++) {\n if(keywordRegistry.hasOwnProperty(wordArray[i]) == false) {\n keywordRegistry[wordArray[i]] = 0;\n }\n keywordRegistry[wordArray[i]] = keywordRegistry[wordArray[i]] + 1;\n}\n\n// now keywordRegistry will have, as properties, all of the \n// words in your word array with their respective counts \n\n// this will alert (choose something better than alert) all words and their counts\nfor(var keyword in keywordRegistry) {\n alert(\"The keyword '\" + keyword + \"' occurred \" + keywordRegistry[keyword] + \" times\");\n}\n" }, { "answer_id": 141369, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "var text = \"Text to be examined to determine which n words are used the most\";\n\n// Find 'em!\nvar wordRegExp = /\\w+(?:'\\w{1,2})?/g;\nvar words = {};\nvar matches;\nwhile ((matches = wordRegExp.exec(text)) != null)\n{\n var word = matches[0].toLowerCase();\n if (typeof words[word] == \"undefined\")\n {\n words[word] = 1;\n }\n else\n {\n words[word]++;\n }\n}\n\n// Sort 'em!\nvar wordList = [];\nfor (var word in words)\n{\n if (words.hasOwnProperty(word))\n {\n wordList.push([word, words[word]]);\n }\n}\nwordList.sort(function(a, b) { return b[1] - a[1]; });\n\n// Come back any time, straaanger!\nvar n = 10;\nvar message = [\"The top \" + n + \" words are:\"];\nfor (var i = 0; i < n; i++)\n{\n message.push(wordList[i][0] + \" - \" + wordList[i][1] + \" occurance\" +\n (wordList[i][1] == 1 ? \"\" : \"s\"));\n}\nalert(message.join(\"\\n\"));\n function getTopNWords(text, n)\n{\n var wordRegExp = /\\w+(?:'\\w{1,2})?/g;\n var words = {};\n var matches;\n while ((matches = wordRegExp.exec(text)) != null)\n {\n var word = matches[0].toLowerCase();\n if (typeof words[word] == \"undefined\")\n {\n words[word] = 1;\n }\n else\n {\n words[word]++;\n }\n }\n\n var wordList = [];\n for (var word in words)\n {\n if (words.hasOwnProperty(word))\n {\n wordList.push([word, words[word]]);\n }\n }\n wordList.sort(function(a, b) { return b[1] - a[1]; });\n\n var topWords = [];\n for (var i = 0; i < n; i++)\n {\n topWords.push(wordList[i][0]);\n }\n return topWords;\n}\n" }, { "answer_id": 141396, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": -1, "selected": false, "text": "var a = new Array;\na[word] = a[word]?a[word]+1:1;\n" }, { "answer_id": 141928, "author": "awatts", "author_id": 22847, "author_profile": "https://Stackoverflow.com/users/22847", "pm_score": 1, "selected": false, "text": "function top_words(text, n) {\n // Split text on non word characters\n var words = text.toLowerCase().split(/\\W+/)\n var positions = new Array()\n var word_counts = new Array()\n for (var i=0; i<words.length; i++) {\n var word = words[i]\n if (!word) {\n continue\n }\n\n if (typeof positions[word] == 'undefined') {\n positions[word] = word_counts.length\n word_counts.push([word, 1])\n } else {\n word_counts[positions[word]][1]++\n }\n }\n // Put most frequent words at the beginning.\n word_counts.sort(function (a, b) {return b[1] - a[1]})\n // Return the first n items\n return word_counts.slice(0, n)\n}\n\n// Let's see if it works.\nvar text = \"Words in here are repeated. Are repeated, repeated!\"\nalert(top_words(text, 3))\n [['repeated',3], ['are',2], ['words', 1]]" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
141,284
<p>What is the difference between using the <code>Runnable</code> and <code>Callable</code> interfaces when designing a concurrent thread in Java, why would you choose one over the other?</p>
[ { "answer_id": 2149017, "author": "amoran", "author_id": 256478, "author_profile": "https://Stackoverflow.com/users/256478", "pm_score": 5, "selected": false, "text": "Callable<V> V Runnable Callable<V> Runnable Runnable Runnable Callable Runnable" }, { "answer_id": 3952292, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 8, "selected": false, "text": "Runnable Callable Callable Callable Callable Runnable Runnable Callable Runnable Callable Runnable Runnable.run() Runnable Callable<Void> null call()" }, { "answer_id": 16650744, "author": "nikli", "author_id": 1012497, "author_profile": "https://Stackoverflow.com/users/1012497", "pm_score": 7, "selected": false, "text": "Callable call() Runnable run() Callable Runnable Callable Runnable Callable ExecutorService#invokeXXX(Collection<? extends Callable<T>> tasks) Runnable public interface Runnable {\n void run();\n}\n\npublic interface Callable<V> {\n V call() throws Exception;\n}\n" }, { "answer_id": 27665269, "author": "Aniket Thakur", "author_id": 2396539, "author_profile": "https://Stackoverflow.com/users/2396539", "pm_score": 4, "selected": false, "text": "Callable call() public interface Callable<V> {\n /**\n * Computes a result, or throws an exception if unable to do so.\n *\n * @return computed result\n * @throws Exception if unable to compute a result\n */\n V call() throws Exception;\n}\n Runnable run() public interface Runnable {\n /**\n * When an object implementing interface <code>Runnable</code> is used \n * to create a thread, starting the thread causes the object's \n * <code>run</code> method to be called in that separately executing \n * thread. \n * <p>\n * The general contract of the method <code>run</code> is that it may \n * take any action whatsoever.\n *\n * @see java.lang.Thread#run()\n */\n public abstract void run();\n}\n Runnable Callable Runnable Callable Runnable Callable <T> Future<T> submit(Callable<T> task);\nFuture<?> submit(Runnable task);\n<T> Future<T> submit(Runnable task, T result);\n" }, { "answer_id": 35407598, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 4, "selected": false, "text": "Thread run Callable Runnable Runnable Runnable Callable ExecutorService public class HelloRunnable implements Runnable {\n\n public void run() {\n System.out.println(\"Hello from a thread!\");\n } \n\n public static void main(String args[]) {\n (new Thread(new HelloRunnable())).start();\n }\n\n}\n Runnable Callable Callable Runnable invokeAny invokeAll run() Runnable call() Callable" }, { "answer_id": 46636794, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 3, "selected": false, "text": "+----------------------------------------+--------------------------------------------------------------------------------------------------+\n| Runnable | Callable<T> |\n+----------------------------------------+--------------------------------------------------------------------------------------------------+\n| Introduced in Java 1.0 of java.lang | Introduced in Java 1.5 of java.util.concurrent library |\n| Runnable cannot be parametrized | Callable is a parametrized type whose type parameter indicates the return type of its run method |\n| Runnable has run() method | Callable has call() method |\n| Runnable.run() returns void | Callable.call() returns a generic value V |\n| No way to propagate checked exceptions | Callable's call()“throws Exception” clause so we can easily propagate checked exceptions further | |\n+----------------------------------------+--------------------------------------------------------------------------------------------------+\n Runnable Runnable Callable Runnable" }, { "answer_id": 52944182, "author": "Sudhakar Pandey", "author_id": 5221821, "author_profile": "https://Stackoverflow.com/users/5221821", "pm_score": 3, "selected": false, "text": "public void run(){}\n public Object call(){}\n public Object call() throws Exception {}\n" }, { "answer_id": 56424946, "author": "Yash", "author_id": 5081877, "author_profile": "https://Stackoverflow.com/users/5081877", "pm_score": 3, "selected": false, "text": "Executor Runnable static HashMap<String, List> multiTasksData = new HashMap();\npublic static void main(String[] args) {\n Thread t1 = new Thread( new RunnableImpl(1), \"T1\" );\n Thread t2 = new Thread( new RunnableImpl(2), \"T2\" );\n Thread t3 = new Thread( new RunnableImpl(3), \"T3\" );\n\n multiTasksData.put(\"T1\", new ArrayList() ); // later get the value and update it.\n multiTasksData.put(\"T2\", new ArrayList() );\n multiTasksData.put(\"T3\", new ArrayList() );\n}\n Callable<V> public interface Runnable {\npublic void run();\n}\n\npublic interface Callable<Object> {\n public Object call() throws Exception;\n}\n execute(Runnable task):void submit(Callable<?>):Future<?> submit(Runnable):Future<?> class CallableTask implements Callable<Integer> {\n private int num = 0;\n public CallableTask(int num) {\n this.num = num;\n }\n @Override\n public Integer call() throws Exception {\n String threadName = Thread.currentThread().getName();\n System.out.println(threadName + \" : Started Task...\");\n\n for (int i = 0; i < 5; i++) {\n System.out.println(i + \" : \" + threadName + \" : \" + num);\n num = num + i;\n MainThread_Wait_TillWorkerThreadsComplete.sleep(1);\n }\n System.out.println(threadName + \" : Completed Task. Final Value : \"+ num);\n\n return num;\n }\n}\nclass RunnableTask implements Runnable {\n private int num = 0;\n public RunnableTask(int num) {\n this.num = num;\n }\n @Override\n public void run() {\n String threadName = Thread.currentThread().getName();\n System.out.println(threadName + \" : Started Task...\");\n\n for (int i = 0; i < 5; i++) {\n System.out.println(i + \" : \" + threadName + \" : \" + num);\n num = num + i;\n MainThread_Wait_TillWorkerThreadsComplete.sleep(1);\n }\n System.out.println(threadName + \" : Completed Task. Final Value : \"+ num);\n }\n}\npublic class MainThread_Wait_TillWorkerThreadsComplete {\n public static void main(String[] args) throws InterruptedException, ExecutionException {\n System.out.println(\"Main Thread start...\");\n Instant start = java.time.Instant.now();\n\n runnableThreads();\n callableThreads();\n\n Instant end = java.time.Instant.now();\n Duration between = java.time.Duration.between(start, end);\n System.out.format(\"Time taken : %02d:%02d.%04d \\n\", between.toMinutes(), between.getSeconds(), between.toMillis()); \n\n System.out.println(\"Main Thread completed...\");\n }\n public static void runnableThreads() throws InterruptedException, ExecutionException {\n ExecutorService executor = Executors.newFixedThreadPool(4);\n Future<?> f1 = executor.submit( new RunnableTask(5) );\n Future<?> f2 = executor.submit( new RunnableTask(2) );\n Future<?> f3 = executor.submit( new RunnableTask(1) );\n\n // Waits until pool-thread complete, return null upon successful completion.\n System.out.println(\"F1 : \"+ f1.get());\n System.out.println(\"F2 : \"+ f2.get());\n System.out.println(\"F3 : \"+ f3.get());\n\n executor.shutdown();\n }\n public static void callableThreads() throws InterruptedException, ExecutionException {\n ExecutorService executor = Executors.newFixedThreadPool(4);\n Future<Integer> f1 = executor.submit( new CallableTask(5) );\n Future<Integer> f2 = executor.submit( new CallableTask(2) );\n Future<Integer> f3 = executor.submit( new CallableTask(1) );\n\n // Waits until pool-thread complete, returns the result.\n System.out.println(\"F1 : \"+ f1.get());\n System.out.println(\"F2 : \"+ f2.get());\n System.out.println(\"F3 : \"+ f3.get());\n\n executor.shutdown();\n }\n}\n" }, { "answer_id": 61232621, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 2, "selected": false, "text": "//Runnable\ninterface Runnable {\n void run();\n}\n\n//Action - throws exception\ninterface Action {\n void run() throws Exception;\n}\n\n//Consumer - consumes a value/values, throws exception\n//BiConsumer, \ninterface Consumer1<T> {\n void accept(T t) throws Exception;\n}\n\n//Callable - return result, throws exception\ninterface Callable<R> {\n R call() throws Exception;\n}\n\n//Supplier - returns result, throws exception\ninterface Supplier<R> {\n R get() throws Exception;\n}\n\n//Predicate - consumes a value/values, returns true or false, throws exception\ninterface Predicate1<T> {\n boolean test(T t) throws Exception;\n}\n\n//Function - consumes a value/values, returns result, throws exception\n//BiFunction, Function3...\npublic interface Function1<T, R> {\n R apply(T t) throws Exception;\n}\n\n...\n\n//Executor\npublic interface Executor {\n void execute(Runnable command);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22061/" ]
141,288
<p>Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect.</p> <p>If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK?</p>
[ { "answer_id": 141522, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" creationComplete=\"onCreationComplete()\">\n <mx:Script source=\"Script.as\" />\n</mx:Application>\n import mx.controls.Button;\nimport flash.events.MouseEvent;\nimport mx.controls.Alert;\nimport mx.core.Application;\n\nprivate function onCreationComplete() : void {\n var button : Button = new Button();\n button.label = \"Click me\";\n button.addEventListener(MouseEvent.CLICK, function(e : MouseEvent) : void {\n Alert.show(\"Clicked\");\n });\n\n Application.application.addChild(button);\n}\n" }, { "answer_id": 141827, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "mx.core.Application <mx:Application> package {\n\n import mx.core.Application;\n\n\n public class MyFancyApplication extends Application {\n\n // do whatever you want here\n\n }\n\n}\n mxmlc mxmlc mx.core.Application" }, { "answer_id": 219571, "author": "jgormley", "author_id": 29738, "author_profile": "https://Stackoverflow.com/users/29738", "pm_score": 5, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<custom:ApplicationClass xmlns:custom=\"components.*\"/>\n package components {\n import mx.core.Application;\n import mx.events.FlexEvent;\n import flash.events.MouseEvent;\n import mx.controls.Alert;\n import mx.controls.Button;\n\n public class ApplicationClass extends Application {\n public function ApplicationClass () {\n addEventListener (FlexEvent.CREATION_COMPLETE, handleComplete);\n }\n private function handleComplete( event : FlexEvent ) : void {\n var button : Button = new Button();\n button.label = \"My favorite button\";\n button.styleName=\"halo\"\n button.addEventListener(MouseEvent.CLICK, handleClick);\n addChild( button );\n }\n private function handleClick(e:MouseEvent):void {\n Alert.show(\"You clicked on the button!\", \"Clickity\");\n }\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<local:MyApplication xmlns:fx=\"http://ns.adobe.com/mxml/2009\" xmlns:local=\"components.*\" />\n package components {\n import flash.events.MouseEvent;\n import mx.controls.Alert;\n import mx.events.FlexEvent;\n import spark.components.Application;\n import spark.components.Button;\n\n public class MyApplication extends Application {\n public function MyApplication() {\n addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler);\n }\n private function creationHandler(e:FlexEvent):void {\n var button : Button = new Button();\n button.label = \"My favorite button\";\n button.styleName=\"halo\"\n button.addEventListener(MouseEvent.CLICK, handleClick);\n addElement( button );\n }\n private function handleClick(e:MouseEvent):void {\n Alert.show(\"You clicked it!\", \"Clickity!\");\n }\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
141,291
<p>I want to be able to list only the directories inside some folder. This means I don't want filenames listed, nor do I want additional sub-folders.</p> <p>Let's see if an example helps. In the current directory we have:</p> <pre><code>&gt;&gt;&gt; os.listdir(os.getcwd()) ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl', 'Tools', 'w9xpopen.exe'] </code></pre> <p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p> <pre><code>&gt;&gt;&gt; for root, dirnames, filenames in os.walk('.'): ... print dirnames ... break ... ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools'] </code></pre> <p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
[ { "answer_id": 141313, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 4, "selected": false, "text": "directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]\n" }, { "answer_id": 141317, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 1, "selected": false, "text": ">>>> [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]\n" }, { "answer_id": 141318, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 2, "selected": false, "text": "[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]\n" }, { "answer_id": 141327, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 8, "selected": true, "text": ">>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]\n['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']\n" }, { "answer_id": 141336, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 6, "selected": false, "text": "filter(os.path.isdir, os.listdir(os.getcwd()))\n" }, { "answer_id": 142368, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "os.listdir(os.getcwd()) os.listdir(os.path.curdir) def listdirs(folder):\n return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]\n def listdirs(folder):\n return [\n d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))\n if os.path.isdir(d)\n ]\n" }, { "answer_id": 142535, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 8, "selected": false, "text": "os.walk next next(os.walk('.'))[1]\n os.walk('.').next()[1]\n os.walk next [1] dirnames" }, { "answer_id": 4820270, "author": "antiplex", "author_id": 294930, "author_profile": "https://Stackoverflow.com/users/294930", "pm_score": 2, "selected": false, "text": "def listdirs(folder): \n return [\n d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))\n if os.path.isdir(d)\n]\n def listdirs(folder): \n return [\n d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]\n if os.path.isdir(d)\n ]\n" }, { "answer_id": 14378583, "author": "foz", "author_id": 1671320, "author_profile": "https://Stackoverflow.com/users/1671320", "pm_score": 3, "selected": false, "text": ">>>> import timeit\n>>>> timeit.timeit(\"os.walk('.').next()[1]\", \"import os\", number=10000)\n1.1215229034423828\n>>>> timeit.timeit(\"[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]\", \"import os\", number=10000)\n1.0592019557952881\n" }, { "answer_id": 15521489, "author": "Malius Arth", "author_id": 2190476, "author_profile": "https://Stackoverflow.com/users/2190476", "pm_score": 1, "selected": false, "text": "def listdirs(dir):\n return [os.path.join(os.path.join(dir, x)) for x in os.listdir(dir) \n if os.path.isdir(os.path.join(dir, x))]\n" }, { "answer_id": 26338900, "author": "manty", "author_id": 4085421, "author_profile": "https://Stackoverflow.com/users/4085421", "pm_score": 3, "selected": false, "text": " import os\n dir_list = os.walk('.').next()[1]\n print dir_list\n" }, { "answer_id": 38216530, "author": "Travis", "author_id": 267157, "author_profile": "https://Stackoverflow.com/users/267157", "pm_score": 4, "selected": false, "text": "import glob, os\nglob.glob('*' + os.path.sep)\n" }, { "answer_id": 45232249, "author": "Alexey Gavrilov", "author_id": 4323224, "author_profile": "https://Stackoverflow.com/users/4323224", "pm_score": 0, "selected": false, "text": "def listdirs(folder):\n if os.path.exists(folder):\n return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]\n else:\n return []\n" }, { "answer_id": 46283751, "author": "nvd", "author_id": 1943525, "author_profile": "https://Stackoverflow.com/users/1943525", "pm_score": 1, "selected": false, "text": "scanDir = \"abc\"\ndirectories = [d for d in os.listdir(scanDir) if os.path.isdir(os.path.join(os.path.abspath(scanDir), d))]\n" }, { "answer_id": 48998735, "author": "venkata maddineni", "author_id": 6318033, "author_profile": "https://Stackoverflow.com/users/6318033", "pm_score": -1, "selected": false, "text": "-- This will exclude files and traverse through 1 level of sub folders in the root\n\ndef list_files(dir):\n List = []\n filterstr = ' '\n for root, dirs, files in os.walk(dir, topdown = True):\n #r.append(root)\n if (root == dir):\n pass\n elif filterstr in root:\n #filterstr = ' '\n pass\n else:\n filterstr = root\n #print(root)\n for name in files:\n print(root)\n print(dirs)\n List.append(os.path.join(root,name))\n #print(os.path.join(root,name),\"\\n\")\n print(List,\"\\n\")\n\n return List\n" }, { "answer_id": 55605290, "author": "KBLee", "author_id": 9605162, "author_profile": "https://Stackoverflow.com/users/9605162", "pm_score": 4, "selected": false, "text": "[a for a in os.listdir() if os.path.isdir(a)]\n" }, { "answer_id": 63001540, "author": "joelostblom", "author_id": 2166823, "author_profile": "https://Stackoverflow.com/users/2166823", "pm_score": 2, "selected": false, "text": "pathlib from pathlib import Path\n\np = Path('./')\n[f for f in p.iterdir() if f.is_dir()]\n" }, { "answer_id": 63715910, "author": "pandichef", "author_id": 10134077, "author_profile": "https://Stackoverflow.com/users/10134077", "pm_score": 1, "selected": false, "text": "os.walk In [30]: %timeit [d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]\n1.23 ms ± 97.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nIn [31]: %timeit list(filter(os.path.isdir, os.listdir(os.getcwd())))\n1.13 ms ± 13.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nIn [32]: %timeit next(os.walk(os.getcwd()))[1]\n132 µs ± 9.34 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n" }, { "answer_id": 66170445, "author": "G M", "author_id": 2132157, "author_profile": "https://Stackoverflow.com/users/2132157", "pm_score": 2, "selected": false, "text": "os.scandir with os.scandir(os.getcwd()) as mydir:\n dirs = [i.name for i in mydir if i.is_dir()]\n i.path" }, { "answer_id": 69067814, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 2, "selected": false, "text": "glob import glob, os\n\np = \"/some/path/\"\nfor d in glob.glob(p + \"*\" + os.path.sep):\n print(d)\n" }, { "answer_id": 71596385, "author": "Darren Weber", "author_id": 1172685, "author_profile": "https://Stackoverflow.com/users/1172685", "pm_score": 1, "selected": false, "text": "$ mkdir tmpdir\n$ mkdir -p tmpdir/a/b/c\n$ mkdir -p tmpdir/x/y/z\n\n$ touch tmpdir/a/b/c/abc.txt\n$ touch tmpdir/a/b/ab.txt\n$ touch tmpdir/a/a.txt\n\n$ python --version\nPython 3.7.12\n >>> from pathlib import Path\n>>> tmpdir = Path(\"./tmpdir\")\n>>> [d for d in tmpdir.iterdir() if d.is_dir]\n[PosixPath('tmpdir/x'), PosixPath('tmpdir/a')]\n>>> sorted(d for d in tmpdir.iterdir() if d.is_dir)\n[PosixPath('tmpdir/a'), PosixPath('tmpdir/x')]\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
141,302
<p>Is there a way to check if a file has been opened by ReWrite in Delphi? </p> <p>Code would go something like this:</p> <pre><code>AssignFile(textfile, 'somefile.txt'); if not textFile.IsOpen then Rewrite(textFile); </code></pre>
[ { "answer_id": 141339, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 5, "selected": true, "text": "55216 = closed\n55217 = open read\n55218 = open write\n\nfmClosed = $D7B0;\nfmInput = $D7B1;\nfmOutput = $D7B2;\nfmInOut = $D7B3;\n" }, { "answer_id": 141376, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": false, "text": "function IsFileInUse(fName: string) : boolean;\nvar\n HFileRes: HFILE;\nbegin\n Result := False;\n if not FileExists(fName) then begin\n Exit;\n end;\n\n HFileRes := CreateFile(PChar(fName)\n ,GENERIC_READ or GENERIC_WRITE\n ,0\n ,nil\n ,OPEN_EXISTING\n ,FILE_ATTRIBUTE_NORMAL\n ,0);\n\n Result := (HFileRes = INVALID_HANDLE_VALUE);\n\n if not(Result) then begin\n CloseHandle(HFileRes);\n end;\nend;\n" }, { "answer_id": 7730228, "author": "Mike Baran", "author_id": 990053, "author_profile": "https://Stackoverflow.com/users/990053", "pm_score": 1, "selected": false, "text": "bFileIsOpen bFileIsOpen := true if (bFileIsOpen) then Close(datafile);" }, { "answer_id": 8166349, "author": "Ramon", "author_id": 1051656, "author_profile": "https://Stackoverflow.com/users/1051656", "pm_score": 3, "selected": false, "text": "function IsOpen(const txt:TextFile):Boolean;\nconst\n fmTextOpenRead = 55217;\n fmTextOpenWrite = 55218;\nbegin\n Result := (TTextRec(txt).Mode = fmTextOpenRead) or (TTextRec(txt).Mode = fmTextOpenWrite)\nend;\n" }, { "answer_id": 27875732, "author": "Whitehairedgeezer", "author_id": 3074340, "author_profile": "https://Stackoverflow.com/users/3074340", "pm_score": -1, "selected": false, "text": "filenotopen Result := (HFileRes = INVALID_HANDLE_VALUE);\n Result := NOT (HFileRes = INVALID_HANDLE_VALUE);\n if filenotopen(filename) then \n begin\n assignfile(f,filename);\n reset(f)\n etc;\n end\nelse\n message('file open by a different program')\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
141,315
<p>Is there a way to check to see if a date/time is valid you would think these would be easy to check:</p> <pre><code>$date = '0000-00-00'; $time = '00:00:00'; $dateTime = $date . ' ' . $time; if(strtotime($dateTime)) { // why is this valid? } </code></pre> <p>what really gets me is this:</p> <pre><code>echo date('Y-m-d', strtotime($date)); </code></pre> <p>results in: "1999-11-30",</p> <p>huh? i went from 0000-00-00 to 1999-11-30 ???</p> <p>I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?</p> <p>Edit: People are asking what i'm running: Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux</p>
[ { "answer_id": 141341, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "strtotime mktime(), localtime(), strtotime() /**\n * Converts strings of the format \"YYYY-MM-DD HH:MM:SS\" into php dates\n */\nfunction convert_date_string($date_string)\n{\n list($date, $time) = explode(\" \", $date_string);\n list($hours, $minutes, $seconds) = explode(\":\", $time);\n list($year, $month, $day) = explode(\"-\", $date);\n return mktime($hours, $minutes, $seconds, $month, $day, $year);\n}\n" }, { "answer_id": 141365, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 6, "selected": true, "text": "<?php\nfunction isValidDateTime($dateTime)\n{\n if (preg_match(\"/^(\\d{4})-(\\d{2})-(\\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/\", $dateTime, $matches)) {\n if (checkdate($matches[2], $matches[3], $matches[1])) {\n return true;\n }\n }\n\n return false;\n}\n?>\n" }, { "answer_id": 2069817, "author": "dave", "author_id": 251324, "author_profile": "https://Stackoverflow.com/users/251324", "pm_score": 1, "selected": false, "text": "function ConvertDateString ($DateString)\n{\n list($year, $month, $day) = explode(\"-\", $DateString);\n return date (\"Y-m-d, mktime (0, 0, 0, $month, $day, $year));\n}\n" }, { "answer_id": 4605939, "author": "asupynuk", "author_id": 564167, "author_profile": "https://Stackoverflow.com/users/564167", "pm_score": 1, "selected": false, "text": "function isValidDateTime($dateTime) {\n if (trim($dateTime) == '') {\n return true;\n }\n if (preg_match('/^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{2,4})(\\s+(([01]?[0-9])|(2[0-3]))(:[0-5][0-9]){0,2}(\\s+(am|pm))?)?$/i', $dateTime, $matches)) {\n list($all,$mm,$dd,$year) = $matches;\n if ($year <= 99) {\n $year += 2000;\n }\n return checkdate($mm, $dd, $year);\n }\n return false;\n}\n" }, { "answer_id": 7475555, "author": "martin", "author_id": 953300, "author_profile": "https://Stackoverflow.com/users/953300", "pm_score": -1, "selected": false, "text": "<?php\n\nfunction is_date( $str ) {\n $stamp = strtotime( $str );\n\n if (!is_numeric($stamp)) {\n return FALSE;\n }\n $month = date( 'm', $stamp );\n $day = date( 'd', $stamp );\n $year = date( 'Y', $stamp );\n\n if (checkdate($month, $day, $year)) {\n return TRUE;\n }\n return FALSE;\n}\n?>\n" }, { "answer_id": 8938609, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?php\necho is_date(\"13/04/10\");\n\nfunction is_date( $str ) {\n $flag = strpos($str, '/');\n\n if(intval($flag)<=0){\n $stamp = strtotime( $str );\n } else {\n list($d, $m, $y) = explode('/', $str); \n $stamp = strtotime(\"$d-$m-$y\");\n } \n //var_dump($stamp) ;\n\n if (!is_numeric($stamp)) {\n //echo \"ho\" ;\n return \"not a date\" ; \n }\n\n $month = date( 'n', $stamp ); // use n to get date in correct format\n $day = date( 'd', $stamp );\n $year = date( 'Y', $stamp );\n\n if (checkdate($month, $day, $year)) {\n $dt = \"$year-$month-$day\" ;\n return strftime(\"%d-%b-%Y\", strtotime($dt));\n //return TRUE;\n } else {\n return \"not a date\" ;\n }\n}\n?>\n" }, { "answer_id": 9742388, "author": "Josue", "author_id": 1133003, "author_profile": "https://Stackoverflow.com/users/1133003", "pm_score": 0, "selected": false, "text": "<?php\nfunction is_valid_date($user_date=false, $valid_date = \"1900-01-01\") {\n $user_date = date(\"Y-m-d H:i:s\",strtotime($user_date));\n return strtotime($user_date) >= strtotime($valid_date) ? true : false;\n}\n\necho is_valid_date(\"00-00-00\") ? 1 : 0; // return 0\n\necho is_valid_date(\"3/5/2011\") ? 1 : 0; // return 1\n" }, { "answer_id": 9933557, "author": "Izkata", "author_id": 500202, "author_profile": "https://Stackoverflow.com/users/500202", "pm_score": 3, "selected": false, "text": ">> date('Y-m-d', strtotime('2012-03-00'))\nstring: '2012-02-29'\n>> date('Y-m-d', strtotime('2012-02-00'))\nstring: '2012-01-31'\n>> date('Y-m-d', strtotime('2012-01-00'))\nstring: '2011-12-31'\n>> date('Y-m-d', strtotime('2012-00-00'))\nstring: '2011-11-30'\n" }, { "answer_id": 10313431, "author": "eli", "author_id": 281924, "author_profile": "https://Stackoverflow.com/users/281924", "pm_score": 0, "selected": false, "text": "function check_sql_date_format($date) {\n $date = substr($date, 0, 10);\n list($year, $month, $day) = explode('-', $date);\n if (!is_numeric($year) || !is_numeric($month) || !is_numeric($day)) {\n return false;\n }\n return checkdate($month, $day, $year);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
141,332
<p>I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this:</p> <pre><code>sub _read_from_client { my ($file_handle) = @_; while (my $line = &lt;$file_handle&gt;) { print STDOUT $line; } return; } </code></pre> <p>Importantly, the snippet needs to work in Win32 platform. There are many solutions for *nix platforms that I'm not interested in. I'm using ActivePerl 5.10.</p>
[ { "answer_id": 141770, "author": "xdg", "author_id": 11800, "author_profile": "https://Stackoverflow.com/users/11800", "pm_score": 4, "selected": true, "text": "ioctl($socket, 0x8004667e, 1);\n" }, { "answer_id": 143138, "author": "Corion", "author_id": 21731, "author_profile": "https://Stackoverflow.com/users/21731", "pm_score": 2, "selected": false, "text": "sysread Poe::Wheel::Run::Win32" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7045/" ]
141,337
<p>Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects.</p> <p>Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life &amp; scope myself and just store the pointers to those objects in my STL containers?</p> <p>I realize this is somewhat short on details, but I'm looking for the "theoretical" better answer if it exists, since I know both of these solutions are possible.</p> <p>Two very obvious disadvantage to playing with pointers: 1) I must manage allocation/deallocation of these objects myself in a scope beyond the STL. 2) I cannot create a temp object on the stack and add it to my containers.</p> <p>Is there anything else I'm missing?</p>
[ { "answer_id": 141366, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 4, "selected": false, "text": "boost::shared_ptr std::shared_ptr" }, { "answer_id": 141490, "author": "Nick Haddad", "author_id": 2813, "author_profile": "https://Stackoverflow.com/users/2813", "pm_score": 6, "selected": false, "text": "class BigExpensive { ... }\n\n// create a pointer vector\nptr_vector<BigExpensive> bigVector;\nbigVector.push_back( new BigExpensive( \"Lexus\", 57700 ) );\nbigVector.push_back( new BigExpensive( \"House\", 15000000 );\n\n// get a reference to the first element\nMyClass& expensiveItem = bigList[0];\nexpensiveItem.sell();\n" }, { "answer_id": 143082, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "std::vector<boost::shared_ptr<protocol> > protocols;\n...\nconnection c(protocols[0].get()); // pointer to protocol stays valid even if resized\n std::vector<protocol> protocols;\nconnection c(protocols[0]); // value-semantics, takes a copy of the protocol\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13022/" ]
141,344
<p>How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.</p> <p>Is there a better way of doing this? Something like <a href="https://ss64.com/nt/find.html" rel="nofollow noreferrer">FIND</a> or <a href="https://ss64.com/nt/findstr.html" rel="nofollow noreferrer">FINDSTR</a> operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.</p> <pre><code>FOR /F &quot;delims=;&quot; %%P IN (&quot;%PATH%&quot;) DO ( @ECHO %%~P ) </code></pre>
[ { "answer_id": 141385, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 5, "selected": false, "text": "echo ;%PATH%; | find /C /I \";<string>;\"\n" }, { "answer_id": 142381, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "for /f delims %%P for /f" }, { "answer_id": 142395, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 1, "selected": false, "text": "if a%X%==a%PATH% echo %X% is in PATH\necho %PATH% | find /c /i \";%X%\"\nif errorlevel 1 echo %X% is in PATH\necho %PATH% | find /c /i \"%X%;\"\nif errorlevel 1 echo %X% is in PATH\n" }, { "answer_id": 142605, "author": "indiv", "author_id": 19719, "author_profile": "https://Stackoverflow.com/users/19719", "pm_score": 2, "selected": false, "text": "@echo off\nSET MYPATHCOPY=%PATH%\n\n:search\nfor /f \"delims=; tokens=1,2*\" %%p in (\"%MYPATHCOPY%\") do (\n @echo %%~p\n SET MYPATHCOPY=%%~q;%%~r\n)\n\nif \"%MYPATHCOPY%\"==\";\" goto done;\ngoto search;\n\n:done\n Z:\\>path.bat\nC:\\Program Files\\Microsoft DirectX SDK (November 2007)\\Utilities\\Bin\\x86\nc:\\program files\\imagemagick-6.3.4-q16\nC:\\WINDOWS\\system32\nC:\\WINDOWS\nC:\\SFU\\common\\\nc:\\Program Files\\Debugging Tools for Windows\nC:\\Program Files\\Nmap\n" }, { "answer_id": 157744, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 3, "selected": false, "text": "for delims PATH @echo off \nsetlocal \nif \"%~1\"==\"\" (\n set PATHQ=%PATH%\n) else (\n set PATHQ=%~1 ) \n:WHILE\n if \"%PATHQ%\"==\"\" goto WEND\n for /F \"delims=;\" %%i in (\"%PATHQ%\") do echo %%i\n for /F \"delims=; tokens=1,*\" %%i in (\"%PATHQ%\") do set PATHQ=%%j\n goto WHILE \n:WEND\n findstr tidypath.cmd findstr > tidypath | findstr /i \"%ProgramFiles%\"\n" }, { "answer_id": 2559366, "author": "bert bruynooghe", "author_id": 306730, "author_profile": "https://Stackoverflow.com/users/306730", "pm_score": 5, "selected": false, "text": "mvn --help > NUL 2> NUL\nif errorlevel 1 goto mvnNotInPath\n" }, { "answer_id": 5296725, "author": "Noam Manos", "author_id": 658497, "author_profile": "https://Stackoverflow.com/users/658497", "pm_score": 1, "selected": false, "text": "set myPath=c:\\mypath\nFor /F \"Delims=\" %%I In ('echo %PATH% ^| find /C /I \"%myPath%\"') Do set pathExists=%%I 2>Nul\nIf %pathExists%==0 (set PATH=%myPath%;%PATH%)\n" }, { "answer_id": 5572997, "author": "mousio", "author_id": 653295, "author_profile": "https://Stackoverflow.com/users/653295", "pm_score": 2, "selected": false, "text": "for %P in (\"%path:;=\";\"%\") do @if /i %P==\"PATH_TO_CHECK\" echo %P exists in PATH\n @for %%P in (\"%path:;=\";\"%\") do @if /i %%P==\"%~1\" echo %%P exists in PATH\n checkpath \"%ProgramFiles%\"" }, { "answer_id": 5573965, "author": "Andriy M", "author_id": 297408, "author_profile": "https://Stackoverflow.com/users/297408", "pm_score": 1, "selected": false, "text": "PATH PATH @ECHO OFF\nSET \"mypath=D:\\the\\searched-for\\path\"\nSET unusualname=nowthisissupposedtobesomeveryunusualfilename\nECHO.>\"%mypath%\\%unusualname%\"\nFOR %%f IN (%unusualname%) DO SET \"foundpath=%%~dp$PATH:f\"\nERASE \"%mypath%\\%unusualname%\"\nIF \"%mypath%\" == \"%foundpath%\" (\n ECHO The dir exists in PATH\n) ELSE (\n ECHO The dir DOES NOT exist in PATH\n)\n" }, { "answer_id": 6802486, "author": "Kevin Edwards", "author_id": 244173, "author_profile": "https://Stackoverflow.com/users/244173", "pm_score": 2, "selected": false, "text": "set PATH_NQ=%PATH:\"=%\nif not \"%PATH_NQ%\"==\"%PATH_NQ:c:\\mydir=%\" goto already_in_path\nset PATH=%PATH%;c:\\mydir\n:already_in_path\n" }, { "answer_id": 7685205, "author": "Chris Degnen", "author_id": 879601, "author_profile": "https://Stackoverflow.com/users/879601", "pm_score": 1, "selected": false, "text": "@echo off\necho %PATH% | find /c /i \"vim71\" > nul\nif not errorlevel 1 goto jump\nPATH = C:\\Program Files\\Vim\\vim71\\;%PATH%\n:jump\n @echo on\necho %PATH% | find /c /i \"Windows\"\nif \"%errorlevel%\"==\"0\" echo Found Windows\necho %PATH% | find /c /i \"Nonesuch\"\nif \"%errorlevel%\"==\"0\" echo Found Nonesuch\n not errorlevel 1 @echo off\nsetlocal\nPATH = C:\\Program Files\\Vim\\vim71\\;%PATH%\nrem your code here\nendlocal\n" }, { "answer_id": 7731616, "author": "Redsplinter", "author_id": 990204, "author_profile": "https://Stackoverflow.com/users/990204", "pm_score": 2, "selected": false, "text": "set myPath=<pathToEnsure | %1>\necho ;%PATH%; | find /C /I \";%myPath%;\" >nul\nif %ERRORLEVEL% NEQ 0 set PATH=%PATH%;%myPath%\n" }, { "answer_id": 8046515, "author": "dbenham", "author_id": 1012053, "author_profile": "https://Stackoverflow.com/users/1012053", "pm_score": 7, "selected": false, "text": "\\ \\ \\ C: C:\\ / \\ / \\ \\ \\ C: C:\\ C:\\ C:\\\\ \"C:\\test. \" \"C:\\test\" .\\ ..\\ C:\\.\\parent\\child\\..\\.\\child\\ C:\\parent\\child <space> , ; ^ & = ; D: \\myPath myPath .\\ ~s ~s ~s \\ ~s <letter>:<separator> <letter>:<separator><separator> \\ / \\\\ ~s C:\\THIS & THAT;\"C:\\& THE OTHER THING\" \"%PATH%\" %PATH% ; ; ~s @echo off\n:inPath pathVar\n::\n:: Tests if the path stored within variable pathVar exists within PATH.\n::\n:: The result is returned as the ERRORLEVEL:\n:: 0 if the pathVar path is found in PATH.\n:: 1 if the pathVar path is not found in PATH.\n:: 2 if pathVar is missing or undefined or if PATH is undefined.\n::\n:: If the pathVar path is fully qualified, then it is logically compared\n:: to each fully qualified path within PATH. The path strings don't have\n:: to match exactly, they just need to be logically equivalent.\n::\n:: If the pathVar path is relative, then it is strictly compared to each\n:: relative path within PATH. Case differences and double quotes are\n:: ignored, but otherwise the path strings must match exactly.\n::\n::------------------------------------------------------------------------\n::\n:: Error checking\nif \"%~1\"==\"\" exit /b 2\nif not defined %~1 exit /b 2\nif not defined path exit /b 2\n::\n:: Prepare to safely parse PATH into individual paths\nsetlocal DisableDelayedExpansion\nset \"var=%path:\"=\"\"%\"\nset \"var=%var:^=^^%\"\nset \"var=%var:&=^&%\"\nset \"var=%var:|=^|%\"\nset \"var=%var:<=^<%\"\nset \"var=%var:>=^>%\"\nset \"var=%var:;=^;^;%\"\nset var=%var:\"\"=\"%\nset \"var=%var:\"=\"\"Q%\"\nset \"var=%var:;;=\"S\"S%\"\nset \"var=%var:^;^;=;%\"\nset \"var=%var:\"\"=\"%\"\nsetlocal EnableDelayedExpansion\nset \"var=!var:\"Q=!\"\nset \"var=!var:\"S\"S=\";\"!\"\n::\n:: Remove quotes from pathVar and abort if it becomes empty\nset \"new=!%~1:\"=!\"\nif not defined new exit /b 2\n::\n:: Determine if pathVar is fully qualified\necho(\"!new!\"|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" >nul ^\n && set \"abs=1\" || set \"abs=0\"\n::\n:: For each path in PATH, check if path is fully qualified and then do\n:: proper comparison with pathVar.\n:: Exit with ERRORLEVEL 0 if a match is found.\n:: Delayed expansion must be disabled when expanding FOR variables\n:: just in case the value contains !\nfor %%A in (\"!new!\\\") do for %%B in (\"!var!\") do (\n if \"!!\"==\"\" endlocal\n for %%C in (\"%%~B\\\") do (\n echo(%%B|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" >nul ^\n && (if %abs%==1 if /i \"%%~sA\"==\"%%~sC\" exit /b 0) ^\n || (if %abs%==0 if /i \"%%~A\"==\"%%~C\" exit /b 0)\n )\n)\n:: No match was found so exit with ERRORLEVEL 1\nexit /b 1\n set test=c:\\mypath\ncall inPath test && (echo found) || (echo not found)\n path %path%;%newPath% ! @echo off\n:addPath pathVar /B\n::\n:: Safely appends the path contained within variable pathVar to the end\n:: of PATH if and only if the path does not already exist within PATH.\n::\n:: If the case insensitive /B option is specified, then the path is\n:: inserted into the front (Beginning) of PATH instead.\n::\n:: If the pathVar path is fully qualified, then it is logically compared\n:: to each fully qualified path within PATH. The path strings are\n:: considered a match if they are logically equivalent.\n::\n:: If the pathVar path is relative, then it is strictly compared to each\n:: relative path within PATH. Case differences and double quotes are\n:: ignored, but otherwise the path strings must match exactly.\n::\n:: Before appending the pathVar path, all double quotes are stripped, and\n:: then the path is enclosed in double quotes if and only if the path\n:: contains at least one semicolon.\n::\n:: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined\n:: or if PATH is undefined.\n::\n::------------------------------------------------------------------------\n::\n:: Error checking\nif \"%~1\"==\"\" exit /b 2\nif not defined %~1 exit /b 2\nif not defined path exit /b 2\n::\n:: Determine if function was called while delayed expansion was enabled\nsetlocal\nset \"NotDelayed=!\"\n::\n:: Prepare to safely parse PATH into individual paths\nsetlocal DisableDelayedExpansion\nset \"var=%path:\"=\"\"%\"\nset \"var=%var:^=^^%\"\nset \"var=%var:&=^&%\"\nset \"var=%var:|=^|%\"\nset \"var=%var:<=^<%\"\nset \"var=%var:>=^>%\"\nset \"var=%var:;=^;^;%\"\nset var=%var:\"\"=\"%\nset \"var=%var:\"=\"\"Q%\"\nset \"var=%var:;;=\"S\"S%\"\nset \"var=%var:^;^;=;%\"\nset \"var=%var:\"\"=\"%\"\nsetlocal EnableDelayedExpansion\nset \"var=!var:\"Q=!\"\nset \"var=!var:\"S\"S=\";\"!\"\n::\n:: Remove quotes from pathVar and abort if it becomes empty\nset \"new=!%~1:\"^=!\"\nif not defined new exit /b 2\n::\n:: Determine if pathVar is fully qualified\necho(\"!new!\"|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" >nul ^\n && set \"abs=1\" || set \"abs=0\"\n::\n:: For each path in PATH, check if path is fully qualified and then\n:: do proper comparison with pathVar. Exit if a match is found.\n:: Delayed expansion must be disabled when expanding FOR variables\n:: just in case the value contains !\nfor %%A in (\"!new!\\\") do for %%B in (\"!var!\") do (\n if \"!!\"==\"\" setlocal disableDelayedExpansion\n for %%C in (\"%%~B\\\") do (\n echo(%%B|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" >nul ^\n && (if %abs%==1 if /i \"%%~sA\"==\"%%~sC\" exit /b 0) ^\n || (if %abs%==0 if /i %%A==%%C exit /b 0)\n )\n)\n::\n:: Build the modified PATH, enclosing the added path in quotes\n:: only if it contains ;\nsetlocal enableDelayedExpansion\nif \"!new:;=!\" neq \"!new!\" set new=\"!new!\"\nif /i \"%~2\"==\"/B\" (set \"rtn=!new!;!path!\") else set \"rtn=!path!;!new!\"\n::\n:: rtn now contains the modified PATH. We need to safely pass the\n:: value accross the ENDLOCAL barrier\n::\n:: Make rtn safe for assignment using normal expansion by replacing\n:: % and \" with not yet defined FOR variables\nset \"rtn=!rtn:%%=%%A!\"\nset \"rtn=!rtn:\"=%%B!\"\n::\n:: Escape ^ and ! if function was called while delayed expansion was enabled.\n:: The trailing ! in the second assignment is critical and must not be removed.\nif not defined NotDelayed set \"rtn=!rtn:^=^^^^!\"\nif not defined NotDelayed set \"rtn=%rtn:!=^^^!%\" !\n::\n:: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to\n:: restore the % and \" characters. Again the trailing ! is critical.\nfor /f \"usebackq tokens=1,2\" %%A in ('%%^ ^\"') do (\n endlocal & endlocal & endlocal & endlocal & endlocal\n set \"path=%rtn%\" !\n)\nexit /b 0\n" }, { "answer_id": 11018458, "author": "user1454091", "author_id": 1454091, "author_profile": "https://Stackoverflow.com/users/1454091", "pm_score": 1, "selected": false, "text": "@echo off\nwhere /q <put filename here>\nif %errorlevel% == 1 (\n setx PATH \"%PATH%;<additional path stuff>\"\n) else (\n echo \"already set path\"\n)\n" }, { "answer_id": 12884517, "author": "carlsomo", "author_id": 1745223, "author_profile": "https://Stackoverflow.com/users/1745223", "pm_score": 0, "selected": false, "text": "d:\\path\\file @echo off&goto :PathCheck\n:PathCheck.CMD\necho.PathCheck.CMD: Checks for existence of a path or file in %%PATH%% variable\necho.Usage: PathCheck.CMD [Checkpath] or [Checkfile] [PathVar]\necho.Checkpath must have a trailing \\ but checkfile must not\necho.If Checkpath contains spaces use quotes ie. \"C:\\Check path\\\"\necho.Checkfile must not include a path, just the filename.ext\necho.If Checkfile contains spaces use quotes ie. \"Check File.ext\"\necho.Returns 0 if found, 1 if not or -1 if checkpath does not exist at all\necho.If PathVar is not in command line it will be echoed with surrounding quotes\necho.If PathVar is passed it will be set to d:\\path\\checkfile with no trailing \\\necho.Then %%PathVar%% will be set to the fully qualified path to Checkfile\necho.Note: %%PathVar%% variable set will not be surrounded with quotes\necho.To view the path listing line by line use: PathCheck.CMD /L\nexit/b 1\n\n:PathCheck\nif \"%~1\"==\"\" goto :PathCheck.CMD\nsetlocal EnableDelayedExpansion\nset \"PathVar=%~2\"\nset \"pth=\"\nset \"pcheck=%~1\"\nif \"%pcheck:~-1%\" equ \"\\\" (\n if not exist %pcheck% endlocal&exit/b -1\n set/a pth=1\n)\nfor %%G in (\"%path:;=\" \"%\") do (\n set \"Pathfd=%%~G\\\"\n set \"Pathfd=!Pathfd:\\\\=\\!\"\n if /i \"%pcheck%\" equ \"/L\" echo.!Pathfd!\n if defined pth (\n if /i \"%pcheck%\" equ \"!Pathfd!\" endlocal&exit/b 0\n ) else (\n if exist \"!Pathfd!%pcheck%\" goto :CheckfileFound\n )\n)\nendlocal&exit/b 1\n\n:CheckfileFound\nendlocal&(\n if not \"%PathVar%\"==\"\" (\n call set \"%~2=%Pathfd%%pcheck%\"\n ) else (echo.\"%Pathfd%%pcheck%\")\n exit/b 0\n)\n" }, { "answer_id": 19643064, "author": "Aacini", "author_id": 778560, "author_profile": "https://Stackoverflow.com/users/778560", "pm_score": 4, "selected": false, "text": "%PATH% for %%p in (programname.exe) do set \"progpath=%%~$PATH:p\"\nif not defined progpath (\n rem The path to programname.exe don't exist in PATH variable, insert it:\n set \"PATH=%PATH%;C:\\path\\to\\progranname\"\n)\n set \"progpath=\"\nfor %%e in (%PATHEXT%) do (\n if not defined progpath (\n for %%p in (programname.%%e) do set \"progpath=%%~$PATH:p\"\n )\n)\n" }, { "answer_id": 23353210, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "IF \"%PATH:new_path=%\" == \"%PATH%\" PATH=%PATH%;new_path\n IF \"%PATH:C:\\Scripts=%\" == \"%PATH%\" PATH=%PATH%;C:\\Scripts\n new_path PATH new_path new_path PATH new_path new_path" }, { "answer_id": 30711326, "author": "Heyvoon", "author_id": 1824347, "author_profile": "https://Stackoverflow.com/users/1824347", "pm_score": 1, "selected": false, "text": "Test-Path $ENV:SystemRoot\\YourDirectory\nTest-Path C:\\Windows\\YourDirectory\n TRUE FALSE" }, { "answer_id": 43815216, "author": "Albert", "author_id": 2211788, "author_profile": "https://Stackoverflow.com/users/2211788", "pm_score": 2, "selected": false, "text": "$env:Path -split \";\" | % {\"$(test-path $_); $_\"}\n True;C:\\WINDOWS\nTrue;C:\\WINDOWS\\system32\nTrue;C:\\WINDOWS\\System32\\Wbem\nFalse;C:windows\\System32\\windowsPowerShell\\v1.0\\\nFalse;C:\\Program Files (x86)\\Java\\jre7\\bin\n $x = $null; foreach ($t in ($env:Path -split \";\") ) {if (test-path $t) {$x += $t + \";\"}}; $x\n" }, { "answer_id": 56883320, "author": "Günter Zöchbauer", "author_id": 217408, "author_profile": "https://Stackoverflow.com/users/217408", "pm_score": 0, "selected": false, "text": "-contains $pathToCheck = \"c:\\some path\\to\\a\\file.txt\"\n\n$env:Path - split ';' -contains $pathToCheck\n $pathToCheck = \"c:\\some path\\to\\a\\file.txt\"\n\nif(!($env:Path -split ';' -contains $vboxPath)) {\n $documentsDir = [Environment]::GetFolderPath(\"MyDocuments\")\n $profileFilePath = Join-Path $documentsDir \"WindowsPowerShell/profile.ps1\"\n Out-File -FilePath $profileFilePath -Append -Force -Encoding ascii -InputObject \"`$env:Path += `\";$pathToCheck`\"\"\n Invoke-Expression -command $profileFilePath\n}\n" }, { "answer_id": 70617492, "author": "Jerry T", "author_id": 2292993, "author_profile": "https://Stackoverflow.com/users/2292993", "pm_score": 0, "selected": false, "text": "rem https://stackoverflow.com/a/59571160/2292993\nrem Don't get mess with %PATH%, it is a concatenation of USER+SYSTEM, and will cause a lot of duplication in the result. \nfor /f \"usebackq tokens=2,*\" %%A in (`reg query HKCU\\Environment /v PATH`) do set userPATH=%%B\nrem userPATH should be %USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps\n\nrem https://stackoverflow.com/questions/141344\nfor /f \"delims=\" %%A in ('echo \";%userPATH%;\" ^| find /C /I \";%WINAPPS%;\"') do set pathExists=%%A\nIf %pathExists%==0 (\n echo Inserting user path...\n setx PATH \"%WINAPPS%; %userPATH%\"\n)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
141,345
<p>I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong.</p> <pre><code>&lt;xsl:template match="one"&gt; &lt;xsl:variable name="varOne" select="@count" /&gt; &lt;/xsl:template&gt; &lt;xsl:template match="two"&gt; &lt;xsl:if test="$varOne = 'Y'"&gt; &lt;xsl:value-of select="varTwo"/&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre> <p>This has been simplified for here.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 141403, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 3, "selected": true, "text": "<!-- You may want to use absolute path -->\n<xsl:variable name=\"varOne\" select=\"one/@count\" />\n\n<xsl:template match=\"one\">\n<!-- // do something --> \n</xsl:template>\n\n<xsl:template match=\"two\">\n <xsl:if test=\"$varOne = 'Y'\">\n <xsl:value-of select=\"varTwo\"/>\n </xsl:if>\n</xsl:template>\n" }, { "answer_id": 141463, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<xsl:apply-templates select=\"two\">\n <xsl:with-param name=\"varOne\">\n <xsl:value-of select=\"one/@count\"/>\n </xsl:with-param>\n</xsl:apply-templates>\n\n<xsl:template match=\"two\">\n <xsl:param name=\"varOne\"/>\n <xsl:if test=\"$varOne = 'Y'\">\n <xsl:value-of select=\"varTwo\"/>\n </xsl:if>\n</xsl:template>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16354/" ]
141,348
<p>I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript <code>Date()</code> object so I can easily perform comparisons and other things on it.</p> <p>I tried the <code>parse()</code> method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same <code>Date()</code> object:</p> <ul> <li>1:00 pm</li> <li>1:00 p.m.</li> <li>1:00 p</li> <li>1:00pm</li> <li>1:00p.m.</li> <li>1:00p</li> <li>1 pm</li> <li>1 p.m.</li> <li>1 p</li> <li>1pm</li> <li>1p.m.</li> <li>1p</li> <li>13:00</li> <li>13</li> </ul> <p>I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my <code>Date()</code> object. What is the best way to do this?</p>
[ { "answer_id": 141504, "author": "John Resig", "author_id": 6524, "author_profile": "https://Stackoverflow.com/users/6524", "pm_score": 7, "selected": true, "text": "function parseTime( t ) {\n var d = new Date();\n var time = t.match( /(\\d+)(?::(\\d\\d))?\\s*(p?)/ );\n d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) );\n d.setMinutes( parseInt( time[2]) || 0 );\n return d;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 253680, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 2, "selected": false, "text": "function parseTime(timeString)\n{\n if (timeString == '') return null;\n var d = new Date();\n var time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*(p?)/);\n d.setHours( parseInt(time[1]) + ( ( parseInt(time[1]) < 12 && time[4] ) ? 12 : 0) );\n d.setMinutes( parseInt(time[3]) || 0 );\n d.setSeconds(0, 0);\n return d;\n} // parseTime()\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 338439, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 4, "selected": false, "text": "function parseTime(timeString)\n{\n if (timeString == '') return null;\n var d = new Date();\n var time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*(p?)/i);\n d.setHours( parseInt(time[1],10) + ( ( parseInt(time[1],10) < 12 && time[4] ) ? 12 : 0) );\n d.setMinutes( parseInt(time[3],10) || 0 );\n d.setSeconds(0, 0);\n return d;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 432785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "/(\\d+)(?::(\\d\\d))(?::(\\d\\d))?\\s*([pP]?)/ \n\n// added test for p or P\n// added seconds\n\nd.setHours( parseInt(time[1]) + (time[4] ? 12 : 0) ); // care with new indexes\nd.setMinutes( parseInt(time[2]) || 0 );\nd.setSeconds( parseInt(time[3]) || 0 );\n" }, { "answer_id": 2188651, "author": "Nathan Villaescusa", "author_id": 264837, "author_profile": "https://Stackoverflow.com/users/264837", "pm_score": 6, "selected": false, "text": "function parseTime(timeString) { \n if (timeString == '') return null;\n \n var time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*(p?)/i); \n if (time == null) return null;\n \n var hours = parseInt(time[1],10); \n if (hours == 12 && !time[4]) {\n hours = 0;\n }\n else {\n hours += (hours < 12 && time[4])? 12 : 0;\n } \n var d = new Date(); \n d.setHours(hours);\n d.setMinutes(parseInt(time[3],10) || 0);\n d.setSeconds(0, 0); \n return d;\n}\n\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n} /^(\\d+)(:(\\d\\d))?\\s*((a|(p))m?)?$/i\n" }, { "answer_id": 2307344, "author": "Pieter de Zwart", "author_id": 278277, "author_profile": "https://Stackoverflow.com/users/278277", "pm_score": 2, "selected": false, "text": "/**\n * Parse a string that looks like time and return a date object.\n * @return Date object on success, false on error.\n */\nString.prototype.parseTime = function() {\n // trim it and reverse it so that the minutes will always be greedy first:\n var value = this.trim().reverse();\n\n // We need to reverse the string to match the minutes in greedy first, then hours\n var timeParts = value.match(/(a|p)?\\s*((\\d{2})?:?)(\\d{1,2})/i);\n\n // This didnt match something we know\n if (!timeParts) {\n return false;\n }\n\n // reverse it:\n timeParts = timeParts.reverse();\n\n // Reverse the internal parts:\n for( var i = 0; i < timeParts.length; i++ ) {\n timeParts[i] = timeParts[i] === undefined ? '' : timeParts[i].reverse();\n }\n\n // Parse out the sections:\n var minutes = parseInt(timeParts[1], 10) || 0;\n var hours = parseInt(timeParts[0], 10);\n var afternoon = timeParts[3].toLowerCase() == 'p' ? true : false;\n\n // If meridian not set, and hours is 12, then assume afternoon.\n afternoon = !timeParts[3] && hours == 12 ? true : afternoon;\n // Anytime the hours are greater than 12, they mean afternoon\n afternoon = hours > 12 ? true : afternoon;\n // Make hours be between 0 and 12:\n hours -= hours > 12 ? 12 : 0;\n // Add 12 if its PM but not noon\n hours += afternoon && hours != 12 ? 12 : 0;\n // Remove 12 for midnight:\n hours -= !afternoon && hours == 12 ? 12 : 0;\n\n // Check number sanity:\n if( minutes >= 60 || hours >= 24 ) {\n return false;\n }\n\n // Return a date object with these values set.\n var d = new Date();\n d.setHours(hours);\n d.setMinutes(minutes);\n return d;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + tests[i].parseTime() );\n} var str = '12am';\nvar date = str.parseTime();\n" }, { "answer_id": 3998001, "author": "Brad", "author_id": 188547, "author_profile": "https://Stackoverflow.com/users/188547", "pm_score": 0, "selected": false, "text": "function parseTime( timeString ) {\nvar d = new Date();\nvar time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*([pP]?)/i);\nvar h = parseInt(time[1], 10);\nif (time[4])\n{\n if (h < 12)\n h += 12;\n}\nelse if (h == 12)\n h = 0;\nd.setHours(h);\nd.setMinutes(parseInt(time[3], 10) || 0);\nd.setSeconds(0, 0);\nreturn d;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 3998370, "author": "Stefan Haberl", "author_id": 287138, "author_profile": "https://Stackoverflow.com/users/287138", "pm_score": 2, "selected": false, "text": "function parseTime(text) {\n var time = text.match(/(\\d?\\d):?(\\d?\\d?)/);\n var h = parseInt(time[1], 10);\n var m = parseInt(time[2], 10) || 0;\n \n if (h > 24) {\n // try a different format\n time = text.match(/(\\d)(\\d?\\d?)/);\n h = parseInt(time[1], 10);\n m = parseInt(time[2], 10) || 0;\n } \n \n var d = new Date();\n d.setHours(h);\n d.setMinutes(m);\n return d; \n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 8395948, "author": "Andrew Cetinic", "author_id": 151447, "author_profile": "https://Stackoverflow.com/users/151447", "pm_score": 1, "selected": false, "text": "function parseTime(timeString) {\n if (timeString == '') return null;\n\n var time = timeString.match(/^(\\d+)([:\\.](\\d\\d))?\\s*((a|(p))m?)?$/i);\n\n if (time == null) return null;\n\n var m = parseInt(time[3], 10) || 0;\n var hours = parseInt(time[1], 10);\n\n if (time[4]) time[4] = time[4].toLowerCase();\n\n // 12 hour time\n if (hours == 12 && !time[4]) {\n hours = 12;\n }\n else if (hours == 12 && (time[4] == \"am\" || time[4] == \"a\")) {\n hours += 12;\n }\n else if (hours < 12 && (time[4] != \"am\" && time[4] != \"a\")) {\n hours += 12;\n }\n // 24 hour time\n else if(hours > 24 && hours.toString().length >= 3) {\n if(hours.toString().length == 3) {\n m = parseInt(hours.toString().substring(1,3), 10);\n hours = parseInt(hours.toString().charAt(0), 10);\n }\n else if(hours.toString().length == 4) {\n m = parseInt(hours.toString().substring(2,4), 10);\n hours = parseInt(hours.toString().substring(0,2), 10);\n }\n }\n\n var d = new Date();\n d.setHours(hours);\n d.setMinutes(m);\n d.setSeconds(0, 0);\n return d;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 14787410, "author": "claviska", "author_id": 567486, "author_profile": "https://Stackoverflow.com/users/567486", "pm_score": 4, "selected": false, "text": "1330 130pm function parseTime(time, format, step) {\n \n var hour, minute, stepMinute,\n defaultFormat = 'g:ia',\n pm = time.match(/p/i) !== null,\n num = time.replace(/[^0-9]/g, '');\n \n // Parse for hour and minute\n switch(num.length) {\n case 4:\n hour = parseInt(num[0] + num[1], 10);\n minute = parseInt(num[2] + num[3], 10);\n break;\n case 3:\n hour = parseInt(num[0], 10);\n minute = parseInt(num[1] + num[2], 10);\n break;\n case 2:\n case 1:\n hour = parseInt(num[0] + (num[1] || ''), 10);\n minute = 0;\n break;\n default:\n return '';\n }\n \n // Make sure hour is in 24 hour format\n if( pm === true && hour > 0 && hour < 12 ) hour += 12;\n \n // Force pm for hours between 13:00 and 23:00\n if( hour >= 13 && hour <= 23 ) pm = true;\n \n // Handle step\n if( step ) {\n // Step to the nearest hour requires 60, not 0\n if( step === 0 ) step = 60;\n // Round to nearest step\n stepMinute = (Math.round(minute / step) * step) % 60;\n // Do we need to round the hour up?\n if( stepMinute === 0 && minute >= 30 ) {\n hour++;\n // Do we need to switch am/pm?\n if( hour === 12 || hour === 24 ) pm = !pm;\n }\n minute = stepMinute;\n }\n \n // Keep within range\n if( hour <= 0 || hour >= 24 ) hour = 0;\n if( minute < 0 || minute > 59 ) minute = 0;\n\n // Format output\n return (format || defaultFormat)\n // 12 hour without leading 0\n .replace(/g/g, hour === 0 ? '12' : 'g')\n .replace(/g/g, hour > 12 ? hour - 12 : hour)\n // 24 hour without leading 0\n .replace(/G/g, hour)\n // 12 hour with leading 0\n .replace(/h/g, hour.toString().length > 1 ? (hour > 12 ? hour - 12 : hour) : '0' + (hour > 12 ? hour - 12 : hour))\n // 24 hour with leading 0\n .replace(/H/g, hour.toString().length > 1 ? hour : '0' + hour)\n // minutes with leading zero\n .replace(/i/g, minute.toString().length > 1 ? minute : '0' + minute)\n // simulate seconds\n .replace(/s/g, '00')\n // lowercase am/pm\n .replace(/a/g, pm ? 'pm' : 'am')\n // lowercase am/pm\n .replace(/A/g, pm ? 'PM' : 'AM');\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 27778902, "author": "RobG", "author_id": 257182, "author_profile": "https://Stackoverflow.com/users/257182", "pm_score": 2, "selected": false, "text": "/**\n * Parse a time in nearly any format\n * @param {string} time - Anything like 1 p, 13, 1:05 p.m., etc.\n * @returns {Date} - Date object for the current date and time set to parsed time\n*/\nfunction parseTime(time) {\n var b = time.match(/\\d+/g);\n \n // return undefined if no matches\n if (!b) return;\n \n var d = new Date();\n d.setHours(b[0]>12? b[0] : b[0]%12 + (/p/i.test(time)? 12 : 0), // hours\n /\\d/.test(b[1])? b[1] : 0, // minutes\n /\\d/.test(b[2])? b[2] : 0); // seconds\n return d;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n}" }, { "answer_id": 42590912, "author": "Sgnl", "author_id": 2612640, "author_profile": "https://Stackoverflow.com/users/2612640", "pm_score": 2, "selected": false, "text": "README.md var t = Time('2p');\nt.hours(); // 2\nt.minutes(); // 0\nt.period(); // 'pm'\nt.toString(); // '2:00 pm'\nt.nextDate(); // Sep 10 2:00 (assuming it is 1 o'clock Sep 10)\nt.format('hh:mm AM') // '02:00 PM'\nt.isValid(); // true\nTime.isValid('99:12'); // false\n" }, { "answer_id": 49185071, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 1, "selected": false, "text": "\"use strict\";\n\nString.prototype.toTime = function () {\n var time = this;\n var post_meridiem = false;\n var ante_meridiem = false;\n var hours = 0;\n var minutes = 0;\n\n if( time != null ) {\n post_meridiem = time.match( /p/i ) !== null;\n ante_meridiem = time.match( /a/i ) !== null;\n\n // Preserve 2400h time by changing leading zeros to 24.\n time = time.replace( /^00/, '24' );\n\n // Strip the string down to digits and convert to a number.\n time = parseInt( time.replace( /\\D/g, '' ) );\n }\n else {\n time = 0;\n }\n\n if( time > 0 && time < 24 ) {\n // 1 through 23 become hours, no minutes.\n hours = time;\n }\n else if( time >= 100 && time <= 2359 ) {\n // 100 through 2359 become hours and two-digit minutes.\n hours = ~~(time / 100);\n minutes = time % 100;\n }\n else if( time >= 2400 ) {\n // After 2400, it's midnight again.\n minutes = (time % 100);\n post_meridiem = false;\n }\n\n if( hours == 12 && ante_meridiem === false ) {\n post_meridiem = true;\n }\n\n if( hours > 12 ) {\n post_meridiem = true;\n hours -= 12;\n }\n\n if( minutes > 59 ) {\n minutes = 59;\n }\n\n var result =\n (\"\"+hours).padStart( 2, \"0\" ) + \":\" + (\"\"+minutes).padStart( 2, \"0\" ) +\n (post_meridiem ? \"PM\" : \"AM\");\n\n return result;\n};\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + tests[i].toTime() );\n} <input type=\"text\" class=\"time\" />\n $(\".time\").change( function() {\n var $this = $(this);\n $(this).val( time.toTime() );\n });\n" }, { "answer_id": 50769298, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 1, "selected": false, "text": "undefined localDate 1330 ^\\s* timeToString npm i simplertime /**\n * Parses a string into a Date. Supports several formats: \"12\", \"1234\",\n * \"12:34\", \"12:34pm\", \"12:34 PM\", \"12:34:56 pm\", and \"12:34:56.789\".\n * The time must be at the beginning of the string but can have leading spaces.\n * Anything is allowed after the time as long as the time itself appears to\n * be valid, e.g. \"12:34*Z\" is OK but \"12345\" is not.\n * @param {string} t Time string, e.g. \"1435\" or \"2:35 PM\" or \"14:35:00.0\"\n * @param {Date|undefined} localDate If this parameter is provided, setHours\n * is called on it. Otherwise, setUTCHours is called on 1970/1/1.\n * @returns {Date|undefined} The parsed date, if parsing succeeded.\n */\nfunction parseTime(t, localDate) {\n // ?: means non-capturing group and ?! is zero-width negative lookahead\n var time = t.match(/^\\s*(\\d\\d?)(?::?(\\d\\d))?(?::(\\d\\d))?(?!\\d)(\\.\\d+)?\\s*(pm?|am?)?/i);\n if (time) {\n var hour = parseInt(time[1]), pm = (time[5] || ' ')[0].toUpperCase();\n var min = time[2] ? parseInt(time[2]) : 0;\n var sec = time[3] ? parseInt(time[3]) : 0;\n var ms = (time[4] ? parseFloat(time[4]) * 1000 : 0);\n if (pm !== ' ' && (hour == 0 || hour > 12) || hour > 24 || min >= 60 || sec >= 60)\n return undefined;\n if (pm === 'A' && hour === 12) hour = 0;\n if (pm === 'P' && hour !== 12) hour += 12;\n if (hour === 24) hour = 0;\n var date = new Date(localDate!==undefined ? localDate.valueOf() : 0);\n var set = (localDate!==undefined ? date.setHours : date.setUTCHours);\n set.call(date, hour, min, sec, ms);\n return date;\n }\n return undefined;\n}\n\nvar testSuite = {\n '1300': ['1:00 pm','1:00 P.M.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1:00:00PM', '1300', '13'],\n '1100': ['11:00am', '11:00 AM', '11:00', '11:00:00', '1100'],\n '1359': ['1:59 PM', '13:59', '13:59:00', '1359', '1359:00', '0159pm'],\n '100': ['1:00am', '1:00 am', '0100', '1', '1a', '1 am'],\n '0': ['00:00', '24:00', '12:00am', '12am', '12:00:00 AM', '0000', '1200 AM'],\n '30': ['0:30', '00:30', '24:30', '00:30:00', '12:30:00 am', '0030', '1230am'],\n '1435': [\"2:35 PM\", \"14:35:00.0\", \"1435\"],\n '715.5': [\"7:15:30\", \"7:15:30am\"],\n '109': ['109'], // Three-digit numbers work (I wasn't sure if they would)\n '': ['12:60', '11:59:99', '-12:00', 'foo', '0660', '12345', '25:00'],\n};\n\nvar passed = 0;\nfor (var key in testSuite) {\n let num = parseFloat(key), h = num / 100 | 0;\n let m = num % 100 | 0, s = (num % 1) * 60;\n let expected = Date.UTC(1970, 0, 1, h, m, s); // Month is zero-based\n let strings = testSuite[key];\n for (let i = 0; i < strings.length; i++) {\n var result = parseTime(strings[i]);\n if (result === undefined ? key !== '' : key === '' || expected !== result.valueOf()) {\n console.log(`Test failed at ${key}:\"${strings[i]}\" with result ${result ? result.toUTCString() : 'undefined'}`);\n } else {\n passed++;\n }\n }\n}\nconsole.log(passed + ' tests passed.');\n" }, { "answer_id": 51969817, "author": "Souradeep Nanda", "author_id": 1217998, "author_profile": "https://Stackoverflow.com/users/1217998", "pm_score": 0, "selected": false, "text": "const toSeconds = s => s.split(':').map(v => parseInt(v)).reverse().reduce((acc,e,i) => acc + e * Math.pow(60,i))\n" }, { "answer_id": 53738137, "author": "V. Rubinetti", "author_id": 2180570, "author_profile": "https://Stackoverflow.com/users/2180570", "pm_score": 2, "selected": false, "text": "// heres some filler code of the functions I included in the test,\n// because StackOverfleaux wont let me have a jsfiddle link without code\nFunctions = [\n JohnResig,\n Qwertie,\n PatrickMcElhaney,\n Brad,\n NathanVillaescusa,\n DaveJarvis,\n AndrewCetinic,\n StefanHaberl,\n PieterDeZwart,\n JoeLencioni,\n Claviska,\n RobG,\n DateJS,\n MomentJS\n];\n// I didn't include `date-fns`, because it seems to have even more\n// limited parsing than MomentJS or DateJS\n 12 12:00am 12:00pm red yellow undefined null NaN \"\" \"invalid date\" green Date() light green Date() HH:mm" }, { "answer_id": 53752557, "author": "V. Rubinetti", "author_id": 2180570, "author_profile": "https://Stackoverflow.com/users/2180570", "pm_score": 0, "selected": false, "text": "// attempt to parse string as time. return js date object\nfunction parseTime(string) {\n string = String(string);\n\n var am = null;\n\n // check if \"apm\" or \"pm\" explicitly specified, otherwise null\n if (string.toLowerCase().includes(\"p\")) am = false;\n else if (string.toLowerCase().includes(\"a\")) am = true;\n\n string = string.replace(/\\D/g, \"\"); // remove non-digit characters\n string = string.substring(0, 4); // take only first 4 digits\n if (string.length === 3) string = \"0\" + string; // consider eg \"030\" as \"0030\"\n string = string.replace(/^00/, \"24\"); // add 24 hours to preserve eg \"0012\" as \"00:12\" instead of \"12:00\", since will be converted to integer\n\n var time = parseInt(string); // convert to integer\n // default time if all else fails\n var hours = 12,\n minutes = 0;\n\n // if able to parse as int\n if (Number.isInteger(time)) {\n // treat eg \"4\" as \"4:00pm\" (or \"4:00am\" if \"am\" explicitly specified)\n if (time >= 0 && time <= 12) {\n hours = time;\n minutes = 0;\n // if \"am\" or \"pm\" not specified, establish from number\n if (am === null) {\n if (hours >= 1 && hours <= 12) am = false;\n else am = true;\n }\n }\n // treat eg \"20\" as \"8:00pm\"\n else if (time >= 13 && time <= 99) {\n hours = time % 24;\n minutes = 0;\n // if \"am\" or \"pm\" not specified, force \"am\"\n if (am === null) am = true;\n }\n // treat eg \"52:95\" as 52 hours 95 minutes \n else if (time >= 100) {\n hours = Math.floor(time / 100); // take first two digits as hour\n minutes = time % 100; // take last two digits as minute\n // if \"am\" or \"pm\" not specified, establish from number\n if (am === null) {\n if (hours >= 1 && hours <= 12) am = false;\n else am = true;\n }\n }\n\n // add 12 hours if \"pm\"\n if (am === false && hours !== 12) hours += 12;\n // sub 12 hours if \"12:00am\" (midnight), making \"00:00\"\n if (am === true && hours === 12) hours = 0;\n\n // keep hours within 24 and minutes within 60\n // eg 52 hours 95 minutes becomes 4 hours 35 minutes\n hours = hours % 24;\n minutes = minutes % 60;\n }\n\n // convert to js date object\n var date = new Date();\n date.setHours(hours);\n date.setMinutes(minutes);\n date.setSeconds(0);\n return date;\n}\n\nvar tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\n\nfor ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\n} 1 13:00 1:00pm 1100 23:00 11:00pm 456 16:56 4:56pm" }, { "answer_id": 66371079, "author": "Gabriel", "author_id": 5660086, "author_profile": "https://Stackoverflow.com/users/5660086", "pm_score": 0, "selected": false, "text": " function parse(time){\n let post_meridiem = time.match(/p/i) !== null;\n let result;\n time = time.replace(/[^\\d:-]/g, '');\n let hours = 0;\n let minutes = 0;\n if (!time) return;\n let parts = time.split(':');\n if (parts.length > 2) time = parts[0] + ':' + parts[1];\n if (parts[0] > 59 && parts.length === 2) time = parts[0];\n if (!parts[0] && parts[1] < 60) minutes = parts[1];\n else if (!parts[0] && parts[1] >= 60) return;\n time = time.replace(/^00/, '24');\n time = parseInt(time.replace(/\\D/g, ''));\n if (time >= 2500) return;\n if (time > 0 && time < 24 && parts.length === 1) hours = time;\n else if (time < 59) minutes = time;\n else if (time >= 60 && time <= 99 && parts[0]) {\n hours = ('' + time)[0];\n minutes = ('' + time)[1];\n } else if (time >= 100 && time <= 2359) {\n hours = ~~(time / 100);\n minutes = time % 100;\n } else if (time >= 2400) {\n hours = ~~(time / 100) - 24;\n minutes = time % 100;\n post_meridiem = false;\n }\n if (hours > 59 || minutes > 59) return;\n if (post_meridiem && hours !== 0) hours += 12;\n if (minutes > 59) minutes = 59;\n if (hours > 23) hours = 0;\n result = ('' + hours).padStart(2, '0') + ':' + ('' + minutes).padStart(2, '0');\n return result;\n}\n var tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '0000', '0011', '-1', 'mioaw',\n \"0820\",\n \"32\",\n \"124\",\n \"1330\",\n \"130pm\",\n \"456\",\n \":40\",\n \":90\",\n \"12:69\",\n \"50:90\",\n \"aaa12:34aaa\",\n \"aaa50:00aaa\",\n ];\n\n for ( var i = 0; i < tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parse(tests[i]) );\n }" }, { "answer_id": 71097961, "author": "Jacob Lockett", "author_id": 8429492, "author_profile": "https://Stackoverflow.com/users/8429492", "pm_score": 0, "selected": false, "text": "const parseTime = (timeString, assumedTimeOfDay = \"pm\") => {\n // Validate timeString input\n if (!timeString) return null\n\n const regex = /(\\d{1,2})(\\d{2})?([a|p]m?)?/\n const noOfDigits = timeString.replace(/[^\\d]/g, \"\").length\n\n if (noOfDigits === 0) return null\n\n // Seconds are unsupported (rare use case in my eyes, feel free to edit)\n if (noOfDigits > 4) return null\n\n // Add a leading 0 to prevent bad regex match (i.e. 100 = 1hr 00min, not 10hr 0min)\n const sanitized = `${noOfDigits === 3 ? \"0\" : \"\"}${timeString}`\n .toLowerCase()\n .replace(/[^\\dapm]/g, \"\")\n const parsed = sanitized.match(regex)\n\n if (!parsed) return null\n\n // Clean up and name parsed data\n const {\n input,\n hours,\n minutes,\n meridian\n } = {\n input: parsed[0],\n hours: Number(parsed[1] || 0),\n minutes: Number(parsed[2] || 0),\n // Defaults to pm if user provided assumedTimeOfDay is not am or pm\n meridian: /am/.test(`${parsed[3] || assumedTimeOfDay.toLowerCase()}m`) ?\n \"am\" : \"pm\",\n }\n\n // Quick check for valid numbers\n if (hours < 0 || hours >= 24 || minutes < 0 || minutes >= 60) return null\n\n // Convert hours to 24hr format\n const timeOfDay = hours >= 13 ? \"pm\" : meridian\n const newHours =\n hours >= 13 ?\n hours :\n hours === 12 && timeOfDay === \"am\" ?\n 0 :\n (hours === 12 && timeOfDay === \"pm\") || timeOfDay === \"am\" ?\n hours :\n hours + 12\n\n // Convert data to Date object and return\n return new Date(new Date().setHours(newHours, minutes, 0))\n}\n\nconst times = [\n '12',\n '12p',\n '12pm',\n '12p.m.',\n '12 p',\n '12 pm',\n '12 p.m.',\n '12:00',\n '12:00p',\n '12:00pm',\n '12:00p.m.',\n '12:00 p',\n '12:00 pm',\n '12:00 p.m.',\n '12:00',\n '12:00p',\n '12:00pm',\n '12:00p.m.',\n '12:00 p',\n '12:00 pm',\n '12:00 p.m.',\n '1200',\n '1200p',\n '1200pm',\n '1200p.m.',\n '1200 p',\n '1200 pm',\n '1200 p.m.',\n '12',\n '1200',\n '12:00',\n '1',\n '1p',\n '1pm',\n '1p.m.',\n '1 p',\n '1 pm',\n '1 p.m.',\n '1:00',\n '1:00p',\n '1:00pm',\n '1:00p.m.',\n '1:00 p',\n '1:00 pm',\n '1:00 p.m.',\n '01:00',\n '01:00p',\n '01:00pm',\n '01:00p.m.',\n '01:00 p',\n '01:00 pm',\n '01:00 p.m.',\n '0100',\n '0100p',\n '0100pm',\n '0100p.m.',\n '0100 p',\n '0100 pm',\n '0100 p.m.',\n '13',\n '1300',\n '13:00',\n 'random',\n '092fsd9)*(U243',\n '092fsd9)*(U'\n]\n\ntimes.map(t => {\n const parsed = parseTime(t)\n\n if (parsed) {\n console.log(`${parsed.toLocaleTimeString()} from ${t}`)\n } else {\n console.log(`Invalid Time (${t})`)\n }\n})" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18986/" ]
141,351
<p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="https://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p> <p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="https://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
[ { "answer_id": 142138, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 2, "selected": false, "text": "x = SomeObject()\n... later ...\noldRefCount = sys.getrefcount( x )\nsuspiciousFunction( x )\nif (oldRefCount != sys.getrefcount(x)):\n print \"Possible memory leak...\"\n Py_INCREF Py_DECREF" }, { "answer_id": 142177, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "gc" }, { "answer_id": 9567831, "author": "gerdemb", "author_id": 27478, "author_profile": "https://Stackoverflow.com/users/27478", "pm_score": 5, "selected": false, "text": "gc sys.getsizeof() rss = psutil.Process(os.getpid()).get_memory_info().rss\n# Dump variables if using more than 100MB of memory\nif rss > 100 * 1024 * 1024:\n memory_dump()\n os.abort()\n\ndef memory_dump():\n dump = open(\"memory.pickle\", 'wb')\n xs = []\n for obj in gc.get_objects():\n i = id(obj)\n size = sys.getsizeof(obj, 0)\n # referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]\n referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]\n if hasattr(obj, '__class__'):\n cls = str(obj.__class__)\n xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})\n cPickle.dump(xs, dump)\n __class__ with open(\"memory.pickle\", 'rb') as dump:\n objs = cPickle.load(dump)\n import gc\nimport sys\nimport _pickle as cPickle\n\ndef memory_dump():\n with open(\"memory.pickle\", 'wb') as dump:\n xs = []\n for obj in gc.get_objects():\n i = id(obj)\n size = sys.getsizeof(obj, 0)\n # referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]\n referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]\n if hasattr(obj, '__class__'):\n cls = str(obj.__class__)\n xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})\n cPickle.dump(xs, dump)\n" }, { "answer_id": 61260839, "author": "saaj", "author_id": 2072035, "author_profile": "https://Stackoverflow.com/users/2072035", "pm_score": 6, "selected": true, "text": "tracemalloc gc.get_objects dozer > 0.7 pip install celery < 4.5 import time\n\nimport celery \n\n\nredis_dsn = 'redis://localhost'\napp = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn)\n\n@app.task\ndef subtask():\n pass\n\n@app.task\ndef task():\n for i in range(10_000):\n subtask.delay()\n time.sleep(0.01)\n\n\nif __name__ == '__main__':\n task.delay().get()\n procpath pip install procpath procpath record -d celery.sqlite -i1 \"$..children[?('celery' in @.cmdline)]\" docker run --rm -it -p 6379:6379 redis celery -A demo worker --concurrency 2 python demo.py procpath celery.sqlite SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rss\nFROM record \n X=ts Y=rss By=stat_pid dozer echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip pip install pillow dozer pip install pyrasite pyrasite-shell 26572\n wsgiref import threading\nimport wsgiref.simple_server\n\nimport dozer\n\n\ndef run_dozer():\n app = dozer.Dozer(app=None, path='/')\n with wsgiref.simple_server.make_server('', 8000, app) as httpd:\n print('Serving Dozer on port 8000...')\n httpd.serve_forever()\n\nthreading.Thread(target=run_dozer, daemon=True).start()\n http://localhost:8000 python demo.py celery.result.AsyncResult vine.promises.promise weakref.WeakMethod gc.get_referrers gc.get_referents objgraph pip install objgraph apt-get install graphviz python demo.py floor=0 filter=AsyncResult objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png')\n Context list _children celery.result.AsyncResult Filter=celery.*context celery.app.task.Context trail = True result.children trail=False @app.task(trail=False)\ndef task():\n for i in range(10_000):\n subtask.delay()\n time.sleep(0.01)\n python demo.py" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9585/" ]
141,360
<p>I came across this topic today while investigating something very strange. Doing certain things in our Flex app can cause the number of frames rendered to rocket, from 12fps to ~30fps: loaded animations start playing at high speed and the GUI starts to lock up.</p> <p>Since everything I've read on Flex/Flash hammers home the point "the frame rate is capped at the fps set in the top level app", it seems the only way these extra renders can be happening is due to some events causing them (no programmatic changes to the stage's framerate are done anywhere). Since it only happens when I put my update logic in the ENTER_FRAME handler, I'm trying to figure out what might be happening which to apparently causing Flex to go render-crazy.</p> <p>Hypothesis: something in my update function is triggering an immediate screen update, this raises another ENTER_FRAME immediately, which means my update loop gets called, which triggers another immediate screen update, ...</p> <p>We have Flex components used in our GUI, if this is a factor. I don't really know where to go next on this.</p> <p><strong>Clarifications</strong>:</p> <ul> <li>When I say things speed up, there are two ways this manifests.</li> <li>Firstly, my ENTER_FRAME handler gets called far more often.</li> <li>Secondly, a loaded Flash SWF with a looping animation built in suddenly speeds up to te point it looks silly.</li> <li>I am not using updateAfterEvent, I only found this existed when researching this problem. Apparently, some events on Sprite subclasses automatically call this and I wonder if that's the root cause.</li> <li>I am not doing any direct messsing about with rendering at all. Background animations play automatically as they have timelines built-in from CS3 authoring, all our update function does is change the position of DisPlayObjects or add/remove them etc</li> </ul> <p><strong>Update:</strong> I added a label to my app to print out stage.frameRate, and discovered at certain times, it suddenly changes from 12 to 1000 (the maximum allowed value). While it was trivial to add a line to my ENTER_FRAME handler to reset it that's hardly a big help. Also, even doing this, the rendering is all messed up. Certain actions (like raising an Alert popup) make it all spring back into life. Unfortunately, I am not able to view the source of the Stage class to set a breakpoint on the setter property.</p> <p>That's very interesting about the Flex loading 'set to 1000fps' thing. What we have are several Flex applications which all provide a common interface. A master app is in charge of loading these modules as required through the SWFLoader class. However, the loading process already takes into account the delayed loading... when the SWF loads we then wait for the APPLICATION_COMPLETE from the SystemManager. Once this is received, shouldn't the applications completion have occurred?</p>
[ { "answer_id": 143204, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 1, "selected": false, "text": "updateAfterEvent() ENTER_FRAME invalidate()" }, { "answer_id": 143830, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 1, "selected": false, "text": "stage.frameRate Event.EXIT_FRAME Event.FRAME_CONSTRUCTED MouseEvent.MOUSE_MOVE" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
141,368
<p>Given two datetimes. What is the best way to calculate the number of working hours between them. Considering the working hours are Mon 8 - 5.30, and Tue-Fri 8.30 - 5.30, and that potentially any day could be a public holiday.</p> <p>This is my effort, seem hideously inefficient but in terms of the number of iterations and that the IsWorkingDay method hits the DB to see if that datetime is a public holiday.</p> <p>Can anyone suggest any optimizations or alternatives.</p> <pre><code> public decimal ElapsedWorkingHours(DateTime start, DateTime finish) { decimal counter = 0; while (start.CompareTo(finish) &lt;= 0) { if (IsWorkingDay(start) &amp;&amp; IsOfficeHours(start)) { start = start.AddMinutes(1); counter++; } else { start = start.AddMinutes(1); } } decimal hours; if (counter != 0) { hours = counter/60; } return hours; } </code></pre>
[ { "answer_id": 141392, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 2, "selected": false, "text": "// Normalise start and end \nwhile start.day is weekend or holiday, start.day++, start.time = 0.00am\n if start.day is monday,\n start.time = max(start.time, 8am)\n else\n start.time = max(start.time, 8.30am)\nwhile end.day is weekend or holiday, end.day--, end.time = 11.59pm\nend.time = min(end.time, 5.30pm)\n\n// Now we've normalised, is there any time left? \nif start > end\n return 0\n\n// Calculate time in first day \ntimediff = 5.30pm - start.time\nday = start.day + 1\n// Add time on all intervening days\nwhile(day < end.day)\n // returns 9 or 9.30hrs or 0 as appropriate, could be optimised to grab all records\n // from the database in 1 or 2 hits, by counting all intervening mondays, and all\n // intervening tue-fris (non-holidays)\n timediff += duration(day) \n\n// Add time on last day\ntimediff += end.time - 08.30am\nif end.day is Monday then\n timediff += end.time - 08.00am\nelse\n timediff += end.time - 08.30am\n\nreturn timediff\n" }, { "answer_id": 141401, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 1, "selected": false, "text": "SELECT COUNT(*) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End\n HolidayStart HolidayEnd" }, { "answer_id": 141473, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "TimeSpan = TimeSpan Between Date1 And Date2\ncntDays = TimeSpan.Days \ncntNumberMondays = Iterate Between Date1 And Date2 Counting Mondays \ncntdays = cntdays - cntnumbermondays\nNumHolidays = DBCall To Get # Holidays BETWEEN Date1 AND Date2\nCntdays = cntdays - numholidays \nnumberhours = ((decimal)cntdays * NumberHoursInWorkingDay )+((decimal)cntNumberMondays * NumberHoursInMondayWorkDay )\n" }, { "answer_id": 141494, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 1, "selected": false, "text": "public decimal ElapseddWorkingHours(DateTime start, DateTime finish)\n{\n if (start.Date == finish.Date)\n return (finish - start).TotalHours;\n\n if (IsWorkingDay(start.Date))\n return ElapsedWorkingHours(start, new DateTime(start.Year, start.Month, start.Day, 17, 30, 0))\n + ElapsedWorkingHours(start.Date.AddDays(1).AddHours(DateStartTime(start.Date.AddDays(1)), finish);\n else\n return ElapsedWorkingHours(start.Date.AddDays(1), finish);\n}\n" }, { "answer_id": 141529, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "saturdays = ((finish - start) + Weekday(start) + 2) / 7;\nsundays = ((finish - start) + Weekday(start) + 1) / 7;\n" }, { "answer_id": 3603200, "author": "Wes", "author_id": 435243, "author_profile": "https://Stackoverflow.com/users/435243", "pm_score": -1, "selected": false, "text": "Dim totalMinutes As Integer = 0\n\nFor minute As Integer = 0 To DateDiff(DateInterval.Minute, contextInParameter1, contextInParameter2)\n Dim d As Date = contextInParameter1.AddMinutes(minute)\n If d.DayOfWeek <= DayOfWeek.Friday AndAlso _\n d.DayOfWeek >= DayOfWeek.Monday AndAlso _\n d.Hour >= 8 AndAlso _\n d.Hour <= 17 Then\n totalMinutes += 1\n Else\n Dim test = \"\"\n End If\nNext minute\n\nDim totalHours = totalMinutes / 60\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
141,370
<p>What is the best way to specify a property name when using INotifyPropertyChanged? </p> <p>Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.</p>
[ { "answer_id": 142403, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 1, "selected": false, "text": "protected void OnPropertyChanged()\n{\n OnPropertyChanged(PropertyName);\n}\n\nprotected string PropertyName\n{\n get\n {\n MethodBase mb = new StackFrame(1).GetMethod();\n string name = mb.Name;\n if(mb.Name.IndexOf(\"get_\") > -1)\n name = mb.Name.Replace(\"get_\", \"\");\n\n if(mb.Name.IndexOf(\"set_\") > -1)\n name = mb.Name.Replace(\"set_\", \"\");\n\n return name;\n }\n}\n" }, { "answer_id": 143611, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 7, "selected": true, "text": "PropertyChanged PropertyChanged GetProperty PropertyInfo GetValue GetProperty public class Person : INotifyPropertyChanged\n{\n private string name;\n\n public string Name\n {\n get { return this.name; }\n set \n { \n this.name = value;\n FirePropertyChanged(p => p.Name);\n }\n }\n\n private void FirePropertyChanged<TValue>(Expression<Func<Person, TValue>> propertySelector)\n {\n if (PropertyChanged == null)\n return;\n\n var memberExpression = propertySelector.Body as MemberExpression;\n if (memberExpression == null)\n return;\n\n PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n}\n Expression FirePropertyChanged(p => p.Name);\n" }, { "answer_id": 283844, "author": "Philipp", "author_id": 36889, "author_profile": "https://Stackoverflow.com/users/36889", "pm_score": 4, "selected": false, "text": "private int age;\npublic int Age\n{\n get { return age; }\n set\n {\n age = value;\n OnPropertyChanged(() => Age);\n }\n}\n\n\nprivate void OnPropertyChanged<T>(Expression<Func<T>> exp)\n{\n //the cast will always succeed\n MemberExpression memberExpression = (MemberExpression) exp.Body;\n string propertyName = memberExpression.Member.Name;\n\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n}\n" }, { "answer_id": 1209104, "author": "Phil", "author_id": 148089, "author_profile": "https://Stackoverflow.com/users/148089", "pm_score": 4, "selected": false, "text": " public class Observable<T> : INotifyPropertyChanged\n where T : Observable<T>\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected static PropertyChangedEventArgs CreateArgs(\n Expression<Func<T, object>> propertyExpression)\n {\n var lambda = propertyExpression as LambdaExpression;\n MemberExpression memberExpression;\n if (lambda.Body is UnaryExpression)\n {\n var unaryExpression = lambda.Body as UnaryExpression;\n memberExpression = unaryExpression.Operand as MemberExpression;\n }\n else\n {\n memberExpression = lambda.Body as MemberExpression;\n }\n\n var propertyInfo = memberExpression.Member as PropertyInfo;\n\n return new PropertyChangedEventArgs(propertyInfo.Name);\n }\n\n protected void NotifyChange(PropertyChangedEventArgs args)\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, args);\n }\n }\n}\n\npublic class Person : Observable<Person>\n{\n // property change event arg objects\n static PropertyChangedEventArgs _firstNameChangeArgs = CreateArgs(x => x.FirstName);\n static PropertyChangedEventArgs _lastNameChangeArgs = CreateArgs(x => x.LastName);\n\n string _firstName;\n string _lastName;\n\n public string FirstName\n {\n get { return _firstName; }\n set\n {\n _firstName = value;\n NotifyChange(_firstNameChangeArgs);\n }\n }\n\n public string LastName\n {\n get { return _lastName; }\n set\n {\n _lastName = value;\n NotifyChange(_lastNameChangeArgs);\n }\n }\n}\n" }, { "answer_id": 9192761, "author": "Kévin Rapaille", "author_id": 1073448, "author_profile": "https://Stackoverflow.com/users/1073448", "pm_score": 2, "selected": false, "text": "public class Person : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n public string GivenNames { get; set; }\n public string FamilyName { get; set; }\n\n public string FullName\n {\n get\n {\n return string.Format(\"{0} {1}\", GivenNames, FamilyName);\n }\n }\n}\n public class Person : INotifyPropertyChanged\n{\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n private string givenNames;\n public string GivenNames\n {\n get { return givenNames; }\n set\n {\n if (value != givenNames)\n {\n givenNames = value;\n OnPropertyChanged(\"GivenNames\");\n OnPropertyChanged(\"FullName\");\n }\n }\n }\n\n private string familyName;\n public string FamilyName\n {\n get { return familyName; }\n set\n {\n if (value != familyName)\n {\n familyName = value;\n OnPropertyChanged(\"FamilyName\");\n OnPropertyChanged(\"FullName\");\n }\n }\n }\n\n public string FullName\n {\n get\n {\n return string.Format(\"{0} {1}\", GivenNames, FamilyName);\n }\n }\n\n public virtual void OnPropertyChanged(string propertyName)\n {\n var propertyChanged = PropertyChanged;\n if (propertyChanged != null)\n {\n propertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n}\n" }, { "answer_id": 14133657, "author": "Denys Wessels", "author_id": 923095, "author_profile": "https://Stackoverflow.com/users/923095", "pm_score": 5, "selected": false, "text": "public event PropertyChangedEventHandler PropertyChanged = delegate { };\n\npublic void OnPropertyChanged([CallerMemberName]string propertyName=\"\")\n{\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n}\n\nprivate string name;\npublic string Name\n{\n get { return name; }\n set \n { \n name = value;\n OnPropertyChanged();\n }\n}\n" }, { "answer_id": 43206049, "author": "Rekshino", "author_id": 7713750, "author_profile": "https://Stackoverflow.com/users/7713750", "pm_score": 2, "selected": false, "text": "public event PropertyChangedEventHandler PropertyChanged;\n\nprotected void NotifyPropertyChanged(string info)\n{ \n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));\n}\npublic string SelectedItem\n{\n get\n {\n return _selectedItem;\n }\n set\n {\n if (_selectedItem != value)\n {\n _selectedItem = value;\n NotifyPropertyChanged(nameof(SelectedItem));\n }\n }\n}\nprivate string _selectedItem;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22813/" ]
141,372
<p>Emacs has a useful <code>transpose-words</code> command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.</p> <p>For example, ‘<code>stack |overflow</code>’ + M-t = ‘<code>overflow stack|</code>’ (‘<code>|</code>’ is the cursor position).</p> <p><code>&lt;a&gt;|&lt;p&gt;</code> becomes <code>&lt;p&gt;&lt;a|&gt;</code>.</p> <p>Is it possible to emulate it in Vim? I know I can use <code>dwwP</code>, but it doesn’t work well with punctuation.</p> <p><em>Update:</em> No, <code>dwwP</code> is <em>really</em> not a solution. Imagine:</p> <pre><code>SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) ) // with cursor here ^ </code></pre> <p>Emacs’ M-t would have exchanged <code>b</code> and <code>c</code>, resulting in <code>(a)(c)(b)</code>.</p> <p>What works is <code>/\w yiwNviwpnviwgp</code>. But it spoils <code>""</code> and <code>"/</code>. Is there a cleaner solution?</p> <p><em>Update²:</em></p> <h1>Solved</h1> <pre><code>:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,&lt;CR&gt;kgJ:nohl&lt;CR&gt; </code></pre> <p>Imperfect, but works.</p> <p>Thanks Camflan for bringing the <code>%#</code> item to my attention. Of course, it’s all on the <a href="http://vim.wikia.com/wiki/VimTip47" rel="noreferrer">wiki</a>, but I didn’t realize it could solve the problem of <em>exact</em> (Emacs got it completely right) duplication of the <code>transpose-words</code> feature.</p>
[ { "answer_id": 141485, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "dw wP\n 2dw bhP\n map L dwwP\nmap M 2dwbhP \n" }, { "answer_id": 141824, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 4, "selected": true, "text": "\" swap two words\n:vnoremap <C-X> <Esc>`.``gvP``P\n\" Swap word with next word\nnmap <silent> gw \"_yiw:s/\\(\\%#\\w\\+\\)\\(\\_W\\+\\)\\(\\w\\+\\)/\\3\\2\\1/<cr><c-o><c-l> *N*\n" }, { "answer_id": 12512287, "author": "Ji Han", "author_id": 1685865, "author_profile": "https://Stackoverflow.com/users/1685865", "pm_score": 2, "selected": false, "text": "\"transpose words (like emacs `transpose-words')\nfunction! TransposeWords()\n if search('\\w\\+\\%#\\w*\\W\\+\\w\\+')\n elseif search('\\w\\+\\W\\+\\%#\\W*\\w\\+')\n endif\n let l:pos = getpos('.')\n exec 'silent! :s/\\(\\%#\\w\\+\\)\\(\\W\\+\\)\\(\\w\\+\\)/\\3\\2\\1/'\n call setpos('.', l:pos)\n let l:_ = search('\\(\\%#\\w\\+\\W\\+\\)\\@<=\\w\\+')\n normal el\nendfunction\n\nnmap <silent> <M-right> :call TransposeWords()<CR>\nimap <silent> <M-right> <C-O>:call TransposeWords()<CR>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21055/" ]
141,388
<p>Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:</p> <pre><code>&lt;ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}" dataProvider="{_data.staticData.dead_reason}" labelField="@label" width="300"/&gt; </code></pre> <p>The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?</p>
[ { "answer_id": 141408, "author": "bill d", "author_id": 1798, "author_profile": "https://Stackoverflow.com/users/1798", "pm_score": 2, "selected": false, "text": "<mx:Repeater dataProvider=\"{_data.staticData.dead_reason}\">\n <mx:RadioButton groupName=\"reasons\" ...>\n</mx:Repeater>\n" }, { "answer_id": 806732, "author": "Kevin", "author_id": 98514, "author_profile": "https://Stackoverflow.com/users/98514", "pm_score": 0, "selected": false, "text": "<mx:RadioButtonGroup id=\"RDO_Group\"/>\n<mx:Repeater id=\"myRepeater\" dataProvider=\"{_data.staticData.dead_reason}\">\n<mx:RadioButton id=\"rdo\" label=\"{myRepeater.currentItem}\" value=\"{myRepeater.currentItem}\" groupName=\"RDO_Group\"/>\n</mx:Repeater>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
141,399
<p>I'm pretty new to both C++ and Block Cipher encryption, and I am currently in the process of writing a decryption function for AES (16 byte seed / 16 byte blocks). All is going well, but my total data size is not always a multiple of my block size. I'm wondering what the best way to handle leftover data at the end of my data.</p> <p>I'm using Crypto++ for the AES library.</p> <p>The <code>ProcessBlock()</code> function takes an Input and Output char array. I'm assuming it is expecting them to be at least big enough as the block size. </p> <p>What would be the best way to process all 16 byte blocks in a block cipher, and then also process the leftover data? </p>
[ { "answer_id": 141410, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 0, "selected": false, "text": " 01\n 02 02\n 03 03 03\n 04 04 04 04\n 05 05 05 05 05\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
141,411
<p>I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service. I'm running it with jdk 1.6.0_07.</p> <p>It runs when I start it with tomcat6.exe.</p> <p>I got a vague error in the System Event Log on Windows.</p> <p>The Apache Tomcat 6 service terminated with service-specific error 0 (0x0).</p>
[ { "answer_id": 10008471, "author": "lrkwz", "author_id": 509565, "author_profile": "https://Stackoverflow.com/users/509565", "pm_score": 2, "selected": false, "text": "service install tomcat-6.0.35 \n tomcat6w //ES/tomcat-6.0.35\n C:\\Program Files(x86)\\Java\\jre\\bin\\client\\jvm.dll" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
141,422
<p>Using assorted matrix math, I've solved a system of equations resulting in coefficients for a polynomial of degree 'n'</p> <pre><code>Ax^(n-1) + Bx^(n-2) + ... + Z </code></pre> <p>I then evaulate the polynomial over a given x range, essentially I'm rendering the polynomial curve. Now here's the catch. I've done this work in one coordinate system we'll call "data space". Now I need to present the same curve in another coordinate space. It is easy to transform input/output to and from the coordinate spaces, but the end user is only interested in the coefficients [A,B,....,Z] since they can reconstruct the polynomial on their own. How can I present a second set of coefficients [A',B',....,Z'] which represent the same shaped curve in a different coordinate system.</p> <p>If it helps, I'm working in 2D space. Plain old x's and y's. I also feel like this may involve multiplying the coefficients by a transformation matrix? Would it some incorporate the scale/translation factor between the coordinate systems? Would it be the inverse of this matrix? I feel like I'm headed in the right direction...</p> <p>Update: Coordinate systems are linearly related. Would have been useful info eh?</p>
[ { "answer_id": 141493, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 0, "selected": false, "text": "y = Ax^(n-1) + Bx^(n-2) + ... + Z\n 5x = x' and 10y = y'\n y' = 2Ax'^(n-1) + 2Bx'^(n-2) + ... + 10Z\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/287/" ]
141,432
<p>I have created a brand new project in XCode and have the following in my AppDelegate.py file:</p> <pre><code>from Foundation import * from AppKit import * class MyApplicationAppDelegate(NSObject): def applicationDidFinishLaunching_(self, sender): NSLog("Application did finish launching.") statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setTitle_(u"12%") statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) </code></pre> <p>However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.</p>
[ { "answer_id": 142162, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 4, "selected": true, "text": "MyApplicationAppDelegate statusItem.retain()" }, { "answer_id": 4379633, "author": "brandon", "author_id": 445251, "author_profile": "https://Stackoverflow.com/users/445251", "pm_score": 3, "selected": false, "text": "from Foundation import *\nfrom AppKit import *\nfrom PyObjCTools import AppHelper\n\nstart_time = NSDate.date()\n\n\nclass MyApplicationAppDelegate(NSObject):\n\n state = 'idle'\n\n def applicationDidFinishLaunching_(self, sender):\n NSLog(\"Application did finish launching.\")\n\n self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)\n self.statusItem.setTitle_(u\"Hello World\")\n self.statusItem.setHighlightMode_(TRUE)\n self.statusItem.setEnabled_(TRUE)\n\n # Get the timer going\n self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 5.0, self, 'tick:', None, True)\n NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)\n self.timer.fire()\n\n def sync_(self, notification):\n print \"sync\"\n\n def tick_(self, notification):\n print self.state\n\n\nif __name__ == \"__main__\":\n app = NSApplication.sharedApplication()\n delegate = MyApplicationAppDelegate.alloc().init()\n app.setDelegate_(delegate)\n AppHelper.runEventLoop()\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
141,441
<p>In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?</p> <pre><code>try{ if(myInfo.person.name == newInfo.person.name &amp;&amp; myInfo.person.address.street == newInfo.person.address.street &amp;&amp; myInfo.person.address.zip == newInfo.person.address.zip) { this.setAddress(newInfo); } } catch(e) {} // ignore missing args </code></pre>
[ { "answer_id": 141481, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "if( myInfo && newInfo \n && myInfo.person && newInfo.person\n && myInfo.person.address && newInfo.person.address\n && ( myInfo.person.name == newInfo.person.name\n && myInfo.person.address.street == newInfo.person.address.street\n && myInfo.person.address.zip == newInfo.person.address.zip\n )\n) \n{\n this.setAddress(newInfo);\n} \n" }, { "answer_id": 141530, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "//this will [NOT] do the reset in Internet Explorer\ntry{\n doErrorProneAction();\n} finally {\n //clean up\n this.reset();\n}\n\n//this [WILL] do the reset in Internet Explorer\ntry{\n doErrorProneAction();\n} catch(ex){\n //do nothing\n} finally {\n //clean up\n this.reset();\n}\n" }, { "answer_id": 142186, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 0, "selected": false, "text": "function pathEquals(obj1, obj2, path)\n{\n var properties = path.split(\".\");\n for (var i = 0, l = properties.length; i < l; i++)\n {\n var property = properties[i];\n if (obj1 === null || typeof obj1[property] == \"undefined\" ||\n obj2 === null || typeof obj2[property] == \"undefined\")\n {\n return false;\n }\n\n obj1 = obj1[property];\n obj2 = obj2[property];\n }\n\n return (obj1 === obj2);\n}\n\nif (pathEquals(myInfo, newInfo, \"person.name\") &&\n pathEquals(myInfo, newInfo, \"person.address.street\") &&\n pathEquals(myInfo, newInfo, \"person.address.zip\"))\n{\n this.setAddress(newInfo);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22816/" ]
141,449
<p>How do I create a file-like object (same duck type as File) with the contents of a string?</p>
[ { "answer_id": 141451, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 8, "selected": true, "text": ">>> from cStringIO import StringIO\n>>> f = StringIO('foo')\n>>> f.read()\n'foo'\n io f = io.StringIO('foo')\n" }, { "answer_id": 142251, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": "import io\n\nwith io.StringIO() as f:\n f.write('abcdef')\n print('gh', file=f)\n f.seek(0)\n print(f.read())\n 'abcdefgh'\n" }, { "answer_id": 49011746, "author": "guettli", "author_id": 633961, "author_profile": "https://Stackoverflow.com/users/633961", "pm_score": 4, "selected": false, "text": "io.StringIO(u'foo')\n" }, { "answer_id": 60083264, "author": "lensonp", "author_id": 5818920, "author_profile": "https://Stackoverflow.com/users/5818920", "pm_score": 3, "selected": false, "text": "from io import BytesIO\n\nstring_repr_of_file = 'header\\n byline\\n body\\n body\\n end'\nfunction_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
141,450
<p>I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:</p> <ul> <li>Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.</li> <li>Change events, but these only are triggered when the select box's value changes.</li> </ul> <p>Ideas?</p>
[ { "answer_id": 142285, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": -1, "selected": false, "text": "$('something').css('display')\n" }, { "answer_id": 142490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n<head>\n<title></title>\n<script language=\"javascript\" type=\"text/javascript\">\n\nvar STECHZ = {\n init : function() {\n STECHZ.setDisplayedInterval();\n },\n setDisplayedInterval : function() {\n STECHZ.isDisplayedInterval = window.setInterval(function(){\n if ( document.getElementById( \"mySelectMenu\" ).style.display == \"none\" ) {\n document.getElementById( \"myObjectToShow\" ).style.display = \"block\";\n } else {\n document.getElementById( \"myObjectToShow\" ).style.display = \"none\";\n }\n }, 1000);\n },\n isDisplayedInterval : null,\n toggleDisplay : function() {\n var mySelectMenu = document.getElementById( \"mySelectMenu\" );\n if ( mySelectMenu.style.display == \"none\" ) {\n mySelectMenu.style.display = \"block\";\n } else {\n mySelectMenu.style.display = \"none\";\n }\n }\n};\n\nwindow.onload = function(){\n\n STECHZ.init();\n\n}\n\n</script>\n</head>\n<body>\n <p>\n <a href=\"#\" onclick=\"STECHZ.toggleDisplay();return false;\">Click to toggle display.</a>\n </p>\n <select id=\"mySelectMenu\">\n <option>Option 1</option>\n <option>Option 2</option>\n <option>Option 3</option>\n </select>\n <div id=\"myObjectToShow\" style=\"display: none;\">Only show when mySelectMenu is not showing.</div>\n</body>\n</html>\n" }, { "answer_id": 1070950, "author": "Sampson", "author_id": 54680, "author_profile": "https://Stackoverflow.com/users/54680", "pm_score": 2, "selected": false, "text": "<select id=\"theSelectId\">\n <option value=\"dogs\">Dogs</option>\n <option value=\"birds\">Birds</option>\n <option value=\"cats\">Cats</option>\n <option value=\"horses\">Horses</option>\n</select>\n\n<div id=\"myDiv\" style=\"width:300px;height:100px;background:#cc0000\"></div>\n $(\"#theSelectId\").change(function(){\n if ($(this).val() != \"dogs\")\n $(\"#myDiv\").fadeOut();\n else\n $(\"#myDiv\").fadeIn();\n});\n" }, { "answer_id": 1112669, "author": "Your Friend Ken", "author_id": 86295, "author_profile": "https://Stackoverflow.com/users/86295", "pm_score": 2, "selected": false, "text": "<html>\n <head>\n <title>SandBox</title>\n </head>\n <body>\n <select id=\"ddlBox\">\n <option>Option 1</option>\n <option>Option 2</option>\n <option>Option 3</option>\n </select>\n <div id=\"divMsg\">some text or whatever goes here.</div>\n </body>\n</html>\n<script type=\"text/javascript\">\n window.onload = function() {\n var ddlBox = document.getElementById(\"ddlBox\");\n var divMsg = document.getElementById(\"divMsg\");\n if (ddlBox && divMsg) {\n ddlBox.onfocus = function() {\n divMsg.style.display = \"none\";\n }\n ddlBox.onblur = function() {\n divMsg.style.display = \"\";\n }\n divMsg.style.display = \"\";\n }\n }\n</script>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10290/" ]
141,452
<p>I've got a nice little class built that acts as a cache. Each item has an expiration TimeSpan or DateTime. Each time an attempt to access an item in the cache is made, the item's expiration is checked, and if it's expired, the item is removed from the cache and nothing is returned.</p> <p>That's great for objects that are accessed frequently, but if an item is put in the cache and never accessed again, it's never removed, even though it's expired.</p> <p>What's a good methodology for expiring such items from the cache?</p> <p>Should I have a background thread infinitely enumerating every item in the cache to check if it's expired?</p>
[ { "answer_id": 141483, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "private DateTime nextFlush;\npublic object getItem(object key)\n{\n DateTime now = DateTime.Now\n if (now > nextFlush)\n {\n Flush();\n nextFlush = now.AddMinutes(1)\n }\n return fetchItem(key);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
141,467
<p>I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?</p> <p>Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.</p>
[ { "answer_id": 141495, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 0, "selected": false, "text": "static class EnumerableExtensions\n{\n public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence)\n {\n foreach(var child in sequence)\n foreach(var item in child)\n yield return item;\n }\n}\n" }, { "answer_id": 141524, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "private void flattenList(IEnumerable<T> list)\n{\n foreach (T item in list)\n {\n masterList.Add(item);\n\n if (item.Count > 0)\n {\n this.flattenList(item);\n }\n }\n}\n" }, { "answer_id": 141528, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences)\n where TSequence : IEnumerable<TElement> \n{\n foreach (TSequence sequence in sequences)\n {\n foreach(TElement element in sequence)\n {\n yield return element;\n }\n }\n}\n static IEnumerable Flatten(params object[] objects)\n{\n // Can't easily get varargs behaviour with IEnumerable\n return Flatten((IEnumerable) objects);\n}\n\nstatic IEnumerable Flatten(IEnumerable enumerable)\n{\n foreach (object element in enumerable)\n {\n IEnumerable candidate = element as IEnumerable;\n if (candidate != null)\n {\n foreach (object nested in candidate)\n {\n yield return nested;\n }\n }\n else\n {\n yield return element;\n }\n }\n}\n" }, { "answer_id": 141539, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "enum1.SelectMany(\n a => a.SelectMany(\n b => b.SelectMany(\n c => c.Select(\n d => d.Name\n )\n )\n )\n);\n" }, { "answer_id": 229442, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "/// Traverses an object hierarchy and return a flattened list of elements\n/// based on a predicate.\n/// \n/// TSource: The type of object in your collection.</typeparam>\n/// source: The collection of your topmost TSource objects.</param>\n/// selectorFunction: A predicate for choosing the objects you want.\n/// getChildrenFunction: A function that fetches the child collection from an object.\n/// returns: A flattened list of objects which meet the criteria in selectorFunction.\npublic static IEnumerable<TSource> Map<TSource>(\n this IEnumerable<TSource> source,\n Func<TSource, bool> selectorFunction,\n Func<TSource, IEnumerable<TSource>> getChildrenFunction)\n{\n // Add what we have to the stack\n var flattenedList = source.Where(selectorFunction);\n\n // Go through the input enumerable looking for children,\n // and add those if we have them\n foreach (TSource element in source)\n {\n flattenedList = flattenedList.Concat(\n getChildrenFunction(element).Map(selectorFunction,\n getChildrenFunction)\n );\n }\n return flattenedList;\n}\n class Node\n{\n public int NodeId { get; set; }\n public int LevelId { get; set; }\n public IEnumerable<Node> Children { get; set; }\n\n public override string ToString()\n {\n return String.Format(\"Node {0}, Level {1}\", this.NodeId, this.LevelId);\n }\n}\n private IEnumerable<Node> GetNodes()\n{\n // Create a 3-level deep hierarchy of nodes\n Node[] nodes = new Node[]\n {\n new Node \n { \n NodeId = 1, \n LevelId = 1, \n Children = new Node[]\n {\n new Node { NodeId = 2, LevelId = 2, Children = new Node[] {} },\n new Node\n {\n NodeId = 3,\n LevelId = 2,\n Children = new Node[]\n {\n new Node { NodeId = 4, LevelId = 3, Children = new Node[] {} },\n new Node { NodeId = 5, LevelId = 3, Children = new Node[] {} }\n }\n }\n }\n },\n new Node { NodeId = 6, LevelId = 1, Children = new Node[] {} }\n };\n return nodes;\n}\n [Test]\npublic void Flatten_Nested_Heirachy()\n{\n IEnumerable<Node> nodes = GetNodes();\n var flattenedNodes = nodes.Map(\n p => true, \n (Node n) => { return n.Children; }\n );\n foreach (Node flatNode in flattenedNodes)\n {\n Console.WriteLine(flatNode.ToString());\n }\n\n // Make sure we only end up with 6 nodes\n Assert.AreEqual(6, flattenedNodes.Count());\n}\n Node 1, Level 1\nNode 6, Level 1\nNode 2, Level 2\nNode 3, Level 2\nNode 4, Level 3\nNode 5, Level 3\n [Test]\npublic void Only_Return_Nodes_With_Even_Numbered_Node_IDs()\n{\n IEnumerable<Node> nodes = GetNodes();\n var flattenedNodes = nodes.Map(\n p => (p.NodeId % 2) == 0, \n (Node n) => { return n.Children; }\n );\n foreach (Node flatNode in flattenedNodes)\n {\n Console.WriteLine(flatNode.ToString());\n }\n // Make sure we only end up with 3 nodes\n Assert.AreEqual(3, flattenedNodes.Count());\n}\n Node 6, Level 1\nNode 2, Level 2\nNode 4, Level 3\n" }, { "answer_id": 229515, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "SelectMany" }, { "answer_id": 310188, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "static IEnumerable Flatten(IEnumerable enumerable)\n{\n foreach (object element in enumerable)\n {\n IEnumerable candidate = element as IEnumerable;\n if (candidate != null)\n {\n foreach (object nested in Flatten(candidate))\n {\n yield return nested;\n }\n }\n else\n {\n yield return element;\n }\n }\n}\n #!/usr/bin/env python\n\ndef flatten(iterable):\n for item in iterable:\n if hasattr(item, '__iter__'):\n for nested in flatten(item):\n yield nested\n else:\n yield item\n\nif __name__ == '__main__':\n for item in flatten([1,[2, 3, [[4], 5]], 6, [[[7]]], [8]]):\n print(item, end=\" \")\n 1 2 3 4 5 6 7 8 \n" }, { "answer_id": 3738191, "author": "Richard Collette", "author_id": 107683, "author_profile": "https://Stackoverflow.com/users/107683", "pm_score": 1, "selected": false, "text": "<Extension()>\nPublic Function Flatten(Of T)(ByVal objects As Generic.IEnumerable(Of T), ByVal selector As Func(Of T, Generic.IEnumerable(Of T))) As Generic.IEnumerable(Of T)\n If(objects.Any()) Then\n Return objects.Union(objects.Select(selector).Where(e => e != null).SelectMany(e => e)).Flatten(selector))\n Else\n Return objects \n End If\nEnd Function\n public static class Extensions{\n public static IEnumerable<T> Flatten<T>(this IEnumerable<T> objects, Func<T, IEnumerable<T>> selector) where T:Component{\n if(objects.Any()){\n return objects.Union(objects.Select(selector).Where(e => e != null).SelectMany(e => e).Flatten(selector));\n }\n return objects;\n }\n}\n" }, { "answer_id": 17237709, "author": "marchewek", "author_id": 968745, "author_profile": "https://Stackoverflow.com/users/968745", "pm_score": 4, "selected": false, "text": "public static class IEnumerableExtensions\n{\n public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)\n {\n if (source == null) throw new ArgumentNullException(\"source\");\n if (selector == null) throw new ArgumentNullException(\"selector\");\n\n return !source.Any() ? source :\n source.Concat(\n source\n .SelectMany(i => selector(i).EmptyIfNull())\n .SelectManyRecursive(selector)\n );\n }\n\n public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)\n {\n return source ?? Enumerable.Empty<T>();\n }\n}\n public static class IEnumerableExtensions\n{\n public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)\n {\n if (source == null) throw new ArgumentNullException(\"source\");\n if (selector == null) throw new ArgumentNullException(\"selector\");\n\n foreach (T item in source)\n {\n yield return item;\n\n var children = selector(item);\n if (children == null)\n continue;\n\n foreach (T descendant in children.SelectManyRecursive(selector))\n {\n yield return descendant;\n }\n }\n }\n}\n IEnumerable source = source.EmptyIfNull(); return if (source != null) foreach .EmptyIfNull() SelectMany if (children == null) continue; foreach IEnumerable .Where public static class ScreenObjectExtensions\n{\n public static IEnumerable<IContentItemProxy> FindControls(this IScreenObject screen)\n {\n var model = screen.Details.GetModel();\n\n return model.GetChildItems()\n .SelectManyRecursive(c => c.GetChildItems())\n .OfType<IContentItemDefinition>()\n .Select(c => screen.FindControl(c.Name));\n }\n}\n" }, { "answer_id": 24747394, "author": "Aidin", "author_id": 1084235, "author_profile": "https://Stackoverflow.com/users/1084235", "pm_score": 1, "selected": false, "text": "var flattenlist = rootItem.Flatten(obj => obj.ChildItems, obj => obj.Id)\n public static class Extensions\n {\n /// <summary>\n /// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the\n /// items in the data structure regardless of the level of nesting.\n /// </summary>\n /// <typeparam name=\"T\">Type of the recursive data structure</typeparam>\n /// <param name=\"source\">Source element</param>\n /// <param name=\"childrenSelector\">a function that returns the children of a given data element of type T</param>\n /// <param name=\"keySelector\">a function that returns a key value for each element</param>\n /// <returns>a faltten list of all the items within recursive data structure of T</returns>\n public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source,\n Func<T, IEnumerable<T>> childrenSelector,\n Func<T, object> keySelector) where T : class\n {\n if (source == null)\n throw new ArgumentNullException(\"source\");\n if (childrenSelector == null)\n throw new ArgumentNullException(\"childrenSelector\");\n if (keySelector == null)\n throw new ArgumentNullException(\"keySelector\");\n var stack = new Stack<T>( source);\n var dictionary = new Dictionary<object, T>();\n while (stack.Any())\n {\n var currentItem = stack.Pop();\n var currentkey = keySelector(currentItem);\n if (dictionary.ContainsKey(currentkey) == false)\n {\n dictionary.Add(currentkey, currentItem);\n var children = childrenSelector(currentItem);\n if (children != null)\n {\n foreach (var child in children)\n {\n stack.Push(child);\n }\n }\n }\n yield return currentItem;\n }\n }\n\n /// <summary>\n /// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the\n /// items in the data structure regardless of the level of nesting.\n /// </summary>\n /// <typeparam name=\"T\">Type of the recursive data structure</typeparam>\n /// <param name=\"source\">Source element</param>\n /// <param name=\"childrenSelector\">a function that returns the children of a given data element of type T</param>\n /// <param name=\"keySelector\">a function that returns a key value for each element</param>\n /// <returns>a faltten list of all the items within recursive data structure of T</returns>\n public static IEnumerable<T> Flatten<T>(this T source, \n Func<T, IEnumerable<T>> childrenSelector,\n Func<T, object> keySelector) where T: class\n {\n return Flatten(new [] {source}, childrenSelector, keySelector);\n }\n }\n" }, { "answer_id": 30325216, "author": "Yasin Kilicdere", "author_id": 410448, "author_profile": "https://Stackoverflow.com/users/410448", "pm_score": 2, "selected": false, "text": "public static class MyExtentions\n{\n public static IEnumerable<T> RecursiveSelector<T>(this IEnumerable<T> nodes, Func<T, IEnumerable<T>> selector)\n {\n if(nodes.Any() == false)\n {\n return nodes; \n }\n\n var descendants = nodes\n .SelectMany(selector)\n .RecursiveSelector(selector);\n\n return nodes.Concat(descendants);\n } \n}\n var ar = new[]\n{\n new Node\n {\n Name = \"1\",\n Chilren = new[]\n {\n new Node\n {\n Name = \"11\",\n Children = new[]\n {\n new Node\n {\n Name = \"111\",\n \n }\n }\n }\n }\n }\n};\n\nvar flattened = ar.RecursiveSelector(x => x.Children).ToList();\n" }, { "answer_id": 49847583, "author": "Casey Plummer", "author_id": 704532, "author_profile": "https://Stackoverflow.com/users/704532", "pm_score": 2, "selected": false, "text": " public static IEnumerable<TNode> Flatten<TNode>(\n this IEnumerable<TNode> nodes, \n Func<TNode, bool> filterBy = null,\n Func<TNode, IEnumerable<TNode>> selectChildren = null\n )\n {\n if (nodes == null) yield break;\n if (filterBy != null) nodes = nodes.Where(filterBy);\n\n foreach (var node in nodes)\n {\n yield return node;\n\n var children = (selectChildren == null)\n ? node as IEnumerable<TNode>\n : selectChildren(node);\n\n if (children == null) continue;\n\n foreach (var child in children.Flatten(filterBy, selectChildren))\n {\n yield return child;\n }\n }\n }\n // With filter predicate, with selection function\nvar flatList = nodes.Flatten(n => n.IsDeleted == false, n => n.Children);\n" }, { "answer_id": 50152534, "author": "FindOutIslamNow", "author_id": 7429464, "author_profile": "https://Stackoverflow.com/users/7429464", "pm_score": 0, "selected": false, "text": "class PageViewModel { \n public IEnumerable<PageViewModel> ChildrenPages { get; set; } \n}\n\nFunc<IEnumerable<PageViewModel>, IEnumerable<PageViewModel>> concatAll = null;\nconcatAll = list => list.SelectMany(l => l.ChildrenPages.Any() ? \n concatAll(l.ChildrenPages).Union(new[] { l }) : new[] { l });\n\nvar allPages = concatAll(source).ToArray();\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049/" ]
141,487
<pre><code>class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() </code></pre> <p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
[ { "answer_id": 141505, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": 2, "selected": false, "text": "slug = models.SlugField(prepopulate_from=('title',))\n" }, { "answer_id": 141554, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 7, "selected": true, "text": "prepopulated_fields = {'slug': ('title',), }\n slugify |slugify" }, { "answer_id": 141947, "author": "AdamKG", "author_id": 16361, "author_profile": "https://Stackoverflow.com/users/16361", "pm_score": 3, "selected": false, "text": ".save() prepopulated_fields" }, { "answer_id": 55772264, "author": "Andreas Bergström", "author_id": 1202214, "author_profile": "https://Stackoverflow.com/users/1202214", "pm_score": 3, "selected": false, "text": "class ArticleAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"title\",)}\n\nadmin.site.register(Article, ArticleAdmin)\n class Article(Model):\n title = CharField(max_length=200)\n slug = AutoSlugField(populate_from='title')\n class Article(Model):\n title = CharField(max_length=200)\n slug = SlugField()\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super().save(*args, **kwargs)\n" }, { "answer_id": 71843695, "author": "Iasmini Gomes", "author_id": 2638015, "author_profile": "https://Stackoverflow.com/users/2638015", "pm_score": 1, "selected": false, "text": "from django.db import models\n\n\nclass Place:\n name = models.CharField(max_length=50)\n slug_name = models.SlugField(max_length=50)\n from django.db.models.signals import pre_save\nfrom django.dispatch import receiver\nfrom django.template.defaultfilters import slugify as django_slugify\n\nfrom v1 import models\n\n\n@receiver(pre_save, sender=models.Place)\ndef validate_slug_name(sender, instance: models.Place, **kwargs):\n instance.slug_name = django_slugify(instance.name)\n" }, { "answer_id": 72656749, "author": "Epsilon36170", "author_id": 16734290, "author_profile": "https://Stackoverflow.com/users/16734290", "pm_score": 0, "selected": false, "text": "prepopulated_fields = {'slug': ('title',), }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ]
141,498
<p>Java has some very good open source static analysis tools such as <a href="http://findbugs.sf.net/" rel="nofollow noreferrer">FindBugs</a>, <a href="http://checkstyle.sf.net/" rel="nofollow noreferrer">Checkstyle</a> and <a href="http://pmd.sf.net/" rel="nofollow noreferrer">PMD</a>. Those tools are easy to use, very helpful, runs on multiple operating systems and <em>free</em>.</p> <p>Commercial C++ static analysis products are available. Although having such products are great, the cost is just way too much for students and it is usually rather hard to get trial version.</p> <p>The alternative is to find open source C++ static analysis tools that will run on multiple platforms (Windows and Unix). By using an open source tool, it could be modified to fit certain needs. Finding the tools has not been easy task.</p> <p>Below is a short list of C++ static analysis tools that were found or suggested by others.</p> <ul> <li>C++ Check <a href="http://sf.net/projects/cppcheck/" rel="nofollow noreferrer">http://sf.net/projects/cppcheck/</a></li> <li>Oink <a href="http://danielwilkerson.com/oink/index.html" rel="nofollow noreferrer">http://danielwilkerson.com/oink/index.html</a></li> <li>C and C++ Code Counter <a href="http://sourceforge.net/projects/cccc/" rel="nofollow noreferrer">http://sourceforge.net/projects/cccc/</a></li> <li>Splint (from answers)</li> <li>Mozilla's Pork (from answers) (This is now part of Oink)</li> <li>Mozilla's Dehydra (from answers)</li> <li>Use option <code>-Weffc++</code> for GNU g++ (from answers)</li> </ul> <p>What are some <strong>other</strong> portable open source C++ static analysis tools that anyone knows of and can be recommended?</p> <p>Some related links.</p> <ul> <li><a href="http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis</a></li> <li><a href="http://www.chris-lott.org/resources/cmetrics/" rel="nofollow noreferrer">http://www.chris-lott.org/resources/cmetrics/</a></li> <li><a href="https://stackoverflow.com/questions/93260/a-free-tool-to-check-cc-source-code-against-a-set-of-coding-standards">A free tool to check C/C++ source code against a set of coding standards?</a></li> <li><a href="http://spinroot.com/static/" rel="nofollow noreferrer">http://spinroot.com/static/</a></li> <li><a href="https://stackoverflow.com/questions/2873/choosing-a-static-code-analysis-tool">Choosing a static code analysis tool</a></li> </ul>
[ { "answer_id": 141564, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 2, "selected": false, "text": "brew install splint\n" }, { "answer_id": 143202, "author": "user15071", "author_id": 15071, "author_profile": "https://Stackoverflow.com/users/15071", "pm_score": 3, "selected": false, "text": "cl /analyze Sample.cpp\n" }, { "answer_id": 842234, "author": "Soo Wei Tan", "author_id": 77915, "author_profile": "https://Stackoverflow.com/users/77915", "pm_score": 6, "selected": false, "text": "brew install cppcheck\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22807/" ]
141,499
<p>I'm not sure if this even exists or not, so I figured I would tap the wisdom of others.. </p> <p>I was wondering if there are any Java libraries out there that can be used to validate a SQL query's syntax. I know that there are many deviations from common SQL spec, so it would probably only work against something like SQL:2006, but that would certainly suffice. </p> <p>My goal is to use this for unit-testing purposes without needing to attempt the execution against the DB. I know it's of limited use, but it would still be useful. </p> <p>Thanks!</p>
[ { "answer_id": 141713, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "org.apache.derby.impl.sql" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812/" ]
141,513
<p>I personally use <a href="http://php.net/var_dump" rel="nofollow noreferrer"><code>var_dump</code></a>, but lots of people like <a href="http://php.net/print_r" rel="nofollow noreferrer"><code>print_r</code></a>. </p> <p>What does everyone use? Pros and Cons?</p> <p>Does someone have a special home brew function of their own?</p>
[ { "answer_id": 141516, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "print_r() var_dump $obj = (object) array(1, 2, 3);\n\n// output of var_dump:\nobject(stdClass)#1 (3) {\n [0]=>\n int(1)\n [1]=>\n int(2)\n [2]=>\n int(3)\n}\n\n// output of print_r\nstdClass Object\n(\n [0] => 1\n [1] => 2\n [2] => 3\n) \n" }, { "answer_id": 141563, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "function show($array)\n{\n echo '<pre>';\n print_r($array);\n echo '</pre>';\n}\n\nfunction prn($var)\n{\n echo '<br/>' . $var . '<br/>';\n}\n" }, { "answer_id": 141588, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "// Primitive debug message storage\n// $level = \"Info\", \"Warn\", \"Error\", \"Title\"\nfunction DebugPrint($toDump, $level = \"Info\") {\n global $debugMode, $debugDump, $debugCount;\n\n if ($debugMode != 'N') {\n $debugDump[$debugCount++] = \"<div class='Dbg$level'>\" . $toDump . \"</div>\\n\";\n }\n}\n\n// Initialize debug information collection\n$debugMode = 'N'; // N=no, desactivated, P=dump to Web page, F=dump to file\n$debugSavePath = 'C:\\www\\App\\log_debug.txt'; // If mode F\n$debugDump = array();\n$debugCount = 0;\n\n// Primitive debug message dump\nfunction DebugDump() {\n global $debugMode, $debugSavePath, $debugDump, $debugCount;\n\n if ($debugMode == 'F') {\n $fp = fopen($debugSavePath, \"a\"); #open for writing\n }\n if ($debugCount > 0) {\n switch ($debugMode) {\n case 'P':\n echo '<div style=\"color: red; background: #8FC; font-size: 24px;\">Debug:<br />\n';\n for ($i = 0; $i < $debugCount; $i++) {\n echo $debugDump[$i];\n }\n echo '</div>\n';\n break;\n case 'F':\n for ($i = 0; $i < $debugCount; $i++) {\n fputs($fp, $debugDump[$i]);\n }\n break;\n//~ default:\n//~ echo \"debugMode = $debugMode<br />\\n\";\n }\n }\n if ($fp != null) {\n fputs($fp, \"-----\\n\");\n fclose($fp);\n }\n}\n\n// Pre array dump\nfunction DebugArrayPrint($array) {\nglobal $debugMode;\n\n if ($debugMode != 'N') {\n return \"<pre class='ArrayPrint'>\" . print_r($array, true) . \"</pre>\";\n } else return \"\"; // Gain some microseconds...\n}\n" }, { "answer_id": 141597, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 1, "selected": false, "text": "ob_start();\nvar_dump($this); echo $that; print_r($stuff);\n$out = ob_get_contents();\nob_end_clean();\n\nuser_error($out);\n" }, { "answer_id": 142258, "author": "Meisner", "author_id": 22827, "author_profile": "https://Stackoverflow.com/users/22827", "pm_score": 1, "selected": false, "text": "function dump($val) {\n echo '<pre>'.var_export($val,true).'</pre>';\n return $val;\n}\n $a=2+dump(2*2);\n" }, { "answer_id": 143276, "author": "user22960", "author_id": 22960, "author_profile": "https://Stackoverflow.com/users/22960", "pm_score": 1, "selected": false, "text": "header('X-eleg:'.serialize($yourstuff));" }, { "answer_id": 299692, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 0, "selected": false, "text": "<pre>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
141,519
<p>We have a pair of applications. One is written in C# and uses something like:</p> <pre><code> string s = "alpha\r\nbeta\r\ngamma\r\ndelta"; // Actually there's wrapper code here to make sure this works. System.Windows.Forms.Clipboard.SetDataObject(s, true); </code></pre> <p>To put a list of items onto the clipboard. Another application (in WinBatch) then picks up the list using a ClipGet() function. (We use the clipboard functions to give people the option of editing the list in notepad or something, without having to actually cut-and-paste every time.)</p> <p>In this particular environment, we have many users on one system via Citrix. Many using these pairs of programs.</p> <p>Just <em>one</em> user is having the problem where the line delimiters in the text are getting switched from CRLF to LF somewhere between the SetDataObject() and the CLipGet(). I could explain this in a mixed Unix/Windows environment, but there is no Unix here. No unix-y utilities anywhere near this system either. Other users on the same server, no problems at all. It's like something in Windows/Citrix is being "helpful" when we really don't want it, but just for this one guy.</p> <p>Ideas?</p>
[ { "answer_id": 141516, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "print_r() var_dump $obj = (object) array(1, 2, 3);\n\n// output of var_dump:\nobject(stdClass)#1 (3) {\n [0]=>\n int(1)\n [1]=>\n int(2)\n [2]=>\n int(3)\n}\n\n// output of print_r\nstdClass Object\n(\n [0] => 1\n [1] => 2\n [2] => 3\n) \n" }, { "answer_id": 141563, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "function show($array)\n{\n echo '<pre>';\n print_r($array);\n echo '</pre>';\n}\n\nfunction prn($var)\n{\n echo '<br/>' . $var . '<br/>';\n}\n" }, { "answer_id": 141588, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "// Primitive debug message storage\n// $level = \"Info\", \"Warn\", \"Error\", \"Title\"\nfunction DebugPrint($toDump, $level = \"Info\") {\n global $debugMode, $debugDump, $debugCount;\n\n if ($debugMode != 'N') {\n $debugDump[$debugCount++] = \"<div class='Dbg$level'>\" . $toDump . \"</div>\\n\";\n }\n}\n\n// Initialize debug information collection\n$debugMode = 'N'; // N=no, desactivated, P=dump to Web page, F=dump to file\n$debugSavePath = 'C:\\www\\App\\log_debug.txt'; // If mode F\n$debugDump = array();\n$debugCount = 0;\n\n// Primitive debug message dump\nfunction DebugDump() {\n global $debugMode, $debugSavePath, $debugDump, $debugCount;\n\n if ($debugMode == 'F') {\n $fp = fopen($debugSavePath, \"a\"); #open for writing\n }\n if ($debugCount > 0) {\n switch ($debugMode) {\n case 'P':\n echo '<div style=\"color: red; background: #8FC; font-size: 24px;\">Debug:<br />\n';\n for ($i = 0; $i < $debugCount; $i++) {\n echo $debugDump[$i];\n }\n echo '</div>\n';\n break;\n case 'F':\n for ($i = 0; $i < $debugCount; $i++) {\n fputs($fp, $debugDump[$i]);\n }\n break;\n//~ default:\n//~ echo \"debugMode = $debugMode<br />\\n\";\n }\n }\n if ($fp != null) {\n fputs($fp, \"-----\\n\");\n fclose($fp);\n }\n}\n\n// Pre array dump\nfunction DebugArrayPrint($array) {\nglobal $debugMode;\n\n if ($debugMode != 'N') {\n return \"<pre class='ArrayPrint'>\" . print_r($array, true) . \"</pre>\";\n } else return \"\"; // Gain some microseconds...\n}\n" }, { "answer_id": 141597, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 1, "selected": false, "text": "ob_start();\nvar_dump($this); echo $that; print_r($stuff);\n$out = ob_get_contents();\nob_end_clean();\n\nuser_error($out);\n" }, { "answer_id": 142258, "author": "Meisner", "author_id": 22827, "author_profile": "https://Stackoverflow.com/users/22827", "pm_score": 1, "selected": false, "text": "function dump($val) {\n echo '<pre>'.var_export($val,true).'</pre>';\n return $val;\n}\n $a=2+dump(2*2);\n" }, { "answer_id": 143276, "author": "user22960", "author_id": 22960, "author_profile": "https://Stackoverflow.com/users/22960", "pm_score": 1, "selected": false, "text": "header('X-eleg:'.serialize($yourstuff));" }, { "answer_id": 299692, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 0, "selected": false, "text": "<pre>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8173/" ]
141,525
<p>I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...</p> <p>At a core level, what does bit-shifting (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>, <code>&gt;&gt;&gt;</code>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.</p>
[ { "answer_id": 141576, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 8, "selected": false, "text": "0110110\n 1101100\n memoryOffset = (row * 320) + column\n (row * 320) = (row * 256) + (row * 64)\n (row * 320) = (row << 8) + (row << 6)\n memoryOffset = ((row << 8) + (row << 6)) + column\n mov ax, 320; 2 cycles\nmul word [row]; 22 CPU Cycles\nmov di,ax; 2 cycles\nadd di, [column]; 2 cycles\n; di = [row]*320 + [column]\n\n; 16-bit addressing mode limitations:\n; [di] is a valid addressing mode, but [ax] isn't, otherwise we could skip the last mov\n mov ax, [row]; 2 cycles\nmov di, ax; 2\nshl ax, 6; 2\nshl di, 8; 2\nadd di, ax; 2 (320 = 256+64)\nadd di, [column]; 2\n; di = [row]*(256+64) + [column]\n imul edi, [row], 320 ; 3 cycle latency from [row] being ready\nadd edi, [column] ; 1 cycle latency (from [column] and edi being ready).\n; edi = [row]*(256+64) + [column], in 4 cycles from [row] being ready.\n mov edi, [row]\nshl edi, 6 ; row*64. 1 cycle latency\nlea edi, [edi + edi*4] ; row*(64 + 64*4). 1 cycle latency\nadd edi, [column] ; 1 cycle latency from edi and [column] both being ready\n; edi = [row]*(256+64) + [column], in 3 cycles from [row] being ready.\n return 320*row + col; LEA add // Byte1: 11110000\n// Byte2: 00001111\n\nInt16 value = ((byte)(Byte1 >> 8) | Byte2));\n\n// value = 000011111110000;\n struct" }, { "answer_id": 141645, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 5, "selected": false, "text": "char x = -1;\nx >> 1;\n" }, { "answer_id": 141873, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 12, "selected": true, "text": ">> >>> << int long short byte char int int <<< >> >> int 00000000 00000000 00000000 00000110\n 6 << 1 00000000 00000000 00000000 00001100\n 6 << 1 6 * 2 6 << 3 6 * 8 3,758,096,384 << 1 11100000 00000000 00000000 00000000\n 11000000 00000000 00000000 00000000\n 00000000 00000000 00000000 00001100\n 12 >>> 1 00000000 00000000 00000000 00000110\n 00111000 00000000 00000000 00000110\n 939,524,102 << 4 10000000 00000000 00000000 01100000\n (939,524,102 << 4) >>> 4 00001000 00000000 00000000 00000110\n 10000000 00000000 00000000 01100000\n 11111000 00000000 00000000 00000110\n" }, { "answer_id": 142335, "author": "robottobor", "author_id": 10184, "author_profile": "https://Stackoverflow.com/users/10184", "pm_score": 7, "selected": false, "text": " bit | 15| 14| 13| 12| 11| 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |\n | Blue | Green | Red |\n #define GREEN_MASK 0x7E0\n #define GREEN_OFFSET 5\n\n // Read green\n uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;\n #define GREEN_MASK 0x7E0\n uint16_t green = (pixel & GREEN_MASK) ...;\n uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;\n #define GREEN_OFFSET 5 i <<= x; // i *= 2^x;\n i >>= y; // i /= 2^y;\n" }, { "answer_id": 29366874, "author": "Basti Funck", "author_id": 2043922, "author_profile": "https://Stackoverflow.com/users/2043922", "pm_score": 6, "selected": false, "text": " Pixel-Color Value in Hex: B9B9B900\n Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000\n Red Green Blue Alpha\n Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000\n Red Green Blue Alpha\n color : 10111001 10111001 10111001 00000000\n green_mask : 00000000 11111111 00000000 00000000\n\n masked_color = color & green_mask\n\n masked_color: 00000000 10111001 00000000 00000000\n & green_value = masked_color >>> 16\n Pixels-Green Value in Hex: 000000B9\n Pixels-Green Value in Binary: 00000000 00000000 00000000 10111001\n Pixels-Green Value in Decimal: 185\n jpg png" }, { "answer_id": 32271993, "author": "Patrick Monkelban", "author_id": 4585281, "author_profile": "https://Stackoverflow.com/users/4585281", "pm_score": 3, "selected": false, "text": "(long) 4 >> 65\n (long) 4 >> (65 % 64)\n" }, { "answer_id": 39987901, "author": "HoneyBeer", "author_id": 2050095, "author_profile": "https://Stackoverflow.com/users/2050095", "pm_score": 5, "selected": false, "text": "n = n*2 n = n<<1 n = n/2 n = n>>1 !(n & (n-1)) n n |= (1 << x) x&1 == 0 x ^ (1<<n)" }, { "answer_id": 55883733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "# Basic bit operations\n# Integer to binary\nprint(bin(10))\n\n# Binary to integer\nprint(int('1010', 2))\n\n# Multiplying x with 2 .... x**2 == x << 1\nprint(200 << 1)\n\n# Dividing x with 2 .... x/2 == x >> 1\nprint(200 >> 1)\n\n# Modulo x with 2 .... x % 2 == x & 1\nif 20 & 1 == 0:\n print(\"20 is a even number\")\n\n# Check if n is power of 2: check !(n & (n-1))\nprint(not(33 & (33-1)))\n\n# Getting xth bit of n: (n >> x) & 1\nprint((10 >> 2) & 1) # Bin of 10 == 1010 and second bit is 0\n\n# Toggle nth bit of x : x^(1 << n)\n# take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)\nprint(10^(1 << 2))\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
141,545
<p>Let's say I have a class that has a member called data which is a list. </p> <p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p> <p>What's your technique for doing this?</p> <p>Do you just check the type by looking at <code>__class__</code>?</p> <p>Is there some trick I might be missing?</p> <p>I'm used to C++ where overloading by argument type is easy. </p>
[ { "answer_id": 141565, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "def __init__ (self, filename):\n if isinstance (filename, basestring):\n # filename is a string\n else:\n # try to convert to a list\n self.path = list (filename)\n" }, { "answer_id": 141570, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "isinstance self.data = data if isinstance(data, list) else self.parse(data)\n" }, { "answer_id": 141571, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 2, "selected": false, "text": "isinstance(...)\n isinstance(object, class-or-type-or-tuple) -> bool\n\n Return whether an object is an instance of a class or of a subclass thereof.\n With a type as second argument, return whether that is the object's type.\n The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n isinstance(x, A) or isinstance(x, B) or ... (etc.).\n" }, { "answer_id": 141700, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": -1, "selected": false, "text": "class MyData:\n def __init__(self, data):\n self.myList = []\n if isinstance(data, tuple):\n for i in data:\n self.myList.append(i)\n else:\n self.myList = data\n\n def GetData(self):\n print self.myList\n" }, { "answer_id": 141777, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 10, "selected": true, "text": ">>> class MyData:\n... def __init__(self, data):\n... \"Initialize MyData from a sequence\"\n... self.data = data\n... \n... @classmethod\n... def fromfilename(cls, filename):\n... \"Initialize MyData from a file\"\n... data = open(filename).readlines()\n... return cls(data)\n... \n... @classmethod\n... def fromdict(cls, datadict):\n... \"Initialize MyData from a dict's items\"\n... return cls(datadict.items())\n... \n>>> MyData([1, 2, 3]).data\n[1, 2, 3]\n>>> MyData.fromfilename(\"/tmp/foobar\").data\n['foo\\n', 'bar\\n', 'baz\\n']\n>>> MyData.fromdict({\"spam\": \"ham\"}).data\n[('spam', 'ham')]\n isinstance(x, basestring)" }, { "answer_id": 212130, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 5, "selected": false, "text": "read def read(self, str=None, filename=None, addr=0):\n \"\"\" Read binary data and return a store object. The data\n store is also saved in the interal 'data' attribute.\n\n The data can either be taken from a string (str \n argument) or a file (provide a filename, which will \n be read in binary mode). If both are provided, the str \n will be used. If neither is provided, an ArgumentError \n is raised.\n \"\"\"\n if str is None:\n if filename is None:\n raise ArgumentError('Please supply a string or a filename')\n\n file = open(filename, 'rb')\n str = file.read()\n file.close()\n ...\n ... # rest of code\n obj.read(filename=\"blob.txt\")\n obj.read(str=\"\\x34\\x55\")\n" }, { "answer_id": 10218436, "author": "Ben", "author_id": 1322906, "author_profile": "https://Stackoverflow.com/users/1322906", "pm_score": 4, "selected": false, "text": "class MyData:\n def __init__(string=None,list=None):\n if string is not None:\n #do stuff\n elif list is not None:\n #do other stuff\n else:\n #make data empty\n MyData(astring)\nMyData(None, alist)\nMyData()\n" }, { "answer_id": 23415425, "author": "ankostis", "author_id": 548792, "author_profile": "https://Stackoverflow.com/users/548792", "pm_score": -1, "selected": false, "text": "class AutoList:\ndef __init__(self, inp):\n try: ## Assume an opened-file...\n self.data = inp.read()\n except AttributeError:\n try: ## Assume an existent filename...\n with open(inp, 'r') as fd:\n self.data = fd.read()\n except:\n self.data = inp ## Who cares what that might be?\n" }, { "answer_id": 26018762, "author": "Fydo", "author_id": 385025, "author_profile": "https://Stackoverflow.com/users/385025", "pm_score": -1, "selected": false, "text": "class MyClass:\n _data = []\n __init__(self,data=None):\n # do init stuff\n if not data: return\n self._data = list(data) # list() copies the list, instead of pointing to it.\n MyClass() MyClass([1,2,3])" }, { "answer_id": 49936625, "author": "carton.swing", "author_id": 5765458, "author_profile": "https://Stackoverflow.com/users/5765458", "pm_score": 5, "selected": false, "text": "import time\n\n\nclass Date(metaclass=MultipleMeta):\n def __init__(self, year:int, month:int, day:int):\n self.year = year\n self.month = month\n self.day = day\n\n def __init__(self):\n t = time.localtime()\n self.__init__(t.tm_year, t.tm_mon, t.tm_mday)\n >>> d = Date(2012, 12, 21)\n>>> d.year\n2012\n>>> e = Date()\n>>> e.year\n2018\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179/" ]
141,560
<p>I have a loop that looks something like this:</p> <pre><code>for (int i = 0; i &lt; max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } </code></pre> <p>This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return <code>null</code> if there is an error, so I put the loop inside a <code>try...catch</code> block, like this:</p> <pre><code>try { for (int i = 0; i &lt; max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } } catch (NumberFormatException ex) { return null; } </code></pre> <p>But then I also thought of putting the <code>try...catch</code> block inside the loop, like this:</p> <pre><code>for (int i = 0; i &lt; max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum; } </code></pre> <p>Is there any reason, performance or otherwise, to prefer one over the other?</p> <hr> <p><strong>Edit:</strong> The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?</p>
[ { "answer_id": 141589, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 6, "selected": false, "text": "class Parsing\n{\n public static Float MyParseFloat(string inputValue)\n {\n try\n {\n return Float.parseFloat(inputValue);\n }\n catch ( NumberFormatException e )\n {\n return null;\n }\n }\n\n // .... your code\n for(int i = 0; i < max; i++) \n {\n String myString = ...;\n Float myNum = Parsing.MyParseFloat(myString);\n if ( myNum == null ) return;\n myFloats[i] = (float) myNum;\n }\n}\n" }, { "answer_id": 149610, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 7, "selected": true, "text": "public class Main {\n\n private static final int NUM_TESTS = 100;\n private static int ITERATIONS = 1000000;\n // time counters\n private static long inTime = 0L;\n private static long aroundTime = 0L;\n\n public static void main(String[] args) {\n for (int i = 0; i < NUM_TESTS; i++) {\n test();\n ITERATIONS += 1; // so the tests don't always return the same number\n }\n System.out.println(\"Inside loop: \" + (inTime/1000000.0) + \" ms.\");\n System.out.println(\"Around loop: \" + (aroundTime/1000000.0) + \" ms.\");\n }\n public static void test() {\n aroundTime += testAround();\n inTime += testIn();\n }\n public static long testIn() {\n long start = System.nanoTime();\n Integer i = tryInLoop();\n long ret = System.nanoTime() - start;\n System.out.println(i); // don't optimize it away\n return ret;\n }\n public static long testAround() {\n long start = System.nanoTime();\n Integer i = tryAroundLoop();\n long ret = System.nanoTime() - start;\n System.out.println(i); // don't optimize it away\n return ret;\n }\n public static Integer tryInLoop() {\n int count = 0;\n for (int i = 0; i < ITERATIONS; i++) {\n try {\n count = Integer.parseInt(Integer.toString(count)) + 1;\n } catch (NumberFormatException ex) {\n return null;\n }\n }\n return count;\n }\n public static Integer tryAroundLoop() {\n int count = 0;\n try {\n for (int i = 0; i < ITERATIONS; i++) {\n count = Integer.parseInt(Integer.toString(count)) + 1;\n }\n return count;\n } catch (NumberFormatException ex) {\n return null;\n }\n }\n}\n" }, { "answer_id": 155000, "author": "Matt N", "author_id": 20605, "author_profile": "https://Stackoverflow.com/users/20605", "pm_score": 4, "selected": false, "text": "public static void main(String[] args) {\n String[] myNumberStrings = new String[] {\"1.2345\", \"asdf\", \"2.3456\"};\n ArrayList asNumbers = parseAll(myNumberStrings);\n}\n\npublic static ArrayList parseAll(String[] numberStrings){\n ArrayList myFloats = new ArrayList();\n\n for(int i = 0; i < numberStrings.length; i++){\n myFloats.add(new Float(numberStrings[i]));\n }\n return myFloats;\n}\n public static ArrayList parseAll1(String[] numberStrings){\n ArrayList myFloats = new ArrayList();\n try{\n for(int i = 0; i < numberStrings.length; i++){\n myFloats.add(new Float(numberStrings[i]));\n }\n } catch (NumberFormatException nfe){\n //fail on any error\n return null;\n }\n return myFloats;\n}\n public static ArrayList parseAll2(String[] numberStrings){\n ArrayList myFloats = new ArrayList();\n\n for(int i = 0; i < numberStrings.length; i++){\n try{\n myFloats.add(new Float(numberStrings[i]));\n } catch (NumberFormatException nfe){\n //don't add just this one\n }\n }\n\n return myFloats;\n}\n" }, { "answer_id": 156325, "author": "Kyle Dyer", "author_id": 24011, "author_profile": "https://Stackoverflow.com/users/24011", "pm_score": 1, "selected": false, "text": "try {\n // parse\n} catch (NumberFormatException nfe){\n throw new RuntimeException(\"Could not parse as a Float: [\" + myString + \n \"] found at index: \" + i, nfe);\n} \n" }, { "answer_id": 172153, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "0.02c try-catch catch NumberFormatException try-catch catch return null" }, { "answer_id": 177556, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 1, "selected": false, "text": "for(int i = 0; i < max; i++) {\n String myString = ...;\n try {\n float myNum = Float.parseFloat(myString);\n myFloats[i] = myNum;\n } catch (NumberFormatException ex) {\n --i;\n }\n}\n" }, { "answer_id": 188076, "author": "Ogre Psalm33", "author_id": 13140, "author_profile": "https://Stackoverflow.com/users/13140", "pm_score": 1, "selected": false, "text": "try {\n for(int i = 0; i < max; i++) {\n String myString = ...;\n float myNum = Float.parseFloat(myString);\n dbConnection.update(\"MY_FLOATS\",\"INDEX\",i,\"VALUE\",myNum);\n }\n} catch (NumberFormatException ex) {\n return null;\n} finally {\n dbConnection.release(); // Always release DB connection, even if transaction fails.\n}\n" }, { "answer_id": 33435986, "author": "seBaka28", "author_id": 4252577, "author_profile": "https://Stackoverflow.com/users/4252577", "pm_score": 4, "selected": false, "text": "Integer j = 0;\n try {\n while (true) {\n ++j;\n\n if (j == 20) { throw new Exception(); }\n if (j%4 == 0) { System.out.println(j); }\n if (j == 40) { break; }\n }\n } catch (Exception e) {\n System.out.println(\"in catch block\");\n }\n Integer i = 0;\n while (true) {\n try {\n ++i;\n\n if (i == 20) { throw new Exception(); }\n if (i%4 == 0) { System.out.println(i); }\n if (i == 40) { break; }\n\n } catch (Exception e) { System.out.println(\"in catch block\"); }\n }\n 4\n8\n12 \n16\nin catch block\n 4\n8\n12\n16\nin catch block\n24\n28\n32\n36\n40\n" }, { "answer_id": 54680065, "author": "surendrapanday", "author_id": 9851598, "author_profile": "https://Stackoverflow.com/users/9851598", "pm_score": 2, "selected": false, "text": "PLEASE AVOID USING TRY-CATCH BLOCKS IN LOOPS" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13531/" ]
141,562
<p>I can select all the distinct values in a column in the following ways:</p> <ul> <li><code>SELECT DISTINCT column_name FROM table_name;</code></li> <li><code>SELECT column_name FROM table_name GROUP BY column_name;</code></li> </ul> <p>But how do I get the row count from that query? Is a subquery required?</p>
[ { "answer_id": 141573, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": false, "text": "select Count(distinct columnName) as columnNameCount from tableName \n" }, { "answer_id": 141574, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 10, "selected": true, "text": "DISTINCT COUNT SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name\n" }, { "answer_id": 141579, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 4, "selected": false, "text": "SELECT COUNT(DISTINCT column_name) FROM table as column_name_count;\n" }, { "answer_id": 142111, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 5, "selected": false, "text": "select count(distinct my_col)\n + count(distinct Case when my_col is null then 1 else null end)\nfrom my_table\n/\n" }, { "answer_id": 261344, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "select count(*) from \n(\nSELECT distinct column1,column2,column3,column4 FROM abcd\n) T\n" }, { "answer_id": 13101647, "author": "Paul James", "author_id": 1779496, "author_profile": "https://Stackoverflow.com/users/1779496", "pm_score": 8, "selected": false, "text": "SELECT [columnName], count([columnName]) AS CountOf\nFROM [tableName]\nGROUP BY [columnName]\n" }, { "answer_id": 30338143, "author": "xchiltonx", "author_id": 1422486, "author_profile": "https://Stackoverflow.com/users/1422486", "pm_score": 5, "selected": false, "text": "SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name ORDER BY 2 DESC;\n" }, { "answer_id": 53926812, "author": "Nilesh Shinde", "author_id": 6260075, "author_profile": "https://Stackoverflow.com/users/6260075", "pm_score": 1, "selected": false, "text": "select count(distinct(Column_Name)) from TableName\n" }, { "answer_id": 56459021, "author": "Nitika Chopra", "author_id": 7534013, "author_profile": "https://Stackoverflow.com/users/7534013", "pm_score": 0, "selected": false, "text": "select count(distinct(column_name)) AS columndatacount from table_name where somecondition=true\n" }, { "answer_id": 60293936, "author": "Alper", "author_id": 12829409, "author_profile": "https://Stackoverflow.com/users/12829409", "pm_score": 1, "selected": false, "text": "SELECT column_name, COUNT(column_name) OVER (PARTITION BY column_name) \nFROM table_name\nGROUP BY column_name\n" }, { "answer_id": 67828388, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 1, "selected": false, "text": "OVER SELECT DISTINCT my_col,\n count(*) OVER (PARTITION BY my_col\n ORDER BY my_col) AS num_rows\nFROM my_tbl\n OVER DISTINCT ORDER BY GROUP BY" }, { "answer_id": 72966995, "author": "Deva44", "author_id": 6766414, "author_profile": "https://Stackoverflow.com/users/6766414", "pm_score": 0, "selected": false, "text": "SELECT COUNT(C)\nFROM (SELECT COUNT(column_name) as C\nFROM table_name\nGROUP BY column_name)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3757/" ]
141,598
<p>I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: <code>School</code>, <code>Course</code>, and <code>Student</code>, which are defined as follows:</p> <pre><code>class School { List&lt;Course&gt; Courses; List&lt;Student&gt; Students; } class Course { string Number; string Description; } class Student { string Name; List&lt;Course&gt; EnrolledIn; } </code></pre> <p>I would store such a data structure in XML like so:</p> <pre><code>&lt;School&gt; &lt;Courses&gt; &lt;Course Number="ENGL 101" Description="English I" /&gt; &lt;Course Number="CHEM 102" Description="General Inorganic Chemistry" /&gt; &lt;Course Number="MATH 103" Description="Trigonometry" /&gt; &lt;/Courses&gt; &lt;Students&gt; &lt;Student Name="Jack"&gt; &lt;EnrolledIn&gt; &lt;Course Number="CHEM 102" /&gt; &lt;Course Number="MATH 103" /&gt; &lt;/EnrolledIn&gt; &lt;/Student&gt; &lt;Student Name="Jill"&gt; &lt;EnrolledIn&gt; &lt;Course Number="ENGL 101" /&gt; &lt;Course Number="MATH 103" /&gt; &lt;/EnrolledIn&gt; &lt;/Student&gt; &lt;/Students&gt; &lt;/School&gt; </code></pre> <p>With the XML ordered this way, I can parse <code>Courses</code> first. Then, when I parse <code>Students</code>, I can look up each <code>Course</code> listed in <code>EnrolledIn</code> (by its <code>Number</code>) in the <code>School.Courses</code> list. This will give me an object reference to add to the <code>EnrolledIn</code> list in <code>Student</code>. If <code>Students</code>, however, comes <em>before</em> <code>Courses</code>, such a lookup to get a object reference is not possible. (Since <code>School.Courses</code> has not yet been populated.)</p> <p>So what are the best practices for storing relational data in XML? - Should I enforce that <code>Courses</code> must always come before <code>Students</code>? - Should I tolerate any ordering and create a stub <code>Course</code> object whenever I encounter one I have not yet seen? (To be expanded when the definition of the <code>Course</code> is eventually reached later.) - Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing <code>Save</code> and <code>Load</code> methods on all my business objects and doing all this manually using <code>System.Xml.XmlDocument</code> and its associated classes.)</p> <p>I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated.</p>
[ { "answer_id": 141665, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 0, "selected": false, "text": "Courses Students" }, { "answer_id": 141677, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 0, "selected": false, "text": "<School>\n <Students>\n <Student Name=\"Jack\">\n <EnrolledIn>\n <Course Number=\"CHEM 102\" Description=\"General Inorganic Chemistry\" />\n <Course Number=\"MATH 103\" Description=\"Trigonometry\" />\n </EnrolledIn>\n </Student>\n <Student Name=\"Jill\">\n <EnrolledIn>\n <Course Number=\"ENGL 101\" Description=\"English I\" />\n <Course Number=\"MATH 103\" Description=\"Trigonometry\" />\n </EnrolledIn>\n </Student>\n </Students>\n</School>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
141,599
<p>What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'. </p> <p>Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?</p> <p>Example:</p> <pre><code>svn -v log -d 2008-9-23:2008-9:24 &gt; report.txt </code></pre>
[ { "answer_id": 141619, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 7, "selected": true, "text": "svn log <url> -r\n {2008-09-19}:{2008-09-26}" }, { "answer_id": 141631, "author": "Rob", "author_id": 22832, "author_profile": "https://Stackoverflow.com/users/22832", "pm_score": 4, "selected": false, "text": "svn log -v -r {2008-09-23}:{2008-09-24} > report.txt\n" }, { "answer_id": 141653, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 3, "selected": false, "text": "svn log -r{2008-9-23}:{2008-9-24} > report.txt\n --xml -r" }, { "answer_id": 18710975, "author": "Harikrushna", "author_id": 1587594, "author_profile": "https://Stackoverflow.com/users/1587594", "pm_score": 3, "selected": false, "text": "svn log -r '{2013-9-23}:{2013-9-24}'\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
141,606
<p>Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some reference material.</p> <p>Here's an example:</p> <blockquote> <p><strong>Using The Best Product in the World to Create World Peace</strong></p> <p><em>Note: This article assumes you are already familiar with The Best Product in the World. To learn more about The Best Product in the World, please see the official web site.</em></p> <p> The Best Product in the World ... </p> </blockquote> <p>Now, I don't want the note to show up in <strike>Google</strike> search engine results, only the title and the content that follows the note. Is there any way I can achieve this?</p> <p>Also, is it possible to do this without direct control over the entire HTML file and/or HTTP response, i.e. on blog hosted by a third party, like <a href="http://www.wordpress.com" rel="nofollow noreferrer">Wordpress.com</a>?</p> <p><strong>Update</strong></p> <p>Unfortunately, both the JavaScript solution and the HTML meta tag approach does not work on hosted Wordpress.com blogs, since they don't allow JavaScript in posts and they don't provide access to edit the HTML meta tags directly.</p>
[ { "answer_id": 141616, "author": "Paul Mrozowski", "author_id": 3656, "author_profile": "https://Stackoverflow.com/users/3656", "pm_score": 3, "selected": true, "text": "<html>\n<body>\n <div id=\"dynContent\">\n </div>\n Rest of the content here.\n</body>\n<script language='javascript' type='text/javascript'>\n var dyn = document.getElementById('dynContent');\n dyn.innerHTML = \"Put the dynamic content here\";\n</script>\n</html>\n" }, { "answer_id": 142222, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 2, "selected": false, "text": "<meta name=\"robots\" content=\"noindex, nofollow\">\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
141,611
<p>I have an Enum like this</p> <pre><code>package com.example; public enum CoverageEnum { COUNTRY, REGIONAL, COUNTY } </code></pre> <p>I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:</p> <pre><code>&lt;c:forEach var="type" items="&lt;%= com.example.CoverageEnum.values() %&gt;"&gt; ${type} &lt;/c:forEach&gt; </code></pre> <p>But can I achieve the same thing without scriptlets?</p> <p>Cheers, Don</p>
[ { "answer_id": 141658, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 3, "selected": false, "text": "<c:forEach var=\"type\" items=\"${myprefix:getValues()}\">\n public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {\n try { \n Method m = klass.getMethod(\"values\", null);\n Object obj = m.invoke(null, null);\n return (Enum<T>[])obj;\n } catch(Exception ex) {\n //shouldn't happen...\n return null;\n }\n}\n" }, { "answer_id": 3857480, "author": "Ted Pennings", "author_id": 134583, "author_profile": "https://Stackoverflow.com/users/134583", "pm_score": 3, "selected": false, "text": " <form:form method=\"post\" modelAttribute=\"cluster\" cssClass=\"form\" enctype=\"multipart/form-data\">\n <form:label path=\"clusterType\">Cluster Type\n <form:errors path=\"clusterType\" cssClass=\"error\" />\n </form:label>\n <form:select items=\"${clusterTypes}\" var=\"type\" path=\"clusterType\"/>\n </form:form>\n <form:error> clusterTypes @ModelAttribute(\"clusterTypes\")\npublic MyClusterType[] populateClusterTypes() {\n return MyClusterType.values();\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
141,612
<p>I'm working on database designs for a project management system as personal project and I've hit a snag.</p> <p>I want to implement a ticket system and I want the tickets to look like the <a href="http://trac.edgewall.org/ticket/6436" rel="noreferrer">tickets in Trac</a>. What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing)</p> <p>Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again. </p> <p><strong>Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.</strong> </p>
[ { "answer_id": 141634, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": " CREATE OR REPLACE TRIGGER history$yourTable\n BEFORE UPDATE ON yourTable\n FOR EACH ROW\n BEGIN\n INSERT INTO\n history\n VALUES\n (\n :old.field1,\n :old.field2,\n :old.field3,\n :old.field4,\n :old.field5,\n :old.field6\n );\n END;\n /\n SHOW ERRORS TRIGGER history$yourTable\n" }, { "answer_id": 141651, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 5, "selected": true, "text": "RecordID Table Column OldValue NewValue\n-------- ----- ------ -------- --------\n CHANGE LOG TABLE:\nRecordID Table Column OldValue NewValue TransactionID\n-------- ----- ------ -------- -------- -------------\n\nTRANSACTION LOG TABLE:\nTransactionID UserID TransactionDate\n------------- ------ ---------------\n" }, { "answer_id": 141664, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 2, "selected": false, "text": "id ticket_number revision_date ticket_number id revision_date" }, { "answer_id": 141812, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 2, "selected": false, "text": "┌──────────────────┐ ┌──────────────────┐\n│ LoggableEntity │ │ EntityLog │\n│ ──────────────── │ │ ──────────────── │\n│ (PK) ID │ ◀──┐ │ (PK) ID │\n└──────────────────┘ └───── │ (FK) LoggableID │\n ▲ │ ... │\n │ └──────────────────┘\n┌──────────────────┐\n│ Customer │\n│ ──────────────── │\n│ (PK) ID │\n│ (FK) LoggableID │\n│ ... │\n└──────────────────┘\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ]
141,620
<p>i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.</p> <p>i have this code in the application.rb:</p> <p>def check_role @user = session[:user]</p> <p>if @user.role.can_access_admin.nil? || !@user.role.can_access_admin render :text => "your current role does not allow access to the administration area." return end end</p> <p>and then i have this code inside one of the admin controllers:</p> <p>class Admin::BlogsController &lt; ApplicationController before_filter :check_role</p> <p>def list @blogList = Blog.find(:all) end end</p> <p>and when i try to view the list action i get this error:</p> <p>undefined method 'role' for user...</p> <p>anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)</p>
[ { "answer_id": 141721, "author": "MatthewFord", "author_id": 21596, "author_profile": "https://Stackoverflow.com/users/21596", "pm_score": 4, "selected": true, "text": "@user = User.find(session[:user])\n" }, { "answer_id": 142365, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 1, "selected": false, "text": "current_user" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
141,626
<p>I've got a windows form in Visual Studio 2008 using .NET 3.5 which has a WebBrowser control on it. I need to analyse the form's PostData in the Navigating event handler before the request is sent. Is there a way to get to it?</p> <p>The old win32 browser control had a Before_Navigate event which had PostData as one of its arguments. Not so with the new .NET WebBrowser control.</p>
[ { "answer_id": 144354, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 4, "selected": true, "text": "Dim ie = DirectCast(WebBrowser1.ActiveXInstance, SHDocVw.InternetExplorer)\nAddHandler ie.BeforeNavigate2, AddressOf WebBrowser_BeforeNavigate2\n Private Sub WebBrowser_BeforeNavigate2(ByVal pDisp As Object, ByRef URL As Object, _\n ByRef Flags As Object, ByRef TargetFrameName As Object, _\n ByRef PostData As Object, ByRef Headers As Object, ByRef Cancel As Boolean)\n Dim PostDataText = System.Text.Encoding.ASCII.GetString(PostData)\nEnd Sub\n" }, { "answer_id": 12002267, "author": "Vadim Zin4uk", "author_id": 1329308, "author_profile": "https://Stackoverflow.com/users/1329308", "pm_score": 3, "selected": false, "text": " /// <summary>\n /// Fires before navigation occurs in the given object (on either a window or frameset element).\n /// </summary>\n /// <param name=\"pDisp\">Object that evaluates to the top level or frame WebBrowser object corresponding to the navigation.</param>\n /// <param name=\"url\">String expression that evaluates to the URL to which the browser is navigating.</param>\n /// <param name=\"Flags\">Reserved. Set to zero.</param>\n /// <param name=\"TargetFrameName\">String expression that evaluates to the name of the frame in which the resource will be displayed, or Null if no named frame is targeted for the resource.</param>\n /// <param name=\"PostData\">Data to send to the server if the HTTP POST transaction is being used.</param>\n /// <param name=\"Headers\">Value that specifies the additional HTTP headers to send to the server (HTTP URLs only). The headers can specify such things as the action required of the server, the type of data being passed to the server, or a status code.</param>\n /// <param name=\"Cancel\">Boolean value that the container can set to True to cancel the navigation operation, or to False to allow it to proceed.</param>\n private delegate void BeforeNavigate2(object pDisp, ref dynamic url, ref dynamic Flags, ref dynamic TargetFrameName, ref dynamic PostData, ref dynamic Headers, ref bool Cancel);\n\n private void Form1_Load(object sender, EventArgs e)\n {\n dynamic d = webBrowser1.ActiveXInstance;\n\n d.BeforeNavigate2 += new BeforeNavigate2((object pDisp,\n ref dynamic url,\n ref dynamic Flags,\n ref dynamic TargetFrameName,\n ref dynamic PostData,\n ref dynamic Headers,\n ref bool Cancel) => {\n\n // Do something with PostData\n });\n }\n dynamic d = webBrowser1.ActiveXInstance;\n using System.Reflection;\n ...\n PropertyInfo prop = typeof(System.Windows.Controls.WebBrowser).GetProperty(\"ActiveXInstance\", BindingFlags.NonPublic | BindingFlags.Instance);\n MethodInfo getter = prop.GetGetMethod(true);\n dynamic d = getter.Invoke(webBrowser1, null);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
141,630
<p>If I drag and drop a selection of a webpage from Firefox to HTML-Kit, HTML-Kit asks me whether I want to paste as text or HTML. If I select "text," I get this:</p> <pre><code>Version:0.9 StartHTML:00000147 EndHTML:00000516 StartFragment:00000181 EndFragment:00000480 SourceURL:http://en.wikipedia.org/wiki/Herodotus &lt;html&gt;&lt;body&gt; &lt;!--StartFragment--&gt;Additional details have been garnered from the &lt;i&gt;&lt;a href="http://en.wikipedia.org/wiki/Suda" title="Suda"&gt;Suda&lt;/a&gt;&lt;/i&gt;, an 11th-century encyclopaedia of the &lt;a href="http://en.wikipedia.org/wiki/Byzantium" title="Byzantium"&gt;Byzantium&lt;/a&gt; which likely took its information from traditional accounts.&lt;!--EndFragment--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format" rel="nofollow noreferrer">According to MSDN</a>, this is "CF_HTML" formatted clipboard data. Is it the same on OS X and Linux systems? </p> <p>Is there any way to access this kind of detailed information (as opposed to just the plain clip fragment) in a webpage-to-webpage drag and drop operation? What about to a C# WinForms desktop application?</p>
[ { "answer_id": 57678502, "author": "Markus", "author_id": 1332129, "author_profile": "https://Stackoverflow.com/users/1332129", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n//--------------------------------------------------------------------------------\nhttp://metadataconsulting.blogspot.com/2019/06/How-to-get-HTML-from-the-Windows-system-clipboard-directly-using-PInvoke-Win32-Native-methods-avoiding-bad-funny-characters.html\n//--------------------------------------------------------------------------------\n\npublic class ClipboardHelper\n{\n #region Win32 Native PInvoke\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n private static extern uint RegisterClipboardFormat(string lpszFormat);\n //or specifically - private static extern uint RegisterClipboardFormatA(string lpszFormat);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool IsClipboardFormatAvailable(uint format);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n private static extern IntPtr GetClipboardData(uint uFormat);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CloseClipboard();\n\n [DllImport(\"Kernel32.dll\", SetLastError = true)]\n private static extern IntPtr GlobalLock(IntPtr hMem);\n\n [DllImport(\"Kernel32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GlobalUnlock(IntPtr hMem);\n\n [DllImport(\"Kernel32.dll\", SetLastError = true)]\n private static extern int GlobalSize(IntPtr hMem);\n\n #endregion\n\n public static string GetHTMLWin32Native()\n {\n\n string strHTMLUTF8 = string.Empty; \n uint CF_HTML = RegisterClipboardFormatA(\"HTML Format\");\n if (CF_HTML != null || CF_HTML == 0)\n return null;\n\n if (!IsClipboardFormatAvailable(CF_HTML))\n return null;\n\n try\n {\n if (!OpenClipboard(IntPtr.Zero))\n return null;\n\n IntPtr handle = GetClipboardData(CF_HTML);\n if (handle == IntPtr.Zero)\n return null;\n\n IntPtr pointer = IntPtr.Zero;\n\n try\n {\n pointer = GlobalLock(handle);\n if (pointer == IntPtr.Zero)\n return null;\n\n uint size = GlobalSize(handle);\n byte[] buff = new byte[size];\n\n Marshal.Copy(pointer, buff, 0, (int)size);\n\n strHTMLUTF8 = System.Text.Encoding.UTF8.GetString(buff);\n }\n finally\n {\n if (pointer != IntPtr.Zero)\n GlobalUnlock(handle);\n }\n }\n finally\n {\n CloseClipboard();\n }\n\n return strHTMLUTF8; \n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965/" ]
141,641
<p>I've been working with Perl long enough that many of its idiosyncracies have become second nature to me. When new programmers join our group, they frequently have little to no experience with Perl, and it's usually my task to train them (to the extent necessary). I'd like to know what to focus on when training a programmer who is new to Perl but has experience with other languages (this question is meant to be language-agnostic, but most developers I've worked with have come from Java).</p> <p>A few things occur to me: </p> <ul> <li>The proper use of sigils</li> <li>Referencing/Dereferencing</li> <li>Use of list functions like <strong>map</strong>, <strong>grep</strong>, <strong>sort</strong></li> </ul> <p>Is there anything in particular that you've found it useful to focus on when helping a programmer to transition to Perl? Do you stress the similarities or the differences, or both in equal measure?</p>
[ { "answer_id": 141676, "author": "Ben", "author_id": 16424, "author_profile": "https://Stackoverflow.com/users/16424", "pm_score": 2, "selected": false, "text": "next unless \"$_\" !~ /^#/;\n" }, { "answer_id": 141698, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": " Customary Generic Meaning Interpolates\n '' q{} Literal no\n \"\" qq{} Literal yes\n `` qx{} Command yes*\n qw{} Word list no\n // m{} Pattern match yes*\n qr{} Pattern yes*\n s{}{} Substitution yes*\n tr{}{} Transliteration no (but see below)\n <<EOF here-doc yes*\n\n * unless the delimiter is ''.\n" }, { "answer_id": 141732, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "perldoc perltoc perldoc -q $keyword perldoc -f $function" }, { "answer_id": 141799, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 2, "selected": false, "text": "for (my $i = 0; $i < @a; $i++)\n{\n &do_something_with($array[$i]);\n}\n foreach my $a (@array)\n{\n &do_something_with($a);\n}\n" }, { "answer_id": 141814, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "use strict;\nuse warnings;\n $_ @_ $_ @_ next unless /foo/ map grep" }, { "answer_id": 141886, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "use integer;@A=split//,<>;sub R{for$i(0..80){next if$A[$i];my%t=map{$_/9\n==$i/9||$_%9==$i%9||$_/27==$i/27&&$_%9/3==$i%9/3?$A[$_]:0=>1}0..80;R($A[\n$i]=$_)for grep{!$t{$_}}1..9;return$A[$i]=0}die@A}R\n" }, { "answer_id": 164453, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 2, "selected": false, "text": "use strict;\nuse warnings;\n use diagnostics;\n use autodie; #or Fatal\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ]
141,642
<p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p> <p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html" rel="noreferrer">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p> <p>Seeing a code example for a concrete limitation would be great.</p> <p><strong>Related questions</strong>:</p> <ul> <li><a href="https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li> <li><a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a ‘Closure’?</a></li> <li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li> </ul>
[ { "answer_id": 141670, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "def outer ():\n x = 1\n def inner ():\n print x\n x = 2\n return inner\nouter () ()\n" }, { "answer_id": 141710, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 7, "selected": true, "text": ">>> def outer(x): \n... def inner_reads():\n... # Will return outer's 'x'.\n... return x\n... def inner_writes(y):\n... # Will assign to a local 'x', not the outer 'x'\n... x = y\n... def inner_error(y):\n... # Will produce an error: 'x' is local because of the assignment,\n... # but we use it before it is assigned to.\n... tmp = x\n... x = y\n... return tmp\n... return inner_reads, inner_writes, inner_error\n... \n>>> inner_reads, inner_writes, inner_error = outer(5)\n>>> inner_reads()\n5\n>>> inner_writes(10)\n>>> inner_reads()\n5\n>>> inner_error(10)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 11, in inner_error\nUnboundLocalError: local variable 'x' referenced before assignment\n >>> def outer(x):\n... x = [x]\n... def inner_reads():\n... # Will return outer's x's first (and only) element.\n... return x[0]\n... def inner_writes(y):\n... # Will look up outer's x, then mutate it. \n... x[0] = y\n... def inner_error(y):\n... # Will now work, because 'x' is not assigned to, just referenced.\n... tmp = x[0]\n... x[0] = y\n... return tmp\n... return inner_reads, inner_writes, inner_error\n... \n>>> inner_reads, inner_writes, inner_error = outer(5)\n>>> inner_reads()\n5\n>>> inner_writes(10)\n>>> inner_reads()\n10\n>>> inner_error(15)\n10\n>>> inner_reads()\n15\n" }, { "answer_id": 141744, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "def outer():\n x = 1 # local to `outer()`\n\n def inner():\n x = 2 # local to `inner()`\n print(x)\n x = 3\n return x\n\n def inner2():\n nonlocal x\n print(x) # local to `outer()`\n x = 4 # change `x`, it is not local to `inner2()`\n return x\n\n x = 5 # local to `outer()`\n return (inner, inner2)\n\nfor inner in outer():\n print(inner()) \n\n# -> 2 3 5 4\n" }, { "answer_id": 141767, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 3, "selected": false, "text": "nonlocal nonlocal" }, { "answer_id": 141881, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "nonlocal x = 0 # global x\ndef outer():\n x = 1 # local to `outer`\n def inner():\n global x\n x = 2 # change global\n print(x) \n x = 3 # change global\n return x\n def inner2():\n## nonlocal x # can't use `nonlocal` here\n print(x) # prints global\n## x = 4 # can't change `x` here\n return x\n x = 5\n return (inner, inner2)\n\nfor inner in outer():\n print(inner())\n# -> 2 3 3 3\n x = 0\ndef outer():\n x = 1 # local to `outer`\n def inner():\n## global x\n x = 2\n print(x) # local to `inner` \n x = 3 \n return x\n def inner2():\n nonlocal x\n print(x)\n x = 4 # local to `outer`\n return x\n x = 5\n return (inner, inner2)\n\nfor inner in outer():\n print(inner())\n# -> 2 3 5 4\n" }, { "answer_id": 6990028, "author": "mykhal", "author_id": 234248, "author_profile": "https://Stackoverflow.com/users/234248", "pm_score": 3, "selected": false, "text": "var mksecretmaker = function(){\n var secrets = [];\n var mksecret = function() {\n secrets.push(Math.random())\n }\n return mksecret\n}\nvar secretmaker = mksecretmaker();\nsecretmaker(); secretmaker()\n// privately generated secret number list\n// is practically inaccessible\n import random\ndef mksecretmaker():\n secrets = []\n def mksecret():\n secrets.append(random.random())\n return mksecret\n\nsecretmaker = mksecretmaker()\nsecretmaker(); secretmaker()\n# \"secrets\" are easily accessible,\n# it's difficult to hide something in Python:\nsecretmaker.__closure__[0].cell_contents # -> e.g. [0.680752847190161, 0.9068475951742101]\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
141,650
<p>I've seen <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function">the other post about this</a>, but is there a clean way of doing this in Haskell?</p> <p>As a 2nd part, can it also be done without making the function monadic?</p>
[ { "answer_id": 142269, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 1, "selected": false, "text": "memo f = let values = map f [0..]\n in \\n -> values !! n\n" }, { "answer_id": 142280, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 2, "selected": false, "text": "memoize :: Ord a => (a -> IO b) -> IO (a -> IO b)\nmemoize f =\n do r <- newIORef Map.empty\n return $ \\x -> do m <- readIORef r\n case Map.lookup x m of\n Just y -> return y\n Nothing -> do y <- f x\n writeIORef r (Map.insert x y m)\n return y\n" }, { "answer_id": 169031, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 4, "selected": true, "text": "type Cacher a b = (a -> b) -> a -> b\n\npositive_list_cacher :: Cacher Int b\npositive_list_cacher f n = (map f [0..]) !! n\n integer_list_cacher :: Cacher Int b\ninteger_list_cacher f n = (map f (interleave [0..] [-1, -2, ..]) !!\n index n where\n index n | n < 0 = 2*abs(n) - 1\n index n | n >= 0 = 2 * n\n f_with_memo :: (a -> b) -> a -> b\nf_with_memo memoed base = base_answer\nf_with_memo memoed arg = calc (memoed (simpler arg))\n memoize cacher f = cached where\n cached = cacher (f cached)\n exposed_f = memoize cacher_for_f f\n" }, { "answer_id": 308594, "author": "luqui", "author_id": 33796, "author_profile": "https://Stackoverflow.com/users/33796", "pm_score": 4, "selected": false, "text": "type Memo a = forall r. (a -> r) -> (a -> r)\n unit :: Memo () integral :: Memo Int pair :: Memo a -> Memo b -> Memo (a,b) list :: Memo a -> Memo [a]" }, { "answer_id": 4236284, "author": "martin lütke", "author_id": 514872, "author_profile": "https://Stackoverflow.com/users/514872", "pm_score": 4, "selected": false, "text": "import qualified Data.Map as Map\nimport Data.IORef\nimport System.IO.Unsafe\n\nmemoize :: Ord a => (a -> b) -> (a -> b)\nmemoize f = unsafePerformIO $ do \n r <- newIORef Map.empty\n return $ \\ x -> unsafePerformIO $ do \n m <- readIORef r\n case Map.lookup x m of\n Just y -> return y\n Nothing -> do \n let y = f x\n writeIORef r (Map.insert x y m)\n return y\n fib :: Int -> Integer\nfib 0 = 1\nfib 1 = 1\nfib n = fib_memo (n-1) + fib_memo (n-2)\n\nfib_memo :: Int -> Integer\nfib_memo = memoize fib\n f :: String -> [Int] -> Float\nf ...\n\nf_memo = curry (memoize (uncurry f))\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12887/" ]
141,682
<p>I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION_SCHEMA.</p> <p>I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere.</p> <p>Are they not there? (I'm using MS SQL Server 2000).</p> <p>EDIT: I'm looking to get by the name of the constraint.</p>
[ { "answer_id": 142229, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 0, "selected": false, "text": "\"ALTER TABLE xxx ALTER COLUMN yyy SET DEFAULT...\"" }, { "answer_id": 142625, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 5, "selected": false, "text": "Information_Schema SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name" }, { "answer_id": 541757, "author": "Tim Lentine", "author_id": 2833, "author_profile": "https://Stackoverflow.com/users/2833", "pm_score": 6, "selected": false, "text": "select * from sysobjects o \ninner join syscolumns c\non o.id = c.cdefault\ninner join sysobjects t\non c.id = t.id\nwhere o.xtype = 'D'\nand c.name = 'Column_Name'\nand t.name = 'Table_Name'\n" }, { "answer_id": 912764, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name\n from information_schema.columns columns\n inner join information_schema.constraint_column_usage usage on \n columns.column_name = usage.column_name and columns.table_name = usage.table_name\n inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name\n where columns.column_default is not null\n" }, { "answer_id": 1538651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "select c.name, col.name from sys.default_constraints c\n inner join sys.columns col on col.default_object_id = c.object_id\n inner join sys.objects o on o.object_id = c.parent_object_id\n inner join sys.schemas s on s.schema_id = o.schema_id\nwhere s.name = @SchemaName and o.name = @TableName and col.name = @ColumnName\n" }, { "answer_id": 6328669, "author": "Johan Badenhorst", "author_id": 318229, "author_profile": "https://Stackoverflow.com/users/318229", "pm_score": 4, "selected": false, "text": "SELECT \n b.name AS TABLE_NAME,\n d.name AS COLUMN_NAME,\n a.name AS CONSTRAINT_NAME,\n c.text AS DEFAULT_VALUE\nFROM sys.sysobjects a INNER JOIN\n (SELECT name, id\n FROM sys.sysobjects \n WHERE xtype = 'U') b on (a.parent_obj = b.id)\n INNER JOIN sys.syscomments c ON (a.id = c.id)\n INNER JOIN sys.syscolumns d ON (d.cdefault = a.id) \n WHERE a.xtype = 'D' \n ORDER BY b.name, a.name\n" }, { "answer_id": 9721492, "author": "Robert Calhoun", "author_id": 198374, "author_profile": "https://Stackoverflow.com/users/198374", "pm_score": 8, "selected": true, "text": "-- returns name of a column's default value constraint \nSELECT\n default_constraints.name\nFROM \n sys.all_columns\n\n INNER JOIN\n sys.tables\n ON all_columns.object_id = tables.object_id\n\n INNER JOIN \n sys.schemas\n ON tables.schema_id = schemas.schema_id\n\n INNER JOIN\n sys.default_constraints\n ON all_columns.default_object_id = default_constraints.object_id\n\nWHERE \n schemas.name = 'dbo'\n AND tables.name = 'tablename'\n AND all_columns.name = 'columnname'\n" }, { "answer_id": 32750390, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 3, "selected": false, "text": "sysobjects sys IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN\n -- constraint exists, work with it.\nEND\n" }, { "answer_id": 35912249, "author": "Mirec", "author_id": 6043907, "author_profile": "https://Stackoverflow.com/users/6043907", "pm_score": 0, "selected": false, "text": "SELECT \n t.name AS TableName, c.name AS ColumnName, SC.COLUMN_DEFAULT AS DefaultValue, dc.name AS DefaultConstraintName\nFROM \n sys.all_columns c\n JOIN sys.tables t ON c.object_id = t.object_id\n JOIN sys.schemas s ON t.schema_id = s.schema_id\n LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id\n LEFT JOIN INFORMATION_SCHEMA.COLUMNS SC ON (SC.TABLE_NAME = t.name AND SC.COLUMN_NAME = c.name)\nWHERE \n SC.COLUMN_DEFAULT IS NOT NULL\n --WHERE t.name = '' and c.name = ''\n" }, { "answer_id": 46459428, "author": "user3059720", "author_id": 3059720, "author_profile": "https://Stackoverflow.com/users/3059720", "pm_score": 1, "selected": false, "text": "WHILE EXISTS( \n SELECT * FROM sys.all_columns \n INNER JOIN sys.tables ST ON all_columns.object_id = ST.object_id\n INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id\n INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id\n WHERE \n schemas.name = 'dbo'\n AND ST.name = 'MyTable'\n)\nBEGIN \nDECLARE @SQL NVARCHAR(MAX) = N'';\n\nSET @SQL = ( SELECT TOP 1\n 'ALTER TABLE ['+ schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'\n FROM \n sys.all_columns\n\n INNER JOIN\n sys.tables ST\n ON all_columns.object_id = ST.object_id\n\n INNER JOIN \n sys.schemas\n ON ST.schema_id = schemas.schema_id\n\n INNER JOIN\n sys.default_constraints\n ON all_columns.default_object_id = default_constraints.object_id\n\n WHERE \n schemas.name = 'dbo'\n AND ST.name = 'MyTable'\n )\n PRINT @SQL\n EXECUTE sp_executesql @SQL \n\n --End if Error \n IF @@ERROR <> 0 \n BREAK\nEND \n" }, { "answer_id": 47053361, "author": "eigenharsha", "author_id": 4089958, "author_profile": "https://Stackoverflow.com/users/4089958", "pm_score": 0, "selected": false, "text": "INFORMATION_SCHEMA sys.default_constraints SELECT so.object_id TableName,\n ss.name AS TableSchema,\n cc.name AS Name,\n cc.object_id AS ObjectID, \n sc.name AS ColumnName,\n cc.parent_column_id AS ColumnID,\n cc.definition AS Defination,\n CONVERT(BIT,\n CASE cc.is_system_named\n WHEN 1\n THEN 1\n ELSE 0\n END) AS IsSystemNamed,\n cc.create_date AS CreationDate,\n cc.modify_date AS LastModifiednDate\nFROM sys.default_constraints cc WITH (NOLOCK)\n INNER JOIN sys.objects so WITH (NOLOCK) ON so.object_id = cc.parent_object_id\n LEFT JOIN sys.schemas ss WITH (NOLOCK) ON ss.schema_id = so.schema_id\n LEFT JOIN sys.columns sc WITH (NOLOCK) ON sc.column_id = cc.parent_column_id\n AND sc.object_id = cc.parent_object_id\nORDER BY so.name,\n cc.name;\n" }, { "answer_id": 57622699, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "IF NOT EXISTS(\n SELECT * FROM INFORMATION_SCHEMA.COLUMNS\n WHERE (1=1) \n AND TABLE_SCHEMA = 'dbo' \n AND TABLE_NAME = 'T_VWS_PdfBibliothek' \n AND COLUMN_NAME = 'PB_Text'\n AND COLUMN_DEFAULT IS NOT NULL \n)\nBEGIN \n EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek \n ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text; \n '); \nEND \n -- Alternative way: \nIF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL \nBEGIN\n -- constraint exists, deal with it.\nEND \n CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS \nAS \nSELECT \n DB_NAME() AS CONSTRAINT_CATALOG \n ,csch.name AS CONSTRAINT_SCHEMA\n ,dc.name AS CONSTRAINT_NAME \n ,DB_NAME() AS TABLE_CATALOG \n ,sch.name AS TABLE_SCHEMA \n ,syst.name AS TABLE_NAME \n ,sysc.name AS COLUMN_NAME \n ,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION \n ,dc.type_desc AS CONSTRAINT_TYPE \n ,dc.definition AS COLUMN_DEFAULT \n\n -- ,dc.create_date \n -- ,dc.modify_date \nFROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where \n-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where \n\nINNER JOIN sys.tables AS syst \n ON syst.object_id = sysc.object_id \n\nINNER JOIN sys.schemas AS sch\n ON sch.schema_id = syst.schema_id \n\nINNER JOIN sys.default_constraints AS dc \n ON sysc.default_object_id = dc.object_id\n\nINNER JOIN sys.schemas AS csch\n ON csch.schema_id = dc.schema_id \n\nWHERE (1=1) \nAND dc.is_ms_shipped = 0 \n\n/*\nWHERE (1=1) \nAND sch.name = 'dbo'\nAND syst.name = 'tablename'\nAND sysc.name = 'columnname'\n*/\n" }, { "answer_id": 65834870, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 0, "selected": false, "text": "SELECT DC.[name]\n FROM [sys].[default_constraints] AS DC\n WHERE DC.[parent_object_id] = OBJECT_ID('[Schema].[TableName]') \n" }, { "answer_id": 73573218, "author": "SAinCA", "author_id": 364795, "author_profile": "https://Stackoverflow.com/users/364795", "pm_score": 0, "selected": false, "text": "sys.default_constraints sys.syscolpars dflt SELECT ConstraintName = sdc.name\n , SchemaName = ssch.name\n , TableName = stab.name\n , ColumnName = scol.name\n FROM sys.objects sdc\n INNER JOIN sys.columns scol\n ON scol.default_object_id = sdc.object_id\n INNER JOIN sys.objects stab\n ON stab.object_id = scol.object_id\n INNER JOIN sys.schemas ssch\n ON ssch.schema_id = stab.schema_id;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9052/" ]
141,693
<p>Two main ways to deploy a J2EE/Java Web app (in a very simplistic sense):</p> <h2>Deploy assembled artifacts to production box</h2> <p>Here, we create the <code>.war</code> (or whatever) elsewhere, configure it for production (possibly creating numerous artifacts for numerous boxes) and place the resulting artifacts on the production servers.</p> <ul> <li><strong>Pros</strong>: No dev tools on production boxes, can re-use artifacts from testing directly, staff doing deployment doesn't need knowledge of build process</li> <li><strong>Cons</strong>: two processes for creating and deploying artifacts; potentially complex configuration of pre-built artifacts could make process hard to script/automate; have to version binary artifacts </li> </ul> <h2>Build the artifacts <strong>on</strong> the production box</h2> <p>Here, the same process used day-to-day to build and deploy locally on developer boxes is used to deploy to production.</p> <ul> <li><strong>Pros</strong>: One process to maintain; and it's heavily tested/validated by frequent use. Potentially easier to customize configuration at artifact creation time rather than customize pre-built artifact afterword; no versioning of binary artifacts needed.</li> <li><strong>Cons</strong>: Potentially complex development tools needed on all production boxes; deployment staff needs to understand build process; you <strong>aren't</strong> deploying what you tested</li> </ul> <p>I've mostly used the second process, admittedly out of necessity (no time/priority for another deployment process). Personally I don't buy arguments like "the production box has to be clean of all compilers, etc.", but I <strong>can</strong> see the logic in deploying what you've tested (as opposed to building another artifact). </p> <p>However, Java Enterprise applications are so sensitive to configuration, it feels like asking for trouble having two processes for configuring artifacts.</p> <p>Thoughts?</p> <h2>Update</h2> <p>Here's a concrete example:</p> <p>We use OSCache, and enable the disk cache. The configuration file must be inside the .war file and it references a file path. This path is different on every environment. The build process detects the user's configured location and ensures that the properties file placed in the war is correct for his environment. </p> <p>If we were to use the build process for deployment, it would be a matter of creating the right configuration for the production environment (e.g. <code>production.build.properties</code>).</p> <p>If we were to follow the "deploy assembled artifacts to the production box", we would need an additional process to extract the (incorrect) OSCache properties and replace it with one appropriate to the production environment.</p> <p>This creates two processes to accomplish the same thing.</p> <p>So, the questions are:</p> <ul> <li>Is this avoidable without "compiling on production"?</li> <li>If not, is this worth it? It the value of "no compiling on production" greater than "Don't Repeat Yourself"?</li> </ul>
[ { "answer_id": 176402, "author": "Mike Pone", "author_id": 16404, "author_profile": "https://Stackoverflow.com/users/16404", "pm_score": 0, "selected": false, "text": "<replace file=\"${BUILDS.ROOT}/DefaultWebApp/WEB-INF/classes/log4j.xml\" token=\"@@@\" value=\"${LOG4J.WEBSPHERE.LOGS}\"/>\n\n\n<!-- update the war file We don't want the source files in the war file.-->\n<war basedir=\"${BUILDS.ROOT}/DefaultWebApp\" destfile=\"${BUILDS.ROOT}/myThomson.war\" excludes=\"WEB-INF/src/**\" update=\"true\"/>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029/" ]
141,701
<p>How do I tar a list of files and folders (all in the same directory) with the exclusion of a single directory (which contains a huge amount of data)</p>
[ { "answer_id": 141722, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 3, "selected": false, "text": "tar --exclude=PATTERN xvzf nameof.tar.gz ./*" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22837/" ]
141,707
<p>I have a <a href="http://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux" rel="noreferrer">RHEL</a> box that I need to put under a moderate and variable amount of CPU load (50%-75%).</p> <p>What is the best way to go about this? Is there a program that can do this that I am not aware of? I am happy to write some C code to make this happen, I just don't know what system calls will help.</p>
[ { "answer_id": 141743, "author": "ya8282", "author_id": 22811, "author_profile": "https://Stackoverflow.com/users/22811", "pm_score": 0, "selected": false, "text": "renice #!/bin/bash\nwhile true ; do\ntrue\ndone\n" }, { "answer_id": 19227582, "author": "mat48", "author_id": 2855025, "author_profile": "https://Stackoverflow.com/users/2855025", "pm_score": 1, "selected": false, "text": "lookbusy -c util[-high_util], --cpu-util util[-high_util]\n\ni.e. 60% load\nlookbusy -c 60\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
141,718
<p>I have a multi-user ASP.NET app running against SQL Server and want to have StoredProcA create a #temptable temp table - not a table variable - to insert some data, then branch to StoredProcB, StoredProcC, and StoredProcD to manipulate the data in #temptable per business rules. </p> <p>The web app uses connection pooling when talking to SQL. Will I get a new #temptable scratch area for each call of StoredProcA? Or will the connection pooling share the #temptable between users?</p>
[ { "answer_id": 141754, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 2, "selected": false, "text": "#temptable" }, { "answer_id": 141821, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 7, "selected": true, "text": "sp_reset_connection" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ]
141,720
<p>How do you compare two instances of structs for equality in standard C?</p>
[ { "answer_id": 141791, "author": "Sufian", "author_id": 9241, "author_profile": "https://Stackoverflow.com/users/9241", "pm_score": 7, "selected": false, "text": "memcmp(&a, &b, sizeof(struct foo)) calloc memset memcmp" }, { "answer_id": 141800, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": " // bad\n memcmp(&struct1, &struct2, sizeof(struct1));\n typedef struct Foo {\n char a;\n /* padding */\n double d;\n /* padding */\n char e;\n /* padding */\n int f;\n} Foo ;\n" }, { "answer_id": 11852576, "author": "sergio", "author_id": 1555470, "author_profile": "https://Stackoverflow.com/users/1555470", "pm_score": 2, "selected": false, "text": "memcmp memcmp" }, { "answer_id": 26126317, "author": "Hesham Eraqi", "author_id": 1625695, "author_profile": "https://Stackoverflow.com/users/1625695", "pm_score": -1, "selected": false, "text": "#include <string.h>\n\n#pragma pack(push, 1)\nstruct s {\n char c;\n int i;\n char buffer[13];\n};\n#pragma pack(pop)\n\nvoid compare(const struct s *left, const struct s *right) { \n if (0 == memcmp(left, right, sizeof(struct s))) {\n /* ... */\n }\n}\n" }, { "answer_id": 32087322, "author": "Demi", "author_id": 2474792, "author_profile": "https://Stackoverflow.com/users/2474792", "pm_score": 3, "selected": false, "text": "memcmp NaN -Wpadded memset BOOL NULL UNICODE_STRING" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
141,734
<p>If I do not specify the following in my web.xml file:</p> <pre><code>&lt;session-config&gt; &lt;session-timeout&gt;10&lt;/session-timeout&gt; &lt;/session-config&gt; </code></pre> <p>What will be my default session timeout? (I am running Tomcat 6.0)</p>
[ { "answer_id": 142372, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 3, "selected": false, "text": "HttpSession" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ]
141,775
<p>I inherited an application where display:none was used to control conditional display of input elements based the values of other input elements.</p> <p>The way this was handled is by running some pretty ugly code to evaluate field values and reset the display property in the during page load. Every time.</p> <p>Isn't there a better way?</p>
[ { "answer_id": 15564963, "author": "hfarazm", "author_id": 1786755, "author_profile": "https://Stackoverflow.com/users/1786755", "pm_score": 0, "selected": false, "text": "opacity:0;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20132/" ]
141,779
<p>The problem/comic in question: <a href="http://xkcd.com/287/" rel="nofollow noreferrer">http://xkcd.com/287/</a></p> <p><img src="https://imgs.xkcd.com/comics/np_complete.png" alt="General solutions get you a 50% tip"></p> <p>I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone.</p> <pre><code>&lt;cffunction name="testCombo" returntype="boolean"&gt; &lt;cfargument name="currentCombo" type="string" required="true" /&gt; &lt;cfargument name="currentTotal" type="numeric" required="true" /&gt; &lt;cfargument name="apps" type="array" required="true" /&gt; &lt;cfset var a = 0 /&gt; &lt;cfset var found = false /&gt; &lt;cfloop from="1" to="#arrayLen(arguments.apps)#" index="a"&gt; &lt;cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) /&gt; &lt;cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost /&gt; &lt;cfif arguments.currentTotal eq 15.05&gt; &lt;!--- print current combo ---&gt; &lt;cfoutput&gt;&lt;strong&gt;#arguments.currentCombo# = 15.05&lt;/strong&gt;&lt;/cfoutput&gt;&lt;br /&gt; &lt;cfreturn true /&gt; &lt;cfelseif arguments.currentTotal gt 15.05&gt; &lt;cfoutput&gt;#arguments.currentCombo# &gt; 15.05 (aborting)&lt;/cfoutput&gt;&lt;br /&gt; &lt;cfreturn false /&gt; &lt;cfelse&gt; &lt;!--- less than 15.05 ---&gt; &lt;cfoutput&gt;#arguments.currentCombo# &lt; 15.05 (traversing)&lt;/cfoutput&gt;&lt;br /&gt; &lt;cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) /&gt; &lt;/cfif&gt; &lt;/cfloop&gt; &lt;/cffunction&gt; &lt;cfset mf = {name="Mixed Fruit", cost=2.15} /&gt; &lt;cfset ff = {name="French Fries", cost=2.75} /&gt; &lt;cfset ss = {name="side salad", cost=3.35} /&gt; &lt;cfset hw = {name="hot wings", cost=3.55} /&gt; &lt;cfset ms = {name="moz sticks", cost=4.20} /&gt; &lt;cfset sp = {name="sampler plate", cost=5.80} /&gt; &lt;cfset apps = [ mf, ff, ss, hw, ms, sp ] /&gt; &lt;cfloop from="1" to="6" index="b"&gt; &lt;cfoutput&gt;#testCombo(apps[b].name, apps[b].cost, apps)#&lt;/cfoutput&gt; &lt;/cfloop&gt; </code></pre> <p>The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete.</p> <p>Is there a better algorithm to come to the correct solution? Did I come to the correct solution?</p>
[ { "answer_id": 141909, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 0, "selected": false, "text": "<cffunction name=\"testCombo\" returntype=\"numeric\">\n <cfargument name=\"currentCombo\" type=\"string\" required=\"true\" />\n <cfargument name=\"currentTotal\" type=\"numeric\" required=\"true\" />\n <cfargument name=\"apps\" type=\"array\" required=\"true\" />\n\n <cfset var a = 0 />\n <cfset var found = false /> \n <cfset var CC = \"\" />\n <cfset var CT = 0 />\n\n <cfset tries = tries + 1 />\n\n <cfloop from=\"1\" to=\"#arrayLen(arguments.apps)#\" index=\"a\">\n <cfset combos = combos + 1 />\n <cfset CC = listAppend(arguments.currentCombo, arguments.apps[a].name) />\n <cfset CT = arguments.currentTotal + arguments.apps[a].cost />\n <cfif CT eq 15.05>\n <!--- print current combo --->\n <cfoutput><strong>#CC# = 15.05</strong></cfoutput><br />\n <cfreturn true />\n <cfelseif CT gt 15.05>\n <!--<cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br />-->\n <cfelse>\n <!--- less than 15.50 --->\n <!--<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />-->\n <cfset found = testCombo(CC, CT, arguments.apps) />\n </cfif>\n </cfloop>\n <cfreturn found />\n</cffunction>\n\n<cfset mf = {name=\"Mixed Fruit\", cost=2.15} />\n<cfset ff = {name=\"French Fries\", cost=2.75} />\n<cfset ss = {name=\"side salad\", cost=3.35} />\n<cfset hw = {name=\"hot wings\", cost=3.55} />\n<cfset ms = {name=\"moz sticks\", cost=4.20} />\n<cfset sp = {name=\"sampler plate\", cost=5.80} />\n<cfset apps = [ mf, ff, ss, hw, ms, sp ] />\n\n<cfset tries = 0 />\n<cfset combos = 0 />\n\n<cfoutput>\n <cfloop from=\"1\" to=\"6\" index=\"b\">\n #testCombo(apps[b].name, apps[b].cost, apps)#\n </cfloop>\n <br />\n tries: #tries#<br />\n combos: #combos#\n</cfoutput>\n Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit = 15.05\nMixed Fruit,hot wings,hot wings,sampler plate = 15.05\nMixed Fruit,hot wings,sampler plate,hot wings = 15.05\nMixed Fruit,sampler plate,hot wings,hot wings = 15.05\nfalse false false hot wings,Mixed Fruit,hot wings,sampler plate = 15.05\nhot wings,Mixed Fruit,sampler plate,hot wings = 15.05\nhot wings,hot wings,Mixed Fruit,sampler plate = 15.05\nhot wings,sampler plate,Mixed Fruit,hot wings = 15.05\nfalse false sampler plate,Mixed Fruit,hot wings,hot wings = 15.05\nsampler plate,hot wings,Mixed Fruit,hot wings = 15.05\nfalse\ntries: 2014\ncombos: 12067\n" }, { "answer_id": 141949, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 2, "selected": false, "text": " <cfelse>\n <!--- less than 15.50 --->\n <!--<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />-->\n <cfset found = testCombo(CC, CT, arguments.apps) />\n ------- remove the item from the apps array that was just checked here ------\n </cfif>\n</cfloop>\n <?\n function rc($total, $string, $m) {\n global $c;\n\n $m2 = $m;\n $c++;\n\n foreach($m as $i=>$p) {\n if ($total-$p == 0) {\n print \"$string $i\\n\";\n return;\n }\n if ($total-$p > 0) {\n rc($total-$p, $string . \" \" . $i, $m2);\n }\n unset($m2[$i]);\n }\n }\n\n $c = 0;\n\n $m = array(\"mf\"=>215, \"ff\"=>275, \"ss\"=>335, \"hw\"=>355, \"ms\"=>420, \"sp\"=>580);\n rc(1505, \"\", $m);\n print $c;\n?>\n mf mf mf mf mf mf mf\n mf hw hw sp\n209\n MF (2.15)\n MF (4.30)\n MF (6.45) *\n FF (7.05) X\n SS (7.65) X\n ...\n [MF removed for depth 2]\n FF (4.90)\n [checking MF now would be redundant since we checked MF/MF/FF previously]\n FF (7.65) X\n ...\n [FF removed for depth 2]\n SS (5.50)\n ...\n[MF removed for depth 1]\n" }, { "answer_id": 143213, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "#light\n\ntype Appetizer = { name : string; cost : int }\n\nlet menu = [\n {name=\"fruit\"; cost=215}\n {name=\"fries\"; cost=275}\n {name=\"salad\"; cost=335}\n {name=\"wings\"; cost=355}\n {name=\"moz sticks\"; cost=420}\n {name=\"sampler\"; cost=580}\n ] \n\n// Choose: list<Appetizer> -> list<Appetizer> -> int -> list<list<Appetizer>>\nlet rec Choose allowedMenu pickedSoFar remainingMoney =\n if remainingMoney = 0 then\n // solved it, return this solution\n [ pickedSoFar ]\n else\n // there's more to spend\n [match allowedMenu with\n | [] -> yield! [] // no more items to choose, no solutions this branch\n | item :: rest -> \n if item.cost <= remainingMoney then\n // if first allowed is within budget, pick it and recurse\n yield! Choose allowedMenu (item :: pickedSoFar) (remainingMoney - item.cost)\n // regardless, also skip ever picking more of that first item and recurse\n yield! Choose rest pickedSoFar remainingMoney]\n\nlet solutions = Choose menu [] 1505\n\nprintfn \"%d solutions:\" solutions.Length \nsolutions |> List.iter (fun solution ->\n solution |> List.iter (fun item -> printf \"%s, \" item.name)\n printfn \"\"\n)\n\n(*\n2 solutions:\nfruit, fruit, fruit, fruit, fruit, fruit, fruit,\nsampler, wings, wings, fruit,\n*)\n" }, { "answer_id": 143261, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy @weights = (2.15, 2.75, 3.35, 3.55, 4.20, 5.80);\n\nmy $total = 0;\nmy @order = ();\n\niterate($total, @order);\n\nsub iterate\n{\n my ($total, @order) = @_;\n foreach my $w (@weights)\n {\n if ($total+$w == 15.05)\n {\n print join (', ', (@order, $w)), \"\\n\";\n }\n if ($total+$w < 15.05)\n {\n iterate($total+$w, (@order, $w));\n }\n }\n}\n marco@unimatrix-01:~$ ./xkcd-knapsack.pl\n2.15, 2.15, 2.15, 2.15, 2.15, 2.15, 2.15\n2.15, 3.55, 3.55, 5.8\n2.15, 3.55, 5.8, 3.55\n2.15, 5.8, 3.55, 3.55\n3.55, 2.15, 3.55, 5.8\n3.55, 2.15, 5.8, 3.55\n3.55, 3.55, 2.15, 5.8\n3.55, 5.8, 2.15, 3.55\n5.8, 2.15, 3.55, 3.55\n5.8, 3.55, 2.15, 3.55\n" }, { "answer_id": 168059, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 0, "selected": false, "text": "function testCombo(minIndex, currentCombo, currentTotal){\n var a = 0;\n var CC = \"\";\n var CT = 0;\n var found = false;\n\n tries += 1;\n for (a=arguments.minIndex; a <= arrayLen(apps); a++){\n combos += 1;\n CC = listAppend(arguments.currentCombo, apps[a].name);\n CT = arguments.currentTotal + apps[a].cost;\n if (CT eq 15.05){\n //print current combo\n WriteOutput(\"<strong>#CC# = 15.05</strong><br />\");\n return(true);\n }else if (CT gt 15.05){\n //since we know the array is sorted by cost (asc),\n //and we've already gone over the price limit,\n //we can ignore anything else in the array\n break; \n }else{\n //less than 15.50, try adding something else\n found = testCombo(a, CC, CT);\n }\n }\n return(found);\n}\n\nmf = {name=\"mixed fruit\", cost=2.15};\nff = {name=\"french fries\", cost=2.75};\nss = {name=\"side salad\", cost=3.35};\nhw = {name=\"hot wings\", cost=3.55};\nms = {name=\"mozarella sticks\", cost=4.20};\nsp = {name=\"sampler plate\", cost=5.80};\napps = [ mf, ff, ss, hw, ms, sp ];\n\ntries = 0;\ncombos = 0;\n\ntestCombo(1, \"\", 0);\n\nWriteOutput(\"<br />tries: #tries#<br />combos: #combos#\");\n" }, { "answer_id": 228810, "author": "Toby", "author_id": 291137, "author_profile": "https://Stackoverflow.com/users/291137", "pm_score": 5, "selected": false, "text": "item(X) :- member(X,[215, 275, 335, 355, 420, 580]).\nsolution([X|Y], Z) :- item(X), plus(S, X, Z), Z >= 0, solution(Y, S).\nsolution([], 0).\n ?- solution(X, 1505).\n\nX = [215, 215, 215, 215, 215, 215, 215] ;\n\nX = [215, 355, 355, 580] ;\n\nX = [215, 355, 580, 355] ;\n\nX = [215, 580, 355, 355] ;\n\nX = [355, 215, 355, 580] ;\n\nX = [355, 215, 580, 355] ;\n\nX = [355, 355, 215, 580] ;\n\nX = [355, 355, 580, 215] ;\n\nX = [355, 580, 215, 355] ;\n\nX = [355, 580, 355, 215] ;\n\nX = [580, 215, 355, 355] ;\n\nX = [580, 355, 215, 355] ;\n\nX = [580, 355, 355, 215] ;\n\nNo\n" }, { "answer_id": 390629, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": ">>> from constraint import *\n>>> problem = Problem()\n>>> menu = {'mixed-fruit': 2.15,\n... 'french-fries': 2.75,\n... 'side-salad': 3.35,\n... 'hot-wings': 3.55,\n... 'mozarella-sticks': 4.20,\n... 'sampler-plate': 5.80}\n>>> for appetizer in menu:\n... problem.addVariable( appetizer, [ menu[appetizer] * i for i in range( 8 )] )\n>>> problem.addConstraint(ExactSumConstraint(15.05))\n>>> problem.getSolutions()\n[{'side-salad': 0.0, 'french-fries': 0.0, 'sampler-plate': 5.7999999999999998, 'mixed-fruit': 2.1499999999999999, 'mozarella-sticks': 0.0, 'hot-wings': 7.0999999999999996},\n {'side-salad': 0.0, 'french-fries': 0.0, 'sampler-plate': 0.0, 'mixed-fruit': 15.049999999999999, 'mozarella-sticks': 0.0, 'hot-wings': 0.0}]\n" }, { "answer_id": 398109, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 2, "selected": false, "text": "....\n\nprivate void findAndReportSolutions(\n int target, // goal to be achieved\n int balance, // amount of goal remaining\n int index // menu item to try next\n) {\n ++calls;\n if (balance == 0) {\n reportSolution(target);\n return; // no addition to perfect order is possible\n }\n if (index == items.length) {\n ++falls;\n return; // ran out of menu items without finding solution\n }\n final int price = items[index].price;\n if (balance < price) {\n return; // all remaining items cost too much\n }\n int maxCount = balance / price; // max uses for this item\n for (int n = maxCount; 0 <= n; --n) { // loop for this item, recur for others\n ++loops;\n counts[index] = n;\n findAndReportSolutions(\n target, balance - n * price, index + 1\n );\n }\n}\n\npublic void reportSolutionsFor(int target) {\n counts = new int[items.length];\n calls = loops = falls = 0;\n findAndReportSolutions(target, target, 0);\n ps.printf(\"%d calls, %d loops, %d falls%n\", calls, loops, falls);\n}\n\npublic static void main(String[] args) {\n MenuItem[] items = {\n new MenuItem(\"mixed fruit\", 215),\n new MenuItem(\"french fries\", 275),\n new MenuItem(\"side salad\", 335),\n new MenuItem(\"hot wings\", 355),\n new MenuItem(\"mozzarella sticks\", 420),\n new MenuItem(\"sampler plate\", 580),\n };\n Solver solver = new Solver(items);\n solver.reportSolutionsFor(1505);\n}\n\n...\n 7 mixed fruit (1505) = 1505\n1 mixed fruit (215) + 2 hot wings (710) + 1 sampler plate (580) = 1505\n348 calls, 347 loops, 79 falls\n findAndReportSolution(...) index" }, { "answer_id": 936743, "author": "kinghajj", "author_id": 76721, "author_profile": "https://Stackoverflow.com/users/76721", "pm_score": 0, "selected": false, "text": "(items-with-price 15.05) (items-with-price 100) nil ;; np-complete.clj\n;; A Clojure solution to XKCD #287 \"NP-Complete\"\n;; By Sam Fredrickson\n;;\n;; The function \"items-with-price\" returns a sequence of items whose sum price\n;; is equal to the given price, or nil.\n\n(defstruct item :name :price)\n\n(def *items* #{(struct item \"Mixed Fruit\" 2.15)\n (struct item \"French Fries\" 2.75)\n (struct item \"Side Salad\" 3.35)\n (struct item \"Hot Wings\" 3.55)\n (struct item \"Mozzarella Sticks\" 4.20)\n (struct item \"Sampler Plate\" 5.80)})\n\n(defn items-with-price [price]\n (let [check-count (atom 0)\n recur-count (atom 0)\n result (atom nil)\n checker (agent nil)\n ; gets the total price of a seq of items.\n items-price (fn [items] (apply + (map #(:price %) items)))\n ; checks if the price of the seq of items matches the sought price.\n ; if so, it changes the result atom. if the result atom is already\n ; non-nil, nothing is done.\n check-items (fn [unused items]\n (swap! check-count inc)\n (if (and (nil? @result)\n (= (items-price items) price))\n (reset! result items)))\n ; lazily generates a list of combinations of the given seq s.\n ; haven't tested well...\n combinations (fn combinations [cur s]\n (swap! recur-count inc)\n (if (or (empty? s)\n (> (items-price cur) price))\n '()\n (cons cur\n (lazy-cat (combinations (cons (first s) cur) s)\n (combinations (cons (first s) cur) (rest s))\n (combinations cur (rest s))))))]\n ; loops through the combinations of items, checking each one in a thread\n ; pool until there are no more combinations or the result atom is non-nil.\n (loop [items-comb (combinations '() (seq *items*))]\n (if (and (nil? @result)\n (not-empty items-comb))\n (do (send checker check-items (first items-comb))\n (recur (rest items-comb)))))\n (await checker)\n (println \"No. of recursions:\" @recur-count)\n (println \"No. of checks:\" @check-count)\n @result))\n" }, { "answer_id": 959851, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 1, "selected": false, "text": "class Solver(object):\n def __init__(self):\n self.solved = False\n self.total = 0\n def solve(s, p, pl, curList = []):\n poss = [i for i in sorted(pl, reverse = True) if i <= p]\n if len(poss) == 0 or s.solved:\n s.total += 1\n return curList\n if abs(poss[0]-p) < 0.00001:\n s.solved = True # Solved it!!!\n s.total += 1\n return curList + [poss[0]]\n ml,md = [], 10**8\n for j in [s.solve(p-i, pl, [i]) for i in poss]:\n if abs(sum(j)-p)<md: ml,md = j, abs(sum(j)-p)\n s.total += 1\n return ml + curList\n\n\npriceList = [5.8, 4.2, 3.55, 3.35, 2.75, 2.15]\nappetizers = ['Sampler Plate', 'Mozzarella Sticks', \\\n 'Hot wings', 'Side salad', 'French Fries', 'Mixed Fruit']\n\nmenu = zip(priceList, appetizers)\n\nsol = Solver()\nq = sol.solve(15.05, priceList)\nprint 'Total time it runned: ', sol.total\nprint '-'*30\norder = [(m, q.count(m[0])) for m in menu if m[0] in q]\nfor o in order:\n print '%d x %s \\t\\t\\t (%.2f)' % (o[1],o[0][1],o[0][0])\n\nprint '-'*30\nts = 'Total: %.2f' % sum(q)\nprint ' '*(30-len(ts)-1),ts\n Total time it runned: 29\n------------------------------\n1 x Sampler Plate (5.80)\n2 x Hot wings (3.55)\n1 x Mixed Fruit (2.15)\n------------------------------\n Total: 15.05\n" }, { "answer_id": 2022885, "author": "Scott McDonald", "author_id": 245805, "author_profile": "https://Stackoverflow.com/users/245805", "pm_score": 0, "selected": false, "text": "public class NPComplete {\n private static final int[] FOOD = { 580, 420, 355, 335, 275, 215 };\n private static int tries;\n\n public static void main(String[] ignore) {\n tries = 0;\n addFood(1505, \"\", 0);\n System.out.println(\"Combinations tried: \" + tries);\n }\n\n private static void addFood(int goal, String result, int index) {\n // If no more food to add, see if this is a solution\n if (index >= FOOD.length) {\n tries++;\n if (goal == 0)\n System.out.println(tries + \" tries: \" + result.substring(3));\n return;\n }\n\n // Try all possible quantities of this food\n // If this is the last food item, only try the max quantity\n int qty = goal / FOOD[index];\n do {\n addFood(goal - qty * FOOD[index],\n result + \" + \" + qty + \" * \" + FOOD[index], index + 1);\n } while (index < FOOD.length - 1 && --qty >= 0);\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
141,780
<p>Okay, I am sure this is simple but it is driving me nuts. I recently went to work on a program where I have had to step back in time a bit and use Redhat 9. When I'm typing on the command line from a standard xterm running KornShell (ksh), and I reach the end of the line the screen slides to the right (cutting off the left side of my command) instead of wrapping the text around to a new line. This makes things difficult for me because I can't easily copy and paste from the previous command straight from the command line. I have to look at the history and paste the command from there. In case you are wondering, I do a lot of command-line awk scripts that cause the line to get quite long. </p> <p>Is there a way to force the command line to wrap instead of shifting visibility to the right side of the command I am typing? </p> <p>I have poured through man page options with no luck. </p> <p>I'm running:</p> <ul> <li>XFree86 4.2.99.903(174)</li> <li>KSH 5.2.14. </li> </ul> <p>Thanks.</p>
[ { "answer_id": 143070, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "'\\''" }, { "answer_id": 152867, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "man ksh set -o multiline man ksh" }, { "answer_id": 152909, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 0, "selected": false, "text": "strings ~/.history | grep COMMAND\n strings ~/.history | tail\n" }, { "answer_id": 18754248, "author": "Tankman六四", "author_id": 1758793, "author_profile": "https://Stackoverflow.com/users/1758793", "pm_score": 2, "selected": false, "text": "$ set -o multiline\n $ set +o emacs\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22810/" ]
141,802
<p>I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.</p> <p>(This is a variation on my question about <a href="https://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system">debugging memleaks in a production system</a>.)</p>
[ { "answer_id": 12690278, "author": "HoverHell", "author_id": 62821, "author_profile": "https://Stackoverflow.com/users/62821", "pm_score": 1, "selected": false, "text": "dir() getattr()" }, { "answer_id": 73086039, "author": "Eduardo", "author_id": 709975, "author_profile": "https://Stackoverflow.com/users/709975", "pm_score": 2, "selected": false, "text": "dump_session load_session" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9585/" ]
141,808
<p>I have a micro-mini-search engine that highlights the search terms in my rails app. The search ignores accents and the highlight is case insensitive. Almost perfect. But, for instance if I have a record with the text "pão de queijo" and searches for "pao de queijo" the record <strong>is</strong> returned but the iext <strong>is not</strong> highlighted. Similarly, if I search for "pÃo de queijo" the record is returned but not highlighted properly.</p> <p>My code is as simple as:</p> <pre><code>&lt;%= highlight(result_pessoa.observacoes, search_string, '&lt;span style="background-color: yellow;"&gt;\1&lt;/span&gt;') %&gt; </code></pre>
[ { "answer_id": 1922265, "author": "johno", "author_id": 233852, "author_profile": "https://Stackoverflow.com/users/233852", "pm_score": 3, "selected": true, "text": " # Highlights one or more +phrases+ everywhere in +text+ by inserting it into\n # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>\n # as a single-quoted string with \\1 where the phrase is to be inserted (defaults to\n # '<strong class=\"highlight\">\\1</strong>')\n #\n # ==== Examples\n # highlight('You searched for: rails', 'rails')\n # # => You searched for: <strong class=\"highlight\">rails</strong>\n #\n # highlight('You searched for: ruby, rails, dhh', 'actionpack')\n # # => You searched for: ruby, rails, dhh\n #\n # highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\\1</em>')\n # # => You searched <em>for</em>: <em>rails</em>\n #\n # highlight('You searched for: rails', 'rails', :highlighter => '<a href=\"search?q=\\1\">\\1</a>')\n # # => You searched for: <a href=\"search?q=rails\">rails</a>\n #\n # highlight('Šumné dievčatá', ['šumňe', 'dievca'], :ignore_special_chars => true)\n # # => <strong class=\"highlight\">Šumné</strong> <strong class=\"highlight\">dievča</strong>tá \n #\n # You can still use <tt>highlight</tt> with the old API that accepts the\n # +highlighter+ as its optional third parameter:\n # highlight('You searched for: rails', 'rails', '<a href=\"search?q=\\1\">\\1</a>') # => You searched for: <a href=\"search?q=rails\">rails</a>\n def highlight(text, phrases, *args)\n options = args.extract_options!\n unless args.empty?\n options[:highlighter] = args[0] || '<strong class=\"highlight\">\\1</strong>'\n end\n options.reverse_merge!(:highlighter => '<strong class=\"highlight\">\\1</strong>')\n\n if text.blank? || phrases.blank?\n text\n else\n haystack = text.clone\n match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')\n if options[:ignore_special_chars]\n haystack = haystack.mb_chars.normalize(:kd)\n match = match.mb_chars.normalize(:kd).gsub(/[^\\x00-\\x7F]+/n, '').gsub(/\\w/, '\\0[^\\x00-\\x7F]*')\n end\n highlighted = haystack.gsub(/(#{match})(?!(?:[^<]*?)(?:[\"'])[^<>]*>)/i, options[:highlighter])\n highlighted = highlighted.mb_chars.normalize(:kc) if options[:ignore_special_chars]\n highlighted\n end\n end\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
141,810
<p>I have a corrupt database. If I open it in MS Access, MS Access offers to repair it, and it succeeds.</p> <p>How can I do that with code? On a machine where MS Access is not installed.</p> <p>I know from trying it that JRO.JetEngine.CompactDatabase does NOT work.</p> <p>In other words, I want to do what Access or JETCOMP.exe is doing, not what JRO.JetEngine.CompactDatabase is doing.</p>
[ { "answer_id": 141857, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 1, "selected": false, "text": "/compact\n" }, { "answer_id": 141882, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "Call Shell(\"Jetcomp.exe <arguments>\")\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
141,820
<p>I know a Haskell module name, but I can't figure out in what package it is defined. This is bad because I can't compile without a package exposing this module.</p> <p>Specificaly it is Text.Regex that I can't locate, but I would like to know how to solve that problem in general.</p>
[ { "answer_id": 5970428, "author": "hammar", "author_id": 98117, "author_profile": "https://Stackoverflow.com/users/98117", "pm_score": 2, "selected": false, "text": "cabal build Main.hs:1:8:\n Could not find module `Text.Regex':\n It is a member of the hidden package `regex-compat-0.93.1'.\n Perhaps you need to add `regex-compat' to the build-depends in your .cabal file.\n Use -v to see a list of the files searched for.\n" }, { "answer_id": 7534642, "author": "Joachim Breitner", "author_id": 946226, "author_profile": "https://Stackoverflow.com/users/946226", "pm_score": 0, "selected": false, "text": "/usr/share/doc/ghc-doc/html/libraries/index.html" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5978/" ]
141,828
<p>I just did a <strong>delete from table</strong></p> <p>How do I roll back or undelete the rows??</p>
[ { "answer_id": 141840, "author": "Wes P", "author_id": 13611, "author_profile": "https://Stackoverflow.com/users/13611", "pm_score": 4, "selected": true, "text": "begin transaction commit rollback" }, { "answer_id": 141849, "author": "Oli", "author_id": 15296, "author_profile": "https://Stackoverflow.com/users/15296", "pm_score": 0, "selected": false, "text": "rollback;\n" }, { "answer_id": 142066, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "BACKUP LOG DBName\n TO DISK='C:\\DBName.TRN'\nGO\n\nRESTORE DATABASE DBName2\n FROM DISK='C:\\DBName.BAK'\n WITH \n MOVE 'DBName.MDF' TO 'C:\\DBName2.MDF',\n MOVE 'DBName.LDF' TO 'C:\\DBName2.LDF',\n NORECOVERY\nGO\n\nRESTORE LOG DBName2\n FROM DISK='C:\\DBName.TRN'\n WITH\n RECOVERY,\n STOPAT = '09/26/2008 17:00'\nGO\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3522/" ]
141,855
<p><strong>Motivation</strong></p> <p>I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI.</p> <p><strong>Possibility 1</strong></p> <p>Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want?</p> <p><strong>Possibility 2</strong></p> <p>My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?</p>
[ { "answer_id": 141867, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 5, "selected": false, "text": "public static Color Lighten(Color inColor, double inAmount)\n{\n return Color.FromArgb(\n inColor.A,\n (int) Math.Min(255, inColor.R + 255 * inAmount),\n (int) Math.Min(255, inColor.G + 255 * inAmount),\n (int) Math.Min(255, inColor.B + 255 * inAmount) );\n}\n" }, { "answer_id": 141877, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "\nfor(i = 0; i < 16; i++)\n{\n colors[i].R = start.R + (i * (end.R - start.R)) / 15;\n colors[i].G = start.G + (i * (end.G - start.G)) / 15;\n colors[i].B = start.B + (i * (end.B - start.B)) / 15;\n}\n" }, { "answer_id": 141943, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": false, "text": "def clamp_rgb(r, g, b):\n return min(255, int(r)), min(255, int(g)), min(255, int(b))\n\ndef redistribute_rgb(r, g, b):\n threshold = 255.999\n m = max(r, g, b)\n if m <= threshold:\n return int(r), int(g), int(b)\n total = r + g + b\n if total >= 3 * threshold:\n return int(threshold), int(threshold), int(threshold)\n x = (3 * threshold - total) / (3 * m - total)\n gray = threshold - x * m\n return int(gray + x * r), int(gray + x * g), int(gray + x * b)\n clamp_rgb redistribute_rgb colorsys L" }, { "answer_id": 221431, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 4, "selected": false, "text": "public static Color Dark(Color baseColor, float percOfDarkDark);\n" }, { "answer_id": 13045535, "author": "Pavel Vladov", "author_id": 698498, "author_profile": "https://Stackoverflow.com/users/698498", "pm_score": 3, "selected": false, "text": "float correctionFactor = 0.5f;\nfloat red = (255 - color.R) * correctionFactor + color.R;\nfloat green = (255 - color.G) * correctionFactor + color.G;\nfloat blue = (255 - color.B) * correctionFactor + color.B;\nColor lighterColor = Color.FromArgb(color.A, (int)red, (int)green, (int)blue);\n" }, { "answer_id": 14486731, "author": "user1873073", "author_id": 1873073, "author_profile": "https://Stackoverflow.com/users/1873073", "pm_score": 2, "selected": false, "text": "function calcLightness(l, r, g, b) {\n var tmp_r = r;\n var tmp_g = g;\n var tmp_b = b;\n\n tmp_r = (255 - r) * l + r;\n tmp_g = (255 - g) * l + g;\n tmp_b = (255 - b) * l + b;\n\n if (tmp_r > 255 || tmp_g > 255 || tmp_b > 255) \n return { r: r, g: g, b: b };\n else \n return { r:parseInt(tmp_r), g:parseInt(tmp_g), b:parseInt(tmp_b) }\n}\n" }, { "answer_id": 20687331, "author": "prewett", "author_id": 218226, "author_profile": "https://Stackoverflow.com/users/218226", "pm_score": 1, "selected": false, "text": "oneMinus = 1.0 - amount\nr = amount + oneMinus * r\ng = amount + oneMinus * g\nb = amount + oneMinus * b\n amount oneMinus = 1.0 - amount\nr = amount * dest_r + oneMinus * r\ng = amount * dest_g + oneMinus * g\nb = amount * dest_b + oneMinus * b\n (dest_r, dest_g, dest_b) amount (r, g, b) (dest.r, dest.g, dest.b)" }, { "answer_id": 21547078, "author": "Pimp Trizkit", "author_id": 693927, "author_profile": "https://Stackoverflow.com/users/693927", "pm_score": 1, "selected": false, "text": "shadeColor2" }, { "answer_id": 43838620, "author": "Aidan", "author_id": 597597, "author_profile": "https://Stackoverflow.com/users/597597", "pm_score": 0, "selected": false, "text": "def lighten(hex, amount):\n \"\"\" Lighten an RGB color by an amount (between 0 and 1),\n\n e.g. lighten('#4290e5', .5) = #C1FFFF\n \"\"\"\n hex = hex.replace('#','')\n red = min(255, int(hex[0:2], 16) + 255 * amount)\n green = min(255, int(hex[2:4], 16) + 255 * amount)\n blue = min(255, int(hex[4:6], 16) + 255 * amount)\n return \"#%X%X%X\" % (int(red), int(green), int(blue))\n" }, { "answer_id": 49835284, "author": "Ari", "author_id": 1383356, "author_profile": "https://Stackoverflow.com/users/1383356", "pm_score": 1, "selected": false, "text": "javascript nodejs tinycolor(\"red\").lighten().desaturate().toHexString() // \"#f53d3d\" \n" }, { "answer_id": 70125978, "author": "john16384", "author_id": 1262865, "author_profile": "https://Stackoverflow.com/users/1262865", "pm_score": 0, "selected": false, "text": "clampRGB clampRGB private static Color convertToDesiredLuminance(Color input, double desiredLuminance) {\n if(desiredLuminance > 1.0) {\n return Color.WHITE;\n }\n if(desiredLuminance < 0.0) {\n return Color.BLACK;\n }\n\n double ratio = desiredLuminance / luminance(input);\n double r = Double.isInfinite(ratio) ? desiredLuminance : toLinear(input.getRed()) * ratio;\n double g = Double.isInfinite(ratio) ? desiredLuminance : toLinear(input.getGreen()) * ratio;\n double b = Double.isInfinite(ratio) ? desiredLuminance : toLinear(input.getBlue()) * ratio;\n\n if(r > 1.0 || g > 1.0 || b > 1.0) { // anything outside range?\n double br = Math.min(r, 1.0); // base values\n double bg = Math.min(g, 1.0);\n double bb = Math.min(b, 1.0);\n double rr = 1.0 - br; // ratios between RGB components to maintain\n double rg = 1.0 - bg;\n double rb = 1.0 - bb;\n\n double x = (desiredLuminance - luminance(br, bg, bb)) / luminance(rr, rg, rb);\n\n r = 0.0001 * Math.round(10000.0 * (br + rr * x));\n g = 0.0001 * Math.round(10000.0 * (bg + rg * x));\n b = 0.0001 * Math.round(10000.0 * (bb + rb * x));\n }\n\n return Color.color(toGamma(r), toGamma(g), toGamma(b));\n}\n private static double toLinear(double v) { // inverse is #toGamma\n return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\n}\n\nprivate static double toGamma(double v) { // inverse is #toLinear\n return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1.0 / 2.4) - 0.055;\n}\n\nprivate static double luminance(Color c) {\n return luminance(toLinear(c.getRed()), toLinear(c.getGreen()), toLinear(c.getBlue()));\n}\n\nprivate static double luminance(double r, double g, double b) {\n return r * 0.2126 + g * 0.7152 + b * 0.0722;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9960/" ]
141,864
<p>I need help understanding some C++ operator overload statements. The class is declared like this: </p> <pre><code>template &lt;class key_t, class ipdc_t&gt; class ipdc_map_template_t : public ipdc_lockable_t { ... typedef map&lt;key_t, ipdc_t*, less&lt;key_t&gt;&gt; map_t; ... </code></pre> <p>The creator of the class has created an iterator for the internal map structure:</p> <pre><code>struct iterator : public map_t::iterator { iterator() {} iterator(const map_t::iterator &amp; it) : map_t::iterator(it) {} iterator(const iterator &amp; it) : map_t::iterator( *static_cast&lt;const map_t::iterator *&gt;(&amp;it)) {} operator key_t() {return ((this-&gt;operator*()).first);} // I don't understand this. operator ipdc_t*() const {return ((this-&gt;operator*()).second);} // or this. }; </code></pre> <p>And begin() and end() return the begin() and end() of the map:</p> <pre><code>iterator begin() {IT_ASSERT(is_owner()); return map.begin();} iterator end() {return map.end();} </code></pre> <p>My question is, if I have an iterator, how do I use those overloads to get the key and the value?</p> <pre><code>ipdc_map_template_t::iterator iter; for( iter = my_instance.begin(); iter != my_instance.end(); ++iter ) { key_t my_key = ??????; ipdc_t *my_value = ??????; } </code></pre>
[ { "answer_id": 141893, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": " typedef ipdc_map_template_t<int,std::string> MyMap;\n MyMap mymap;\n\n for(MyMap::iterator iter = mymap.begin();\n iter != mymap.end();\n ++iter )\n {\n int my_key = iter;\n std::string* my_value = iter;\n\n }\n" }, { "answer_id": 141903, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 2, "selected": false, "text": "ipdc_map_template_t::iterator iter;\n for( iter = my_instance.begin();\n iter != my_instance.end();\n ++iter )\n {\n key_t my_key = iter;\n ipdc_t my_value = iter;\n }\n" }, { "answer_id": 141926, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 4, "selected": true, "text": "{\n key_t key = iter;\n ipdc_t *val = iter;\n}\n ipdc_map_template::iterator std::map::iterator {\n key_t key = (*iter).first;\n ipdc_t *val = (*iter).second;\n\n // or, equivalently\n key_t key = iter->first;\n ipdc_t *val = iter->second;\n\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19719/" ]
141,875
<p>What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:</p> <pre><code>number: (MONTH|INT); </code></pre> <p>It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:</p> <pre><code>date: month '/' day ( '/' year )? -&gt; ^('DATE' year month day); </code></pre> <p>I don't care if month,day &amp; year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:</p> <pre><code>foo: STRING OP number -&gt; ^(OP STRING number); STRING: ('a'..'z')+; OP: ('&lt;'|'&gt;'); </code></pre>
[ { "answer_id": 142009, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "INT: '0'..'9'+;\n DATENUM: '0' '1'..'9';\nINT: '0' | SIGN? '1'..'9' '0'..'9'*;\n date: INT '/' INT ( '/' INT )?\n date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?\n date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}\n" }, { "answer_id": 31711538, "author": "simonrkeen", "author_id": 5171119, "author_profile": "https://Stackoverflow.com/users/5171119", "pm_score": 1, "selected": false, "text": "// parser rules\n\ndate \n : INT SEPARATOR month SEPARATOR INT\n | INT SEPARATOR month SEPARATOR INT4\n | INT SEPARATOR INT SEPARATOR INT4;\n\nmonth : JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC ;\n\nnumber : FLOAT | INT | INT4 ;\n\n// lexer rules\n\nFLOAT : DIGIT+ '.' DIGIT+ ;\n\nINT4 : DIGIT DIGIT DIGIT DIGIT;\nINT : DIGIT+;\n\nJAN : [Jj][Aa][Nn] ;\nFEB : [Ff][Ee][Bb] ;\nMAR : [Mm][Aa][Rr] ;\nAPR : [Aa][Pp][Rr] ;\nMAY : [Mm][Aa][Yy] ; \nJUN : [Jj][Uu][Nn] ;\nJUL : [Jj][Uu][Ll] ;\nAUG : [Aa][Uu][Gg] ;\nSEP : [Ss][Ee][Pp] ; \nOCT : [Oo][Cc][Tt] ; \nNOV : [Nn][Oo][Vv] ;\nDEC : [Dd][Ee][Cc] ;\n\nSEPARATOR : [/\\\\\\-] ;\n\nfragment DIGIT : [0-9];\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12034/" ]
141,876
<p>Platform: Windows XP Development Platform: VB6</p> <p>When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.</p> <p>Does anyone have a workaround or fix for this? </p> <hr> <p>Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) . </p> <p>Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string. </p> <p>I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB. </p>
[ { "answer_id": 142214, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 2, "selected": false, "text": "Private Sub Form_Load()\n App.Title = String(41, \"X\")\n MsgBox Len(App.Title)\nEnd Sub\n Dim nTitleBarTextWidth As Long\nDim nNewWidth As Long\n\nMe.Caption = \"My really really really really really long app title here\"\n\n' Get titlebar text width (somehow) '\nnTitleBarTextWidth = GetTitleBarTextWidth()\n\n' Compute the new width for the Form such that the title will fit within it '\n' (May have to add a constant to this to make sure the title fits correctly) '\nnNewWidth = Me.ScaleX(nTitleBarTextWidth, vbPixels, Me.ScaleMode)\n\n' If the new width is bigger than the forms current size, use the new width '\nIf nNewWidth > Me.Width Then\n Form.Width = nNewWidth\nEnd If\n" }, { "answer_id": 142943, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 3, "selected": true, "text": "Option Explicit\n\nPrivate Type SIZE\n cx As Long\n cy As Long\nEnd Type\n\nPrivate Const LF_FACESIZE = 32\n\n'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):'\n' '\n' For some bizarre reason, maybe to do with byte '\n' alignment, the LOGFONT structure we must apply '\n' to NONCLIENTMETRICS seems to require an LF_FACESIZE '\n' 4 bytes smaller than normal: '\n\nPrivate Type NMLOGFONT\n lfHeight As Long\n lfWidth As Long\n lfEscapement As Long\n lfOrientation As Long\n lfWeight As Long\n lfItalic As Byte\n lfUnderline As Byte\n lfStrikeOut As Byte\n lfCharSet As Byte\n lfOutPrecision As Byte\n lfClipPrecision As Byte\n lfQuality As Byte\n lfPitchAndFamily As Byte\n lfFaceName(LF_FACESIZE - 4) As Byte\nEnd Type\n\nPrivate Type LOGFONT\n lfHeight As Long\n lfWidth As Long\n lfEscapement As Long\n lfOrientation As Long\n lfWeight As Long\n lfItalic As Byte\n lfUnderline As Byte\n lfStrikeOut As Byte\n lfCharSet As Byte\n lfOutPrecision As Byte\n lfClipPrecision As Byte\n lfQuality As Byte\n lfPitchAndFamily As Byte\n lfFaceName(LF_FACESIZE) As Byte\nEnd Type\n\nPrivate Type NONCLIENTMETRICS\n cbSize As Long\n iBorderWidth As Long\n iScrollWidth As Long\n iScrollHeight As Long\n iCaptionWidth As Long\n iCaptionHeight As Long\n lfCaptionFont As NMLOGFONT\n iSMCaptionWidth As Long\n iSMCaptionHeight As Long\n lfSMCaptionFont As NMLOGFONT\n iMenuWidth As Long\n iMenuHeight As Long\n lfMenuFont As NMLOGFONT\n lfStatusFont As NMLOGFONT\n lfMessageFont As NMLOGFONT\nEnd Type\n\nPrivate Enum SystemMetrics\n SM_CXBORDER = 5\n SM_CXDLGFRAME = 7\n SM_CXFRAME = 32\n SM_CXSCREEN = 0\n SM_CXICON = 11\n SM_CXICONSPACING = 38\n SM_CXSIZE = 30\n SM_CXEDGE = 45\n SM_CXSMICON = 49\n SM_CXSMSIZE = 52\nEnd Enum\n\nPrivate Const SPI_GETNONCLIENTMETRICS = 41\nPrivate Const SPI_SETNONCLIENTMETRICS = 42\n\nPrivate Declare Function GetTextExtentPoint32 Lib \"gdi32\" Alias \"GetTextExtentPoint32A\" _\n (ByVal hdc As Long, _\n ByVal lpszString As String, _\n ByVal cbString As Long, _\n lpSize As SIZE) As Long\n\nPrivate Declare Function GetSystemMetrics Lib \"user32\" (ByVal nIndex As SystemMetrics) As Long\n\nPrivate Declare Function SystemParametersInfo Lib \"user32\" Alias \"SystemParametersInfoA\" ( _\n ByVal uAction As Long, _\n ByVal uParam As Long, _\n lpvParam As Any, _\n ByVal fuWinIni As Long) As Long\n\nPrivate Declare Function SelectObject Lib \"gdi32\" (ByVal hdc As Long, ByVal hObject As Long) As Long\nPrivate Declare Function DeleteObject Lib \"gdi32\" (ByVal hObject As Long) As Long\nPrivate Declare Function CreateFontIndirect Lib \"gdi32\" Alias \"CreateFontIndirectA\" (lpLogFont As LOGFONT) As Long\n\nPrivate Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" (Destination As Any, Source As Any, ByVal Length As Long)\n\nPrivate Function GetCaptionTextWidth(ByVal frm As Form) As Long\n\n '-----------------------------------------------'\n ' This function does the following: '\n ' '\n ' 1. Get the font used for the forms caption '\n ' 2. Call GetTextExtent32 to get the width in '\n ' pixels of the forms caption '\n ' 3. Convert the width from pixels into '\n ' the scaling mode being used by the form '\n ' '\n '-----------------------------------------------'\n\n Dim sz As SIZE\n Dim hOldFont As Long\n Dim hCaptionFont As Long\n Dim CaptionFont As LOGFONT\n Dim ncm As NONCLIENTMETRICS\n\n ncm.cbSize = LenB(ncm)\n\n If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then\n ' What should we do if we the call fails? Change as needed for your app,'\n ' but this call is unlikely to fail anyway'\n Exit Function\n End If\n\n CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont)\n\n hCaptionFont = CreateFontIndirect(CaptionFont)\n hOldFont = SelectObject(frm.hdc, hCaptionFont)\n\n GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz\n GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode)\n\n 'clean up, otherwise bad things will happen...'\n DeleteObject (SelectObject(frm.hdc, hOldFont))\n\nEnd Function\n\nPrivate Function GetControlBoxWidth(ByVal frm As Form) As Long\n\n Dim nButtonWidth As Long\n Dim nButtonCount As Long\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n nButtonCount = 1 'close button is always present'\n nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar'\n\n ' account for min and max buttons if they are visible'\n If frm.MinButton Then nButtonCount = nButtonCount + 1\n If frm.MaxButton Then nButtonCount = nButtonCount + 1\n\n nFinalWidth = nButtonWidth * nButtonCount\n\n End If\n\n 'convert to whatever scale the form is using'\n GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPrivate Function GetIconWidth(ByVal frm As Form) As Long\n\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n Select Case frm.BorderStyle\n\n Case vbFixedSingle, vbFixedDialog, vbSizable:\n 'we have an icon, gets its width'\n nFinalWidth = GetSystemMetrics(SM_CXSMICON)\n Case Else:\n 'no icon present, so report zero width'\n nFinalWidth = 0\n\n End Select\n\n End If\n\n 'convert to whatever scale the form is using'\n GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPrivate Function GetFrameWidth(ByVal frm As Form) As Long\n\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n Select Case frm.BorderStyle\n\n Case vbFixedSingle, vbFixedDialog:\n nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME)\n Case vbSizable:\n nFinalWidth = GetSystemMetrics(SM_CXFRAME)\n End Select\n\n End If\n\n 'convert to whatever scale the form is using'\n GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPrivate Function GetBorderWidth(ByVal frm As Form) As Long\n\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n Select Case frm.Appearance\n\n Case 0 'flat'\n nFinalWidth = GetSystemMetrics(SM_CXBORDER)\n Case 1 '3D'\n nFinalWidth = GetSystemMetrics(SM_CXEDGE)\n End Select\n\n End If\n\n 'convert to whatever scale the form is using'\n GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPublic Function GetRecommendedWidth(ByVal frm As Form) As Long\n\n Dim nNewWidth As Long\n\n ' An abitrary amount of extra padding so that the caption text '\n ' is not scrunched up against the min/max/close buttons '\n\n Const PADDING_TWIPS = 120\n\n nNewWidth = _\n GetCaptionTextWidth(frm) _\n + GetControlBoxWidth(frm) _\n + GetIconWidth(frm) _\n + GetFrameWidth(frm) * 2 _\n + GetBorderWidth(frm) * 2 _\n + PADDING_TWIPS\n\n If nNewWidth > frm.Width Then\n GetRecommendedWidth = nNewWidth\n Else\n GetRecommendedWidth = frm.Width\n End If\n\nEnd Function\n Private Sub Form_Load()\n\n Me.Caption = String(100, \"x\") 'replace this with your caption'\n Me.Width = GetRecommendedWidth(Me)\n\nEnd Sub\n" }, { "answer_id": 143411, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 2, "selected": false, "text": "Function MsgBox(Prompt, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title, Optional HelpFile, Optional Context) As VbMsgBoxResult\n If IsMissing(Title) Then Title = String(40, \"x\") & \"abc\"\n MsgBox = Interaction.MsgBox(Prompt, Buttons, Title, HelpFile, Context)\nEnd Function\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
141,878
<p>The following snippet is supposed to take the value of PROJECT (defined in the Makefile) and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR</p> <p>I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?</p> <pre><code>#define PROJECT classifier #define QMAKESTR(x) #x #define MAKESTR(x) QMAKESTR(x) #define MAKEINC(x) x ## _ir.h #define PROJECTINC MAKEINC(PROJECT) #define PROJECTINCSTR MAKESTR(PROJECTINC) #include PROJECTINCSTR </code></pre> <p>Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.</p>
[ { "answer_id": 141930, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 4, "selected": true, "text": "#define QMAKESTR(x) #x\n#define MAKESTR(x) QMAKESTR(x)\n#define SMASH(x,y) x##y\n#define MAKEINC(x) SMASH(x,_ir.h)\n#define PROJECTINC MAKEINC(PROJECT)\n#define PROJECTINCSTR MAKESTR(PROJECTINC)" }, { "answer_id": 141962, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "#define QMAKESTR(x) #x\n#define MAKESTR(x) QMAKESTR(x)\n#define MAKEINC(x) x ## _ir.h\n#define PROJECTINC(x) MAKEINC(x)\n#define PROJECTINCSTR MAKESTR(PROJECTINC(PROJECT))\n\n#include PROJECTINCSTR\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22781/" ]
141,885
<p>Is there a nice way to dependency inject using a jsp taglib?</p> <p>either using ejb 3.0, spring, or guice...</p> <p>I have a lot of services/pojos that I would like to use in my taglibs</p>
[ { "answer_id": 20874815, "author": "Capn Sparrow", "author_id": 1140456, "author_profile": "https://Stackoverflow.com/users/1140456", "pm_score": 0, "selected": false, "text": "public class GuiceServletConfig extends GuiceServletContextListener {\n\n@Override\nprotected Injector getInjector() {\n return Guice.createInjector(blah, blah);\n}\n\n@Override\npublic void contextDestroyed(ServletContextEvent servletContextEvent) {\n ServletContext servletContext = servletContextEvent.getServletContext();\n servletContext.removeAttribute(Injector.class.getName());\n super.contextDestroyed(servletContextEvent);\n}\n\n@Override\npublic void contextInitialized(ServletContextEvent servletContextEvent) {\n Injector injector = getInjector();\n ServletContext servletContext = servletContextEvent.getServletContext();\n servletContext.setAttribute(Injector.class.getName(), injector);\n super.contextInitialized(servletContextEvent);\n}\n @Singleton\n@SuppressWarnings(\"serial\")\npublic class MySampleTag extends TagSupport {\n@Inject private MyInjectedService myService;\n\n@Override\npublic int doStartTag() throws JspException {\n Injector injector = (Injector) pageContext.getServletContext().getAttribute(Injector.class.getName());\n injector.injectMembers(this);\n\n String value = myService.doSomething();\n etc.\n etc.\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641/" ]
141,888
<p>This must be a classic .NET question for anyone migrating from Java. </p> <p>.NET does not seem to have a direct equivalent to java.io.StreamTokenizer, however the JLCA provides a SupportClass that attempts to implement it. I believe the JLCA also provides a Tokenizer SupportClass that takes a String as the source, which I thought a StreamTokenizer would be derived from, but isn't.</p> <p><strike>What is the <em>preferred</em> way to Tokenize both a Stream and a String? or is there one?</strike> How are streams tokenized in .Net? I'd like to have the flexibility that java.io.StreamTokenizer provides. Any thoughts?</p>
[ { "answer_id": 141892, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "string.Split(...)" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18051/" ]
141,913
<p>I'm parsing XML results from an API call using PHP and xpath. </p> <pre><code> $dom = new DOMDocument(); $dom-&gt;loadXML($response-&gt;getBody()); $xpath = new DOMXPath($dom); $xpath-&gt;registerNamespace("a", "http://www.example.com"); $hrefs = $xpath-&gt;query('//a:Books/text()', $dom); for ($i = 0; $i &lt; $hrefs-&gt;length; $i++) { $arrBookTitle[$i] = $hrefs-&gt;item($i)-&gt;data; } $hrefs = $xpath-&gt;query('//a:Books', $dom); for ($i = 0; $i &lt; $hrefs-&gt;length; $i++) { $arrBookDewey[$i] = $hrefs-&gt;item($i)-&gt;getAttribute('DeweyDecimal'); } </code></pre> <p>This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed?</p>
[ { "answer_id": 141933, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);\n" }, { "answer_id": 143029, "author": "Scott Gottreu", "author_id": 2863, "author_profile": "https://Stackoverflow.com/users/2863", "pm_score": 3, "selected": true, "text": "$hrefs = $xpath->query('//a:Books', $dom);\n\nfor ($i = 0; $i < $hrefs->length; $i++) {\n $arrBookTitle[$i] = $hrefs->item($i)->nodeValue;\n $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');\n}\n" }, { "answer_id": 143360, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": false, "text": "$xml=simplexml_load_string($response->getBody());\n$xml->registerXPathNamespace('a', 'http://www.example.com');\n$books=$xml->xpath('//a:Books');\nforeach ($books as $i => $book) {\n $arrBookTitle[$i]=(string)$book;\n $arrBookDewey[$i]=$book['DeweyDecimal'];\n}\n" }, { "answer_id": 328375, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 2, "selected": false, "text": "//a:Books/text() | //a:Books/@DeweyDecimal" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ]
141,939
<p>I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting </p> <pre><code>./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj </code></pre> <p>Which c++filt describes as </p> <pre><code>std::_Rb_tree&lt;unsigned int, unsigned int, std::_Identity&lt;unsigned int&gt;, std::less&lt;unsigned int&gt;, std::allocator&lt;unsigned int&gt; &gt;::insert_unique(unsigned int const&amp;) </code></pre> <p>I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including <code>-lstdc++</code>.</p> <p>Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?</p> <p><em>EDIT:</em> After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.</p>
[ { "answer_id": 141957, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 1, "selected": false, "text": "std::_Rb_Tree map libstdc++ libstdc++ map hash_map" }, { "answer_id": 141977, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "#include < map > " } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209/" ]
141,970
<p>I'm experimenting with generics and I'm trying to create structure similar to Dataset class.<br> I have following code</p> <pre><code>public struct Column&lt;T&gt; { T value; T originalValue; public bool HasChanges { get { return !value.Equals(originalValue); } } public void AcceptChanges() { originalValue = value; } } public class Record { Column&lt;int&gt; id; Column&lt;string&gt; name; Column&lt;DateTime?&gt; someDate; Column&lt;int?&gt; someInt; public bool HasChanges { get { return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges; } } public void AcceptChanges() { id.AcceptChanges(); name.AcceptChanges(); someDate.AcceptChanges(); someInt.AcceptChanges(); } } </code></pre> <p>Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring.<br> So first solution that cames to my mind was something like this:</p> <pre><code>public interface IColumn { bool HasChanges { get; } void AcceptChanges(); } public struct Column&lt;T&gt; : IColumn {...} public class Record { Column&lt;int&gt; id; Column&lt;string&gt; name; Column&lt;DateTime?&gt; someDate; Column&lt;int?&gt; someInt; IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }} public bool HasChanges { get { bool has = false; IColumn[] columns = Columns; //clone and boxing for (int i = 0; i &lt; columns.Length; i++) has |= columns[i].HasChanges; return has; } } public void AcceptChanges() { IColumn[] columns = Columns; //clone and boxing for (int i = 0; i &lt; columns.Length; i++) columns[i].AcceptChanges(); //Here we are changing clone } } </code></pre> <p>As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me. <br> <br> So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage. <br> <br> <strong>Edit:</strong><br> sfg thanks for suggestion about macros.<br> In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain.<br><br> Some usefull links:<br> <a href="http://www.t4editor.net/" rel="nofollow noreferrer" title="T4 Editor for VS">T4 Editor for VS</a><br> <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" rel="nofollow noreferrer" title="Blog with links and tutorials about T4">Blog with links and tutorials about T4</a><br> <a href="http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/" rel="nofollow noreferrer" title="Blog entry with example that uses EnvDTE to read project files">Blog entry with example that uses EnvDTE to read project files</a></p>
[ { "answer_id": 142253, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 1, "selected": false, "text": "Column IColumn IColumn AcceptChanges() HasChanges() Column Column public class Record\n{\n public enum ColumnNames { ID = 0, Name, Date, Int, NumCols };\n\n private IColumn [] columns;\n\n public Record()\n {\n columns = new IColumn[ColumnNames.NumCols];\n columns[ID] = ...\n }\n\n public bool HasChanges\n {\n get\n {\n bool has = false;\n for (int i = 0; i < columns.Length; i++)\n has |= columns[i].HasChanges;\n return has;\n }\n }\n\n public void AcceptChanges()\n {\n for (int i = 0; i < columns.Length; i++)\n columns[i].AcceptChanges();\n }\n}\n" }, { "answer_id": 142297, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 0, "selected": false, "text": "public void AcceptChanges()\n{\n foreach (FieldInfo field in GetType().GetFields()) {\n if (!typeof(IColumn).IsAssignableFrom(field.FieldType))\n continue; // ignore all non-IColumn fields\n IColumn col = (IColumn)field.GetValue(this); // Boxes storage -> clone\n col.AcceptChanges(); // Works on clone\n field.SetValue(this, col); // Unboxes clone -> storage\n }\n}\n" }, { "answer_id": 143068, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 0, "selected": false, "text": "public interface IColumn<T>\n{\n T Value { get; set; }\n T OriginalValue { get; set; }\n}\n\npublic struct Column<T> : IColumn<T>\n{\n public T Value { get; set; }\n public T OriginalValue { get; set; }\n}\n\npublic static class ColumnService\n{\n public static bool HasChanges<T, S>(T column) where T : IColumn<S>\n {\n return !(column.Value.Equals(column.OriginalValue));\n }\n\n public static void AcceptChanges<T, S>(T column) where T : IColumn<S>\n {\n column.Value = column.OriginalValue;\n }\n}\n Column<int> age = new Column<int>();\nage.Value = 35;\nage.OriginalValue = 34;\n\nif (ColumnService.HasChanges<Column<int>, int>(age))\n{\n ColumnService.AcceptChanges<Column<int>, int>(age);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22569/" ]
141,973
<p>Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.</p> <p>EDIT: Here is what I have unsuccessfully tried:</p> <pre><code>class Comment(db.Model): series = db.ReferenceProperty(reference_class=Series); def series_id(self): return self._series </code></pre> <p>And in my template:</p> <pre><code>&lt;a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}"&gt;more&lt;/a&gt; </code></pre> <p>The result:</p> <pre><code>&lt;a href="games/view-series.html?series=#comm59"&gt;more&lt;/a&gt; </code></pre>
[ { "answer_id": 164870, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "class Comment(db.Model):\n series = db.ReferenceProperty(reference_class=Series);\n\n def series_id(self):\n return Comment.series.get_value_for_datastore(self)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
141,975
<p>How do the full text search systems of PostgreSQL and MySQL compare? Is any clearly better than the oder? In which way are they different?</p>
[ { "answer_id": 147433, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 3, "selected": false, "text": "SELECT title\nFROM pgweb\nWHERE to_tsvector(body) @@ to_tsquery('friend');\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
141,993
<p>I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.</p> <p>When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)</p> <p>I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage. </p> <p>So, boiled down, the question is:</p> <p>Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.</p>
[ { "answer_id": 142167, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 9, "selected": true, "text": "public class SomeTest extends XMLTestCase {\n @Test\n public void test() {\n String xml1 = ...\n String xml2 = ...\n\n XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences\n\n // can also compare xml Documents, InputSources, Readers, Diffs\n assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase\n }\n}\n" }, { "answer_id": 4022381, "author": "Pimin Konstantin Kefaloukos", "author_id": 209786, "author_profile": "https://Stackoverflow.com/users/209786", "pm_score": 2, "selected": false, "text": "<foo a=\"xxx\" b=\"xxx\">xxx</foo>\n <foo b=\"yyy\" a=\"yyy\">yyy</foo> \n" }, { "answer_id": 4211237, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 5, "selected": false, "text": "xml:space" }, { "answer_id": 5816079, "author": "Javelin", "author_id": 728928, "author_profile": "https://Stackoverflow.com/users/728928", "pm_score": 3, "selected": false, "text": "import java.io.ByteArrayInputStream;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\n\npublic class XmlDiff \n{\n private boolean nodeTypeDiff = true;\n private boolean nodeValueDiff = true;\n\n public boolean diff( String xml1, String xml2, List<String> diffs ) throws Exception\n {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(true);\n dbf.setCoalescing(true);\n dbf.setIgnoringElementContentWhitespace(true);\n dbf.setIgnoringComments(true);\n DocumentBuilder db = dbf.newDocumentBuilder();\n\n\n Document doc1 = db.parse(new ByteArrayInputStream(xml1.getBytes()));\n Document doc2 = db.parse(new ByteArrayInputStream(xml2.getBytes()));\n\n doc1.normalizeDocument();\n doc2.normalizeDocument();\n\n return diff( doc1, doc2, diffs );\n\n }\n\n /**\n * Diff 2 nodes and put the diffs in the list \n */\n public boolean diff( Node node1, Node node2, List<String> diffs ) throws Exception\n {\n if( diffNodeExists( node1, node2, diffs ) )\n {\n return true;\n }\n\n if( nodeTypeDiff )\n {\n diffNodeType(node1, node2, diffs );\n }\n\n if( nodeValueDiff )\n {\n diffNodeValue(node1, node2, diffs );\n }\n\n\n System.out.println(node1.getNodeName() + \"/\" + node2.getNodeName());\n\n diffAttributes( node1, node2, diffs );\n diffNodes( node1, node2, diffs );\n\n return diffs.size() > 0;\n }\n\n /**\n * Diff the nodes\n */\n public boolean diffNodes( Node node1, Node node2, List<String> diffs ) throws Exception\n {\n //Sort by Name\n Map<String,Node> children1 = new LinkedHashMap<String,Node>(); \n for( Node child1 = node1.getFirstChild(); child1 != null; child1 = child1.getNextSibling() )\n {\n children1.put( child1.getNodeName(), child1 );\n }\n\n //Sort by Name\n Map<String,Node> children2 = new LinkedHashMap<String,Node>(); \n for( Node child2 = node2.getFirstChild(); child2!= null; child2 = child2.getNextSibling() )\n {\n children2.put( child2.getNodeName(), child2 );\n }\n\n //Diff all the children1\n for( Node child1 : children1.values() )\n {\n Node child2 = children2.remove( child1.getNodeName() );\n diff( child1, child2, diffs );\n }\n\n //Diff all the children2 left over\n for( Node child2 : children2.values() )\n {\n Node child1 = children1.get( child2.getNodeName() );\n diff( child1, child2, diffs );\n }\n\n return diffs.size() > 0;\n }\n\n\n /**\n * Diff the nodes\n */\n public boolean diffAttributes( Node node1, Node node2, List<String> diffs ) throws Exception\n { \n //Sort by Name\n NamedNodeMap nodeMap1 = node1.getAttributes();\n Map<String,Node> attributes1 = new LinkedHashMap<String,Node>(); \n for( int index = 0; nodeMap1 != null && index < nodeMap1.getLength(); index++ )\n {\n attributes1.put( nodeMap1.item(index).getNodeName(), nodeMap1.item(index) );\n }\n\n //Sort by Name\n NamedNodeMap nodeMap2 = node2.getAttributes();\n Map<String,Node> attributes2 = new LinkedHashMap<String,Node>(); \n for( int index = 0; nodeMap2 != null && index < nodeMap2.getLength(); index++ )\n {\n attributes2.put( nodeMap2.item(index).getNodeName(), nodeMap2.item(index) );\n\n }\n\n //Diff all the attributes1\n for( Node attribute1 : attributes1.values() )\n {\n Node attribute2 = attributes2.remove( attribute1.getNodeName() );\n diff( attribute1, attribute2, diffs );\n }\n\n //Diff all the attributes2 left over\n for( Node attribute2 : attributes2.values() )\n {\n Node attribute1 = attributes1.get( attribute2.getNodeName() );\n diff( attribute1, attribute2, diffs );\n }\n\n return diffs.size() > 0;\n }\n /**\n * Check that the nodes exist\n */\n public boolean diffNodeExists( Node node1, Node node2, List<String> diffs ) throws Exception\n {\n if( node1 == null && node2 == null )\n {\n diffs.add( getPath(node2) + \":node \" + node1 + \"!=\" + node2 + \"\\n\" );\n return true;\n }\n\n if( node1 == null && node2 != null )\n {\n diffs.add( getPath(node2) + \":node \" + node1 + \"!=\" + node2.getNodeName() );\n return true;\n }\n\n if( node1 != null && node2 == null )\n {\n diffs.add( getPath(node1) + \":node \" + node1.getNodeName() + \"!=\" + node2 );\n return true;\n }\n\n return false;\n }\n\n /**\n * Diff the Node Type\n */\n public boolean diffNodeType( Node node1, Node node2, List<String> diffs ) throws Exception\n { \n if( node1.getNodeType() != node2.getNodeType() ) \n {\n diffs.add( getPath(node1) + \":type \" + node1.getNodeType() + \"!=\" + node2.getNodeType() );\n return true;\n }\n\n return false;\n }\n\n /**\n * Diff the Node Value\n */\n public boolean diffNodeValue( Node node1, Node node2, List<String> diffs ) throws Exception\n { \n if( node1.getNodeValue() == null && node2.getNodeValue() == null )\n {\n return false;\n }\n\n if( node1.getNodeValue() == null && node2.getNodeValue() != null )\n {\n diffs.add( getPath(node1) + \":type \" + node1 + \"!=\" + node2.getNodeValue() );\n return true;\n }\n\n if( node1.getNodeValue() != null && node2.getNodeValue() == null )\n {\n diffs.add( getPath(node1) + \":type \" + node1.getNodeValue() + \"!=\" + node2 );\n return true;\n }\n\n if( !node1.getNodeValue().equals( node2.getNodeValue() ) )\n {\n diffs.add( getPath(node1) + \":type \" + node1.getNodeValue() + \"!=\" + node2.getNodeValue() );\n return true;\n }\n\n return false;\n }\n\n\n /**\n * Get the node path\n */\n public String getPath( Node node )\n {\n StringBuilder path = new StringBuilder();\n\n do\n { \n path.insert(0, node.getNodeName() );\n path.insert( 0, \"/\" );\n }\n while( ( node = node.getParentNode() ) != null );\n\n return path.toString();\n }\n}\n" }, { "answer_id": 14787497, "author": "Sree", "author_id": 1294908, "author_profile": "https://Stackoverflow.com/users/1294908", "pm_score": 0, "selected": false, "text": " import com.a7soft.examxml.ExamXML;\n import com.a7soft.examxml.Options;\n\n .................\n\n // Reads two XML files into two strings\n String s1 = readFile(\"orders1.xml\");\n String s2 = readFile(\"orders.xml\");\n\n // Loads options saved in a property file\n Options.loadOptions(\"options\");\n\n // Compares two Strings representing XML entities\n System.out.println( ExamXML.compareXMLString( s1, s2 ) );\n" }, { "answer_id": 16471601, "author": "acdcjunior", "author_id": 1850609, "author_profile": "https://Stackoverflow.com/users/1850609", "pm_score": 5, "selected": false, "text": "XMLUnit.setIgnoreWhitespace() XMLUnit.setIgnoreAttributeOrder() import org.custommonkey.xmlunit.DetailedDiff;\nimport org.custommonkey.xmlunit.XMLUnit;\nimport org.junit.Assert;\n\npublic class TestXml {\n\n public static void main(String[] args) throws Exception {\n String result = \"<abc attr=\\\"value1\\\" title=\\\"something\\\"> </abc>\";\n // will be ok\n assertXMLEquals(\"<abc attr=\\\"value1\\\" title=\\\"something\\\"></abc>\", result);\n }\n\n public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {\n XMLUnit.setIgnoreWhitespace(true);\n XMLUnit.setIgnoreAttributeOrder(true);\n\n DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));\n\n List<?> allDifferences = diff.getAllDifferences();\n Assert.assertEquals(\"Differences found: \"+ diff.toString(), 0, allDifferences.size());\n }\n\n}\n pom.xml <dependency>\n <groupId>xmlunit</groupId>\n <artifactId>xmlunit</artifactId>\n <version>1.4</version>\n</dependency>\n" }, { "answer_id": 26361718, "author": "Wojtek", "author_id": 2685402, "author_profile": "https://Stackoverflow.com/users/2685402", "pm_score": 1, "selected": false, "text": "import org.apache.xml.security.c14n.CanonicalizationException;\nimport org.apache.xml.security.c14n.Canonicalizer;\nimport org.apache.xml.security.c14n.InvalidCanonicalizerException;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.bootstrap.DOMImplementationRegistry;\nimport org.w3c.dom.ls.DOMImplementationLS;\nimport org.w3c.dom.ls.LSSerializer;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\nimport java.io.IOException;\nimport java.io.StringReader;\n\nimport static org.apache.xml.security.Init.init;\nimport static org.junit.Assert.assertEquals;\n\npublic class XmlUtils {\n static {\n init();\n }\n\n public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {\n Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);\n byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());\n return new String(canonXmlBytes);\n }\n\n public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {\n InputSource src = new InputSource(new StringReader(input));\n Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();\n Boolean keepDeclaration = input.startsWith(\"<?xml\");\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n writer.getDomConfig().setParameter(\"format-pretty-print\", Boolean.TRUE);\n writer.getDomConfig().setParameter(\"xml-declaration\", keepDeclaration);\n return writer.writeToString(document);\n }\n\n public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {\n String canonicalExpected = prettyFormat(toCanonicalXml(expected));\n String canonicalActual = prettyFormat(toCanonicalXml(actual));\n assertEquals(canonicalExpected, canonicalActual);\n }\n}\n" }, { "answer_id": 36144815, "author": "Tom Saleeba", "author_id": 1410035, "author_profile": "https://Stackoverflow.com/users/1410035", "pm_score": 3, "selected": false, "text": " <dependency>\n <groupId>org.xmlunit</groupId>\n <artifactId>xmlunit-core</artifactId>\n <version>2.0.0</version>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>org.xmlunit</groupId>\n <artifactId>xmlunit-matchers</artifactId>\n <version>2.0.0</version>\n <scope>test</scope>\n </dependency>\n import static org.junit.Assert.assertThat;\nimport static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;\nimport org.xmlunit.builder.Input;\nimport org.xmlunit.input.WhitespaceStrippedSource;\n\npublic class SomeTest extends XMLTestCase {\n @Test\n public void test() {\n String result = \"<root></root>\";\n String expected = \"<root> </root>\";\n\n // ignore whitespace differences\n // https://github.com/xmlunit/user-guide/wiki/Providing-Input-to-XMLUnit#whitespacestrippedsource\n assertThat(result, isIdenticalTo(new WhitespaceStrippedSource(Input.from(expected).build())));\n\n assertThat(result, isIdenticalTo(Input.from(expected).build())); // will fail due to whitespace differences\n }\n}\n" }, { "answer_id": 36570105, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 3, "selected": false, "text": "String expectedXml = \"<foo />\";\nString actualXml = \"<bar />\";\nassertThat(actualXml).isXmlEqualTo(expectedXml);\n" }, { "answer_id": 36658480, "author": "TouDick", "author_id": 1688570, "author_profile": "https://Stackoverflow.com/users/1688570", "pm_score": 2, "selected": false, "text": "import java.io.ByteArrayInputStream;\nimport java.nio.charset.Charset;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport org.junit.Assert;\nimport org.w3c.dom.Document;\n\n/**\n * Asserts for asserting XML strings.\n */\npublic final class AssertXml {\n\n private AssertXml() {\n }\n\n private static Pattern NAMESPACE_PATTERN = Pattern.compile(\"xmlns:(ns\\\\d+)=\\\"(.*?)\\\"\");\n\n /**\n * Asserts that two XML are of identical content (namespace aliases are ignored).\n * \n * @param expectedXml expected XML\n * @param actualXml actual XML\n * @throws Exception thrown if XML parsing fails\n */\n public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {\n // Find all namespace mappings\n Map<String, String> fullnamespace2newAlias = new HashMap<String, String>();\n generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);\n generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);\n\n for (Entry<String, String> entry : fullnamespace2newAlias.entrySet()) {\n String newAlias = entry.getValue();\n String namespace = entry.getKey();\n Pattern nsReplacePattern = Pattern.compile(\"xmlns:(ns\\\\d+)=\\\"\" + namespace + \"\\\"\");\n expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);\n actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);\n }\n\n // nomralize namespaces accoring to given mapping\n\n DocumentBuilder db = initDocumentParserFactory();\n\n Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName(\"UTF-8\"))));\n expectedDocuemnt.normalizeDocument();\n\n Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName(\"UTF-8\"))));\n actualDocument.normalizeDocument();\n\n if (!expectedDocuemnt.isEqualNode(actualDocument)) {\n Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse\n }\n }\n\n\n private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(false);\n dbf.setCoalescing(true);\n dbf.setIgnoringElementContentWhitespace(true);\n dbf.setIgnoringComments(true);\n DocumentBuilder db = dbf.newDocumentBuilder();\n return db;\n }\n\n private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {\n Matcher nsMatcherExp = namespacePattern.matcher(xml);\n if (nsMatcherExp.find()) {\n xml = xml.replaceAll(nsMatcherExp.group(1) + \"[:]\", newAlias + \":\");\n xml = xml.replaceAll(nsMatcherExp.group(1) + \"=\", newAlias + \"=\");\n }\n return xml;\n }\n\n private static void generateNewAliasesForNamespacesFromXml(String xml, Map<String, String> fullnamespace2newAlias) {\n Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);\n while (nsMatcher.find()) {\n if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {\n fullnamespace2newAlias.put(nsMatcher.group(2), \"nsTr\" + (fullnamespace2newAlias.size() + 1));\n }\n }\n }\n\n}\n" }, { "answer_id": 45839956, "author": "arunkumar sambu", "author_id": 6799634, "author_profile": "https://Stackoverflow.com/users/6799634", "pm_score": 2, "selected": false, "text": "String xml1 = ...\nString xml2 = ...\nXMLUnit.setIgnoreWhitespace(true);\nXMLUnit.setIgnoreAttributeOrder(true);\nXMLAssert.assertXMLEqual(actualxml, xmlInDb);\n" }, { "answer_id": 71255057, "author": "Nicolas Sénave", "author_id": 13425151, "author_profile": "https://Stackoverflow.com/users/13425151", "pm_score": 1, "selected": false, "text": "pom.xml <dependency>\n <groupId>org.xmlunit</groupId>\n <artifactId>xmlunit-assertj3</artifactId>\n <version>2.9.0</version>\n</dependency>\n import org.junit.jupiter.api.Test;\nimport org.xmlunit.assertj3.XmlAssert;\n\npublic class FooTest {\n\n @Test\n public void compareXml() {\n //\n String xmlContentA = \"<foo></foo>\";\n String xmlContentB = \"<foo></foo>\";\n //\n XmlAssert.assertThat(xmlContentA).and(xmlContentB).areSimilar();\n }\n}\n areIdentical() areNotIdentical() areNotSimilar() assertThat(~).and(~) DifferenceEvaluator" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
142,000
<p>I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with <code>e.preventDefault()</code> and runs an AJAX command. This works fine when the submit button is clicked but when a link with <code>onclick='document.formName.submit();'</code> is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?</p>
[ { "answer_id": 142075, "author": "user16624", "author_id": 16624, "author_profile": "https://Stackoverflow.com/users/16624", "pm_score": 1, "selected": false, "text": "this._form.bind('submit', Delegate.create(this, function(e) {\n e.preventDefault();\n this._searchFadeOut();\n this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value')));\n});\n onclick" }, { "answer_id": 142109, "author": "stechz", "author_id": 10290, "author_profile": "https://Stackoverflow.com/users/10290", "pm_score": 6, "selected": true, "text": "\n var oldSubmit = form.submit;\n form.submit = function() {\n $(form).trigger(\"submit\");\n oldSubmit.call(form, arguments);\n }\n \n $(\"form a\").click(function() {\n $(this).parents().filter(\"form\").trigger(\"submit\");\n });\n" }, { "answer_id": 5640759, "author": "Joel", "author_id": 704789, "author_profile": "https://Stackoverflow.com/users/704789", "pm_score": 1, "selected": false, "text": "$(\"#mySubmit\").click(function(){\n $(\"#submit\").trigger(\"click\"); });\n preventDefault" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16624/" ]
142,003
<p>I have a scenario. (Windows Forms, C#, .NET)</p> <ol> <li>There is a main form which hosts some user control.</li> <li>The user control does some heavy data operation, such that if I directly call the <code>UserControl_Load</code> method the UI become nonresponsive for the duration for load method execution.</li> <li>To overcome this I load data on different thread (trying to change existing code as little as I can)</li> <li>I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.</li> <li>Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.</li> </ol> <p>The pseudocode would look like this:</p> <p><strong>CODE 1</strong></p> <pre><code>UserContrl1_LoadDataMethod() { if (textbox1.text == &quot;MyName&quot;) // This gives exception { //Load data corresponding to &quot;MyName&quot;. //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage. } } </code></pre> <p>The Exception it gave was</p> <blockquote> <p>Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.</p> </blockquote> <p>To know more about this I did some googling and a suggestion came up like using the following code</p> <p><strong>CODE 2</strong></p> <pre><code>UserContrl1_LoadDataMethod() { if (InvokeRequired) // Line #1 { this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod)); return; } if (textbox1.text == &quot;MyName&quot;) // Now it won't give an exception { //Load data correspondin to &quot;MyName&quot; //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage } } </code></pre> <p>But it still seems that I've come back to square one. The Application again becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.</p> <p>I don't know whether I perceived this right or wrong. I'm new to threading.</p> <p>How do I resolve this and also what is the effect of execution of Line#1 if block?</p> <p><strong>The situation is this</strong>: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.</p> <p>So only accessing the value so that the corresponding data can be fetched from the database.</p>
[ { "answer_id": 142064, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "Invoke BeginInvoke BackgroundWorker Control.Invoke Control.BeginInvoke BackgroundWorker BackgroundWorker" }, { "answer_id": 142069, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": 10, "selected": true, "text": "UserContrl1_LOadDataMethod()\n{\n string name = \"\";\n if(textbox1.InvokeRequired)\n {\n textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));\n }\n if(name == \"MyName\")\n {\n // do whatever\n }\n}\n UserContrl1_LOadDataMethod()\n{\n if(textbox1.text==\"MyName\") //<<======Now it wont give exception**\n {\n //Load data correspondin to \"MyName\"\n //Populate a globale variable List<string> which will be\n //bound to grid at some later stage\n if(InvokeRequired)\n {\n // after we've done all the processing, \n this.Invoke(new MethodInvoker(delegate {\n // load the control with the appropriate data\n }));\n return;\n }\n }\n}\n" }, { "answer_id": 437759, "author": "Peter C", "author_id": 1952, "author_profile": "https://Stackoverflow.com/users/1952", "pm_score": 5, "selected": false, "text": "FileSystemWatcher fsw.SynchronizingObject = this" }, { "answer_id": 10746375, "author": "Ashitakalax", "author_id": 970011, "author_profile": "https://Stackoverflow.com/users/970011", "pm_score": 3, "selected": false, "text": "(InvokeRequired)\n delegate void updateMainFormObject(FormObjectType objectWithoutInvoke, string text);\n\nprivate void updateFormObjectType(FormObjectType objectWithoutInvoke, string text)\n{\n MainForm.Invoke(new updateMainFormObject(UpdateObject), objectWithoutInvoke, text);\n}\n\npublic void UpdateObject(ToolStripStatusLabel objectWithoutInvoke, string text)\n{\n objectWithoutInvoke.Text = text;\n}\n" }, { "answer_id": 18748673, "author": "RandallTo", "author_id": 609346, "author_profile": "https://Stackoverflow.com/users/609346", "pm_score": 3, "selected": false, "text": "public partial class Form1 : Form\n{\n private ExampleController.MyController controller;\n\n public Form1()\n { \n InitializeComponent();\n controller = new ExampleController.MyController((ISynchronizeInvoke) this);\n controller.Finished += controller_Finished;\n }\n\n void controller_Finished(string returnValue)\n {\n label1.Text = returnValue; \n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n controller.SubmitTask(\"Do It\");\n }\n}\n public delegate void FinishedTasksHandler(string returnValue);\n\npublic class MyController\n{\n private ISynchronizeInvoke _syn; \n public MyController(ISynchronizeInvoke syn) { _syn = syn; } \n public event FinishedTasksHandler Finished; \n\n public void SubmitTask(string someValue)\n {\n System.Threading.ThreadPool.QueueUserWorkItem(state => submitTask(someValue));\n }\n\n private void submitTask(string someValue)\n {\n someValue = someValue + \" \" + DateTime.Now.ToString();\n System.Threading.Thread.Sleep(5000);\n//Finished(someValue); This causes cross threading error if called like this.\n\n if (Finished != null)\n {\n if (_syn.InvokeRequired)\n {\n _syn.Invoke(Finished, new object[] { someValue });\n }\n else\n {\n Finished(someValue);\n }\n }\n }\n}\n" }, { "answer_id": 21576814, "author": "UrsulRosu", "author_id": 1764994, "author_profile": "https://Stackoverflow.com/users/1764994", "pm_score": 3, "selected": false, "text": "Private Delegate Function GetControlTextInvoker(ByVal ctl As Control) As String\n\nPrivate Function GetControlText(ByVal ctl As Control) As String\n Dim text As String\n\n If ctl.InvokeRequired Then\n text = CStr(ctl.Invoke(\n New GetControlTextInvoker(AddressOf GetControlText), ctl))\n Else\n text = ctl.Text\n End If\n\n Return text\nEnd Function\n" }, { "answer_id": 26506411, "author": "Mike", "author_id": 3083679, "author_profile": "https://Stackoverflow.com/users/3083679", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Helper method to determin if invoke required, if so will rerun method on correct thread.\n/// if not do nothing.\n/// </summary>\n/// <param name=\"c\">Control that might require invoking</param>\n/// <param name=\"a\">action to preform on control thread if so.</param>\n/// <returns>true if invoke required</returns>\npublic bool ControlInvokeRequired(Control c, Action a)\n{\n if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate\n {\n a();\n }));\n else return false;\n\n return true;\n}\n // usage on textbox\npublic void UpdateTextBox1(String text)\n{\n //Check if invoke requied if so return - as i will be recalled in correct thread\n if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;\n textBox1.Text = ellapsed;\n}\n\n//Or any control\npublic void UpdateControl(Color c, String s)\n{\n //Check if invoke requied if so return - as i will be recalled in correct thread\n if (ControlInvokeRequired(myControl, () => UpdateControl(c, s))) return;\n myControl.Text = s;\n myControl.BackColor = c;\n}\n" }, { "answer_id": 36983936, "author": "Rob", "author_id": 563532, "author_profile": "https://Stackoverflow.com/users/563532", "pm_score": 4, "selected": false, "text": "public static class Extensions\n{\n public static void Invoke<TControlType>(this TControlType control, Action<TControlType> del) \n where TControlType : Control\n {\n if (control.InvokeRequired)\n control.Invoke(new Action(() => del(control)));\n else\n del(control);\n }\n}\n textbox1.Invoke(t => t.Text = \"A\");\n" }, { "answer_id": 37077612, "author": "Vanderley Maia", "author_id": 2126783, "author_profile": "https://Stackoverflow.com/users/2126783", "pm_score": 3, "selected": false, "text": "using System.Threading.Tasks;\nusing System.Threading;\n\nnamespace TESTE\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n Action<string> DelegateTeste_ModifyText = THREAD_MOD;\n Invoke(DelegateTeste_ModifyText, \"MODIFY BY THREAD\");\n }\n\n private void THREAD_MOD(string teste)\n {\n textBox1.Text = teste;\n }\n }\n}\n" }, { "answer_id": 37245647, "author": "JWP", "author_id": 1522548, "author_profile": "https://Stackoverflow.com/users/1522548", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// A new way to use Tasks for Asynchronous calls\n/// </summary>\npublic class Example\n{\n /// <summary>\n /// No more delegates, background workers etc. just one line of code as shown below\n /// Note it is dependent on the XTask class shown next.\n /// </summary>\n public async void ExampleMethod()\n {\n //Still on GUI/Original Thread here\n //Do your updates before the next line of code\n await XTask.RunAsync(() =>\n {\n //Running an asynchronous task here\n //Cannot update GUI Thread here, but can do lots of work\n });\n //Can update GUI/Original thread on this line\n }\n}\n\n/// <summary>\n/// A class containing extension methods for the Task class \n/// Put this file in folder named Extensions\n/// Use prefix of X for the class it Extends\n/// </summary>\npublic static class XTask\n{\n /// <summary>\n /// RunAsync is an extension method that encapsulates the Task.Run using a callback\n /// </summary>\n /// <param name=\"Code\">The caller is called back on the new Task (on a different thread)</param>\n /// <returns></returns>\n public async static Task RunAsync(Action Code)\n {\n await Task.Run(() =>\n {\n Code();\n });\n return;\n }\n}\n /// <summary>\n /// Run Async\n /// </summary>\n /// <typeparam name=\"T\">The type to return</typeparam>\n /// <param name=\"Code\">The callback to the code</param>\n /// <param name=\"Error\">The handled and logged exception if one occurs</param>\n /// <returns>The type expected as a competed task</returns>\n\n public async static Task<T> RunAsync<T>(Func<string,T> Code, Action<Exception> Error)\n {\n var done = await Task<T>.Run(() =>\n {\n T result = default(T);\n try\n {\n result = Code(\"Code Here\");\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Unhandled Exception: \" + ex.Message);\n Console.WriteLine(ex.StackTrace);\n Error(ex);\n }\n return result;\n\n });\n return done;\n }\n public async void HowToUse()\n {\n //We now inject the type we want the async routine to return!\n var result = await RunAsync<bool>((code) => {\n //write code here, all exceptions are logged via the wrapped try catch.\n //return what is needed\n return someBoolValue;\n }, \n error => {\n\n //exceptions are already handled but are sent back here for further processing\n });\n if (result)\n {\n //we can now process the result because the code above awaited for the completion before\n //moving to this statement\n }\n }\n" }, { "answer_id": 43012655, "author": "Saurabh", "author_id": 3556867, "author_profile": "https://Stackoverflow.com/users/3556867", "pm_score": 2, "selected": false, "text": "public class data_holder_for_controls\n{\n //it will hold value for your label\n public string status = string.Empty;\n}\n\nclass Demo\n{\n public static data_holder_for_controls d1 = new data_holder_for_controls();\n static void Main(string[] args)\n {\n ThreadStart ts = new ThreadStart(perform_logic);\n Thread t1 = new Thread(ts);\n t1.Start();\n t1.Join();\n //your_label.Text=d1.status; --- can access it from any thread \n }\n\n public static void perform_logic()\n {\n //put some code here in this function\n for (int i = 0; i < 10; i++)\n {\n //statements here\n }\n //set result in status variable\n d1.status = \"Task done\";\n }\n}\n" }, { "answer_id": 43890612, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 3, "selected": false, "text": "CheckForIllegalCrossThreadCalls = false\n Form1()" }, { "answer_id": 46789543, "author": "Bravo", "author_id": 835464, "author_profile": "https://Stackoverflow.com/users/835464", "pm_score": 6, "selected": false, "text": "Invoke(new Action(() =>\n {\n label1.Text = \"WooHoo!!!\";\n }));\n" }, { "answer_id": 47085518, "author": "Hamid Jolany", "author_id": 555078, "author_profile": "https://Stackoverflow.com/users/555078", "pm_score": 3, "selected": false, "text": "this.Invoke(new MethodInvoker(delegate\n {\n //your code here;\n }));\n" }, { "answer_id": 49626128, "author": "Nasir Mahmood", "author_id": 1019417, "author_profile": "https://Stackoverflow.com/users/1019417", "pm_score": -1, "selected": false, "text": "Control.InvokeRequired Property \n SynchronizationContext Post Method\n" }, { "answer_id": 55894507, "author": "Hasan Shouman", "author_id": 3293110, "author_profile": "https://Stackoverflow.com/users/3293110", "pm_score": 2, "selected": false, "text": "this.Invoke((MethodInvoker)delegate\n {\n YourControl.Property= value; // runs thread safe\n });\n" }, { "answer_id": 61685935, "author": "Timothy Macharia", "author_id": 3499361, "author_profile": "https://Stackoverflow.com/users/3499361", "pm_score": 3, "selected": false, "text": "public static class FormExts\n{\n public static void LoadOnUI(this Form frm, Action action)\n {\n if (frm.InvokeRequired) frm.Invoke(action);\n else action.Invoke();\n }\n}\n private void OnAnyEvent(object sender, EventArgs args)\n{\n this.LoadOnUI(() =>\n {\n label1.Text = \"\";\n button1.Text = \"\";\n });\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22858/" ]
142,007
<p>Is there a way to force a Samba process to close a given file without killing it?</p> <p>Samba opens a process for each client connection, and sometimes I see it holds open files far longer than needed. Usually i just kill the process, and the (windows) client will reopen it the next time it access the share; but sometimes it's actively reading other file for a long time, and i'd like to just 'kill' one file, and not the whole connection.</p> <p>edit: I've tried the 'net rpc file close ', but doesn't seem to work. Anybody knows why?</p> <p>edit: <a href="http://www.nabble.com/Fw:-Files-left-open-td5578614.html" rel="nofollow noreferrer">this</a> is the best mention i've found of something similar. It seems to be a problem on the win32 client, something that microsoft servers have a workaround for; but Samba doesn't. I wish the <code>net rpc file close &lt;fileid&gt;</code> command worked, I'll keep trying to find out why. I'm accepting LuckyLindy's answer, even if it didn't solve the problem, because it's the only useful procedure in this case.</p>
[ { "answer_id": 588984, "author": "Beep beep", "author_id": 257954, "author_profile": "https://Stackoverflow.com/users/257954", "pm_score": 4, "selected": true, "text": "lsof|grep -i <file_name> kill -9 <pid>" }, { "answer_id": 589553, "author": "X-Istence", "author_id": 13986, "author_profile": "https://Stackoverflow.com/users/13986", "pm_score": 2, "selected": false, "text": "posix locking=no" }, { "answer_id": 35812410, "author": "jpfx1342", "author_id": 1709144, "author_profile": "https://Stackoverflow.com/users/1709144", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nPIDS_TO_CLOSE=$(smbstatus -L | tail -n-3 | grep \"$1\" | cut -d' ' -f1 - | sort -u | sed '/^$/$\nfor PID in $PIDS_TO_CLOSE; do\n kill $PID\ndone\n smbclose /media/drive\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11649/" ]
142,010
<p>Say I have the following XML...</p> <pre><code>&lt;root&gt; &lt;base&gt; &lt;tent key="1" color="red"/&gt; &lt;tent key="2" color="yellow"/&gt; &lt;tent key="3" color="blue"/&gt; &lt;/base&gt; &lt;bucket&gt; &lt;tent key="1"/&gt; &lt;tent key="3"/&gt; &lt;/bucket&gt; &lt;/root&gt; </code></pre> <p>...what would the XPath be that returns that the "bucket" contains "red" and "blue"?</p>
[ { "answer_id": 142067, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 2, "selected": false, "text": "/root/base/tent[/root/bucket/tent/@key = @key ]/@color\n" }, { "answer_id": 144505, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<xsl:key name=\"tents\" match=\"base/tent\" use=\"@key\" />\n <tent> <base> key key('tents', $id)\n key('tents', /root/bucket/tent/@key)/@color\n $bucket <bucket> key('tents', $bucket/tent/@key)/@color\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
142,016
<p>I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.</p> <p>IE: given</p> <pre><code>struct mstct { int myfield; int myfield2; }; </code></pre> <p>I could write:</p> <pre><code>mstct thing; printf("offset %lu\n", (unsigned long)(&amp;thing.myfield2 - &amp;thing)); </code></pre> <p>And get <code>offset 4</code> for the output. How can I do it without that <code>mstct thing</code> declaration/allocating one?</p> <p>I know that <code>&amp;&lt;struct&gt;</code> does not always point at the first byte of the first field of the structure, I can account for that later.</p>
[ { "answer_id": 142023, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 7, "selected": true, "text": "#define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))\n" }, { "answer_id": 142049, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "offsetof offsetof(struct mstct, myfield2)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
142,042
<p>I want to attach an xslt stylesheet to an XML document that I build with XMLBuilder. This is done with a Processing Instruction that looks like</p> <pre><code>&lt;?xml-stylesheet type='text/xsl' href='/stylesheets/style.xslt' ?&gt; </code></pre> <p>Normally, I'd use the <code>instruct!</code> method, but <code>:xml-stylesheet</code> is not a valid Ruby symbol.</p> <p>XMLBuilder has a solution for this case for elements using <code>tag!</code> method, but I don't see the equivalent for Processing Instructions.</p> <p>Any ideas?</p>
[ { "answer_id": 142158, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 3, "selected": false, "text": "xm.instruct! 'xml-stylesheet', {:href=>'/stylesheets/style.xslt', :type=>'text/xsl'}\n xm.instruct! :xml, {:encoding=>\"your_encoding_type\"}\n" }, { "answer_id": 26656521, "author": "andrhamm", "author_id": 169717, "author_profile": "https://Stackoverflow.com/users/169717", "pm_score": 0, "selected": false, "text": "atom_feed instruct atom_feed(instruct: {\n 'xml-stylesheet' => {type: 'text/xsl', href: 'styles.xml'}\n }) do |feed|\n feed.title \"My Atom Feed\"\n # entries...\nend\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styles.xml\"?>\n<feed xml:lang=\"en-US\" xmlns=\"http://www.w3.org/2005/Atom\">\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10026/" ]
142,058
<p>I am trying to use VBScript to do an XSLT transform on an XML object.<br> The XSL file I'm translating includes the <code>&lt;xsl:import href="script.xsl"/&gt;</code> directive. If I use the absolute URL (<code>http://localhost/mysite/script.xsl</code>), it imports the style sheet fine; however, if I use the relative path (<code>script.xsl</code>) it reports "resource not found." I need to be able to port this amongst a set of machines, so I need to be able to use the relative URI. Any suggestions?</p> <p>Notes:</p> <ul> <li>VBScript file is at <code>http://localhost/myscript.asp</code></li> <li>first XSL file is at <code>http://localhost/mysite/styles.xsl</code></li> <li>second XSL file is at <code>http://localhost/mysite/script.xsl</code></li> <li>using the relative path <code>mysite/script.xsl</code> also does not work</li> </ul> <p>Addendum:</p> <p>Thanks, everyone, for your answers. The more I dig into the code that is doing this, the stranger it is. <code>myscript.asp</code> is a rather unusual compilation of code. What happens is <code>styles.xsl</code> is included in the HTML output of <code>myscript.asp</code> as an XML chunk (<code>&lt;xml src=...&gt;</code>) and then that chunk is loaded as a stylesheet, using VBScript, on the client side. This stylesheet is then used to transform an XML chunk that is retrieved via XMLHTTP. So the problem is the context of <code>styles.xsl</code> is the HTML on the client side and has no relation to where <code>script.xsl</code> is.</p>
[ { "answer_id": 142102, "author": "Jon Schneider", "author_id": 12484, "author_profile": "https://Stackoverflow.com/users/12484", "pm_score": 0, "selected": false, "text": "<xsl:import href=\"mysite/script.xsl\"/>\n" }, { "answer_id": 164461, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 1, "selected": false, "text": "<xsl:import href=\"/mysite/script.xsl\"/>\n" }, { "answer_id": 197642, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": -1, "selected": false, "text": " <xsl:import href=\"{$approot}/somedir/script.xsl\"/>\n <xsl:import href=\"{/root/@approot}/somedir/script.xsl\"/>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
142,071
<p>I am looking for an app that will let me type in code ON my cellphone. I don't need to compile or anything, and its not to program for the cellphone. Just something nice to have when an idea pops in my head.</p> <p>Am I completely overlooking a simple code editor for Symbian S60v3 phones? </p> <p>I am looking for something similar to <a href="http://www.logicalsky.com/Product_CEdit.php" rel="nofollow noreferrer">CEdit</a> which is for Windows Mobile. </p>
[ { "answer_id": 1394097, "author": "sbabybird", "author_id": 88450, "author_profile": "https://Stackoverflow.com/users/88450", "pm_score": 1, "selected": false, "text": "ped-s60" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2855/" ]
142,090
<p>I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method. Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?</p> <p>Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.</p>
[ { "answer_id": 142112, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "class ValidationRule {\n public delegate bool Validator();\n\n private Validator _v;\n\n public ValidationRule(Validator v) { _v = v; }\n\n public Validator Validator {\n get { return _v; }\n set { _v = value; }\n }\n\n public bool IsValid { get { return _v(); } }\n}\n\nvar alwaysPasses = new ValidationRule(() => true);\nvar alwaysFails = new ValidationRule(() => false);\n\nvar textBoxHasText = new ValidationRule(() => textBox1.Text.Length > 0);\n Validator ValidationRules textBoxHasText interface IValidationRule {\n bool IsValid { get; }\n}\n\nclass BoxHasText : IValidationRule {\n TextBox _c;\n\n public BoxHasText(TextBox c) { _c = c; }\n\n public bool IsValid {\n get { return _c.Text.Length > 0; }\n }\n}\n" }, { "answer_id": 142129, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": "Func<T,bool> validator.AddValidation(item => (item.HasEnoughInformation() || item.IsEmpty());\n List<Func<T,bool>>" }, { "answer_id": 142160, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 1, "selected": false, "text": "class ValidationRule\n{\n private Func<bool> validation;\n\n public ValidationRule(Func<bool> validation)\n {\n this.validation = validation;\n }\n public bool IsValid()\n {\n return validation();\n }\n}\n" }, { "answer_id": 142165, "author": "Jason Olson", "author_id": 5418, "author_profile": "https://Stackoverflow.com/users/5418", "pm_score": 2, "selected": false, "text": " class Entity\n {\n public string MyProperty { get; set; }\n }\n class ValidationRule<T> where T : Entity\n {\n private Func<T, bool> _rule;\n\n public ValidationRule(Func<T, bool> rule)\n {\n _rule = rule;\n }\n\n public bool IsValid(T entity)\n {\n return _rule(entity);\n }\n }\n var myEntity = new Entity() { MyProperty = \"Hello World\" };\n var rule = new ValidationRule<Entity>(entity => entity.MyProperty == \"Hello World\");\n\n var valid = rule.IsValid(myEntity);\n var rule = new ValidationRule<TextBox>(tb => tb.Text.Length > 0);\n rule.IsValid(myTextBox);\n" }, { "answer_id": 541488, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 0, "selected": false, "text": " public static void Valid(Address address, IScope scope)\n {\n scope.Validate(() => address.Street1, StringIs.Limited(10, 256));\n scope.Validate(() => address.Street2, StringIs.Limited(256));\n scope.Validate(() => address.Country, Is.NotDefault);\n scope.Validate(() => address.Zip, StringIs.Limited(10));\n\n switch (address.Country)\n {\n case Country.USA:\n scope.Validate(() => address.Zip, StringIs.Limited(5, 10));\n break;\n case Country.France:\n break;\n case Country.Russia:\n scope.Validate(() => address.Zip, StringIs.Limited(6, 6));\n break;\n default:\n scope.Validate(() => address.Zip, StringIs.Limited(1, 64));\n break;\n }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
142,110
<p>Basically I want to know how to set center alignment for a cell using VBScript...</p> <p>I've been googling it and can't seem to find anything that helps.</p>
[ { "answer_id": 142170, "author": "mistrmark", "author_id": 19242, "author_profile": "https://Stackoverflow.com/users/19242", "pm_score": 1, "selected": false, "text": "'Select a Cell Range\nRange(\"D4\").Select\n\n'Set the horizontal and vertical alignment\nWith Selection\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlBottom\nEnd With\n" }, { "answer_id": 142187, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 4, "selected": true, "text": "Set excel = CreateObject(\"Excel.Application\")\n\nexcel.Workbooks.Add() ' create blank workbook\n\nSet workbook = excel.Workbooks(1)\n\n' set A1 to be centered.\nworkbook.Sheets(1).Cells(1,1).HorizontalAlignment = -4108 ' xlCenter constant.\n\nworkbook.SaveAs(\"C:\\NewFile.xls\")\n\nexcel.Quit()\n\nset excel = nothing\n\n'If the script errors, it'll give you an orphaned excel process, so be warned.\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
142,121
<p>I have a class that processes a 2 xml files and produces a text file. </p> <p>I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following:</p> <ol> <li>For input A and B, generate the output.</li> <li>Compare the contents of the generated file to the contents expected output</li> <li>When the actual contents differ from the expected contents, fail and display some <strong>useful</strong> information about the differences.</li> </ol> <p>Below is the prototype for the class along with my first stab at unit tests.</p> <p><strong>Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?</strong></p> <p><strong>Is there a better way to coax text-file differences from NUnit?</strong> Should I embed a textfile diff algorithm?</p> <hr> <pre><code>class ReportGenerator { string Generate(string inputPathA, string inputPathB) { //do stuff } } </code></pre> <hr> <pre><code>[TextFixture] public class ReportGeneratorTests { static Diff(string pathToExpectedResult, string pathToActualResult) { using (StreamReader rs1 = File.OpenText(pathToExpectedResult)) { using (StreamReader rs2 = File.OpenText(pathToActualResult)) { string actualContents = rs2.ReadToEnd(); string expectedContents = rs1.ReadToEnd(); //this works, but the output could be a LOT more useful. Assert.AreEqual(expectedContents, actualContents); } } } static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult) { ReportGenerator obj = new ReportGenerator(); string pathToResult = obj.Generate(pathToInputA, pathToInputB); Diff(pathToExpectedResult, pathToResult); } [Test] public void TestX() { TestGenerate("x1.xml", "x2.xml", "x-expected.txt"); } [Test] public void TestY() { TestGenerate("y1.xml", "y2.xml", "y-expected.txt"); } //etc... } </code></pre> <hr> <h2>Update</h2> <p>I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures.</p>
[ { "answer_id": 142312, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 4, "selected": true, "text": "using NUnit.Framework.Extensions;\n\n[RowTest]\n[Row(\"x1.xml\", \"x2.xml\", \"x-expected.xml\")]\n[Row(\"y1.xml\", \"y2.xml\", \"y-expected.xml\")]\npublic void TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)\n {\n ReportGenerator obj = new ReportGenerator();\n string pathToResult = obj.Generate(pathToInputA, pathToInputB);\n Diff(pathToExpectedResult, pathToResult);\n }\n" }, { "answer_id": 145345, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "[Test] public void TestX() { DoTest(\"X\"); }\n[Test] public void TestY() { DoTest(\"Y\"); }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
142,142
<p>Is there a query in SQL Server 2005 I can use to get the server's IP or name?</p>
[ { "answer_id": 142144, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 3, "selected": false, "text": "select @@servername\n" }, { "answer_id": 142146, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 3, "selected": false, "text": "SELECT @@SERVERNAME;\n" }, { "answer_id": 142157, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "SELECT @@SERVERNAME;\n SELECT LEFT(ltrim(rtrim(@@ServerName)), Charindex('\\', ltrim(rtrim(@@ServerName))) -1)\n SELECT SERVERPROPERTY('MachineName')\n create Procedure sp_get_ip_address (@ip varchar(40) out)\nas\nbegin\nDeclare @ipLine varchar(200)\nDeclare @pos int\nset nocount on\n set @ip = NULL\n Create table #temp (ipLine varchar(200))\n Insert #temp exec master..xp_cmdshell 'ipconfig'\n select @ipLine = ipLine\n from #temp\n where upper (ipLine) like '%IP ADDRESS%'\n if (isnull (@ipLine,'***') != '***')\n begin \n set @pos = CharIndex (':',@ipLine,1);\n set @ip = rtrim(ltrim(substring (@ipLine , \n @pos + 1 ,\n len (@ipLine) - @pos)))\n end \ndrop table #temp\nset nocount off\nend \ngo\n\ndeclare @ip varchar(40)\nexec sp_get_ip_address @ip out\nprint @ip\n" }, { "answer_id": 142517, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 2, "selected": false, "text": "SELECT SERVERPROPERTY('MachineName')\n" }, { "answer_id": 9622810, "author": "chris", "author_id": 1236579, "author_profile": "https://Stackoverflow.com/users/1236579", "pm_score": 5, "selected": false, "text": "SELECT dec.local_net_address\nFROM sys.dm_exec_connections AS dec\nWHERE dec.session_id = @@SPID;\n SELECT SERVERPROPERTY(N'MachineName');\n" }, { "answer_id": 14695530, "author": "Jeff Muzzy", "author_id": 2041021, "author_profile": "https://Stackoverflow.com/users/2041021", "pm_score": 8, "selected": false, "text": "SELECT \n CONNECTIONPROPERTY('net_transport') AS net_transport,\n CONNECTIONPROPERTY('protocol_type') AS protocol_type,\n CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,\n CONNECTIONPROPERTY('local_net_address') AS local_net_address,\n CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,\n CONNECTIONPROPERTY('client_net_address') AS client_net_address \n <local machine>" }, { "answer_id": 33652731, "author": "Dave Mason", "author_id": 2961160, "author_profile": "https://Stackoverflow.com/users/2961160", "pm_score": 4, "selected": false, "text": "ipconfig.exe xp_cmdshell sys.dm_exec_connections SELECT c.local_net_address\nFROM sys.dm_exec_connections AS c\nWHERE c.session_id = @@SPID;\n\nSELECT TOP(1) c.local_net_address\nFROM sys.dm_exec_connections AS c\nWHERE c.local_net_address IS NOT NULL;\n" }, { "answer_id": 35604300, "author": "Bert Van Landeghem", "author_id": 2208335, "author_profile": "https://Stackoverflow.com/users/2208335", "pm_score": 2, "selected": false, "text": "DECLARE @ip_address varchar(15)\nDECLARE @tcp_port int \nDECLARE @connectionstring nvarchar(max) \nDECLARE @parm_definition nvarchar(max)\nDECLARE @command nvarchar(max)\n\nSET @connectionstring = N'Server=tcp:' + @@SERVERNAME + ';Trusted_Connection=yes;'\nSET @parm_definition = N'@ip_address_OUT varchar(15) OUTPUT\n , @tcp_port_OUT int OUTPUT';\n\nSET @command = N'SELECT @ip_address_OUT = a.local_net_address,\n @tcp_port_OUT = a.local_tcp_port\n FROM OPENROWSET(''SQLNCLI''\n , ''' + @connectionstring + '''\n , ''SELECT local_net_address\n , local_tcp_port\n FROM sys.dm_exec_connections\n WHERE session_id = @@spid\n '') as a'\n\nEXEC SP_executeSQL @command\n , @parm_definition\n , @ip_address_OUT = @ip_address OUTPUT\n , @tcp_port_OUT = @tcp_port OUTPUT;\n\n\nSELECT @ip_address, @tcp_port\n" }, { "answer_id": 38758901, "author": "Ranjana Ghimire", "author_id": 6636573, "author_profile": "https://Stackoverflow.com/users/6636573", "pm_score": 3, "selected": false, "text": "exec xp_cmdshell 'ipconfig'\n" }, { "answer_id": 47144078, "author": "Hank Freeman", "author_id": 2437624, "author_profile": "https://Stackoverflow.com/users/2437624", "pm_score": 4, "selected": false, "text": "SELECT \nSERVERPROPERTY('ComputerNamePhysicalNetBios') as 'Is_Current_Owner'\n ,SERVERPROPERTY('MachineName') as 'MachineName'\n ,case when @@ServiceName = \n Right (@@Servername,len(@@ServiceName)) then @@Servername \n else @@servername +' \\ ' + @@Servicename\n end as '@@Servername \\ Servicename', \n CONNECTIONPROPERTY('net_transport') AS net_transport,\n CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,\n dec.local_tcp_port,\n CONNECTIONPROPERTY('local_net_address') AS local_net_address,\n dec.local_net_address as 'dec.local_net_address'\n FROM sys.dm_exec_connections AS dec\n WHERE dec.session_id = @@SPID;\n" }, { "answer_id": 65750630, "author": "Eralper", "author_id": 832991, "author_profile": "https://Stackoverflow.com/users/832991", "pm_score": 0, "selected": false, "text": "select HOST_NAME()\n" }, { "answer_id": 67483921, "author": "گلی", "author_id": 15765660, "author_profile": "https://Stackoverflow.com/users/15765660", "pm_score": 2, "selected": false, "text": "SELECT CONNECTIONPROPERTY('local_net_address') AS [IP]\n\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
142,147
<p>I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.</p> <p>When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.</p> <p>Why does the scope of the 'ii' variable continue between loops?</p> <pre><code>var fs:Array = new Array(); for (var i = 0; i &lt; 3; i++){ var ii = i + 1; fs[i] = function(){ trace(ii); } } fs[0](); </code></pre>
[ { "answer_id": 142224, "author": "gltovar", "author_id": 2855, "author_profile": "https://Stackoverflow.com/users/2855", "pm_score": 0, "selected": false, "text": "var fs:Array = new Array();\n\nfor (var i = 0; i < 3; i++){\n\n var ii = i + 1; \n fs[i] = function(){\n trace(ii);\n }\n}\n\nfs[0]();\ntrace(\"out of scope: \" + ii + \"... but still works\");\n" }, { "answer_id": 143356, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 2, "selected": false, "text": "call apply function foo() {\n trace( this.value );\n}\n\nobjA = { value:\"A\" };\nobjB = { value:\"B\" };\n\nfoo.apply( objA ); // A\nfoo.apply( objB ); // B\n\nobjA.foo = foo;\nobjB.foo = foo;\n\nobjA.foo(); // A\nobjB.foo(); // B\n" }, { "answer_id": 148682, "author": "Bill", "author_id": 23063, "author_profile": "https://Stackoverflow.com/users/23063", "pm_score": 0, "selected": false, "text": "var fs:Array = new Array();\n\nfor (var i = 0; i < 3; i++){ \n var ii = i + 1; \n\n f = function(j){\n return function(){\n trace(j);\n };\n };\n fs[i] = f(ii);\n}\n\nfs[0](); //1\nfs[1](); //2\nfs[2](); //3\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
142,151
<p>How do I locate resources on the classpath in java? Specifically stuff that ends in .hbm.xml.</p> <p>My goal is to get a List of all resources on the classpath that end with ".hbm.xml".</p>
[ { "answer_id": 9282106, "author": "Maxim Veksler", "author_id": 48062, "author_profile": "https://Stackoverflow.com/users/48062", "pm_score": 1, "selected": false, "text": "findClasses ClassLoaderUtil public class ClassLoaderUtil {\n /**\n * Recursive method used to find all classes in a given path (directory or zip file url). Directories\n * are searched recursively. (zip files are\n * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files\n *\n * @param path The base directory or url from which to search.\n * @param packageName The package name for classes found inside the base directory\n * @param regex an optional class name pattern. e.g. .*Test\n * @return The classes\n */\n private static TreeSet<String> findClasses(String path, String packageName, Pattern regex) throws Exception {\n TreeSet<String> classes = new TreeSet<String>();\n if (path.startsWith(\"file:\") && path.contains(\"!\")) {\n String[] split = path.split(\"!\");\n URL jar = new URL(split[0]);\n ZipInputStream zip = new ZipInputStream(jar.openStream());\n ZipEntry entry;\n while ((entry = zip.getNextEntry()) != null) {\n if (entry.getName().endsWith(\".class\")) {\n String className = entry.getName().replaceAll(\"[$].*\", \"\").replaceAll(\"[.]class\", \"\").replace('/', '.');\n if (className.startsWith(packageName) && (regex == null || regex.matcher(className).matches()))\n classes.add(className);\n }\n }\n }\n File dir = new File(path);\n if (!dir.exists()) {\n return classes;\n }\n\n File[] files = dir.listFiles();\n for (File file : files) {\n if (file.isDirectory()) {\n assert !file.getName().contains(\".\");\n classes.addAll(findClasses(file.getAbsolutePath(), packageName + \".\" + file.getName(), regex));\n } else if (file.getName().endsWith(\".class\")) {\n String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);\n if (regex == null || regex.matcher(className).matches())\n classes.add(className);\n }\n }\n return classes;\n }\n\n public static <T> List<T> instances(Class<? extends T>[] classList) {\n List<T> tList = new LinkedList<T>();\n for(Class<? extends T> tClass : classList) {\n try {\n // Only try to instantiate real classes.\n if(! Modifier.isAbstract(tClass.getModifiers()) && ! Modifier.isInterface(tClass.getModifiers())) {\n tList.add(tClass.newInstance());\n }\n } catch (Throwable t) {\n throw new RuntimeException(t.getMessage(), t);\n }\n\n }\n\n return tList;\n }\n\n public static Class[] findByPackage(String packageName, Class isAssignableFrom) {\n Class[] clazzes = getClassesInPackage(packageName, null);\n\n if(isAssignableFrom == null) {\n return clazzes;\n } else {\n List<Class> filteredList = new ArrayList<Class>();\n for(Class clazz : clazzes) {\n if(isAssignableFrom.isAssignableFrom(clazz))\n filteredList.add(clazz);\n }\n\n return filteredList.toArray(new Class[0]);\n }\n }\n\n /**\n * Scans all classes accessible from the context class loader which belong to the given package and subpackages.\n * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files\n *\n * @param packageName The base package\n * @param regexFilter an optional class name pattern.\n * @return The classes\n */\n public static Class[] getClassesInPackage(String packageName, String regexFilter) {\n Pattern regex = null;\n if (regexFilter != null)\n regex = Pattern.compile(regexFilter);\n\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n assert classLoader != null;\n String path = packageName.replace('.', '/');\n Enumeration<URL> resources = classLoader.getResources(path);\n List<String> dirs = new ArrayList<String>();\n while (resources.hasMoreElements()) {\n URL resource = resources.nextElement();\n dirs.add(resource.getFile());\n }\n TreeSet<String> classes = new TreeSet<String>();\n for (String directory : dirs) {\n classes.addAll(findClasses(directory, packageName, regex));\n }\n ArrayList<Class> classList = new ArrayList<Class>();\n for (String clazz : classes) {\n classList.add(Class.forName(clazz));\n }\n return classList.toArray(new Class[classes.size()]);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
142,223
<p>What factors indicate that a project's solution should not be coded in a dynamic language?</p>
[ { "answer_id": 142410, "author": "alps123", "author_id": 22337, "author_profile": "https://Stackoverflow.com/users/22337", "pm_score": 0, "selected": false, "text": "@contents = <FILE>;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
142,239
<p>We're building an app that stores "hours of operation" for various businesses. What is the easiest way to represent this data so you can easily check if an item is open?</p> <p>Some options:</p> <ul> <li>Segment out blocks (every 15 minutes) that you can mark "open/closed". Checking involves seeing if the "open" bit is set for the desired time (a bit like a train schedule).</li> <li>Storing a list of time ranges (11am-2pm, 5-7pm, etc.) and checking whether the current time falls in any specified range (this is what our brain does when parsing the strings above).</li> </ul> <p>Does anyone have experience in storing and querying timetable information and any advice to give?</p> <p>(There's all sorts of crazy corner cases like "closed the first Tuesday of the month", but we'll leave that for another day).</p>
[ { "answer_id": 142460, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "BusinessID | weekDay | OpenTime | CloseTime \n---------------------------------------------\n 1 1 9 13\n 1 2 5 18\n 1 3 5 18\n 1 4 5 18\n 1 5 5 18\n 1 6 5 18\n 1 7 5 18\n SELECT @isOpen = CAST\n (SELECT 1 FROM tblHours \n WHERE BusinessId = @id AND weekDay = @Day \n AND CONVERT(Currentime to 24 hour) IS BETWEEN(OpenTime,CloseTime)) AS BIT;\n" }, { "answer_id": 142484, "author": "Christopher Mahan", "author_id": 479, "author_profile": "https://Stackoverflow.com/users/479", "pm_score": 1, "selected": false, "text": "businessID | datetime | type\n==========================================\n 1 10/1/2008 10:30:00 AM 1\n 1 10/1/2008 02:45:00 PM 0\n 1 10/1/2008 05:15:00 PM 1\n 1 10/2/2008 02:00:00 AM 0\n 1 10/2/2008 10:30:00 AM 1\n select top 1 type from thehours where datetimefield<=somedatetime and businessID = somebusinessid order by datetime desc\n" }, { "answer_id": 142575, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 0, "selected": false, "text": "Business_id (int)\nStart_Time (time)\nEnd_Time (time)\nCondition varchar/string\nOpen bit\n Let Query1 = select count(open) from store_hours where @t between start_time and end_time and open = true and business_id = @id and (.. dynamically built expression)\n\nLet Query2 = select count(closed) from store_hours where @t between start_time and end_time and open = false and business_id = @id and (.. dynamically built expression)\n select cast(Query1 as bit) & ~cast(Query2 as bit)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]