qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
20,722
<p>How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of <a href="http://silverlight.net/" rel="nofollow noreferrer">Silverlight</a> currently running on the browser?</p>
[ { "answer_id": 20745, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 2, "selected": false, "text": "Silverlight.isInstalled = function(d)\n{\n var c = false, a = null;\n try\n {\n var b = null;\n if(Silverlight.ua.Browser == \"MSIE\")\n b = new ActiveXObject(\"AgControl.AgControl\");\n else\n if(navigator.plugins[\"Silverlight Plug-In\"])\n {\n a = document.createElement(\"div\");\n document.body.appendChild(a);\n a.innerHTML = '<embed type=\"application/x-silverlight\" />';\n b = a.childNodes[0]\n }\n\n if(b.IsVersionSupported(d))\n c = true;\n b = null;\n Silverlight.available = true\n }\n catch(e)\n {\n c=false\n }\n\n if(a)\n document.body.removeChild(a);\n return c\n};\n" }, { "answer_id": 26956, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 4, "selected": true, "text": "if(slPlugin.isVersionSupported(\"2.0\")) {\n alert(\"I haz some flavour of Silverlight 2\");\n if(slPlugin.isVersionSupported(\"2.0.30523\")) {\n alert(\"I haz Silverlight 2.0.30523, but could be any revision.\");\n alert(navigator.plugins[\"Silverlight Plug-In\"].description);\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/375/" ]
20,731
<p>I've tried several things already,</p> <pre><code>std::stringstream m; m.empty(); m.clear(); </code></pre> <p>both of which don't work.</p>
[ { "answer_id": 20732, "author": "CodingWithoutComments", "author_id": 25, "author_profile": "https://Stackoverflow.com/users/25", "pm_score": 5, "selected": false, "text": "m.str(\"\");\n" }, { "answer_id": 20792, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 11, "selected": true, "text": "empty() clear() ios eofbit clear() goodbit stringstream m.str(\"\");\n m.str(std::string());\n std::string const char*" }, { "answer_id": 12309628, "author": "John", "author_id": 1653342, "author_profile": "https://Stackoverflow.com/users/1653342", "pm_score": -1, "selected": false, "text": " m.str(\"\");\n m.str() = \"\";\n m.str(std::string());\n m.str().clear();\n" }, { "answer_id": 12843784, "author": "jerron", "author_id": 1738731, "author_profile": "https://Stackoverflow.com/users/1738731", "pm_score": 5, "selected": false, "text": "m=std::stringstream();\n" }, { "answer_id": 19439633, "author": "Francisco Cortes", "author_id": 2406499, "author_profile": "https://Stackoverflow.com/users/2406499", "pm_score": 4, "selected": false, "text": "//clear the stringstream variable\n\nsstm.str(\"\");\nsstm.clear();\n\n//fill up the streamstream variable\nsstm << \"crap\" << \"morecrap\";\n" }, { "answer_id": 22668889, "author": "TimoK", "author_id": 2757147, "author_profile": "https://Stackoverflow.com/users/2757147", "pm_score": 4, "selected": false, "text": "{\n std::stringstream ss;\n ss << \"what\";\n}\n\n{\n std::stringstream ss;\n ss << \"the\";\n}\n\n{\n std::stringstream ss;\n ss << \"heck\";\n}\n" }, { "answer_id": 23266418, "author": "Nikos Athanasiou", "author_id": 2567683, "author_profile": "https://Stackoverflow.com/users/2567683", "pm_score": 6, "selected": false, "text": "std::stringstream().swap(m); // swap m with a default constructed stringstream\n int main ()\n{\n std::string payload(16, 'x');\n \n std::stringstream *ss = new std::stringstream; // Create a memory leak\n (*ss) << payload; // Leak more memory\n \n // Now choose a way to \"clear\" a string stream\n //std::stringstream().swap(*ss); // Method 1\n //ss->str(std::string()); // Method 2\n \n std::cout << \"end\" << std::endl;\n}\n =================================================================\n==10415==ERROR: LeakSanitizer: detected memory leaks\n\nDirect leak of 392 byte(s) in 1 object(s) allocated from:\n #0 0x510ae8 in operator new(unsigned long) (/tmp/1637178326.0089633/a.out+0x510ae8)\n #1 0x514e80 in main (/tmp/1637178326.0089633/a.out+0x514e80)\n #2 0x7f3079ffb82f in __libc_start_main /build/glibc-Cl5G7W/glibc-2.23/csu/../csu/libc-start.c:291\n\nIndirect leak of 513 byte(s) in 1 object(s) allocated from:\n #0 0x510ae8 in operator new(unsigned long) (/tmp/1637178326.0089633/a.out+0x510ae8)\n #1 0x7f307b03a25c in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::reserve(unsigned long) (/usr/local/lib64/libstdc++.so.6+0x13725c)\n #2 0x603000000010 (<unknown module>)\n\nSUMMARY: AddressSanitizer: 905 byte(s) leaked in 2 allocation(s).\n vector::clear" }, { "answer_id": 69164375, "author": "Kuba hasn't forgotten Monica", "author_id": 1329652, "author_profile": "https://Stackoverflow.com/users/1329652", "pm_score": 2, "selected": false, "text": "stringstream::str stringbuf::str void clear(std::stringstream &stream)\n{\n if (stream.rdbuf()) stream.rdbuf()->pubseekpos(0);\n}\n std::size_t availSize() (const std::stringstream& stream)\n{\n if (stream.rdbuf())\n return std::size_t(\n stream.rdbuf()->pubseekoff(0, std::ios_base::cur, std::ios_base::out));\n else\n return 0;\n}\n std::size_t readAndClear(std::stringstream &stream, void* outBuf, std::size_t outSize)\n{\n auto const copySize = std::min(availSize(stream), outSize);\n if (!copySize) return 0; // takes care of null stream.rdbuf()\n\n stream.rdbuf()->sgetn(outBuf, copySize);\n stream.rdbuf()->pubseekpos(0); // clear the buffer\n\n return copySize;\n}\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
20,744
<p>Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue.</p>
[ { "answer_id": 886149, "author": "Liron Yahdav", "author_id": 62, "author_profile": "https://Stackoverflow.com/users/62", "pm_score": 3, "selected": true, "text": "function getRepViewBtn() {\n return document.getElementsByName(\"ReportViewer1$ctl00$ctl00\")[0];\n}\n\nfunction hideViewReportButton() { // call this where needed\n var btn = getRepViewBtn();\n btn.style.display = 'none';\n}\n" }, { "answer_id": 1843548, "author": "Travis Collins", "author_id": 30460, "author_profile": "https://Stackoverflow.com/users/30460", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#<%= ReportViewer1.ClientID %> td:first\").attr(\"width\", \"1\");\n });\n</script>\n" }, { "answer_id": 27257819, "author": "PoppyIndicular", "author_id": 4317302, "author_profile": "https://Stackoverflow.com/users/4317302", "pm_score": 1, "selected": false, "text": "function moveButton() {\n document.getElementById('ParameterTable_ctl00_MainContent_MyReports_ctl04').appendChild(document.getElementById('ctl00_MainContent_MyReports_ctl04_ctl00'));\n }\n ScriptManager.RegisterStartupScript(Me, Me.GetType(), \"moveButton\", \"moveButton();\", True)\n #ctl00_MainContent_MyReports_ctl04_ctl00 {\n margin: 0px 0px 0px 50px;\n}\n" }, { "answer_id": 52813948, "author": "Paul", "author_id": 894995, "author_profile": "https://Stackoverflow.com/users/894995", "pm_score": 0, "selected": false, "text": " <script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#_ctl0_MainContent_reportViewer_fixedTable tr:first td:first-child\").attr(\"width\", \"1\"); \n $(\"#_ctl0_MainContent_reportViewer_fixedTable tr:first td:last-child\").attr(\"align\", \"left\"); \n });\n</script>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215/" ]
20,762
<p>Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML?</p> <p>Note: </p> <ul> <li>The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point.</li> <li>The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character.</li> </ul> <p><em>Background:</em></p> <p>I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification.</p> <p>In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.</p>
[ { "answer_id": 20777, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 7, "selected": true, "text": "/// <summary>\n/// Removes control characters and other non-UTF-8 characters\n/// </summary>\n/// <param name=\"inString\">The string to process</param>\n/// <returns>A string with no control characters or entities above 0x00FD</returns>\npublic static string RemoveTroublesomeCharacters(string inString)\n{\n if (inString == null) return null;\n\n StringBuilder newString = new StringBuilder();\n char ch;\n\n for (int i = 0; i < inString.Length; i++)\n {\n\n ch = inString[i];\n // remove any characters outside the valid UTF-8 range as well as all control characters\n // except tabs and new lines\n //if ((ch < 0x00FD && ch > 0x001F) || ch == '\\t' || ch == '\\n' || ch == '\\r')\n //if using .NET version prior to 4, use above logic\n if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4\n {\n newString.Append(ch);\n }\n }\n return newString.ToString();\n\n}\n" }, { "answer_id": 641632, "author": "dnewcome", "author_id": 35311, "author_profile": "https://Stackoverflow.com/users/35311", "pm_score": 6, "selected": false, "text": "public static string XmlCharacterWhitelist( string in_string ) {\n if( in_string == null ) return null;\n\n StringBuilder sbOutput = new StringBuilder();\n char ch;\n\n for( int i = 0; i < in_string.Length; i++ ) {\n ch = in_string[i];\n if( ( ch >= 0x0020 && ch <= 0xD7FF ) || \n ( ch >= 0xE000 && ch <= 0xFFFD ) ||\n ch == 0x0009 ||\n ch == 0x000A || \n ch == 0x000D ) {\n sbOutput.Append( ch );\n }\n }\n return sbOutput.ToString();\n}\n" }, { "answer_id": 2293111, "author": "savio", "author_id": 276570, "author_profile": "https://Stackoverflow.com/users/276570", "pm_score": -1, "selected": false, "text": "private static String removeNonUtf8CompliantCharacters( final String inString ) {\n if (null == inString ) return null;\n byte[] byteArr = inString.getBytes();\n for ( int i=0; i < byteArr.length; i++ ) {\n byte ch= byteArr[i]; \n // remove any characters outside the valid UTF-8 range as well as all control characters\n // except tabs and new lines\n if ( !( (ch > 31 && ch < 253 ) || ch == '\\t' || ch == '\\n' || ch == '\\r') ) {\n byteArr[i]=' ';\n }\n }\n return new String( byteArr );\n}\n" }, { "answer_id": 3503958, "author": "Kesavan", "author_id": 422998, "author_profile": "https://Stackoverflow.com/users/422998", "pm_score": -1, "selected": false, "text": "$goodUTF8 = iconv(\"utf-8\", \"utf-8//IGNORE\", $badUTF8);\n" }, { "answer_id": 5239529, "author": "Nathan G", "author_id": 423508, "author_profile": "https://Stackoverflow.com/users/423508", "pm_score": 2, "selected": false, "text": " public static string CleanInvalidXmlChars( string Xml, string XMLVersion )\n {\n string pattern = String.Empty;\n switch( XMLVersion )\n {\n case \"1.0\":\n pattern = @\"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F]);\";\n break;\n case \"1.1\":\n pattern = @\"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF]);\";\n break;\n default:\n throw new Exception( \"Error: Invalid XML Version!\" );\n }\n\n Regex regex = new Regex( pattern, RegexOptions.IgnoreCase );\n if( regex.IsMatch( Xml ) )\n Xml = regex.Replace( Xml, String.Empty );\n return Xml;\n }\n" }, { "answer_id": 5936162, "author": "Murari Kumar", "author_id": 430608, "author_profile": "https://Stackoverflow.com/users/430608", "pm_score": -1, "selected": false, "text": "string sFinalString = \"\";\nstring hex = \"\";\nforeach (char ch in UTFCHAR)\n{\n int tmp = ch;\n if ((ch < 0x00FD && ch > 0x001F) || ch == '\\t' || ch == '\\n' || ch == '\\r')\n {\n sFinalString += ch;\n }\n else\n { \n sFinalString += \"&#\" + tmp+\";\";\n }\n}\n" }, { "answer_id": 10244306, "author": "Jodrell", "author_id": 659190, "author_profile": "https://Stackoverflow.com/users/659190", "pm_score": 3, "selected": false, "text": "public static string RemoveInvalidXmlChars(string input)\n{\n var isValid = new Predicate<char>(value =>\n (value >= 0x0020 && value <= 0xD7FF) ||\n (value >= 0xE000 && value <= 0xFFFD) ||\n value == 0x0009 ||\n value == 0x000A ||\n value == 0x000D);\n\n return new string(Array.FindAll(input.ToCharArray(), isValid));\n}\n public static string RemoveInvalidXmlChars(string input)\n{\n return new string(input.Where(value =>\n (value >= 0x0020 && value <= 0xD7FF) ||\n (value >= 0xE000 && value <= 0xFFFD) ||\n value == 0x0009 ||\n value == 0x000A ||\n value == 0x000D).ToArray());\n}\n Buffer.BlockCopy" }, { "answer_id": 14912930, "author": "Igor Kustov", "author_id": 1244353, "author_profile": "https://Stackoverflow.com/users/1244353", "pm_score": 5, "selected": false, "text": "void Main() {\n string content = \"\\v\\f\\0\";\n Console.WriteLine(IsValidXmlString(content)); // False\n\n content = RemoveInvalidXmlChars(content);\n Console.WriteLine(IsValidXmlString(content)); // True\n}\n\nstatic string RemoveInvalidXmlChars(string text) {\n char[] validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();\n return new string(validXmlChars);\n}\n\nstatic bool IsValidXmlString(string text) {\n try {\n XmlConvert.VerifyXmlChars(text);\n return true;\n } catch {\n return false;\n }\n}\n" }, { "answer_id": 24225671, "author": "mnaoumov", "author_id": 1074455, "author_profile": "https://Stackoverflow.com/users/1074455", "pm_score": 2, "selected": false, "text": "public static string StripInvalidXmlCharacters(string str)\n{\n var invalidXmlCharactersRegex = new Regex(\"[^\\u0009\\u000a\\u000d\\u0020-\\ud7ff\\ue000-\\ufffd]|([\\ud800-\\udbff](?![\\udc00-\\udfff]))|((?<![\\ud800-\\udbff])[\\udc00-\\udfff])\");\n return invalidXmlCharactersRegex.Replace(str, \"\");\n" }, { "answer_id": 27239510, "author": "Ryan Adams", "author_id": 4313632, "author_profile": "https://Stackoverflow.com/users/4313632", "pm_score": 3, "selected": false, "text": "public class InvalidXmlCharacterReplacingStreamReader : TextReader\n{\n private StreamReader implementingStreamReader;\n private char replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(Stream stream, char replacementCharacter)\n {\n implementingStreamReader = new StreamReader(stream);\n this.replacementCharacter = replacementCharacter;\n }\n\n public override void Close()\n {\n implementingStreamReader.Close();\n }\n\n public override ObjRef CreateObjRef(Type requestedType)\n {\n return implementingStreamReader.CreateObjRef(requestedType);\n }\n\n public void Dispose()\n {\n implementingStreamReader.Dispose();\n }\n\n public override bool Equals(object obj)\n {\n return implementingStreamReader.Equals(obj);\n }\n\n public override int GetHashCode()\n {\n return implementingStreamReader.GetHashCode();\n }\n\n public override object InitializeLifetimeService()\n {\n return implementingStreamReader.InitializeLifetimeService();\n }\n\n public override int Peek()\n {\n int ch = implementingStreamReader.Peek();\n if (ch != -1)\n {\n if (\n (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D\n )\n {\n return replacementCharacter;\n }\n }\n return ch;\n }\n\n public override int Read()\n {\n int ch = implementingStreamReader.Read();\n if (ch != -1)\n {\n if (\n (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D\n )\n {\n return replacementCharacter;\n }\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n int readCount = implementingStreamReader.Read(buffer, index, count);\n for (int i = index; i < readCount+index; i++)\n {\n char ch = buffer[i];\n if (\n (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D\n )\n {\n buffer[i] = replacementCharacter;\n }\n }\n return readCount;\n }\n\n public override Task<int> ReadAsync(char[] buffer, int index, int count)\n {\n throw new NotImplementedException();\n }\n\n public override int ReadBlock(char[] buffer, int index, int count)\n {\n throw new NotImplementedException();\n }\n\n public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)\n {\n throw new NotImplementedException();\n }\n\n public override string ReadLine()\n {\n throw new NotImplementedException();\n }\n\n public override Task<string> ReadLineAsync()\n {\n throw new NotImplementedException();\n }\n\n public override string ReadToEnd()\n {\n throw new NotImplementedException();\n }\n\n public override Task<string> ReadToEndAsync()\n {\n throw new NotImplementedException();\n }\n\n public override string ToString()\n {\n return implementingStreamReader.ToString();\n }\n}\n" }, { "answer_id": 30351313, "author": "Victor Zakharov", "author_id": 897326, "author_profile": "https://Stackoverflow.com/users/897326", "pm_score": 4, "selected": false, "text": "public class InvalidXmlCharacterReplacingStreamReader : StreamReader\n{\n private readonly char _replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(string fileName, char replacementCharacter) : base(fileName)\n {\n this._replacementCharacter = replacementCharacter;\n }\n\n public override int Peek()\n {\n int ch = base.Peek();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return this._replacementCharacter;\n }\n return ch;\n }\n\n public override int Read()\n {\n int ch = base.Read();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return this._replacementCharacter;\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n int readCount = base.Read(buffer, index, count);\n for (int i = index; i < readCount + index; i++)\n {\n char ch = buffer[i];\n if (IsInvalidChar(ch))\n {\n buffer[i] = this._replacementCharacter;\n }\n }\n return readCount;\n }\n\n private static bool IsInvalidChar(int ch)\n {\n return (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D;\n }\n}\n" }, { "answer_id": 40720009, "author": "Munavvar", "author_id": 3261852, "author_profile": "https://Stackoverflow.com/users/3261852", "pm_score": 0, "selected": false, "text": "public static string CleanInvalidXmlChars(string text) \n{ \n string re = @\"[^\\x09\\x0A\\x0D\\x20-\\xD7FF\\xE000-\\xFFFD\\x10000-x10FFFF]\"; \n return Regex.Replace(text, re, \"\"); \n} \n" }, { "answer_id": 44189911, "author": "BogdanRB", "author_id": 1295946, "author_profile": "https://Stackoverflow.com/users/1295946", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Replaces invalid Xml characters from input file, NOTE: if replacement character is \\0, then invalid Xml character is removed, instead of 1-for-1 replacement\n /// </summary>\n public class InvalidXmlCharacterReplacingStreamReader : StreamReader\n {\n private readonly char _replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(string fileName, char replacementCharacter)\n : base(fileName)\n {\n _replacementCharacter = replacementCharacter;\n }\n\n public override int Peek()\n {\n int ch = base.Peek();\n if (ch != -1 && IsInvalidChar(ch))\n {\n if ('\\0' == _replacementCharacter)\n return Peek(); // peek at the next one\n\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read()\n {\n int ch = base.Read();\n if (ch != -1 && IsInvalidChar(ch))\n {\n if ('\\0' == _replacementCharacter)\n return Read(); // read next one\n\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n int readCount= 0, ch;\n\n for (int i = 0; i < count && (ch = Read()) != -1; i++)\n {\n readCount++;\n buffer[index + i] = (char)ch;\n }\n\n return readCount;\n }\n\n\n private static bool IsInvalidChar(int ch)\n {\n return !XmlConvert.IsXmlChar((char)ch);\n }\n }\n" }, { "answer_id": 54390234, "author": "Georg Jung", "author_id": 1200847, "author_profile": "https://Stackoverflow.com/users/1200847", "pm_score": 2, "selected": false, "text": "*Async XmlConvert.IsXmlChar public class InvalidXmlCharacterReplacingStreamReader : StreamReader\n{\n private readonly char _replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(string fileName, char replacementCharacter) : base(fileName)\n {\n _replacementCharacter = replacementCharacter;\n }\n\n public InvalidXmlCharacterReplacingStreamReader(Stream stream, char replacementCharacter) : base(stream)\n {\n _replacementCharacter = replacementCharacter;\n }\n\n public override int Peek()\n {\n var ch = base.Peek();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read()\n {\n var ch = base.Read();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n var readCount = base.Read(buffer, index, count);\n ReplaceInBuffer(buffer, index, readCount);\n return readCount;\n }\n\n public override async Task<int> ReadAsync(char[] buffer, int index, int count)\n {\n var readCount = await base.ReadAsync(buffer, index, count).ConfigureAwait(false);\n ReplaceInBuffer(buffer, index, readCount);\n return readCount;\n }\n\n private void ReplaceInBuffer(char[] buffer, int index, int readCount)\n {\n for (var i = index; i < readCount + index; i++)\n {\n var ch = buffer[i];\n if (IsInvalidChar(ch))\n {\n buffer[i] = _replacementCharacter;\n }\n }\n }\n\n private static bool IsInvalidChar(int ch)\n {\n return IsInvalidChar((char)ch);\n }\n\n private static bool IsInvalidChar(char ch)\n {\n return !XmlConvert.IsXmlChar(ch);\n }\n}\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2029/" ]
20,778
<p>I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport.</p> <p>What I've got right now is</p> <pre><code>byte[] buffer = ...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore </code></pre> <p>Does anyone know how to convert binary to String and back without data loss?</p> <p>Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem.</p> <p>EDIT: Just for the sake of completeness, I used the <a href="http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html" rel="noreferrer">Base64</a> class from the <a href="http://commons.apache.org/" rel="noreferrer">Apache Commons</a> <a href="http://commons.apache.org/codec/" rel="noreferrer">Codec</a> package to solve this problem.</p>
[ { "answer_id": 20860, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 5, "selected": false, "text": "byte[] bytes = loadFile(file); \n//all chars in encoded are guaranteed to be 7-bit ASCII\nbyte[] encoded = Base64.encodeBase64(bytes);\nString printMe = new String(encoded, \"US-ASCII\");\nSystem.out.println(printMe);\nbyte[] decoded = Base64.decodeBase64(encoded);\n import java.io.*;\nimport java.nio.channels.*;\nimport javax.xml.bind.DatatypeConverter;\n\npublic class EncodeDecode { \n public static void main(String[] args) throws Exception {\n File file = new File(\"/bin/ls\");\n byte[] bytes = loadFile(file, new ByteArrayOutputStream()).toByteArray();\n String encoded = DatatypeConverter.printBase64Binary(bytes);\n System.out.println(encoded);\n byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);\n // check\n for (int i = 0; i < bytes.length; i++) {\n assert bytes[i] == decoded[i];\n }\n }\n\n private static <T extends OutputStream> T loadFile(File file, T out)\n throws IOException {\n FileChannel in = new FileInputStream(file).getChannel();\n try {\n assert in.size() == in.transferTo(0, in.size(), Channels.newChannel(out));\n return out;\n } finally {\n in.close();\n }\n }\n}\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
20,787
<p>In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables?</p> <p>Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables?</p>
[ { "answer_id": 20916, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": false, "text": "struct MyBitset {\n bool firstOption:1;\n bool secondOption:1;\n bool thirdOption:1;\n int fourBitNumber:4;\n};\n MyBitset bits;\nbits.firstOption = true;\nbits.fourBitNumber = 2;\n\nif(bits.thirdOption) {\n // Whatever!\n}\n" }, { "answer_id": 300994, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "op<< op>> std::bitset" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
20,794
<p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
[ { "answer_id": 20843, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "find . -type f -exec test \\{} -ef /path/to/file \\; -print man test -L -h head -0 FILE1 0 1" }, { "answer_id": 20845, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 1, "selected": false, "text": "wembley 0 /home/jj33/swap > cat p\nmy $f = shift;\n\nwhile (my $l = readlink($f)) {\n print \"$f -> $l\\n\";\n $f = $l;\n}\n\nif (!-e $f) {\n print \"$f doesn't exist\\n\";\n}\nwembley 0 /home/jj33/swap > ls -l | grep ^l\nlrwxrwxrwx 1 jj33 users 17 Aug 21 14:30 link -> non-existant-file\nlrwxrwxrwx 1 root users 31 Oct 10 2007 mm -> ../systems/mm/20071009-rewrite//\nlrwxrwxrwx 1 jj33 users 2 Aug 21 14:34 mmm -> mm/\nwembley 0 /home/jj33/swap > perl p mm\nmm -> ../systems/mm/20071009-rewrite/\nwembley 0 /home/jj33/swap > perl p mmm\nmmm -> mm\nmm -> ../systems/mm/20071009-rewrite/\nwembley 0 /home/jj33/swap > perl p link\nlink -> non-existant-file\nnon-existant-file doesn't exist\nwembley 0 /home/jj33/swap >\n" }, { "answer_id": 26957, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 6, "selected": true, "text": "if os.path.exists(path):\n os.unlink(path)\n try:\n os.stat(path)\nexcept OSError, e:\n if e.errno == errno.ENOENT:\n print 'path %s does not exist or is a broken symlink' % path\n else:\n raise e\n if not os.path.exists(os.readlink(path)):\n print 'path %s is a broken symlink' % path\n" }, { "answer_id": 31102280, "author": "am70", "author_id": 5058564, "author_profile": "https://Stackoverflow.com/users/5058564", "pm_score": 4, "selected": false, "text": " os.path.islink(filename) and not os.path.exists(filename)" }, { "answer_id": 40274852, "author": "Pierre D", "author_id": 758174, "author_profile": "https://Stackoverflow.com/users/758174", "pm_score": 0, "selected": false, "text": "import os\nfrom functools import lru_cache\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n@lru_cache(maxsize=2000)\ndef check_broken_link(filename):\n \"\"\"\n Check for broken symlinks, either at the file level, or in the\n hierarchy of parent dirs.\n If it finds a broken link, an ERROR message is logged.\n The function is cached, so that the same error messages are not repeated.\n\n Args:\n filename: file to check\n\n Returns:\n True if the file (or one of its parents) is a broken symlink.\n False otherwise (i.e. either it exists or not, but no element\n on its path is a broken link).\n\n \"\"\"\n if os.path.isfile(filename) or os.path.isdir(filename):\n return False\n if os.path.islink(filename):\n # there is a symlink, but it is dead (pointing nowhere)\n link = os.readlink(filename)\n logger.error('broken symlink: {} -> {}'.format(filename, link))\n return True\n # ok, we have either:\n # 1. a filename that simply doesn't exist (but the containing dir\n does exist), or\n # 2. a broken link in some parent dir\n parent = os.path.dirname(filename)\n if parent == filename:\n # reached root\n return False\n return check_broken_link(parent)\n import logging\nimport shutil\nimport tempfile\nimport os\n\nimport unittest\nfrom ..util import fileutil\n\n\nclass TestFile(unittest.TestCase):\n\n def _mkdir(self, path, create=True):\n d = os.path.join(self.test_dir, path)\n if create:\n os.makedirs(d, exist_ok=True)\n return d\n\n def _mkfile(self, path, create=True):\n f = os.path.join(self.test_dir, path)\n if create:\n d = os.path.dirname(f)\n os.makedirs(d, exist_ok=True)\n with open(f, mode='w') as fp:\n fp.write('hello')\n return f\n\n def _mklink(self, target, path):\n f = os.path.join(self.test_dir, path)\n d = os.path.dirname(f)\n os.makedirs(d, exist_ok=True)\n os.symlink(target, f)\n return f\n\n def setUp(self):\n # reset the lru_cache of check_broken_link\n fileutil.check_broken_link.cache_clear()\n\n # create a temporary directory for our tests\n self.test_dir = tempfile.mkdtemp()\n\n # create a small tree of dirs, files, and symlinks\n self._mkfile('a/b/c/foo.txt')\n self._mklink('b', 'a/x')\n self._mklink('b/c/foo.txt', 'a/f')\n self._mklink('../..', 'a/b/c/y')\n self._mklink('not_exist.txt', 'a/b/c/bad_link.txt')\n bad_path = self._mkfile('a/XXX/c/foo.txt', create=False)\n self._mklink(bad_path, 'a/b/c/bad_path.txt')\n self._mklink('not_a_dir', 'a/bad_dir')\n\n def tearDown(self):\n # Remove the directory after the test\n shutil.rmtree(self.test_dir)\n\n def catch_check_broken_link(self, expected_errors, expected_result, path):\n filename = self._mkfile(path, create=False)\n with self.assertLogs(level='ERROR') as cm:\n result = fileutil.check_broken_link(filename)\n logging.critical('nothing') # trick: emit one extra message, so the with assertLogs block doesn't fail\n error_logs = [r for r in cm.records if r.levelname is 'ERROR']\n actual_errors = len(error_logs)\n self.assertEqual(expected_result, result, msg=path)\n self.assertEqual(expected_errors, actual_errors, msg=path)\n\n def test_check_broken_link_exists(self):\n self.catch_check_broken_link(0, False, 'a/b/c/foo.txt')\n self.catch_check_broken_link(0, False, 'a/x/c/foo.txt')\n self.catch_check_broken_link(0, False, 'a/f')\n self.catch_check_broken_link(0, False, 'a/b/c/y/b/c/y/b/c/foo.txt')\n\n def test_check_broken_link_notfound(self):\n self.catch_check_broken_link(0, False, 'a/b/c/not_found.txt')\n\n def test_check_broken_link_badlink(self):\n self.catch_check_broken_link(1, True, 'a/b/c/bad_link.txt')\n self.catch_check_broken_link(0, True, 'a/b/c/bad_link.txt')\n\n def test_check_broken_link_badpath(self):\n self.catch_check_broken_link(1, True, 'a/b/c/bad_path.txt')\n self.catch_check_broken_link(0, True, 'a/b/c/bad_path.txt')\n\n def test_check_broken_link_badparent(self):\n self.catch_check_broken_link(1, True, 'a/bad_dir/c/foo.txt')\n self.catch_check_broken_link(0, True, 'a/bad_dir/c/foo.txt')\n # bad link, but shouldn't log a new error:\n self.catch_check_broken_link(0, True, 'a/bad_dir/c')\n # bad link, but shouldn't log a new error:\n self.catch_check_broken_link(0, True, 'a/bad_dir')\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "answer_id": 64213004, "author": "Владислав Шибалов", "author_id": 14395948, "author_profile": "https://Stackoverflow.com/users/14395948", "pm_score": 2, "selected": false, "text": "def kek(argum):\n if path.exists(\"/root/\" + argum) == False and path.islink(\"/root/\" + argum) == True:\n print(\"The path is a broken link, location: \" + os.readlink(\"/root/\" + argum))\n else:\n return \"No broken links fond\"\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
20,797
<p>I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:</p> <pre><code>byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); </code></pre> <p><code>smallPortion</code> would equal 1,2,3,4<br> <code>largeBytes</code> would equal 5,6,7,8,9</p>
[ { "answer_id": 20826, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "std::vector<int> IEnumerable<>" }, { "answer_id": 20949, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 5, "selected": true, "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nclass ArrayView<T> : IEnumerable<T>\n{\n private readonly T[] array;\n private readonly int offset, count;\n\n public ArrayView(T[] array, int offset, int count)\n {\n this.array = array;\n this.offset = offset;\n this.count = count;\n }\n\n public int Length\n {\n get { return count; }\n }\n\n public T this[int index]\n {\n get\n {\n if (index < 0 || index >= this.count)\n throw new IndexOutOfRangeException();\n else\n return this.array[offset + index];\n }\n set\n {\n if (index < 0 || index >= this.count)\n throw new IndexOutOfRangeException();\n else\n this.array[offset + index] = value;\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n for (int i = offset; i < offset + count; i++)\n yield return array[i];\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n IEnumerator<T> enumerator = this.GetEnumerator();\n while (enumerator.MoveNext())\n {\n yield return enumerator.Current;\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };\n ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5);\n ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5);\n Console.WriteLine(\"First array:\");\n foreach (byte b in p1)\n {\n Console.Write(b);\n }\n Console.Write(\"\\n\");\n Console.WriteLine(\"Second array:\");\n foreach (byte b in p2)\n {\n Console.Write(b);\n }\n Console.ReadKey();\n }\n}\n" }, { "answer_id": 1662438, "author": "Eren Ersönmez", "author_id": 201088, "author_profile": "https://Stackoverflow.com/users/201088", "pm_score": 5, "selected": false, "text": "System.ArraySegment<T> ArrayView<T>" }, { "answer_id": 5057108, "author": "Alireza Naghizadeh", "author_id": 625217, "author_profile": "https://Stackoverflow.com/users/625217", "pm_score": 5, "selected": false, "text": "smallPortion = largeBytes.Take(4).ToArray();\nlargeBytes = largeBytes.Skip(4).Take(5).ToArray();\n" }, { "answer_id": 13176553, "author": "Robert Wisniewski", "author_id": 1791254, "author_profile": "https://Stackoverflow.com/users/1791254", "pm_score": 2, "selected": false, "text": "private IEnumerable<byte[]> ArraySplit(byte[] bArray, int intBufforLengt)\n {\n int bArrayLenght = bArray.Length;\n byte[] bReturn = null;\n\n int i = 0;\n for (; bArrayLenght > (i + 1) * intBufforLengt; i++)\n {\n bReturn = new byte[intBufforLengt];\n Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);\n yield return bReturn;\n }\n\n int intBufforLeft = bArrayLenght - i * intBufforLengt;\n if (intBufforLeft > 0)\n {\n bReturn = new byte[intBufforLeft];\n Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);\n yield return bReturn;\n }\n }\n" }, { "answer_id": 44464131, "author": "orad", "author_id": 450913, "author_profile": "https://Stackoverflow.com/users/450913", "pm_score": 2, "selected": false, "text": "ArraySegment<T> public static class ArrayExtensionMethods\n{\n public static ArraySegment<T> GetSegment<T>(this T[] arr, int offset, int? count = null)\n {\n if (count == null) { count = arr.Length - offset; }\n return new ArraySegment<T>(arr, offset, count.Value);\n }\n}\n\nvoid Main()\n{\n byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };\n var p1 = arr.GetSegment(0, 5);\n var p2 = arr.GetSegment(5);\n Console.WriteLine(\"First array:\");\n foreach (byte b in p1)\n {\n Console.Write(b);\n }\n Console.Write(\"\\n\");\n Console.WriteLine(\"Second array:\");\n foreach (byte b in p2)\n {\n Console.Write(b);\n }\n}\n" }, { "answer_id": 66403734, "author": "Yefka", "author_id": 1008954, "author_profile": "https://Stackoverflow.com/users/1008954", "pm_score": 0, "selected": false, "text": " public static Guid ToGuid(this byte[] byteArray, int offset)\n {\n return new Guid(BitConverter.ToInt32(byteArray, offset), BitConverter.ToInt16(byteArray, offset + 4), BitConverter.ToInt16(byteArray, offset + 6), byteArray[offset + 8], byteArray[offset + 9], byteArray[offset + 10], byteArray[offset + 11], byteArray[offset + 12], byteArray[offset + 13], byteArray[offset + 14], byteArray[offset + 15]);\n }\n Done (Skip().Take()) in 1,156ms (for only 100000 guids :))\nDone (Array.Copy) in 1,219ms\nDone (ToGuid extension) in 994ms\nDone (ArraySegment) in 2,411ms\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
20,840
<p>Why should I or shouldn't I use dirty reads:</p> <pre><code>set transaction isolation level read uncommitted </code></pre> <p>in SQL Server?</p>
[ { "answer_id": 34477845, "author": "K ROHAN", "author_id": 5719882, "author_profile": "https://Stackoverflow.com/users/5719882", "pm_score": -1, "selected": false, "text": "Select * from table_name with(nolock) \n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
20,850
<p>I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.</p> <p>Basically, I have an external disk with two volumes: </p> <p>One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.</p> <p>So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. </p> <p>What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:</p> <ul> <li>I've tried going through options in Disk Utility</li> <li>I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.</li> <li>I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.</li> </ul> <p>Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).</p> <p>EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.</p>
[ { "answer_id": 36907, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "/etc/fstab LABEL=VolumeName none ntfs noauto\n /etc/fstab.hd diskarbitrationd" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1120/" ]
20,852
<p>I'd like to be able to track file read/writes of specific program invocations. No information about the actual transactions is required, just the file names involved.</p> <p>Is there a cross platform solution to this? <br /> What are various platform specific methods? <br /> On Linux I know there's strace/ptrace (if there are faster methods that'd be good too). <br />I think on mac os there's ktrace. <br /> What about Windows?</p> <p>Also, it would be amazing if it would be possible to block (stall out) file accesses until some later time.</p> <p>Thanks!</p>
[ { "answer_id": 21269, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 1, "selected": false, "text": "ReadDirectoryChangesW" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164871/" ]
20,856
<p>I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?</p> <p>Am I missing a best practice for tags?</p>
[ { "answer_id": 20871, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 10, "selected": true, "text": "Table: Item\nColumns: ItemID, Title, Content\n\nTable: Tag\nColumns: TagID, Title\n\nTable: ItemTag\nColumns: ItemID, TagID\n" }, { "answer_id": 48714, "author": "Nick Retallack", "author_id": 2653, "author_profile": "https://Stackoverflow.com/users/2653", "pm_score": 5, "selected": false, "text": "tagcloud: {\n map: function(doc){ \n for(tag in doc.tags){ \n emit(doc.tags[tag],1) \n }\n }\n reduce: function(keys,values){\n return values.length\n }\n}\n" }, { "answer_id": 18923641, "author": "Scheintod", "author_id": 1455622, "author_profile": "https://Stackoverflow.com/users/1455622", "pm_score": 7, "selected": false, "text": "Table: Item\nColumns: ItemID, Title, Content\nIndexes: ItemID\n\nTable: Tag\nColumns: ItemID, Title\nIndexes: ItemId, Title\n item Tag Tags Item SELECT Tag.Title \n FROM Tag \n JOIN ItemTag ON Tag.TagID = ItemTag.TagID\n WHERE ItemTag.ItemID = :id\n SELECT Tag.Title\nFROM Tag\nWHERE Tag.ItemID = :id\n SELECT Tag.Title, count(*)\n FROM Tag\n JOIN ItemTag ON Tag.TagID = ItemTag.TagID\n GROUP BY Tag.Title\n SELECT Tag.Title, count(*)\n FROM Tag\n GROUP BY Tag.Title\n SELECT Item.*\n FROM Item\n JOIN ItemTag ON Item.ItemID = ItemTag.ItemID\n JOIN Tag ON ItemTag.TagID = Tag.TagID\n WHERE Tag.Title = :title\n SELECT Item.*\n FROM Item\n JOIN Tag ON Item.ItemID = Tag.ItemID\n WHERE Tag.Title = :title\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
20,876
<p>I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:</p> <blockquote> <ul> <li>Query to get a list of popular IDs</li> <li>Subquery on each item to get properties from another table</li> </ul> </blockquote> <p>Ideally, the final report columns would look like this:</p> <pre><code>[ID] [property1] [property2] [SELECT COUNT(*) FROM AnotherTable WHERE ForeignID=ID] </code></pre> <p>There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.</p>
[ { "answer_id": 20914, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 0, "selected": false, "text": "select *,\n (select count(*) from tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt\nfrom tbl1 t1\n declare @tbl1 table\n(\n tbl1ID int,\n prop1 varchar(1),\n prop2 varchar(2)\n)\n\ndeclare @tbl2 table\n(\n tbl2ID int,\n tbl1ID int\n)\n\nselect *,\n (select count(*) from @tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt\nfrom @tbl1 t1\n" }, { "answer_id": 21037, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 0, "selected": false, "text": "select t1.ID, t1.property1, t1.property2, t2.somecol, t2.someothercol\nfrom table t1 left join anothertable t2 on t1.ID = t2.ID\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
20,882
<p>Some things look strange to me:</p> <ul> <li>What is the distinction between 0.0.0.0, 127.0.0.1, and [::]?</li> <li>How should each part of the foreign address be read (part1:part2)?</li> <li>What does a state Time_Wait, Close_Wait mean?</li> <li>etc.</li> </ul> <p>Could someone give a quick overview of how to interpret these results?</p>
[ { "answer_id": 2247948, "author": "PlanetUnknown", "author_id": 179521, "author_profile": "https://Stackoverflow.com/users/179521", "pm_score": 2, "selected": false, "text": "TCP Connection States SYN_SEND SYN_RECEIVED ESTABLISHED LISTEN TIMED_WAIT CLOSE_WAIT FIN_WAIT_2 LAST_ACK CLOSED" }, { "answer_id": 14511485, "author": "Aravind Yarram", "author_id": 127320, "author_profile": "https://Stackoverflow.com/users/127320", "pm_score": 4, "selected": false, "text": "0.0.0.0 127.0.0.1 online IP local network IP" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
20,910
<p>My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development.</p> <p>Most of our other development is done using .NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the .NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all .NET code. We have more .NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash.</p> <p>I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers. </p> <p>So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each?</p>
[ { "answer_id": 1508585, "author": "Akash Kava", "author_id": 85597, "author_profile": "https://Stackoverflow.com/users/85597", "pm_score": 4, "selected": false, "text": "e.g.\n// this is possible in flex..\n// but not in silverlight\n<mx:TextBox id=\"firstName\"/>\n<mx:TextBox id=\"lastName\"/>\n\n// display full name..\n<mx:Label text=\"{firstName.text} {lastName.text}\"/>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226/" ]
20,912
<p>I'm trying to do a file system backup of a RedHat Enterprise Linux v4 server using Symantec Backup Exec 11d (Rev 7170). The backup server is Windows Server 2003.</p> <p>I can browse the target server to create a selection list, and when I do a test run it completes successfully.</p> <p>However, when I run a real backup, the job fails immediately during the "processing" phase with the error: </p> <p><em>e000fe30 - A communications failure has occured.</em></p> <p>I've tried opening ports (10000, 1025-9999), etc. But no joy. Any ideas?</p>
[ { "answer_id": 30982, "author": "Tyler Gooch", "author_id": 1372, "author_profile": "https://Stackoverflow.com/users/1372", "pm_score": 0, "selected": false, "text": "[root@MYSERVER ~]# service iptables status \nTable: filter \nChain INPUT (policy ACCEPT) \ntarget prot opt source destination \nRH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 \n\nChain FORWARD (policy ACCEPT) \ntarget prot opt source destination \nRH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 \n\nChain OUTPUT (policy ACCEPT)\ntarget prot opt source destination \n\nChain RH-Firewall-1-INPUT (2 references) \ntarget prot opt source destination \nACCEPT all -- 0.0.0.0/0 0.0.0.0/0 \nACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmp type 255 \nACCEPT esp -- 0.0.0.0/0 0.0.0.0/0 \nACCEPT ah -- 0.0.0.0/0 0.0.0.0/0 \nACCEPT udp -- 0.0.0.0/0 224.0.0.251 udp dpt:5353 \nACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:631 \nACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:80 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:443 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5801 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5802 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5804 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5901 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5902 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5904 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:9099 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:10000 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:1025 \nREJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited\n [root@MYSERVER ~]# iptables -I RH-Firewall-1-INPUT 14 -p tcp -m tcp --dport 1024:65535 -j ACCEPT\n [root@MYSERVER ~]# service iptables status \nTable: filter \nChain INPUT (policy ACCEPT) \ntarget prot opt source destination \nRH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 \n\nChain FORWARD (policy ACCEPT) \ntarget prot opt source destination \nRH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 \n\nChain OUTPUT (policy ACCEPT)\ntarget prot opt source destination \n\nChain RH-Firewall-1-INPUT (2 references) \ntarget prot opt source destination \nACCEPT all -- 0.0.0.0/0 0.0.0.0/0 \nACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmp type 255 \nACCEPT esp -- 0.0.0.0/0 0.0.0.0/0 \nACCEPT ah -- 0.0.0.0/0 0.0.0.0/0 \nACCEPT udp -- 0.0.0.0/0 224.0.0.251 udp dpt:5353 \nACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:631 \nACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:80 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:443 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5801 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5802 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5804 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpts:1025:65535 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5901 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5902 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5904 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:9099 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:10000 \nACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:1025 \nREJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited \n [root@MYSERVER ~]# service iptables save\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372/" ]
20,923
<p>I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.</p> <p>Ideally I would like to adsutil.vbs to update the metabase. How do I do this?</p>
[ { "answer_id": 20953, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "'******************************************************************************************\n' Name: SetASPDotNetVersion\n' Description: Set the script mappings for the specified ASP.NET version\n' Inputs: objIIS, strNewVersion\n'******************************************************************************************\nSub SetASPDotNetVersion(objIIS, strNewVersion)\n Dim i, ScriptMaps, arrVersions(2), thisVersion, thisScriptMap\n Dim strSearchText, strReplaceText\n\n Select Case Trim(LCase(strNewVersion))\n Case \"1.1\"\n strReplaceText = \"v1.1.4322\"\n Case \"2.0\"\n strReplaceText = \"v2.0.50727\"\n Case Else\n wscript.echo \"WARNING: Non-supported ASP.NET version specified!\"\n Exit Sub\n End Select\n\n ScriptMaps = objIIS.ScriptMaps\n arrVersions(0) = \"v1.1.4322\"\n arrVersions(1) = \"v2.0.50727\"\n 'Loop through all three potential old values\n For Each thisVersion in arrVersions\n 'Loop through all the mappings\n For thisScriptMap = LBound(ScriptMaps) to UBound(ScriptMaps)\n 'Replace the old with the new \n ScriptMaps(thisScriptMap) = Replace(ScriptMaps(thisScriptMap), thisVersion, strReplaceText)\n Next\n Next \n\n objIIS.ScriptMaps = ScriptMaps\n objIIS.SetInfo\n wscript.echo \"<-------Set ASP.NET version to \" & strNewVersion & \" successfully.------->\"\nEnd Sub \n" }, { "answer_id": 21001, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "%windir%\\microsoft.net\\framework\\v1.1.4322\\aspnet_regiis -s W3SVC/[iisnumber]/ROOT\n %windir%\\microsoft.net\\framework\\v2.0.50727\\aspnet_regiis -s W3SVC/[iisnumber]/ROOT\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
20,926
<p>Today I was working on a tab navigation for a webpage. I tried the <a href="http://www.alistapart.com/articles/slidingdoors2/" rel="noreferrer">Sliding Doors</a> approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). </p> <p>I wanted to use a nested anchor, which didn't work because it is <a href="http://www.w3.org/TR/html4/struct/links.html#h-12.2.2" rel="noreferrer">not</a> allowed. Then I saw the tab- navigation at <a href="http://www.pageflakes.com" rel="noreferrer">Pageflakes</a>, which was actually working (including nested hyperlinks). Why?</p>
[ { "answer_id": 20944, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": true, "text": "<a class=\"page_tab page_tab\">\n <div class=\"page_title\" title=\"Click to rename this page.\">Click & Type Page Name</div>\n <a class=\"delete_page\" title=\"Click to delete this page\" style=\"display: block;\">X</a>\n</a>\n" }, { "answer_id": 33499678, "author": "Anas", "author_id": 2721727, "author_profile": "https://Stackoverflow.com/users/2721727", "pm_score": 0, "selected": false, "text": "$('<a>', {\n href: 'http://google.com',\n html: '<a>i am nested anchor </a>I am top Anchor'\n }).appendTo($('body'))\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078/" ]
20,927
<p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p> <pre><code>def save(self): super(Attachment, self).save() self.message.updated = self.updated </code></pre> <p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
[ { "answer_id": 72359, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 1, "selected": false, "text": "save()" }, { "answer_id": 33449486, "author": "Serjik", "author_id": 546822, "author_profile": "https://Stackoverflow.com/users/546822", "pm_score": 3, "selected": false, "text": "self.message.save() class Message(models.Model):\n updated = models.DateTimeField(auto_now = True)\n ...\n\nclass Attachment(models.Model):\n updated = models.DateTimeField(auto_now = True)\n message = models.ForeignKey(Message)\n\n def save(self):\n super(Attachment, self).save()\n self.message.save()\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1914/" ]
20,952
<p>I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx" rel="noreferrer">System.Configuration.Configuration</a> for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:</p> <pre><code>Configuration testConfig = new Configuration("&lt;?xml version=\"1.0\"?&gt;&lt;configuration&gt;...&lt;/configuration&gt;"); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section != null); </code></pre> <p>However, it looks like <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">ConfigurationManager</a> will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?</p>
[ { "answer_id": 704817, "author": "Oliver Pearmain", "author_id": 334395, "author_profile": "https://Stackoverflow.com/users/334395", "pm_score": 5, "selected": true, "text": "public class MyXmlCustomConfigSection : MyCustomConfigSection\n{\n public MyXmlCustomConfigSection (string configXml)\n {\n XmlTextReader reader = new XmlTextReader(new StringReader(configXml));\n DeserializeSection(reader);\n }\n}\n string configXml = \"<?xml version=\\\"1.0\\\"?><configuration>...</configuration>\";\nMyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338/" ]
20,958
<p>I'm designing a database table and asking myself this question: <em>How long should the firstname field be?</em></p> <p>Does anyone have a list of reasonable lengths for the most common fields, such as first name, last name, and email address?</p>
[ { "answer_id": 10103305, "author": "Micheal Mouner Mikhail Youssif", "author_id": 1119452, "author_profile": "https://Stackoverflow.com/users/1119452", "pm_score": 2, "selected": false, "text": "+------------+---------------+---------------------------------+\n| Field | Length (Char) | Description |\n+------------+---------------+---------------------------------+\n|firstname | 35 | |\n|lastname | 35 | |\n|email | 255 | |\n|url | 60+ | According to server and browser |\n|city | 45 | |\n|address | 90 | |\n+------------+---------------+---------------------------------+\n" }, { "answer_id": 19845397, "author": "Neil McGuigan", "author_id": 223478, "author_profile": "https://Stackoverflow.com/users/223478", "pm_score": 6, "selected": false, "text": " Min Max\n\nHostname 1 255\nDomain Name 4 253\nEmail Address 7 254\nEmail Address [1] 3 254\nTelephone Number 10 15 \nTelephone Number [2] 3 26 \nHTTP(S) URL w domain name 11 2083 \nURL [3] 6 2083 \nPostal Code [4] 2 11\nIP Address (incl ipv6) 7 45\nLongitude numeric 9,6\nLatitude numeric 8,6\nMoney[5] numeric 19,4\n\n[1] Allow local domains or TLD-only domains\n[2] Allow short numbers like 911 and extensions like 16045551212x12345\n[3] Allow local domains, tv:// scheme\n[4] http://en.wikipedia.org/wiki/List_of_postal_codes. Use max 12 if storing dash or space\n[5] http://stackoverflow.com/questions/224462/storing-money-in-a-decimal-column-what-precision-and-scale\n names: [\n {\n type:\"POLYNYM\",\n role:\"LEGAL\",\n given:\"George\",\n middle:\"Herman\",\n moniker:\"Babe\",\n surname:\"Ruth\",\n generation:\"JUNIOR\"\n },\n {\n type:\"MONONYM\",\n role:\"SOBRIQUET\",\n mononym:\"The Bambino\" /* mononyms can be more than one word, but only one component */\n },\n {\n type:\"MONONYM\",\n role:\"SOBRIQUET\",\n mononym:\"The Sultan of Swat\"\n }\n]\n names: [\n {\n type:\"POLYNYM\",\n role:\"PREFERRED\",\n given:\"Malcolm\",\n surname:\"X\"\n },\n {\n type:\"POLYNYM\",\n role:\"BIRTH\",\n given:\"Malcolm\",\n surname:\"Little\"\n },\n {\n type:\"POLYNYM\",\n role:\"LEGAL\",\n given:\"Malik\",\n surname:\"El-Shabazz\"\n }\n]\n names:[\n {\n type:\"POLYNYM\",\n role:\"LEGAL\",\n given:\"Prince\",\n middle:\"Rogers\",\n surname:\"Nelson\"\n },\n {\n type:\"MONONYM\",\n role:\"SOBRIQUET\",\n mononym:\"Prince\"\n },\n {\n type:\"PICTONYM\",\n role:\"LEGAL\",\n url:\"http://upload.wikimedia.org/wikipedia/en/thumb/a/af/Prince_logo.svg/130px-Prince_logo.svg.png\"\n }\n]\n names:[\n {\n type:\"POLYNYM\",\n role:\"LEGAL\",\n given:\"Juan Pablo\",\n surname:\"Fernández de Calderón\",\n secondarySurname:\"García-Iglesias\" /* hispanic people often have two surnames. it can be impolite to use the wrong one. Portuguese and Spaniards differ as to which surname is important */\n }\n]\n \"Billy Bob\" Thornton Ralph \"Vaughn Williams\"" }, { "answer_id": 41374563, "author": "PodTech.io", "author_id": 1842743, "author_profile": "https://Stackoverflow.com/users/1842743", "pm_score": 3, "selected": false, "text": "youtube max channel length = 20\nfacebook max name length = 50\ntwitter max handle length = 15\nemail max length = 255 \n" }, { "answer_id": 52347423, "author": "jrc", "author_id": 594211, "author_profile": "https://Stackoverflow.com/users/594211", "pm_score": 7, "selected": true, "text": "VARCHAR(255)" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437/" ]
20,959
<p>How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.</p> <p>It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.</p>
[ { "answer_id": 20970, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "AppDomain.CurrentDomain.GetAssemblies();" }, { "answer_id": 20974, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 5, "selected": true, "text": "using System;\nusing System.Reflection;\nusing System.Windows.Forms;\n\npublic class MyAppDomain\n{\n public static void Main(string[] args)\n {\n AppDomain ad = AppDomain.CurrentDomain;\n Assembly[] loadedAssemblies = ad.GetAssemblies();\n\n Console.WriteLine(\"Here are the assemblies loaded in this appdomain\\n\");\n foreach(Assembly a in loadedAssemblies)\n {\n Console.WriteLine(a.FullName);\n }\n }\n}\n" }, { "answer_id": 5847255, "author": "bernd_k", "author_id": 522317, "author_profile": "https://Stackoverflow.com/users/522317", "pm_score": 2, "selected": false, "text": "[System.AppDomain]::CurrentDomain.GetAssemblies()\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
20,993
<p>When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in?</p> <p>Two ways I've thought about have been:</p> <ul> <li>Stored the user database id in a session variable</li> <li>Stored the entire user object in a session variable</li> </ul> <p>Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc.</p>
[ { "answer_id": 21344, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 3, "selected": false, "text": "|Session |UserID | |--------+-------| |a1d4e...+ 12345 | |--------+-------| |c64b2...+ 23456 | |--------+-------|" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610/" ]
20,998
<p>When I try to create a SQL Server Login by saying</p> <pre><code>CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS; </code></pre> <p>I get this error</p> <blockquote> <p>The server principal 'ourdomain\SQLAccessGroup' already exists.</p> </blockquote> <p>However, when I try this code</p> <pre><code>DROP LOGIN [ourdomain\SQLAccessGroup] </code></pre> <p>I get this error</p> <blockquote> <p>Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission.</p> </blockquote> <p>The user that I am executing this code as is a sysadmin. Additionally, the user <code>ourdomain\SQLAccessGroup</code> does not show up in this query</p> <pre><code>select * from sys.server_principals </code></pre> <p>Does anyone have any ideas?</p>
[ { "answer_id": 21074, "author": "Pete", "author_id": 76, "author_profile": "https://Stackoverflow.com/users/76", "pm_score": 4, "selected": true, "text": "The login already has an account under a different user name.\n" }, { "answer_id": 21115, "author": "jonezy", "author_id": 2272, "author_profile": "https://Stackoverflow.com/users/2272", "pm_score": 2, "selected": false, "text": "EXEC sp_change_users_login ‘Auto_Fix’, ‘user_in_here’\n" }, { "answer_id": 57805923, "author": "Kuba D", "author_id": 4314825, "author_profile": "https://Stackoverflow.com/users/4314825", "pm_score": 0, "selected": false, "text": "ALTER LOGIN \"oldname\\RMS\" WITH name=\"currentname\\RMS\"\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76/" ]
21,027
<p>Is it possible to change how <kbd>Ctrl</kbd> + <kbd>Tab</kbd> and <kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>Tab</kbd> work in Visual Studio? I have disabled the popup navigator window, because I only want to switch between items in the tab control. My problem is the inconsistency of what switching to the next and previous document do.</p> <p>Every other program that uses a tab control for open document I have seen uses <kbd>Ctrl</kbd> + <kbd>Tab</kbd> to move from left to right and <kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>Tab</kbd> to go right to left. Visual Studio breaks this with its jump to the last tab selected. You can never know what document you will end up on, and it is never the same way twice. </p> <p>It is very counterintuitive. Is this a subtle way to encourage everyone to only ever have two document open at once?</p> <hr> <p>Let's say I have a few files open. I am working in one, and I need to see what is in the next tab to the right. In every other single application on the face of the Earth, <kbd>Ctrl</kbd> + <kbd>Tab</kbd> will get me there. But in Visual Studio, I have no idea which of the other tabs it will take me to. If I only ever have two documents open, this works great. As soon as you go to three or more, all bets are off as to what tab Visual Studio has decided to send you to. </p> <p>The problem with this is that I shouldn't have to think about the tool, it should fade into the background, and I should be thinking about the task. The current tab behavior keeps pulling me out of the task and makes me have to pay attention to the tool.</p>
[ { "answer_id": 21092, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": -1, "selected": false, "text": "#IfWinActive Microsoft Excel (application specific remapping)\n\n; Printing area in Excel (@ Ctrl+Alt+A)\n^!a::\nSend !ade\nreturn\n\n#IfWinActive\n\n\n$f4::\n; Closes the active window (make double tapping F4 works like ALT+F4)\nif f4_cnt > 0 \n{\n f4_cnt += 1\n return\n}\n\nf4_cnt = 1\nSetTimer, f4_Handler, 250\nreturn\n\nf4_Handler:\nSetTimer, f4_Handler, off\n\nif (f4_cnt >= 2) ; Pressed more than two times\n{ \n SendInput !{f4}\n} else {\n ; Resend f4 to the application\n Send {f4}\n}\n\nf4_cnt = 0\nreturn\n" }, { "answer_id": 36569, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 3, "selected": false, "text": "Next(Previous)DocumentWindowNav" }, { "answer_id": 3401858, "author": "user410261", "author_id": 410261, "author_profile": "https://Stackoverflow.com/users/410261", "pm_score": 3, "selected": false, "text": "Imports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module TabCtrl\n\nPublic Sub TabForward()\n Dim i As Integer\n Dim activateNext As Boolean = False\n\n For i = 1 To DTE.Windows.Count\n If DTE.Windows().Item(i).Kind = \"Document\" Then\n\n If activateNext Then\n DTE.Windows().Item(i).Activate()\n GoTo done\n End If\n\n If DTE.Windows().Item(i) Is DTE.ActiveWindow Then\n activateNext = True\n End If\n End If\n Next\n\n ' Was the last window... go back to the first\n If activateNext Then\n For i = 1 To DTE.Windows.Count\n If DTE.Windows().Item(i).Kind = \"Document\" Then\n DTE.Windows().Item(i).Activate()\n GoTo done\n End If\n Next\n End If\ndone:\n\nEnd Sub\n\nPublic Sub TabBackward()\n Dim i As Integer\n Dim activateNext As Boolean = False\n\n For i = DTE.Windows.Count To 1 Step -1\n If DTE.Windows().Item(i).Kind = \"Document\" Then\n\n If activateNext Then\n DTE.Windows().Item(i).Activate()\n GoTo done\n End If\n\n If DTE.Windows().Item(i) Is DTE.ActiveWindow Then\n activateNext = True\n End If\n End If\n Next\n\n ' Was the first window... go back to the last\n If activateNext Then\n For i = DTE.Windows.Count To 1 Step -1\n If DTE.Windows().Item(i).Kind = \"Document\" Then\n DTE.Windows().Item(i).Activate()\n GoTo done\n End If\n Next\n End If\ndone:\n\nEnd Sub\n\nEnd Module\n" }, { "answer_id": 10339707, "author": "Zoey", "author_id": 871086, "author_profile": "https://Stackoverflow.com/users/871086", "pm_score": 6, "selected": false, "text": "Window.[Previous/Next]..Document Tools -> Options -> Environment -> Keyboard,\n Window.[Next/Previous]Tab" }, { "answer_id": 15753497, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 6, "selected": false, "text": "TOOLS > Options > Environment > Keyboard Window.NextDocumentWindow Window.NextDocumentWindowNav Window.NextTab Previous" }, { "answer_id": 62254279, "author": "JWCS", "author_id": 6069586, "author_profile": "https://Stackoverflow.com/users/6069586", "pm_score": 0, "selected": false, "text": "[Ctrl]+," } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2277/" ]
21,052
<p>When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following:</p> <pre><code>&lt;%#((MyType)Container.DataItem).PropertyOfMyType%&gt; </code></pre> <p>The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified.</p> <pre><code>&lt;%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%&gt; </code></pre> <p>Is there any kind of <code>using</code> directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?</p>
[ { "answer_id": 21056, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 7, "selected": true, "text": "<%@ Import Namespace=\"RootNamespace.SubNamespace1\" %> \n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
21,060
<p>I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)</p> <p>Do you know if there's some setting I could touch for this not to happen?</p>
[ { "answer_id": 21056, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 7, "selected": true, "text": "<%@ Import Namespace=\"RootNamespace.SubNamespace1\" %> \n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
21,078
<p>What's the most efficient way to concatenate strings?</p>
[ { "answer_id": 21084, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 2, "selected": false, "text": "StringBuilder sb = new StringBuilder();\nsb.Append(\"string1\");\nsb.Append(\"string2\");\n...etc...\nString strResult = sb.ToString();\n" }, { "answer_id": 21093, "author": "TheEmirOfGroofunkistan", "author_id": 1874, "author_profile": "https://Stackoverflow.com/users/1874", "pm_score": 8, "selected": true, "text": "StringBuilder.Append() + String.Join() StringBuilder StringBuilder sb = new StringBuilder();\nsb.Append(someString);\n String.Join string.Empty string key = String.Join(\"_\", new String[] \n{ \"Customers_Contacts\", customerID, database, SessionID });\n" }, { "answer_id": 21113, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 6, "selected": false, "text": "StringBuilder @ StringBuilder" }, { "answer_id": 21118, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 4, "selected": false, "text": "StringBuilder String.Concat String.Format" }, { "answer_id": 21131, "author": "Lee", "author_id": 1954, "author_profile": "https://Stackoverflow.com/users/1954", "pm_score": 8, "selected": false, "text": "x = f1(...) + f2(...) + f3(...) + f4(...) if (...) x += f1(...) if (...) x += f2(...) if (...) x += f3(...) if (...) x += f4(...) +" }, { "answer_id": 12257751, "author": "Mr_Green", "author_id": 1577396, "author_profile": "https://Stackoverflow.com/users/1577396", "pm_score": 7, "selected": false, "text": "+ string.Concat() string.Join() string.Format() string.Append() StringBuilder string.Concat() StringBuilder" }, { "answer_id": 19365619, "author": "talles", "author_id": 1316620, "author_profile": "https://Stackoverflow.com/users/1316620", "pm_score": 3, "selected": false, "text": "+" }, { "answer_id": 34558305, "author": "Eduardo Mass", "author_id": 5696173, "author_profile": "https://Stackoverflow.com/users/5696173", "pm_score": 3, "selected": false, "text": " static void Main(string[] args)\n {\n StringBuilder s = new StringBuilder();\n for (int i = 0; i < 10000000; i++)\n {\n s.Append( i.ToString());\n }\n Console.Write(\"End\");\n Console.Read();\n }\n static void Main(string[] args)\n {\n string s = \"\";\n for (int i = 0; i < 10000000; i++)\n {\n s += i.ToString();\n }\n Console.Write(\"End\");\n Console.Read();\n }\n" }, { "answer_id": 43069670, "author": "RP Nainwal", "author_id": 1106356, "author_profile": "https://Stackoverflow.com/users/1106356", "pm_score": 3, "selected": false, "text": "String str1 = \"sometext\";\nstring str2 = \"some other text\";\n\nstring afterConcate = $\"{str1}{str2}\";\n" }, { "answer_id": 47231853, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 4, "selected": false, "text": "IEnumerable<T> Char String IEnumerable<T> ToString() String String /// <summary>\n/// Concatenate the strings in 'rg', none of which may be null, into a single String.\n/// </summary>\npublic static unsafe String StringJoin(this String[] rg)\n{\n int i;\n if (rg == null || (i = rg.Length) == 0)\n return String.Empty;\n\n if (i == 1)\n return rg[0];\n\n String s, t;\n int cch = 0;\n do\n cch += rg[--i].Length;\n while (i > 0);\n if (cch == 0)\n return String.Empty;\n\n i = rg.Length;\n fixed (Char* _p = (s = new String(default(Char), cch)))\n {\n Char* pDst = _p + cch;\n do\n if ((t = rg[--i]).Length > 0)\n fixed (Char* pSrc = t)\n memcpy(pDst -= t.Length, pSrc, (UIntPtr)(t.Length << 1));\n while (pDst > _p);\n }\n return s;\n}\n\n[DllImport(\"MSVCR120_CLR0400\", CallingConvention = CallingConvention.Cdecl)]\nstatic extern unsafe void* memcpy(void* dest, void* src, UIntPtr cb);\n memcpy" }, { "answer_id": 48340975, "author": "asady", "author_id": 9239715, "author_profile": "https://Stackoverflow.com/users/9239715", "pm_score": 2, "selected": false, "text": "List<string> lst= new List<string>();\n\nfor(int i=0; i<100000; i++){\n ...........\n lst.Add(...);\n}\nreturn String.Join(\"\", lst.ToArray());;\n" }, { "answer_id": 74502341, "author": "bertasoft", "author_id": 3917318, "author_profile": "https://Stackoverflow.com/users/3917318", "pm_score": 0, "selected": false, "text": " [MemoryDiagnoser]\npublic class StringConcatSimple\n{\n private string\n title = \"Mr.\", firstName = \"David\", middleName = \"Patrick\", lastName = \"Callan\";\n\n [Benchmark]\n public string FastConcat()\n {\n return FastConcat(\n title, \" \", \n firstName, \" \",\n middleName, \" \", \n lastName);\n }\n\n [Benchmark]\n public string StringBuilder()\n {\n var stringBuilder =\n new StringBuilder();\n\n return stringBuilder\n .Append(title).Append(' ')\n .Append(firstName).Append(' ')\n .Append(middleName).Append(' ')\n .Append(lastName).ToString();\n }\n\n [Benchmark]\n public string StringBuilderExact24()\n {\n var stringBuilder =\n new StringBuilder(24);\n\n return stringBuilder\n .Append(title).Append(' ')\n .Append(firstName).Append(' ')\n .Append(middleName).Append(' ')\n .Append(lastName).ToString();\n }\n\n [Benchmark]\n public string StringBuilderEstimate100()\n {\n var stringBuilder =\n new StringBuilder(100);\n\n return stringBuilder\n .Append(title).Append(' ')\n .Append(firstName).Append(' ')\n .Append(middleName).Append(' ')\n .Append(lastName).ToString();\n }\n\n [Benchmark]\n public string StringPlus()\n {\n return title + ' ' + firstName + ' ' +\n middleName + ' ' + lastName;\n }\n\n [Benchmark]\n public string StringFormat()\n {\n return string.Format(\"{0} {1} {2} {3}\",\n title, firstName, middleName, lastName);\n }\n\n [Benchmark]\n public string StringInterpolation()\n {\n return\n $\"{title} {firstName} {middleName} {lastName}\";\n }\n\n [Benchmark]\n public string StringJoin()\n {\n return string.Join(\" \", title, firstName,\n middleName, lastName);\n }\n\n [Benchmark]\n public string StringConcat()\n {\n return string.\n Concat(new String[]\n { title, \" \", firstName, \" \",\n middleName, \" \", lastName });\n }\n}\n public static unsafe string FastConcat(string str1, string str2, string str3, string str4, string str5, string str6, string str7)\n {\n var capacity = 0;\n\n var str1Length = 0;\n var str2Length = 0;\n var str3Length = 0;\n var str4Length = 0;\n var str5Length = 0;\n var str6Length = 0;\n var str7Length = 0;\n\n if (str1 != null)\n {\n str1Length = str1.Length;\n capacity = str1Length;\n }\n\n if (str2 != null)\n {\n str2Length = str2.Length;\n capacity += str2Length;\n }\n\n if (str3 != null)\n {\n str3Length = str3.Length;\n capacity += str3Length;\n }\n\n if (str4 != null)\n {\n str4Length = str4.Length;\n capacity += str4Length;\n }\n\n if (str5 != null)\n {\n str5Length = str5.Length;\n capacity += str5Length;\n }\n\n if (str6 != null)\n {\n str6Length = str6.Length;\n capacity += str6Length;\n }\n\n if (str7 != null)\n {\n str7Length = str7.Length;\n capacity += str7Length;\n }\n\n\n string result = new string(' ', capacity);\n\n fixed (char* dest = result)\n {\n var x = dest;\n\n if (str1Length > 0)\n {\n fixed (char* src = str1)\n {\n Unsafe.CopyBlock(x, src, (uint)str1Length * 2); \n x += str1Length;\n }\n }\n\n if (str2Length > 0)\n {\n fixed (char* src = str2)\n {\n Unsafe.CopyBlock(x, src, (uint)str2Length * 2);\n x += str2Length;\n }\n }\n\n if (str3Length > 0)\n {\n fixed (char* src = str3)\n {\n Unsafe.CopyBlock(x, src, (uint)str3Length * 2);\n x += str3Length;\n }\n }\n\n if (str4Length > 0)\n {\n fixed (char* src = str4)\n {\n Unsafe.CopyBlock(x, src, (uint)str4Length * 2);\n x += str4Length;\n }\n }\n\n if (str5Length > 0)\n {\n fixed (char* src = str5)\n {\n Unsafe.CopyBlock(x, src, (uint)str5Length * 2);\n x += str5Length;\n }\n }\n\n if (str6Length > 0)\n {\n fixed (char* src = str6)\n {\n Unsafe.CopyBlock(x, src, (uint)str6Length * 2);\n x += str6Length;\n }\n }\n\n if (str7Length > 0)\n {\n fixed (char* src = str7)\n {\n Unsafe.CopyBlock(x, src, (uint)str7Length * 2);\n }\n }\n }\n\n return result;\n }\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2358/" ]
21,091
<p>Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider.</p> <p>I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.).</p> <p>What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)?</p> <p><strong>Update:</strong> There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.</p>
[ { "answer_id": 320316, "author": "jbandi", "author_id": 32749, "author_profile": "https://Stackoverflow.com/users/32749", "pm_score": 3, "selected": false, "text": "class Firm < ActiveRecord::Base\n has_many :clients\n has_one :account\n belongs_to :conglomorate\nend\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1793/" ]
21,133
<p>What's the easiest way to profile a PHP script?</p> <p>I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.</p> <p>I tried experimenting with the <a href="http://php.net/microtime" rel="noreferrer">microtime</a> function:</p> <pre><code>$then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); </code></pre> <p>but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.</p>
[ { "answer_id": 21139, "author": "Eric Lamb", "author_id": 538, "author_profile": "https://Stackoverflow.com/users/538", "pm_score": 3, "selected": false, "text": "microtime() get_memory_usage() get_peak_memory_usage()" }, { "answer_id": 21189, "author": "Vincent", "author_id": 1508, "author_profile": "https://Stackoverflow.com/users/1508", "pm_score": 8, "selected": true, "text": "<?php\napd_set_pprof_trace();\n\n//rest of the script\n?>\n pprofp Trace for /home/dan/testapd.php\nTotal Elapsed Time = 0.00\nTotal System Time = 0.00\nTotal User Time = 0.00\n\n\nReal User System secs/ cumm\n%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name\n--------------------------------------------------------------------------------------\n100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main\n56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace\n28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace\n14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace\n" }, { "answer_id": 8807044, "author": "luka", "author_id": 494545, "author_profile": "https://Stackoverflow.com/users/494545", "pm_score": 5, "selected": false, "text": "true microtime(true) true" }, { "answer_id": 29022400, "author": "TimH - Codidact", "author_id": 382254, "author_profile": "https://Stackoverflow.com/users/382254", "pm_score": 7, "selected": false, "text": "// Call this at each point of interest, passing a descriptive string\nfunction prof_flag($str)\n{\n global $prof_timing, $prof_names;\n $prof_timing[] = microtime(true);\n $prof_names[] = $str;\n}\n\n// Call this when you're done and want to see the results\nfunction prof_print()\n{\n global $prof_timing, $prof_names;\n $size = count($prof_timing);\n for($i=0;$i<$size - 1; $i++)\n {\n echo \"<b>{$prof_names[$i]}</b><br>\";\n echo sprintf(\"&nbsp;&nbsp;&nbsp;%f<br>\", $prof_timing[$i+1]-$prof_timing[$i]);\n }\n echo \"<b>{$prof_names[$size-1]}</b><br>\";\n}\n prof_flag(\"Start\");\n\n include '../lib/database.php';\n include '../lib/helper_func.php';\n\nprof_flag(\"Connect to DB\");\n\n connect_to_db();\n\nprof_flag(\"Perform query\");\n\n // Get all the data\n\n $select_query = \"SELECT * FROM data_table\";\n $result = mysql_query($select_query);\n\nprof_flag(\"Retrieve data\");\n\n $rows = array();\n $found_data=false;\n while($r = mysql_fetch_assoc($result))\n {\n $found_data=true;\n $rows[] = $r;\n }\n\nprof_flag(\"Close DB\");\n\n mysql_close(); //close database connection\n\nprof_flag(\"Done\");\nprof_print();\n" }, { "answer_id": 39378588, "author": "bishop", "author_id": 2908724, "author_profile": "https://Stackoverflow.com/users/2908724", "pm_score": 4, "selected": false, "text": "function p_open($flag) {\n global $p_times;\n if (null === $p_times)\n $p_times = [];\n if (! array_key_exists($flag, $p_times))\n $p_times[$flag] = [ 'total' => 0, 'open' => 0 ];\n $p_times[$flag]['open'] = microtime(true);\n}\n\nfunction p_close($flag)\n{\n global $p_times;\n if (isset($p_times[$flag]['open'])) {\n $p_times[$flag]['total'] += (microtime(true) - $p_times[$flag]['open']);\n unset($p_times[$flag]['open']);\n }\n}\n\nfunction p_dump()\n{\n global $p_times;\n $dump = [];\n $sum = 0;\n foreach ($p_times as $flag => $info) {\n $dump[$flag]['elapsed'] = $info['total'];\n $sum += $info['total'];\n }\n foreach ($dump as $flag => $info) {\n $dump[$flag]['percent'] = $dump[$flag]['elapsed']/$sum;\n }\n return $dump;\n}\n <?php\n\np_open('foo');\nsleep(1);\np_open('bar');\nsleep(2);\np_open('baz');\nsleep(3);\np_close('baz');\nsleep(2);\np_close('bar');\nsleep(1);\np_close('foo');\n\nvar_dump(p_dump());\n array:3 [\n \"foo\" => array:2 [\n \"elapsed\" => 9.000766992569\n \"percent\" => 0.4736904954747\n ]\n \"bar\" => array:2 [\n \"elapsed\" => 7.0004580020905\n \"percent\" => 0.36841864946596\n ]\n \"baz\" => array:2 [\n \"elapsed\" => 3.0001420974731\n \"percent\" => 0.15789085505934\n ]\n]\n" }, { "answer_id": 45512462, "author": "Matt S", "author_id": 163024, "author_profile": "https://Stackoverflow.com/users/163024", "pm_score": 6, "selected": false, "text": "php-xdebug # php.ini settings\n# Set to 1 to turn it on for every request\nxdebug.profiler_enable = 0\n# Let's use a GET/POST parameter to turn on the profiler\nxdebug.profiler_enable_trigger = 1\n# The GET/POST value we will pass; empty for any value\nxdebug.profiler_enable_trigger_value = \"\"\n# Output cachegrind files to /tmp so our system cleans them up later\nxdebug.profiler_output_dir = \"/tmp\"\nxdebug.profiler_output_name = \"cachegrind.out.%p\"\n http://example.com/article/1?XDEBUG_PROFILE=1\n /tmp/cachegrind.out.12345\n xdebug.profiler_output_name" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
21,184
<p>I've got a System.Generic.Collections.List(Of MyCustomClass) type object.</p> <p>Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?</p>
[ { "answer_id": 21389, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 6, "selected": true, "text": "var pageNum = 3;\nvar pageSize = 20;\nquery = query.Skip((pageNum - 1) * pageSize).Take(pageSize);\n query.Page(2,50)\n" }, { "answer_id": 442698, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 3, "selected": false, "text": "var query = from item in DB.Table\nwhere item.Field == 1\norderby item.Field2\nselect item;\n\nPagedList<MyType> pagedList = query.ToPagedList(pageIndex, pageSize);\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
21,207
<p>I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o? </p>
[ { "answer_id": 24499, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 7, "selected": true, "text": "// C# syntax for \"Find all MyFoos with Bar == 23\".\n// (Note the Java syntax is more verbose using the Predicate class.)\nIList<MyFoo> results = db4o.Query<MyFoo>(input => input.Bar == 23);\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562/" ]
21,232
<p>I've got a System.Generic.Collections.List(Of MyCustomClass) type object.</p> <p>Given integer varaibles pagesize and pagenumber, how can I collect only any single page of <code>MyCustomClass</code> objects?</p> <p>This is what I've got. How can I improve it?</p> <pre><code>'my given collection and paging parameters Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN Dim pagesize As Integer = GIVEN Dim pagenumber As Integer = GIVEN 'collect current page objects Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass) Dim objcount As Integer = 1 For Each obj As MyCustomClass In AllOfMyCustomClassObjects If objcount &gt; pagesize * (pagenumber - 1) And count &lt;= pagesize * pagenumber Then PageObjects.Add(obj) End If objcount = objcount + 1 Next 'find total page count Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize)) If objcount Mod pagesize &gt; 0 Then totalpages = totalpages + 1 End If </code></pre>
[ { "answer_id": 21267, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "List<int> lolInts = new List<int>();\n\nfor (int i = 0; i <= 100; i++)\n{\n lolInts.Add(i);\n}\n\nList<int> page1 = lolInts.GetRange(0, 49);\nList<int> page2 = lilInts.GetRange(50, 100);\n" }, { "answer_id": 21268, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 2, "selected": false, "text": "Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)\nPageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize)\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
21,265
<p>What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.</p>
[ { "answer_id": 21277, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 4, "selected": true, "text": "bool is_nan(float f)\n{\n return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<unsigned __int32*>(&f) & 0x007fffff) != 0;\n}\n\nbool is_finite(float f)\n{\n return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) != 0x7f800000;\n}\n\n// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)\n// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other\n#define UNEQUAL_NANS 1\n// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)\n// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX\n#define INFINITE_INFINITIES 1\n\n// test whether two IEEE floats are within a specified number of representable values of each other\n// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers\nbool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)\n{\n#ifdef UNEQUAL_NANS\n if(is_nan(lhs) || is_nan(rhs))\n {\n return false;\n }\n#endif\n#ifdef INFINITE_INFINITIES\n if((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs)))\n {\n return false;\n }\n#endif\n signed __int32 left(*reinterpret_cast<signed __int32*>(&lhs));\n // transform signed magnitude ints into 2s complement signed ints\n if(left < 0)\n {\n left = 0x80000000 - left;\n }\n signed __int32 right(*reinterpret_cast<signed __int32*>(&rhs));\n // transform signed magnitude ints into 2s complement signed ints\n if(right < 0)\n {\n right = 0x80000000 - right;\n }\n if(static_cast<unsigned __int32>(std::abs(left - right)) <= max_ulp_difference)\n {\n return true;\n }\n return false;\n}\n" }, { "answer_id": 21298, "author": "Craig H", "author_id": 2328, "author_profile": "https://Stackoverflow.com/users/2328", "pm_score": 2, "selected": false, "text": "bool is_equals(float A, float B,\n float maxRelativeError, float maxAbsoluteError)\n{\n\n if (fabs(A - B) < maxAbsoluteError)\n return true;\n\n float relativeError;\n if (fabs(B) > fabs(A))\n relativeError = fabs((A - B) / B);\n else\n relativeError = fabs((A - B) / A);\n\n if (relativeError <= maxRelativeError)\n return true;\n\n return false;\n}\n" }, { "answer_id": 21337, "author": "Craig H", "author_id": 2328, "author_profile": "https://Stackoverflow.com/users/2328", "pm_score": 0, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\n\nint main()\n{\n float a = 1.0;\n float b = 0.0;\n\n for(int i=0;i<10;++i)\n {\n b+=0.1;\n }\n\n if(a != b)\n {\n cout << \"Something is wrong\" << endl;\n }\n\n return 1;\n}\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
21,280
<p>I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.</p> <p>I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?</p>
[ { "answer_id": 21292, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "foreach (int number in list1)\n{\n foreach (int number2 in list2)\n {\n if (number2 == number)\n {\n returnList.add(number2);\n }\n }\n}\n var results = list1.Intersect(list2);\n" }, { "answer_id": 21418, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "int[] data = { 0, 1, 3, 3, 7, 8, 0, 9, 2, 1 };\n\nvar uniqueData = data.GroupBy(i => i).Select(g => g.Key);\n" }, { "answer_id": 80709, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 4, "selected": false, "text": "// Init Movie\nm_ImageArray = new Image[K_NB_IMAGE];\n\nStream l_ImageStream = null;\nBitmap l_Bitmap = null;\n\n// get a reference to the current assembly\nAssembly l_Assembly = Assembly.GetExecutingAssembly();\n\n// get a list of resource names from the manifest\nstring[] l_ResourceName = l_Assembly.GetManifestResourceNames();\n\nforeach (string l_Str in l_ResourceName)\n{\n if (l_Str.EndsWith(\".png\"))\n {\n // attach to stream to the resource in the manifest\n l_ImageStream = l_Assembly.GetManifestResourceStream(l_Str);\n if (!(null == l_ImageStream))\n {\n // create a new bitmap from this stream and \n // add it to the arraylist\n l_Bitmap = Bitmap.FromStream(l_ImageStream) as Bitmap;\n if (!(null == l_Bitmap))\n {\n int l_Index = Convert.ToInt32(l_Str.Substring(l_Str.Length - 6, 2));\n l_Index -= 1;\n if (l_Index < 0) l_Index = 0;\n if (l_Index > K_NB_IMAGE) l_Index = K_NB_IMAGE;\n m_ImageArray[l_Index] = l_Bitmap;\n }\n l_Bitmap = null;\n l_ImageStream.Close();\n l_ImageStream = null;\n } // if\n } // if\n} // foreach\n Assembly l_Assembly = Assembly.GetExecutingAssembly();\n\n//Linq is the tops\nm_ImageList = l_Assembly.GetManifestResourceNames()\n .Where(a => a.EndsWith(\".png\"))\n .OrderBy(b => b)\n .Select(c => l_Assembly.GetManifestResourceStream(c))\n .Where(d => d != null) //ImageStream not null\n .Select(e => Bitmap.FromStream(e))\n .Where(f => f != null) //Bitmap not null\n .ToList();\n Assembly l_Assembly = Assembly.GetExecutingAssembly();\n\n//Linq is the tops\nm_ImageList = (\n from resource in l_Assembly.GetManifestResourceNames()\n where resource.EndsWith(\".png\")\n orderby resource\n let imageStream = l_Assembly.GetManifestResourceStream(resource)\n where imageStream != null\n let bitmap = Bitmap.FromStream(imageStream)\n where bitmap != null)\n .ToList();\n" }, { "answer_id": 641324, "author": "Jacob Stanley", "author_id": 72821, "author_profile": "https://Stackoverflow.com/users/72821", "pm_score": 2, "selected": false, "text": " var requests = new[] \n {\n WebRequest.Create(\"http://www.google.com/\"),\n WebRequest.Create(\"http://www.yahoo.com/\"),\n WebRequest.Create(\"http://channel9.msdn.com/\")\n };\n\n var pages = from request in requests\n select\n from response in request.GetResponseAsync()\n let stream = response.GetResponseStream()\n from html in stream.ReadToEndAsync()\n select new { html, response };\n\n foreach (var page in pages)\n {\n page(d =>\n {\n Console.WriteLine(d.response.ResponseUri.ToString());\n Console.WriteLine(d.html.Substring(0, 40));\n Console.WriteLine();\n });\n }\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
21,288
<p>Which C#/.NET Dependency Injection frameworks are worth looking into? And what can you say about their complexity and speed.</p>
[ { "answer_id": 227012, "author": "Glenn Block", "author_id": 18419, "author_profile": "https://Stackoverflow.com/users/18419", "pm_score": 6, "selected": false, "text": "Spring.NET Castle Windsor Structure Map Autofac Ninject Unity" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2011/" ]
21,294
<p>How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.</p> <p>The client that uses the component isn't required to load all the library script files (and manually insert <code>&lt;script&gt;</code> tags into their web page) that implement this component - just the 'main' component script file.</p> <p><strong>How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?</strong> Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?</p> <p>An addition to this question: <strong>is there a way to handle the event after a dynamically included JavaScript file is loaded?</strong> Prototype has <code>document.observe</code> for document-wide events. Example:</p> <pre><code>document.observe("dom:loaded", function() { // initially hide all containers for tab content $$('div.tabcontent').invoke('hide'); }); </code></pre> <p><strong>What are the available events for a script element?</strong></p>
[ { "answer_id": 21297, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 3, "selected": false, "text": " function include(url)\n {\n var s = document.createElement(\"script\");\n s.setAttribute(\"type\", \"text/javascript\");\n s.setAttribute(\"src\", url);\n var nodes = document.getElementsByTagName(\"*\");\n var node = nodes[nodes.length -1].parentNode;\n node.appendChild(s);\n }\n" }, { "answer_id": 21300, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "var loader = new YAHOO.util.YUILoader({\n\n require: ['calendar'], // what components?\n\n base: '../../build/',//where do they live?\n\n //filter: \"DEBUG\", //use debug versions (or apply some\n //some other filter?\n\n //loadOptional: true, //load all optional dependencies?\n\n //onSuccess is the function that YUI Loader\n //should call when all components are successfully loaded.\n onSuccess: function() {\n //Once the YUI Calendar Control and dependencies are on\n //the page, we'll verify that our target container is \n //available in the DOM and then instantiate a default\n //calendar into it:\n YAHOO.util.Event.onAvailable(\"calendar_container\", function() {\n var myCal = new YAHOO.widget.Calendar(\"mycal_id\", \"calendar_container\");\n myCal.render();\n })\n },\n\n // should a failure occur, the onFailure function will be executed\n onFailure: function(o) {\n alert(\"error: \" + YAHOO.lang.dump(o));\n }\n\n });\n\n// Calculate the dependency and insert the required scripts and css resources\n// into the document\nloader.insert();\n" }, { "answer_id": 21311, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 4, "selected": false, "text": "head include function include( url, type ){\n // First make sure it hasn't been loaded by something else.\n if( Array.contains( includedFile, url ) )\n return;\n \n // Determine the MIME type.\n var jsExpr = new RegExp( \"js$\", \"i\" );\n var cssExpr = new RegExp( \"css$\", \"i\" );\n if( type == null )\n if( jsExpr.test( url ) )\n type = 'text/javascript';\n else if( cssExpr.test( url ) )\n type = 'text/css';\n \n // Create the appropriate element.\n var element = null;\n switch( type ){\n case 'text/javascript' :\n element = document.createElement( 'script' );\n element.type = type;\n element.src = url;\n break;\n case 'text/css' :\n element = document.createElement( 'link' );\n element.rel = 'stylesheet';\n element.type = type;\n element.href = url;\n break;\n }\n \n // Insert it to the <head> and the array to ensure it is not\n // loaded again.\n document.getElementsByTagName(\"head\")[0].appendChild( element );\n Array.add( includedFile, url );\n}\n" }, { "answer_id": 21320, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 2, "selected": false, "text": "function include(url) {\n var s = document.createElement(\"script\");\n s.setAttribute(\"type\", \"text/javascript\");\n s.setAttribute(\"src\", url);\n document.body.appendChild(s);\n}\n" }, { "answer_id": 24313, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 5, "selected": false, "text": "<script src=\"scripts/jquery.js\"></script>\n<script>\n var js = [\"scripts/jquery.dimensions.js\", \"scripts/shadedborder.js\", \"scripts/jqmodal.js\", \"scripts/main.js\"];\n var $head = $(\"head\");\n for (var i = 0; i < js.length; i++) {\n $head.append(\"<script src=\\\"\" + js[i] + \"\\\"></scr\" + \"ipt>\");\n }\n</script>\n <script>\n var js = [\"scripts/jquery.dimensions.js\", \"scripts/shadedborder.js\", \"scripts/jqmodal.js\", \"scripts/main.js\"];\n for (var i = 0, l = js.length; i < l; i++) {\n document.getElementsByTagName(\"head\")[0].innerHTML += (\"<script src=\\\"\" + js[i] + \"\\\"></scr\" + \"ipt>\");\n }\n</script>\n" }, { "answer_id": 28249, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 2, "selected": false, "text": "/** include - including .js files from JS - [email protected] - 2005-02-09\n ** Code licensed under Creative Commons Attribution-ShareAlike License \n ** http://creativecommons.org/licenses/by-sa/2.0/\n **/ \nvar hIncludes = null;\nfunction include(sURI)\n{ \n if (document.getElementsByTagName)\n { \n if (!hIncludes)\n {\n hIncludes = {}; \n var cScripts = document.getElementsByTagName(\"script\");\n for (var i=0,len=cScripts.length; i < len; i++)\n if (cScripts[i].src) hIncludes[cScripts[i].src] = true;\n }\n if (!hIncludes[sURI])\n {\n var oNew = document.createElement(\"script\");\n oNew.type = \"text/javascript\";\n oNew.src = sURI;\n hIncludes[sURI]=true;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n }\n } \n} \n" }, { "answer_id": 242607, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 7, "selected": true, "text": "new Element(\"script\", {src: \"myBigCodeLibrary.js\", type: \"text/javascript\"});\n if (iNeedSomeMore) {\n Script.load(\"myBigCodeLibrary.js\"); // includes code for myFancyMethod();\n myFancyMethod(); // cool, no need for callbacks!\n}\n var Script = {\n _loadedScripts: [],\n include: function(script) {\n // include script only once\n if (this._loadedScripts.include(script)) {\n return false;\n }\n // request file synchronous\n var code = new Ajax.Request(script, {\n asynchronous: false,\n method: \"GET\",\n evalJS: false,\n evalJSON: false\n }).transport.responseText;\n // eval code on global level\n if (Prototype.Browser.IE) {\n window.execScript(code);\n } else if (Prototype.Browser.WebKit) {\n $$(\"head\").first().insert(Object.extend(\n new Element(\"script\", {\n type: \"text/javascript\"\n }), {\n text: code\n }\n ));\n } else {\n window.eval(code);\n }\n // remember included script\n this._loadedScripts.push(script);\n }\n};\n" }, { "answer_id": 684047, "author": "Kariem", "author_id": 12039, "author_profile": "https://Stackoverflow.com/users/12039", "pm_score": 2, "selected": false, "text": "YUI({\n modules: {\n 'simple': {\n fullpath: \"http://example.com/public/js/simple.js\"\n },\n 'complicated': {\n fullpath: \"http://example.com/public/js/complicated.js\"\n requires: ['simple'] // <-- dependency to 'simple' module\n }\n },\n timeout: 10000\n}).use('complicated', function(Y, result) {\n // called as soon as 'complicated' is loaded\n if (!result.success) {\n // loading failed, or timeout\n handleError(result.msg);\n } else {\n // call a function that needs 'complicated'\n doSomethingComplicated(...);\n }\n});\n" }, { "answer_id": 4689568, "author": "JM Design", "author_id": 572322, "author_profile": "https://Stackoverflow.com/users/572322", "pm_score": 2, "selected": false, "text": "/*\n * FILENAME : project.library.js\n * USAGE : loads any javascript library\n */\n var dirPath = \"../js/\";\n var library = [\"functions.js\",\"swfobject.js\",\"jquery.jeditable.mini.js\",\"jquery-ui-1.8.8.custom.min.js\",\"ui/jquery.ui.core.min.js\",\"ui/jquery.ui.widget.min.js\",\"ui/jquery.ui.position.min.js\",\"ui/jquery.ui.button.min.js\",\"ui/jquery.ui.mouse.min.js\",\"ui/jquery.ui.dialog.min.js\",\"ui/jquery.effects.core.min.js\",\"ui/jquery.effects.blind.min.js\",\"ui/jquery.effects.fade.min.js\",\"ui/jquery.effects.slide.min.js\",\"ui/jquery.effects.transfer.min.js\"];\n\n for(var script in library){\n $('head').append('<script type=\"text/javascript\" src=\"' + dirPath + library[script] + '\"></script>');\n }\n <script type=\"text/javascript\" src=\"project.library.js\"></script>\n" }, { "answer_id": 10013923, "author": "Naveed", "author_id": 671046, "author_profile": "https://Stackoverflow.com/users/671046", "pm_score": 4, "selected": false, "text": "$.getScript(\"my_lovely_script.js\", function(){\n\n\n alert(\"Script loaded and executed.\");\n // here you can use anything you defined in the loaded script\n\n });\n" }, { "answer_id": 14786759, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "script head body var js = document.createElement(\"script\");\n\njs.type = \"text/javascript\";\njs.src = jsFilePath;\n\ndocument.body.appendChild(js);\n\nvar s = new MySuperObject();\n\nError : MySuperObject is undefined\n function loadScript(url, callback)\n{\n // adding the script element to the head as suggested before\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = url;\n\n // then bind the event to the callback function \n // there are several events for cross browser compatibility\n script.onreadystatechange = callback;\n script.onload = callback;\n\n // fire the loading\n head.appendChild(script);\n}\n var myPrettyCode = function() {\n // here, do what ever you want\n};\n loadScript(\"my_lovely_script.js\", myPrettyCode);\n $.getScript(\"my_lovely_script.js\", function() {\n alert(\"Script loaded and executed.\");\n // here you can use anything you defined in the loaded script\n});\n" }, { "answer_id": 15976901, "author": "stamat", "author_id": 1909864, "author_profile": "https://Stackoverflow.com/users/1909864", "pm_score": 1, "selected": false, "text": "var _rmod = _rmod || {}; //require module namespace\n_rmod.on_ready_fn_stack = [];\n_rmod.libpath = '';\n_rmod.imported = {};\n_rmod.loading = {\n scripts: {},\n length: 0\n};\n\n_rmod.findScriptPath = function(script_name) {\n var script_elems = document.getElementsByTagName('script');\n for (var i = 0; i < script_elems.length; i++) {\n if (script_elems[i].src.endsWith(script_name)) {\n var href = window.location.href;\n href = href.substring(0, href.lastIndexOf('/'));\n var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);\n return url.substring(href.length+1, url.length);\n }\n }\n return '';\n};\n\n_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library\n\n\n_rmod.injectScript = function(script_name, uri, callback, prepare) {\n\n if(!prepare)\n prepare(script_name, uri);\n\n var script_elem = document.createElement('script');\n script_elem.type = 'text/javascript';\n script_elem.title = script_name;\n script_elem.src = uri;\n script_elem.async = true;\n script_elem.defer = false;\n\n if(!callback)\n script_elem.onload = function() {\n callback(script_name, uri);\n };\n\n document.getElementsByTagName('head')[0].appendChild(script_elem);\n};\n\n_rmod.requirePrepare = function(script_name, uri) {\n _rmod.loading.scripts[script_name] = uri;\n _rmod.loading.length++;\n};\n\n_rmod.requireCallback = function(script_name, uri) {\n _rmod.loading.length--;\n delete _rmod.loading.scripts[script_name];\n _rmod.imported[script_name] = uri;\n\n if(_rmod.loading.length == 0)\n _rmod.onReady();\n};\n\n_rmod.onReady = function() {\n if (!_rmod.LOADED) {\n for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){\n _rmod.on_ready_fn_stack[i]();\n });\n _rmod.LOADED = true;\n }\n};\n\n//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.\nvar require = function(script_name) {\n var np = script_name.split('.');\n if (np[np.length-1] === '*') {\n np.pop();\n np.push('_all');\n }\n\n script_name = np.join('.');\n var uri = _rmod.libpath + np.join('/')+'.js';\n if (!_rmod.loading.scripts.hasOwnProperty(script_name) \n && !_rmod.imported.hasOwnProperty(script_name)) {\n _rmod.injectScript(script_name, uri, \n _rmod.requireCallback, \n _rmod.requirePrepare);\n }\n};\n\nvar ready = function(fn) {\n _rmod.on_ready_fn_stack.push(fn);\n};\n\n// ----- USAGE -----\n\nrequire('ivar.util.array');\nrequire('ivar.util.string');\nrequire('ivar.net.*');\n\nready(function(){\n //do something when required scripts are loaded\n});\n" }, { "answer_id": 16955574, "author": "Sielu", "author_id": 1250626, "author_profile": "https://Stackoverflow.com/users/1250626", "pm_score": 2, "selected": false, "text": "/*sample requires an additional method for array prototype:*/\n\nif (Array.prototype.contains === undefined) {\nArray.prototype.contains = function (obj) {\n var i = this.length;\n while (i--) { if (this[i] === obj) return true; }\n return false;\n};\n};\n\n/*define object that will wrap our logic*/\nvar ScriptLoader = {\nLoadedFiles: [],\n\nLoadFile: function (url) {\n var self = this;\n if (this.LoadedFiles.contains(url)) return;\n\n var xhr = new XMLHttpRequest();\n xhr.onload = function () {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n self.LoadedFiles.push(url);\n self.AddScript(xhr.responseText);\n } else {\n if (console) console.error(xhr.statusText);\n }\n }\n };\n xhr.open(\"GET\", url, false);/*last parameter defines if call is async or not*/\n xhr.send(null);\n},\n\nAddScript: function (code) {\n var oNew = document.createElement(\"script\");\n oNew.type = \"text/javascript\";\n oNew.textContent = code;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n}\n};\n\n/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/\n\nScriptLoader.LoadFile(\"Scripts/jquery-2.0.1.min.js\");\nScriptLoader.LoadFile(\"Scripts/jquery-2.0.1.min.js\");\n/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id \"tb1\"*/\n$(function () { alert($('#tb1').val()); });\n" }, { "answer_id": 28389499, "author": "tfont", "author_id": 1804013, "author_profile": "https://Stackoverflow.com/users/1804013", "pm_score": 2, "selected": false, "text": "// 3rd party plugins / script (don't forget the full path is necessary)\nvar FULL_PATH = '', s =\n[\n FULL_PATH + 'plugins/script.js' // Script example\n FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library \n FULL_PATH + 'plugins/crypto-js/hmac-sha1.js', // CryptoJS\n FULL_PATH + 'plugins/crypto-js/enc-base64-min.js' // CryptoJS\n];\n\nfunction load(url)\n{\n var ajax = new XMLHttpRequest();\n ajax.open('GET', url, false);\n ajax.onreadystatechange = function ()\n {\n var script = ajax.response || ajax.responseText;\n if (ajax.readyState === 4)\n {\n switch(ajax.status)\n {\n case 200:\n eval.apply( window, [script] );\n console.log(\"library loaded: \", url);\n break;\n default:\n console.log(\"ERROR: library not loaded: \", url);\n }\n }\n };\n ajax.send(null);\n}\n\n // initialize a single load \nload('plugins/script.js');\n\n// initialize a full load of scripts\nif (s.length > 0)\n{\n for (i = 0; i < s.length; i++)\n {\n load(s[i]);\n }\n}\n" }, { "answer_id": 35793206, "author": "adrianTNT", "author_id": 928532, "author_profile": "https://Stackoverflow.com/users/928532", "pm_score": 1, "selected": false, "text": "document.write(\"<script src='https://www.google.com/recaptcha/api.js'></script>\");\n" }, { "answer_id": 42667747, "author": "Jacob", "author_id": 665783, "author_profile": "https://Stackoverflow.com/users/665783", "pm_score": 1, "selected": false, "text": "function loadScript(url, callback) {\n\n var script = document.createElement(\"script\")\n script.type = \"text/javascript\";\n\n if (script.readyState) { //IE\n script.onreadystatechange = function () {\n if (script.readyState == \"loaded\" || script.readyState == \"complete\") {\n script.onreadystatechange = null;\n callback();\n }\n };\n } else { //Others\n script.onload = function () {\n callback();\n };\n }\n\n script.src = url;\n document.getElementsByTagName(\"head\")[0].appendChild(script);\n}\n\nloadScript(\"https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\", function () {\n\n //jQuery loaded\n console.log('jquery loaded');\n\n});\n" }, { "answer_id": 45488894, "author": "asmmahmud", "author_id": 1576255, "author_profile": "https://Stackoverflow.com/users/1576255", "pm_score": 2, "selected": false, "text": "script1.js, script2.js, script3.js, script4.js [\n 'script1.js',\n 'script2.js',\n 'script3.js',\n 'script4.js'\n].forEach(function(src) {\n var script = document.createElement('script');\n script.src = src;\n script.async = false;\n document.head.appendChild(script);\n});\n var scripts = [\n 'script1.js',\n 'script2.js',\n 'script3.js',\n 'script4.js'\n];\nvar src;\nvar script;\nvar pendingScripts = [];\nvar firstScript = document.scripts[0];\n\n// Watch scripts load in IE\nfunction stateChange() {\n // Execute as many scripts in order as we can\n var pendingScript;\n while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {\n pendingScript = pendingScripts.shift();\n // avoid future loading events from this script (eg, if src changes)\n pendingScript.onreadystatechange = null;\n // can't just appendChild, old IE bug if element isn't closed\n firstScript.parentNode.insertBefore(pendingScript, firstScript);\n }\n}\n\n// loop through our script urls\nwhile (src = scripts.shift()) {\n if ('async' in firstScript) { // modern browsers\n script = document.createElement('script');\n script.async = false;\n script.src = src;\n document.head.appendChild(script);\n }\n else if (firstScript.readyState) { // IE<10\n // create a script and add it to our todo pile\n script = document.createElement('script');\n pendingScripts.push(script);\n // listen for state changes\n script.onreadystatechange = stateChange;\n // must set src AFTER adding onreadystatechange listener\n // else we’ll miss the loaded event for cached scripts\n script.src = src;\n }\n else { // fall back to defer\n document.write('<script src=\"' + src + '\" defer></'+'script>');\n }\n}\n !function(e,t,r){function n(){for(;d[0]&&\"loaded\"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o=\"onreadystatechange\",f=\"readyState\";s=r.shift();)a=e.createElement(t),\"async\"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write(\"<\"+t+' src=\"'+s+'\" defer></'+t+\">\"),a.src=s}(document,\"script\",[\n \"//other-domain.com/1.js\",\n \"2.js\"\n])\n" }, { "answer_id": 49889707, "author": "James Arnold", "author_id": 2558016, "author_profile": "https://Stackoverflow.com/users/2558016", "pm_score": 2, "selected": false, "text": "<script>\n $(document).ready(function() {\n $('body').append('<script src=\"https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=getCurrentPickupLocation\" async defer><\\/script>');\n });\n</script>\n" }, { "answer_id": 50051689, "author": "João Pimentel Ferreira", "author_id": 1243247, "author_profile": "https://Stackoverflow.com/users/1243247", "pm_score": 1, "selected": false, "text": "$.ajax $.getScript unsafe-inline script.nonce var getScriptOnce = function() {\n\n var scriptArray = []; //array of urls (closure)\n\n //function to defer loading of script\n return function (url, callback){\n //the array doesn't have such url\n if (scriptArray.indexOf(url) === -1){\n\n var script=document.createElement('script');\n script.src=url;\n var head=document.getElementsByTagName('head')[0],\n done=false;\n\n script.onload=script.onreadystatechange = function(){\n if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {\n done=true;\n if (typeof callback === 'function') {\n callback();\n }\n script.onload = script.onreadystatechange = null;\n head.removeChild(script);\n\n scriptArray.push(url);\n }\n };\n\n head.appendChild(script);\n }\n };\n}();\n getScriptOnce(\"url_of_your_JS_file.js\");\n" }, { "answer_id": 51378436, "author": "Alister", "author_id": 1432509, "author_profile": "https://Stackoverflow.com/users/1432509", "pm_score": 2, "selected": false, "text": "const moduleSpecifier = './dir/someModule.js';\n\nimport(moduleSpecifier)\n .then(someModule => someModule.foo()); // executes foo method in someModule\n" }, { "answer_id": 52365356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "await new Promise((resolve, reject) => {let js = document.createElement(\"script\"); js.src=\"mylibrary.js\"; js.onload=resolve; js.onerror=reject; document.body.appendChild(js)});\n import(...)" }, { "answer_id": 57367916, "author": "NVRM", "author_id": 2494754, "author_profile": "https://Stackoverflow.com/users/2494754", "pm_score": 3, "selected": false, "text": "(async () => {\n await import('./synth/BubbleSynth.js')\n})()\n (async () => {\n await import('./synth/BubbleSynth.js').catch((error) => console.log('Loading failed' + error))\n})()\n window.self (async () => {\n await import('https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.8.0/suncalc.min.js')\n .then( () => {\n let times = SunCalc.getTimes(new Date(), 51.5,-0.1);\n console.log(\"Golden Hour today in London: \" + times.goldenHour.getHours() + ':' + times.goldenHour.getMinutes() + \". Take your pics!\")\n })\n})()" }, { "answer_id": 59012155, "author": "VG P", "author_id": 3936513, "author_profile": "https://Stackoverflow.com/users/3936513", "pm_score": 0, "selected": false, "text": "$(document).ready(function(){\n\nif (Array.prototype.contains === undefined) {\nArray.prototype.contains = function (obj) {\n var i = this.length;\n while (i--) { if (this[i] === obj) return true; }\n return false;\n};\n};\n\n/* define object that will wrap our logic */\nvar jsScriptCssLoader = {\n\njsExpr : new RegExp( \"js$\", \"i\" ),\ncssExpr : new RegExp( \"css$\", \"i\" ),\nloadedFiles: [],\n\nloadFile: function (cssJsFileArray) {\n var self = this;\n // remove duplicates with in array\n cssJsFileArray.filter((item,index)=>cssJsFileArray.indexOf(item)==index)\n var loadedFileArray = this.loadedFiles;\n $.each(cssJsFileArray, function( index, url ) {\n // if multiple arrays are loaded the check the uniqueness\n if (loadedFileArray.contains(url)) return;\n if( self.jsExpr.test( url ) ){\n $.get(url, function(data) {\n self.addScript(data);\n });\n\n }else if( self.cssExpr.test( url ) ){\n $.get(url, function(data) {\n self.addCss(data);\n });\n }\n\n self.loadedFiles.push(url);\n });\n\n // don't load twice accross different arrays\n\n},\naddScript: function (code) {\n var oNew = document.createElement(\"script\");\n oNew.type = \"text/javascript\";\n oNew.textContent = code;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n},\naddCss: function (code) {\n var oNew = document.createElement(\"style\");\n oNew.textContent = code;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n}\n\n};\n\n\n//jsScriptCssLoader.loadFile([\"css/1.css\",\"css/2.css\",\"css/3.css\"]);\njsScriptCssLoader.loadFile([\"js/common/1.js\",\"js/2.js\",\"js/common/file/fileReader.js\"]);\n});\n" }, { "answer_id": 59612206, "author": "radulle", "author_id": 3008018, "author_profile": "https://Stackoverflow.com/users/3008018", "pm_score": 2, "selected": false, "text": " const loadCDN = src =>\n new Promise((resolve, reject) => {\n if (document.querySelector(`head > script[src=\"${src}\"]`) !== null) return resolve()\n const script = document.createElement(\"script\")\n script.src = src\n script.async = true\n document.head.appendChild(script)\n script.onload = resolve\n script.onerror = reject\n })\n await loadCDN(\"https://.../script.js\")\n loadCDN(\"https://.../script.js\").then(res => {}).catch(err => {})\n" }, { "answer_id": 60248096, "author": "Ludmil Tinkov", "author_id": 519553, "author_profile": "https://Stackoverflow.com/users/519553", "pm_score": 1, "selected": false, "text": "import('./myscript.js');\n fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());\n" }, { "answer_id": 67646541, "author": "Enrico", "author_id": 7116948, "author_profile": "https://Stackoverflow.com/users/7116948", "pm_score": 1, "selected": false, "text": "//Create a script element that will load\nlet dynamicScript = document.createElement('script');\n\n//Set source to the script we need to load\ndynamicScript.src = 'linkToNeededJsFile.js';\n\n//Set onload to callback function that depends on this script or do inline as shown below\ndynamicScript.onload = () => {\n\n //Code that depends on the loaded script should be here\n\n};\n\n//append the created script element to body element\ndocument.body.append(dynamicScript);\n $.getScript('linkToNeededJsFile.js', () => {\n\n //Code that depends on the loaded script should be here\n\n});\n" }, { "answer_id": 72079575, "author": "vatavale", "author_id": 1056384, "author_profile": "https://Stackoverflow.com/users/1056384", "pm_score": 1, "selected": false, "text": "const loadScript = function () {\n let cache = {};\n return function (src) {\n return cache[src] || (cache[src] = new Promise((resolve, reject) => {\n let s = document.createElement('script');\n s.defer = true;\n s.src = src;\n s.onload = resolve;\n s.onerror = reject;\n document.head.append(s);\n }));\n }\n}();\n Promise.all([\n loadScript('/script1.js'),\n loadScript('/script2.js'),\n // ...\n]).then(() => {\n // do something\n})\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
21,303
<p>VC++ makes functions which are implemented within the class declaration inline functions.</p> <p>If I declare a class <code>Foo</code> as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?</p> <pre><code>class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } </code></pre>
[ { "answer_id": 21326, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 5, "selected": false, "text": "class Foo \n{\n int* p;\npublic:\n Foo();\n ~Foo();\n};\n\ninline Foo::Foo() \n{ \n p = new char[0x00100000]; \n}\n\ninline Foo::~Foo()\n{ \n delete [] p; \n}\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
21,388
<p>I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order.</p> <p>For example, let's say I'm writing a book, and each chapter is an object. I write my book, and put the chapters in the following order:</p> <blockquote> <p>Introduction, Accessibility, Form vs. Function, Errors, Consistency, Conclusion, Index</p> </blockquote> <p>It goes to the editor, and comes back with the following suggested order:</p> <blockquote> <p>Introduction, Form, Function, Accessibility, Consistency, Errors, Conclusion, Index</p> </blockquote> <p>How can I store this ordering in the database in a robust, efficient way?</p> <p>I've had the following ideas, but I'm not thrilled with any of them:</p> <ol> <li><p>Array. Each row has an ordering ID, when order is changed (via a removal followed by an insertion), the order IDs are updated. This makes retrieval easy, since it's just <code>ORDER BY</code>, but it seems easy to break.</p> <blockquote> <p><code>// REMOVAL</code><br> <code>UPDATE ... SET orderingID=NULL WHERE orderingID=removedID</code><br> <code>UPDATE ... SET orderingID=orderingID-1 WHERE orderingID &gt; removedID</code><br> <code>// INSERTION</code><br> <code>UPDATE ... SET orderingID=orderingID+1 WHERE orderingID &gt; insertionID</code><br> <code>UPDATE ... SET orderID=insertionID WHERE ID=addedID</code></p> </blockquote></li> <li><p>Linked list. Each row has a column for the id of the next row in the ordering. Traversal seems costly here, though there may by some way to use <code>ORDER BY</code> that I'm not thinking of.</p></li> <li><p>Spaced array. Set the orderingID (as used in #1) to be large, so the first object is 100, the second is 200, etc. Then when an insertion happens, you just place it at <code>(objectBefore + objectAfter)/2</code>. Of course, this would need to be rebalanced occasionally, so you don't have things too close together (even with floats, you'd eventually run into rounding errors).</p></li> </ol> <p>None of these seem particularly elegant to me. Does anyone have a better way to do it?</p>
[ { "answer_id": 53794303, "author": "Chris Conlan", "author_id": 6073802, "author_profile": "https://Stackoverflow.com/users/6073802", "pm_score": 0, "selected": false, "text": "INSERT INSERT INSERT DELETE DELETE CharField() max_length INSERT JOIN" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2363/" ]
21,437
<p>What are some effective strategies for preventing the use of my proprietary images?</p> <p>I'm talking about saving them, direct linking to them etc...</p> <p>Presently I have a watermark on the image, but I'd rather not.</p> <p>.NET platform preferred, but if there's a strategy that's on another platform that integrates with my existing application that'd be a bonus.</p>
[ { "answer_id": 11382754, "author": "mridul4c", "author_id": 1509915, "author_profile": "https://Stackoverflow.com/users/1509915", "pm_score": 0, "selected": false, "text": " <div style=”float: left;”>\n<img src=”your-image.jpg” style=”width: 200px;height: 200px;”/>\n<img src=”the-dummy-image.png” style=”border: 0px solid #000; width: 200px; height: 250px; margin-left: -200px; ” />\n</div>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975/" ]
21,448
<p>I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files.</p> <p>So far I have this: </p> <pre><code>DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties= ""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E </code></pre> <p>This gives me the error: <strong><code>Option "Properties=Excel 8.0;HDR=Yes" is not valid.</code></strong></p> <p>I've tried a few variations with the Quotation marks but have not been able to get it right yet.</p> <p>Does anyone know how to fix this?</p> <p><strong><code>UPDATE:</code></strong></p> <p>Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version.</p>
[ { "answer_id": 22093, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 2, "selected": false, "text": "\"Data Source=\" + @[User::FilePath] + \";Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBASE IV;\"" }, { "answer_id": 110617, "author": "Michael Entin", "author_id": 19880, "author_profile": "https://Stackoverflow.com/users/19880", "pm_score": 2, "selected": false, "text": "Program Files (x86)\\Microsoft Sql Server\\90\\Dts\\Binn" }, { "answer_id": 774652, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "C:\\Program Files (x86)\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec.exe C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\ set @params = '/set \\package.variables[ImportFilename].Value;\"\\\"' + @FileName + '\\\"\" '\nset @cmd = 'dtexec32 /SQ \"' + @packagename + ' ' + @params + '\"'\n--DECLARE @returncode int\nexec master..xp_cmdshell @cmd\n--exec @returncode = master..xp_cmdshell @cmd\n--select @returncode\n" }, { "answer_id": 6805514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "NOTE: CREATE PROCEDURE [dbo].[GetCurrency]\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT \n TOP 10 CurrencyCode\n , Name\n , ModifiedDate \n FROM Sales.Currency\n ORDER BY CurrencyCode\nEND\nGO\n Data Flow task OLE DB Source Excel Destination Operating System (CmdExec) Operating system (CmdExec) C:\\Program Files (x86)\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec.exe /FILE \n\"D:\\SSIS\\Practice\\20110723_1015_SO_21448_Excel_64_bit_Error.dtsx\" \n/CONNECTION Excel;\"\\\"Provider=Microsoft.Jet.OLEDB.4.0;Data \nSource=D:\\SSIS\\Practice\\Currencies.xls;Extended Properties=\"\"EXCEL 8.0;HDR=YES\"\";\\\"\" \n/MAXCONCURRENT \" -1 \" /CHECKPOINTING OFF /REPORTING EWCDI\n Option “8.0;HDR=YES’;” is not valid." } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2375/" ]
21,449
<p>What is the difference between the following types of endianness?</p> <ul> <li>byte (8b) invariant big and little endianness</li> <li>half-word (16b) invariant big and little endianness</li> <li>word (32b) invariant big and little endianness</li> <li>double-word (64b) invariant big and little endianness</li> </ul> <p>Are there other types/variations?</p>
[ { "answer_id": 21455, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": -1, "selected": false, "text": "1010 0011\n 0011 1010\n 1100 0101\n" }, { "answer_id": 21531, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 1, "selected": false, "text": "FFFF 0000\n 0000 FFFF\n FF 00\n 00 FF\n" }, { "answer_id": 61730, "author": "Ben Lever", "author_id": 2045, "author_profile": "https://Stackoverflow.com/users/2045", "pm_score": 5, "selected": false, "text": "Addr Memory\n 7 0\n | | (LE) (BE)\n |----|\n +0 | aa | lsb msb\n |----|\n +1 | bb | : :\n |----|\n +2 | cc | : :\n |----|\n +3 | dd | msb lsb\n |----|\n | |\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0xaa (preserved)\nRead 2 bytes: 0xbbaa 0xaabb\nRead 4 bytes: 0xddccbbaa 0xaabbccdd\n 0xddccbbaa Addr Memory\n\n | +3 +2 +1 +0 | <- LE\n |-------------------|\n+0 msb | dd | cc | bb | aa | lsb\n |-------------------|\n+4 msb | 99 | 88 | 77 | 66 | lsb\n |-------------------|\n BE -> | +0 +1 +2 +3 |\n\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0xdd\nRead 2 bytes: 0xbbaa 0xddcc\nRead 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)\nRead 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)\n 0xbbaa Addr Memory\n\n | +1 +0 | <- LE\n |---------|\n+0 msb | bb | aa | lsb\n |---------|\n+2 msb | dd | cc | lsb\n |---------|\n+4 msb | 77 | 66 | lsb\n |---------|\n+6 msb | 99 | 88 | lsb\n |---------|\n BE -> | +0 +1 |\n\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0xbb\nRead 2 bytes: 0xbbaa 0xbbaa (preserved)\nRead 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)\nRead 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)\n 0x99887766ddccbbaa Addr Memory\n\n | +7 +6 +5 +4 +3 +2 +1 +0 | <- LE\n |---------------------------------------|\n+0 msb | 99 | 88 | 77 | 66 | dd | cc | bb | aa | lsb\n |---------------------------------------|\n BE -> | +0 +1 +2 +3 +4 +5 +6 +7 |\n\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0x99\nRead 2 bytes: 0xbbaa 0x9988\nRead 4 bytes: 0xddccbbaa 0x99887766\nRead 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)\n" }, { "answer_id": 68689, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "\n 0x100: 12 34 56 78 90 ab cd ef\n\nReads Little Endian Big Endian\n 8-bit: 12 12\n16-bit: 34 12 12 34\n32-bit: 78 56 34 12 12 34 56 78\n64-bit: ef cd ab 90 78 56 34 12 12 34 56 78 90 ab cd ef\n \n uint32_t* lptr = 0x100;\n uint16_t data;\n *lptr = 0x0000FFFF\n\n data = *((uint16_t*)lptr);\n" }, { "answer_id": 69163, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "1010 0011\n 1100 0101\n typedef struct {\n int firstbit:1;\n int middlebits:10;\n int lastbits:21;\n};\n typedef struct {\n int lastbits:21;\n int middlebits:10;\n int firstbit:1;\n};\n" }, { "answer_id": 3581332, "author": "eel ghEEz", "author_id": 80772, "author_profile": "https://Stackoverflow.com/users/80772", "pm_score": 2, "selected": false, "text": "#if LITTLE_ENDIAN\n struct breakdown_t {\n int least_significant_bit: 1;\n int middle_bits: 10;\n int most_significant_bits: 21;\n };\n#elif BIG_ENDIAN\n struct breakdown_t {\n int most_significant_bits: 21;\n int middle_bits: 10;\n int least_significant_bit: 1;\n };\n#else\n #error Huh\n#endif\n\nuint32_t data = ...;\nstruct breakdown_t *b = (struct breakdown_t *)&data;\n uint32_t data = ...;\nuint32_t least_significant_bit = data & 0x00000001;\nuint32_t middle_bits = (data >> 1) & 0x000003FF;\nuint32_t most_significant_bits = (data >> 11) & 0x001fffff;\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045/" ]
21,454
<p>How do I go about specifying and using an ENUM in a Django model?</p>
[ { "answer_id": 21468, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 7, "selected": false, "text": "MAYBECHOICE = (\n ('y', 'Yes'),\n ('n', 'No'),\n ('u', 'Unknown'),\n)\n married = models.CharField(max_length=1, choices=MAYBECHOICE)\n MAYBECHOICE = (\n (0, 'Yes'),\n (1, 'No'),\n (2, 'Unknown'),\n)\n" }, { "answer_id": 33932, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 5, "selected": false, "text": "choices choices SeparateDatabaseAndState" }, { "answer_id": 1530858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "from django.db import models\n\nclass EnumField(models.Field):\n \"\"\"\n A field class that maps to MySQL's ENUM type.\n\n Usage:\n\n class Card(models.Model):\n suit = EnumField(values=('Clubs', 'Diamonds', 'Spades', 'Hearts'))\n\n c = Card()\n c.suit = 'Clubs'\n c.save()\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.values = kwargs.pop('values')\n kwargs['choices'] = [(v, v) for v in self.values]\n kwargs['default'] = self.values[0]\n super(EnumField, self).__init__(*args, **kwargs)\n\n def db_type(self):\n return \"enum({0})\".format( ','.join(\"'%s'\" % v for v in self.values) )\n" }, { "answer_id": 13089465, "author": "keithxm23", "author_id": 1415352, "author_profile": "https://Stackoverflow.com/users/1415352", "pm_score": 3, "selected": false, "text": "class Entry(models.Model):\n LIVE_STATUS = 1\n DRAFT_STATUS = 2\n HIDDEN_STATUS = 3\n STATUS_CHOICES = (\n (LIVE_STATUS, 'Live'),\n (DRAFT_STATUS, 'Draft'),\n (HIDDEN_STATUS, 'Hidden'),\n )\n # ...some other fields here...\n status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)\n\nlive_entries = Entry.objects.filter(status=Entry.LIVE_STATUS)\ndraft_entries = Entry.objects.filter(status=Entry.DRAFT_STATUS)\n\nif entry_object.status == Entry.LIVE_STATUS:\n" }, { "answer_id": 19040441, "author": "David Cain", "author_id": 815632, "author_profile": "https://Stackoverflow.com/users/815632", "pm_score": 3, "selected": false, "text": "choices db_type from django.db import models\n\n\nclass EnumField(models.Field):\n def __init__(self, *args, **kwargs):\n super(EnumField, self).__init__(*args, **kwargs)\n assert self.choices, \"Need choices for enumeration\"\n\n def db_type(self, connection):\n if not all(isinstance(col, basestring) for col, _ in self.choices):\n raise ValueError(\"MySQL ENUM values should be strings\")\n return \"ENUM({})\".format(','.join(\"'{}'\".format(col) \n for col, _ in self.choices))\n\n\nclass IceCreamFlavor(EnumField, models.CharField):\n def __init__(self, *args, **kwargs):\n flavors = [('chocolate', 'Chocolate'),\n ('vanilla', 'Vanilla'),\n ]\n super(IceCreamFlavor, self).__init__(*args, choices=flavors, **kwargs)\n\n\nclass IceCream(models.Model):\n price = models.DecimalField(max_digits=4, decimal_places=2)\n flavor = IceCreamFlavor(max_length=20)\n syncdb ENUM mysql> SHOW COLUMNS IN icecream;\n+--------+-----------------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-----------------------------+------+-----+---------+----------------+\n| id | int(11) | NO | PRI | NULL | auto_increment |\n| price | decimal(4,2) | NO | | NULL | |\n| flavor | enum('chocolate','vanilla') | NO | | NULL | |\n+--------+-----------------------------+------+-----+---------+----------------+\n" }, { "answer_id": 22155357, "author": "Kenzo", "author_id": 1576113, "author_profile": "https://Stackoverflow.com/users/1576113", "pm_score": -1, "selected": false, "text": " enum = lambda *l: [(s,_(s)) for s in l]\n" }, { "answer_id": 58052062, "author": "Cesar Canassa", "author_id": 360829, "author_profile": "https://Stackoverflow.com/users/360829", "pm_score": 3, "selected": false, "text": "from django.utils.translation import gettext_lazy as _\n\nclass Student(models.Model):\n\n class YearInSchool(models.TextChoices):\n FRESHMAN = 'FR', _('Freshman')\n SOPHOMORE = 'SO', _('Sophomore')\n JUNIOR = 'JR', _('Junior')\n SENIOR = 'SR', _('Senior')\n GRADUATE = 'GR', _('Graduate')\n\n year_in_school = models.CharField(\n max_length=2,\n choices=YearInSchool.choices,\n default=YearInSchool.FRESHMAN,\n )\n class Student(models.Model):\n ...\n\n class Meta:\n constraints = [\n CheckConstraint(\n check=Q(year_in_school__in=YearInSchool.values),\n name=\"valid_year_in_school\")\n ]\n" }, { "answer_id": 73765582, "author": "Nikolay", "author_id": 11620296, "author_profile": "https://Stackoverflow.com/users/11620296", "pm_score": 1, "selected": false, "text": "from django.db import models\nfrom django_mysql.models import EnumField\n\n\nclass IceCreamFlavor(models.TextChoices):\n CHOCOLATE = \"chocolate\"\n VANILLA = \"vanilla\"\n\n\nclass IceCream(models.Model):\n price = models.DecimalField(max_digits=4, decimal_places=2)\n ice_cream_flavor = EnumField(choices=IceCreamFlavor.choices)\n\n mysql> SHOW COLUMNS IN myapp.db_icecream;\n+------------------+-----------------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------------+-----------------------------+------+-----+---------+----------------+\n| id | int | NO | PRI | NULL | auto_increment |\n| price | decimal(4,2) | NO | | NULL | |\n| ice_cream_flavor | enum('chocolate','vanilla') | NO | | NULL | |\n+------------------+-----------------------------+------+-----+---------+----------------+\n\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019/" ]
21,461
<pre><code>#if SYMBOL //code #endif </code></pre> <p>what values does C# predefine for use?</p>
[ { "answer_id": 21467, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "Visual Studio DEBUG" }, { "answer_id": 21479, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "#define /define" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
21,489
<p>SQL Experts,</p> <p>Is there an efficient way to group runs of data together using SQL?<br> Or is it going to be more efficient to process the data in code. </p> <p>For example if I have the following data:</p> <pre><code>ID|Name 01|Harry Johns 02|Adam Taylor 03|John Smith 04|John Smith 05|Bill Manning 06|John Smith </code></pre> <p>I need to display this:</p> <pre><code>Harry Johns Adam Taylor John Smith (2) Bill Manning John Smith </code></pre> <p>@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.</p>
[ { "answer_id": 21492, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "select Name, count(*)\nfrom MyTable\ngroup by Name\n select Name + ' (' + cast(count(*) as varchar) + ')'\nfrom MyTable\ngroup by Name\n" }, { "answer_id": 21510, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": false, "text": "select Name, count(Id)\nfrom MyTable\ngroup by Name\n Harry Johns, 1\nAdam Taylor, 1\nJohn Smith, 2\nBill Manning, 1\n select Name +\n case when ( count(Id) > 1 ) \n then ' ('+cast(count(Id) as varchar)+')' \n else ''\n end\nfrom MyTable\ngroup by Name\n Harry Johns\nAdam Taylor\nJohn Smith (2)\nBill Manning\n" }, { "answer_id": 21545, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": true, "text": "select n.name, \n (select count(*) \n from myTable n1\n where n1.name = n.name and n1.id >= n.id and (n1.id <=\n (\n select isnull(min(nn.id), (select max(id) + 1 from myTable))\n from myTable nn\n where nn.id > n.id and nn.name <> n.name\n )\n ))\nfrom myTable n\nwhere not exists (\n select 1\n from myTable n3\n where n3.name = n.name and n3.id < n.id and n3.id > (\n select isnull(max(n4.id), (select min(id) - 1 from myTable))\n from myTable n4\n where n4.id < n.id and n4.name <> n.name\n )\n)\n" }, { "answer_id": 21555, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 2, "selected": false, "text": "Declare @NewName Varchar(50)\nDeclare @OldName Varchar(50)\nDeclare @CountNum int\nSet @CountNum = 0\n\nDECLARE nameCursor CURSOR FOR \nSELECT Name\nFROM NameTest\nOPEN nameCursor\n\nFETCH NEXT FROM nameCursor INTO @NewName\n\n WHILE @@FETCH_STATUS = 0 \n\n BEGIN\n\n if @OldName <> @NewName\n BEGIN\n Print @OldName + ' (' + Cast(@CountNum as Varchar(50)) + ')'\n Set @CountNum = 0\n END\n SELECT @OldName = @NewName\n FETCH NEXT FROM nameCursor INTO @NewName\n Set @CountNum = @CountNum + 1\n\n END\nPrint @OldName + ' (' + Cast(@CountNum as Varchar(50)) + ')'\n\nCLOSE nameCursor\nDEALLOCATE nameCursor\n" }, { "answer_id": 21561, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "declare @tmp table (Id int, Nm varchar(50));\n\ninsert @tmp select 1, 'Harry Johns';\ninsert @tmp select 2, 'Adam Taylor';\ninsert @tmp select 3, 'John Smith';\ninsert @tmp select 4, 'John Smith';\ninsert @tmp select 5, 'Bill Manning';\ninsert @tmp select 6, 'John Smith';\n\nselect * from @tmp order by Id;\n\nselect Nm, count(1) from \n(\nselect Id, Nm, \n case when exists (\n select 1 from @tmp t2 \n where t2.Nm=t1.Nm \n and (t2.Id = t1.Id + 1 or t2.Id = t1.Id - 1)) \n then 1 else 0 end as Run\nfrom @tmp t1\n) truns group by Nm, Run\n select Nm, count(1) from (select Id, Nm, case when exists (\n select 1 from @tmp t2 where t2.Nm=t1.Nm \n and abs(t2.Id-t1.Id)=1) then 1 else 0 end as Run\nfrom @tmp t1) t group by Nm, Run\n" }, { "answer_id": 21768, "author": "Jon Erickson", "author_id": 1950, "author_profile": "https://Stackoverflow.com/users/1950", "pm_score": 2, "selected": false, "text": "-- Setup test table\nDECLARE @names TABLE (\n id INT IDENTITY(1,1),\n name NVARCHAR(25) NOT NULL,\n grp UNIQUEIDENTIFIER NULL\n )\n\nINSERT @names (name)\nSELECT 'Harry Johns' UNION ALL \nSELECT 'Adam Taylor' UNION ALL\nSELECT 'John Smith' UNION ALL\nSELECT 'John Smith' UNION ALL\nSELECT 'Bill Manning' UNION ALL\nSELECT 'Bill Manning' UNION ALL\nSELECT 'Bill Manning' UNION ALL\nSELECT 'John Smith' UNION ALL\nSELECT 'Bill Manning' \n\n-- Set the first id's group to a newid()\nUPDATE n\nSET grp = newid()\nFROM @names n\nWHERE n.id = (SELECT MIN(id) FROM @names)\n\n-- Set the group to a newid() if the name does not equal the previous\nUPDATE n\nSET grp = newid()\nFROM @names n\nINNER JOIN @names b\n ON (n.ID - 1) = b.ID\n AND ISNULL(b.Name, '') <> n.Name\n\n-- Set groups that are null to the previous group\n-- Keep on doing this until all groups have been set\nWHILE (EXISTS(SELECT 1 FROM @names WHERE grp IS NULL))\nBEGIN\n UPDATE n\n SET grp = b.grp\n FROM @names n\n INNER JOIN @names b\n ON (n.ID - 1) = b.ID\n AND n.grp IS NULL\nEND\n\n-- Final output\nSELECT MIN(id) AS id_start,\n MAX(id) AS id_end,\n name,\n count(1) AS consecutive\nFROM @names\nGROUP BY grp, \n name\nORDER BY id_start\n\n/*\nResults:\n\nid_start id_end name consecutive\n1 1 Harry Johns 1\n2 2 Adam Taylor 1\n3 4 John Smith 2\n5 7 Bill Manning 3\n8 8 John Smith 1\n9 9 Bill Manning 1\n*/\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
21,514
<p>Within c#, I need to be able to</p> <ul> <li>Connect to a remote system, specifying username/password as appropriate</li> <li>List the members of a localgroup on that system</li> <li>Fetch the results back to the executing computer</li> </ul> <p>So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administrators including SOMESYSTEM\Administrator, SOMESYSTEM\Bob, DOMAIN\AlanH, "DOMAIN\Domain Administrators".</p> <p>I've tried this with system.directoryservices.accountmanagement but am running into problems with authentication. Sometimes I get:</p> <p><em>Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. (Exception from HRESULT: 0x800704C3)</em></p> <p>The above is trying because there will be situations where I simply cannot unmap existing drives or UNC connections.</p> <p>Other times my program gets UNKNOWN ERROR and the security log on the remote system reports an error 675, code 0x19 which is KDC_ERR_PREAUTH_REQUIRED.</p> <p>I need a simpler and less error prone way to do this!</p>
[ { "answer_id": 24075, "author": "quux", "author_id": 2383, "author_profile": "https://Stackoverflow.com/users/2383", "pm_score": 2, "selected": false, "text": "SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \"Win32_Group.Domain='thehostname',Name='thegroupname'\"\n public string GroupMembers(string targethost, string groupname, string targetusername, string targetpassword)\n {\n StringBuilder result = new StringBuilder(); \n try\n {\n ConnectionOptions Conn = new ConnectionOptions();\n if (targethost != Environment.MachineName) //WMI errors if creds given for localhost\n {\n Conn.Username = targetusername; //can be null\n Conn.Password = targetpassword; //can be null\n }\n Conn.Timeout = TimeSpan.FromSeconds(2);\n ManagementScope scope = new ManagementScope(\"\\\\\\\\\" + targethost + \"\\\\root\\\\cimv2\", Conn);\n scope.Connect();\n StringBuilder qs = new StringBuilder();\n qs.Append(\"SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \\\"Win32_Group.Domain='\");\n qs.Append(targethost);\n qs.Append(\"',Name='\");\n qs.Append(groupname);\n qs.AppendLine(\"'\\\"\");\n ObjectQuery query = new ObjectQuery(qs.ToString());\n ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);\n ManagementObjectCollection queryCollection = searcher.Get();\n foreach (ManagementObject m in queryCollection)\n {\n ManagementPath path = new ManagementPath(m[\"PartComponent\"].ToString()); \n { \n String[] names = path.RelativePath.Split(',');\n result.Append(names[0].Substring(names[0].IndexOf(\"=\") + 1).Replace(\"\\\"\", \" \").Trim() + \"\\\\\"); \n result.AppendLine(names[1].Substring(names[1].IndexOf(\"=\") + 1).Replace(\"\\\"\", \" \").Trim()); \n }\n }\n return result.ToString();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error. Message: \" + e.Message);\n return \"fail\";\n }\n }\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2383/" ]
21,547
<p>I've spent a good amount of time coming up with solution to this problem, so in the spirit of <a href="https://stackoverflow.com/questions/21245/questions-vs-conveying-information">this post</a>, I'm posting it here, since I think it might be useful to others. </p> <p>If anyone has a better script, or anything to add, please post it.</p> <p>Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.</p>
[ { "answer_id": 21551, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 5, "selected": false, "text": "declare @schema varchar(100), @table varchar(100)\nset @schema = 'dbo' -- set schema name here\nset @table = 'MyTable' -- set table name here\ndeclare @sql table(s varchar(1000), id int identity)\n\n-- create statement\ninsert into @sql(s) values ('create table [' + @table + '] (')\n\n-- column list\ninsert into @sql(s)\nselect \n ' ['+column_name+'] ' + \n data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=@table\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(@table) as varchar) + ',' + \n cast(ident_incr(@table) as varchar) + ')'\n else ''\n end + ' ' +\n ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + \n coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','\n\n from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema\n order by ordinal_position\n\n-- primary key\ndeclare @pkname varchar(100)\nselect @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nwhere table_name = @table and constraint_type='PRIMARY KEY'\n\nif ( @pkname is not null ) begin\n insert into @sql(s) values(' PRIMARY KEY (')\n insert into @sql(s)\n select ' ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n where constraint_name = @pkname\n order by ordinal_position\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\n insert into @sql(s) values (' )')\nend\nelse begin\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\nend\n\n-- closing bracket\ninsert into @sql(s) values( ')' )\n\n-- result!\nselect s from @sql order by id\n" }, { "answer_id": 22126, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "CREATE TABLE" }, { "answer_id": 317864, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "\nselect 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END\nfrom sysobjects so\ncross apply\n (SELECT \n ' ['+column_name+'] ' + \n data_type + case data_type\n when 'sql_variant' then ''\n when 'text' then ''\n when 'ntext' then ''\n when 'xml' then ''\n when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'\n else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=so.name\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end + ' ' +\n (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + \n case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' \n\n from information_schema.columns where table_name = so.name\n order by ordinal_position\n FOR XML PATH('')) o (list)\nleft join\n information_schema.table_constraints tc\non tc.Table_name = so.Name\nAND tc.Constraint_Type = 'PRIMARY KEY'\ncross apply\n (select '[' + Column_Name + '], '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY\n ORDINAL_POSITION\n FOR XML PATH('')) j (list)\nwhere xtype = 'U'\nAND name NOT IN ('dtproperties')\n\n" }, { "answer_id": 991321, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "USE [db]\nGO\n\n/****** Object: StoredProcedure [dbo].[procUtils_InsertGeneratorWithId] Script Date: 06/13/2009 22:18:11 ******/\nSET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\n\ncreate PROC [dbo].[procUtils_InsertGeneratorWithId] \n( \n@domain_user varchar(50), \n@tableName varchar(100) \n) \n\n\nas \n\n--Declare a cursor to retrieve column specific information for the specified table \nDECLARE cursCol CURSOR FAST_FORWARD FOR \nSELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName \nOPEN cursCol \nDECLARE @string nvarchar(3000) --for storing the first half of INSERT statement \nDECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement \nDECLARE @dataType nvarchar(1000) --data types returned for respective columns \nDECLARE @IDENTITY_STRING nvarchar ( 100 ) \nSET @IDENTITY_STRING = ' ' \nselect @IDENTITY_STRING \nSET @string='INSERT '+@tableName+'(' \nSET @stringData='' \n\nDECLARE @colName nvarchar(50) \n\nFETCH NEXT FROM cursCol INTO @colName,@dataType \n\nIF @@fetch_status<>0 \n begin \n print 'Table '+@tableName+' not found, processing skipped.' \n close curscol \n deallocate curscol \n return \nEND \n\nWHILE @@FETCH_STATUS=0 \nBEGIN \nIF @dataType in ('varchar','char','nchar','nvarchar') \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+' \nEND \nELSE \nif @dataType in ('text','ntext') --if the datatype is text or something else \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+' \nEND \nELSE \nIF @dataType = 'money' --because money doesn't get converted from varchar implicitly \nBEGIN \n SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \nEND \nELSE \nIF @dataType='datetime' \nBEGIN \n --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+' \n --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \n --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \n SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n -- 'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \nEND \nELSE \nIF @dataType='image' \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+' \nEND \nELSE --presuming the data type is int,bit,numeric,decimal \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+' \n --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+' \nEND \n\nSET @string=@string+@colName+',' \n\nFETCH NEXT FROM cursCol INTO @colName,@dataType \nEND \nDECLARE @Query nvarchar(4000) \n\nSET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName \nexec sp_executesql @query \n--select @query \n\nCLOSE cursCol \nDEALLOCATE cursCol \n\n\n /*\nUSAGE\n\n*/\n\nGO\n USE [db]\nGO\n\n/****** Object: StoredProcedure [dbo].[procUtils_InsertGenerator] Script Date: 06/13/2009 22:20:52 ******/\nSET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\nCREATE PROC [dbo].[procUtils_InsertGenerator] \n( \n@domain_user varchar(50), \n@tableName varchar(100) \n) \n\n\nas \n\n--Declare a cursor to retrieve column specific information for the specified table \nDECLARE cursCol CURSOR FAST_FORWARD FOR \n\n\n-- SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName \n/* NEW \nSELECT c.name , sc.data_type FROM sys.extended_properties AS ep \nINNER JOIN sys.tables AS t ON ep.major_id = t.object_id \nINNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id \n= c.column_id \nINNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and \nc.name = sc.column_name \nWHERE t.name = @tableName and c.is_identity=0 \n */ \n\nselect object_name(c.object_id) \"TABLE_NAME\", c.name \"COLUMN_NAME\", s.name \"DATA_TYPE\" \n from sys.columns c \n join sys.systypes s on (s.xtype = c.system_type_id) \n where object_name(c.object_id) in (select name from sys.tables where name not like 'sysdiagrams') \n AND object_name(c.object_id) in (select name from sys.tables where [name]=@tableName ) and c.is_identity=0 and s.name not like 'sysname' \n\n\n\n\nOPEN cursCol \nDECLARE @string nvarchar(3000) --for storing the first half of INSERT statement \nDECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement \nDECLARE @dataType nvarchar(1000) --data types returned for respective columns \nDECLARE @IDENTITY_STRING nvarchar ( 100 ) \nSET @IDENTITY_STRING = ' ' \nselect @IDENTITY_STRING \nSET @string='INSERT '+@tableName+'(' \nSET @stringData='' \n\nDECLARE @colName nvarchar(50) \n\nFETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType \n\nIF @@fetch_status<>0 \n begin \n print 'Table '+@tableName+' not found, processing skipped.' \n close curscol \n deallocate curscol \n return \nEND \n\nWHILE @@FETCH_STATUS=0 \nBEGIN \nIF @dataType in ('varchar','char','nchar','nvarchar') \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+' \nEND \nELSE \nif @dataType in ('text','ntext') --if the datatype is text or something else \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+' \nEND \nELSE \nIF @dataType = 'money' --because money doesn't get converted from varchar implicitly \nBEGIN \n SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \nEND \nELSE \nIF @dataType='datetime' \nBEGIN \n --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+' \n --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \n --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \n SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n -- 'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \nEND \nELSE \nIF @dataType='image' \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+' \nEND \nELSE --presuming the data type is int,bit,numeric,decimal \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+' \n --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+' \nEND \n\nSET @string=@string+@colName+',' \n\nFETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType \nEND \nDECLARE @Query nvarchar(4000) \n\nSET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName \nexec sp_executesql @query \n--select @query \n\nCLOSE cursCol \nDEALLOCATE cursCol \n\n\n /* \n\nuse poc \ngo \n\nDECLARE @RC int \nDECLARE @domain_user varchar(50) \nDECLARE @tableName varchar(100) \n\n-- TODO: Set parameter values here. \nset @domain_user='yorgeorg' \nset @tableName = 'tbGui_WizardTabButtonAreas' \n\nEXECUTE @RC = [POC].[dbo].[procUtils_InsertGenerator] \n @domain_user \n ,@tableName \n\n*/\nGO\n" }, { "answer_id": 10115560, "author": "8kb", "author_id": 375799, "author_profile": "https://Stackoverflow.com/users/375799", "pm_score": 4, "selected": false, "text": "# Script all tables in a database\n[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SqlServer.SMO\") \n | out-null\n\n$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') '<Servername>'\n$db = $s.Databases['<Database>']\n\n$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)\n$scrp.Options.AppendToFile = $True\n$scrp.Options.ClusteredIndexes = $True\n$scrp.Options.DriAll = $True\n$scrp.Options.ScriptDrops = $False\n$scrp.Options.IncludeHeaders = $False\n$scrp.Options.ToFileOnly = $True\n$scrp.Options.Indexes = $True\n$scrp.Options.WithDependencies = $True\n$scrp.Options.FileName = 'C:\\Temp\\<Database>.SQL'\n\nforeach($item in $db.Tables) { $tablearray+=@($item) }\n$scrp.Script($tablearray)\n\nWrite-Host \"Scripting complete\"\n" }, { "answer_id": 15645815, "author": "zanlok", "author_id": 512671, "author_profile": "https://Stackoverflow.com/users/512671", "pm_score": 4, "selected": false, "text": "SELECT \n t.TABLE_CATALOG,\n t.TABLE_SCHEMA,\n t.TABLE_NAME,\n 'create table '+QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) + ' (' + LEFT(o.List, Len(o.List)-1) + '); ' \n + CASE WHEN tc.Constraint_Name IS NULL THEN '' \n ELSE \n 'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) \n + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + '); ' \n END as 'SQL_CREATE_TABLE'\nFROM sysobjects so\n\nCROSS APPLY (\n SELECT \n ' ['+column_name+'] ' \n + data_type \n + case data_type\n when 'sql_variant' then ''\n when 'text' then ''\n when 'ntext' then ''\n when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'\n else \n coalesce(\n '('+ case when character_maximum_length = -1 \n then 'MAX' \n else cast(character_maximum_length as varchar) end \n + ')','') \n end \n + ' ' \n + case when exists ( \n SELECT id \n FROM syscolumns\n WHERE \n object_name(id) = so.name\n and name = column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end \n + ' ' \n + (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) \n + 'NULL ' \n + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT \n ELSE '' \n END \n + ',' -- can't have a field name or we'll end up with XML\n\n FROM information_schema.columns \n WHERE table_name = so.name\n ORDER BY ordinal_position\n FOR XML PATH('')\n) o (list)\n\nLEFT JOIN information_schema.table_constraints tc on \n tc.Table_name = so.Name\n AND tc.Constraint_Type = 'PRIMARY KEY'\n\nLEFT JOIN information_schema.tables t on \n t.Table_name = so.Name\n\nCROSS APPLY (\n SELECT QuoteName(Column_Name) + ', '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY ORDINAL_POSITION\n FOR XML PATH('')\n) j (list)\n\nWHERE\n xtype = 'U'\n AND name NOT IN ('dtproperties')\n -- AND so.name = 'ASPStateTempSessions'\n;\n -- settings\nDECLARE @CRLF NCHAR(2)\nSET @CRLF = Nchar(13) + NChar(10)\nDECLARE @PLACEHOLDER NCHAR(3)\nSET @PLACEHOLDER = '{:}'\n\n-- the main query\nSELECT \n t.TABLE_CATALOG,\n t.TABLE_SCHEMA,\n t.TABLE_NAME,\n CAST(\n REPLACE(\n 'create table ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.name) + ' (' + @CRLF \n + LEFT(o.List, Len(o.List) - (LEN(@PLACEHOLDER)+2)) + @CRLF + ');' + @CRLF\n + CASE WHEN tc.Constraint_Name IS NULL THEN '' \n ELSE\n 'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.Name) \n + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY (' + LEFT(j.List, Len(j.List) - 1) + ');' + @CRLF\n END,\n @PLACEHOLDER,\n @CRLF\n )\n AS XML) as 'SQL_CREATE_TABLE'\nFROM sysobjects so\n\nCROSS APPLY (\n SELECT \n ' '\n + '['+column_name+'] ' \n + data_type \n + case data_type\n when 'sql_variant' then ''\n when 'text' then ''\n when 'ntext' then ''\n when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'\n else \n coalesce(\n '('+ case when character_maximum_length = -1 \n then 'MAX' \n else cast(character_maximum_length as varchar) end \n + ')','') \n end \n + ' ' \n + case when exists ( \n SELECT id \n FROM syscolumns\n WHERE \n object_name(id) = so.name\n and name = column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end \n + ' ' \n + (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) \n + 'NULL ' \n + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT \n ELSE '' \n END \n + ', ' \n + @PLACEHOLDER -- note, can't have a field name or we'll end up with XML\n\n FROM information_schema.columns where table_name = so.name\n ORDER BY ordinal_position\n FOR XML PATH('')\n) o (list)\n\nLEFT JOIN information_schema.table_constraints tc on \n tc.Table_name = so.Name\n AND tc.Constraint_Type = 'PRIMARY KEY'\n\nLEFT JOIN information_schema.tables t on \n t.Table_name = so.Name\n\nCROSS APPLY (\n SELECT QUOTENAME(Column_Name) + ', '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY ORDINAL_POSITION\n FOR XML PATH('')\n) j (list)\n\nWHERE\n xtype = 'U'\n AND name NOT IN ('dtproperties')\n -- AND so.name = 'ASPStateTempSessions'\n;\n -- 1 (scripting version)\ncreate table [dbo].[ASPStateTempApplications] ( [AppId] int NOT NULL , [AppName] char(280) NOT NULL ); ALTER TABLE [dbo].[ASPStateTempApplications] ADD CONSTRAINT PK__ASPState__8E2CF7F908EA5793 PRIMARY KEY ([AppId]); \n\n-- 2 (SSMS version)\ncreate table [dbo].[ASPStateTempSessions] (\n [SessionId] nvarchar(88) NOT NULL , \n [Created] datetime NOT NULL DEFAULT (getutcdate()), \n [Expires] datetime NOT NULL , \n [LockDate] datetime NOT NULL , \n [LockDateLocal] datetime NOT NULL , \n [LockCookie] int NOT NULL , \n [Timeout] int NOT NULL , \n [Locked] bit NOT NULL , \n [SessionItemShort] varbinary(7000) NULL , \n [SessionItemLong] image(2147483647) NULL , \n [Flags] int NOT NULL DEFAULT ((0))\n);\nALTER TABLE [dbo].[ASPStateTempSessions] ADD CONSTRAINT PK__ASPState__C9F4929003317E3D PRIMARY KEY ([SessionId]);\n" }, { "answer_id": 18619504, "author": "Hubbitus", "author_id": 307525, "author_profile": "https://Stackoverflow.com/users/307525", "pm_score": 3, "selected": false, "text": " SELECT\n obj.name\n ,'CREATE TABLE [' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')'\n + ISNULL(' ' + refs.list, '')\n FROM sysobjects obj\n CROSS APPLY (\n SELECT \n CHAR(10)\n + ' [' + column_name + '] '\n + data_type\n + CASE data_type\n WHEN 'sql_variant' THEN ''\n WHEN 'text' THEN ''\n WHEN 'ntext' THEN ''\n WHEN 'xml' THEN ''\n WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'\n ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')\n END\n + ' '\n + case when exists ( -- Identity skip\n select id from syscolumns\n where object_name(id) = obj.name\n and name = column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(obj.name) as varchar) + ',' + \n cast(ident_incr(obj.name) as varchar) + ')'\n else ''\n end + ' '\n + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END\n + 'NULL'\n + CASE WHEN information_schema.columns.column_default IS NOT NULL THEN ' DEFAULT ' + information_schema.columns.column_default ELSE '' END\n + ','\n FROM\n INFORMATION_SCHEMA.COLUMNS\n WHERE table_name = obj.name\n ORDER BY ordinal_position\n FOR XML PATH('')\n ) cols (list)\n CROSS APPLY(\n SELECT\n CHAR(10) + 'ALTER TABLE ' + obj.name + '_noident_temp ADD ' + LEFT(alt, LEN(alt)-1)\n FROM(\n SELECT\n CHAR(10)\n + ' CONSTRAINT ' + tc.constraint_name\n + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'\n + COALESCE(CHAR(10) + r.list, ', ')\n FROM\n information_schema.table_constraints tc\n CROSS APPLY(\n SELECT\n '[' + kcu.column_name + '], '\n FROM\n information_schema.key_column_usage kcu\n WHERE\n kcu.constraint_name = tc.constraint_name\n ORDER BY\n kcu.ordinal_position\n FOR XML PATH('')\n ) c (list)\n OUTER APPLY(\n -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema\n SELECT\n ' REFERENCES [' + kcu1.constraint_schema + '].' + '[' + kcu2.table_name + ']' + '(' + kcu2.column_name + '), '\n FROM information_schema.referential_constraints as rc\n JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)\n JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)\n WHERE\n kcu1.constraint_catalog = tc.constraint_catalog AND kcu1.constraint_schema = tc.constraint_schema AND kcu1.constraint_name = tc.constraint_name\n ) r (list)\n WHERE tc.table_name = obj.name\n FOR XML PATH('')\n ) a (alt)\n ) refs (list)\n WHERE\n xtype = 'U'\n AND name NOT IN ('dtproperties')\n AND obj.name = 'your_table_name'\n" }, { "answer_id": 25324645, "author": "JasmineOT", "author_id": 2991410, "author_profile": "https://Stackoverflow.com/users/2991410", "pm_score": 3, "selected": false, "text": "declare @table varchar(100)\ndeclare @schema varchar(100)\nset @table = 'Persons' -- set table name here\nset @schema = 'OT' -- set SCHEMA name here\ndeclare @sql table(s varchar(1000), id int identity)\n\n-- create statement\ninsert into @sql(s) values ('create table ' + @table + ' (')\n\n-- column list\ninsert into @sql(s)\nselect \n ' '+column_name+' ' + \n data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=@table\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(@table) as varchar) + ',' + \n cast(ident_incr(@table) as varchar) + ')'\n else ''\n end + ' ' +\n ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + \n coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','\n\n from information_schema.columns where table_name = @table and table_schema = @schema\n order by ordinal_position\n\n-- primary key\ndeclare @pkname varchar(100)\nselect @pkname = constraint_name from information_schema.table_constraints\nwhere table_name = @table and constraint_type='PRIMARY KEY'\n\nif ( @pkname is not null ) begin\n insert into @sql(s) values(' PRIMARY KEY (')\n insert into @sql(s)\n select ' '+COLUMN_NAME+',' from information_schema.key_column_usage\n where constraint_name = @pkname\n order by ordinal_position\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\n insert into @sql(s) values (' )')\nend\nelse begin\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\nend\n\n\n-- foreign key\ndeclare @fkname varchar(100)\nselect @fkname = constraint_name from information_schema.table_constraints\nwhere table_name = @table and constraint_type='FOREIGN KEY'\n\nif ( @fkname is not null ) begin\n insert into @sql(s) values(',')\n insert into @sql(s) values(' FOREIGN KEY (')\n insert into @sql(s)\n select ' '+COLUMN_NAME+',' from information_schema.key_column_usage\n where constraint_name = @fkname\n order by ordinal_position\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\n insert into @sql(s) values (' ) REFERENCES ')\n insert into @sql(s) \n SELECT \n OBJECT_NAME(fk.referenced_object_id)\n FROM \n sys.foreign_keys fk\n INNER JOIN \n sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id\n INNER JOIN\n sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id\n INNER JOIN\n sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id\n where fk.name = @fkname\n insert into @sql(s) \n SELECT \n '('+c2.name+')'\n FROM \n sys.foreign_keys fk\n INNER JOIN \n sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id\n INNER JOIN\n sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id\n INNER JOIN\n sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id\n where fk.name = @fkname\nend\n\n-- closing bracket\ninsert into @sql(s) values( ')' )\n\n-- result!\nselect s from @sql order by id\n" }, { "answer_id": 35092198, "author": "FLICKER", "author_id": 1017065, "author_profile": "https://Stackoverflow.com/users/1017065", "pm_score": 3, "selected": false, "text": "declare @partition_scheme varchar(100) = (\nselect distinct ps.Name AS PartitionScheme\nfrom sys.indexes i \njoin sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id \njoin sys.partition_schemes ps on ps.data_space_id = i.data_space_id \nwhere i.object_id = object_id('your table name')\n)\nprint @partition_scheme\n\ndeclare @partition_column varchar(100) = (\nselect c.name \nfrom sys.tables t\njoin sys.indexes i \n on(i.object_id = t.object_id \n and i.index_id < 2)\njoin sys.index_columns ic \n on(ic.partition_ordinal > 0 \n and ic.index_id = i.index_id and ic.object_id = t.object_id)\njoin sys.columns c \n on(c.object_id = ic.object_id \n and c.column_id = ic.column_id)\nwhere t.object_id = object_id('your table name')\n)\nprint @partition_column\n + IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')\n" }, { "answer_id": 41834624, "author": "Erick Lanford Xenes", "author_id": 5190625, "author_profile": "https://Stackoverflow.com/users/5190625", "pm_score": 2, "selected": false, "text": " select 'CREATE TABLE [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END, name\nfrom sysobjects so\ncross apply\n (SELECT\n\ncase when comps.definition is not null then ' ['+column_name+'] AS ' + comps.definition \nelse\n ' ['+column_name+'] ' + data_type + \n case\n when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')\n then ''\n when data_type in ('float')\n then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'\n when data_type in ('datetime2', 'datetimeoffset', 'time')\n then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'\n when data_type in ('decimal', 'numeric')\n then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'\n when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1\n then '(max)'\n when character_maximum_length is not null\n then '(' + cast(character_maximum_length as varchar(11)) + ')'\n else ''\n end + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=so.name\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end + ' ' +\n (case when information_schema.columns.IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + \n case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END \nend + ', ' \n\n from information_schema.columns \n left join sys.computed_columns comps \n on OBJECT_ID(information_schema.columns.TABLE_NAME)=comps.object_id and information_schema.columns.COLUMN_NAME=comps.name\n\n where table_name = so.name\n order by ordinal_position\n FOR XML PATH('')) o (list)\nleft join\n information_schema.table_constraints tc\non tc.Table_name = so.Name\nAND tc.Constraint_Type = 'PRIMARY KEY'\ncross apply\n (select '[' + Column_Name + '], '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY\n ORDINAL_POSITION\n FOR XML PATH('')) j (list)\nwhere xtype = 'U'\nAND name NOT IN ('dtproperties')\n" }, { "answer_id": 46601179, "author": "Stu", "author_id": 178362, "author_profile": "https://Stackoverflow.com/users/178362", "pm_score": 2, "selected": false, "text": "select into x from db.schema.y where 1=0\n" }, { "answer_id": 63866858, "author": "AMieres", "author_id": 4550898, "author_profile": "https://Stackoverflow.com/users/4550898", "pm_score": 1, "selected": false, "text": "SELECT \n Schema_Name = SCHEMA_NAME(obj.uid)\n, Table_Name = name\n, Drop_Table = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + SCHEMA_NAME(obj.uid) + ''' AND TABLE_NAME = ''' + obj.name + '''))\nDROP TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] '\n, Create_Table ='\nCREATE TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')' + ISNULL(' ' + refs.list, '')\n FROM sysobjects obj\n CROSS APPLY (\n SELECT \n CHAR(10)\n + ' [' + column_name + '] '\n + data_type\n + CASE data_type\n WHEN 'sql_variant' THEN ''\n WHEN 'text' THEN ''\n WHEN 'ntext' THEN ''\n WHEN 'xml' THEN ''\n WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'\n ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')\n END\n + ' '\n + case when exists ( -- Identity skip\n select id from syscolumns\n where id = obj.id\n and name = column_name\n and columnproperty(id, name, 'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(obj.name) as varchar) + ',' + \n cast(ident_incr(obj.name) as varchar) + ')'\n else ''\n end + ' '\n + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END\n + 'NULL'\n + CASE WHEN IC.column_default IS NOT NULL THEN ' DEFAULT ' + IC.column_default ELSE '' END\n + ','\n FROM INFORMATION_SCHEMA.COLUMNS IC\n WHERE IC.table_name = obj.name\n AND IC.TABLE_SCHEMA = SCHEMA_NAME(obj.uid)\n ORDER BY ordinal_position\n FOR XML PATH('')\n ) cols (list)\n CROSS APPLY(\n SELECT\n CHAR(10) + 'ALTER TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] ADD ' + LEFT(alt, LEN(alt)-1)\n FROM(\n SELECT\n CHAR(10)\n + ' CONSTRAINT ' + tc.constraint_name\n + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'\n + COALESCE(CHAR(10) + r.list, ', ')\n FROM information_schema.table_constraints tc\n CROSS APPLY(\n SELECT '[' + kcu.column_name + '], '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.constraint_name = tc.constraint_name\n ORDER BY kcu.ordinal_position\n FOR XML PATH('')\n ) c (list)\n OUTER APPLY(\n -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema\n SELECT LEFT(f.list, LEN(f.list)-1) + ')' + IIF(rc.DELETE_RULE = 'NO ACTION', '', ' ON DELETE ' + rc.DELETE_RULE) + IIF(rc.UPDATE_RULE = 'NO ACTION', '', ' ON UPDATE ' + rc.UPDATE_RULE) + ', '\n FROM information_schema.referential_constraints rc\n CROSS APPLY(\n SELECT IIF(kcu.ordinal_position = 1, ' REFERENCES [' + kcu.table_schema + '].[' + kcu.table_name + '] (', '') \n + '[' + kcu.column_name + '], '\n FROM information_schema.key_column_usage kcu \n WHERE kcu.constraint_catalog = rc.unique_constraint_catalog AND kcu.constraint_schema = rc.unique_constraint_schema AND kcu.constraint_name = rc.unique_constraint_name\n ORDER BY kcu.ordinal_position\n FOR XML PATH('')\n ) f (list)\n WHERE rc.constraint_catalog = tc.constraint_catalog \n AND rc.constraint_schema = tc.constraint_schema \n AND rc.constraint_name = tc.constraint_name\n ) r (list)\n WHERE tc.table_name = obj.name\n FOR XML PATH('')\n ) a (alt)\n ) refs (list)\n WHERE xtype = 'U'\n SELECT Drop_Table + CHAR(10) + Create_Table FROM SysCreateTables\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
21,558
<p>I want to know what a "<em>virtual base class</em>" is and what it means.</p> <p>Let me show an example:</p> <pre><code>class Foo { public: void DoSomething() { /* ... */ } }; class Bar : public virtual Foo { public: void DoSpecific() { /* ... */ } }; </code></pre>
[ { "answer_id": 21607, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 10, "selected": true, "text": "class A { public: void Foo() {} };\nclass B : public A {};\nclass C : public A {};\nclass D : public B, public C {};\n A\n / \\\nB C\n \\ /\n D\n D d;\nd.Foo(); // is this B's Foo() or C's Foo() ??\n class A { public: void Foo() {} };\nclass B : public virtual A {};\nclass C : public virtual A {};\nclass D : public B, public C {};\n D d;\nd.Foo(); // no longer ambiguous\n" }, { "answer_id": 21629, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 3, "selected": false, "text": " B\n / \\\nD11 D12\n | |\nD21 D22\n \\ /\n DD\n" }, { "answer_id": 112474, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": false, "text": " A\n / \\\nB C\n \\ /\n D\n A A\n| |\nB C\n \\ /\n D\n D::foo() A class A\n{\n public :\n foo() ;\n int m_iValue ;\n} ;\n m_iValue D m_iValue B::m_iValue A::m_iValue B C::m_iValue A::m_iValue C foo() m_iValue A B C m_iValue D B C A m_iValue D m_iValues D m_iValue D D C B m_iValue m_iValue C C B" }, { "answer_id": 41026159, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 2, "selected": false, "text": "#include <cassert>\n\nclass A {\n public:\n A(){}\n A(int i) : i(i) {}\n int i;\n virtual int f() = 0;\n virtual int g() = 0;\n virtual int h() = 0;\n};\n\nclass B : public virtual A {\n public:\n B(int j) : j(j) {}\n int j;\n virtual int f() { return this->i + this->j; }\n};\n\nclass C : public virtual A {\n public:\n C(int k) : k(k) {}\n int k;\n virtual int g() { return this->i + this->k; }\n};\n\nclass D : public B, public C {\n public:\n D(int i, int j, int k) : A(i), B(j), C(k) {}\n virtual int h() { return this->i + this->j + this->k; }\n};\n\nint main() {\n D d = D(1, 2, 4);\n assert(d.f() == 3);\n assert(d.g() == 5);\n assert(d.h() == 7);\n}\n g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp\n./main.out\n virtual class B : public virtual A\n main.cpp:27:7: warning: virtual base ‘A’ inaccessible in ‘D’ due to ambiguity [-Wextra]\n 27 | class D : public B, public C {\n | ^\nmain.cpp: In member function ‘virtual int D::h()’:\nmain.cpp:30:40: error: request for member ‘i’ is ambiguous\n 30 | virtual int h() { return this->i + this->j + this->k; }\n | ^\nmain.cpp:7:13: note: candidates are: ‘int A::i’\n 7 | int i;\n | ^\nmain.cpp:7:13: note: ‘int A::i’\nmain.cpp: In function ‘int main()’:\nmain.cpp:34:20: error: invalid cast to abstract class type ‘D’\n 34 | D d = D(1, 2, 4);\n | ^\nmain.cpp:27:7: note: because the following virtual functions are pure within ‘D’:\n 27 | class D : public B, public C {\n | ^\nmain.cpp:8:21: note: ‘virtual int A::f()’\n 8 | virtual int f() = 0;\n | ^\nmain.cpp:9:21: note: ‘virtual int A::g()’\n 9 | virtual int g() = 0;\n | ^\nmain.cpp:34:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’\n 34 | D d = D(1, 2, 4);\n | ^\nIn file included from /usr/include/c++/9/cassert:44,\n from main.cpp:1:\nmain.cpp:35:14: error: request for member ‘f’ is ambiguous\n 35 | assert(d.f() == 3);\n | ^\nmain.cpp:8:21: note: candidates are: ‘virtual int A::f()’\n 8 | virtual int f() = 0;\n | ^\nmain.cpp:17:21: note: ‘virtual int B::f()’\n 17 | virtual int f() { return this->i + this->j; }\n | ^\nIn file included from /usr/include/c++/9/cassert:44,\n from main.cpp:1:\nmain.cpp:36:14: error: request for member ‘g’ is ambiguous\n 36 | assert(d.g() == 5);\n | ^\nmain.cpp:9:21: note: candidates are: ‘virtual int A::g()’\n 9 | virtual int g() = 0;\n | ^\nmain.cpp:24:21: note: ‘virtual int C::g()’\n 24 | virtual int g() { return this->i + this->k; }\n | ^\nmain.cpp:9:21: note: ‘virtual int A::g()’\n 9 | virtual int g() = 0;\n | ^\n./main.out\n" }, { "answer_id": 62281777, "author": "Lewis Kelsey", "author_id": 7194773, "author_profile": "https://Stackoverflow.com/users/7194773", "pm_score": 2, "selected": false, "text": "new new _GLIBCXX_WEAK_DEFINITION void *\noperator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)\n malloc A::function() Type::function() vtable for Base:\n .quad 0\n .quad typeinfo for Base\n .quad Base::CommonFunction()\n .quad Base::VirtualFunction()\n\npointer is typically to the first function i.e. \n\n mov edx, OFFSET FLAT:vtable for Base+16\n virtual override = 0 final = default = delete class Base\n {\n int a = 1;\n int b = 2;\n public:\n void virtual CommonFunction(){} ; //define empty method body\n void virtual VirtualFunction(){} ;\n };\n\n\nclass DerivedClass1: virtual public Base\n {\n int c = 3;\n public:\n void virtual DerivedCommonFunction(){} ;\n void virtual VirtualFunction(){} ;\n };\n \n class DerivedClass2 : virtual public Base\n {\n int d = 4;\n public:\n //void virtual DerivedCommonFunction(){} ; \n void virtual VirtualFunction(){} ;\n void virtual DerivedCommonFunction2(){} ;\n };\n\nclass DerivedDerivedClass : public DerivedClass1, public DerivedClass2\n {\n int e = 5;\n public:\n void virtual DerivedDerivedCommonFunction(){} ;\n void virtual VirtualFunction(){} ;\n };\n \n int main () {\n DerivedDerivedClass* d = new DerivedDerivedClass;\n d->VirtualFunction();\n d->DerivedCommonFunction();\n d->DerivedCommonFunction2();\n d->DerivedDerivedCommonFunction();\n ((DerivedClass2*)d)->DerivedCommonFunction2();\n ((Base*)d)->VirtualFunction();\n }\n new DerivedDerivedClass::DerivedDerivedClass() Base::Base() DerivedDerivedClass::DerivedDerivedClass() DerivedClass1::DerivedClass1() DerivedClass1::DerivedClass1() DerivedDerivedClass::DerivedDerivedClass() DerivedDerivedClass::DerivedDerivedClass() DerivedClass1::DerivedClass1() Base::Base() DerivedClass2::DerivedClass2() Base::Base() DerivedDerivedClass main:\n.LFB8:\n push rbp\n mov rbp, rsp\n push rbx\n sub rsp, 24\n mov edi, 48 //pass size to new\n call operator new(unsigned long) //call new\n mov rbx, rax //move the address of the allocation to rbx\n mov rdi, rbx //move it to rdi i.e. pass to the call\n call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor] //construct on this address\n mov QWORD PTR [rbp-24], rbx //store the address of the object on the stack as the d pointer variable on -O0, will be optimised off on -Ofast if the address of the pointer itself isn't taken in the code, because this address does not need to be on the stack, it can just be passed in a register to the subsequent methods\n DerivedDerivedClass d = DerivedDerivedClass() main main:\n push rbp\n mov rbp, rsp\n sub rsp, 48 // make room for and zero 48 bytes on the stack for the 48 byte object, no extra padding required as the frame is 64 bytes with `rbp` and return address of the function it calls (no stack params are passed to any function it calls), hence rsp will be aligned by 16 assuming it was aligned at the start of this frame\n mov QWORD PTR [rbp-48], 0\n mov QWORD PTR [rbp-40], 0\n mov QWORD PTR [rbp-32], 0\n mov QWORD PTR [rbp-24], 0\n mov QWORD PTR [rbp-16], 0\n mov QWORD PTR [rbp-8], 0\n lea rax, [rbp-48] // load the address of the cleared 48 bytes\n mov rdi, rax // pass the address as a pointer to the 48 bytes cleared as the first parameter to the constructor\n call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]\n //address is not stored on the stack because the object is used directly -- there is no pointer variable -- d refers to the object on the stack as opposed to being a pointer\n DerivedDerivedClass DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]:\n.LFB20:\n push rbp\n mov rbp, rsp\n sub rsp, 16\n mov QWORD PTR [rbp-8], rdi\n.LBB5:\n mov rax, QWORD PTR [rbp-8] // object address now in rax \n add rax, 32 //increment address by 32\n mov rdi, rax // move object address+32 to rdi i.e. pass to call\n call Base::Base() [base object constructor]\n mov rax, QWORD PTR [rbp-8] //move object address to rax\n mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+8 //move address of VTT+8 to edx\n mov rsi, rdx //pass VTT+8 address as 2nd parameter \n mov rdi, rax //object address as first (DerivedClass1 subobject)\n call DerivedClass1::DerivedClass1() [base object constructor]\n mov rax, QWORD PTR [rbp-8] //move object address to rax\n add rax, 16 //increment object address by 16\n mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+24 //store address of VTT+24 in edx\n mov rsi, rdx //pass address of VTT+24 as second parameter\n mov rdi, rax //address of DerivedClass2 subobject as first\n call DerivedClass2::DerivedClass2() [base object constructor]\n mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+24 //move this to edx\n mov rax, QWORD PTR [rbp-8] // object address now in rax\n mov QWORD PTR [rax], rdx. //store address of vtable for DerivedDerivedClass+24 at the start of the object\n mov rax, QWORD PTR [rbp-8] // object address now in rax\n add rax, 32 // increment object address by 32\n mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+120 //move this to edx\n mov QWORD PTR [rax], rdx //store vtable for DerivedDerivedClass+120 at object+32 (Base) \n mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+72 //store this in edx\n mov rax, QWORD PTR [rbp-8] //move object address to rax\n mov QWORD PTR [rax+16], rdx //store vtable for DerivedDerivedClass+72 at object+16 (DerivedClass2)\n mov rax, QWORD PTR [rbp-8]\n mov DWORD PTR [rax+28], 5 // stores e = 5 in the object\n.LBE5:\n nop\n leave\n ret\n DerivedDerivedClass Base::Base() Base::Base() [base object constructor]:\n.LFB11:\n push rbp\n mov rbp, rsp\n mov QWORD PTR [rbp-8], rdi //stores address of object on stack (-O0)\n.LBB2:\n mov edx, OFFSET FLAT:vtable for Base+16 //puts vtable for Base+16 in edx\n mov rax, QWORD PTR [rbp-8] //copies address of object from stack to rax\n mov QWORD PTR [rax], rdx //stores it address of object\n mov rax, QWORD PTR [rbp-8] //copies address of object on stack to rax again\n mov DWORD PTR [rax+8], 1 //stores a = 1 in the object\n mov rax, QWORD PTR [rbp-8] //junk from -O0\n mov DWORD PTR [rax+12], 2 //stores b = 2 in the object\n.LBE2:\n nop\n pop rbp\n ret\n DerivedDerivedClass::DerivedDerivedClass() DerivedClass1::DerivedClass1() VTT for DerivedDerivedClass+8 DerivedClass1::DerivedClass1() [base object constructor]:\n.LFB14:\n push rbp\n mov rbp, rsp\n mov QWORD PTR [rbp-8], rdi //address of object\n mov QWORD PTR [rbp-16], rsi //address of VTT+8\n.LBB3:\n mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax\n mov rdx, QWORD PTR [rax] //address of DerivedClass1-in-DerivedDerivedClass+24 now in rdx\n mov rax, QWORD PTR [rbp-8] //address of object now in rax\n mov QWORD PTR [rax], rdx //store address of DerivedClass1-in-.. in the object\n mov rax, QWORD PTR [rbp-8] // address of object now in rax\n mov rax, QWORD PTR [rax] //address of DerivedClass1-in.. now implicitly in rax\n sub rax, 24 //address of DerivedClass1-in-DerivedDerivedClass+0 now in rax\n mov rax, QWORD PTR [rax] //value of 32 now in rax\n mov rdx, rax // now in rdx\n mov rax, QWORD PTR [rbp-8] //address of object now in rax\n add rdx, rax //address of object+32 now in rdx\n mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax\n mov rax, QWORD PTR [rax+8] //derference VTT+8+8; address of DerivedClass1-in-DerivedDerivedClass+72 (Base::CommonFunction()) now in rax\n mov QWORD PTR [rdx], rax //store at address object+32 (offset to Base)\n mov rax, QWORD PTR [rbp-8] //store address of object in rax, return\n mov DWORD PTR [rax+8], 3 //store its attribute c = 3 in the object\n.LBE3:\n nop\n pop rbp\n ret\n VTT for DerivedDerivedClass:\n .quad vtable for DerivedDerivedClass+24\n .quad construction vtable for DerivedClass1-in-DerivedDerivedClass+24 //(DerivedClass1 uses this to write its vtable pointer)\n .quad construction vtable for DerivedClass1-in-DerivedDerivedClass+72 //(DerivedClass1 uses this to overwrite the base vtable pointer)\n .quad construction vtable for DerivedClass2-in-DerivedDerivedClass+24\n .quad construction vtable for DerivedClass2-in-DerivedDerivedClass+72\n .quad vtable for DerivedDerivedClass+120 // DerivedDerivedClass supposed to use this to overwrite Bases's vtable pointer\n .quad vtable for DerivedDerivedClass+72 // DerivedDerivedClass supposed to use this to overwrite DerivedClass2's vtable pointer\n//although DerivedDerivedClass uses vtable for DerivedDerivedClass+72 and DerivedDerivedClass+120 directly to overwrite them instead of going through the VTT\n\nconstruction vtable for DerivedClass1-in-DerivedDerivedClass:\n .quad 32\n .quad 0\n .quad typeinfo for DerivedClass1\n .quad DerivedClass1::DerivedCommonFunction()\n .quad DerivedClass1::VirtualFunction()\n .quad -32\n .quad 0\n .quad -32\n .quad typeinfo for DerivedClass1\n .quad Base::CommonFunction()\n .quad virtual thunk to DerivedClass1::VirtualFunction()\nconstruction vtable for DerivedClass2-in-DerivedDerivedClass:\n .quad 16\n .quad 0\n .quad typeinfo for DerivedClass2\n .quad DerivedClass2::VirtualFunction()\n .quad DerivedClass2::DerivedCommonFunction2()\n .quad -16\n .quad 0\n .quad -16\n .quad typeinfo for DerivedClass2\n .quad Base::CommonFunction()\n .quad virtual thunk to DerivedClass2::VirtualFunction()\nvtable for DerivedDerivedClass:\n .quad 32\n .quad 0\n .quad typeinfo for DerivedDerivedClass\n .quad DerivedClass1::DerivedCommonFunction()\n .quad DerivedDerivedClass::VirtualFunction()\n .quad DerivedDerivedClass::DerivedDerivedCommonFunction()\n .quad 16\n .quad -16\n .quad typeinfo for DerivedDerivedClass\n .quad non-virtual thunk to DerivedDerivedClass::VirtualFunction()\n .quad DerivedClass2::DerivedCommonFunction2()\n .quad -32\n .quad 0\n .quad -32\n .quad typeinfo for DerivedDerivedClass\n .quad Base::CommonFunction()\n .quad virtual thunk to DerivedDerivedClass::VirtualFunction()\n\nvirtual thunk to DerivedClass1::VirtualFunction():\n mov r10, QWORD PTR [rdi]\n add rdi, QWORD PTR [r10-32]\n jmp .LTHUNK0\nvirtual thunk to DerivedClass2::VirtualFunction():\n mov r10, QWORD PTR [rdi]\n add rdi, QWORD PTR [r10-32]\n jmp .LTHUNK1\nvirtual thunk to DerivedDerivedClass::VirtualFunction():\n mov r10, QWORD PTR [rdi]\n add rdi, QWORD PTR [r10-32]\n jmp .LTHUNK2\nnon-virtual thunk to DerivedDerivedClass::VirtualFunction():\n sub rdi, 16\n jmp .LTHUNK3\n\n .set .LTHUNK0,DerivedClass1::VirtualFunction()\n .set .LTHUNK1,DerivedClass2::VirtualFunction()\n .set .LTHUNK2,DerivedDerivedClass::VirtualFunction()\n .set .LTHUNK3,DerivedDerivedClass::VirtualFunction()\n\n\n DerivedDerivedClass DerivedDerivedClass DerivedDerivedClass DerivedDerivedClass::DerivedDerivedClass() DerivedDerivedClass+24 DerivedClass2::DerivedClass2() DerivedClass1::DerivedClass1() mov DWORD PTR [rax+8], 3 d = 4 DerivedDerivedClass d->VirtualFunction() main mov rax, QWORD PTR [rbp-24] //store pointer to object (and hence vtable pointer) in rax\n mov rax, QWORD PTR [rax] //dereference this pointer to vtable pointer and store virtual table pointer in rax\n add rax, 8 // add 8 to the pointer to get the 2nd function pointer in the table\n mov rdx, QWORD PTR [rax] //dereference this pointer to get the address of the method to call\n mov rax, QWORD PTR [rbp-24] //restore pointer to object in rax (-O0 is inefficient, yes)\n mov rdi, rax //pass object to the method\n call rdx\n d->DerivedCommonFunction(); mov rax, QWORD PTR [rbp-24]\n mov rdx, QWORD PTR [rbp-24]\n mov rdx, QWORD PTR [rdx]\n mov rdx, QWORD PTR [rdx]\n mov rdi, rax //pass object to method\n call rdx //call the first function in the table\n d->DerivedCommonFunction2(); mov rax, QWORD PTR [rbp-24] //get the object pointer\n lea rdx, [rax+16] //get the address of the 2nd subobject in the object\n mov rax, QWORD PTR [rbp-24] //get the object pointer\n mov rax, QWORD PTR [rax+16] // get the vtable pointer of the 2nd subobject\n add rax, 8 //call the 2nd function in this table\n mov rax, QWORD PTR [rax] //get the address of the 2nd function\n mov rdi, rdx //call it and pass the 2nd subobject to it\n call rax\n d->DerivedDerivedCommonFunction(); mov rax, QWORD PTR [rbp-24] //get the object pointer\n mov rax, QWORD PTR [rax] //get the vtable pointer\n add rax, 16 //get the 3rd function in the first virtual table (which is where virtual functions that that first appear in the most derived class go, because they belong to the full object which uses the virtual table pointer at the start of the object)\n mov rdx, QWORD PTR [rax] //get the address of the object\n mov rax, QWORD PTR [rbp-24]\n mov rdi, rax //call it and pass the whole object to it\n call rdx\n ((DerivedClass2*)d)->DerivedCommonFunction2(); //it casts the object to its subobject and calls the corresponding method in its virtual table, which will be a non-virtual thunk\n\n cmp QWORD PTR [rbp-24], 0\n je .L14\n mov rax, QWORD PTR [rbp-24]\n add rax, 16\n jmp .L15\n.L14:\n mov eax, 0\n.L15:\n cmp QWORD PTR [rbp-24], 0\n cmp QWORD PTR [rbp-24], 0\n je .L18\n mov rdx, QWORD PTR [rbp-24]\n add rdx, 16\n jmp .L19\n.L18:\n mov edx, 0\n.L19:\n mov rdx, QWORD PTR [rdx]\n add rdx, 8\n mov rdx, QWORD PTR [rdx]\n mov rdi, rax\n call rdx\n ((Base*)d)->VirtualFunction(); //it casts the object to its subobject and calls the corresponding function in its virtual table, which will be a virtual thunk\n\n cmp QWORD PTR [rbp-24], 0\n je .L20\n mov rax, QWORD PTR [rbp-24]\n mov rax, QWORD PTR [rax]\n sub rax, 24\n mov rax, QWORD PTR [rax]\n mov rdx, rax\n mov rax, QWORD PTR [rbp-24]\n add rax, rdx\n jmp .L21\n.L20:\n mov eax, 0\n.L21:\n cmp QWORD PTR [rbp-24], 0\n cmp QWORD PTR [rbp-24], 0\n je .L24\n mov rdx, QWORD PTR [rbp-24]\n mov rdx, QWORD PTR [rdx]\n sub rdx, 24\n mov rdx, QWORD PTR [rdx]\n mov rcx, rdx\n mov rdx, QWORD PTR [rbp-24]\n add rdx, rcx\n jmp .L25\n.L24:\n mov edx, 0\n.L25:\n mov rdx, QWORD PTR [rdx]\n add rdx, 8\n mov rdx, QWORD PTR [rdx]\n mov rdi, rax\n call rdx\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
21,564
<p>I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like:</p> <pre><code>cat somefile.txt | prepend-timestamp </code></pre> <p>(Before you answer sed, I tried this:</p> <pre><code>cat somefile.txt | sed "s/^/`date`/" </code></pre> <p>But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)</p>
[ { "answer_id": 21602, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 5, "selected": false, "text": "cat somefile.txt | perl -pne 'print scalar(localtime()), \" \";'\n tail -f /path/to/log | perl -pne 'print scalar(localtime()), \" \";' > /path/to/log-with-timestamps\n" }, { "answer_id": 21614, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "gawk '{print strftime(\"%d/%m/%y\",systime()) $0 }' < somefile.txt\n" }, { "answer_id": 21620, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 9, "selected": true, "text": "awk <command> | awk '{ print strftime(\"%Y-%m-%d %H:%M:%S\"), $0; fflush(); }'\n <command> awk gawk" }, { "answer_id": 21907, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": false, "text": "unbuffer <command> | awk '{ print strftime(\"%Y-%m-%d %H:%M:%S\"), $0; }'\n" }, { "answer_id": 21909, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 6, "selected": false, "text": "annotate-output devscripts $ echo -e \"a\\nb\\nc\" > lines\n$ annotate-output cat lines\n17:00:47 I: Started cat lines\n17:00:47 O: a\n17:00:47 O: b\n17:00:47 O: c\n17:00:47 I: Finished with exitcode 0\n" }, { "answer_id": 22441, "author": "caerwyn", "author_id": 2406, "author_profile": "https://Stackoverflow.com/users/2406", "pm_score": 3, "selected": false, "text": "$ cat timestamp\n#!/bin/sh\nwhile read line\ndo\n echo `date` $line\ndone\n$ cat somefile.txt | ./timestamp\n" }, { "answer_id": 436536, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#! /bin/sh\nunbuffer \"$@\" | perl -e '\nuse Time::HiRes (gettimeofday);\nwhile(<>) {\n ($s,$ms) = gettimeofday();\n print $s . \".\" . $ms . \" \" . $_;\n}'\n" }, { "answer_id": 5158624, "author": "ElGringoGeek", "author_id": 639872, "author_profile": "https://Stackoverflow.com/users/639872", "pm_score": 2, "selected": false, "text": "/\"pattern\"/ \"C\\:\\\\\\\\bin\\\\\\\\date '+%m/%d %R'\" | getline timestamp; print timestamp, $0; \"date '+%m/%d %R'\" | getline timestamp;\n" }, { "answer_id": 9613514, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 4, "selected": false, "text": "cat file | tai64n | tai64nlocal\n" }, { "answer_id": 9813614, "author": "Mark McKinstry", "author_id": 712655, "author_profile": "https://Stackoverflow.com/users/712655", "pm_score": 8, "selected": false, "text": "ts $ echo 'foo bar baz' | ts\nMar 21 18:07:28 foo bar baz\n$ echo 'blah blah blah' | ts '%F %T'\n2012-03-21 18:07:30 blah blah blah\n$ \n sudo apt-get install moreutils\n" }, { "answer_id": 18923989, "author": "crumplecrap", "author_id": 2800436, "author_profile": "https://Stackoverflow.com/users/2800436", "pm_score": 1, "selected": false, "text": "timestamp(){\n while read line\n do\n echo `date` $line\n done\n}\n\necho testing 123 |timestamp\n" }, { "answer_id": 19662206, "author": "Willem", "author_id": 604515, "author_profile": "https://Stackoverflow.com/users/604515", "pm_score": 5, "selected": false, "text": "unbuffer $COMMAND | ts\n sudo apt-get install expect-dev moreutils\n" }, { "answer_id": 27001032, "author": "orion elenzil", "author_id": 230851, "author_profile": "https://Stackoverflow.com/users/230851", "pm_score": 0, "selected": false, "text": "date tr xargs alias predate=\"xargs -I{} sh -c 'date +\\\"%Y-%m-%d %H:%M:%S\\\" | tr \\\"\\n\\\" \\\" \\\"; echo \\\"{}\\\"'\"\n<command> | predate\n alias predate=\"xargs -I{} sh -c 'date +\\\"%Y-%m-%d %H:%M:%S.%3N\\\" | tr \\\"\\n\\\" \\\" \\\"; echo \\\"{}\\\"'\"\n brew install coreutils alias predate=\"xargs -I{} sh -c 'gdate +\\\"%Y-%m-%d %H:%M:%S.%3N\\\" | tr \\\"\\n\\\" \\\" \\\"; echo \\\"{}\\\"'\"\n" }, { "answer_id": 33218664, "author": "Keymon", "author_id": 395686, "author_profile": "https://Stackoverflow.com/users/395686", "pm_score": 2, "selected": false, "text": "date tail -f log | perl -pne '\n use Time::HiRes (gettimeofday);\n use POSIX qw(strftime);\n ($s,$ms) = gettimeofday();\n print strftime \"%Y-%m-%dT%H:%M:%S+$ms \", gmtime($s);\n '\n tail -f log | perl -pne '\n use Time::HiRes (gettimeofday); use POSIX qw(strftime);\n $|=1;\n while(<>) {\n ($s,$ms) = gettimeofday();\n print strftime \"%Y-%m-%dT%H:%M:%S+$ms $_\", gmtime($s);\n }'\n" }, { "answer_id": 44746681, "author": "Momchil Atanasov", "author_id": 2852445, "author_profile": "https://Stackoverflow.com/users/2852445", "pm_score": 1, "selected": false, "text": "<command> | preftime" }, { "answer_id": 44786469, "author": "aleksandr barakin", "author_id": 4827341, "author_profile": "https://Stackoverflow.com/users/4827341", "pm_score": 2, "selected": false, "text": "$ cat somefile.txt | sed \"s/^/`date`/\"\n $ some-command | sed \"x;s/.*/date +%T/e;G;s/\\n/ /g\"\n $ { echo 'line1'; sleep 2; echo 'line2'; } | sed \"x;s/.*/date +%T/e;G;s/\\n/ /g\"\n20:24:22 line1\n20:24:24 line2\n date +%T" }, { "answer_id": 71806202, "author": "Lucas Wiman", "author_id": 303931, "author_profile": "https://Stackoverflow.com/users/303931", "pm_score": 1, "selected": false, "text": "[timestamp] [timestamp] stdout line \\nstderr line unbuffer stdbuf -i0 -o0 -e0 ruby -pe 'print Time.now.strftime(\\\"[%Y-%m-%d %H:%M:%S] \\\")' $_ ruby -pe '\\$_ = Time.now.strftime(\\\"[%Y-%m-%d %H:%M:%S] \\\") + \\$_' $_ alias tslines-pipe=\"stdbuf -i0 -o0 ruby -pe '\\$_ = Time.now.strftime(\\\"[%Y-%m-%d %H:%M:%S] \\\") + \\$_'\"\nfunction tslines() (\n stdbuf -o0 -e0 \"$@\" 2> >(tslines-pipe) > >(tslines-pipe)\n status=\"$?\"\n exit $status\n)\n tslines some command --options tslines tslines bash -c '(for (( i=1; i<=20; i++ )); do echo stderr 1>&2; echo stdout; done)'\n alias tslines-pipe=\"stdbuf -i0 -o0 ruby -pe '\\$_ = Time.now.strftime(\\\"[%Y-%m-%d %H:%M:%S] \\\") + \\$_'\"\nfunction tslines() (\n # Pick a random name for the pipe to prevent collisions.\n pipe=\"/tmp/pipe-$RANDOM\"\n \n # Ensure the pipe gets deleted when the method exits.\n trap \"rm -f $pipe\" EXIT\n\n # Create the pipe. See https://www.linuxjournal.com/content/using-named-pipes-fifos-bash\n mkfifo \"$pipe\"\n # echo will block until the pipe is read.\n stdbuf -o0 -e0 \"$@\" 2> >(tslines-pipe; echo \"done\" >> $pipe) > >(tslines-pipe; echo \"done\" >> $pipe)\n status=\"$?\"\n\n # Wait until we've received data from both pipe commands before exiting.\n linecount=0\n while [[ $linecount -lt 2 ]]; do\n read line\n if [[ \"$line\" == \"done\" ]]; then\n ((linecount++))\n fi\n done < \"$pipe\"\n exit $status\n)\n" }, { "answer_id": 71810273, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 0, "selected": false, "text": "strftime() echo \"abc 123 xyz\\njan 765 feb\" \\\n \\\n | gawk -Sbe 'BEGIN {_=strftime()\" \"} sub(\"^\",_)'\n\n Sat Apr 9 13:14:53 EDT 2022 abc 123 xyz\n Sat Apr 9 13:14:53 EDT 2022 jan 765 feb\n mawk 1.3.4. awk echo \"abc 123 xyz\\njan 765 feb\" \\\n\\\n| mawk2 'BEGIN { (__=\"date\")|getline _;\n close(__)\n _=_\" \" } sub(\"^\",_)'\n \nSat Apr 9 13:19:38 EDT 2022 abc 123 xyz\nSat Apr 9 13:19:38 EDT 2022 jan 765 feb\n mawk2 'sub(\"^\",_\" \")' \\_=\"$(date)\"\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156/" ]
21,574
<p>I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?</p>
[ { "answer_id": 21621, "author": "Tim Sullivan", "author_id": 722, "author_profile": "https://Stackoverflow.com/users/722", "pm_score": 8, "selected": true, "text": "irb(main):001:0> ?c\n=> \"c\"\n irb(main):001:0> ?c\n=> 99\n irb(main):001:0> \"cat\"[1]\n=> \"a\"\n irb(main):001:0> \"cat\"[1]\n=> 97\n irb(main):002:0> {1,2}\nSyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC\n irb(main):001:0> {1,2}\n=> {1=>2}\n Array.to_s irb(main):001:0> [1,2,3].to_s\n=> \"[1, 2, 3]\"\n irb(main):001:0> [1,2,3].to_s\n=> \"123\"\n irb(main):001:0> case 'a'; when /\\w/: puts 'word'; end\nSyntaxError: (irb):1: syntax error, unexpected ':',\nexpecting keyword_then or ',' or ';' or '\\n'\n irb(main):001:0> case 'a'; when /\\w/: puts 'word'; end\nword\n irb(main):001:0> i=0; [1,2,3].each {|i|}; i\n=> 0\nirb(main):002:0> i=0; for i in [1,2,3]; end; i\n=> 3\n irb(main):001:0> i=0; [1,2,3].each {|i|}; i\n=> 3\n Hash.index irb(main):001:0> {1=>2}.index(2)\n(irb):18: warning: Hash#index is deprecated; use Hash#key\n=> 1\nirb(main):002:0> {1=>2}.key(2)\n=> 1\n irb(main):001:0> {1=>2}.index(2)\n=> 1\n Fixnum.to_sym irb(main):001:0> 5.to_sym\nNoMethodError: undefined method 'to_sym' for 5:Fixnum\n irb(main):001:0> 5.to_sym\n=> nil\n # Find an argument value by name or index.\ndef [](index)\n lookup(index.to_sym)\nend\n irb(main):001:0> {:a=>\"a\", :c=>\"c\", :b=>\"b\"}\n=> {:a=>\"a\", :c=>\"c\", :b=>\"b\"}\n irb(main):001:0> {:a=>\"a\", :c=>\"c\", :b=>\"b\"}\n=> {:a=>\"a\", :b=>\"b\", :c=>\"c\"}\n irb(main):001:0> /\\x80/u\nSyntaxError: (irb):2: invalid multibyte escape: /\\x80/\n irb(main):001:0> /\\x80/u\n=> /\\x80/u\n tr Regexp unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT).\n gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR).\n gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]}\n pack unpack def xchr(escape=true)\n n = XChar::CP1252[self] || self\n case n when *XChar::VALID\n XChar::PREDEFINED[n] or \n (n>128 ? n.chr : (escape ? \"&##{n};\" : [n].pack('U*')))\n else\n Builder::XChar::REPLACEMENT_CHAR\n end\nend\nunpack('U*').map {|n| n.xchr(escape)}.join\n BasicObject BlankSlate irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f\nNameError: uninitialized constant C::Math\n irb(main):001:0> require 'blankslate'\n=> true\nirb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f\n=> 3.14159265358979\n irb(main):002:0> class C < SimpleDelegator; end\n=> nil\nirb(main):003:0> C.new('').class\n=> String\n irb(main):002:0> class C < SimpleDelegator; end\n=> nil\nirb(main):003:0> C.new('').class\n=> C\nirb(main):004:0>\n irb(main):004:1> $KCODE = 'UTF8'\n(irb):4: warning: variable $KCODE is no longer effective; ignored\n=> \"UTF8\"\n irb(main):001:0> $KCODE = 'UTF8'\n=> \"UTF8\"\n instance_methods irb(main):001:0> {}.methods.sort.last\n=> :zip\n irb(main):001:0> {}.methods.sort.last\n=> \"zip\"\n # coding: utf-8\n # -*- encoding: utf-8 -*-\n #!/usr/local/rubybook/bin/ruby\n# encoding: utf-8\n {a: b}\n\nredirect_to action: show\n {:a => b}\n\nredirect_to :action => show\n [1,2].each {|value; t| t=value*value}\n [1,2].inject(:+)\n [1,2].inject {|a,b| a+b}\n to_enum short_enum = [1, 2, 3].to_enum\nlong_enum = ('a'..'z').to_enum\nloop do\n puts \"#{short_enum.next} #{long_enum.next}\"\nend\n e = [1,2,3].each\n p = -> a,b,c {a+b+c}\nputs p.(1,2,3)\nputs p[1,2,3]\n p = lambda {|a,b,c| a+b+c}\nputs p.call(1,2,3)\n Complex(3,4) == 3 + 4.im\n irb(main):001:0> 1.2-1.1\n=> 0.0999999999999999\n /\\p{Space}/\n /[:space:]/\n def foo(first, *middle, last)\n\n(->a, *b, c {p a-c}).(*5.downto(1))\n f = Fiber.new do\n a,b = 0,1\n Fiber.yield a\n Fiber.yield b\n loop do\n a,b = b,a+b\n Fiber.yield b\n end\nend\n10.times {puts f.resume}\n match =\n while line = gets\n next if line =~ /^#/\n break line if line.find('ruby')\n end\n def toggle\n def toggle\n \"subsequent times\"\n end\n \"first time\"\nend\n" }, { "answer_id": 22941140, "author": "Wim Yedema", "author_id": 3224442, "author_profile": "https://Stackoverflow.com/users/3224442", "pm_score": 1, "selected": false, "text": "def function\n return *[1]\nend\n\na=function\n def function(array)\n array.each { |v| p v }\nend\nfunction \"1\"\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
21,583
<p>This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements. I ran into some trouble when I tried to test against the database. To my understanding, unit tests should be:</p> <ul> <li>stateless</li> <li>independent from each other</li> <li>repeatable with the same results i.e. no persisting changes</li> </ul> <p>These requirements seem to be at odds with each other when developing for a database. For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first. But, what if they aren't already there? Then I would need to call the Exists() function first.</p> <p>My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems. This is sacrificing on the independence of the tests while maintaining their statelessness.</p> <p>Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like <a href="http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx" rel="noreferrer">Roy Osherove's XtUnit</a>. This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand.</p> <p>So, what has the SO community done when confronted with this situation?</p> <hr> <p>tgmdbm said:</p> <blockquote> <p>You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing <strong>how your concrete classes interact with each other and with the database</strong>.</p> </blockquote> <p>So if I read this correctly, there is really no way to <em>effectively</em> unit-test a Data Access Layer. Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database?</p>
[ { "answer_id": 23297120, "author": "Mustafa Ekici", "author_id": 687817, "author_profile": "https://Stackoverflow.com/users/687817", "pm_score": 1, "selected": false, "text": " [TestFixture]\n public class TrannsactionScopeTests\n {\n private TransactionScope trans = null;\n\n [SetUp]\n public void SetUp()\n {\n trans = new TransactionScope(TransactionScopeOption.Required);\n }\n\n [TearDown]\n public void TearDown()\n {\n trans.Dispose();\n }\n\n [Test]\n public void TestServicedSameTransaction()\n {\n MySimpleClass c = new MySimpleClass();\n long id = c.InsertCategoryStandard(\"whatever\");\n long id2 = c.InsertCategoryStandard(\"whatever\");\n Console.WriteLine(\"Got id of \" + id);\n Console.WriteLine(\"Got id of \" + id2);\n Assert.AreNotEqual(id, id2);\n }\n }\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
21,589
<p>I did some tests a while ago and never figured out how to make this work. </p> <p><strong>The ingredients:</strong></p> <ul> <li>COM+ transactional object (developed in VB6) </li> <li>.Net web application (with transaction) in IIS that...<br> makes a call to the COM+ component<br> updates a row in a SQL database</li> </ul> <p><strong>Testing:</strong> </p> <p>Run the .Net application and force an exception. </p> <p><strong>Result:</strong> </p> <p>The update made from the .Net application rolls back.<br> The update made by the COM+ object does not roll back.</p> <p>If I call the COM+ object from an old ASP page the rollback works.</p> <p>I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.</p>
[ { "answer_id": 66513, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 3, "selected": true, "text": "void SomeMethod()\n{\n EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full;\n using (TransactionScope s = new TransactionScope(e))\n {\n MyComPlusClass o = new MyComPlusClass();\n\n o.SomeTransactionalMethod();\n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328/" ]
21,593
<p>What is the difference between using angle brackets and quotes in an <code>include</code> directive?</p> <ul> <li><code>#include &lt;filename&gt;</code></li> <li><code>#include &quot;filename&quot;</code></li> </ul>
[ { "answer_id": 21594, "author": "quest49", "author_id": 2399, "author_profile": "https://Stackoverflow.com/users/2399", "pm_score": 11, "selected": false, "text": "#include <filename> #include \"filename\"" }, { "answer_id": 41538, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<file> -I \"file\" -I # include <h-char-sequence> new-line # include \"q-char-sequence\" new-line # include <h-char-sequence> new-line \"xxx\" <xxx>" }, { "answer_id": 50266, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 8, "selected": false, "text": "#include \"file\" #include <file> #include #include" }, { "answer_id": 77092, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 10, "selected": false, "text": "#include <h-char-sequence> new-line\n < > #include \"q-char-sequence\" new-line\n \" #include <h-char-sequence> new-line\n > #include pp-tokens new-line\n include < > \" > \"" }, { "answer_id": 4932605, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 6, "selected": false, "text": "\"mypath/myfile\" is short for ./mypath/myfile\n . #include default_include_paths <mypath/myfile> is short for <defaultincludepaths>/mypath/myfile\n ./ <default_include_paths> mypath/myfile" }, { "answer_id": 4932607, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 4, "selected": false, "text": "#include \"\" #include <>" }, { "answer_id": 7589297, "author": "Barbara", "author_id": 969921, "author_profile": "https://Stackoverflow.com/users/969921", "pm_score": 3, "selected": false, "text": "#include \"filename\" // User defined header\n#include <filename> // Standard library header.\n Seller.h #ifndef SELLER_H // Header guard\n#define SELLER_H // Header guard\n\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nclass Seller\n{\n private:\n char name[31];\n double sales_total;\n\n public:\n Seller();\n Seller(char[], double);\n char*getName();\n\n#endif\n Seller.cpp Seller.h #include \"Seller.h\"\n" }, { "answer_id": 11576616, "author": "Yann Droneaud", "author_id": 611560, "author_profile": "https://Stackoverflow.com/users/611560", "pm_score": 7, "selected": false, "text": "#include \"file.h\" ./file.h . #include #include <file.h> /usr/include/file.h /usr/include" }, { "answer_id": 13910243, "author": "AndroidDev", "author_id": 1085742, "author_profile": "https://Stackoverflow.com/users/1085742", "pm_score": 4, "selected": false, "text": "#include <> #include <iostream>\n #include \" \" myfile.h #include \"myfile.h\"\n" }, { "answer_id": 22011884, "author": "sp2danny", "author_id": 3202093, "author_profile": "https://Stackoverflow.com/users/3202093", "pm_score": 4, "selected": false, "text": "#include <list> #include <xxx>" }, { "answer_id": 25535615, "author": "srsci", "author_id": 1216268, "author_profile": "https://Stackoverflow.com/users/1216268", "pm_score": 3, "selected": false, "text": "#include <filename> /usr/include /usr/local/include #include \"filename\"" }, { "answer_id": 26372302, "author": "riderBill", "author_id": 4079867, "author_profile": "https://Stackoverflow.com/users/4079867", "pm_score": 4, "selected": false, "text": "\"myApp.hpp\" <libHeader.hpp> /I INCLUDE #include \"../../MyProgDir/SourceDir1/someFile.hpp\"\n \"./myHeader.h\" /I INCLUDE /I INCLUDE" }, { "answer_id": 29418258, "author": "Hafiz Shehbaz Ali", "author_id": 2189932, "author_profile": "https://Stackoverflow.com/users/2189932", "pm_score": 3, "selected": false, "text": "#include <filename> #include \"path-to-file/filename\"" }, { "answer_id": 32064944, "author": "skyking", "author_id": 4498329, "author_profile": "https://Stackoverflow.com/users/4498329", "pm_score": 5, "selected": false, "text": "#include <h-char-sequence> new-line\n < > #include \"q-char-sequence\" new-line\n \" #include <h-char-sequence> new-line\n > #include pp-tokens new-line\n include < > \" > \" <stdio.h> #include \"...\" #include #include <...>" }, { "answer_id": 41646905, "author": "Suraj Jain", "author_id": 5473170, "author_profile": "https://Stackoverflow.com/users/5473170", "pm_score": 6, "selected": false, "text": "‘#include’ #include <file> -I #include \"file\" <file> -iquote ‘#include’ #include <x/*y> x/*y #include \"x\\n\\\\y\" ‘/’ ‘/’" }, { "answer_id": 41807677, "author": "Christy Wald", "author_id": 7109320, "author_profile": "https://Stackoverflow.com/users/7109320", "pm_score": 3, "selected": false, "text": "#include <abc.h>\n #include \"xyz.h\"\n -I" }, { "answer_id": 49226070, "author": "adrian", "author_id": 5487769, "author_profile": "https://Stackoverflow.com/users/5487769", "pm_score": 6, "selected": false, "text": "#include <file.h> file.h #include \"file\" file -I -I includes myheader.h #include <myheader.h> -I . -I #include \"myheader.h\" myheader.h include" }, { "answer_id": 49789599, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 4, "selected": false, "text": "#include <filename> #include \"filename\"" }, { "answer_id": 51907153, "author": "LocalHost", "author_id": 9121710, "author_profile": "https://Stackoverflow.com/users/9121710", "pm_score": -1, "selected": false, "text": "#include\"filename\"\n#include<filename>\n #include\"mylib.h\"\n mylib.h #include<mylib.h>\n mylib.h" }, { "answer_id": 52633884, "author": "Hogstrom", "author_id": 6943197, "author_profile": "https://Stackoverflow.com/users/6943197", "pm_score": 2, "selected": false, "text": "cpp -v /dev/null -o /dev/null" }, { "answer_id": 59496298, "author": "Kalana", "author_id": 11383441, "author_profile": "https://Stackoverflow.com/users/11383441", "pm_score": 3, "selected": false, "text": "#include <filename> #include \"filename\" #include <filename> #include <filename>" }, { "answer_id": 60480645, "author": "IAmAUser", "author_id": 12739607, "author_profile": "https://Stackoverflow.com/users/12739607", "pm_score": 2, "selected": false, "text": "#include <file> \n #include \"file\" \n" }, { "answer_id": 66401239, "author": "Paul Yang", "author_id": 15039201, "author_profile": "https://Stackoverflow.com/users/15039201", "pm_score": 2, "selected": false, "text": "\"\" ./ gcc -v -o a a.c\n // a.c\n#include \"stdio.h\"\nint main() {\n int a = 3;\n printf(\"a = %d\\n\", a);\n return 0;\n\n}\n // b.c\n#include <stdio.h>\nint main() {\n int a = 3;\n printf(\"a = %d\\n\", a);\n return 0;\n\n}\n stdio.h // stdio.h\ninline int foo()\n{\n return 10;\n}\n a.c b.c d.c // d.c\n#include <stdio.h>\n#include \"stdio.h\"\nint main()\n{\n int a = 0;\n\n a = foo();\n\n printf(\"a=%d\\n\", a);\n\n return 0;\n}\n" }, { "answer_id": 68311198, "author": "david", "author_id": 1335492, "author_profile": "https://Stackoverflow.com/users/1335492", "pm_score": 0, "selected": false, "text": "#include <myFilename> #include \"myFilename\"" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2399/" ]
21,635
<p>I have a product which has been traditionally shipped as an MSI file. It is deployed through some sort of SMS push to thousands of desktops by our various clients. The software we use to create these installers is getting long in the tooth and we are looking to replace it. We have already standardized on InstallAnywhere for most of our products as we support many operating systems. Unfortunately InstallAnywhere cannot produce MSI files. </p> <p>I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe). If not, are there any open source programmes for creating MSI files? </p>
[ { "answer_id": 21650, "author": "Chris", "author_id": 2134, "author_profile": "https://Stackoverflow.com/users/2134", "pm_score": 2, "selected": false, "text": "MSI WiX 3.0 Dark" }, { "answer_id": 21726, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 3, "selected": true, "text": "Active Directory / Group Policy Objects" }, { "answer_id": 21775, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 1, "selected": false, "text": "ZAP MSI" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
21,640
<p>Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:</p> <p><code>http://www.mywebsite.com:80/pages/page1.aspx</code></p> <p>I need to return:</p> <p><code>http://www.mywebsite.com:80</code></p> <p>I know I can use <code>Request.Url.AbsoluteUri</code> to get the complete URL, and I know I can use <code>Request.Url.Authority</code> to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.</p> <p>Any suggestions?</p>
[ { "answer_id": 21653, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 5, "selected": false, "text": "Uri url = Request.Url;\nstring protocol = url.Scheme;\n" }, { "answer_id": 22361, "author": "Rick", "author_id": 4367, "author_profile": "https://Stackoverflow.com/users/4367", "pm_score": 9, "selected": true, "text": "Uri uri = new Uri(\"http://www.mywebsite.com:80/pages/page1.aspx\");\nstring requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + \":\" + uri.Port;\n" }, { "answer_id": 578083, "author": "dthrasher", "author_id": 19112, "author_profile": "https://Stackoverflow.com/users/19112", "pm_score": 9, "selected": false, "text": "Uri.GetLeftPart() Uri url = new Uri(\"http://www.mywebsite.com:80/pages/page1.aspx\");\nstring output = url.GetLeftPart(UriPartial.Authority);\n GetLeftPart() GetLeftPart() http://www.mywebsite.com" }, { "answer_id": 4195319, "author": "Holger", "author_id": 317431, "author_profile": "https://Stackoverflow.com/users/317431", "pm_score": 6, "selected": false, "text": "var scheme = Request.Url.Scheme; // will get http, https, etc.\nvar host = Request.Url.Host; // will get www.mywebsite.com\nvar port = Request.Url.Port; // will get the port\nvar path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx\n" }, { "answer_id": 5238832, "author": "Haonan Tan", "author_id": 650550, "author_profile": "https://Stackoverflow.com/users/650550", "pm_score": 5, "selected": false, "text": "var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);\n" }, { "answer_id": 32615682, "author": "Mark Shapiro", "author_id": 789680, "author_profile": "https://Stackoverflow.com/users/789680", "pm_score": 5, "selected": false, "text": "string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)\n" }, { "answer_id": 33714244, "author": "benscabbia", "author_id": 3828228, "author_profile": "https://Stackoverflow.com/users/3828228", "pm_score": 4, "selected": false, "text": "Uri uri = Context.Request.Url; \nvar scheme = uri.Scheme // returns http, https\nvar scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://\nvar host = uri.Host; // return www.mywebsite.com\nvar port = uri.Port; // returns port number\n LocalHost Port Number var Uri uri = Context.Request.Url;\nvar host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + \":\" + uri.Port; \n http://localhost:12345" }, { "answer_id": 73877202, "author": "Kashif Usman I", "author_id": 15583595, "author_profile": "https://Stackoverflow.com/users/15583595", "pm_score": -1, "selected": false, "text": "Uri uri = new Uri(\"http://www.mywebsite.com:80/pages/page1.aspx\");\nstring requested = uri.Scheme + Uri.SchemeDelimiter + uri.Authority;\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2076253/" ]
21,647
<p>The following <strong>C++</strong> code uses a <strong>ifstream</strong> object to read integers from a text file (which has one number per line) until it hits <strong>EOF</strong>. Why does it read the integer on the last line twice? How to fix this?</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile &gt;&gt; x; cerr &lt;&lt; x &lt;&lt; endl; } return 0; } </code></pre> <p><strong>input.txt</strong>:</p> <pre><code>10 20 30 </code></pre> <p><strong>Output</strong>:</p> <pre><code>10 20 30 30 </code></pre> <p><strong>Note</strong>: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).</p>
[ { "answer_id": 21656, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 8, "selected": true, "text": "while (true) {\n int x;\n iFile >> x;\n if( iFile.eof() ) break;\n cerr << x << endl;\n}\n" }, { "answer_id": 21666, "author": "Patrick Loz", "author_id": 2091, "author_profile": "https://Stackoverflow.com/users/2091", "pm_score": 5, "selected": false, "text": "ifstream iFile(\"input.txt\"); // input.txt has integers, one per line\nint x;\n\nwhile (iFile >> x) \n{\n cerr << x << endl;\n}\n" }, { "answer_id": 21787, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "#include <iterator>\n#include <algorithm>\n\n// ...\n\n copy(istream_iterator<int>(iFile), istream_iterator<int>(),\n ostream_iterator<int>(cerr, \"\\n\"));\n" }, { "answer_id": 14836904, "author": "Solostaran14", "author_id": 1033530, "author_profile": "https://Stackoverflow.com/users/1033530", "pm_score": 3, "selected": false, "text": "while (!iFile.eof())\n{ \n int x;\n iFile >> x;\n if (!iFile.eof()) break;\n cerr << x << endl;\n}\n" }, { "answer_id": 15958291, "author": "user1384482", "author_id": 1384482, "author_profile": "https://Stackoverflow.com/users/1384482", "pm_score": 2, "selected": false, "text": "int x;\nifile >> x\n\nwhile (!iFile.eof())\n{ \n cerr << x << endl; \n iFile >> x; \n}\n" }, { "answer_id": 27273529, "author": "Brian Jack", "author_id": 669580, "author_profile": "https://Stackoverflow.com/users/669580", "pm_score": 3, "selected": false, "text": "int x;\n\niFile >> x; // prime read here\nwhile (!iFile.eof()) {\n cerr << x << endl;\n iFile >> x;\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
21,652
<p>I have some code that gives a user id to a utility that then send email to that user.</p> <pre><code>emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } </code></pre> <p><code>MailException</code> could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.</p> <p>My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.</p> <p><strong>Edit:</strong> As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a <strong>valid</strong> email address, or it could fail.. etc.</p> <p>My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).</p> <p>Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.</p>
[ { "answer_id": 21858, "author": "niklasfi", "author_id": 2275, "author_profile": "https://Stackoverflow.com/users/2275", "pm_score": -1, "selected": false, "text": "throw new exception(\"WhatCausedIt\")\n" }, { "answer_id": 138532, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 4, "selected": true, "text": "throws SpecificException1, SpecificException2, SpecificException3 ...\n throws GeneralException\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
21,669
<p>I didn't get the answer to this anywhere. What is the runtime complexity of a Regex match and substitution?</p> <p>Edit: I work in python. But would like to know in general about most popular languages/tools (java, perl, sed).</p>
[ { "answer_id": 766514, "author": "jpalecek", "author_id": 51831, "author_profile": "https://Stackoverflow.com/users/51831", "pm_score": 3, "selected": false, "text": "O(m*n+m) m n m O(m) O(m^2+n) O(2^m) O(n^2*m) a*a*" }, { "answer_id": 63529950, "author": "Peter Franek", "author_id": 1119629, "author_profile": "https://Stackoverflow.com/users/1119629", "pm_score": 0, "selected": false, "text": "re" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
21,697
<p>I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns.</p> <p>So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:</p> <pre><code>public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view) : this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } </code></pre> <p>I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.</p> <p>Let's say the following Service Layer messages can show up:</p> <ul> <li>E-mail account already exists (failure)</li> <li>Refering user entered does not exist (failure)</li> <li>Password length exceeds datastore allowed length (failure)</li> <li>Member created successfully (success)</li> </ul> <p>Let's also say that more rules will be in the service layer that the UI cannot anticipate.</p> <p>Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.</p> <hr> <blockquote> <p><strong>Edit not by OP: merging in follow-up comments that were posted as answers by the OP</strong></p> </blockquote> <hr> <p>Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.</p> <p>tgmdbm, I like the clever use of the lambda expression there!</p> <hr> <p>Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.</p> <p>However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?</p> <p>Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:</p> <p><img src="https://i.stack.imgur.com/HOJU7.png" alt="Create a user"></p> <p>For this kind of error, it's nice to report it to the same view. </p> <p>Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.</p>
[ { "answer_id": 22043, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 5, "selected": true, "text": "try {\n // call service etc.\n // handle success to view\n} \ncatch (AccountAlreadyExistsException) {\n // set the message and some other unique data in the view\n}\ncatch (ServiceLayerException) {\n // set the message in the view\n}\n// system exceptions, and unrecoverable exceptions are allowed to bubble \n// up the call stack so a general error can be shown to the user, rather \n// than showing the form again.\n" }, { "answer_id": 22586, "author": "tgmdbm", "author_id": 1851, "author_profile": "https://Stackoverflow.com/users/1851", "pm_score": 2, "selected": false, "text": "public static class Try {\n public static List<string> This( Action action ) {\n var errors = new List<string>();\n try {\n action();\n }\n catch ( SpecificException e ) {\n errors.Add( \"Something went 'orribly wrong\" );\n }\n catch ( ... )\n // ...\n return errors;\n }\n}\n var errors = Try.This( () => {\n // call your service here\n tasks.CreateMember( ... );\n} );\n" }, { "answer_id": 25030, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 1, "selected": false, "text": "<bean id=\"exceptionResolver\"\n class=\"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver\">\n\n <property name=\"exceptionMappings\">\n <props>\n <prop key=\"UserNotFoundException\">\n rescues/UserNotFound\n </prop>\n <prop key=\"HibernateJdbcException\">\n rescues/databaseProblem\n </prop>\n <prop key=\"java.net.ConnectException\">\n rescues/networkTimeout\n </prop>\n <prop key=\"ValidationException\">\n rescues/validationError\n </prop>\n <prop key=\"EnvironmentNotConfiguredException\">\n rescues/environmentNotConfigured\n </prop>\n <prop key=\"MessageRejectedPleaseRetryException\">\n rescues/messageRejected\n </prop>\n </props>\n </property>\n <property name=\"defaultErrorView\" value=\"rescues/general\" />\n</bean>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1894/" ]
21,698
<p>I'm trying to write a RegEx for a code generator (in C#) to determine a proper class or package name of an AS3 class.</p> <p>I know that class names</p> <ul> <li>must start with a letter (capital or otherwise)</li> <li>any other digit can be alphanumeric</li> <li>cannot have spaces</li> </ul> <p>Is there anything else?</p>
[ { "answer_id": 22290, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 1, "selected": false, "text": "public class $Test {}\npublic class _Test {}\npublic class test {}\n" }, { "answer_id": 72319, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 2, "selected": false, "text": "useful_thing" }, { "answer_id": 82938, "author": "Martin", "author_id": 15840, "author_profile": "https://Stackoverflow.com/users/15840", "pm_score": 2, "selected": false, "text": "import com.yourdomain.nameofsubfolder.YourSpecialClass;\n import flash.events.MouseEvent;\nimport flash.display.MovieClip;\n Styleable Drawable Movable IEventDispatcher\nIExternalizable \nIFocusManager\n flash.*" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1306/" ]
21,715
<p>Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable</p> <p>IE:</p> <pre><code>public class CollectionBase : IEnumerable </code></pre> <p>and then would derive their Business Object collections from that.</p> <pre><code>public class BusinessObjectCollection : CollectionBase </code></pre> <p>Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:</p> <pre><code>public class BusinessObjectCollection : List&lt;BusinessObject&gt; </code></pre> <p>I do this because I like to have strongly typed names instead of just passing Lists around.</p> <p>What is <strong>your</strong> approach?</p>
[ { "answer_id": 21722, "author": "Scott Muc", "author_id": 1894, "author_profile": "https://Stackoverflow.com/users/1894", "pm_score": 2, "selected": false, "text": "public class BusinessObjectCollection : List<BusinessObject> {}\n public IEnumerable<BusinessObject> GetBusinessObjects();\n" }, { "answer_id": 21724, "author": "jeremcc", "author_id": 1436, "author_profile": "https://Stackoverflow.com/users/1436", "pm_score": 2, "selected": false, "text": "List<T> LoadAll()" }, { "answer_id": 21730, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 3, "selected": false, "text": "List<BusinessObject> List<BusinessObject> List List<BusinessObject> BusinessObjectCollection" }, { "answer_id": 21786, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 7, "selected": true, "text": "IEnumerable var d = new Dictionary<string, int>\n{\n {\"hello\", 0},\n {\"the answer to life the universe and everything is:\", 42}\n};\n class c1 : IEnumerable\n{\n void Add(int x1, int x2, int x3)\n {\n //...\n }\n\n //...\n}\n var x = new c1\n{\n {1,2,3},\n {4,5,6}\n}\n List<Customer> var x = new List<Customer>\n{\n new Customer(\"Scott Wisniewski\", \"555-555-5555\", \"Seattle\", \"WA\"),\n new Customer(\"John Doe\", \"555-555-1234\", \"Los Angeles\", \"CA\"),\n new Customer(\"Michael Scott\", \"555-555-8769\", \"Scranton PA\"),\n new Customer(\"Ali G\", \"\", \"Staines\", \"UK\")\n}\n class CustomerList : List<Customer>\n{\n public void Add(string name, string phoneNumber, string city, string stateOrCountry)\n {\n Add(new Customer(name, phoneNumber, city, stateOrCounter));\n }\n}\n var customers = new CustomerList\n{\n {\"Scott Wisniewski\", \"555-555-5555\", \"Seattle\", \"WA\"},\n {\"John Doe\", \"555-555-1234\", \"Los Angeles\", \"CA\"},\n {\"Michael Scott\", \"555-555-8769\", \"Scranton PA\"},\n {\"Ali G\", \"\", \"Staines\", \"UK\"}\n}\n List<T>" }, { "answer_id": 43133, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": -1, "selected": false, "text": "IEnumerable<T>" }, { "answer_id": 75319, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "public MyTypeCollection : List<MyType>\n" }, { "answer_id": 192059, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "using BusinessObjectCollection = List<BusinessObject>;\n" }, { "answer_id": 394843, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 0, "selected": false, "text": "System.Collections.ObjectModel.Collection<BusinessObject>\n" }, { "answer_id": 483504, "author": "Ed Blackburn", "author_id": 27962, "author_profile": "https://Stackoverflow.com/users/27962", "pm_score": 2, "selected": false, "text": "public OrderItemCollection : IEnumerable<OrderItem> \n{\n private readonly List<OrderItem> _orderItems = new List<OrderItem>();\n\n void Add(OrderItem item)\n {\n _orderItems.Add(item)\n }\n\n //implement only the list members, which are required from your domain. \n //ie. sum items, calculate weight etc...\n\n private IEnumerator<string> Enumerator() {\n return _orderItems.GetEnumerator();\n }\n\n public IEnumerator<string> GetEnumerator() {\n return Enumerator();\n } \n}\n" }, { "answer_id": 483590, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 2, "selected": false, "text": "List<BusinessObject> BusinessObject IEnumerable<T> IList<T> ReadOnlyCollection<T> public static int SomeCount(this IEnumerable<BusinessObject> someList)\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
21,725
<p>What are your favorite (G)Vim plugins/scripts?</p>
[ { "answer_id": 26092, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "ctags" }, { "answer_id": 58846, "author": "Dominic Dos Santos", "author_id": 5379, "author_profile": "https://Stackoverflow.com/users/5379", "pm_score": 5, "selected": false, "text": ":A F2" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386/" ]
21,749
<p>I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window.</p> <p>If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight.</p> <p>I've tried setting the owner and the ParentWindow properties to the form it is related to:</p> <blockquote><code>dialog := TDialogForm.Create( parentForm );<br> dialog.ParentWindow := parentForm.Handle; </code></blockquote> <p>How can I fix this problem? What else should I be trying?</p> <p>Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order.</p> <p><b>Note</b>: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.</p>
[ { "answer_id": 21978, "author": "Marius", "author_id": 1008, "author_profile": "https://Stackoverflow.com/users/1008", "pm_score": 4, "selected": true, "text": "dialog := TDialogForm.Create( parentForm );\ndialog.PopupParent := parentForm;\ndialog.PopupMode := pmExplicit; \ndialog.ShowModal();\n" }, { "answer_id": 29257, "author": "garethm", "author_id": 2219, "author_profile": "https://Stackoverflow.com/users/2219", "pm_score": 2, "selected": false, "text": "\nprocedure TDialogForm.CreateParams(var Params: TCreateParams);\nbegin\n inherited;\n Params.Style := Params.Style or WS_POPUP;\n Params.WndParent := (Owner as TWinControl).Handle;\nend;\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2219/" ]
21,817
<p>The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?</p> <pre><code>public interface ITest { public static String test(); } </code></pre> <p>The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public &amp; abstract are permitted".</p>
[ { "answer_id": 21823, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 4, "selected": false, "text": "Math.add(2, 3);\n" }, { "answer_id": 21845, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "public interface IPayable\n{\n public Pay(double amount);\n}\n public class BusinessAccount : IPayable\n{\n public void Pay(double amount)\n {\n //Logic\n }\n}\n\npublic class CustomerAccount : IPayable\n{\n public void Pay(double amount)\n {\n //Logic\n }\n}\n List<IPayable> accountsToPay = new List<IPayable>();\naccountsToPay.add(new CustomerAccount());\naccountsToPay.add(new BusinessAccount());\n foreach (IPayable account in accountsToPay)\n{\n account.Pay(50.00);\n}\n" }, { "answer_id": 22497, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 7, "selected": true, "text": "public interface Foo {\n public static int bar();\n}\n public interface Foo {\n public static int bar() {\n ...\n }\n}\n" }, { "answer_id": 138340, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 4, "selected": false, "text": "public class A {\n public method x() {...}\n}\npublic class B {\n public method x() {...}\n}\npublic class C extends A, B { ... }\n public interface A {\n public static method x() {...}\n}\npublic interface B {\n public static method x() {...}\n}\npublic class C implements A, B { ... }\n" }, { "answer_id": 18841163, "author": "Lenik", "author_id": 217071, "author_profile": "https://Stackoverflow.com/users/217071", "pm_score": 2, "selected": false, "text": "interface Foo {\n // ...\n class fn {\n public static void func1(...) {\n // ...\n }\n }\n}\n public @interface Foo {\n String value();\n\n class fn {\n public static String getValue(Object obj) {\n Foo foo = obj.getClass().getAnnotation(Foo.class);\n return foo == null ? null : foo.value();\n }\n }\n}\n Interface.fn... Class.fn..." }, { "answer_id": 22711415, "author": "Anandaraja_Srinivasan", "author_id": 2978567, "author_profile": "https://Stackoverflow.com/users/2978567", "pm_score": 3, "selected": false, "text": "interface X {\n static void foo() {\n System.out.println(\"foo\");\n }\n}\n\nclass Y implements X {\n //...\n}\n\npublic class Z {\n public static void main(String[] args) {\n X.foo();\n // Y.foo(); // won't compile because foo() is a Static Method of X and not Y\n }\n}\n" }, { "answer_id": 35220948, "author": "Kumar Abhishek", "author_id": 5772982, "author_profile": "https://Stackoverflow.com/users/5772982", "pm_score": 1, "selected": false, "text": "public interface StaticMethodInterface {\npublic static int testStaticMethod() {\n return 0;\n}\n\n/**\n * Illegal combination of modifiers for the interface method\n * testStaticMethod; only one of abstract, default, or static permitted\n * \n * @param i\n * @return\n */\n// public static abstract int testStaticMethod(float i);\n\ndefault int testNonStaticMethod() {\n return 1;\n}\n\n/**\n * Without implementation.\n * \n * @param i\n * @return\n */\nint testNonStaticMethod(float i);\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]
21,848
<p>There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch.</p> <p>Some ways this could be asked/solved: How do I rename my master branch to something else and then rename something else to master? How do I back up master and then cause all commits I've backed up past to be on a different branch?</p> <p>Thanks for all the (quick) answers! They're all good.</p>
[ { "answer_id": 21897, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 3, "selected": false, "text": "git checkout -b fake_master master # fake_master now points to the same commit as master\ngit branch -D master # get rid of incorrect master\ngit checkout -b master real_master # master now points to your actual master\ngit checkout master # optional -- switch on to your master branch\n" }, { "answer_id": 21905, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 4, "selected": false, "text": "master in-progress master $ git branch in-progress\n$ git reset --hard HEAD^\n" }, { "answer_id": 21932, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "git branch -m master crap_work\ngit branch -m previous_master master\n" }, { "answer_id": 12021187, "author": "Penghe Geng", "author_id": 814145, "author_profile": "https://Stackoverflow.com/users/814145", "pm_score": 0, "selected": false, "text": "git checkout -B master new_point\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427/" ]
21,877
<p>What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. </p> <p>I have done this by using </p> <pre><code> Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); </code></pre> <p>but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?</p>
[ { "answer_id": 21885, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Web;\n\nnamespace Example\n{ \n public class GetImage : IHttpHandler\n {\n\n public void ProcessRequest(HttpContext context)\n {\n if (context.Request.QueryString(\"id\") != null)\n {\n Blob = GetBlobFromDataBase(id);\n context.Response.Clear();\n context.Response.ContentType = \"image/pjpeg\";\n context.Response.BinaryWrite(Blob);\n context.Response.End();\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n }\n}\n <img src=\"GetImage.ashx?id=111\"/>\n using System;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace Example.WebControl\n{\n\n [ToolboxData(\"<{0}:DatabaseImage runat=server></{0}:DatabaseImage>\")]\n public class DatabaseImage : Control\n {\n\n public int DatabaseId\n {\n get\n {\n if (ViewState[\"DatabaseId\" + this.ID] == null)\n return 0;\n else\n return ViewState[\"DataBaseId\"];\n }\n set\n {\n ViewState[\"DatabaseId\" + this.ID] = value;\n }\n }\n\n protected override void RenderContents(HtmlTextWriter output)\n {\n output.Write(\"<img src='getImage.ashx?id=\" + this.DatabaseId + \"'/>\");\n base.RenderContents(output);\n }\n }\n}\n <cc:DatabaseImage id=\"db1\" DatabaseId=\"123\" runat=\"server/>\n" }, { "answer_id": 21887, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 5, "selected": true, "text": "public class ImageHandler : IHttpHandler\n{\n\n public void ProcessRequest(HttpContext context)\n {\n using(Image image = GetImage(context.Request.QueryString[\"ID\"]))\n { \n context.Response.ContentType = \"image/jpeg\";\n image.Save(context.Response.OutputStream, ImageFormat.Jpeg);\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return true;\n }\n }\n}\n <asp:Image runat=\"server\" ImageUrl=\"~/Image.ashx?ID=myImageId\" /> \n" }, { "answer_id": 21889, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 0, "selected": false, "text": "<img src=\"myhandler.ashx?imageid=5\"> \n" }, { "answer_id": 19257098, "author": "Fidel Orozco", "author_id": 1260174, "author_profile": "https://Stackoverflow.com/users/1260174", "pm_score": 2, "selected": false, "text": "public FileContentResult Image(int id)\n{\n //Get data from database. The Image BLOB is return like byte[]\n SomeLogic ItemsDB= new SomeLogic(\"[ImageId]=\" + id.ToString());\n FileContentResult MyImage = null;\n if (ItemsDB.Count > 0)\n {\n MyImage= new FileContentResult(ItemsDB.Image, \"image/jpg\");\n }\n\n return MyImage;\n}\n this.imgExample.ImageUrl = \"~/Items/Image/\" + MyItem.Id.ToString();\n this.imgExample.Height = new Unit(120);\n this.imgExample.Width = new Unit(120);\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932/" ]
21,879
<p>I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are <a href="http://www.appscanadian.ca/archives/cs-101-introduction-to-computer-science/" rel="noreferrer">here</a> if you're interested in helping out). </p> <p>My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??</p> <p>What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?</p> <p>Thank!</p>
[ { "answer_id": 21962, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": true, "text": "base:\n algebra\n trigonometry\n analytic geometry\n\ntrack 1 track 2 track 3\n calc 1 linear algebra statistics\n calc 2 discrete math 1\n calc 3 (multivariable) discrete math 2\n differential equations \n algebra, discrete\nalgebra, linear algebra, discrete (if you want to cover matrices first)\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1588/" ]
21,908
<p>I'm working on a web application that needs to prints silently -- that is without user involvement. What's the best way to accomplish this? It doesn't like it can be done with strictly with Javascript, nor Flash and/or AIR. The closest I've seen involves a Java applet.</p> <p>I can understand why it would a Bad Idea for just any website to be able to do this. This specific instance is for an internal application, and it's perfectly acceptable if the user needs to add the URL to a trusted site list, install an addon, etc.</p>
[ { "answer_id": 21924, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<script>\nfunction Print() {\n alert (\"THUD.. another tree bites the dust!\")\n if (document.layers)\n {\n window.print();\n }\n else if (document.all)\n {\n WebBrowser1.ExecWB(6, 1);\n //use 6, 1 to prompt the print dialog or 6, 6 to omit it\n //some websites also indicate that 6,2 should be used to omit the box\n WebBrowser1.outerHTML = \"\";\n }\n}\n</script>\n<object ID=\"WebBrowser1\" WIDTH=\"0\" HEIGHT=\"0\"\nCLASSID=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\">\n</object>\n if (navigator.appName == \"Microsoft Internet Explorer\")\n{ \n var PrintCommand = '<object ID=\"PrintCommandObject\" WIDTH=0 HEIGHT=0 CLASSID=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>';\n document.body.insertAdjacentHTML('beforeEnd', PrintCommand); \n PrintCommandObject.ExecWB(6, -1); PrintCommandObject.outerHTML = \"\"; \n} \nelse { \n window.print();\n} \n" }, { "answer_id": 14943756, "author": "Iannazzi", "author_id": 1303144, "author_profile": "https://Stackoverflow.com/users/1303144", "pm_score": 3, "selected": false, "text": "#!/bin/bash\n\n# Get a remote directory Folder\n# List the contents every second\n# Copy the files to a local folder\n# delete the file from server\n# send the file to a printer\n# delete the file\n# compliments of embrasse-moi.com\n\n\nclear # clear terminal window\n\necho \"##########################################\"\necho \"Embrasse-Moi's Remote Print Queue Script\"\necho \"##########################################\"\n\n#Local Print Queue Directory\nCOPY_TO_DIRECTORY=/volumes/DATA/test/\necho \"Local Directory: $COPY_TO_DIRECTORY\"\n#Priter\nPRINTER='Brother_MFC_7820N'\necho \"Printer Name: $PRINTER\"\n\n#FTP Info\nUSER=\"user\"\nPASS=\"pass\"\nHOST=\"ftp.yourserver.com\"\n#remote path\nCOPY_REMOTE_DIRECTORY_FILES=/path\necho \"Remote Print Queue Directory: $HOST$COPY_REMOTE_DIRECTORY_FILES\"\n\necho 'Entering Repeating Loop'\nwhile true; do\n\n #make the copy to directory if not exist\n echo \"Making Directory If it Does Not Exist\"\n mkdir -p $COPY_TO_DIRECTORY\n cd $COPY_TO_DIRECTORY\n\n ######################### WGET ATTEMPTS ############################################\n #NOTE wget will need to be installed\n echo \"NOT Using wget to retrieve remote files...\"\n\n # wget --tries=45 -o log --ftp-user=$USER --ftp-password=$PASS ftp://ftp.yourserver.com$COPY_REMOTE_DIRECTORY_FILES/*.pdf\n\n ######################### FTP ATTEMPTS ############################################\n echo \"NOT Using ftp to retrieve and delete remote files...\"\n #This seems to fail at mget, plus not sure how to delete file or loop through files\n ftp -n $HOST <<END_SCRIPT\n quote USER $USER\n quote PASS $PASS\n cd $COPY_REMOTE_DIRECTORY_FILES\n ls\n prompt\n mget *\n mdel *\nEND_SCRIPT\n\n\n echo \"Examining Files in $COPY_TO_DIRECTORY\"\n for f in $COPY_TO_DIRECTORY/*.pdf\n do\n # take action on each file. $f store current file name \n #print\n echo \"Printing File: $f To: $PRINTER\"\n lpr -P $PRINTER $f\n\n # This will remove the file.....\n echo \"Deleting File: $f\"\n rm \"$f\"\n done\n echo \"Script Complete... now repeat until killed...\"\n sleep 5\ndone\n on run {input, parameters}\n\n tell application \"Finder\" to get folder of (path to me) as Unicode text\n set workingDir to POSIX path of result\n tell application \"Terminal\"\n do script \"sh \" & \"'\" & workingDir & \"script1.sh\" & \"'\"\n\n end tell\n\n return input\nend run\n" }, { "answer_id": 30038360, "author": "Cedric", "author_id": 310923, "author_profile": "https://Stackoverflow.com/users/310923", "pm_score": 4, "selected": false, "text": "--kiosk-printing" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181/" ]
21,934
<p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p> <p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p> <p>Why does Java choose this strategy and what is the benefit from this?</p> <p>Is this better than the Python approach?</p>
[ { "answer_id": 22219, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "def parse_some_attrs(fname):\n return open(fname).read().split(\"~~~\")[2:4]\n def parse_some_attrs(fname):\n with open(fname) as f:\n return f.read().split(\"~~~\")[2:4]\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
21,938
<p>Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.</p>
[ { "answer_id": 21942, "author": "Philippe", "author_id": 920, "author_profile": "https://Stackoverflow.com/users/920", "pm_score": 3, "selected": false, "text": "IOException NullPointerException Exception" }, { "answer_id": 21950, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 8, "selected": true, "text": "try { \n something(); \n} catch (Exception ex) {}\n try:\n something()\nexcept:\n pass\n" }, { "answer_id": 53328948, "author": "Peter Griffin", "author_id": 3839722, "author_profile": "https://Stackoverflow.com/users/3839722", "pm_score": -1, "selected": false, "text": " catch (final RemoteException exc)\n {\n exc.printStackTrace();\n }\n catch (final IntentSender.SendIntentException exc)\n {\n exc.printStackTrace();\n }\n catch (final IabHelper.IabAsyncInProgressException exc)\n {\n exc.printStackTrace();\n }\n catch (final NullPointerException exc)\n {\n exc.printStackTrace();\n }\n catch (final IllegalStateException exc)\n {\n exc.printStackTrace();\n }\n catch (final Exception exc)\n {\n exc.printStackTrace();\n }\n" }, { "answer_id": 54563389, "author": "Beefster", "author_id": 5079779, "author_profile": "https://Stackoverflow.com/users/5079779", "pm_score": 1, "selected": false, "text": "KeyboardInterrupt SystemExit Exception finally defer with" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1731/" ]
21,956
<p>I have two arrays of <code>System.Data.DataRow</code> objects which I want to compare. </p> <p>The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted. </p> <p><strong>How do I do this in PowerShell?</strong></p>
[ { "answer_id": 48471891, "author": "Dongminator", "author_id": 1178960, "author_profile": "https://Stackoverflow.com/users/1178960", "pm_score": 1, "selected": false, "text": "foreach ($property in ($row1 | Get-Member -MemberType Property)) {\n $pName = $property.Name\n\n if ($row1.$pName -ne $row2.$pName) {\n Write-Host \"== $pName ==\"\n $row1.$pName\n $row2.$pName\n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966/" ]
21,961
<pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime("01-31-2009", "%m-%d-%Y") (2009, 1, 31, 0, 0, 0, 5, 31, -1) &gt;&gt;&gt; time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233378000.0 &gt;&gt;&gt; 60*60*24 # seconds in a day 86400 &gt;&gt;&gt; 1233378000.0 / 86400 14275.208333333334 </code></pre> <p><code>time.mktime</code> should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
[ { "answer_id": 21973, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 2, "selected": false, "text": "mktime(...)\n mktime(tuple) -> floating point number\n\n Convert a time tuple in local time to seconds since the Epoch.\n The other representation is a tuple of 9 integers giving local time.\nThe tuple items are:\n year (four digits, e.g. 1998)\n month (1-12)\n day (1-31)\n hours (0-23)\n minutes (0-59)\n seconds (0-59)\n weekday (0-6, Monday is 0)\n Julian day (day in the year, 1-366)\n DST (Daylight Savings Time) flag (-1, 0 or 1)\nIf the DST flag is 0, the time is given in the regular time zone;\nif it is 1, the time is given in the DST time zone;\nif it is -1, mktime() should guess based on the date and time.\n >>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233356400.0\n>>> (1233378000.0 - 1233356400)/(60*60)\n6.0\n" }, { "answer_id": 21974, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": ">>> now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1))\n>>> tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1))\n>>> tomorrow - now\n86400.0\n" }, { "answer_id": 21975, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 3, "selected": false, "text": "time.mktime() >>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233360000.0\n >>> (1233378000 - 1233360000) / (60*60) \n5\n time.gmtime()" }, { "answer_id": 22021, "author": "Daniel Benamy", "author_id": 2427, "author_profile": "https://Stackoverflow.com/users/2427", "pm_score": 2, "selected": false, "text": ">>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233360000\n>>> 1233360000 / (60*60*24)\n14275\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427/" ]
21,987
<p>I am developing an application that controls an Machine.<br/> When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing.</p> <p>There's one little annoyance using the <code>FlashWindowEx</code> function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing).</p> <p><a href="https://i.stack.imgur.com/GOS2r.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GOS2r.gif" alt="" /></a></p> <pre><code>[Flags] public enum FlashMode { /// &lt;summary&gt; /// Stop flashing. The system restores the window to its original state. /// &lt;/summary&gt; FLASHW_STOP = 0, /// &lt;summary&gt; /// Flash the window caption. /// &lt;/summary&gt; FLASHW_CAPTION = 1, /// &lt;summary&gt; /// Flash the taskbar button. /// &lt;/summary&gt; FLASHW_TRAY = 2, /// &lt;summary&gt; /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// &lt;/summary&gt; FLASHW_ALL = 3, /// &lt;summary&gt; /// Flash continuously, until the FLASHW_STOP flag is set. /// &lt;/summary&gt; FLASHW_TIMER = 4, /// &lt;summary&gt; /// Flash continuously until the window comes to the foreground. /// &lt;/summary&gt; FLASHW_TIMERNOFG = 12 } public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) { FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = (UInt32)fm; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; return FlashWindowEx(ref fInfo); } [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } </code></pre> <p>In my case I use <code>FLASHW_TRAY</code> to start flashing and <code>FLASHW_STOP</code> to stop the flashing.</p> <p>Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?</p>
[ { "answer_id": 23285, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 4, "selected": true, "text": "FLASHW_STOP" }, { "answer_id": 37615, "author": "Stormenet", "author_id": 2090, "author_profile": "https://Stackoverflow.com/users/2090", "pm_score": 0, "selected": false, "text": "FLASHW_ALL | FLASHW_TIMERNOFG" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090/" ]
21,992
<p>I'm looking for (arguably) the correct way to return data from a <code>XmlHttpRequest</code>. Options I see are:</p> <ul> <li><p><strong>Plain HTML</strong>. Let the request format the data and return it in a usable format.<br> <em>Advantage</em>: easy to consume by the calling page.<br><em>Disadvantage</em>: Very rigid, stuck with a fixed layout.</p></li> <li><p><strong>XML</strong>. Let the request return XML, format it using XSLT on the calling page.<br><em>Advantage</em>: the requested service is easily consumed by other sources.<br><em>Disadvantage</em>: Is browser support for XSLT good enough?</p></li> <li><p><strong>JSON</strong>. Let the request return JSON, consume it using javascript, render HTML accordingly.<br><em>Advantage</em>: easier to 'OO-ify' the javascript making the request. <br><em>Disadvantage</em>: Probably not as easy to use as the previous two options.</p></li> </ul> <p>I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons.</p> <p>While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?</p>
[ { "answer_id": 22002, "author": "Hrvoje Hudo", "author_id": 1407, "author_profile": "https://Stackoverflow.com/users/1407", "pm_score": 0, "selected": false, "text": "JSON OO js" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909/" ]
21,999
<p>Anti aliasing <a href="http://forums.msdn.microsoft.com/en-US/wpf/thread/1ad9a62a-d1a4-4ca2-a950-3b7bf5240de5" rel="noreferrer">cannot be turned off</a> in WPF. But I want to remove the blurred look of WPF fonts when they are small. </p> <p>One possibility would be to use a .net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though.</p> <p>Anyone has a solution for this? Any drawbacks from it?</p> <p>Thank you</p>
[ { "answer_id": 6943415, "author": "Wolkenjaeger", "author_id": 408659, "author_profile": "https://Stackoverflow.com/users/408659", "pm_score": 3, "selected": false, "text": "TextOptions.TextFormattingMode=\"Display\"\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013/" ]
22,000
<p>I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me ;)</p> <p>I have <a href="http://woarl.com/board/rob.php?mode=map&amp;x=-1&amp;y=9&amp;w=2&amp;h=2" rel="noreferrer">made the latest version live</a> so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated.</p> <p>In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question.</p> <p>I have also uploaded an <a href="http://woarl.com/badMap.png" rel="noreferrer">image of the issue</a>.</p>
[ { "answer_id": 22013, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<img> </td> <td>\n <img src=\"image.jpg\"/>\n</td>\n <td><img src=\"image.jpg\"/></td>\n" }, { "answer_id": 22016, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 1, "selected": false, "text": "</span> <div class=\"inner\"><span class=\"corners-top\"><span></span></span>\n<div class=\"content\" style=\"font-size: 1.1em;\">\n\n<!-- Stackoverflow findy thingy -->\n<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" }, { "answer_id": 22025, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 6, "selected": true, "text": "display: block inline" }, { "answer_id": 22068, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "td {\n line-height: 0\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
22,001
<p>I'm learning objective-C and Cocoa. In the Apple tutorial I'm working through there's a side note that says: </p> <blockquote> <p><code>IBOutlet</code> is a null-defined macro, which the C preprocessor removes at compile time.</p> </blockquote> <p>I'm curious - what's a null-defined macro?</p>
[ { "answer_id": 22003, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "#define IBOutlet\n" }, { "answer_id": 22455, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 3, "selected": false, "text": "IBOutlet IBOutlet" }, { "answer_id": 45364, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 3, "selected": false, "text": "name address phone" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
22,012
<p>My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.</p> <p>Is there a way to tell the runtime that the dlls are in a seperate subfolder?</p>
[ { "answer_id": 22022, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<probing> <configuration>\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <probing privatePath=\"bin;bin2\\subbin;bin3\"/>\n </assemblyBinding>\n </runtime>\n</configuration>\n" }, { "answer_id": 22026, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 5, "selected": true, "text": "AppDomain currentDomain = AppDomain.CurrentDomain;\ncurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);\n" }, { "answer_id": 22029, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 1, "selected": false, "text": "<codeBase>" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374/" ]
22,106
<p>In Linux, what is the difference between <code>/dev/ttyS0</code> and <code>/dev/ttys0</code>?</p> <p>I know that the first is a serial port, but what about the second, with the small <code>s</code>?</p>
[ { "answer_id": 22124, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "3 char Pseudo-TTY slaves\n 0 = /dev/ttyp0 First PTY slave\n 1 = /dev/ttyp1 Second PTY slave\n ...\n 255 = /dev/ttyef 256th PTY slave\n\n These are the old-style (BSD) PTY devices; Unix98\n devices are on major 136 and above.\n 4 char TTY devices\n 0 = /dev/tty0 Current virtual console\n\n 1 = /dev/tty1 First virtual console\n ...\n 63 = /dev/tty63 63rd virtual console\n 64 = /dev/ttyS0 First UART serial port\n ...\n 255 = /dev/ttyS191 192nd UART serial port\n\n UART serial ports refer to 8250/16450/16550 series devices.\n\n Older versions of the Linux kernel used this major\n number for BSD PTY devices. As of Linux 2.1.115, this\n is no longer supported. Use major numbers 2 and 3.\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
22,115
<p>I am writing a Java utility that helps me to generate loads of data for performance testing. It would be <em>really</em> cool to be able to specify a regex for Strings so that my generator spits out things that match this.</p> <p>Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there?</p>
[ { "answer_id": 22133, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 7, "selected": true, "text": "dk.brics.automaton" }, { "answer_id": 245381, "author": "J Wynia", "author_id": 1124, "author_profile": "https://Stackoverflow.com/users/1124", "pm_score": 2, "selected": false, "text": "[A-Z0-9]{3,3}-[A-Z0-9]{3,3}\n LLK-32U\n" }, { "answer_id": 280105, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "# q = \"(How (much|many)|What) is (the (value|result) of)? :num1 :op :num2?\"\n# values = { :num1=>42, :op=>\"plus\", :num2=>17 }\n# 4.times{ puts q.variation( values ) }\n# => What is 42 plus 17?\n# => How many is the result of 42 plus 17?\n# => What is the result of 42 plus 17?\n# => How much is the value of 42 plus 17?\nclass String\n def variation( values={} )\n out = self.dup\n while out.gsub!( /\\(([^())?]+)\\)(\\?)?/ ){\n ( $2 && ( rand > 0.5 ) ) ? '' : $1.split( '|' ).random\n }; end\n out.gsub!( /:(#{values.keys.join('|')})\\b/ ){ values[$1.intern] }\n out.gsub!( /\\s{2,}/, ' ' )\n out\n end\nend\n\nclass Array\n def random\n self[ rand( self.length ) ]\n end\nend" }, { "answer_id": 1590630, "author": "Wilfred Springer", "author_id": 136476, "author_profile": "https://Stackoverflow.com/users/136476", "pm_score": 4, "selected": false, "text": "String regex = \"[ab]{4,6}c\";\nXeger generator = new Xeger(regex);\nString result = generator.generate();\nassert result.matches(regex);\n" }, { "answer_id": 12151715, "author": "R dhabalia", "author_id": 1629062, "author_profile": "https://Stackoverflow.com/users/1629062", "pm_score": 2, "selected": false, "text": "public static void main(String[] args) {\n\n String line = \"[A-Z0-9]{16}\";\n String[] tokens = line.split(line);\n char[] pattern = new char[100];\n int i = 0;\n int len = tokens.length;\n String sep1 = \"[{\";\n StringTokenizer st = new StringTokenizer(line, sep1);\n\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n System.out.println(token);\n\n if (token.contains(\"]\")) {\n char[] endStr = null;\n\n if (!token.endsWith(\"]\")) {\n String[] subTokens = token.split(\"]\");\n token = subTokens[0];\n\n if (!subTokens[1].equalsIgnoreCase(\"*\")) {\n endStr = subTokens[1].toCharArray();\n }\n }\n\n if (token.startsWith(\"^\")) {\n String subStr = token.substring(1, token.length() - 1);\n char[] subChar = subStr.toCharArray();\n Set set = new HashSet<Character>();\n\n for (int p = 0; p < subChar.length; p++) {\n set.add(subChar[p]);\n }\n\n int asci = 1;\n\n while (true) {\n char newChar = (char) (subChar[0] + (asci++));\n\n if (!set.contains(newChar)) {\n pattern[i++] = newChar;\n break;\n }\n }\n if (endStr != null) {\n for (int r = 0; r < endStr.length; r++) {\n pattern[i++] = endStr[r];\n }\n }\n\n } else {\n pattern[i++] = token.charAt(0);\n }\n } else if (token.contains(\"}\")) {\n char[] endStr = null;\n\n if (!token.endsWith(\"}\")) {\n String[] subTokens = token.split(\"}\");\n token = subTokens[0];\n\n if (!subTokens[1].equalsIgnoreCase(\"*\")) {\n endStr = subTokens[1].toCharArray();\n }\n }\n\n int length = Integer.parseInt((new StringTokenizer(token, (\",}\"))).nextToken());\n char element = pattern[i - 1];\n\n for (int j = 0; j < length - 1; j++) {\n pattern[i++] = element;\n }\n\n if (endStr != null) {\n for (int r = 0; r < endStr.length; r++) {\n pattern[i++] = endStr[r];\n }\n }\n } else {\n char[] temp = token.toCharArray();\n\n for (int q = 0; q < temp.length; q++) {\n pattern[i++] = temp[q];\n }\n }\n }\n\n String result = \"\";\n\n for (int j = 0; j < i; j++) {\n result += pattern[j];\n }\n\n System.out.print(result);\n}\n" }, { "answer_id": 24659605, "author": "Mifmif", "author_id": 1250229, "author_profile": "https://Stackoverflow.com/users/1250229", "pm_score": 5, "selected": false, "text": "Generex generex = new Generex(\"[0-3]([a-c]|[e-g]{1,2})\");\n\n// generate the second String in lexicographical order that matches the given Regex.\nString secondString = generex.getMatchedString(2);\nSystem.out.println(secondString);// it print '0b'\n\n// Generate all String that matches the given Regex.\nList<String> matchedStrs = generex.getAllMatchedStrings();\n\n// Using Generex iterator\nIterator iterator = generex.iterator();\nwhile (iterator.hasNext()) {\n System.out.print(iterator.next() + \" \");\n}\n// it prints 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e\n// 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g\n// 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee\n\n// Generate random String\nString randomStr = generex.random();\nSystem.out.println(randomStr);// a random value from the previous String list\n" }, { "answer_id": 58813696, "author": "Vladislav Varslavans", "author_id": 4174003, "author_profile": "https://Stackoverflow.com/users/4174003", "pm_score": 4, "selected": false, "text": "a{60000} (A|B|C|D|E|F) RgxGen rgxGen = new RgxGen(aRegex); // Create generator\nString s = rgxGen.generate(); // Generate new random value\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2455/" ]
22,135
<p>I am trying to implement NTLM authentication on one of our internal sites and everything is working. The one piece of the puzzle I do not have is how to take the information from NTLM and authenticate with Active Directory.</p> <p>There is a <a href="http://www.innovation.ch/personal/ronald/ntlm.html" rel="nofollow noreferrer">good description of NTLM</a> and the <a href="http://us1.samba.org/samba/docs/man/Samba-Developers-Guide/pwencrypt.html" rel="nofollow noreferrer">encryption used for the passwords</a>, which I used to implement this, but I am not sure of how to verify if the user's password is valid.</p> <p>I am using ColdFusion but a solution to this problem can be in any language (Java, Python, PHP, etc).</p> <p>Edit:</p> <p>I am using ColdFusion on Redhat Enterprise Linux. Unfortunately we cannot use IIS to manage this and instead have to write or use a 3rd party tool for this.</p> <hr> <p><strong>Update</strong> - <em>I got this working and here is what I did</em></p> <p>I went with the <a href="http://jcifs.samba.org/" rel="nofollow noreferrer">JCIFS library from samba.org.</a></p> <blockquote> <p>Note that the method below will only work with NTLMv1 and <strong>DOES NOT</strong> work with NTLMv2. If you are unable to use NTLMv1 you can try <a href="http://www.ioplex.com/jespa.html" rel="nofollow noreferrer">Jespa</a>, which supports NTLMv2 but is not open source, or you can use <a href="http://spnego.sourceforge.net" rel="nofollow noreferrer">Kerberos/SPNEGO.</a></p> </blockquote> <p>Here is my web.xml:</p> <pre><code>&lt;web-app&gt; &lt;display-name&gt;Ntlm&lt;/display-name&gt; &lt;filter&gt; &lt;filter-name&gt;NtlmHttpFilter&lt;/filter-name&gt; &lt;filter-class&gt;jcifs.http.NtlmHttpFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;jcifs.http.domainController&lt;/param-name&gt; &lt;param-value&gt;dc01.corp.example.com&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;jcifs.smb.client.domain&lt;/param-name&gt; &lt;param-value&gt;CORP.EXAMPLE.COM&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;NtlmHttpFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/admin/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;/web-app&gt; </code></pre> <p>Now all URLs matching <code>/admin/*</code> will require NTLM authentication.</p>
[ { "answer_id": 464096, "author": "user8134", "author_id": 8134, "author_profile": "https://Stackoverflow.com/users/8134", "pm_score": 4, "selected": false, "text": "yum install samba-winbind yum install mod_auth_ntlm_winbind" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309844/" ]
22,140
<p>As part of our product release we ship Apache HTTP Server binaries that we have compiled on our (UNIX) development machine.</p> <p>We tell our clients to install the binaries (on their UNIX servers) under the same directory structure that we compiled it under. For some clients this is not appropriate, e.g. where there are restrictions on where they can install software on their servers and they don't want to compile Apache themselves.</p> <p>Is there a way of compiling Apache HTTP Server so its installation location(s) can be specified dynamically using environment variables ?</p> <p>I spent a few days trying to sort this out and couldn't find a way to do it. It led me to believe that the Apache binaries were hard coding some directory paths at compilation preventing the portability we require.</p> <p>Has anyone managed to do this ?</p>
[ { "answer_id": 27644, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 0, "selected": false, "text": "/opt/my_apache2/" }, { "answer_id": 27902, "author": "Hissohathair", "author_id": 2997, "author_profile": "https://Stackoverflow.com/users/2997", "pm_score": 1, "selected": false, "text": "./configure --prefix=/opt/apache2 sudo make install cd /opt/apache2; sudo tar cf - apache2 | gzip -c > ~/apache2.tar.gz /opt/mynewdir/dan/apache2 conf/httpd.conf ./bin/httpd -f /opt/mynewdir/dan/conf/httpd.conf" }, { "answer_id": 47738, "author": "cwhite", "author_id": 4923, "author_profile": "https://Stackoverflow.com/users/4923", "pm_score": 0, "selected": false, "text": "6). ./bin/httpd -d <server path> (although it can be overridden in the config file) \n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
22,156
<p>I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong</p>
[ { "answer_id": 22171, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 0, "selected": false, "text": "Asp.Net HttpHandler public class Page : TemplateControl, IHttpHandler\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
22,165
<p>I have a need to create a "transactional" process using an external API that does not support COM+ or .NET transactions (Sharepoint to be exact)</p> <p>What I need to do is to be able to perform a number of processes in a sequence, but any failure in that sequence means that I will have to manually undo all of the previous steps. In my case there are only 2 types of step, both af which are fairly easy to undo/roll back.</p> <p>Does anyony have any suggestions for design patterns or structures that could be usefull for this ?</p>
[ { "answer_id": 22220, "author": "vitule", "author_id": 1287, "author_profile": "https://Stackoverflow.com/users/1287", "pm_score": 3, "selected": true, "text": "Update() SPList.Update() SPWeb.Update()" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/983/" ]
22,181
<p>I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ... </p> <p>What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ...</p> <pre><code>Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = Convert.ToInt32(reader("ProductID")) product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While </code></pre>
[ { "answer_id": 22189, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "reader.GetOrdinal GetOrdinal IndexOutOfRangeException Dictionary<string, int> ContainsKey" }, { "answer_id": 22195, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "public static void Fill<T>(this IDbCommand cmd,\n IList<T> list, Func<IDataReader, T> rowConverter)\n{\n using (var rdr = cmd.ExecuteReader())\n {\n while (rdr.Read())\n {\n list.Add(rowConverter(rdr));\n }\n }\n}\n cmd.Fill(products, r => r.GetProduct());\n" }, { "answer_id": 22199, "author": "FantaMango77", "author_id": 2374, "author_profile": "https://Stackoverflow.com/users/2374", "pm_score": 1, "selected": false, "text": "GetSchemaTable() DataReader DataTable" }, { "answer_id": 26103, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 2, "selected": true, "text": "Using reader As SqlDataReader = cmd.ExecuteReader() \nDim table As DataTable = reader.GetSchemaTable()\nDim colNames As New DataTable()\nFor Each row As DataRow In table.Rows\n colNames.Columns.Add(row.ItemArray(0))\nNext\nDim product As Product While reader.Read() \nproduct = New Product() \nIf Not colNames.Columns(\"ProductID\") Is Nothing Then\n product.ID = Convert.ToInt32(reader(\"ProductID\"))\nEnd If \nproduct.SupplierID = Convert.ToInt32(reader(\"SupplierID\")) \nproduct.CategoryID = Convert.ToInt32(reader(\"CategoryID\")) \nproduct.ProductName = Convert.ToString(reader(\"ProductName\")) \nproduct.QuantityPerUnit = Convert.ToString(reader(\"QuantityPerUnit\")) \nproduct.UnitPrice = Convert.ToDouble(reader(\"UnitPrice\")) \nproduct.UnitsInStock = Convert.ToInt32(reader(\"UnitsInStock\")) \nproduct.UnitsOnOrder = Convert.ToInt32(reader(\"UnitsOnOrder\")) \nproduct.ReorderLevel = Convert.ToInt32(reader(\"ReorderLevel\")) \nproductList.Add(product) \nEnd While\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
22,187
<p>What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)?</p> <p>Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library.</p>
[ { "answer_id": 22285, "author": "jcsalterego", "author_id": 1416, "author_profile": "https://Stackoverflow.com/users/1416", "pm_score": 4, "selected": true, "text": "#define N 100000\nint main(int argc, char *argv[])\n{\n int i, a[N];\n #pragma omp parallel for\n for (i=0;i<N;i++) \n a[i]= 2*i;\n return 0;\n}\n" }, { "answer_id": 971146, "author": "luccastera", "author_id": 76372, "author_profile": "https://Stackoverflow.com/users/76372", "pm_score": 2, "selected": false, "text": " myactor = Actor.spawn do\n Actor.receive do |filter|\n filter.when(:dog) { puts \"I got a dog!\" }\n end\n end\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
22,239
<p>(I'm using Visual C++ 2008) I've always heard that main() is <em>required</em> to return an integer, but here I didn't put in <code>return 0;</code> and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a <code>return;</code> also causes the error to appear. But leaving it out completely, it compiles just fine.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Hey look I'm supposed to return an int but I'm not gonna!\n"; } </code></pre> <p>Could this be a bug in VC++?</p>
[ { "answer_id": 22262, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 7, "selected": true, "text": "main int int main() { /* ... */ }\n int main(int argc, char* argv[]) {\n/* ... */\n}\n return main exit main" }, { "answer_id": 3492633, "author": "Chubsdad", "author_id": 418110, "author_profile": "https://Stackoverflow.com/users/418110", "pm_score": 2, "selected": false, "text": "int f(){\n if(0){\n if(1)\n return true;\n }\n}\n\nint main(){\n f();\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2222/" ]
22,245
<p>I have multiple projects in a couple of different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible.</p>
[ { "answer_id": 58591630, "author": "Vishal Sareen", "author_id": 12285975, "author_profile": "https://Stackoverflow.com/users/12285975", "pm_score": 0, "selected": false, "text": "File -> Source Control -> Advanced -> Workspace" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
22,259
<p>I want to allow users to upload avatar-type images in a variety of formats (<strong>GIF, JPEG, and PNG at least</strong>), but to save them all as <strong>PNG database BLOBs</strong>. If the images are oversized, pixelwise, I want to resize them before DB-insertion.</p> <p><strong>What is the best way to use GD to do the resizing and PNG conversion?</strong></p> <p>Edit: Sadly, only <a href="http://php.net/manual/en/book.image.php" rel="nofollow noreferrer">GD</a> is available on the server I need to use, no <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a>.</p>
[ { "answer_id": 22333, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "\n<?php\n //Input file\n $file = \"myImage.png\";\n $img = ImageCreateFromPNG($file);\n\n //Dimensions\n $width = imagesx($img);\n $height = imagesy($img);\n $max_width = 300;\n $max_height = 300;\n $percentage = 1;\n\n //Image scaling calculations\n if ( $width > $max_width ) { \n $percentage = ($height / ($width / $max_width)) > $max_height ?\n $height / $max_height :\n $width / $max_width;\n }\n elseif ( $height > $max_height) {\n $percentage = ($width / ($height / $max_height)) > $max_width ? \n $width / $max_width :\n $height / $max_height;\n }\n $new_width = $width / $percentage;\n $new_height = $height / $percentage;\n\n //scaled image\n $out = imagecreatetruecolor($new_width, $new_height);\n imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);\n\n //output image\n imagepng($out);\n?>\n" }, { "answer_id": 22403, "author": "Acuminate", "author_id": 2482, "author_profile": "https://Stackoverflow.com/users/2482", "pm_score": 6, "selected": true, "text": "<?php \n/*\nResizes an image and converts it to PNG returning the PNG data as a string\n*/\nfunction imageToPng($srcFile, $maxSize = 100) { \n list($width_orig, $height_orig, $type) = getimagesize($srcFile); \n\n // Get the aspect ratio\n $ratio_orig = $width_orig / $height_orig;\n\n $width = $maxSize; \n $height = $maxSize;\n\n // resize to height (orig is portrait) \n if ($ratio_orig < 1) {\n $width = $height * $ratio_orig;\n } \n // resize to width (orig is landscape)\n else {\n $height = $width / $ratio_orig;\n }\n\n // Temporarily increase the memory limit to allow for larger images\n ini_set('memory_limit', '32M'); \n\n switch ($type) \n {\n case IMAGETYPE_GIF: \n $image = imagecreatefromgif($srcFile); \n break; \n case IMAGETYPE_JPEG: \n $image = imagecreatefromjpeg($srcFile); \n break; \n case IMAGETYPE_PNG: \n $image = imagecreatefrompng($srcFile);\n break; \n default:\n throw new Exception('Unrecognized image type ' . $type);\n }\n\n // create a new blank image\n $newImage = imagecreatetruecolor($width, $height);\n\n // Copy the old image to the new image\n imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);\n\n // Output to a temp file\n $destFile = tempnam();\n imagepng($newImage, $destFile); \n\n // Free memory \n imagedestroy($newImage);\n\n if ( is_file($destFile) ) {\n $f = fopen($destFile, 'rb'); \n $data = fread($f); \n fclose($f);\n\n // Remove the tempfile\n unlink($destFile); \n return $data;\n }\n\n throw new Exception('Image conversion failed.');\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820/" ]
22,269
<p>I'm trying to build a C# console application to automate grabbing certain files from our website, mostly to save myself clicks and - frankly - just to have done it. But I've hit a snag that for which I've been unable to find a working solution.</p> <p>The website I'm trying to which I'm trying to connect uses ASP.Net forms authorization, and I cannot figure out how to authenticate myself with it. This application is a complete hack so I can hard code my username and password or any other needed auth info, and the solution itself doesn't need to be something that is viable enough to release to general users. In other words, if the only possible solution is a hack, I'm fine with that.</p> <p>Basically, I'm trying to use HttpWebRequest to pull the site that has the list of files, iterating through that list and then downloading what I need. So the actual work on the site is fairly trivial once I can get the website to consider me authorized.</p>
[ { "answer_id": 22333, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "\n<?php\n //Input file\n $file = \"myImage.png\";\n $img = ImageCreateFromPNG($file);\n\n //Dimensions\n $width = imagesx($img);\n $height = imagesy($img);\n $max_width = 300;\n $max_height = 300;\n $percentage = 1;\n\n //Image scaling calculations\n if ( $width > $max_width ) { \n $percentage = ($height / ($width / $max_width)) > $max_height ?\n $height / $max_height :\n $width / $max_width;\n }\n elseif ( $height > $max_height) {\n $percentage = ($width / ($height / $max_height)) > $max_width ? \n $width / $max_width :\n $height / $max_height;\n }\n $new_width = $width / $percentage;\n $new_height = $height / $percentage;\n\n //scaled image\n $out = imagecreatetruecolor($new_width, $new_height);\n imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);\n\n //output image\n imagepng($out);\n?>\n" }, { "answer_id": 22403, "author": "Acuminate", "author_id": 2482, "author_profile": "https://Stackoverflow.com/users/2482", "pm_score": 6, "selected": true, "text": "<?php \n/*\nResizes an image and converts it to PNG returning the PNG data as a string\n*/\nfunction imageToPng($srcFile, $maxSize = 100) { \n list($width_orig, $height_orig, $type) = getimagesize($srcFile); \n\n // Get the aspect ratio\n $ratio_orig = $width_orig / $height_orig;\n\n $width = $maxSize; \n $height = $maxSize;\n\n // resize to height (orig is portrait) \n if ($ratio_orig < 1) {\n $width = $height * $ratio_orig;\n } \n // resize to width (orig is landscape)\n else {\n $height = $width / $ratio_orig;\n }\n\n // Temporarily increase the memory limit to allow for larger images\n ini_set('memory_limit', '32M'); \n\n switch ($type) \n {\n case IMAGETYPE_GIF: \n $image = imagecreatefromgif($srcFile); \n break; \n case IMAGETYPE_JPEG: \n $image = imagecreatefromjpeg($srcFile); \n break; \n case IMAGETYPE_PNG: \n $image = imagecreatefrompng($srcFile);\n break; \n default:\n throw new Exception('Unrecognized image type ' . $type);\n }\n\n // create a new blank image\n $newImage = imagecreatetruecolor($width, $height);\n\n // Copy the old image to the new image\n imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);\n\n // Output to a temp file\n $destFile = tempnam();\n imagepng($newImage, $destFile); \n\n // Free memory \n imagedestroy($newImage);\n\n if ( is_file($destFile) ) {\n $f = fopen($destFile, 'rb'); \n $data = fread($f); \n fclose($f);\n\n // Remove the tempfile\n unlink($destFile); \n return $data;\n }\n\n throw new Exception('Image conversion failed.');\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
22,322
<p>I've got a problem similar to,but subtly different from, that described <a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">here</a> (Loading assemblies and their dependencies).</p> <p>I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? </p> <p>Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?</p> <p>Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?</p>
[ { "answer_id": 479664, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 4, "selected": true, "text": "static void Main(String[] argv)\n {\n // Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit\n // sub-directories.\n\n AppDomainSetup objADS = new AppDomainSetup();\n\n System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n switch (System.IntPtr.Size)\n {\n case (4): assemblyDir += \"\\\\win32\\\\\";\n break;\n case (8): assemblyDir += \"\\\\x64\\\\\";\n break;\n }\n\n objADS.ApplicationBase = assemblyDir;\n\n // We set the PrivateBinPath to the application directory, so that we can still\n // load the platform neutral assemblies from the app directory.\n objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n\n AppDomain objAD = AppDomain.CreateDomain(\"\", null, objADS);\n if (argv.Length > 0)\n objAD.ExecuteAssembly(argv[0]);\n else\n objAD.ExecuteAssembly(\"MyApplication.exe\");\n\n AppDomain.Unload(objAD);\n\n }\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2102/" ]
22,326
<p>I am trying to <strong>replace the current selection in Word (2003/2007)</strong> by some <strong>RTF string</strong> stored in a variable.</p> <p>Here is the current code:</p> <pre><code>Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) </code></pre> <p>Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?</p>
[ { "answer_id": 22335, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": -1, "selected": false, "text": "RichTextBox r = new RichTextBox();\nr.Rtf = strRTFString;\nConsole.WriteLine(r.Text);\n" }, { "answer_id": 27425, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 5, "selected": true, "text": "Selection.InsertFile FileName:=\"myfile.rtf\", Range :=\"\", _\n ConfirmConversions:=False, Link:=False, Attachment:=False" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
22,354
<p>I am working on a SharePoint application that supports importing multiple documents in a single operation. I also have an ItemAdded event handler that performs some basic maintenance of the item metadata. This event fires for both imported documents and manually created ones. The final piece of the puzzle is a batch operation feature that I implemented to kick off a workflow and update another metadata field.</p> <p>I am able to cause a COMException 0x81020037 by extracting the file data of a SPListItem. This file is just an InfoPath form/XML document. I am able to modify the XML and sucessfully push it back into the SPListItem. When I fire off the custom feature immediately afterwards and modify metadata, it occassionally causes the COM error.</p> <p>The error message basically indicates that the file was modified by another thread. It would seem that the ItemAdded event is still writing the file back to the database while the custom feature is changing metadata. I have tried putting in delays and error catching loops to try to detect that the SPListItem is safe to modify with little success.</p> <p>Is there a way to tell if another thread has a lock on a document?</p>
[ { "answer_id": 22703, "author": "vitule", "author_id": 1287, "author_profile": "https://Stackoverflow.com/users/1287", "pm_score": 1, "selected": false, "text": "ItemAdded ItemUpdated ItemAdded() ItemAdded() private static object myLock = new object();\npublic override void ItemAdded(SPItemEventProperties properties) {\n if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(30))\n {\n //do your stuff here.\n System.Threading.Monitor.Exit(myLock);\n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
22,356
<p>I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.</p> <p>Based on the community suggestions, I've used this:</p> <pre><code>// earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here } </code></pre>
[ { "answer_id": 22387, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)\n{\n if (InvokeRequired)\n {\n Invoke(new Action<object, CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args);\n return;\n }\n // do the dirty work of my method here\n}\n System.Windows.Forms.MethodInvoker System.Action EventHandler" }, { "answer_id": 22395, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "private void OnCoolEvent(CoolObjectEventArgs e)\n{\n BeginInvoke((o,e) => /*do work here*/,this, e);\n}\n" }, { "answer_id": 22397, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 6, "selected": true, "text": " BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent), \n sender, \n args);\n Invoke BeginInvoke EndInvoke TargetInvocationException" }, { "answer_id": 22470, "author": "gbc", "author_id": 1667, "author_profile": "https://Stackoverflow.com/users/1667", "pm_score": 2, "selected": false, "text": "<TextBox Text=\"{Binding Path=Name}\"/>\n" }, { "answer_id": 258385, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 6, "selected": false, "text": "private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)\n{\n // You could use \"() =>\" in place of \"delegate\"; it's a style choice.\n this.Invoke(delegate\n {\n // Do the dirty work of my method here.\n });\n}\n" }, { "answer_id": 12743503, "author": "TarPista", "author_id": 1722587, "author_profile": "https://Stackoverflow.com/users/1722587", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace CrossThreadCalls\n{\n public static class clsCrossThreadCalls\n {\n private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);\n public static void SetAnyProperty(Control c, string Property, object Value)\n {\n if (c.GetType().GetProperty(Property) != null)\n {\n //The given property exists\n if (c.InvokeRequired)\n {\n SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);\n c.BeginInvoke(d, c, Property, Value);\n }\n else\n {\n c.GetType().GetProperty(Property).SetValue(c, Value, null);\n }\n }\n }\n\n private delegate void SetTextPropertyCallBack(Control c, string Value);\n public static void SetTextProperty(Control c, string Value)\n {\n if (c.InvokeRequired)\n {\n SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);\n c.BeginInvoke(d, c, Value);\n }\n else\n {\n c.Text = Value;\n }\n }\n }\n CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, \"Text\", KvaserCanReader.GetSpeed.ToString());\n" }, { "answer_id": 31263315, "author": "The Lonely Coder", "author_id": 1201038, "author_profile": "https://Stackoverflow.com/users/1201038", "pm_score": 2, "selected": false, "text": " #region SyncContextCancel\n\n private SynchronizationContext _syncContextCancel;\n\n /// <summary>\n /// Gets the synchronization context used for UI-related operations.\n /// </summary>\n /// <value>The synchronization context.</value>\n protected SynchronizationContext SyncContextCancel\n {\n get { return _syncContextCancel; }\n }\n\n #endregion //SyncContextCancel\n\n public void CancelCurrentDbCommand()\n {\n _syncContextCancel = SynchronizationContext.Current;\n\n //ThreadPool.QueueUserWorkItem(CancelWork, null);\n\n Thread worker = new Thread(new ThreadStart(CancelWork));\n worker.Priority = ThreadPriority.Highest;\n worker.Start();\n }\n\n SQLiteConnection _connection;\n private void CancelWork()//object state\n {\n bool success = false;\n\n try\n {\n if (_connection != null)\n {\n log.Debug(\"call cancel\");\n _connection.Cancel();\n log.Debug(\"cancel complete\");\n _connection.Close();\n log.Debug(\"close complete\");\n success = true;\n log.Debug(\"long running query cancelled\" + DateTime.Now.ToLongTimeString());\n }\n }\n catch (Exception ex)\n {\n log.Error(ex.Message, ex);\n }\n\n SyncContextCancel.Send(CancelCompleted, new object[] { success });\n }\n\n public void CancelCompleted(object state)\n {\n object[] args = (object[])state;\n bool success = (bool)args[0];\n\n if (success)\n {\n log.Debug(\"long running query cancelled\" + DateTime.Now.ToLongTimeString());\n\n }\n }\n" }, { "answer_id": 66629283, "author": "mahirgul", "author_id": 2703120, "author_profile": "https://Stackoverflow.com/users/2703120", "pm_score": -1, "selected": false, "text": "Invoke((Action)(() =>\n {\n //your code\n }));\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
22,358
<p>Is there any way to tinker with the iPhone SDK on a Windows machine? Are there plans for an iPhone SDK version for Windows?</p> <p>The only other way I can think of doing this is to run a Mac VM image on a <strong>VMWare</strong> server running on Windows, although I'm not too sure how legal this is.</p>
[ { "answer_id": 1532802, "author": "Keith Adler", "author_id": 135952, "author_profile": "https://Stackoverflow.com/users/135952", "pm_score": 4, "selected": false, "text": "Adobe Flash CS 5 iPhone Windows" }, { "answer_id": 6022718, "author": "priamos", "author_id": 756292, "author_profile": "https://Stackoverflow.com/users/756292", "pm_score": 5, "selected": false, "text": "Objective-C, C++ IPA" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2454/" ]
22,379
<p>I'm wondering how you can implement a program similar to <code>tail -f</code> in C/C++, a program that watches for and processes new lines added to a log file?</p>
[ { "answer_id": 22399, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 4, "selected": true, "text": "wembley 0 /home/jj33/swap >#> cat p\nmy $f = shift;\nopen(I, \"<$f\") || die \"Couldn't open $f: $!\\n\";\n\nwhile (1) {\n seek(I, 0, 1);\n while (defined(my $l = <I>)) {\n print \"Got: $l\";\n }\n print \"Hit EOF, sleeping\\n\";\n sleep(10);\n}\nwembley 0 /home/jj33/swap >#> cat tfile\nThis is\nsome\ntext\nin\na file\nwembley 0 /home/jj33/swap >#> perl p tfile\nGot: This is\nGot: some\nGot: text\nGot: in\nGot: a file\nHit EOF, sleeping\n wembley 0 /home/jj33/swap > echo \"another line of text\" >> tfile\n Hit EOF, sleeping\nGot: another line of text\nHit EOF, sleeping\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
22,401
<p>I'm looking at the <a href="http://www.php.net/manual/en/" rel="noreferrer">PHP Manual</a>, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?</p>
[ { "answer_id": 22405, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "$lst = array(1, 2, 3);\n$hsh = array(1 => \"This\", 2 => \"is a\", 3 => \"test\");\n" }, { "answer_id": 22412, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 3, "selected": false, "text": "$myArray = array(\"Apples\", \"Oranges\", \"Pears\");\n$myScalar = $myArray[0] // == \"Apples\"\n $myArray = array(\"a\"=>\"Apples\", \"b\"=>\"Oranges\", \"c\"=>\"Pears\");\n$myScalar = $myArray[\"a\"] // == \"Apples\"\n" }, { "answer_id": 22416, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "$foo = array(\n 'bar' => array(1,'two',3),\n 'baz' => explode(\" \", \"Some nice words\")\n);\n" }, { "answer_id": 22418, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 4, "selected": false, "text": "array_push() array_pop() array_push() array_shift() $array['key'] = 'value';\n" }, { "answer_id": 5607426, "author": "Abel Perez", "author_id": 698288, "author_profile": "https://Stackoverflow.com/users/698288", "pm_score": 2, "selected": false, "text": "class ArraySet\n{\n /** Elements in this set */\n private $elements;\n\n /** the number of elements in this set */\n private $size = 0;\n\n /**\n * Constructs this set.\n */ \n public function ArraySet() {\n $this->elements = array();\n }\n\n /**\n * Adds the specified element to this set if \n * it is not already present.\n * \n * @param any $element\n *\n * @returns true if the specified element was\n * added to this set.\n */\n public function add($element) {\n if (! in_array($element, $this->elements)) {\n $this->elements[] = $element;\n $this->size++;\n return true;\n }\n return false;\n }\n\n /**\n * Adds all of the elements in the specified \n * collection to this set if they're not already present.\n * \n * @param array $collection\n * \n * @returns true if any of the elements in the\n * specified collection where added to this set. \n */ \n public function addAll($collection) {\n $changed = false;\n foreach ($collection as $element) {\n if ($this->add($element)) {\n $changed = true;\n }\n }\n return $changed;\n }\n\n /**\n * Removes all the elements from this set.\n */ \n public function clear() {\n $this->elements = array();\n $this->size = 0;\n }\n\n /**\n * Checks if this set contains the specified element. \n * \n * @param any $element\n *\n * @returns true if this set contains the specified\n * element.\n */ \n public function contains($element) {\n return in_array($element, $this->elements);\n }\n\n /**\n * Checks if this set contains all the specified \n * element.\n * \n * @param array $collection\n * \n * @returns true if this set contains all the specified\n * element. \n */ \n public function containsAll($collection) {\n foreach ($collection as $element) {\n if (! in_array($element, $this->elements)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Checks if this set contains elements.\n * \n * @returns true if this set contains no elements. \n */ \n public function isEmpty() {\n return count($this->elements) <= 0;\n }\n\n /**\n * Get's an iterator over the elements in this set.\n * \n * @returns an iterator over the elements in this set.\n */ \n public function iterator() {\n return new SimpleIterator($this->elements);\n }\n\n /**\n * Removes the specified element from this set.\n * \n * @param any $element\n *\n * @returns true if the specified element is removed.\n */ \n public function remove($element) {\n if (! in_array($element, $this->elements)) return false;\n\n foreach ($this->elements as $k => $v) {\n if ($element == $v) {\n unset($this->elements[$k]);\n $this->size--;\n return true;\n }\n } \n }\n\n /**\n * Removes all the specified elements from this set.\n * \n * @param array $collection\n *\n * @returns true if all the specified elemensts\n * are removed from this set. \n */ \n public function removeAll($collection) {\n $changed = false;\n foreach ($collection as $element) {\n if ($this->remove($element)) {\n $changed = true;\n } \n }\n return $changed;\n }\n\n /**\n * Retains the elements in this set that are\n * in the specified collection. If the specified\n * collection is also a set, this method effectively\n * modifies this set into the intersection of \n * this set and the specified collection.\n * \n * @param array $collection\n *\n * @returns true if this set changed as a result\n * of the specified collection.\n */ \n public function retainAll($collection) {\n $changed = false;\n foreach ($this->elements as $k => $v) {\n if (! in_array($v, $collection)) {\n unset($this->elements[$k]);\n $this->size--;\n $changed = true;\n }\n }\n return $changed;\n }\n\n /**\n * Returns the number of elements in this set.\n * \n * @returns the number of elements in this set.\n */ \n public function size() {\n return $this->size; \n }\n\n /**\n * Returns an array that contains all the \n * elements in this set.\n * \n * @returns an array that contains all the \n * elements in this set.\n */ \n public function toArray() {\n $elements = $this->elements;\n return $elements; \n }\n}\n" }, { "answer_id": 39558098, "author": "RanjanaLK", "author_id": 4834574, "author_profile": "https://Stackoverflow.com/users/4834574", "pm_score": 5, "selected": false, "text": "ds ds Ds\\ Collection Sequence Hashable Vector Deque Queue PriorityQueue Map Set Stack Pair" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
22,409
<p>I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done...</p> <p>With the release of ColdFusion 8, we got the <a href="http://cfquickdocs.com/cf8/?getDoc=cfimage" rel="nofollow noreferrer">CFImage</a> tag, but it doesn't support this conversion; and nor does <a href="http://x.com" rel="nofollow noreferrer">Image.cfc</a>, or <a href="http://x.com" rel="nofollow noreferrer">Alagad's Image Component</a>.</p> <p>However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process:</p> <pre><code>&lt;cfset jthread = createObject("java", "java.lang.Thread")/&gt; &lt;cfset jthread.sleep(5000)/&gt; </code></pre> <p>I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?</p>
[ { "answer_id": 848533, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 4, "selected": true, "text": "package cmyk;\n\nimport java.awt.color.ColorSpace;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.ColorConvertOp;\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.imageio.ImageIO;\n\nimport org.apache.commons.lang.StringUtils;\n\npublic class Main\n{\n\n /**\n * Creates new RGB images from all the CMYK images passed\n * in on the command line.\n * The new filename generated is, for example \"GIF_original_filename.gif\".\n *\n */\n public static void main(String[] args)\n {\n for (int ii = 0; ii < args.length; ii++)\n {\n String filename = args[ii];\n boolean cmyk = isCMYK(filename);\n System.out.println(cmyk + \": \" + filename);\n if (cmyk)\n {\n try\n {\n String rgbFile = cmyk2rgb(filename);\n System.out.println(isCMYK(rgbFile) + \": \" + rgbFile);\n }\n catch (IOException e)\n {\n System.out.println(e.getMessage());\n }\n }\n }\n }\n\n /**\n * If 'filename' is a CMYK file, then convert the image into RGB,\n * store it into a JPEG file, and return the new filename.\n *\n * @param filename\n */\n private static String cmyk2rgb(String filename) throws IOException\n {\n // Change this format into any ImageIO supported format.\n String format = \"gif\";\n File imageFile = new File(filename);\n String rgbFilename = filename;\n BufferedImage image = ImageIO.read(imageFile);\n if (image != null)\n {\n int colorSpaceType = image.getColorModel().getColorSpace().getType();\n if (colorSpaceType == ColorSpace.TYPE_CMYK)\n {\n BufferedImage rgbImage =\n new BufferedImage(\n image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);\n ColorConvertOp op = new ColorConvertOp(null);\n op.filter(image, rgbImage);\n\n rgbFilename = changeExtension(imageFile.getName(), format);\n rgbFilename = new File(imageFile.getParent(), format + \"_\" + rgbFilename).getPath();\n ImageIO.write(rgbImage, format, new File(rgbFilename));\n }\n }\n return rgbFilename;\n }\n\n /**\n * Change the extension of 'filename' to 'newExtension'.\n *\n * @param filename\n * @param newExtension\n * @return filename with new extension\n */\n private static String changeExtension(String filename, String newExtension)\n {\n String result = filename;\n if (filename != null && newExtension != null && newExtension.length() != 0);\n {\n int dot = filename.lastIndexOf('.');\n if (dot != -1)\n {\n result = filename.substring(0, dot) + '.' + newExtension;\n }\n }\n return result;\n }\n\n private static boolean isCMYK(String filename)\n {\n boolean result = false;\n BufferedImage img = null;\n try\n {\n img = ImageIO.read(new File(filename));\n }\n catch (IOException e)\n {\n System.out.println(e.getMessage() + \": \" + filename);\n }\n if (img != null)\n {\n int colorSpaceType = img.getColorModel().getColorSpace().getType();\n result = colorSpaceType == ColorSpace.TYPE_CMYK;\n }\n\n return result;\n }\n}\n" }, { "answer_id": 17498325, "author": "James Moberg", "author_id": 693068, "author_profile": "https://Stackoverflow.com/users/693068", "pm_score": 0, "selected": false, "text": "<cfset imgData = ImageRead(expandPath(\"./CMYK_image.jpg\"))>\n<cfset ImageWrite(imgData, expandPath(\"./Saved_image.jpg\"))>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
22,417
<p>Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID</p> <p>I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters.</p> <p>I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring.</p> <p>Anyone ever tackle something like this and have insight? </p>
[ { "answer_id": 22448, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": true, "text": "select student_name, score\nfrom students\n join (select student_answers.student_id, count(*) as score\n from student_answers, answer_key\n group by student_id\n where student_answers.question_id = answer_key.question_id\n and student_answers.answer = answer_key.answer)\n as student_scores on students.student_id = student_scores.student_id\nwhere score >= 7\norder by score, student_name\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975/" ]
22,429
<p>Is it possible to embed an inline search box into a web page which provides similar functionality to the <a href="http://www.ie7pro.com/inline-search.html" rel="noreferrer">IE7Pro Inline Search</a> or similar plugins for Firefox/Safari?</p>
[ { "answer_id": 22448, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": true, "text": "select student_name, score\nfrom students\n join (select student_answers.student_id, count(*) as score\n from student_answers, answer_key\n group by student_id\n where student_answers.question_id = answer_key.question_id\n and student_answers.answer = answer_key.answer)\n as student_scores on students.student_id = student_scores.student_id\nwhere score >= 7\norder by score, student_name\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2418/" ]